chore: import upstream snapshot with attribution
Deploy Docs / deploy-docs (push) Failing after 1s
Conformance Tests / client-conformance (push) Failing after 3s
Conformance Tests / server-conformance (push) Failing after 1s
GitHub Actions Security Analysis / zizmor (push) Failing after 1s
CI / checks (push) Failing after 59m20s
CI / all-green (push) Waiting to run

This commit is contained in:
wehub-resource-sync
2026-07-13 12:10:27 +08:00
commit 49b9bb6724
992 changed files with 161690 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
# tools
**Start here.** Register tools with `@mcp.tool()`; the SDK infers the JSON
input schema from type hints, the output schema from the return annotation, and
returns `structuredContent` alongside text. `ToolAnnotations` carries
behavioural hints (`readOnlyHint`, `idempotentHint`) the host can show to
users. The client lists tools, inspects schemas + annotations, calls both, and
asserts structured output.
## Run it
```bash
# stdio (default — the client spawns the server as a subprocess)
uv run python -m stories.tools.client
# HTTP — the client self-hosts the server on a free port, runs, then tears it down
uv run python -m stories.tools.client --http
# same, against the lowlevel-API server variant
uv run python -m stories.tools.client --http --server server_lowlevel
```
## What to look at
- `server.py` `calc``Literal[...]` and `BaseModel` in the signature become
the tool's `inputSchema` / `outputSchema` with zero hand-written JSON.
- `server.py` `echo``structured_output=False` opts out of schema inference
for a plain text-only tool.
- `server_lowlevel.py` — the same wire contract built by hand: this is what
`MCPServer` generates for you.
## Spec
[Tools — server features](https://modelcontextprotocol.io/specification/2025-11-25/server/tools)
## See also
`schema_validators/` (every input-schema source: pydantic / TypedDict /
dataclass / dict), `error_handling/` (`is_error` vs protocol error),
`streaming/` (progress mid-call).
View File
+32
View File
@@ -0,0 +1,32 @@
"""List tools, inspect schemas + annotations, call both tools, assert structured output."""
from mcp_types import TextContent
from mcp.client import Client
from stories._harness import Target, run_client
async def main(target: Target, *, mode: str = "auto") -> None:
async with Client(target, mode=mode) as client:
listed = await client.list_tools()
by_name = {t.name: t for t in listed.tools}
assert set(by_name) == {"calc", "echo"}
calc = by_name["calc"]
assert calc.annotations is not None and calc.annotations.read_only_hint is True
assert calc.annotations.idempotent_hint is True
assert calc.output_schema is not None
assert set(calc.input_schema.get("required", ())) >= {"op", "a", "b"}
assert by_name["echo"].output_schema is None
result = await client.call_tool("calc", {"op": "add", "a": 2, "b": 3})
assert not result.is_error
assert result.structured_content == {"op": "add", "result": 5.0}, result
echoed = await client.call_tool("echo", {"text": "hi"})
assert echoed.structured_content is None
assert isinstance(echoed.content[0], TextContent) and echoed.content[0].text == "hi"
if __name__ == "__main__":
run_client(main)
+37
View File
@@ -0,0 +1,37 @@
"""Tools primitive: register, list, call, structured output, annotations."""
from typing import Literal
from mcp_types import ToolAnnotations
from pydantic import BaseModel
from mcp.server.mcpserver import MCPServer
from stories._hosting import run_server_from_args
class CalcResult(BaseModel):
op: str
result: float
def build_server() -> MCPServer:
mcp = MCPServer("tools-example")
@mcp.tool(
title="Calculator",
description="Apply an arithmetic operation to two numbers.",
annotations=ToolAnnotations(read_only_hint=True, idempotent_hint=True),
)
def calc(op: Literal["add", "sub", "mul"], a: float, b: float) -> CalcResult:
result = a + b if op == "add" else a - b if op == "sub" else a * b
return CalcResult(op=op, result=result)
@mcp.tool(description="Echo the input back as plain text.", structured_output=False)
def echo(text: str) -> str:
return text
return mcp
if __name__ == "__main__":
run_server_from_args(build_server)
+72
View File
@@ -0,0 +1,72 @@
"""Tools primitive (lowlevel API): hand-built Tool descriptors and CallToolResult."""
from typing import Any
import mcp_types as types
from mcp.server.context import ServerRequestContext
from mcp.server.lowlevel import Server
from stories._hosting import run_server_from_args
CALC_INPUT_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {
"op": {"type": "string", "enum": ["add", "sub", "mul"]},
"a": {"type": "number"},
"b": {"type": "number"},
},
"required": ["op", "a", "b"],
}
CALC_OUTPUT_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {"op": {"type": "string"}, "result": {"type": "number"}},
"required": ["op", "result"],
}
ECHO_INPUT_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"],
}
def build_server() -> Server[Any]:
async def list_tools(
ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
) -> types.ListToolsResult:
return types.ListToolsResult(
tools=[
types.Tool(
name="calc",
title="Calculator",
description="Apply an arithmetic operation to two numbers.",
input_schema=CALC_INPUT_SCHEMA,
output_schema=CALC_OUTPUT_SCHEMA,
annotations=types.ToolAnnotations(read_only_hint=True, idempotent_hint=True),
),
types.Tool(
name="echo",
description="Echo the input back as plain text.",
input_schema=ECHO_INPUT_SCHEMA,
),
]
)
async def call_tool(ctx: ServerRequestContext[Any], params: types.CallToolRequestParams) -> types.CallToolResult:
assert params.arguments is not None
if params.name == "calc":
op, a, b = params.arguments["op"], float(params.arguments["a"]), float(params.arguments["b"])
result = a + b if op == "add" else a - b if op == "sub" else a * b
payload = {"op": op, "result": result}
return types.CallToolResult(
content=[types.TextContent(text=f"{a} {op} {b} = {result}")],
structured_content=payload,
)
if params.name == "echo":
return types.CallToolResult(content=[types.TextContent(text=str(params.arguments["text"]))])
raise NotImplementedError
return Server("tools-example", on_list_tools=list_tools, on_call_tool=call_tool)
if __name__ == "__main__":
run_server_from_args(build_server)