mcp-server-flink 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcp_server_flink/__init__.py +1 -0
- mcp_server_flink/__main__.py +4 -0
- mcp_server_flink/cli.py +38 -0
- mcp_server_flink/client.py +319 -0
- mcp_server_flink/config.py +231 -0
- mcp_server_flink/diagnose.py +391 -0
- mcp_server_flink/server.py +639 -0
- mcp_server_flink/shaping.py +401 -0
- mcp_server_flink/sql.py +199 -0
- mcp_server_flink/sql_guard.py +348 -0
- mcp_server_flink-0.1.0.dist-info/METADATA +274 -0
- mcp_server_flink-0.1.0.dist-info/RECORD +15 -0
- mcp_server_flink-0.1.0.dist-info/WHEEL +4 -0
- mcp_server_flink-0.1.0.dist-info/entry_points.txt +2 -0
- mcp_server_flink-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
mcp_server_flink/cli.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .config import ConfigError, insecure_auth_targets, load_settings
|
|
11
|
+
from .server import build_server
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
15
|
+
try:
|
|
16
|
+
settings, args = load_settings(argv)
|
|
17
|
+
except ConfigError as exc:
|
|
18
|
+
print(f"mcp-server-flink: {exc}", file=sys.stderr)
|
|
19
|
+
raise SystemExit(2) from None
|
|
20
|
+
if args.version:
|
|
21
|
+
print(__version__)
|
|
22
|
+
return
|
|
23
|
+
|
|
24
|
+
insecure = insecure_auth_targets(settings)
|
|
25
|
+
if insecure and os.environ.get("FLINK_ALLOW_INSECURE_AUTH", "").lower() not in ("1", "true"):
|
|
26
|
+
print(
|
|
27
|
+
"mcp-server-flink: refusing to send credentials over cleartext HTTP to "
|
|
28
|
+
+ ", ".join(insecure)
|
|
29
|
+
+ "; use https:// or set FLINK_ALLOW_INSECURE_AUTH=true",
|
|
30
|
+
file=sys.stderr,
|
|
31
|
+
)
|
|
32
|
+
raise SystemExit(2)
|
|
33
|
+
|
|
34
|
+
server = build_server(settings)
|
|
35
|
+
if settings.transport == "streamable-http":
|
|
36
|
+
server.run("streamable-http", host=settings.host, port=settings.port)
|
|
37
|
+
else:
|
|
38
|
+
server.run("stdio")
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Async HTTP clients for the Flink REST API and the SQL Gateway REST API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .config import Settings
|
|
14
|
+
|
|
15
|
+
JOB_ID_RE = re.compile(r"^[0-9a-fA-F]{32}$")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FlinkError(Exception):
|
|
19
|
+
"""A request to Flink failed. The message is safe to show to the caller.
|
|
20
|
+
|
|
21
|
+
``detail`` is the error Flink reported, without the request description.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, detail: str | None = None) -> None:
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.detail = detail or message
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class FlinkNotFound(FlinkError):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class FlinkTimeout(FlinkError):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class FlinkUnavailable(FlinkError):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class FlinkApiError(FlinkError):
|
|
42
|
+
def __init__(self, message: str, status: int, detail: str | None = None) -> None:
|
|
43
|
+
super().__init__(message, detail)
|
|
44
|
+
self.status = status
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def summarize_java_error(text: str, max_causes: int = 3, max_len: int = 400) -> str:
|
|
48
|
+
"""Reduce a Java stack trace from Flink to its most useful lines.
|
|
49
|
+
|
|
50
|
+
Flink returns whole stack traces in ``errors``. The innermost ``Caused by``
|
|
51
|
+
lines usually name the problem, so keep the first line and the last few
|
|
52
|
+
distinct causes, and drop the frames.
|
|
53
|
+
"""
|
|
54
|
+
lines = [ln.strip() for ln in text.splitlines()]
|
|
55
|
+
messages = []
|
|
56
|
+
for ln in lines:
|
|
57
|
+
if not ln or ln.startswith(("at ", "...", "<", "End of exception")):
|
|
58
|
+
continue
|
|
59
|
+
if ln.startswith("Caused by: "):
|
|
60
|
+
ln = ln[len("Caused by: ") :]
|
|
61
|
+
messages.append(strip_class_prefix(ln))
|
|
62
|
+
seen: list[str] = []
|
|
63
|
+
for m in messages:
|
|
64
|
+
if m and m not in seen:
|
|
65
|
+
seen.append(m)
|
|
66
|
+
if not seen:
|
|
67
|
+
return text.strip()[:max_len]
|
|
68
|
+
out = " <- ".join(reversed(seen[-max_causes:]))
|
|
69
|
+
return out[:max_len] + ("..." if len(out) > max_len else "")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_CLASS_PREFIX = re.compile(r"^((?:[a-z_][\w$]*\.)+)([A-Z][\w$]*)(:\s*|$)")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def strip_class_prefix(line: str) -> str:
|
|
76
|
+
"""``org.apache.flink.FooException: msg`` -> ``FooException: msg``."""
|
|
77
|
+
m = _CLASS_PREFIX.match(line)
|
|
78
|
+
if not m:
|
|
79
|
+
return line
|
|
80
|
+
rest = line[m.end() :]
|
|
81
|
+
return f"{m.group(2)}: {rest}" if rest else m.group(2)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def error_text(response: httpx.Response) -> str:
|
|
85
|
+
try:
|
|
86
|
+
body = response.json()
|
|
87
|
+
except ValueError:
|
|
88
|
+
return response.text.strip()[:400] or response.reason_phrase
|
|
89
|
+
if isinstance(body, dict) and isinstance(body.get("errors"), list) and body["errors"]:
|
|
90
|
+
joined = "\n".join(str(e) for e in body["errors"])
|
|
91
|
+
return summarize_java_error(joined)
|
|
92
|
+
return str(body)[:400]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class _BaseClient:
|
|
96
|
+
service = "Flink"
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
base_url: str,
|
|
101
|
+
settings: Settings,
|
|
102
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
103
|
+
) -> None:
|
|
104
|
+
headers = {"Accept": "application/json", "User-Agent": f"mcp-server-flink/{__version__}"}
|
|
105
|
+
headers.update(settings.auth_headers())
|
|
106
|
+
self.base_url = base_url
|
|
107
|
+
self.timeout = settings.timeout
|
|
108
|
+
self._http = httpx.AsyncClient(
|
|
109
|
+
base_url=base_url,
|
|
110
|
+
headers=headers,
|
|
111
|
+
auth=settings.basic_auth(),
|
|
112
|
+
verify=settings.verify_tls,
|
|
113
|
+
timeout=settings.timeout,
|
|
114
|
+
transport=transport,
|
|
115
|
+
follow_redirects=False,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
async def aclose(self) -> None:
|
|
119
|
+
await self._http.aclose()
|
|
120
|
+
|
|
121
|
+
async def request(
|
|
122
|
+
self,
|
|
123
|
+
method: str,
|
|
124
|
+
path: str,
|
|
125
|
+
*,
|
|
126
|
+
params: dict[str, Any] | None = None,
|
|
127
|
+
json: Any = None,
|
|
128
|
+
timeout: float | None = None,
|
|
129
|
+
) -> Any:
|
|
130
|
+
try:
|
|
131
|
+
response = await self._http.request(
|
|
132
|
+
method,
|
|
133
|
+
path,
|
|
134
|
+
params=params,
|
|
135
|
+
json=json,
|
|
136
|
+
timeout=timeout if timeout is not None else httpx.USE_CLIENT_DEFAULT,
|
|
137
|
+
)
|
|
138
|
+
except httpx.TimeoutException:
|
|
139
|
+
raise FlinkTimeout(
|
|
140
|
+
f"{self.service} did not answer {method} {path} within "
|
|
141
|
+
f"{timeout or self.timeout:g}s ({self.base_url})"
|
|
142
|
+
) from None
|
|
143
|
+
except httpx.TransportError as exc:
|
|
144
|
+
raise FlinkUnavailable(
|
|
145
|
+
f"cannot reach {self.service} at {self.base_url}: {type(exc).__name__}"
|
|
146
|
+
) from None
|
|
147
|
+
if response.status_code == 404:
|
|
148
|
+
detail = error_text(response)
|
|
149
|
+
raise FlinkNotFound(f"{self.service}: not found: {method} {path}: {detail}", detail)
|
|
150
|
+
if response.status_code >= 400:
|
|
151
|
+
detail = error_text(response)
|
|
152
|
+
raise FlinkApiError(
|
|
153
|
+
f"{self.service} returned HTTP {response.status_code} for {method} {path}: "
|
|
154
|
+
f"{detail}",
|
|
155
|
+
response.status_code,
|
|
156
|
+
detail,
|
|
157
|
+
)
|
|
158
|
+
if not response.content:
|
|
159
|
+
return None
|
|
160
|
+
try:
|
|
161
|
+
return response.json()
|
|
162
|
+
except ValueError:
|
|
163
|
+
raise FlinkApiError(
|
|
164
|
+
f"{self.service} returned a non-JSON response for {method} {path}",
|
|
165
|
+
response.status_code,
|
|
166
|
+
) from None
|
|
167
|
+
|
|
168
|
+
async def get(self, path: str, **params: Any) -> Any:
|
|
169
|
+
clean = {k: v for k, v in params.items() if v is not None}
|
|
170
|
+
return await self.request("GET", path, params=clean or None)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _seg(value: str) -> str:
|
|
174
|
+
return quote(value, safe="")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class FlinkRestClient(_BaseClient):
|
|
178
|
+
"""The read and job-control endpoints of the JobManager REST API."""
|
|
179
|
+
|
|
180
|
+
service = "Flink REST API"
|
|
181
|
+
|
|
182
|
+
async def overview(self) -> dict[str, Any]:
|
|
183
|
+
return await self.get("/overview")
|
|
184
|
+
|
|
185
|
+
async def dashboard_config(self) -> dict[str, Any]:
|
|
186
|
+
return await self.get("/config")
|
|
187
|
+
|
|
188
|
+
async def jobmanager_config(self) -> list[dict[str, Any]]:
|
|
189
|
+
return await self.get("/jobmanager/config")
|
|
190
|
+
|
|
191
|
+
async def jobs_overview(self) -> dict[str, Any]:
|
|
192
|
+
return await self.get("/jobs/overview")
|
|
193
|
+
|
|
194
|
+
async def job(self, job_id: str) -> dict[str, Any]:
|
|
195
|
+
return await self.get(f"/jobs/{job_id}")
|
|
196
|
+
|
|
197
|
+
async def job_config(self, job_id: str) -> dict[str, Any]:
|
|
198
|
+
return await self.get(f"/jobs/{job_id}/config")
|
|
199
|
+
|
|
200
|
+
async def job_exceptions(self, job_id: str, max_exceptions: int = 20) -> dict[str, Any]:
|
|
201
|
+
return await self.get(f"/jobs/{job_id}/exceptions", maxExceptions=max_exceptions)
|
|
202
|
+
|
|
203
|
+
async def checkpoints(self, job_id: str) -> dict[str, Any]:
|
|
204
|
+
return await self.get(f"/jobs/{job_id}/checkpoints")
|
|
205
|
+
|
|
206
|
+
async def checkpoint_config(self, job_id: str) -> dict[str, Any]:
|
|
207
|
+
return await self.get(f"/jobs/{job_id}/checkpoints/config")
|
|
208
|
+
|
|
209
|
+
async def backpressure(
|
|
210
|
+
self, job_id: str, vertex_id: str, attempts: int = 6, delay: float = 0.5
|
|
211
|
+
) -> dict[str, Any]:
|
|
212
|
+
"""Backpressure statistics of one vertex.
|
|
213
|
+
|
|
214
|
+
The first request for a vertex only starts collecting statistics and
|
|
215
|
+
answers ``{"status": "deprecated"}``; ask again until they arrive.
|
|
216
|
+
"""
|
|
217
|
+
data: dict[str, Any] = {}
|
|
218
|
+
for attempt in range(attempts):
|
|
219
|
+
data = await self.get(f"/jobs/{job_id}/vertices/{vertex_id}/backpressure")
|
|
220
|
+
if data.get("status") != "deprecated" or attempt == attempts - 1:
|
|
221
|
+
break
|
|
222
|
+
await asyncio.sleep(delay)
|
|
223
|
+
return data
|
|
224
|
+
|
|
225
|
+
async def watermarks(self, job_id: str, vertex_id: str) -> list[dict[str, Any]]:
|
|
226
|
+
return await self.get(f"/jobs/{job_id}/vertices/{vertex_id}/watermarks")
|
|
227
|
+
|
|
228
|
+
async def job_metrics(self, job_id: str, names: list[str] | None = None) -> list[dict]:
|
|
229
|
+
return await self.get(f"/jobs/{job_id}/metrics", get=_names(names))
|
|
230
|
+
|
|
231
|
+
async def vertex_metrics(
|
|
232
|
+
self, job_id: str, vertex_id: str, names: list[str] | None, agg: list[str] | None
|
|
233
|
+
) -> list[dict]:
|
|
234
|
+
return await self.get(
|
|
235
|
+
f"/jobs/{job_id}/vertices/{vertex_id}/subtasks/metrics",
|
|
236
|
+
get=_names(names),
|
|
237
|
+
agg=_names(agg) if names else None,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
async def taskmanagers(self) -> dict[str, Any]:
|
|
241
|
+
return await self.get("/taskmanagers")
|
|
242
|
+
|
|
243
|
+
async def taskmanager(self, tm_id: str) -> dict[str, Any]:
|
|
244
|
+
return await self.get(f"/taskmanagers/{_seg(tm_id)}")
|
|
245
|
+
|
|
246
|
+
async def taskmanager_metrics(self, tm_id: str, names: list[str] | None = None) -> list[dict]:
|
|
247
|
+
return await self.get(f"/taskmanagers/{_seg(tm_id)}/metrics", get=_names(names))
|
|
248
|
+
|
|
249
|
+
async def jobmanager_metrics(self, names: list[str] | None = None) -> list[dict]:
|
|
250
|
+
return await self.get("/jobmanager/metrics", get=_names(names))
|
|
251
|
+
|
|
252
|
+
# Job control. Only used by the tools registered with --allow-write.
|
|
253
|
+
|
|
254
|
+
async def cancel_job(self, job_id: str) -> None:
|
|
255
|
+
await self.request("PATCH", f"/jobs/{job_id}", params={"mode": "cancel"})
|
|
256
|
+
|
|
257
|
+
async def trigger_savepoint(self, job_id: str, target_directory: str | None) -> str:
|
|
258
|
+
body: dict[str, Any] = {"cancel-job": False}
|
|
259
|
+
if target_directory:
|
|
260
|
+
body["target-directory"] = target_directory
|
|
261
|
+
result = await self.request("POST", f"/jobs/{job_id}/savepoints", json=body)
|
|
262
|
+
return result["request-id"]
|
|
263
|
+
|
|
264
|
+
async def stop_with_savepoint(
|
|
265
|
+
self, job_id: str, target_directory: str | None, drain: bool
|
|
266
|
+
) -> str:
|
|
267
|
+
body: dict[str, Any] = {"drain": drain}
|
|
268
|
+
if target_directory:
|
|
269
|
+
body["targetDirectory"] = target_directory
|
|
270
|
+
result = await self.request("POST", f"/jobs/{job_id}/stop", json=body)
|
|
271
|
+
return result["request-id"]
|
|
272
|
+
|
|
273
|
+
async def savepoint_status(self, job_id: str, trigger_id: str) -> dict[str, Any]:
|
|
274
|
+
return await self.get(f"/jobs/{job_id}/savepoints/{_seg(trigger_id)}")
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _names(names: list[str] | None) -> str | None:
|
|
278
|
+
return ",".join(names) if names else None
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
class SqlGatewayClient(_BaseClient):
|
|
282
|
+
"""The v1 SQL Gateway REST API, which every gateway version serves."""
|
|
283
|
+
|
|
284
|
+
service = "Flink SQL Gateway"
|
|
285
|
+
|
|
286
|
+
async def info(self) -> dict[str, Any]:
|
|
287
|
+
return await self.get("/v1/info")
|
|
288
|
+
|
|
289
|
+
async def open_session(self, name: str, properties: dict[str, str] | None = None) -> str:
|
|
290
|
+
body: dict[str, Any] = {"sessionName": name, "properties": properties or {}}
|
|
291
|
+
result = await self.request("POST", "/v1/sessions", json=body)
|
|
292
|
+
return result["sessionHandle"]
|
|
293
|
+
|
|
294
|
+
async def close_session(self, session: str) -> None:
|
|
295
|
+
await self.request("DELETE", f"/v1/sessions/{_seg(session)}")
|
|
296
|
+
|
|
297
|
+
async def heartbeat(self, session: str) -> None:
|
|
298
|
+
await self.request("POST", f"/v1/sessions/{_seg(session)}/heartbeat")
|
|
299
|
+
|
|
300
|
+
async def execute(self, session: str, statement: str) -> str:
|
|
301
|
+
result = await self.request(
|
|
302
|
+
"POST", f"/v1/sessions/{_seg(session)}/statements", json={"statement": statement}
|
|
303
|
+
)
|
|
304
|
+
return result["operationHandle"]
|
|
305
|
+
|
|
306
|
+
async def operation_status(self, session: str, operation: str) -> str:
|
|
307
|
+
result = await self.get(f"/v1/sessions/{_seg(session)}/operations/{_seg(operation)}/status")
|
|
308
|
+
return result["status"]
|
|
309
|
+
|
|
310
|
+
async def fetch(self, session: str, operation: str, token: int) -> dict[str, Any]:
|
|
311
|
+
return await self.get(
|
|
312
|
+
f"/v1/sessions/{_seg(session)}/operations/{_seg(operation)}/result/{token}",
|
|
313
|
+
rowFormat="JSON",
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
async def close_operation(self, session: str, operation: str) -> None:
|
|
317
|
+
await self.request(
|
|
318
|
+
"DELETE", f"/v1/sessions/{_seg(session)}/operations/{_seg(operation)}/close"
|
|
319
|
+
)
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Settings, read from environment variables and command-line flags."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
10
|
+
|
|
11
|
+
DEFAULT_REST_URL = "http://localhost:8081"
|
|
12
|
+
TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
|
|
13
|
+
FALSE_VALUES = frozenset({"0", "false", "no", "off"})
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ConfigError(ValueError):
|
|
17
|
+
"""The configuration is invalid."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Settings:
|
|
22
|
+
rest_url: str = DEFAULT_REST_URL
|
|
23
|
+
sql_gateway_url: str | None = None
|
|
24
|
+
username: str | None = field(default=None, repr=False)
|
|
25
|
+
password: str | None = field(default=None, repr=False)
|
|
26
|
+
token: str | None = field(default=None, repr=False)
|
|
27
|
+
verify_tls: bool | str = True
|
|
28
|
+
timeout: float = 30.0
|
|
29
|
+
allow_write: bool = False
|
|
30
|
+
sql_max_rows: int = 1000
|
|
31
|
+
sql_default_rows: int = 100
|
|
32
|
+
sql_timeout: float = 30.0
|
|
33
|
+
transport: str = "stdio"
|
|
34
|
+
host: str = "127.0.0.1"
|
|
35
|
+
port: int = 8000
|
|
36
|
+
log_level: str = "WARNING"
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def has_auth(self) -> bool:
|
|
40
|
+
return bool(self.token or self.username)
|
|
41
|
+
|
|
42
|
+
def auth_headers(self) -> dict[str, str]:
|
|
43
|
+
if self.token:
|
|
44
|
+
return {"Authorization": f"Bearer {self.token}"}
|
|
45
|
+
return {}
|
|
46
|
+
|
|
47
|
+
def basic_auth(self) -> tuple[str, str] | None:
|
|
48
|
+
if self.username and not self.token:
|
|
49
|
+
return (self.username, self.password or "")
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _bool(value: str, name: str) -> bool:
|
|
54
|
+
v = value.strip().lower()
|
|
55
|
+
if v in TRUE_VALUES:
|
|
56
|
+
return True
|
|
57
|
+
if v in FALSE_VALUES:
|
|
58
|
+
return False
|
|
59
|
+
raise ConfigError(f"{name} must be true or false, got {value!r}")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _positive(value: str, name: str, kind: type = float) -> float:
|
|
63
|
+
try:
|
|
64
|
+
number = kind(value)
|
|
65
|
+
except ValueError:
|
|
66
|
+
raise ConfigError(f"{name} must be a number, got {value!r}") from None
|
|
67
|
+
if number <= 0:
|
|
68
|
+
raise ConfigError(f"{name} must be positive, got {value!r}")
|
|
69
|
+
return number
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _split_userinfo(url: str, name: str) -> tuple[str, str | None, str | None]:
|
|
73
|
+
"""Validate ``url`` and move any ``user:password@`` part out of it.
|
|
74
|
+
|
|
75
|
+
The URL is kept without credentials, so it can be shown in errors.
|
|
76
|
+
"""
|
|
77
|
+
parts = urlsplit(url.strip())
|
|
78
|
+
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
79
|
+
raise ConfigError(f"{name} must be an http:// or https:// URL, got {url!r}")
|
|
80
|
+
user = parts.username
|
|
81
|
+
password = parts.password
|
|
82
|
+
netloc = parts.hostname
|
|
83
|
+
if ":" in netloc: # IPv6 literal
|
|
84
|
+
netloc = f"[{netloc}]"
|
|
85
|
+
if parts.port:
|
|
86
|
+
netloc += f":{parts.port}"
|
|
87
|
+
clean = urlunsplit((parts.scheme, netloc, parts.path.rstrip("/"), "", ""))
|
|
88
|
+
return clean, user, password
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
92
|
+
p = argparse.ArgumentParser(
|
|
93
|
+
prog="mcp-server-flink",
|
|
94
|
+
description=(
|
|
95
|
+
"An MCP server for Apache Flink: inspect jobs through the Flink REST API "
|
|
96
|
+
"and run read-only SQL through the SQL Gateway."
|
|
97
|
+
),
|
|
98
|
+
)
|
|
99
|
+
p.add_argument("--rest-url", help=f"Flink REST API URL (FLINK_REST_URL, {DEFAULT_REST_URL})")
|
|
100
|
+
p.add_argument(
|
|
101
|
+
"--sql-gateway-url",
|
|
102
|
+
help="SQL Gateway URL (FLINK_SQL_GATEWAY_URL); the SQL tools are off without it",
|
|
103
|
+
)
|
|
104
|
+
p.add_argument(
|
|
105
|
+
"--allow-write",
|
|
106
|
+
action="store_true",
|
|
107
|
+
default=None,
|
|
108
|
+
help="register the job control tools and allow any SQL statement (FLINK_MCP_ALLOW_WRITE)",
|
|
109
|
+
)
|
|
110
|
+
p.add_argument("--timeout", type=float, help="HTTP timeout in seconds (FLINK_TIMEOUT, 30)")
|
|
111
|
+
p.add_argument(
|
|
112
|
+
"--no-verify-tls",
|
|
113
|
+
dest="verify_tls",
|
|
114
|
+
action="store_false",
|
|
115
|
+
default=None,
|
|
116
|
+
help="do not verify TLS certificates (FLINK_VERIFY_TLS=false)",
|
|
117
|
+
)
|
|
118
|
+
p.add_argument(
|
|
119
|
+
"--transport",
|
|
120
|
+
choices=["stdio", "streamable-http"],
|
|
121
|
+
help="MCP transport (FLINK_MCP_TRANSPORT, stdio)",
|
|
122
|
+
)
|
|
123
|
+
p.add_argument("--host", help="bind address for streamable-http (FLINK_MCP_HOST, 127.0.0.1)")
|
|
124
|
+
p.add_argument("--port", type=int, help="port for streamable-http (FLINK_MCP_PORT, 8000)")
|
|
125
|
+
p.add_argument("--version", action="store_true", help="print the version and exit")
|
|
126
|
+
return p
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def load_settings(
|
|
130
|
+
argv: Sequence[str] | None = None, env: Mapping[str, str] | None = None
|
|
131
|
+
) -> tuple[Settings, argparse.Namespace]:
|
|
132
|
+
"""Build Settings from flags, falling back to environment variables."""
|
|
133
|
+
env = os.environ if env is None else env
|
|
134
|
+
args = build_parser().parse_args(argv)
|
|
135
|
+
|
|
136
|
+
def get(name: str) -> str | None:
|
|
137
|
+
value = env.get(name)
|
|
138
|
+
return value if value not in (None, "") else None
|
|
139
|
+
|
|
140
|
+
rest_raw = args.rest_url or get("FLINK_REST_URL") or DEFAULT_REST_URL
|
|
141
|
+
rest_url, url_user, url_password = _split_userinfo(rest_raw, "FLINK_REST_URL")
|
|
142
|
+
|
|
143
|
+
gateway_raw = args.sql_gateway_url or get("FLINK_SQL_GATEWAY_URL")
|
|
144
|
+
gateway_url = None
|
|
145
|
+
if gateway_raw:
|
|
146
|
+
gateway_url, gw_user, gw_password = _split_userinfo(gateway_raw, "FLINK_SQL_GATEWAY_URL")
|
|
147
|
+
url_user = url_user or gw_user
|
|
148
|
+
url_password = url_password or gw_password
|
|
149
|
+
|
|
150
|
+
username = get("FLINK_USERNAME") or url_user
|
|
151
|
+
password = get("FLINK_PASSWORD") or url_password
|
|
152
|
+
token = get("FLINK_TOKEN")
|
|
153
|
+
if password and not username:
|
|
154
|
+
raise ConfigError("FLINK_PASSWORD is set but FLINK_USERNAME is not")
|
|
155
|
+
|
|
156
|
+
verify: bool | str = True
|
|
157
|
+
if get("FLINK_CA_BUNDLE"):
|
|
158
|
+
verify = str(get("FLINK_CA_BUNDLE"))
|
|
159
|
+
if get("FLINK_VERIFY_TLS") is not None:
|
|
160
|
+
if not _bool(str(get("FLINK_VERIFY_TLS")), "FLINK_VERIFY_TLS"):
|
|
161
|
+
verify = False
|
|
162
|
+
if args.verify_tls is False:
|
|
163
|
+
verify = False
|
|
164
|
+
|
|
165
|
+
timeout = args.timeout or (
|
|
166
|
+
_positive(str(get("FLINK_TIMEOUT")), "FLINK_TIMEOUT") if get("FLINK_TIMEOUT") else 30.0
|
|
167
|
+
)
|
|
168
|
+
if timeout <= 0:
|
|
169
|
+
raise ConfigError("--timeout must be positive")
|
|
170
|
+
|
|
171
|
+
allow_write = bool(args.allow_write) or (
|
|
172
|
+
_bool(str(get("FLINK_MCP_ALLOW_WRITE")), "FLINK_MCP_ALLOW_WRITE")
|
|
173
|
+
if get("FLINK_MCP_ALLOW_WRITE")
|
|
174
|
+
else False
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
max_rows = int(
|
|
178
|
+
_positive(str(get("FLINK_SQL_MAX_ROWS")), "FLINK_SQL_MAX_ROWS", int)
|
|
179
|
+
if get("FLINK_SQL_MAX_ROWS")
|
|
180
|
+
else 1000
|
|
181
|
+
)
|
|
182
|
+
sql_timeout = (
|
|
183
|
+
_positive(str(get("FLINK_SQL_TIMEOUT")), "FLINK_SQL_TIMEOUT")
|
|
184
|
+
if get("FLINK_SQL_TIMEOUT")
|
|
185
|
+
else 30.0
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
port = args.port or int(
|
|
189
|
+
_positive(str(get("FLINK_MCP_PORT")), "FLINK_MCP_PORT", int)
|
|
190
|
+
if get("FLINK_MCP_PORT")
|
|
191
|
+
else 8000
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
settings = Settings(
|
|
195
|
+
rest_url=rest_url,
|
|
196
|
+
sql_gateway_url=gateway_url,
|
|
197
|
+
username=username,
|
|
198
|
+
password=password,
|
|
199
|
+
token=token,
|
|
200
|
+
verify_tls=verify,
|
|
201
|
+
timeout=float(timeout),
|
|
202
|
+
allow_write=allow_write,
|
|
203
|
+
sql_max_rows=max_rows,
|
|
204
|
+
sql_default_rows=min(100, max_rows),
|
|
205
|
+
sql_timeout=float(sql_timeout),
|
|
206
|
+
transport=args.transport or get("FLINK_MCP_TRANSPORT") or "stdio",
|
|
207
|
+
host=args.host or get("FLINK_MCP_HOST") or "127.0.0.1",
|
|
208
|
+
port=port,
|
|
209
|
+
log_level=(get("FLINK_MCP_LOG_LEVEL") or "WARNING").upper(),
|
|
210
|
+
)
|
|
211
|
+
if settings.transport not in ("stdio", "streamable-http"):
|
|
212
|
+
raise ConfigError(
|
|
213
|
+
f"FLINK_MCP_TRANSPORT must be stdio or streamable-http, got {settings.transport!r}"
|
|
214
|
+
)
|
|
215
|
+
if settings.log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
|
|
216
|
+
raise ConfigError(f"FLINK_MCP_LOG_LEVEL is not a log level: {settings.log_level!r}")
|
|
217
|
+
return settings, args
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def insecure_auth_targets(settings: Settings) -> list[str]:
|
|
221
|
+
"""URLs that would receive credentials over cleartext HTTP to a remote host."""
|
|
222
|
+
if not settings.has_auth:
|
|
223
|
+
return []
|
|
224
|
+
out = []
|
|
225
|
+
for url in (settings.rest_url, settings.sql_gateway_url):
|
|
226
|
+
if not url:
|
|
227
|
+
continue
|
|
228
|
+
parts = urlsplit(url)
|
|
229
|
+
if parts.scheme == "http" and parts.hostname not in ("localhost", "127.0.0.1", "::1"):
|
|
230
|
+
out.append(url)
|
|
231
|
+
return out
|