razaali10 commited on
Commit
40cf273
·
verified ·
1 Parent(s): ce791fe

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -226
app.py DELETED
@@ -1,226 +0,0 @@
1
- """
2
- EPANET MCP Server — Hugging Face Space wrapper
3
- ==============================================
4
-
5
- Wraps the `epanet-mcp-server` (ePyT/EPANET) FastMCP server and exposes it over
6
- BOTH modern MCP transports simultaneously, behind an optional API key:
7
-
8
- /mcp -> Streamable HTTP (HuggingChat, Codex, Perplexity, Gemini, ChatGPT dev-mode)
9
- /sse -> HTTP + SSE (legacy clients / Claude Desktop via mcp-remote)
10
- /messages/ -> SSE message sink
11
- / -> human-readable landing / status page
12
- /health -> unauthenticated health probe (returns "ok")
13
-
14
- Design notes
15
- ------------
16
- * A single Starlette parent app drives the Streamable-HTTP session manager
17
- lifespan (required) and routes each transport to its own sub-app via a pure
18
- ASGI dispatcher — no Starlette Mount prefix stripping, no double `/mcp/mcp`.
19
- * Auth is PURE ASGI middleware (not BaseHTTPMiddleware) so it never buffers or
20
- breaks the streaming SSE / chunked responses.
21
- * Stateful HTTP is kept ON: loaded networks live in an in-process registry and
22
- must persist across tool calls within one MCP session (single uvicorn worker).
23
- """
24
-
25
- from __future__ import annotations
26
-
27
- import contextlib
28
- import hmac
29
- import os
30
- import textwrap
31
-
32
- from starlette.applications import Starlette
33
- from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse
34
- from starlette.routing import Route
35
-
36
- from epanet_mcp.server import mcp
37
-
38
- # ---------------------------------------------------------------------------
39
- # Configuration
40
- # ---------------------------------------------------------------------------
41
- # CLIENT_API_KEY : if set, every MCP request must present it as a bearer token
42
- # (Authorization: Bearer <key>) or X-API-Key header.
43
- # If unset AND REQUIRE_AUTH is not "true", the server runs OPEN
44
- # (handy for ChatGPT connectors, which are OAuth/none only).
45
- API_KEY = os.environ.get("CLIENT_API_KEY", "").strip()
46
- REQUIRE_AUTH = os.environ.get("REQUIRE_AUTH", "").strip().lower() in {"1", "true", "yes"}
47
- AUTH_ENABLED = bool(API_KEY) or REQUIRE_AUTH
48
-
49
- # Keep session state so load_network -> get_summary -> run_sim share one registry.
50
- mcp.settings.stateless_http = False
51
-
52
- streamable_app = mcp.streamable_http_app() # serves /mcp (+ owns session mgr lifespan)
53
- sse_app = mcp.sse_app() # serves /sse + /messages/
54
-
55
- PROTECTED_PREFIXES = ("/mcp", "/sse", "/messages")
56
-
57
-
58
- # ---------------------------------------------------------------------------
59
- # Pure-ASGI API key middleware
60
- # ---------------------------------------------------------------------------
61
- def _extract_key(headers: list[tuple[bytes, bytes]]) -> str | None:
62
- hdr = {k.lower(): v for k, v in headers}
63
- auth = hdr.get(b"authorization")
64
- if auth:
65
- text = auth.decode("latin-1").strip()
66
- if text.lower().startswith("bearer "):
67
- return text[7:].strip()
68
- return text
69
- xkey = hdr.get(b"x-api-key")
70
- if xkey:
71
- return xkey.decode("latin-1").strip()
72
- return None
73
-
74
-
75
- class APIKeyMiddleware:
76
- def __init__(self, app):
77
- self.app = app
78
-
79
- async def __call__(self, scope, receive, send):
80
- if scope["type"] != "http" or not AUTH_ENABLED:
81
- await self.app(scope, receive, send)
82
- return
83
-
84
- path = scope.get("path", "")
85
- if not any(path == p or path.startswith(p + "/") or path.startswith(p)
86
- for p in PROTECTED_PREFIXES):
87
- await self.app(scope, receive, send)
88
- return
89
-
90
- presented = _extract_key(scope.get("headers", []))
91
- ok = presented is not None and API_KEY != "" and hmac.compare_digest(presented, API_KEY)
92
- if not ok:
93
- resp = JSONResponse(
94
- {"error": "unauthorized",
95
- "detail": "Provide the API key via 'Authorization: Bearer <key>' "
96
- "or the 'X-API-Key' header."},
97
- status_code=401,
98
- )
99
- await resp(scope, receive, send)
100
- return
101
-
102
- await self.app(scope, receive, send)
103
-
104
-
105
- # ---------------------------------------------------------------------------
106
- # Transport dispatcher (pure ASGI)
107
- # ---------------------------------------------------------------------------
108
- class MCPDispatcher:
109
- """Route HTTP requests to the right transport sub-app by path prefix."""
110
-
111
- def __init__(self, streamable, sse, fallback):
112
- self.streamable = streamable
113
- self.sse = sse
114
- self.fallback = fallback
115
-
116
- async def __call__(self, scope, receive, send):
117
- if scope["type"] != "http":
118
- # lifespan is handled by the parent Starlette app's lifespan_context
119
- await self.fallback(scope, receive, send)
120
- return
121
- path = scope.get("path", "")
122
- # Normalise a trailing slash on the transport roots — Gemini / ChatGPT
123
- # sometimes append one (e.g. "/mcp/"), but the sub-app route is "/mcp".
124
- if path in ("/mcp/", "/sse/"):
125
- path = path.rstrip("/")
126
- scope = dict(scope)
127
- scope["path"] = path
128
- if path == "/mcp" or path.startswith("/mcp/"):
129
- await self.streamable(scope, receive, send)
130
- elif path == "/sse" or path.startswith("/messages"):
131
- await self.sse(scope, receive, send)
132
- else:
133
- await self.fallback(scope, receive, send)
134
-
135
-
136
- # ---------------------------------------------------------------------------
137
- # Landing / health routes (the fallback app)
138
- # ---------------------------------------------------------------------------
139
- def _base_url(request) -> str:
140
- # Honour HF's proxy headers so printed URLs use the public https host.
141
- proto = request.headers.get("x-forwarded-proto", request.url.scheme)
142
- host = request.headers.get("x-forwarded-host", request.headers.get("host", request.url.netloc))
143
- return f"{proto}://{host}"
144
-
145
-
146
- async def health(request):
147
- return PlainTextResponse("ok")
148
-
149
-
150
- async def landing(request):
151
- base = _base_url(request)
152
- auth_line = (
153
- "🔒 API key required — send <code>Authorization: Bearer &lt;key&gt;</code>"
154
- if AUTH_ENABLED else
155
- "🔓 Open access — no API key configured (set <code>CLIENT_API_KEY</code> to lock it down)"
156
- )
157
- tool_count = len(getattr(mcp._tool_manager, "_tools", {})) if hasattr(mcp, "_tool_manager") else "40+"
158
- html = textwrap.dedent(f"""\
159
- <!doctype html><html><head><meta charset="utf-8">
160
- <title>EPANET MCP Server</title>
161
- <meta name="viewport" content="width=device-width, initial-scale=1">
162
- <style>
163
- body{{font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;max-width:760px;
164
- margin:40px auto;padding:0 20px;line-height:1.55;color:#0f172a;background:#f8fafc}}
165
- code{{background:#e2e8f0;padding:1px 5px;border-radius:4px;font-size:.9em}}
166
- pre{{background:#0f172a;color:#e2e8f0;padding:14px 16px;border-radius:8px;overflow:auto;font-size:.85em}}
167
- h1{{margin-bottom:.2em}} .sub{{color:#475569;margin-top:0}}
168
- .grid{{display:grid;grid-template-columns:auto 1fr;gap:6px 16px;margin:12px 0}}
169
- .k{{color:#0369a1;font-weight:600}} a{{color:#0369a1}}
170
- .pill{{display:inline-block;background:#dbeafe;color:#1e40af;border-radius:999px;padding:2px 10px;font-size:.8em}}
171
- </style></head><body>
172
- <h1>💧 EPANET MCP Server</h1>
173
- <p class="sub">Water-distribution network modelling over MCP, powered by
174
- <a href="https://github.com/KIOS-Research/EPyT">ePyT</a> / EPANET.
175
- <span class="pill">{tool_count} tools</span></p>
176
- <p>{auth_line}</p>
177
- <h3>Endpoints</h3>
178
- <div class="grid">
179
- <span class="k">Streamable HTTP</span><span><code>{base}/mcp</code> — HuggingChat, Codex, Perplexity, Gemini, ChatGPT (dev mode)</span>
180
- <span class="k">SSE</span><span><code>{base}/sse</code> — legacy clients / Claude Desktop via <code>mcp-remote</code></span>
181
- <span class="k">Health</span><span><code>{base}/health</code></span>
182
- </div>
183
- <h3>Quick connect (Streamable HTTP)</h3>
184
- <pre>{{
185
- "mcpServers": {{
186
- "epanet": {{
187
- "url": "{base}/mcp",
188
- "headers": {{ "Authorization": "Bearer &lt;YOUR_KEY&gt;" }}
189
- }}
190
- }}
191
- }}</pre>
192
- <p>Bundled ePyT benchmark networks + custom networks under
193
- <code>/home/user/app/networks/</code> (e.g. <code>net3.inp</code>, <code>ky4.inp</code>,
194
- <code>Net6.inp</code>, <code>BIWS.inp</code>). Try:
195
- <em>"List bundled networks, then load net3.inp and summarise it."</em></p>
196
- </body></html>""")
197
- return HTMLResponse(html)
198
-
199
-
200
- fallback_app = Starlette(routes=[
201
- Route("/", landing),
202
- Route("/health", health),
203
- ])
204
-
205
- dispatcher = MCPDispatcher(streamable_app, sse_app, fallback_app)
206
- guarded = APIKeyMiddleware(dispatcher)
207
-
208
-
209
- # ---------------------------------------------------------------------------
210
- # Parent app: drives the Streamable-HTTP session-manager lifespan
211
- # ---------------------------------------------------------------------------
212
- @contextlib.asynccontextmanager
213
- async def lifespan(app):
214
- async with streamable_app.router.lifespan_context(app):
215
- yield
216
-
217
-
218
- app = Starlette(lifespan=lifespan)
219
- app.mount("/", guarded)
220
-
221
-
222
- if __name__ == "__main__":
223
- import uvicorn
224
-
225
- port = int(os.environ.get("PORT", "7860"))
226
- uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")