incur-cli 0.10.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.
incur/_mcp.py ADDED
@@ -0,0 +1,872 @@
1
+ """The MCP server: commands as tools over stdio and streamable HTTP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import re
8
+ import typing
9
+ import uuid
10
+ from collections.abc import Awaitable, Callable
11
+ from dataclasses import dataclass, field, replace
12
+ from typing import Any, Literal, TextIO
13
+
14
+ from . import _js
15
+ from ._command import Command, Middleware, MiddlewareContext, Stream, ToolMeta, execute
16
+ from ._errors import Error, format_cta, unknown
17
+ from ._http import Request, Response
18
+ from ._js import Json
19
+ from ._model import build, to_json
20
+ from ._parser import check, parse_env
21
+ from ._schema import Field, Type, json_schema, object_type, validate
22
+ from ._tree import Entry, Group, Spec
23
+
24
+ #: The protocol versions the server speaks, newest first.
25
+ PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07")
26
+
27
+
28
+ @dataclass
29
+ class ToolAnnotations:
30
+ """MCP tool annotations: hints that describe a tool's behavior to clients."""
31
+
32
+ title: str | None = None
33
+ """A human-readable title."""
34
+ read_only_hint: bool | None = None
35
+ """Whether the tool leaves its environment unchanged."""
36
+ destructive_hint: bool | None = None
37
+ """Whether the tool may perform destructive updates."""
38
+ idempotent_hint: bool | None = None
39
+ """Whether repeated calls with the same arguments have no additional effect."""
40
+ open_world_hint: bool | None = None
41
+ """Whether the tool interacts with an open world of external entities."""
42
+
43
+ def to_json(self) -> dict[str, Json]:
44
+ """Returns the annotations as MCP spells them."""
45
+ names = {
46
+ "title": self.title,
47
+ "readOnlyHint": self.read_only_hint,
48
+ "destructiveHint": self.destructive_hint,
49
+ "idempotentHint": self.idempotent_hint,
50
+ "openWorldHint": self.open_world_hint,
51
+ }
52
+ return {key: value for key, value in names.items() if value is not None}
53
+
54
+
55
+ @dataclass
56
+ class McpTool:
57
+ """How a command appears as an MCP tool."""
58
+
59
+ name: str | None = None
60
+ """The tool name. Defaults to the command path joined with `_`."""
61
+ description: str | None = None
62
+ """The tool description. Defaults to the command's."""
63
+ annotations: ToolAnnotations | None = None
64
+ """Behavior hints for clients."""
65
+ instructions: str | None = None
66
+ """Usage instructions, sent as the tool's `_meta.instructions`."""
67
+
68
+ def meta(self) -> ToolMeta:
69
+ """Returns the tool settings as commands store them."""
70
+ annotations = self.annotations.to_json() if self.annotations else None
71
+ return ToolMeta(self.name, self.description, annotations, self.instructions)
72
+
73
+
74
+ @dataclass
75
+ class ToolFilter:
76
+ """Which commands MCP clients see, and how they discover them."""
77
+
78
+ discovery: Literal["direct", "progressive"] = "progressive"
79
+ """`progressive` exposes search, inspect, and call tools instead of every command schema;
80
+ `direct` lists every command as a tool."""
81
+ include: list[str] | None = None
82
+ """Tool name patterns to expose, where `*` matches any characters. Defaults to all."""
83
+ exclude: list[str] = field(default_factory=list[str])
84
+ """Tool name patterns to hide. Excludes win over includes."""
85
+
86
+
87
+ @dataclass
88
+ class McpOptions:
89
+ """MCP server and registration settings."""
90
+
91
+ agents: list[str] = field(default_factory=list[str])
92
+ """Agents that `mcp add` targets by default, such as `claude-code` or `cursor`."""
93
+ command: str | None = None
94
+ """The command agents run to start the server. Detected when omitted."""
95
+ instructions: str | None = None
96
+ """Instructions describing how to use the server."""
97
+ name: str | None = None
98
+ """The server and registration name. Defaults to the CLI name."""
99
+ stateless: bool = True
100
+ """Whether MCP over HTTP runs without sessions."""
101
+ title: str | None = None
102
+ """A human-readable server title."""
103
+ tools: ToolFilter | None = None
104
+ """Which commands clients see."""
105
+
106
+
107
+ @dataclass
108
+ class Tool:
109
+ """A command exposed as a tool."""
110
+
111
+ name: str
112
+ description: str | None
113
+ command: Command
114
+ middleware: list[Middleware]
115
+ details: dict[str, Json]
116
+ """The input schema `get_tool_details` reports."""
117
+ output: dict[str, Json] | None
118
+ annotations: dict[str, Json] | None
119
+ instructions: str | None
120
+ inputs: Type
121
+ """Args, options, and globals merged, as direct tools validate input."""
122
+
123
+
124
+ def collect(spec: Spec, filter_: ToolFilter | None) -> list[Tool]:
125
+ """Collects the tools of a CLI, filtered and sorted by name.
126
+
127
+ Raises:
128
+ ValueError: When two tools share a name.
129
+ """
130
+ tools = _entries(spec.commands, [], [], spec.globals)
131
+ if filter_ is not None:
132
+ includes = [_pattern(p) for p in filter_.include or []]
133
+ excludes = [_pattern(p) for p in filter_.exclude]
134
+ tools = [
135
+ t
136
+ for t in tools
137
+ if not any(p.match(t.name) for p in excludes)
138
+ and (not includes or any(p.match(t.name) for p in includes))
139
+ ]
140
+ seen: set[str] = set()
141
+ for tool in tools:
142
+ if tool.name in seen:
143
+ raise ValueError(f"Duplicate MCP tool name: {tool.name}")
144
+ seen.add(tool.name)
145
+ return sorted(tools, key=lambda t: _js.locale_key(t.name))
146
+
147
+
148
+ def _pattern(pattern: str) -> re.Pattern[str]:
149
+ return re.compile("^" + ".*".join(re.escape(part) for part in pattern.split("*")) + "$")
150
+
151
+
152
+ def _entries(
153
+ commands: dict[str, Entry],
154
+ prefix: list[str],
155
+ middleware: list[Middleware],
156
+ globals_: Type | None,
157
+ ) -> list[Tool]:
158
+ out: list[Tool] = []
159
+ for name, entry in commands.items():
160
+ path = [*prefix, name]
161
+ if isinstance(entry, Group):
162
+ if not entry.mcp:
163
+ continue
164
+ chain = [*middleware, *entry.middleware]
165
+ if entry.root is not None and entry.root.mcp_enabled:
166
+ out.append(_tool(entry.root, path, chain, globals_))
167
+ out += _entries(entry.commands, path, chain, globals_)
168
+ elif isinstance(entry, Command) and entry.mcp_enabled:
169
+ out.append(_tool(entry, path, middleware, globals_))
170
+ return out
171
+
172
+
173
+ def _tool(
174
+ command: Command, path: list[str], middleware: list[Middleware], globals_: Type | None
175
+ ) -> Tool:
176
+ meta = command.mcp or ToolMeta()
177
+ properties: dict[str, Json] = {}
178
+ required: list[Json] = []
179
+ merged: dict[str, Field] = {}
180
+ for schema in (command.args, command.options, globals_):
181
+ if schema is None:
182
+ continue
183
+ out = json_schema(schema)
184
+ properties.update(_js.as_object(out["properties"]))
185
+ required += _js.as_list(out.get("required", []))
186
+ for f in schema.fields:
187
+ merged[f.name] = f
188
+ details: dict[str, Json] = {"type": "object", "properties": properties}
189
+ if required:
190
+ details["required"] = required
191
+ output = json_schema(command.output) if command.output is not None else None
192
+ return Tool(
193
+ name=meta.name or "_".join(path),
194
+ description=meta.description or command.description,
195
+ command=command,
196
+ middleware=middleware,
197
+ details=details,
198
+ output=output if output is not None and output.get("type") == "object" else None,
199
+ annotations=meta.annotations,
200
+ instructions=meta.instructions,
201
+ inputs=object_type(list(merged.values())),
202
+ )
203
+
204
+
205
+ #: Sends a progress message for a streamed chunk.
206
+ Progress = Callable[[Json], Awaitable[None]]
207
+
208
+
209
+ async def call_tool(
210
+ spec: Spec,
211
+ tool: Tool,
212
+ params: dict[str, Json],
213
+ *,
214
+ parsed: bool = False,
215
+ progress: Progress | None = None,
216
+ request: Request | None = None,
217
+ env: dict[str, str] | None = None,
218
+ ) -> dict[str, Json]:
219
+ """Runs a tool's command with flat parameters and returns a tool result."""
220
+ command = tool.command
221
+ source = os.environ if env is None else env
222
+ name = spec.name
223
+ globals_: dict[str, Json] = {}
224
+ inputs = params
225
+ if spec.globals is not None:
226
+ arg_keys = {f.name for f in command.args.fields} if command.args else set[str]()
227
+ global_keys = {f.name for f in spec.globals.fields}
228
+ raw: dict[str, Json] = {}
229
+ inputs = {}
230
+ for key, value in params.items():
231
+ if key in global_keys:
232
+ raw[key] = value
233
+ if key not in global_keys or key in arg_keys:
234
+ inputs[key] = value
235
+ try:
236
+ globals_ = raw if parsed else check(spec.globals, raw)
237
+ except Error as error:
238
+ body: dict[str, Json] = {"code": error.code, "message": error.message}
239
+ body["fieldErrors"] = [f.to_json() for f in error.field_errors or []]
240
+ return {"content": [_text(_js.stringify(body))], "isError": True}
241
+
242
+ context = spec_context(spec, tool.name, globals_, request)
243
+
244
+ def parse() -> tuple[dict[str, Json], dict[str, Json], dict[str, Json]]:
245
+ arg_keys = {f.name for f in command.args.fields} if command.args else set[str]()
246
+ args = {k: v for k, v in inputs.items() if k in arg_keys}
247
+ options = {k: v for k, v in inputs.items() if k not in arg_keys}
248
+ return (
249
+ check(command.args, args) if command.args else {},
250
+ check(command.options, options) if command.options else {},
251
+ parse_env(command.env, source.get) if command.env else {},
252
+ )
253
+
254
+ streamed: list[dict[str, Json]] = []
255
+
256
+ async def sink(chunks: Stream) -> None:
257
+ values: list[Json] = []
258
+ try:
259
+ async for chunk in chunks:
260
+ value = to_json(chunk)
261
+ values.append(value)
262
+ if progress is not None:
263
+ await progress(value)
264
+ except Error as error:
265
+ streamed.append(_failure(error, name))
266
+ return
267
+ except Exception as error:
268
+ streamed.append(_failure(unknown(str(error)), name))
269
+ return
270
+ final = chunks.final
271
+ cta = format_cta(name, getattr(final, "cta", None))
272
+ text = _js.stringify(values)
273
+ result: dict[str, Json] = {}
274
+ if cta is not None:
275
+ result["_meta"] = {"cta": cta.to_json()}
276
+ result["content"] = [_text(f"{text}\n\n{cta.text()}" if cta else text)]
277
+ streamed.append(result)
278
+
279
+ chain = [*spec.middleware, *tool.middleware, *command.middleware]
280
+ try:
281
+ if spec.env is not None:
282
+ context.env = build(spec.env, parse_env(spec.env, source.get))
283
+ except Error as error:
284
+ return _failure(error, name)
285
+ outcome = await execute(command, context, chain, parse, sink)
286
+ if outcome is None:
287
+ return streamed[0]
288
+ if isinstance(outcome, Error):
289
+ return _failure(outcome, name)
290
+ data = outcome.data
291
+ cta = format_cta(name, outcome.cta)
292
+ text = _js.stringify(data)
293
+ result: dict[str, Json] = {}
294
+ if cta is not None:
295
+ result["_meta"] = {"cta": cta.to_json()}
296
+ result["content"] = [_text(f"{text}\n\n{cta.text()}" if cta else text)]
297
+ if data is not None and tool.output is not None:
298
+ result["structuredContent"] = data
299
+ return result
300
+
301
+
302
+ def spec_context(spec: Spec, path: str, globals_: dict[str, Json], request: Request | None) -> Any:
303
+ """Creates the middleware context of an agent run over MCP or HTTP."""
304
+ return MiddlewareContext[Any, Any, Any](
305
+ agent=True,
306
+ command=path,
307
+ display_name=spec.name,
308
+ env=None,
309
+ format="json",
310
+ format_explicit=True,
311
+ globals=build(spec.globals, globals_) if spec.globals else None,
312
+ name=spec.name,
313
+ var=spec.vars_instance(),
314
+ version=spec.version,
315
+ request=request,
316
+ )
317
+
318
+
319
+ def _text(text: str) -> dict[str, Json]:
320
+ return {"type": "text", "text": text}
321
+
322
+
323
+ def _failure(error: Error, name: str) -> dict[str, Json]:
324
+ """Renders a failed command as a tool error."""
325
+ cta = format_cta(name, error.cta)
326
+ text = _js.stringify(error.to_json()) if error.field_errors else error.message
327
+ if error.hint:
328
+ text += f"\nHint: {error.hint}"
329
+ if cta is not None:
330
+ text += f"\n\n{cta.text()}"
331
+ meta: dict[str, Json] = {}
332
+ if cta is not None:
333
+ meta["cta"] = cta.to_json()
334
+ details: dict[str, Json] = {"code": error.code}
335
+ if error.exit_code is not None:
336
+ details["exitCode"] = error.exit_code
337
+ if error.retryable is not None:
338
+ details["retryable"] = error.retryable
339
+ meta["error"] = details
340
+ return {"_meta": meta, "content": [_text(text)], "isError": True}
341
+
342
+
343
+ def _tool_result(value: Json) -> dict[str, Json]:
344
+ return {"content": [_text(_js.stringify(value))]}
345
+
346
+
347
+ def _tool_error(message: str) -> dict[str, Json]:
348
+ return {"content": [_text(_js.stringify({"error": message}))], "isError": True}
349
+
350
+
351
+ def _search(tools: list[Tool], query: str) -> list[Tool]:
352
+ normalized = _normalize_search(query)
353
+ terms = [t for t in normalized.split(" ") if t]
354
+ scored = [(tool, _score(tool, normalized, terms)) for tool in tools]
355
+ matches = [(tool, score) for tool, score in scored if score > 0]
356
+ matches.sort(key=lambda m: (-m[1], _js.locale_key(m[0].name)))
357
+ return [tool for tool, _ in matches]
358
+
359
+
360
+ def _score(tool: Tool, query: str, terms: list[str]) -> int:
361
+ name = _normalize_search(tool.name)
362
+ description = _normalize_search(tool.description or "")
363
+ if name == query:
364
+ return 1000
365
+ score = 100 if name.startswith(query) else 50 if query in name else 0
366
+ for term in terms:
367
+ if term in name.split(" "):
368
+ score += 20
369
+ elif term in name:
370
+ score += 10
371
+ if term in description:
372
+ score += 2
373
+ return score
374
+
375
+
376
+ def _normalize_search(value: str) -> str:
377
+ return re.sub(r"[^a-z0-9]+", " ", value.lower(), flags=re.ASCII).strip(" ")
378
+
379
+
380
+ def _int(name: str, description: str, default: int, low: int, high: int | None = None) -> Field:
381
+ return Field(
382
+ name,
383
+ Type("integer", description=description, default=default, min=low, max=high),
384
+ )
385
+
386
+
387
+ _SEARCH_INPUT = object_type(
388
+ [
389
+ _int("limit", "Maximum matches.", 5, 1, 20),
390
+ _int("offset", "Matches to skip.", 0, 0),
391
+ Field(
392
+ "query",
393
+ Type("string", default="", description="Capability to find. Empty lists all tools."),
394
+ ),
395
+ ]
396
+ )
397
+ _NAME = Field("name", Type("string", min=1, description="Exact tool name."))
398
+ _DETAILS_INPUT = object_type([_NAME])
399
+ _CALL_INPUT = object_type(
400
+ [
401
+ _NAME,
402
+ Field(
403
+ "arguments",
404
+ Type("record", default={}, description="Arguments from its schema."),
405
+ ),
406
+ ]
407
+ )
408
+ _CATALOG: dict[str, Json] = {
409
+ "destructiveHint": False,
410
+ "idempotentHint": True,
411
+ "openWorldHint": False,
412
+ "readOnlyHint": True,
413
+ }
414
+ _READ: dict[str, Json] = {**_CATALOG, "openWorldHint": True}
415
+ _WRITE: dict[str, Json] = {
416
+ "destructiveHint": True,
417
+ "idempotentHint": False,
418
+ "openWorldHint": True,
419
+ "readOnlyHint": False,
420
+ }
421
+
422
+
423
+ @dataclass
424
+ class _Registered:
425
+ """A tool as the server lists and calls it."""
426
+
427
+ name: str
428
+ description: str | None
429
+ inputs: Type | None
430
+ run: Callable[[dict[str, Json], Progress | None, Request | None], Awaitable[dict[str, Json]]]
431
+ annotations: dict[str, Json] | None = None
432
+ output: dict[str, Json] | None = None
433
+ meta: dict[str, Json] | None = None
434
+
435
+
436
+ class Server:
437
+ """An MCP server answering JSON-RPC messages for a CLI's tools."""
438
+
439
+ def __init__(
440
+ self, spec: Spec, env: dict[str, str] | None = None, *, direct: bool = False
441
+ ) -> None:
442
+ self.spec = spec
443
+ options = spec.mcp or McpOptions()
444
+ filter_ = options.tools
445
+ if direct:
446
+ filter_ = replace(filter_ or ToolFilter(), discovery="direct")
447
+ self.name = options.name or spec.name
448
+ self.title = options.title
449
+ self.instructions = options.instructions
450
+ self.version = spec.version or "0.0.0"
451
+ self.env = env
452
+ self.tools = self._register(collect(spec, filter_), filter_)
453
+
454
+ def _register(self, tools: list[Tool], filter_: ToolFilter | None) -> dict[str, _Registered]:
455
+ if not tools:
456
+ return {}
457
+ if (filter_.discovery if filter_ else "progressive") == "direct":
458
+ return {tool.name: self._direct(tool) for tool in tools}
459
+ by_name = {tool.name: tool for tool in tools}
460
+ spec = self.spec
461
+
462
+ async def search(params: dict[str, Json], *_: object) -> dict[str, Json]:
463
+ matches = _search(tools, str(params["query"]))
464
+ offset = int(typing.cast("int", params["offset"]))
465
+ limit = int(typing.cast("int", params["limit"]))
466
+ page = matches[offset : offset + limit]
467
+ listed: list[Json] = []
468
+ for tool in page:
469
+ item: dict[str, Json] = {"name": tool.name}
470
+ if tool.description:
471
+ item["description"] = tool.description
472
+ if tool.annotations:
473
+ item["annotations"] = tool.annotations
474
+ listed.append(item)
475
+ out: dict[str, Json] = {"tools": listed}
476
+ if offset + len(page) < len(matches):
477
+ out["nextOffset"] = offset + len(page)
478
+ return _tool_result(out)
479
+
480
+ async def details(params: dict[str, Json], *_: object) -> dict[str, Json]:
481
+ tool = by_name.get(str(params["name"]))
482
+ if tool is None:
483
+ return _tool_error(f"Unknown tool: {params['name']}")
484
+ out: dict[str, Json] = {"name": tool.name}
485
+ if tool.description:
486
+ out["description"] = tool.description
487
+ out["inputSchema"] = tool.details
488
+ if tool.output:
489
+ out["outputSchema"] = tool.output
490
+ if tool.annotations:
491
+ out["annotations"] = tool.annotations
492
+ if tool.instructions:
493
+ out["instructions"] = tool.instructions
494
+ return _tool_result(out)
495
+
496
+ def caller(read: bool) -> Callable[..., Awaitable[dict[str, Json]]]:
497
+ async def call(
498
+ params: dict[str, Json], progress: Progress | None, request: Request | None
499
+ ) -> dict[str, Json]:
500
+ name = str(params["name"])
501
+ tool = by_name.get(name)
502
+ if tool is None:
503
+ return _tool_error(f"Unknown tool: {name}")
504
+ read_only = (tool.annotations or {}).get("readOnlyHint") is True
505
+ if read and not read_only:
506
+ return _tool_error(f"Tool is not read-only: {name}")
507
+ if not read and read_only:
508
+ return _tool_error(f"Tool is read-only: {name}")
509
+ arguments = _js.as_object(params["arguments"])
510
+ return await call_tool(
511
+ spec, tool, arguments, progress=progress, request=request, env=self.env
512
+ )
513
+
514
+ return call
515
+
516
+ registered = [
517
+ _Registered(
518
+ "search_tools",
519
+ "Search or page through available tools by capability. Returns names and "
520
+ "descriptions without loading their schemas. Inspect a result before calling it.",
521
+ _SEARCH_INPUT,
522
+ search,
523
+ _CATALOG,
524
+ ),
525
+ _Registered(
526
+ "get_tool_details",
527
+ "Inspect one tool returned by search_tools. Returns its complete input schema "
528
+ "and metadata.",
529
+ _DETAILS_INPUT,
530
+ details,
531
+ _CATALOG,
532
+ ),
533
+ _Registered(
534
+ "call_read_tool",
535
+ "Execute a tool marked read-only after inspecting its schema with "
536
+ "get_tool_details.",
537
+ _CALL_INPUT,
538
+ caller(read=True),
539
+ _READ,
540
+ ),
541
+ _Registered(
542
+ "call_write_tool",
543
+ "Execute a writable or unclassified tool after inspecting its schema with "
544
+ "get_tool_details.",
545
+ _CALL_INPUT,
546
+ caller(read=False),
547
+ _WRITE,
548
+ ),
549
+ ]
550
+ return {r.name: r for r in registered}
551
+
552
+ def _direct(self, tool: Tool) -> _Registered:
553
+ spec = self.spec
554
+
555
+ async def run(
556
+ params: dict[str, Json], progress: Progress | None, request: Request | None
557
+ ) -> dict[str, Json]:
558
+ return await call_tool(
559
+ spec, tool, params, parsed=True, progress=progress, request=request, env=self.env
560
+ )
561
+
562
+ return _Registered(
563
+ tool.name,
564
+ tool.description,
565
+ tool.inputs if tool.inputs.fields else None,
566
+ run,
567
+ tool.annotations,
568
+ tool.output,
569
+ {"instructions": tool.instructions} if tool.instructions else None,
570
+ )
571
+
572
+ def initialize(self, params: Json) -> dict[str, Json]:
573
+ """Answers `initialize`, negotiating the protocol version."""
574
+ requested = params.get("protocolVersion") if isinstance(params, dict) else None
575
+ version = requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
576
+ info: dict[str, Json] = {"name": self.name}
577
+ if self.title:
578
+ info["title"] = self.title
579
+ info["version"] = self.version
580
+ out: dict[str, Json] = {
581
+ "protocolVersion": version,
582
+ "capabilities": {"tools": {"listChanged": True}},
583
+ "serverInfo": info,
584
+ }
585
+ if self.instructions:
586
+ out["instructions"] = self.instructions
587
+ return out
588
+
589
+ def list_tools(self) -> dict[str, Json]:
590
+ """Answers `tools/list`."""
591
+ tools: list[Json] = []
592
+ for tool in self.tools.values():
593
+ item: dict[str, Json] = {"name": tool.name}
594
+ if tool.description is not None:
595
+ item["description"] = tool.description
596
+ if tool.inputs is not None:
597
+ schema = json_schema(tool.inputs, "input")
598
+ item["inputSchema"] = {
599
+ "type": "object",
600
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
601
+ **{k: v for k, v in schema.items() if k != "type"},
602
+ }
603
+ else:
604
+ item["inputSchema"] = {"type": "object", "properties": {}}
605
+ if tool.annotations is not None:
606
+ item["annotations"] = tool.annotations
607
+ if tool.meta is not None:
608
+ item["_meta"] = tool.meta
609
+ if tool.output is not None:
610
+ item["outputSchema"] = tool.output
611
+ tools.append(item)
612
+ return {"tools": tools}
613
+
614
+ async def call(
615
+ self, params: dict[str, Json], progress: Progress | None, request: Request | None
616
+ ) -> dict[str, Json]:
617
+ """Answers `tools/call`.
618
+
619
+ Raises:
620
+ RpcError: When the tool does not exist.
621
+ """
622
+ name = params.get("name")
623
+ tool = self.tools.get(name) if isinstance(name, str) else None
624
+ if tool is None:
625
+ raise RpcError(-32602, f"Tool {name} not found")
626
+ arguments = params.get("arguments")
627
+ value: dict[str, Json] = arguments if isinstance(arguments, dict) else {}
628
+ if tool.inputs is not None:
629
+ parsed, issues = validate(tool.inputs, value)
630
+ if issues:
631
+ listed = ", ".join(
632
+ f"{'.'.join(_js.to_string(p) for p in i.path)}: {i.message}"
633
+ if i.path
634
+ else i.message
635
+ for i in issues
636
+ )
637
+ message = f"Input validation error: Invalid arguments for tool {name}: {listed}"
638
+ return {"content": [_text(message)], "isError": True}
639
+ value = parsed
640
+ try:
641
+ result = await tool.run(value, progress, request)
642
+ except Exception as error:
643
+ return {"content": [_text(str(error))], "isError": True}
644
+ if (
645
+ tool.output is not None
646
+ and not result.get("isError")
647
+ and "structuredContent" not in result
648
+ ):
649
+ message = (
650
+ f"Output validation error: Tool {name} has an output schema but no structured "
651
+ "content was provided"
652
+ )
653
+ return {"content": [_text(message)], "isError": True}
654
+ return result
655
+
656
+ async def handle(
657
+ self,
658
+ message: dict[str, Json],
659
+ notify: Callable[[dict[str, Json]], Awaitable[None]],
660
+ request: Request | None = None,
661
+ ) -> dict[str, Json] | None:
662
+ """Answers one JSON-RPC request. Returns `None` for notifications and other messages."""
663
+ method = message.get("method")
664
+ if not isinstance(method, str) or "id" not in message:
665
+ return None
666
+ id_ = message["id"]
667
+ params = message.get("params")
668
+ params = params if isinstance(params, dict) else {}
669
+ try:
670
+ if method == "initialize":
671
+ result = self.initialize(params)
672
+ elif method == "ping":
673
+ result = {}
674
+ elif method == "tools/list":
675
+ result = self.list_tools()
676
+ elif method == "tools/call":
677
+ meta = params.get("_meta")
678
+ token = meta.get("progressToken") if isinstance(meta, dict) else None
679
+ progress = None
680
+ if isinstance(token, (str, int)) and not isinstance(token, bool):
681
+ count = [0]
682
+
683
+ async def send_progress(value: Json) -> None:
684
+ count[0] += 1
685
+ await notify(
686
+ {
687
+ "jsonrpc": "2.0",
688
+ "method": "notifications/progress",
689
+ "params": {
690
+ "progressToken": token,
691
+ "progress": count[0],
692
+ "message": _js.stringify(value),
693
+ },
694
+ }
695
+ )
696
+
697
+ progress = send_progress
698
+ result = await self.call(params, progress, request)
699
+ else:
700
+ raise RpcError(-32601, "Method not found")
701
+ except RpcError as error:
702
+ return {
703
+ "jsonrpc": "2.0",
704
+ "id": id_,
705
+ "error": {"code": error.code, "message": error.message},
706
+ }
707
+ return {"result": result, "jsonrpc": "2.0", "id": id_}
708
+
709
+
710
+ class RpcError(Exception):
711
+ """A JSON-RPC error response."""
712
+
713
+ def __init__(self, code: int, message: str) -> None:
714
+ super().__init__(message)
715
+ self.code = code
716
+ self.message = message
717
+
718
+
719
+ def is_message(value: Json) -> bool:
720
+ """Whether a value is a JSON-RPC 2.0 request, notification, or response."""
721
+ if not isinstance(value, dict) or value.get("jsonrpc") != "2.0":
722
+ return False
723
+ id_ = value.get("id")
724
+ has_id = "id" in value and isinstance(id_, (str, int)) and not isinstance(id_, bool)
725
+ if "method" in value:
726
+ params = value.get("params")
727
+ valid_params = "params" not in value or isinstance(params, dict)
728
+ return isinstance(value["method"], str) and valid_params and ("id" not in value or has_id)
729
+ return has_id and ("result" in value or "error" in value)
730
+
731
+
732
+ async def serve_stdio(spec: Spec, env: dict[str, str], stdin: TextIO, stdout: TextIO) -> None:
733
+ """Serves MCP over stdio until the input ends: one JSON-RPC message per line."""
734
+ server = Server(spec, env)
735
+
736
+ async def write(message: dict[str, Json]) -> None:
737
+ stdout.write(_js.stringify(message) + "\n")
738
+ stdout.flush()
739
+
740
+ while True:
741
+ line = await asyncio.to_thread(stdin.readline)
742
+ if not line:
743
+ return
744
+ message = _js.parse_json(line) if _js.json_parse_error(line) is None else None
745
+ if message is None or not is_message(message):
746
+ continue
747
+ assert isinstance(message, dict)
748
+ response = await server.handle(message, write)
749
+ if response is not None:
750
+ await write(response)
751
+
752
+
753
+ def _json_error(status: int, code: int, message: str) -> Response:
754
+ return Response.json(
755
+ {"jsonrpc": "2.0", "error": {"code": code, "message": message}, "id": None},
756
+ status=status,
757
+ )
758
+
759
+
760
+ class HttpTransport:
761
+ """Streamable HTTP for one server, answering with JSON responses."""
762
+
763
+ def __init__(self, server: Server, *, sessions: bool) -> None:
764
+ self.server = server
765
+ self.sessions = sessions
766
+ self.session: str | None = None
767
+ self.initialized = False
768
+
769
+ def _check_session(self, request: Request) -> Response | None:
770
+ if not self.sessions:
771
+ return None
772
+ if not self.initialized:
773
+ return _json_error(400, -32000, "Bad Request: Server not initialized")
774
+ session = request.headers.get("mcp-session-id")
775
+ if not session:
776
+ return _json_error(400, -32000, "Bad Request: Mcp-Session-Id header is required")
777
+ if session != self.session:
778
+ return _json_error(404, -32001, "Session not found")
779
+ version = request.headers.get("mcp-protocol-version")
780
+ if version is not None and version not in PROTOCOL_VERSIONS:
781
+ return _json_error(
782
+ 400,
783
+ -32000,
784
+ f"Bad Request: Unsupported protocol version: {version} "
785
+ f"(supported versions: {', '.join(PROTOCOL_VERSIONS)})",
786
+ )
787
+ return None
788
+
789
+ async def handle(self, request: Request) -> Response:
790
+ """Answers an HTTP request."""
791
+ if request.method == "GET":
792
+ if "text/event-stream" not in (request.headers.get("accept") or ""):
793
+ return _json_error(
794
+ 406, -32000, "Not Acceptable: Client must accept text/event-stream"
795
+ )
796
+ return self._check_session(request) or _json_error(405, -32000, "Method not allowed.")
797
+ if request.method == "DELETE":
798
+ failure = self._check_session(request)
799
+ if failure is not None:
800
+ return failure
801
+ self.initialized = False
802
+ self.session = None
803
+ return Response(status=200)
804
+ if request.method != "POST":
805
+ response = _json_error(405, -32000, "Method not allowed.")
806
+ response.headers.set("allow", "GET, POST, DELETE")
807
+ return response
808
+ accept = request.headers.get("accept") or ""
809
+ if "application/json" not in accept or "text/event-stream" not in accept:
810
+ return _json_error(
811
+ 406,
812
+ -32000,
813
+ "Not Acceptable: Client must accept both application/json and text/event-stream",
814
+ )
815
+ if "application/json" not in (request.headers.get("content-type") or ""):
816
+ return _json_error(
817
+ 415, -32000, "Unsupported Media Type: Content-Type must be application/json"
818
+ )
819
+ text = request.text()
820
+ if _js.json_parse_error(text) is not None:
821
+ return _json_error(400, -32700, "Parse error: Invalid JSON")
822
+ raw = _js.parse_json(text)
823
+ messages: list[Json] = raw if isinstance(raw, list) else [raw]
824
+ if not all(is_message(m) for m in messages):
825
+ return _json_error(400, -32700, "Parse error: Invalid JSON-RPC message")
826
+ typed = [m for m in messages if isinstance(m, dict)]
827
+ initializing = any(m.get("method") == "initialize" and "id" in m for m in typed)
828
+ if initializing:
829
+ if self.initialized and self.session is not None:
830
+ return _json_error(400, -32600, "Invalid Request: Server already initialized")
831
+ if len(typed) > 1:
832
+ return _json_error(
833
+ 400, -32600, "Invalid Request: Only one initialization request is allowed"
834
+ )
835
+ self.session = str(uuid.uuid4()) if self.sessions else None
836
+ self.initialized = True
837
+ else:
838
+ failure = self._check_session(request)
839
+ if failure is not None:
840
+ return failure
841
+
842
+ async def drop(_: dict[str, Json]) -> None:
843
+ return None
844
+
845
+ responses: list[Json] = []
846
+ for message in typed:
847
+ response = await self.server.handle(message, drop, request)
848
+ if response is not None:
849
+ responses.append(response)
850
+ if not any("method" in m and "id" in m for m in typed):
851
+ return Response(status=202)
852
+ headers = {"mcp-session-id": self.session} if self.session is not None else None
853
+ body = responses[0] if len(responses) == 1 else responses
854
+ return Response.json(body, headers=headers)
855
+
856
+
857
+ class HttpHandler:
858
+ """MCP over HTTP for a CLI: one session, or a fresh server per request when stateless."""
859
+
860
+ def __init__(self, spec: Spec) -> None:
861
+ self.spec = spec
862
+ self.transport: HttpTransport | None = None
863
+
864
+ async def __call__(self, request: Request) -> Response:
865
+ options = self.spec.mcp or McpOptions()
866
+ if options.stateless:
867
+ if request.method != "POST":
868
+ return Response(status=405, headers={"allow": "POST"})
869
+ return await HttpTransport(Server(self.spec), sessions=False).handle(request)
870
+ if self.transport is None:
871
+ self.transport = HttpTransport(Server(self.spec), sessions=True)
872
+ return await self.transport.handle(request)