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
+79
View File
@@ -0,0 +1,79 @@
# mrtr
Multi-round tool result: on the 2026-07-28 protocol a tool that needs user
input mid-call **returns** `resultType: "input_required"` with embedded
`inputRequests` and an opaque `requestState`, instead of pushing a
server-to-client request. The client fulfils the embedded requests and retries the
original `tools/call` carrying `inputResponses` and the echoed `requestState`.
The story shows both the `Client` auto-loop (one `await call_tool`, callbacks
fired transparently) and a manual `client.session` loop (the persistable
form). Because `requestState` round-trips through the client, it also shows
the security surface that protects it: `MCPServer` seals state by default
under a process-local key, handlers keep writing plaintext, and the wire only
ever carries an opaque token. The manual loop tampers with the sealed token to
show what a forged echo gets back.
## Run it
```bash
# HTTP: the client self-hosts the server on a free port, runs, then tears it
# down (the InputRequiredResult round-trip is 2026-era only)
uv run python -m stories.mrtr.client --http
# same, against the lowlevel-API server variant
uv run python -m stories.mrtr.client --http --server server_lowlevel
```
## What to look at
- `server.py` `build_server`: no security configuration at all. The default
seals under a key generated at process start, which is right for a
single-process server like this one; a fleet (multi-worker or load-balanced)
shares keys with `request_state_security=RequestStateSecurity(keys=[...])`
so any instance can verify state another minted.
- `server.py` `deploy`: handlers stay plaintext. The first round returns
`InputRequiredResult(input_requests={...},
request_state="awaiting-confirm")` and the retry asserts
`ctx.request_state == "awaiting-confirm"`. The tool never touches the
crypto; the boundary seals on the way out and unseals the echo on the way
back in.
- `client.py` `main`: the auto-loop is invisible at the call site:
`Client(target, mode=mode, elicitation_callback=on_elicit)` then
`await client.call_tool("deploy", ...)`. The same `on_elicit` callback the
legacy push path uses is dispatched for each embedded `inputRequests` entry.
- `client.py` manual block: `client.session.call_tool(...,
allow_input_required=True)` returns the raw `InputRequiredResult` so
`request_state` can be persisted between rounds. The wire value is an opaque
sealed token, **not** the string the server code wrote. The client asserts
exactly that, then retries with one character of the token flipped and gets
the single frozen error every verification failure maps to: `-32602`,
`"Invalid or expired requestState"`, `{"reason": "invalid_request_state"}`.
The specific reason (tampered tag, expiry, wrong request, wrong principal)
appears only in the server's log, never on the wire. The untampered token
then completes the round normally.
- `server_lowlevel.py`: the lowlevel tier doesn't seal by default; the same
enforcement is one appended middleware:
`server.middleware.append(RequestStateBoundary(RequestStateSecurity.ephemeral(),
default_audience=server.name))`.
## Caveats
- **Loop bound.** The auto-loop gives up after `input_required_max_rounds`
(default 10) with `InputRequiredRoundsExceededError`; raise it on the
`Client` ctor or drop to the manual loop.
- **The default key dies with the process.** It is generated at startup and
held only in memory, so a server restart (or a retry landing on a different
instance) invalidates in-flight rounds: the client gets the same frozen
rejection and must start the flow over. Use
`RequestStateSecurity(keys=[...])` when state must survive either.
## Spec
[Input required tool results (server features)](https://modelcontextprotocol.io/specification/draft/server/tools#input-required-tool-results),
[Multi-round-trip requests (security patterns)](https://modelcontextprotocol.io/specification/draft/basic/patterns/mrtr)
## See also
`legacy_elicitation/` and `sampling/`: the handshake-era push equivalents this
mechanism replaces on the 2026 protocol. `refund_desk/`: resolver DI at the
MCPServer tier: the questions a tool can declare instead of pushing by hand
(its elicited answers ride in the same sealed `requestState`).
View File
+70
View File
@@ -0,0 +1,70 @@
"""Drive the deploy tool both ways: the Client auto-loop, and a manual session-level loop."""
import mcp_types as types
from mcp import MCPError
from mcp.client import Client, ClientRequestContext
from stories._harness import Target, run_client
async def on_elicit(context: ClientRequestContext, params: types.ElicitRequestParams) -> types.ElicitResult:
# The same callback serves legacy push-style elicitation/create requests AND embedded
# InputRequiredResult.input_requests entries — the driver dispatches both here.
assert isinstance(params, types.ElicitRequestFormParams)
assert "confirm" in params.requested_schema["properties"]
return types.ElicitResult(action="accept", content={"confirm": True})
async def main(target: Target, *, mode: str = "auto") -> None:
async with Client(target, mode=mode, elicitation_callback=on_elicit) as client:
# ── auto-loop: Client.call_tool dispatches input_requests to on_elicit and retries
# internally; the caller just sees the final CallToolResult.
deployed = await client.call_tool("deploy", {"env": "production"})
assert isinstance(deployed.content[0], types.TextContent)
assert deployed.content[0].text == "deployed to production", deployed
# ── manual loop: drop to client.session for the raw InputRequiredResult so the
# request_state can be persisted between rounds (e.g. across a process restart).
first = await client.session.call_tool("deploy", {"env": "staging"}, allow_input_required=True)
assert isinstance(first, types.InputRequiredResult)
assert first.input_requests is not None and "confirm" in first.input_requests
# The boundary sealed server.py's plaintext "awaiting-confirm"; the wire token is opaque.
token = first.request_state
assert token is not None and token != "awaiting-confirm", token
responses: types.InputResponses = {"confirm": types.ElicitResult(action="decline")}
# Tamper demo: flipping any one character fails verification, and every failure
# maps to one frozen wire error; the real reason appears only in the server log.
i = len(token) // 2
tampered = token[:i] + ("A" if token[i] != "A" else "B") + token[i + 1 :]
try:
await client.session.call_tool(
"deploy",
{"env": "staging"},
input_responses=responses,
request_state=tampered,
allow_input_required=True,
)
except MCPError as e:
assert e.code == types.INVALID_PARAMS
assert e.message == "Invalid or expired requestState"
assert e.data == {"reason": "invalid_request_state"}
else:
raise AssertionError("expected MCPError for a tampered requestState")
# The untampered token still completes the round; decline so this path diverges from the auto run.
second = await client.session.call_tool(
"deploy",
{"env": "staging"},
input_responses=responses,
request_state=token,
allow_input_required=True,
)
assert isinstance(second, types.CallToolResult)
assert isinstance(second.content[0], types.TextContent)
assert second.content[0].text == "deployment to staging cancelled", second
if __name__ == "__main__":
run_client(main)
+39
View File
@@ -0,0 +1,39 @@
"""Multi-round tool result (2026 era): a tool returns input_required and resumes from echoed state."""
from mcp_types import ElicitRequest, ElicitRequestedSchema, ElicitRequestFormParams, ElicitResult, InputRequiredResult
from mcp.server.mcpserver import Context, MCPServer
from stories._hosting import run_server_from_args
CONFIRM_SCHEMA: ElicitRequestedSchema = {
"type": "object",
"properties": {"confirm": {"type": "boolean", "description": "Proceed with the deployment?"}},
"required": ["confirm"],
}
def build_server() -> MCPServer:
# requestState is sealed by default under a process-local key, which suits this
# single-process server; fleets share keys=[...] so any instance can verify.
mcp = MCPServer("mrtr-example")
@mcp.tool(description="Deploy to an environment, asking the user to confirm first.")
async def deploy(env: str, ctx: Context) -> str | InputRequiredResult:
responses = ctx.input_responses
if responses is None or "confirm" not in responses:
ask = ElicitRequest(
params=ElicitRequestFormParams(message=f"Deploy to {env}?", requested_schema=CONFIRM_SCHEMA)
)
# The boundary seals this plaintext request_state on the way out and unseals the echo on retry.
return InputRequiredResult(input_requests={"confirm": ask}, request_state="awaiting-confirm")
assert ctx.request_state == "awaiting-confirm", ctx.request_state
answer = responses["confirm"]
if isinstance(answer, ElicitResult) and answer.action == "accept" and (answer.content or {}).get("confirm"):
return f"deployed to {env}"
return f"deployment to {env} cancelled"
return mcp
if __name__ == "__main__":
run_server_from_args(build_server)
+67
View File
@@ -0,0 +1,67 @@
"""Multi-round tool result (2026 era) against the low-level Server."""
from typing import Any
import mcp_types as types
from mcp.server.context import ServerRequestContext
from mcp.server.lowlevel import Server
from mcp.server.request_state import RequestStateBoundary, RequestStateSecurity
from stories._hosting import run_server_from_args
CONFIRM_SCHEMA: types.ElicitRequestedSchema = {
"type": "object",
"properties": {"confirm": {"type": "boolean", "description": "Proceed with the deployment?"}},
"required": ["confirm"],
}
DEPLOY_INPUT_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {"env": {"type": "string"}},
"required": ["env"],
}
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="deploy",
description="Deploy to an environment, asking the user to confirm first.",
input_schema=DEPLOY_INPUT_SCHEMA,
)
]
)
async def call_tool(
ctx: ServerRequestContext[Any], params: types.CallToolRequestParams
) -> types.CallToolResult | types.InputRequiredResult:
assert params.name == "deploy" and params.arguments is not None
env = params.arguments["env"]
responses = params.input_responses
if responses is None or "confirm" not in responses:
ask = types.ElicitRequest(
params=types.ElicitRequestFormParams(message=f"Deploy to {env}?", requested_schema=CONFIRM_SCHEMA)
)
return types.InputRequiredResult(input_requests={"confirm": ask}, request_state="awaiting-confirm")
assert params.request_state == "awaiting-confirm", params.request_state
answer = responses["confirm"]
if (
isinstance(answer, types.ElicitResult)
and answer.action == "accept"
and (answer.content or {}).get("confirm")
):
return types.CallToolResult(content=[types.TextContent(text=f"deployed to {env}")])
return types.CallToolResult(content=[types.TextContent(text=f"deployment to {env} cancelled")])
server = Server("mrtr-example", on_list_tools=list_tools, on_call_tool=call_tool)
# Lowlevel opt-in: append the same boundary middleware MCPServer installs by
# default; the server name becomes the token audience.
server.middleware.append(RequestStateBoundary(RequestStateSecurity.ephemeral(), default_audience=server.name))
return server
if __name__ == "__main__":
run_server_from_args(build_server)