mcp-testbench 0.2.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_testbench/__init__.py +28 -0
- mcp_testbench/cli.py +159 -0
- mcp_testbench/client.py +468 -0
- mcp_testbench/diff.py +403 -0
- mcp_testbench/lint.py +322 -0
- mcp_testbench/plugin.py +181 -0
- mcp_testbench/py.typed +0 -0
- mcp_testbench/replay.py +148 -0
- mcp_testbench/schema.py +63 -0
- mcp_testbench-0.2.0.dist-info/METADATA +330 -0
- mcp_testbench-0.2.0.dist-info/RECORD +15 -0
- mcp_testbench-0.2.0.dist-info/WHEEL +5 -0
- mcp_testbench-0.2.0.dist-info/entry_points.txt +5 -0
- mcp_testbench-0.2.0.dist-info/licenses/LICENSE +21 -0
- mcp_testbench-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""mcp-testbench: conformance and contract testing for MCP servers."""
|
|
2
|
+
|
|
3
|
+
from .client import HTTPClient, MCPClient, MCPError, SSEClient, parse_headers
|
|
4
|
+
from .diff import Change, diff_snapshots, has_breaking
|
|
5
|
+
from .lint import LintFinding, has_lint_errors, lint_schema
|
|
6
|
+
from .replay import replay_calls, replay_file
|
|
7
|
+
from .schema import fetch_schema, load_definition, normalize_schema
|
|
8
|
+
|
|
9
|
+
__version__ = "0.2.0"
|
|
10
|
+
__all__ = [
|
|
11
|
+
"HTTPClient",
|
|
12
|
+
"MCPClient",
|
|
13
|
+
"MCPError",
|
|
14
|
+
"SSEClient",
|
|
15
|
+
"parse_headers",
|
|
16
|
+
"Change",
|
|
17
|
+
"diff_snapshots",
|
|
18
|
+
"has_breaking",
|
|
19
|
+
"LintFinding",
|
|
20
|
+
"has_lint_errors",
|
|
21
|
+
"lint_schema",
|
|
22
|
+
"replay_calls",
|
|
23
|
+
"replay_file",
|
|
24
|
+
"fetch_schema",
|
|
25
|
+
"load_definition",
|
|
26
|
+
"normalize_schema",
|
|
27
|
+
"__version__",
|
|
28
|
+
]
|
mcp_testbench/cli.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""mcp-testbench command line.
|
|
2
|
+
|
|
3
|
+
A server is given in one of three ways:
|
|
4
|
+
|
|
5
|
+
a command after ``--`` (stdio)::
|
|
6
|
+
|
|
7
|
+
mcp-testbench snapshot -o snap.json -- python my_server.py
|
|
8
|
+
mcp-testbench check snap.json -- python my_server.py
|
|
9
|
+
mcp-testbench replay calls.jsonl -- python my_server.py
|
|
10
|
+
mcp-testbench lint -- python my_server.py
|
|
11
|
+
|
|
12
|
+
a URL (Streamable HTTP; legacy SSE with ``--sse``)::
|
|
13
|
+
|
|
14
|
+
mcp-testbench inspect --url http://localhost:8000/mcp
|
|
15
|
+
mcp-testbench check snap.json --url https://example.com/mcp --header "Authorization: Bearer X"
|
|
16
|
+
mcp-testbench replay calls.jsonl --url http://localhost:8000/mcp
|
|
17
|
+
|
|
18
|
+
or an offline JSON definition (no live server needed)::
|
|
19
|
+
|
|
20
|
+
mcp-testbench inspect --definition server.json
|
|
21
|
+
mcp-testbench check snap.json --definition server.json
|
|
22
|
+
mcp-testbench lint --definition server.json
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import argparse
|
|
28
|
+
import json
|
|
29
|
+
import sys
|
|
30
|
+
|
|
31
|
+
from .client import HTTPClient, MCPClient, MCPError, SSEClient, parse_headers
|
|
32
|
+
from .diff import diff_snapshots, has_breaking
|
|
33
|
+
from .lint import has_lint_errors, lint_schema
|
|
34
|
+
from .replay import replay_file
|
|
35
|
+
from .schema import fetch_schema, load_definition, load_snapshot, save_snapshot
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _headers(args):
|
|
39
|
+
try:
|
|
40
|
+
return parse_headers(getattr(args, "header", None) or [])
|
|
41
|
+
except MCPError as exc:
|
|
42
|
+
raise SystemExit(str(exc))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _make_client(args):
|
|
46
|
+
"""A started-client context manager for the configured live source."""
|
|
47
|
+
if getattr(args, "url", None):
|
|
48
|
+
cls = SSEClient if getattr(args, "sse", False) else HTTPClient
|
|
49
|
+
return cls(args.url, headers=_headers(args))
|
|
50
|
+
if not getattr(args, "server", None):
|
|
51
|
+
raise SystemExit("give a server command after -- , --url URL, or --definition FILE")
|
|
52
|
+
return MCPClient(args.server)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _get_schema(args):
|
|
56
|
+
if getattr(args, "definition", None):
|
|
57
|
+
return load_definition(args.definition)
|
|
58
|
+
with _make_client(args) as client:
|
|
59
|
+
return fetch_schema(client)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _print_changes(changes):
|
|
63
|
+
if not changes:
|
|
64
|
+
print("no changes")
|
|
65
|
+
return
|
|
66
|
+
for change in changes:
|
|
67
|
+
print(str(change))
|
|
68
|
+
breaking = sum(1 for c in changes if c.severity == "breaking")
|
|
69
|
+
print(f"{len(changes)} change(s), {breaking} breaking")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _add_source(p):
|
|
73
|
+
p.add_argument("--definition", help="offline JSON server definition / snapshot file")
|
|
74
|
+
p.add_argument("--url", help="Streamable HTTP (or, with --sse, legacy SSE) MCP server URL")
|
|
75
|
+
p.add_argument("--sse", action="store_true",
|
|
76
|
+
help="use the legacy SSE transport for --url")
|
|
77
|
+
p.add_argument("--header", action="append", default=[],
|
|
78
|
+
help='extra HTTP header, e.g. --header "Authorization: Bearer X" (repeatable)')
|
|
79
|
+
p.add_argument("server", nargs="*", help="server command, after --")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def main(argv=None):
|
|
83
|
+
parser = argparse.ArgumentParser(prog="mcp-testbench")
|
|
84
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
85
|
+
|
|
86
|
+
p = sub.add_parser("inspect", help="print tools/prompts/resources as JSON")
|
|
87
|
+
_add_source(p)
|
|
88
|
+
|
|
89
|
+
p = sub.add_parser("snapshot", help="capture a server schema snapshot")
|
|
90
|
+
p.add_argument("-o", "--output", required=True)
|
|
91
|
+
_add_source(p)
|
|
92
|
+
|
|
93
|
+
for name in ("check", "diff"):
|
|
94
|
+
p = sub.add_parser(name, help="compare a server against a snapshot; exit 1 on breaking")
|
|
95
|
+
p.add_argument("snapshot")
|
|
96
|
+
_add_source(p)
|
|
97
|
+
|
|
98
|
+
p = sub.add_parser("replay", help="replay a JSONL file of recorded tool calls")
|
|
99
|
+
p.add_argument("calls")
|
|
100
|
+
_add_source(p)
|
|
101
|
+
|
|
102
|
+
p = sub.add_parser("lint", help="lint a server schema; exit 1 on errors (--strict: also warnings)")
|
|
103
|
+
p.add_argument("--strict", action="store_true", help="fail on warnings as well as errors")
|
|
104
|
+
_add_source(p)
|
|
105
|
+
|
|
106
|
+
args = parser.parse_args(argv)
|
|
107
|
+
# argparse keeps a leading "--" in the positional; drop it.
|
|
108
|
+
if getattr(args, "server", None) and args.server[:1] == ["--"]:
|
|
109
|
+
args.server = args.server[1:]
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
if args.command == "inspect":
|
|
113
|
+
print(json.dumps(_get_schema(args), indent=2, sort_keys=True))
|
|
114
|
+
return 0
|
|
115
|
+
if args.command == "snapshot":
|
|
116
|
+
snap = _get_schema(args)
|
|
117
|
+
save_snapshot(snap, args.output)
|
|
118
|
+
print(
|
|
119
|
+
f"wrote {args.output}: {len(snap['tools'])} tool(s), "
|
|
120
|
+
f"{len(snap['prompts'])} prompt(s), {len(snap['resources'])} resource(s)"
|
|
121
|
+
)
|
|
122
|
+
return 0
|
|
123
|
+
if args.command in ("check", "diff"):
|
|
124
|
+
old = load_snapshot(args.snapshot)
|
|
125
|
+
new = _get_schema(args)
|
|
126
|
+
changes = diff_snapshots(old, new)
|
|
127
|
+
_print_changes(changes)
|
|
128
|
+
return 1 if has_breaking(changes) else 0
|
|
129
|
+
if args.command == "lint":
|
|
130
|
+
findings = lint_schema(_get_schema(args))
|
|
131
|
+
for finding in findings:
|
|
132
|
+
print(str(finding))
|
|
133
|
+
errors = sum(1 for f in findings if f.severity == "error")
|
|
134
|
+
warnings = sum(1 for f in findings if f.severity == "warning")
|
|
135
|
+
print(f"{len(findings)} lint finding(s): {errors} error(s), {warnings} warning(s)")
|
|
136
|
+
if errors or (args.strict and warnings):
|
|
137
|
+
return 1
|
|
138
|
+
return 0
|
|
139
|
+
if args.command == "replay":
|
|
140
|
+
if args.definition:
|
|
141
|
+
raise SystemExit("replay needs a live server (it calls tools); --definition cannot be used")
|
|
142
|
+
with _make_client(args) as client:
|
|
143
|
+
results = replay_file(client, args.calls)
|
|
144
|
+
failed = 0
|
|
145
|
+
for r in results:
|
|
146
|
+
status = "PASS" if r.passed else "FAIL"
|
|
147
|
+
if not r.passed:
|
|
148
|
+
failed += 1
|
|
149
|
+
print(f"{status} {r.tool} {r.arguments} {r.detail}")
|
|
150
|
+
print(f"{len(results) - failed}/{len(results)} replayed call(s) passed")
|
|
151
|
+
return 1 if failed else 0
|
|
152
|
+
except MCPError as exc:
|
|
153
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
154
|
+
return 2
|
|
155
|
+
return 0
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
if __name__ == "__main__":
|
|
159
|
+
raise SystemExit(main())
|
mcp_testbench/client.py
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
"""Stdlib-only MCP clients: stdio, Streamable HTTP, and legacy SSE.
|
|
2
|
+
|
|
3
|
+
All three clients expose the same surface -- ``start`` / ``close`` (or use
|
|
4
|
+
as a context manager), ``request``, ``notify``, ``list_tools``,
|
|
5
|
+
``list_prompts``, ``list_resources``, ``call_tool`` -- and carry
|
|
6
|
+
``server_info`` / ``protocol_version`` after ``start()``. No dependency on
|
|
7
|
+
the official ``mcp`` package, so an SDK upgrade on the server side can
|
|
8
|
+
never break the tests.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import threading
|
|
18
|
+
import urllib.error
|
|
19
|
+
import urllib.parse
|
|
20
|
+
import urllib.request
|
|
21
|
+
|
|
22
|
+
PROTOCOL_VERSION = "2025-03-26"
|
|
23
|
+
CLIENT_VERSION = "0.2.0"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class MCPError(RuntimeError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_headers(header_list):
|
|
31
|
+
"""Turn ``["Authorization: Bearer x", ...]`` (or pairs) into a dict."""
|
|
32
|
+
headers = {}
|
|
33
|
+
for item in header_list or []:
|
|
34
|
+
if isinstance(item, (tuple, list)) and len(item) == 2:
|
|
35
|
+
key, value = item
|
|
36
|
+
else:
|
|
37
|
+
if ":" not in str(item):
|
|
38
|
+
raise MCPError(f"header must be 'Name: value', got {item!r}")
|
|
39
|
+
key, value = str(item).split(":", 1)
|
|
40
|
+
headers[str(key).strip()] = str(value).strip()
|
|
41
|
+
return headers
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _BaseClient:
|
|
45
|
+
"""JSON-RPC plumbing shared by every transport."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, timeout=30):
|
|
48
|
+
self.timeout = timeout
|
|
49
|
+
self._next_id = 0
|
|
50
|
+
self.server_info = {}
|
|
51
|
+
self.protocol_version = None
|
|
52
|
+
|
|
53
|
+
def __enter__(self):
|
|
54
|
+
self.start()
|
|
55
|
+
return self
|
|
56
|
+
|
|
57
|
+
def __exit__(self, *exc):
|
|
58
|
+
self.close()
|
|
59
|
+
return False
|
|
60
|
+
|
|
61
|
+
# transport hooks ------------------------------------------------------
|
|
62
|
+
def _roundtrip(self, payload): # pragma: no cover - overridden
|
|
63
|
+
raise NotImplementedError
|
|
64
|
+
|
|
65
|
+
def _send_notification(self, payload): # pragma: no cover - overridden
|
|
66
|
+
raise NotImplementedError
|
|
67
|
+
|
|
68
|
+
# wire -----------------------------------------------------------------
|
|
69
|
+
def notify(self, method, params=None):
|
|
70
|
+
self._send_notification(
|
|
71
|
+
{"jsonrpc": "2.0", "method": method, "params": params or {}}
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def request(self, method, params=None):
|
|
75
|
+
self._next_id += 1
|
|
76
|
+
req_id = self._next_id
|
|
77
|
+
msg = self._roundtrip(
|
|
78
|
+
{"jsonrpc": "2.0", "id": req_id, "method": method, "params": params or {}}
|
|
79
|
+
)
|
|
80
|
+
if msg is None:
|
|
81
|
+
raise MCPError(f"{method}: empty response")
|
|
82
|
+
if msg.get("error"):
|
|
83
|
+
err = msg["error"] or {}
|
|
84
|
+
raise MCPError(f"{method}: {err.get('code')} {err.get('message')}")
|
|
85
|
+
return msg.get("result") or {}
|
|
86
|
+
|
|
87
|
+
def _initialize(self):
|
|
88
|
+
result = self.request(
|
|
89
|
+
"initialize",
|
|
90
|
+
{
|
|
91
|
+
"protocolVersion": PROTOCOL_VERSION,
|
|
92
|
+
"capabilities": {},
|
|
93
|
+
"clientInfo": {"name": "mcp-testbench", "version": CLIENT_VERSION},
|
|
94
|
+
},
|
|
95
|
+
)
|
|
96
|
+
self.server_info = result.get("serverInfo", {}) if isinstance(result, dict) else {}
|
|
97
|
+
self.protocol_version = (
|
|
98
|
+
result.get("protocolVersion") if isinstance(result, dict) else None
|
|
99
|
+
)
|
|
100
|
+
try:
|
|
101
|
+
self.notify("notifications/initialized", {})
|
|
102
|
+
except Exception:
|
|
103
|
+
pass
|
|
104
|
+
return self
|
|
105
|
+
|
|
106
|
+
# protocol -------------------------------------------------------------
|
|
107
|
+
def _list(self, method, key):
|
|
108
|
+
items, cursor = [], None
|
|
109
|
+
while True:
|
|
110
|
+
params = {"cursor": cursor} if cursor else {}
|
|
111
|
+
result = self.request(method, params)
|
|
112
|
+
items.extend(result.get(key, []) or [])
|
|
113
|
+
cursor = result.get("nextCursor")
|
|
114
|
+
if not cursor:
|
|
115
|
+
return items
|
|
116
|
+
|
|
117
|
+
def list_tools(self):
|
|
118
|
+
return self._list("tools/list", "tools")
|
|
119
|
+
|
|
120
|
+
def list_prompts(self):
|
|
121
|
+
try:
|
|
122
|
+
return self._list("prompts/list", "prompts")
|
|
123
|
+
except MCPError:
|
|
124
|
+
return []
|
|
125
|
+
|
|
126
|
+
def list_resources(self):
|
|
127
|
+
try:
|
|
128
|
+
return self._list("resources/list", "resources")
|
|
129
|
+
except MCPError:
|
|
130
|
+
return []
|
|
131
|
+
|
|
132
|
+
def call_tool(self, name, arguments=None):
|
|
133
|
+
return self.request("tools/call", {"name": name, "arguments": arguments or {}})
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class MCPClient(_BaseClient):
|
|
137
|
+
"""MCP over stdio: the server is a subprocess speaking JSON-RPC lines."""
|
|
138
|
+
|
|
139
|
+
def __init__(self, command, env=None, cwd=None, timeout=30):
|
|
140
|
+
super().__init__(timeout=timeout)
|
|
141
|
+
if isinstance(command, str):
|
|
142
|
+
import shlex
|
|
143
|
+
|
|
144
|
+
command = shlex.split(command)
|
|
145
|
+
self.command = list(command)
|
|
146
|
+
self._env = env
|
|
147
|
+
self._cwd = cwd
|
|
148
|
+
self._proc = None
|
|
149
|
+
|
|
150
|
+
def start(self):
|
|
151
|
+
env = None
|
|
152
|
+
if self._env is not None:
|
|
153
|
+
env = dict(os.environ)
|
|
154
|
+
env.update(self._env)
|
|
155
|
+
self._proc = subprocess.Popen(
|
|
156
|
+
self.command,
|
|
157
|
+
stdin=subprocess.PIPE,
|
|
158
|
+
stdout=subprocess.PIPE,
|
|
159
|
+
stderr=subprocess.PIPE,
|
|
160
|
+
text=True,
|
|
161
|
+
bufsize=1,
|
|
162
|
+
env=env,
|
|
163
|
+
cwd=self._cwd,
|
|
164
|
+
)
|
|
165
|
+
return self._initialize()
|
|
166
|
+
|
|
167
|
+
def close(self):
|
|
168
|
+
if self._proc is not None:
|
|
169
|
+
try:
|
|
170
|
+
if self._proc.stdin:
|
|
171
|
+
self._proc.stdin.close()
|
|
172
|
+
except Exception:
|
|
173
|
+
pass
|
|
174
|
+
try:
|
|
175
|
+
self._proc.wait(timeout=5)
|
|
176
|
+
except Exception:
|
|
177
|
+
self._proc.kill()
|
|
178
|
+
self._proc = None
|
|
179
|
+
|
|
180
|
+
def _send(self, payload):
|
|
181
|
+
if self._proc is None or self._proc.stdin is None:
|
|
182
|
+
raise MCPError("client is not started")
|
|
183
|
+
self._proc.stdin.write(json.dumps(payload) + "\n")
|
|
184
|
+
self._proc.stdin.flush()
|
|
185
|
+
|
|
186
|
+
def _send_notification(self, payload):
|
|
187
|
+
self._send(payload)
|
|
188
|
+
|
|
189
|
+
def _roundtrip(self, payload):
|
|
190
|
+
self._send(payload)
|
|
191
|
+
req_id = payload.get("id")
|
|
192
|
+
while True:
|
|
193
|
+
line = self._proc.stdout.readline() if self._proc.stdout else ""
|
|
194
|
+
if not line:
|
|
195
|
+
stderr = ""
|
|
196
|
+
try:
|
|
197
|
+
stderr = self._proc.stderr.read() if self._proc.stderr else ""
|
|
198
|
+
except Exception:
|
|
199
|
+
pass
|
|
200
|
+
raise MCPError(
|
|
201
|
+
f"server closed stdout during request id={req_id} "
|
|
202
|
+
f"(exit={self._proc.poll()}) stderr: {stderr[-500:]}"
|
|
203
|
+
)
|
|
204
|
+
line = line.strip()
|
|
205
|
+
if not line:
|
|
206
|
+
continue
|
|
207
|
+
try:
|
|
208
|
+
msg = json.loads(line)
|
|
209
|
+
except json.JSONDecodeError:
|
|
210
|
+
raise MCPError(
|
|
211
|
+
f"server wrote non-JSON to stdout (breaks stdio transport): {line[:200]}"
|
|
212
|
+
)
|
|
213
|
+
if msg.get("id") != req_id:
|
|
214
|
+
continue # notification or unrelated message
|
|
215
|
+
return msg
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _parse_http_body(body, content_type, req_id):
|
|
219
|
+
"""Extract the JSON-RPC message for ``req_id`` from an HTTP body.
|
|
220
|
+
|
|
221
|
+
Handles a plain JSON body and an SSE-framed (``text/event-stream``)
|
|
222
|
+
body of ``data:`` events, as Streamable HTTP servers may return
|
|
223
|
+
either.
|
|
224
|
+
"""
|
|
225
|
+
text = body.decode("utf-8", "replace") if isinstance(body, bytes) else body
|
|
226
|
+
if "text/event-stream" in (content_type or ""):
|
|
227
|
+
fallback = None
|
|
228
|
+
data_lines = []
|
|
229
|
+
messages = []
|
|
230
|
+
for raw_line in text.splitlines() + [""]:
|
|
231
|
+
line = raw_line.strip()
|
|
232
|
+
if line.startswith("data:"):
|
|
233
|
+
data_lines.append(line[5:].strip())
|
|
234
|
+
elif line == "" and data_lines:
|
|
235
|
+
messages.append("\n".join(data_lines))
|
|
236
|
+
data_lines = []
|
|
237
|
+
for data in messages:
|
|
238
|
+
if not data:
|
|
239
|
+
continue
|
|
240
|
+
try:
|
|
241
|
+
msg = json.loads(data)
|
|
242
|
+
except json.JSONDecodeError:
|
|
243
|
+
continue
|
|
244
|
+
if isinstance(msg, dict):
|
|
245
|
+
if msg.get("id") == req_id:
|
|
246
|
+
return msg
|
|
247
|
+
fallback = fallback or msg
|
|
248
|
+
if fallback is not None:
|
|
249
|
+
return fallback
|
|
250
|
+
raise MCPError("SSE response contained no JSON-RPC message")
|
|
251
|
+
text = text.strip()
|
|
252
|
+
if not text:
|
|
253
|
+
return None
|
|
254
|
+
return json.loads(text)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class HTTPClient(_BaseClient):
|
|
258
|
+
"""MCP over Streamable HTTP: one POST per JSON-RPC message.
|
|
259
|
+
|
|
260
|
+
- Sends ``Accept: application/json, text/event-stream`` and parses
|
|
261
|
+
either a plain JSON response or an SSE-framed one.
|
|
262
|
+
- Captures the ``Mcp-Session-Id`` response header on initialize and
|
|
263
|
+
sends it back on every later request.
|
|
264
|
+
- ``headers`` (dict, or list of ``"Name: value"`` strings) are sent on
|
|
265
|
+
every request -- e.g. ``{"Authorization": "Bearer ..."}``.
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
def __init__(self, url, headers=None, timeout=30):
|
|
269
|
+
super().__init__(timeout=timeout)
|
|
270
|
+
self.url = url
|
|
271
|
+
if headers and not isinstance(headers, dict):
|
|
272
|
+
headers = parse_headers(headers)
|
|
273
|
+
self.headers = dict(headers or {})
|
|
274
|
+
self.session_id = None
|
|
275
|
+
self._started = False
|
|
276
|
+
|
|
277
|
+
def start(self):
|
|
278
|
+
self._started = True
|
|
279
|
+
return self._initialize()
|
|
280
|
+
|
|
281
|
+
def close(self):
|
|
282
|
+
self._started = False
|
|
283
|
+
|
|
284
|
+
def _post(self, payload, expect_response=True):
|
|
285
|
+
body = json.dumps(payload).encode("utf-8")
|
|
286
|
+
headers = {
|
|
287
|
+
"Content-Type": "application/json",
|
|
288
|
+
"Accept": "application/json, text/event-stream",
|
|
289
|
+
}
|
|
290
|
+
headers.update(self.headers)
|
|
291
|
+
if self.session_id:
|
|
292
|
+
headers["Mcp-Session-Id"] = self.session_id
|
|
293
|
+
req = urllib.request.Request(self.url, data=body, headers=headers, method="POST")
|
|
294
|
+
try:
|
|
295
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
296
|
+
session = resp.headers.get("Mcp-Session-Id")
|
|
297
|
+
if session:
|
|
298
|
+
self.session_id = session
|
|
299
|
+
raw = resp.read()
|
|
300
|
+
if not expect_response or resp.status in (202, 204) or not raw:
|
|
301
|
+
return None
|
|
302
|
+
return _parse_http_body(raw, resp.headers.get("Content-Type"), payload.get("id"))
|
|
303
|
+
except urllib.error.HTTPError as exc:
|
|
304
|
+
try:
|
|
305
|
+
raw = exc.read()
|
|
306
|
+
except Exception:
|
|
307
|
+
raw = b""
|
|
308
|
+
if not expect_response:
|
|
309
|
+
return None # notifications may legitimately fail on strict servers
|
|
310
|
+
detail = raw.decode("utf-8", "replace")[:300] if raw else ""
|
|
311
|
+
raise MCPError(f"HTTP {exc.code} from {self.url}: {detail}") from exc
|
|
312
|
+
except urllib.error.URLError as exc:
|
|
313
|
+
if not expect_response:
|
|
314
|
+
return None
|
|
315
|
+
raise MCPError(f"cannot reach {self.url}: {exc.reason}") from exc
|
|
316
|
+
|
|
317
|
+
def _roundtrip(self, payload):
|
|
318
|
+
if not self._started:
|
|
319
|
+
raise MCPError("client is not started")
|
|
320
|
+
return self._post(payload, expect_response=True)
|
|
321
|
+
|
|
322
|
+
def _send_notification(self, payload):
|
|
323
|
+
if self._started:
|
|
324
|
+
self._post(payload, expect_response=False)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class SSEClient(_BaseClient):
|
|
328
|
+
"""Legacy (2024-11-05) SSE transport: GET stream + POST endpoint.
|
|
329
|
+
|
|
330
|
+
Opens the GET stream, waits for the server's ``endpoint`` event, POSTs
|
|
331
|
+
JSON-RPC messages to that endpoint, and matches responses arriving as
|
|
332
|
+
``message`` events on the GET stream by id.
|
|
333
|
+
"""
|
|
334
|
+
|
|
335
|
+
def __init__(self, url, headers=None, timeout=30):
|
|
336
|
+
super().__init__(timeout=timeout)
|
|
337
|
+
self.url = url
|
|
338
|
+
if headers and not isinstance(headers, dict):
|
|
339
|
+
headers = parse_headers(headers)
|
|
340
|
+
self.headers = dict(headers or {})
|
|
341
|
+
self._resp = None
|
|
342
|
+
self._thread = None
|
|
343
|
+
self._closed = False
|
|
344
|
+
self._endpoint = None
|
|
345
|
+
self._endpoint_ready = threading.Event()
|
|
346
|
+
self._pending = {}
|
|
347
|
+
self._cond = threading.Condition()
|
|
348
|
+
|
|
349
|
+
def start(self):
|
|
350
|
+
headers = {"Accept": "text/event-stream"}
|
|
351
|
+
headers.update(self.headers)
|
|
352
|
+
req = urllib.request.Request(self.url, headers=headers, method="GET")
|
|
353
|
+
try:
|
|
354
|
+
self._resp = urllib.request.urlopen(req) # long-lived stream
|
|
355
|
+
except (urllib.error.HTTPError, urllib.error.URLError) as exc:
|
|
356
|
+
raise MCPError(f"cannot open SSE stream {self.url}: {exc}") from exc
|
|
357
|
+
# Keep the raw socket: shutdown() is the only reliable way to wake
|
|
358
|
+
# the reader thread out of readline() from another thread --
|
|
359
|
+
# HTTPResponse.close() blocks on the buffered reader's lock.
|
|
360
|
+
try:
|
|
361
|
+
self._socket = self._resp.fp.raw._sock
|
|
362
|
+
except Exception:
|
|
363
|
+
self._socket = None
|
|
364
|
+
self._thread = threading.Thread(target=self._reader, daemon=True)
|
|
365
|
+
self._thread.start()
|
|
366
|
+
if not self._endpoint_ready.wait(timeout=self.timeout):
|
|
367
|
+
self.close()
|
|
368
|
+
raise MCPError(f"SSE server at {self.url} sent no endpoint event")
|
|
369
|
+
return self._initialize()
|
|
370
|
+
|
|
371
|
+
def _reader(self):
|
|
372
|
+
event, data_lines = None, []
|
|
373
|
+
try:
|
|
374
|
+
while not self._closed:
|
|
375
|
+
raw = self._resp.readline()
|
|
376
|
+
if not raw:
|
|
377
|
+
break
|
|
378
|
+
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
|
379
|
+
if line == "":
|
|
380
|
+
if data_lines:
|
|
381
|
+
self._dispatch(event, "\n".join(data_lines))
|
|
382
|
+
event, data_lines = None, []
|
|
383
|
+
elif line.startswith("event:"):
|
|
384
|
+
event = line[6:].strip()
|
|
385
|
+
elif line.startswith("data:"):
|
|
386
|
+
data_lines.append(line[5:].strip())
|
|
387
|
+
except Exception:
|
|
388
|
+
pass
|
|
389
|
+
|
|
390
|
+
def _dispatch(self, event, data):
|
|
391
|
+
if event == "endpoint":
|
|
392
|
+
self._endpoint = urllib.parse.urljoin(self.url, data.strip())
|
|
393
|
+
self._endpoint_ready.set()
|
|
394
|
+
return
|
|
395
|
+
try:
|
|
396
|
+
msg = json.loads(data)
|
|
397
|
+
except (json.JSONDecodeError, TypeError):
|
|
398
|
+
return
|
|
399
|
+
if isinstance(msg, dict) and msg.get("id") is not None:
|
|
400
|
+
with self._cond:
|
|
401
|
+
self._pending[msg["id"]] = msg
|
|
402
|
+
self._cond.notify_all()
|
|
403
|
+
|
|
404
|
+
def _post(self, payload):
|
|
405
|
+
headers = {"Content-Type": "application/json"}
|
|
406
|
+
headers.update(self.headers)
|
|
407
|
+
req = urllib.request.Request(
|
|
408
|
+
self._endpoint,
|
|
409
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
410
|
+
headers=headers,
|
|
411
|
+
method="POST",
|
|
412
|
+
)
|
|
413
|
+
try:
|
|
414
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
415
|
+
resp.read()
|
|
416
|
+
except urllib.error.HTTPError as exc:
|
|
417
|
+
raise MCPError(f"HTTP {exc.code} posting to SSE endpoint") from exc
|
|
418
|
+
except urllib.error.URLError as exc:
|
|
419
|
+
raise MCPError(f"cannot reach SSE endpoint: {exc.reason}") from exc
|
|
420
|
+
|
|
421
|
+
def _roundtrip(self, payload):
|
|
422
|
+
req_id = payload.get("id")
|
|
423
|
+
self._post(payload)
|
|
424
|
+
with self._cond:
|
|
425
|
+
found = self._cond.wait_for(
|
|
426
|
+
lambda: req_id in self._pending or self._closed, timeout=self.timeout
|
|
427
|
+
)
|
|
428
|
+
if not found or req_id not in self._pending:
|
|
429
|
+
raise MCPError(f"timed out waiting for SSE response id={req_id}")
|
|
430
|
+
return self._pending.pop(req_id)
|
|
431
|
+
|
|
432
|
+
def _send_notification(self, payload):
|
|
433
|
+
try:
|
|
434
|
+
self._post(payload)
|
|
435
|
+
except MCPError:
|
|
436
|
+
pass
|
|
437
|
+
|
|
438
|
+
def close(self):
|
|
439
|
+
self._closed = True
|
|
440
|
+
with self._cond:
|
|
441
|
+
self._cond.notify_all()
|
|
442
|
+
if getattr(self, "_socket", None) is not None:
|
|
443
|
+
try:
|
|
444
|
+
import socket as _socket_module
|
|
445
|
+
|
|
446
|
+
self._socket.shutdown(_socket_module.SHUT_RDWR)
|
|
447
|
+
except Exception:
|
|
448
|
+
pass
|
|
449
|
+
self._socket = None
|
|
450
|
+
if self._resp is not None:
|
|
451
|
+
try:
|
|
452
|
+
self._resp.close()
|
|
453
|
+
except Exception:
|
|
454
|
+
pass
|
|
455
|
+
self._resp = None
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def result_text(result):
|
|
459
|
+
"""Join the text content blocks of a tools/call result."""
|
|
460
|
+
parts = []
|
|
461
|
+
for block in (result or {}).get("content", []) or []:
|
|
462
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
463
|
+
parts.append(str(block.get("text", "")))
|
|
464
|
+
return "\n".join(parts)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def main_server_command(argv):
|
|
468
|
+
return [sys.executable] + list(argv)
|