mcpico 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.
Potentially problematic release.
This version of mcpico might be problematic. Click here for more details.
- mcpico/__init__.py +22 -0
- mcpico/_client.py +593 -0
- mcpico/_context.py +199 -0
- mcpico/_functions.py +164 -0
- mcpico/_headers.py +140 -0
- mcpico/_jsonrpc.py +111 -0
- mcpico/_legacy.py +234 -0
- mcpico/_schema.py +62 -0
- mcpico/_server.py +975 -0
- mcpico/_state.py +85 -0
- mcpico/_transport.py +119 -0
- mcpico/_uri_template.py +51 -0
- mcpico/auth/__init__.py +148 -0
- mcpico/auth/client.py +535 -0
- mcpico/auth/jwt.py +122 -0
- mcpico/errors.py +115 -0
- mcpico/http/__init__.py +6 -0
- mcpico/http/_client.py +168 -0
- mcpico/http/_granian.py +84 -0
- mcpico/http/_legacy.py +132 -0
- mcpico/http/_server.py +372 -0
- mcpico/py.typed +0 -0
- mcpico/stdio.py +304 -0
- mcpico/types.py +433 -0
- mcpico-0.1.0.dist-info/METADATA +371 -0
- mcpico-0.1.0.dist-info/RECORD +28 -0
- mcpico-0.1.0.dist-info/WHEEL +4 -0
- mcpico-0.1.0.dist-info/licenses/LICENSE +21 -0
mcpico/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""MCPico: a lightweight, fully typed Python SDK for the Model Context Protocol."""
|
|
2
|
+
|
|
3
|
+
from ._client import Client, Subscription
|
|
4
|
+
from ._context import Context
|
|
5
|
+
from ._server import Server
|
|
6
|
+
from ._transport import MemoryTransport, SessionTransport, Transport
|
|
7
|
+
from .errors import MCPError
|
|
8
|
+
from .stdio import StdioTransport
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Client",
|
|
12
|
+
"Context",
|
|
13
|
+
"MCPError",
|
|
14
|
+
"MemoryTransport",
|
|
15
|
+
"Server",
|
|
16
|
+
"SessionTransport",
|
|
17
|
+
"StdioTransport",
|
|
18
|
+
"Subscription",
|
|
19
|
+
"Transport",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
mcpico/_client.py
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
"""The MCP client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
import itertools
|
|
8
|
+
import logging
|
|
9
|
+
from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Iterable
|
|
10
|
+
from contextlib import asynccontextmanager
|
|
11
|
+
from typing import Any, Literal, Self
|
|
12
|
+
|
|
13
|
+
import msgspec
|
|
14
|
+
|
|
15
|
+
from . import _jsonrpc as jsonrpc
|
|
16
|
+
from ._headers import encode_value, header_params
|
|
17
|
+
from ._schema import SchemaError, Validator
|
|
18
|
+
from ._transport import SessionTransport, Transport
|
|
19
|
+
from .errors import (
|
|
20
|
+
HEADER_MISMATCH,
|
|
21
|
+
INTERNAL_ERROR,
|
|
22
|
+
METHOD_NOT_FOUND,
|
|
23
|
+
MISSING_REQUIRED_CLIENT_CAPABILITY,
|
|
24
|
+
ConnectionClosedError,
|
|
25
|
+
MCPError,
|
|
26
|
+
ProtocolViolationError,
|
|
27
|
+
RequestTimeoutError,
|
|
28
|
+
UnsupportedVersionError,
|
|
29
|
+
)
|
|
30
|
+
from .types import (
|
|
31
|
+
LATEST_PROTOCOL_VERSION,
|
|
32
|
+
LEGACY_PROTOCOL_VERSIONS,
|
|
33
|
+
SUPPORTED_PROTOCOL_VERSIONS,
|
|
34
|
+
CallToolResult,
|
|
35
|
+
ClientCapabilities,
|
|
36
|
+
CompleteResult,
|
|
37
|
+
Completion,
|
|
38
|
+
DiscoverResult,
|
|
39
|
+
ElicitationCapability,
|
|
40
|
+
ElicitRequest,
|
|
41
|
+
ElicitResult,
|
|
42
|
+
GetPromptResult,
|
|
43
|
+
Implementation,
|
|
44
|
+
InputRequiredResult,
|
|
45
|
+
ListPromptsResult,
|
|
46
|
+
ListResourcesResult,
|
|
47
|
+
ListResourceTemplatesResult,
|
|
48
|
+
ListToolsResult,
|
|
49
|
+
Notification,
|
|
50
|
+
Prompt,
|
|
51
|
+
PromptReference,
|
|
52
|
+
ReadResourceResult,
|
|
53
|
+
Resource,
|
|
54
|
+
ResourceTemplate,
|
|
55
|
+
ResourceTemplateReference,
|
|
56
|
+
ServerCapabilities,
|
|
57
|
+
SubscriptionFilter,
|
|
58
|
+
Tool,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
__all__ = ["Client", "Subscription"]
|
|
62
|
+
|
|
63
|
+
logger = logging.getLogger("mcpico.client")
|
|
64
|
+
|
|
65
|
+
type JSONObject = dict[str, Any]
|
|
66
|
+
type ElicitationHandler = Callable[[ElicitRequest], Awaitable[ElicitResult] | ElicitResult]
|
|
67
|
+
# How the server is spoken to: not yet known, per-request metadata, or an
|
|
68
|
+
# initialize session (2025-11-25).
|
|
69
|
+
type _Era = Literal["unknown", "stateless", "session"]
|
|
70
|
+
type ProgressHandler = Callable[[float, float | None, str | None], Awaitable[None] | None]
|
|
71
|
+
|
|
72
|
+
_INPUT_METHODS = frozenset({"tools/call", "resources/read", "prompts/get"})
|
|
73
|
+
_NAME_PARAM = {"tools/call": "name", "prompts/get": "name", "resources/read": "uri"}
|
|
74
|
+
#: Seconds to wait for the answer to the ``server/discover`` probe.
|
|
75
|
+
_PROBE_TIMEOUT = 10.0
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Subscription:
|
|
79
|
+
"""An open ``subscriptions/listen`` stream. Iterate it to receive notifications."""
|
|
80
|
+
|
|
81
|
+
def __init__(
|
|
82
|
+
self, acknowledged: SubscriptionFilter, stream: AsyncIterator[Notification]
|
|
83
|
+
) -> None:
|
|
84
|
+
#: The notification types the server agreed to send.
|
|
85
|
+
self.acknowledged = acknowledged
|
|
86
|
+
self._stream = stream
|
|
87
|
+
|
|
88
|
+
def __aiter__(self) -> AsyncIterator[Notification]:
|
|
89
|
+
return self._stream
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Client:
|
|
93
|
+
"""A client for one MCP server, reached through a :class:`~mcpico.Transport`.
|
|
94
|
+
|
|
95
|
+
Use it as an async context manager::
|
|
96
|
+
|
|
97
|
+
async with Client(StdioTransport("python", ["server.py"])) as client:
|
|
98
|
+
tools = await client.list_tools()
|
|
99
|
+
result = await client.call_tool("add", {"a": 1, "b": 2})
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
transport: How to reach the server.
|
|
103
|
+
name: Client name sent with every request.
|
|
104
|
+
version: Client version sent with every request.
|
|
105
|
+
elicitation: Called when the server needs user input. Declares the
|
|
106
|
+
elicitation capability when given.
|
|
107
|
+
elicitation_modes: Elicitation modes the handler supports.
|
|
108
|
+
timeout: Default seconds to wait for a response (``None``: forever).
|
|
109
|
+
max_input_rounds: Most retries with user input for one call.
|
|
110
|
+
protocol_versions: Protocol revisions to speak (default: all). The client
|
|
111
|
+
probes with ``server/discover`` and falls back to an ``initialize``
|
|
112
|
+
session (2025-11-25) when the server does not understand it. The stdio
|
|
113
|
+
and Streamable HTTP transports support both.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
transport: Transport,
|
|
119
|
+
*,
|
|
120
|
+
name: str = "mcpico",
|
|
121
|
+
version: str = "0.0.0",
|
|
122
|
+
elicitation: ElicitationHandler | None = None,
|
|
123
|
+
elicitation_modes: Iterable[Literal["form", "url"]] = ("form",),
|
|
124
|
+
timeout: float | None = 60.0,
|
|
125
|
+
max_input_rounds: int = 8,
|
|
126
|
+
protocol_versions: Iterable[str] | None = None,
|
|
127
|
+
) -> None:
|
|
128
|
+
self.transport = transport
|
|
129
|
+
self.info = Implementation(name=name, version=version)
|
|
130
|
+
self.timeout = timeout
|
|
131
|
+
self.max_input_rounds = max_input_rounds
|
|
132
|
+
self._elicitation = elicitation
|
|
133
|
+
modes = set(elicitation_modes)
|
|
134
|
+
self.capabilities = ClientCapabilities(
|
|
135
|
+
elicitation=ElicitationCapability(
|
|
136
|
+
form={} if "form" in modes else None, url={} if "url" in modes else None
|
|
137
|
+
)
|
|
138
|
+
if elicitation is not None
|
|
139
|
+
else None
|
|
140
|
+
)
|
|
141
|
+
self._ids = itertools.count(1)
|
|
142
|
+
self._tools: dict[str, Tool] = {}
|
|
143
|
+
self._started = False
|
|
144
|
+
known = (*SUPPORTED_PROTOCOL_VERSIONS, *LEGACY_PROTOCOL_VERSIONS)
|
|
145
|
+
wanted = set(known if protocol_versions is None else protocol_versions)
|
|
146
|
+
if not wanted or not wanted <= set(known):
|
|
147
|
+
raise ValueError(f"protocol_versions must be a non-empty subset of {known}")
|
|
148
|
+
#: Protocol revisions this client may speak, newest first.
|
|
149
|
+
self.protocol_versions = tuple(v for v in known if v in wanted)
|
|
150
|
+
stateless = [v for v in self.protocol_versions if v in SUPPORTED_PROTOCOL_VERSIONS]
|
|
151
|
+
legacy = [v for v in self.protocol_versions if v in LEGACY_PROTOCOL_VERSIONS]
|
|
152
|
+
self._version = stateless[0] if stateless else LATEST_PROTOCOL_VERSION
|
|
153
|
+
self._era: _Era = (
|
|
154
|
+
"unknown" if stateless and legacy else "stateless" if stateless else "session"
|
|
155
|
+
)
|
|
156
|
+
self._negotiation = asyncio.Lock()
|
|
157
|
+
self._initialized: JSONObject = {}
|
|
158
|
+
|
|
159
|
+
async def __aenter__(self) -> Self:
|
|
160
|
+
await self.transport.start()
|
|
161
|
+
self._started = True
|
|
162
|
+
return self
|
|
163
|
+
|
|
164
|
+
async def __aexit__(self, *exc_info: object) -> None:
|
|
165
|
+
self._started = False
|
|
166
|
+
await self.transport.close()
|
|
167
|
+
|
|
168
|
+
# --- Low-level request API ----------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
def _meta(self, extra: JSONObject | None = None) -> JSONObject:
|
|
171
|
+
meta: JSONObject = {
|
|
172
|
+
"io.modelcontextprotocol/protocolVersion": self._version,
|
|
173
|
+
"io.modelcontextprotocol/clientInfo": msgspec.to_builtins(self.info),
|
|
174
|
+
"io.modelcontextprotocol/clientCapabilities": msgspec.to_builtins(self.capabilities),
|
|
175
|
+
}
|
|
176
|
+
return meta | (extra or {})
|
|
177
|
+
|
|
178
|
+
def _headers(self, method: str, params: JSONObject) -> dict[str, str]:
|
|
179
|
+
if not self.transport.uses_http_headers:
|
|
180
|
+
return {}
|
|
181
|
+
headers: dict[str, str] = {}
|
|
182
|
+
if (field := _NAME_PARAM.get(method)) is not None and isinstance(params.get(field), str):
|
|
183
|
+
headers["Mcp-Name"] = encode_value(params[field])
|
|
184
|
+
if method == "tools/call" and (tool := self._tools.get(params.get("name", ""))) is not None:
|
|
185
|
+
for param in header_params(tool.input_schema):
|
|
186
|
+
value = param.lookup(params.get("arguments"))
|
|
187
|
+
if isinstance(value, str | int | bool):
|
|
188
|
+
headers[param.header] = encode_value(value)
|
|
189
|
+
return headers
|
|
190
|
+
|
|
191
|
+
async def request(
|
|
192
|
+
self,
|
|
193
|
+
method: str,
|
|
194
|
+
params: JSONObject | None = None,
|
|
195
|
+
*,
|
|
196
|
+
timeout: float | None = None,
|
|
197
|
+
progress: ProgressHandler | None = None,
|
|
198
|
+
) -> JSONObject:
|
|
199
|
+
"""Send a request, completing any input rounds, and return the raw result.
|
|
200
|
+
|
|
201
|
+
``timeout`` applies to each round trip; ``None`` uses the client's default.
|
|
202
|
+
"""
|
|
203
|
+
if not self._started:
|
|
204
|
+
raise RuntimeError("use the client as an async context manager first")
|
|
205
|
+
params = dict(params or {})
|
|
206
|
+
timeout = timeout if timeout is not None else self.timeout
|
|
207
|
+
await self._negotiate()
|
|
208
|
+
for _ in range(self.max_input_rounds + 1):
|
|
209
|
+
result = await self._round_trip(method, params, timeout, progress)
|
|
210
|
+
kind = result.get("resultType", "complete")
|
|
211
|
+
if kind == "complete":
|
|
212
|
+
return result
|
|
213
|
+
if kind != "input_required" or method not in _INPUT_METHODS:
|
|
214
|
+
raise ProtocolViolationError(f"unexpected resultType {kind!r} for {method}")
|
|
215
|
+
try:
|
|
216
|
+
interim = msgspec.convert(result, InputRequiredResult)
|
|
217
|
+
except (msgspec.ValidationError, ValueError) as exc:
|
|
218
|
+
raise ProtocolViolationError(f"malformed InputRequiredResult: {exc}") from None
|
|
219
|
+
params.pop("inputResponses", None)
|
|
220
|
+
params.pop("requestState", None)
|
|
221
|
+
if interim.input_requests is not None:
|
|
222
|
+
params["inputResponses"] = await self._fulfil(interim)
|
|
223
|
+
if interim.request_state is not None:
|
|
224
|
+
params["requestState"] = interim.request_state
|
|
225
|
+
raise MCPError(-32603, f"{method} still needs input after {self.max_input_rounds} rounds")
|
|
226
|
+
|
|
227
|
+
async def _fulfil(self, interim: InputRequiredResult) -> JSONObject:
|
|
228
|
+
responses: JSONObject = {}
|
|
229
|
+
for key, request in (interim.input_requests or {}).items():
|
|
230
|
+
responses[key] = await self._answer(request.method, request.params)
|
|
231
|
+
return responses
|
|
232
|
+
|
|
233
|
+
async def _answer(self, method: str, params: JSONObject) -> JSONObject:
|
|
234
|
+
"""Answer one server request for user input."""
|
|
235
|
+
if method != "elicitation/create" or self._elicitation is None:
|
|
236
|
+
raise ProtocolViolationError(f"server asked for undeclared capability {method!r}")
|
|
237
|
+
try:
|
|
238
|
+
elicit = msgspec.convert(params, ElicitRequest)
|
|
239
|
+
except (msgspec.ValidationError, ValueError) as exc:
|
|
240
|
+
raise ProtocolViolationError(f"malformed elicitation request: {exc}") from None
|
|
241
|
+
cap = self.capabilities.elicitation
|
|
242
|
+
if cap is None or (cap.url if elicit.mode == "url" else cap.form) is None:
|
|
243
|
+
raise ProtocolViolationError(f"server used unsupported {elicit.mode} mode elicitation")
|
|
244
|
+
answer = self._elicitation(elicit)
|
|
245
|
+
if inspect.isawaitable(answer):
|
|
246
|
+
answer = await answer
|
|
247
|
+
if answer.action == "accept" and elicit.requested_schema is not None:
|
|
248
|
+
try:
|
|
249
|
+
errors = Validator(elicit.requested_schema).errors(answer.content or {})
|
|
250
|
+
except SchemaError as exc:
|
|
251
|
+
raise ProtocolViolationError(f"server sent an invalid schema: {exc}") from None
|
|
252
|
+
if errors:
|
|
253
|
+
raise ValueError(f"elicitation answer does not match the schema: {errors}")
|
|
254
|
+
result: JSONObject = msgspec.to_builtins(answer)
|
|
255
|
+
return result
|
|
256
|
+
|
|
257
|
+
async def _round_trip(
|
|
258
|
+
self,
|
|
259
|
+
method: str,
|
|
260
|
+
params: JSONObject,
|
|
261
|
+
timeout: float | None,
|
|
262
|
+
progress: ProgressHandler | None,
|
|
263
|
+
) -> JSONObject:
|
|
264
|
+
try:
|
|
265
|
+
return await self._exchange(method, params, timeout, progress)
|
|
266
|
+
except UnsupportedVersionError as exc:
|
|
267
|
+
choices = [v for v in self.protocol_versions if v in SUPPORTED_PROTOCOL_VERSIONS]
|
|
268
|
+
version = next((v for v in choices if v in exc.supported), None)
|
|
269
|
+
if version is None or self._era == "session":
|
|
270
|
+
raise
|
|
271
|
+
self._version = version # retried once; a second rejection propagates
|
|
272
|
+
return await self._exchange(method, params, timeout, progress)
|
|
273
|
+
|
|
274
|
+
async def _exchange(
|
|
275
|
+
self,
|
|
276
|
+
method: str,
|
|
277
|
+
params: JSONObject,
|
|
278
|
+
timeout: float | None,
|
|
279
|
+
progress: ProgressHandler | None,
|
|
280
|
+
) -> JSONObject:
|
|
281
|
+
request_id = next(self._ids)
|
|
282
|
+
extra = {"progressToken": request_id} if progress is not None else None
|
|
283
|
+
headers = self._headers(method, params)
|
|
284
|
+
if self._era != "session":
|
|
285
|
+
request = jsonrpc.Request(request_id, method, params | {"_meta": self._meta(extra)})
|
|
286
|
+
else:
|
|
287
|
+
request = jsonrpc.Request(
|
|
288
|
+
request_id, method, params | ({"_meta": extra} if extra is not None else {})
|
|
289
|
+
)
|
|
290
|
+
if method != "initialize":
|
|
291
|
+
headers["MCP-Protocol-Version"] = self._version
|
|
292
|
+
try:
|
|
293
|
+
async with asyncio.timeout(timeout):
|
|
294
|
+
async with self.transport.send(request, headers) as stream:
|
|
295
|
+
async for message in stream:
|
|
296
|
+
if isinstance(message, jsonrpc.Response):
|
|
297
|
+
if message.error is not None:
|
|
298
|
+
raise message.error
|
|
299
|
+
assert message.result is not None
|
|
300
|
+
return message.result
|
|
301
|
+
if message.method == "notifications/progress" and progress is not None:
|
|
302
|
+
p = message.params
|
|
303
|
+
outcome = progress(
|
|
304
|
+
p.get("progress", 0), p.get("total"), p.get("message")
|
|
305
|
+
)
|
|
306
|
+
if inspect.isawaitable(outcome):
|
|
307
|
+
await outcome
|
|
308
|
+
except TimeoutError:
|
|
309
|
+
raise RequestTimeoutError(f"{method} timed out after {timeout} seconds") from None
|
|
310
|
+
raise ConnectionClosedError(f"no response to {method}")
|
|
311
|
+
|
|
312
|
+
# --- Protocol negotiation -----------------------------------------------------------
|
|
313
|
+
|
|
314
|
+
async def _negotiate(self) -> None:
|
|
315
|
+
"""Settle the server's protocol era once: stateless, or an initialize session."""
|
|
316
|
+
if self._era == "stateless" or self._initialized:
|
|
317
|
+
return
|
|
318
|
+
async with self._negotiation:
|
|
319
|
+
if self._era == "unknown":
|
|
320
|
+
self._era = await self._probe()
|
|
321
|
+
if self._era == "session" and not self._initialized:
|
|
322
|
+
await self._initialize()
|
|
323
|
+
|
|
324
|
+
async def _probe(self) -> _Era:
|
|
325
|
+
"""Ask for ``server/discover``; a server that does not understand it needs a session."""
|
|
326
|
+
timeout = _PROBE_TIMEOUT if self.timeout is None else min(self.timeout, _PROBE_TIMEOUT)
|
|
327
|
+
try:
|
|
328
|
+
await self._round_trip("server/discover", {}, timeout, None)
|
|
329
|
+
except UnsupportedVersionError as exc:
|
|
330
|
+
legacy = any(v in LEGACY_PROTOCOL_VERSIONS for v in exc.supported)
|
|
331
|
+
return "session" if legacy else "stateless"
|
|
332
|
+
except MCPError as exc:
|
|
333
|
+
stateless = exc.code in (HEADER_MISMATCH, MISSING_REQUIRED_CLIENT_CAPABILITY)
|
|
334
|
+
return "stateless" if stateless else "session"
|
|
335
|
+
except asyncio.CancelledError:
|
|
336
|
+
raise
|
|
337
|
+
except Exception: # an older server may answer with anything: fall back
|
|
338
|
+
return "session"
|
|
339
|
+
return "stateless"
|
|
340
|
+
|
|
341
|
+
async def _initialize(self) -> None:
|
|
342
|
+
versions = [v for v in self.protocol_versions if v in LEGACY_PROTOCOL_VERSIONS]
|
|
343
|
+
transport = self.transport
|
|
344
|
+
if not versions:
|
|
345
|
+
raise MCPError(
|
|
346
|
+
INTERNAL_ERROR,
|
|
347
|
+
"the server does not speak the client's protocol versions "
|
|
348
|
+
f"({', '.join(self.protocol_versions)})",
|
|
349
|
+
)
|
|
350
|
+
if not isinstance(transport, SessionTransport):
|
|
351
|
+
raise MCPError(
|
|
352
|
+
INTERNAL_ERROR,
|
|
353
|
+
f"the server needs protocol {versions[0]}, which "
|
|
354
|
+
f"{type(transport).__name__} cannot carry (it is not a SessionTransport)",
|
|
355
|
+
)
|
|
356
|
+
self._version = versions[0]
|
|
357
|
+
params: JSONObject = {
|
|
358
|
+
"protocolVersion": versions[0],
|
|
359
|
+
"capabilities": msgspec.to_builtins(self.capabilities),
|
|
360
|
+
"clientInfo": msgspec.to_builtins(self.info),
|
|
361
|
+
}
|
|
362
|
+
result = await self._exchange("initialize", params, self.timeout, None)
|
|
363
|
+
version = result.get("protocolVersion")
|
|
364
|
+
if not isinstance(version, str) or version not in versions:
|
|
365
|
+
raise UnsupportedVersionError(
|
|
366
|
+
f"the server offered protocol version {version!r}",
|
|
367
|
+
{"supported": [version], "requested": versions[0]},
|
|
368
|
+
)
|
|
369
|
+
self._version = version
|
|
370
|
+
self._initialized = result
|
|
371
|
+
transport.request_handler = self._serve_request
|
|
372
|
+
await transport.post(
|
|
373
|
+
jsonrpc.Notification("notifications/initialized"),
|
|
374
|
+
{"MCP-Protocol-Version": self._version},
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
async def _serve_request(self, request: jsonrpc.Request) -> jsonrpc.Response:
|
|
378
|
+
"""Answer a request from an initialize-based server (elicitation, ping)."""
|
|
379
|
+
try:
|
|
380
|
+
if request.method == "ping":
|
|
381
|
+
return jsonrpc.Response(request.id, result={})
|
|
382
|
+
if request.method != "elicitation/create":
|
|
383
|
+
raise MCPError(METHOD_NOT_FOUND, f"Method not found: {request.method}")
|
|
384
|
+
result = await self._answer(request.method, request.params)
|
|
385
|
+
return jsonrpc.Response(request.id, result=result)
|
|
386
|
+
except MCPError as exc:
|
|
387
|
+
return jsonrpc.Response(request.id, error=exc)
|
|
388
|
+
except Exception as exc:
|
|
389
|
+
return jsonrpc.Response(request.id, error=MCPError(INTERNAL_ERROR, str(exc)))
|
|
390
|
+
|
|
391
|
+
# --- Server discovery ---------------------------------------------------------------
|
|
392
|
+
|
|
393
|
+
async def discover(self) -> DiscoverResult:
|
|
394
|
+
"""Fetch the server's supported versions, capabilities and identity."""
|
|
395
|
+
await self._negotiate()
|
|
396
|
+
if self._era == "session":
|
|
397
|
+
result = self._initialized
|
|
398
|
+
return DiscoverResult(
|
|
399
|
+
supported_versions=[self._version],
|
|
400
|
+
capabilities=_convert(result.get("capabilities") or {}, ServerCapabilities),
|
|
401
|
+
instructions=result.get("instructions"),
|
|
402
|
+
)
|
|
403
|
+
return _convert(await self.request("server/discover"), DiscoverResult)
|
|
404
|
+
|
|
405
|
+
# --- Tools --------------------------------------------------------------------------
|
|
406
|
+
|
|
407
|
+
async def list_tools(self) -> list[Tool]:
|
|
408
|
+
"""List all tools, following pagination."""
|
|
409
|
+
tools: list[Tool] = []
|
|
410
|
+
async for page in self._pages("tools/list", ListToolsResult):
|
|
411
|
+
tools.extend(page.tools)
|
|
412
|
+
if self.transport.uses_http_headers:
|
|
413
|
+
tools = [tool for tool in tools if _valid_header_tool(tool)]
|
|
414
|
+
self._tools = {tool.name: tool for tool in tools}
|
|
415
|
+
return tools
|
|
416
|
+
|
|
417
|
+
async def call_tool(
|
|
418
|
+
self,
|
|
419
|
+
name: str,
|
|
420
|
+
arguments: JSONObject | None = None,
|
|
421
|
+
*,
|
|
422
|
+
timeout: float | None = None,
|
|
423
|
+
progress: ProgressHandler | None = None,
|
|
424
|
+
) -> CallToolResult:
|
|
425
|
+
"""Call a tool. Tool failures come back with ``is_error=True``, not as exceptions."""
|
|
426
|
+
params: JSONObject = {"name": name, "arguments": arguments or {}}
|
|
427
|
+
try:
|
|
428
|
+
raw = await self.request("tools/call", params, timeout=timeout, progress=progress)
|
|
429
|
+
except MCPError as exc:
|
|
430
|
+
if exc.code != HEADER_MISMATCH or not self.transport.uses_http_headers:
|
|
431
|
+
raise
|
|
432
|
+
await self.list_tools() # the tool's x-mcp-header annotations may have changed
|
|
433
|
+
raw = await self.request("tools/call", params, timeout=timeout, progress=progress)
|
|
434
|
+
result = _convert(raw, CallToolResult)
|
|
435
|
+
tool = self._tools.get(name)
|
|
436
|
+
if tool is not None and tool.output_schema is not None and not result.is_error:
|
|
437
|
+
errors = Validator(tool.output_schema).errors(result.structured_content)
|
|
438
|
+
if errors:
|
|
439
|
+
raise ProtocolViolationError(
|
|
440
|
+
f"tool {name!r} returned invalid structured content: {errors}"
|
|
441
|
+
)
|
|
442
|
+
return result
|
|
443
|
+
|
|
444
|
+
# --- Resources ----------------------------------------------------------------------
|
|
445
|
+
|
|
446
|
+
async def list_resources(self) -> list[Resource]:
|
|
447
|
+
"""List all resources, following pagination."""
|
|
448
|
+
return [
|
|
449
|
+
r
|
|
450
|
+
async for page in self._pages("resources/list", ListResourcesResult)
|
|
451
|
+
for r in page.resources
|
|
452
|
+
]
|
|
453
|
+
|
|
454
|
+
async def list_resource_templates(self) -> list[ResourceTemplate]:
|
|
455
|
+
"""List all resource templates, following pagination."""
|
|
456
|
+
pages = self._pages("resources/templates/list", ListResourceTemplatesResult)
|
|
457
|
+
return [t async for page in pages for t in page.resource_templates]
|
|
458
|
+
|
|
459
|
+
async def read_resource(self, uri: str, *, timeout: float | None = None) -> ReadResourceResult:
|
|
460
|
+
return _convert(
|
|
461
|
+
await self.request("resources/read", {"uri": uri}, timeout=timeout), ReadResourceResult
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
# --- Prompts ------------------------------------------------------------------------
|
|
465
|
+
|
|
466
|
+
async def list_prompts(self) -> list[Prompt]:
|
|
467
|
+
"""List all prompts, following pagination."""
|
|
468
|
+
return [
|
|
469
|
+
p async for page in self._pages("prompts/list", ListPromptsResult) for p in page.prompts
|
|
470
|
+
]
|
|
471
|
+
|
|
472
|
+
async def get_prompt(
|
|
473
|
+
self,
|
|
474
|
+
name: str,
|
|
475
|
+
arguments: dict[str, str] | None = None,
|
|
476
|
+
*,
|
|
477
|
+
timeout: float | None = None,
|
|
478
|
+
) -> GetPromptResult:
|
|
479
|
+
params: JSONObject = {"name": name, "arguments": arguments or {}}
|
|
480
|
+
return _convert(await self.request("prompts/get", params, timeout=timeout), GetPromptResult)
|
|
481
|
+
|
|
482
|
+
# --- Completion ---------------------------------------------------------------------
|
|
483
|
+
|
|
484
|
+
async def complete(
|
|
485
|
+
self,
|
|
486
|
+
ref: PromptReference | ResourceTemplateReference,
|
|
487
|
+
argument: str,
|
|
488
|
+
value: str,
|
|
489
|
+
context: dict[str, str] | None = None,
|
|
490
|
+
) -> Completion:
|
|
491
|
+
"""Ask for completions of a prompt or resource template argument."""
|
|
492
|
+
params: JSONObject = {
|
|
493
|
+
"ref": msgspec.to_builtins(ref),
|
|
494
|
+
"argument": {"name": argument, "value": value},
|
|
495
|
+
}
|
|
496
|
+
if context is not None:
|
|
497
|
+
params["context"] = {"arguments": context}
|
|
498
|
+
return _convert(
|
|
499
|
+
await self.request("completion/complete", params), CompleteResult
|
|
500
|
+
).completion
|
|
501
|
+
|
|
502
|
+
# --- Subscriptions ------------------------------------------------------------------
|
|
503
|
+
|
|
504
|
+
@asynccontextmanager
|
|
505
|
+
async def listen(
|
|
506
|
+
self,
|
|
507
|
+
*,
|
|
508
|
+
tools: bool = False,
|
|
509
|
+
prompts: bool = False,
|
|
510
|
+
resources: bool = False,
|
|
511
|
+
resource_uris: Iterable[str] = (),
|
|
512
|
+
) -> AsyncGenerator[Subscription]:
|
|
513
|
+
"""Open a change-notification stream::
|
|
514
|
+
|
|
515
|
+
async with client.listen(tools=True) as subscription:
|
|
516
|
+
async for notification in subscription:
|
|
517
|
+
...
|
|
518
|
+
|
|
519
|
+
The stream ends when the context exits or the server closes it.
|
|
520
|
+
"""
|
|
521
|
+
requested = SubscriptionFilter(
|
|
522
|
+
tools_list_changed=tools or None,
|
|
523
|
+
prompts_list_changed=prompts or None,
|
|
524
|
+
resources_list_changed=resources or None,
|
|
525
|
+
resource_subscriptions=list(resource_uris) or None,
|
|
526
|
+
)
|
|
527
|
+
await self._negotiate()
|
|
528
|
+
if self._era == "session":
|
|
529
|
+
raise MCPError(METHOD_NOT_FOUND, "subscriptions/listen needs protocol 2026-07-28")
|
|
530
|
+
request_id = next(self._ids)
|
|
531
|
+
params = {"notifications": msgspec.to_builtins(requested), "_meta": self._meta()}
|
|
532
|
+
request = jsonrpc.Request(request_id, "subscriptions/listen", params)
|
|
533
|
+
async with self.transport.send(request, {}) as stream:
|
|
534
|
+
iterator = aiter(stream)
|
|
535
|
+
try:
|
|
536
|
+
async with asyncio.timeout(self.timeout):
|
|
537
|
+
first = await anext(iterator)
|
|
538
|
+
except StopAsyncIteration:
|
|
539
|
+
raise ConnectionClosedError("subscription closed before acknowledgement") from None
|
|
540
|
+
if isinstance(first, jsonrpc.Response):
|
|
541
|
+
if first.error is not None:
|
|
542
|
+
raise first.error
|
|
543
|
+
raise ProtocolViolationError("subscription ended before acknowledgement")
|
|
544
|
+
if first.method != "notifications/subscriptions/acknowledged":
|
|
545
|
+
raise ProtocolViolationError(f"expected acknowledgement, got {first.method}")
|
|
546
|
+
acknowledged = _convert(first.params.get("notifications") or {}, SubscriptionFilter)
|
|
547
|
+
|
|
548
|
+
async def notifications() -> AsyncIterator[Notification]:
|
|
549
|
+
async for message in iterator:
|
|
550
|
+
if isinstance(message, jsonrpc.Response):
|
|
551
|
+
if message.error is not None:
|
|
552
|
+
raise message.error
|
|
553
|
+
return
|
|
554
|
+
if message.method == "notifications/cancelled":
|
|
555
|
+
continue # the server is closing; its response follows
|
|
556
|
+
params = {k: v for k, v in message.params.items() if k != "_meta"}
|
|
557
|
+
yield Notification(method=message.method, params=params)
|
|
558
|
+
|
|
559
|
+
yield Subscription(acknowledged, notifications())
|
|
560
|
+
|
|
561
|
+
# --- Helpers ------------------------------------------------------------------------
|
|
562
|
+
|
|
563
|
+
async def _pages[
|
|
564
|
+
R: ListToolsResult | ListResourcesResult | ListResourceTemplatesResult | ListPromptsResult
|
|
565
|
+
](self, method: str, result_type: type[R]) -> AsyncIterator[R]:
|
|
566
|
+
cursor: str | None = None
|
|
567
|
+
seen: set[str] = set()
|
|
568
|
+
while True:
|
|
569
|
+
page = _convert(
|
|
570
|
+
await self.request(method, {"cursor": cursor} if cursor is not None else {}),
|
|
571
|
+
result_type,
|
|
572
|
+
)
|
|
573
|
+
yield page
|
|
574
|
+
cursor = page.next_cursor
|
|
575
|
+
if cursor is None or cursor in seen:
|
|
576
|
+
return
|
|
577
|
+
seen.add(cursor)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _convert[T](raw: Any, tp: type[T]) -> T:
|
|
581
|
+
try:
|
|
582
|
+
return msgspec.convert(raw, tp)
|
|
583
|
+
except (msgspec.ValidationError, ValueError) as exc:
|
|
584
|
+
raise ProtocolViolationError(f"malformed {tp.__name__}: {exc}") from None
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _valid_header_tool(tool: Tool) -> bool:
|
|
588
|
+
try:
|
|
589
|
+
header_params(tool.input_schema)
|
|
590
|
+
except ValueError as exc:
|
|
591
|
+
logger.warning("ignoring tool %r with invalid x-mcp-header: %s", tool.name, exc)
|
|
592
|
+
return False
|
|
593
|
+
return True
|