misclosure 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.
- misclosure/__init__.py +3 -0
- misclosure/cli.py +132 -0
- misclosure/client.py +362 -0
- misclosure/conform/__init__.py +1 -0
- misclosure/conform/compare.py +387 -0
- misclosure/conform/report.py +176 -0
- misclosure/conform/runner.py +506 -0
- misclosure/encoding.py +174 -0
- misclosure/jsonlit.py +61 -0
- misclosure/reference.py +107 -0
- misclosure/score/__init__.py +1 -0
- misclosure/score/numbers.py +122 -0
- misclosure/score/scorer.py +255 -0
- misclosure/score/support.py +200 -0
- misclosure/score/transcript.py +151 -0
- misclosure/score/traps.py +98 -0
- misclosure/selectors.py +159 -0
- misclosure-0.1.0.dist-info/METADATA +295 -0
- misclosure-0.1.0.dist-info/RECORD +22 -0
- misclosure-0.1.0.dist-info/WHEEL +4 -0
- misclosure-0.1.0.dist-info/entry_points.txt +2 -0
- misclosure-0.1.0.dist-info/licenses/LICENSE +202 -0
misclosure/__init__.py
ADDED
misclosure/cli.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Command line: `misclosure conform`, `misclosure score`, `misclosure transcript`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import shlex
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import anyio
|
|
11
|
+
|
|
12
|
+
from misclosure import __version__
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _leaf_errors(exc: BaseException) -> list[BaseException]:
|
|
16
|
+
if isinstance(exc, BaseExceptionGroup):
|
|
17
|
+
return [e for sub in exc.exceptions for e in _leaf_errors(sub)]
|
|
18
|
+
return [exc]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _conform(args: argparse.Namespace) -> int:
|
|
22
|
+
from misclosure.client import ServerSpec
|
|
23
|
+
from misclosure.conform import report
|
|
24
|
+
from misclosure.conform.runner import CaseFile, Runner
|
|
25
|
+
from misclosure.reference import ReferenceError
|
|
26
|
+
|
|
27
|
+
cf = CaseFile.load(args.cases)
|
|
28
|
+
server = None
|
|
29
|
+
if args.server or args.url:
|
|
30
|
+
server = ServerSpec(
|
|
31
|
+
command=shlex.split(args.server) if args.server else None,
|
|
32
|
+
url=args.url,
|
|
33
|
+
mode=args.mode or "auto",
|
|
34
|
+
)
|
|
35
|
+
elif args.mode:
|
|
36
|
+
spec = dict(cf.data.get("server") or {})
|
|
37
|
+
spec["mode"] = args.mode
|
|
38
|
+
cf.data["server"] = spec
|
|
39
|
+
errlog = open(args.server_log, "w", encoding="utf-8") if args.server_log else None # noqa: SIM115
|
|
40
|
+
try:
|
|
41
|
+
runner = Runner(
|
|
42
|
+
cf,
|
|
43
|
+
server=server,
|
|
44
|
+
workdir=Path(args.workdir) if args.workdir else None,
|
|
45
|
+
reference_override=Path(args.reference) if args.reference else None,
|
|
46
|
+
only=args.case or None,
|
|
47
|
+
errlog=errlog,
|
|
48
|
+
)
|
|
49
|
+
result = anyio.run(runner.run)
|
|
50
|
+
except ReferenceError as exc:
|
|
51
|
+
print(f"error: the reference could not be made: {exc}", file=sys.stderr)
|
|
52
|
+
return 2
|
|
53
|
+
except Exception as exc: # the SDK reports a server that will not start as a group
|
|
54
|
+
leaves = list(_leaf_errors(exc))
|
|
55
|
+
print("error: the server run failed:", file=sys.stderr)
|
|
56
|
+
for e in leaves:
|
|
57
|
+
print(f" {type(e).__name__}: {e}", file=sys.stderr)
|
|
58
|
+
print("Run with --server-log to keep the server's stderr.", file=sys.stderr)
|
|
59
|
+
return 2
|
|
60
|
+
finally:
|
|
61
|
+
if errlog:
|
|
62
|
+
errlog.close()
|
|
63
|
+
paths = report.write(result, Path(args.out), Path(args.junit) if args.junit else None)
|
|
64
|
+
t = result.totals()
|
|
65
|
+
print(
|
|
66
|
+
f"{'PASS' if result.passed else 'FAIL'}: {len(result.cases)} cases, "
|
|
67
|
+
f"{t.values} values compared ({t.table_cells} table cells, {t.scalars} scalars, "
|
|
68
|
+
f"{t.other} other checks), "
|
|
69
|
+
f"{sum(len(c.failures) for c in result.cases)} failures"
|
|
70
|
+
)
|
|
71
|
+
version = result.negotiation.get("sdk_protocol_version")
|
|
72
|
+
print(f"protocol {version}; reports in {paths['json'].parent}")
|
|
73
|
+
return 0 if result.passed else 1
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _score(args: argparse.Namespace) -> int:
|
|
77
|
+
from misclosure.score.scorer import run_score
|
|
78
|
+
|
|
79
|
+
return run_score(
|
|
80
|
+
Path(args.eval),
|
|
81
|
+
out=Path(args.out) if args.out else None,
|
|
82
|
+
transcripts=Path(args.transcripts) if args.transcripts else None,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _transcript(args: argparse.Namespace) -> int:
|
|
87
|
+
from misclosure.score.transcript import convert
|
|
88
|
+
|
|
89
|
+
convert(Path(args.input), Path(args.output), args.source_format, strip_prefix=args.strip_prefix)
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def main(argv: list[str] | None = None) -> int:
|
|
94
|
+
p = argparse.ArgumentParser(prog="misclosure", description=__doc__)
|
|
95
|
+
p.add_argument("--version", action="version", version=f"misclosure {__version__}")
|
|
96
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
97
|
+
|
|
98
|
+
c = sub.add_parser("conform", help="compare a server's output with reference values")
|
|
99
|
+
c.add_argument("cases", help="case file (YAML or JSON)")
|
|
100
|
+
g = c.add_mutually_exclusive_group()
|
|
101
|
+
g.add_argument("--server", help="command that starts the server on stdio")
|
|
102
|
+
g.add_argument("--url", help="URL of a streamable HTTP server")
|
|
103
|
+
c.add_argument("--mode", help='protocol negotiation: "auto" (default), "legacy" or a version')
|
|
104
|
+
c.add_argument(
|
|
105
|
+
"--reference", help="use this recorded reference file in place of the declared one"
|
|
106
|
+
)
|
|
107
|
+
c.add_argument("--case", action="append", help="run only this case; repeatable")
|
|
108
|
+
c.add_argument("--out", default="misclosure-out", help="report directory")
|
|
109
|
+
c.add_argument("--junit", help="path of the JUnit XML file")
|
|
110
|
+
c.add_argument("--workdir", help="keep working files here")
|
|
111
|
+
c.add_argument("--server-log", help="write the server's stderr to this file")
|
|
112
|
+
c.set_defaults(func=_conform)
|
|
113
|
+
|
|
114
|
+
s = sub.add_parser("score", help="score answers against reference values")
|
|
115
|
+
s.add_argument("eval", help="evaluation file (YAML or JSON)")
|
|
116
|
+
s.add_argument("--transcripts", help="transcript directory, in place of the declared one")
|
|
117
|
+
s.add_argument("--out", help="report directory (default: beside the evaluation file)")
|
|
118
|
+
s.set_defaults(func=_score)
|
|
119
|
+
|
|
120
|
+
t = sub.add_parser("transcript", help="convert a transcript to the misclosure format")
|
|
121
|
+
t.add_argument("input")
|
|
122
|
+
t.add_argument("output")
|
|
123
|
+
t.add_argument("--from", dest="source_format", default="claude-stream-json")
|
|
124
|
+
t.add_argument("--strip-prefix", default="mcp__", help="tool-name prefix to remove")
|
|
125
|
+
t.set_defaults(func=_transcript)
|
|
126
|
+
|
|
127
|
+
args = p.parse_args(argv)
|
|
128
|
+
return int(args.func(args))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == "__main__":
|
|
132
|
+
sys.exit(main())
|
misclosure/client.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""Connecting to an MCP server with the official Python SDK.
|
|
2
|
+
|
|
3
|
+
The SDK's `Client` negotiates the protocol and makes the calls. The
|
|
4
|
+
transports here pass every message through unchanged and keep a copy of the
|
|
5
|
+
text the server wrote, so the runner can read each number as the server
|
|
6
|
+
wrote it (`jsonlit`), and check the SDK's parse of it.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
from collections.abc import AsyncIterator, Mapping, Sequence
|
|
14
|
+
from contextlib import asynccontextmanager
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any, TextIO
|
|
17
|
+
|
|
18
|
+
import anyio
|
|
19
|
+
import httpx2
|
|
20
|
+
import mcp_types as types
|
|
21
|
+
from anyio.streams.text import TextReceiveStream
|
|
22
|
+
from mcp import Client
|
|
23
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
24
|
+
from mcp.shared.message import SessionMessage
|
|
25
|
+
from mcp_types import Implementation
|
|
26
|
+
|
|
27
|
+
from misclosure import __version__, jsonlit
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Recorder:
|
|
32
|
+
"""The JSON-RPC messages of one connection, as text, in both directions."""
|
|
33
|
+
|
|
34
|
+
outgoing: list[str] = field(default_factory=list)
|
|
35
|
+
incoming: list[str] = field(default_factory=list)
|
|
36
|
+
_methods: dict[Any, str] = field(default_factory=dict)
|
|
37
|
+
_responses: dict[Any, Any] = field(default_factory=dict)
|
|
38
|
+
_last_id: dict[str, Any] = field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
def sent(self, text: str) -> None:
|
|
41
|
+
self.outgoing.append(text)
|
|
42
|
+
msg = jsonlit.loads(text)
|
|
43
|
+
if isinstance(msg, dict) and "method" in msg and "id" in msg:
|
|
44
|
+
key = jsonlit.plain(msg["id"])
|
|
45
|
+
self._methods[key] = msg["method"]
|
|
46
|
+
self._last_id[msg["method"]] = key
|
|
47
|
+
|
|
48
|
+
def received(self, text: str) -> None:
|
|
49
|
+
self.incoming.append(text)
|
|
50
|
+
try:
|
|
51
|
+
msg = jsonlit.loads(text)
|
|
52
|
+
except ValueError:
|
|
53
|
+
return
|
|
54
|
+
for m in msg if isinstance(msg, list) else [msg]:
|
|
55
|
+
if isinstance(m, dict) and "id" in m and ("result" in m or "error" in m):
|
|
56
|
+
self._responses[jsonlit.plain(m["id"])] = m
|
|
57
|
+
|
|
58
|
+
def last_response(self, method: str) -> dict[str, Any] | None:
|
|
59
|
+
"""The response, with literal numbers, to the last request of `method`."""
|
|
60
|
+
key = self._last_id.get(method)
|
|
61
|
+
return None if key is None else self._responses.get(key)
|
|
62
|
+
|
|
63
|
+
def exchange(self, method: str) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
|
|
64
|
+
"""The last request of `method` as sent, and its response."""
|
|
65
|
+
key = self._last_id.get(method)
|
|
66
|
+
if key is None:
|
|
67
|
+
return None, None
|
|
68
|
+
request = None
|
|
69
|
+
for text in reversed(self.outgoing):
|
|
70
|
+
m = jsonlit.loads(text)
|
|
71
|
+
if isinstance(m, dict) and m.get("method") == method:
|
|
72
|
+
request = m
|
|
73
|
+
break
|
|
74
|
+
return request, self._responses.get(key)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ---- stdio ----------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@asynccontextmanager
|
|
81
|
+
async def stdio_transport(
|
|
82
|
+
command: Sequence[str],
|
|
83
|
+
recorder: Recorder,
|
|
84
|
+
*,
|
|
85
|
+
env: Mapping[str, str] | None = None,
|
|
86
|
+
cwd: str | None = None,
|
|
87
|
+
errlog: TextIO | None = None,
|
|
88
|
+
) -> AsyncIterator[Any]:
|
|
89
|
+
"""Run `command` and exchange newline-delimited JSON-RPC over its stdio.
|
|
90
|
+
|
|
91
|
+
The server inherits this process's environment, with `env` on top.
|
|
92
|
+
"""
|
|
93
|
+
process = await anyio.open_process(
|
|
94
|
+
list(command),
|
|
95
|
+
env={**os.environ, **(env or {})},
|
|
96
|
+
cwd=cwd,
|
|
97
|
+
stderr=errlog if errlog is not None else sys.stderr,
|
|
98
|
+
)
|
|
99
|
+
read_send, read_recv = anyio.create_memory_object_stream[SessionMessage | Exception](0)
|
|
100
|
+
write_send, write_recv = anyio.create_memory_object_stream[SessionMessage](0)
|
|
101
|
+
|
|
102
|
+
async def reader() -> None:
|
|
103
|
+
assert process.stdout is not None
|
|
104
|
+
buffer = ""
|
|
105
|
+
async with read_send:
|
|
106
|
+
try:
|
|
107
|
+
async for chunk in TextReceiveStream(process.stdout):
|
|
108
|
+
lines = (buffer + chunk).split("\n")
|
|
109
|
+
buffer = lines.pop()
|
|
110
|
+
for line in lines:
|
|
111
|
+
if not line.strip():
|
|
112
|
+
continue
|
|
113
|
+
recorder.received(line)
|
|
114
|
+
item: SessionMessage | Exception
|
|
115
|
+
try:
|
|
116
|
+
item = SessionMessage(
|
|
117
|
+
types.jsonrpc_message_adapter.validate_json(line, by_name=False)
|
|
118
|
+
)
|
|
119
|
+
except ValueError as exc:
|
|
120
|
+
item = exc
|
|
121
|
+
await read_send.send(item)
|
|
122
|
+
except (anyio.ClosedResourceError, anyio.BrokenResourceError):
|
|
123
|
+
pass
|
|
124
|
+
|
|
125
|
+
async def writer() -> None:
|
|
126
|
+
assert process.stdin is not None
|
|
127
|
+
async with write_recv:
|
|
128
|
+
try:
|
|
129
|
+
async for sm in write_recv:
|
|
130
|
+
text = sm.message.model_dump_json(by_alias=True, exclude_unset=True)
|
|
131
|
+
recorder.sent(text)
|
|
132
|
+
await process.stdin.send((text + "\n").encode("utf-8"))
|
|
133
|
+
except (anyio.ClosedResourceError, anyio.BrokenResourceError, OSError):
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
async with anyio.create_task_group() as tg:
|
|
137
|
+
tg.start_soon(reader)
|
|
138
|
+
tg.start_soon(writer)
|
|
139
|
+
try:
|
|
140
|
+
yield read_recv, write_send
|
|
141
|
+
finally:
|
|
142
|
+
with anyio.CancelScope(shield=True):
|
|
143
|
+
await write_send.aclose()
|
|
144
|
+
if process.stdin is not None:
|
|
145
|
+
await process.stdin.aclose()
|
|
146
|
+
with anyio.move_on_after(5):
|
|
147
|
+
await process.wait()
|
|
148
|
+
if process.returncode is None:
|
|
149
|
+
process.terminate()
|
|
150
|
+
with anyio.move_on_after(3):
|
|
151
|
+
await process.wait()
|
|
152
|
+
if process.returncode is None:
|
|
153
|
+
process.kill()
|
|
154
|
+
await process.wait()
|
|
155
|
+
await read_recv.aclose()
|
|
156
|
+
tg.cancel_scope.cancel()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# ---- streamable HTTP --------------------------------------------------------------
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class _TeeStream(httpx2.AsyncByteStream):
|
|
163
|
+
"""Passes a response body through and gives each JSON-RPC message to the recorder."""
|
|
164
|
+
|
|
165
|
+
def __init__(self, inner: Any, content_type: str, recorder: Recorder) -> None:
|
|
166
|
+
self.inner = inner
|
|
167
|
+
self.sse = "text/event-stream" in content_type
|
|
168
|
+
self.json = "json" in content_type
|
|
169
|
+
self.recorder = recorder
|
|
170
|
+
self.buffer = ""
|
|
171
|
+
|
|
172
|
+
def _events(self, final: bool) -> None:
|
|
173
|
+
text = self.buffer.replace("\r\n", "\n").replace("\r", "\n")
|
|
174
|
+
blocks = text.split("\n\n")
|
|
175
|
+
self.buffer = "" if final else blocks.pop()
|
|
176
|
+
for block in blocks:
|
|
177
|
+
data = [ln[5:].removeprefix(" ") for ln in block.split("\n") if ln.startswith("data:")]
|
|
178
|
+
if data:
|
|
179
|
+
self.recorder.received("\n".join(data))
|
|
180
|
+
|
|
181
|
+
async def __aiter__(self) -> AsyncIterator[bytes]:
|
|
182
|
+
async for chunk in self.inner:
|
|
183
|
+
if self.sse or self.json:
|
|
184
|
+
self.buffer += chunk.decode("utf-8", errors="replace")
|
|
185
|
+
if self.sse:
|
|
186
|
+
self._events(final=False)
|
|
187
|
+
yield chunk
|
|
188
|
+
if self.json and self.buffer.strip():
|
|
189
|
+
self.recorder.received(self.buffer)
|
|
190
|
+
self.buffer = ""
|
|
191
|
+
elif self.sse:
|
|
192
|
+
self._events(final=True)
|
|
193
|
+
|
|
194
|
+
async def aclose(self) -> None:
|
|
195
|
+
await self.inner.aclose()
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class _TeeTransport(httpx2.AsyncBaseTransport):
|
|
199
|
+
def __init__(self, recorder: Recorder) -> None:
|
|
200
|
+
self.inner = httpx2.AsyncHTTPTransport()
|
|
201
|
+
self.recorder = recorder
|
|
202
|
+
|
|
203
|
+
async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:
|
|
204
|
+
response = await self.inner.handle_async_request(request)
|
|
205
|
+
content_type = response.headers.get("content-type", "")
|
|
206
|
+
return httpx2.Response(
|
|
207
|
+
status_code=response.status_code,
|
|
208
|
+
headers=response.headers,
|
|
209
|
+
stream=_TeeStream(response.stream, content_type, self.recorder),
|
|
210
|
+
extensions=response.extensions,
|
|
211
|
+
request=request,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
async def aclose(self) -> None:
|
|
215
|
+
await self.inner.aclose()
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class _RecordingWriter:
|
|
219
|
+
def __init__(self, inner: Any, recorder: Recorder) -> None:
|
|
220
|
+
self.inner = inner
|
|
221
|
+
self.recorder = recorder
|
|
222
|
+
|
|
223
|
+
async def send(self, item: SessionMessage) -> None:
|
|
224
|
+
self.recorder.sent(item.message.model_dump_json(by_alias=True, exclude_unset=True))
|
|
225
|
+
await self.inner.send(item)
|
|
226
|
+
|
|
227
|
+
async def aclose(self) -> None:
|
|
228
|
+
await self.inner.aclose()
|
|
229
|
+
|
|
230
|
+
async def __aenter__(self) -> _RecordingWriter:
|
|
231
|
+
return self
|
|
232
|
+
|
|
233
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
234
|
+
await self.aclose()
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@asynccontextmanager
|
|
238
|
+
async def http_transport(
|
|
239
|
+
url: str, recorder: Recorder, headers: Mapping[str, str] | None = None
|
|
240
|
+
) -> AsyncIterator[Any]:
|
|
241
|
+
"""Streamable HTTP through the SDK, with response bodies copied to the recorder."""
|
|
242
|
+
client = httpx2.AsyncClient(
|
|
243
|
+
transport=_TeeTransport(recorder),
|
|
244
|
+
timeout=httpx2.Timeout(30.0, read=300.0),
|
|
245
|
+
# the copy is taken before decompression, so ask for none
|
|
246
|
+
headers={"Accept-Encoding": "identity", **(headers or {})},
|
|
247
|
+
)
|
|
248
|
+
async with client, streamable_http_client(url, http_client=client) as (read, write):
|
|
249
|
+
yield read, _RecordingWriter(write, recorder)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
# ---- connection -------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
@dataclass
|
|
256
|
+
class ToolOutcome:
|
|
257
|
+
is_error: bool
|
|
258
|
+
structured: Any
|
|
259
|
+
"""structuredContent as the server wrote it, numbers as `jsonlit.Num`."""
|
|
260
|
+
sdk_structured: Any
|
|
261
|
+
"""structuredContent as the SDK parsed it."""
|
|
262
|
+
text: str
|
|
263
|
+
"""The text content blocks, joined."""
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@dataclass
|
|
267
|
+
class ServerSpec:
|
|
268
|
+
command: list[str] | None = None
|
|
269
|
+
url: str | None = None
|
|
270
|
+
env: dict[str, str] = field(default_factory=dict)
|
|
271
|
+
cwd: str | None = None
|
|
272
|
+
mode: str = "auto"
|
|
273
|
+
"""The SDK's negotiation mode: "auto", "legacy", or a protocol version."""
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class Connection:
|
|
277
|
+
def __init__(self, spec: ServerSpec, errlog: TextIO | None = None) -> None:
|
|
278
|
+
self.spec = spec
|
|
279
|
+
self.recorder = Recorder()
|
|
280
|
+
self.errlog = errlog
|
|
281
|
+
self._client: Client | None = None
|
|
282
|
+
self._cm: Any = None
|
|
283
|
+
|
|
284
|
+
async def __aenter__(self) -> Connection:
|
|
285
|
+
if self.spec.url:
|
|
286
|
+
transport = http_transport(self.spec.url, self.recorder)
|
|
287
|
+
elif self.spec.command:
|
|
288
|
+
transport = stdio_transport(
|
|
289
|
+
self.spec.command,
|
|
290
|
+
self.recorder,
|
|
291
|
+
env=self.spec.env,
|
|
292
|
+
cwd=self.spec.cwd,
|
|
293
|
+
errlog=self.errlog,
|
|
294
|
+
)
|
|
295
|
+
else:
|
|
296
|
+
raise ValueError("a server needs a command or a URL")
|
|
297
|
+
# no response cache: every call reaches the server
|
|
298
|
+
self._cm = Client(
|
|
299
|
+
transport, # type: ignore[arg-type]
|
|
300
|
+
mode=self.spec.mode,
|
|
301
|
+
cache=None,
|
|
302
|
+
client_info=Implementation(name="misclosure", version=__version__),
|
|
303
|
+
)
|
|
304
|
+
self._client = await self._cm.__aenter__()
|
|
305
|
+
return self
|
|
306
|
+
|
|
307
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
308
|
+
if self._cm is not None:
|
|
309
|
+
await self._cm.__aexit__(*exc)
|
|
310
|
+
|
|
311
|
+
@property
|
|
312
|
+
def client(self) -> Client:
|
|
313
|
+
assert self._client is not None
|
|
314
|
+
return self._client
|
|
315
|
+
|
|
316
|
+
def negotiation(self) -> dict[str, Any]:
|
|
317
|
+
"""What each side said about the protocol version, from the messages themselves."""
|
|
318
|
+
out: dict[str, Any] = {"sdk_protocol_version": self.client.protocol_version}
|
|
319
|
+
for method in ("server/discover", "initialize"):
|
|
320
|
+
request, response = self.recorder.exchange(method)
|
|
321
|
+
if request is None:
|
|
322
|
+
continue
|
|
323
|
+
params = jsonlit.plain(request.get("params") or {})
|
|
324
|
+
entry: dict[str, Any] = {"client_sent": params.get("protocolVersion")}
|
|
325
|
+
if response is not None and "result" in response:
|
|
326
|
+
result = jsonlit.plain(response["result"])
|
|
327
|
+
entry["server_answered"] = result.get("protocolVersion") or result.get(
|
|
328
|
+
"supportedVersions"
|
|
329
|
+
)
|
|
330
|
+
if "supportedVersions" in result:
|
|
331
|
+
entry["server_supported"] = result["supportedVersions"]
|
|
332
|
+
elif response is not None:
|
|
333
|
+
entry["server_error"] = jsonlit.plain(response.get("error"))
|
|
334
|
+
out[method] = entry
|
|
335
|
+
info = self.client.server_info
|
|
336
|
+
if info is not None:
|
|
337
|
+
out["server"] = {"name": info.name, "version": info.version}
|
|
338
|
+
return out
|
|
339
|
+
|
|
340
|
+
async def call_tool(self, name: str, arguments: Mapping[str, Any]) -> ToolOutcome:
|
|
341
|
+
result = await self.client.call_tool(name, dict(arguments))
|
|
342
|
+
raw = self.recorder.last_response("tools/call")
|
|
343
|
+
structured = None
|
|
344
|
+
if raw is not None and isinstance(raw.get("result"), dict):
|
|
345
|
+
structured = raw["result"].get("structuredContent")
|
|
346
|
+
text = "\n".join(c.text for c in result.content if getattr(c, "type", None) == "text")
|
|
347
|
+
return ToolOutcome(
|
|
348
|
+
is_error=bool(result.is_error),
|
|
349
|
+
structured=structured,
|
|
350
|
+
sdk_structured=result.structured_content,
|
|
351
|
+
text=text,
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
async def read_resource(self, uri: str) -> str:
|
|
355
|
+
result = await self.client.read_resource(uri)
|
|
356
|
+
parts = []
|
|
357
|
+
for c in result.contents:
|
|
358
|
+
t = getattr(c, "text", None)
|
|
359
|
+
if t is None:
|
|
360
|
+
raise ValueError(f"{uri}: not a text resource")
|
|
361
|
+
parts.append(t)
|
|
362
|
+
return "".join(parts)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The conformance runner: server output against reference values, bit for bit."""
|