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) Has been cancelled

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
@@ -0,0 +1,73 @@
# legacy-elicitation
> **Legacy mechanism (2025 handshake era).** This story shows the push-style
> server→client `elicitation/create` request; the 2026-07-28 protocol carries
> elicitation as an `InputRequiredResult` round-trip instead — that path is the
> [`mrtr/`](../mrtr/) story. Elicitation itself is **not** deprecated.
> TODO(maxisbey): unify once the MRTR runtime lands
> ([#2898](https://github.com/modelcontextprotocol/python-sdk/issues/2898)).
> The TypeScript SDK ships a single dual-era `elicitation/` story; this
> directory re-merges back into `elicitation/` once MRTR lands.
A tool pauses mid-call to ask the user for structured input. On the
handshake-era protocol the server pushes an `elicitation/create` *request* to
the client and blocks until the client's `elicitation_callback` answers
`accept` / `decline` / `cancel`. Two modes: **form** (`ctx.elicit(message,
PydanticModel)` — schema derived from the model, accepted content validated
back into it) and **url** (`ctx.elicit_url(...)` — directs the user out-of-band
for OAuth / payment flows; `send_elicit_complete` notifies the client when the
flow finishes).
## Run it
```bash
# stdio (default — the client spawns the server as a subprocess)
uv run python -m stories.legacy_elicitation.client
# HTTP — the client self-hosts the server on a free port, runs, then tears it
# down (--legacy: the push request needs the handshake era)
uv run python -m stories.legacy_elicitation.client --http --legacy
# same, against the lowlevel-API server variant
uv run python -m stories.legacy_elicitation.client --http --legacy --server server_lowlevel
```
## What to look at
- `client.py` `main` — the whole client setup is one visible construction:
`Client(target, mode=mode, elicitation_callback=on_elicit)`. Supplying
`elicitation_callback` is what advertises the `elicitation: {form, url}`
capability; `on_elicit` serves *both* modes by branching on
`isinstance(params, ElicitRequestURLParams)`.
- `server.py` `register_user``await ctx.elicit("...", Registration)` derives
the form schema from the pydantic model and returns a typed
`ElicitationResult[Registration]`; narrow with `isinstance(answer,
AcceptedElicitation)` before reading `answer.data`.
- `server.py` `link_account``ctx.elicit_url(...)` for out-of-band flows;
after the user finishes, `send_elicit_complete` emits
`notifications/elicitation/complete` so the client can correlate.
- `server_lowlevel.py` — the same flow via `ctx.session.elicit_form` /
`ctx.session.elicit_url` and a hand-written `requestedSchema`.
## Caveats
- **Context paths.** `ctx.elicit` / `ctx.elicit_url` and the 2-hop
`ctx.request_context.session.send_elicit_complete` are interim; a later
release will shorten these.
- **No per-mode opt-in.** Supplying any `elicitation_callback` advertises both
form and url support; there is currently no way to advertise form-only from
`Client`.
- **Throw-style URL elicitation** (`raise UrlElicitationRequiredError([...])`
wire `-32042`) is the stateless-transport alternative to `ctx.elicit_url`;
see `tests/interaction/lowlevel/test_elicitation.py` and the `error_handling`
story.
## Spec
[Elicitation — client features](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation)
## See also
`sampling/` (same push-request shape, deprecated per SEP-2577), `mrtr/`
(the 2026-era carrier), `error_handling/`
(`UrlElicitationRequiredError`), `refund_desk/` (resolver DI rides this push
mechanism on handshake-era connections).
@@ -0,0 +1,32 @@
"""Auto-answer form and URL elicitations and assert the tool result reflects them."""
import mcp_types as types
from mcp.client import Client, ClientRequestContext
from stories._harness import Target, run_client
async def on_elicit(context: ClientRequestContext, params: types.ElicitRequestParams) -> types.ElicitResult:
if isinstance(params, types.ElicitRequestURLParams):
# A real client would ask consent and open params.url in a browser, returning
# `accept` right away; the server's notifications/elicitation/complete arrives
# afterward (once the out-of-band flow finishes) for the client to correlate.
assert params.url.startswith("https://example.com/")
return types.ElicitResult(action="accept")
assert "username" in params.requested_schema["properties"]
return types.ElicitResult(action="accept", content={"username": "alice", "plan": "pro"})
async def main(target: Target, *, mode: str = "auto") -> None:
async with Client(target, mode=mode, elicitation_callback=on_elicit) as client:
registered = await client.call_tool("register_user", {})
assert isinstance(registered.content[0], types.TextContent)
assert registered.content[0].text == "registered alice (plan: pro)", registered
linked = await client.call_tool("link_account", {"provider": "github"})
assert isinstance(linked.content[0], types.TextContent)
assert linked.content[0].text == "linked github", linked
if __name__ == "__main__":
run_client(main)
@@ -0,0 +1,47 @@
"""Elicitation (handshake-era push style): a tool blocks on user input mid-call."""
from pydantic import BaseModel
from mcp.server.elicitation import AcceptedElicitation
from mcp.server.mcpserver import Context, MCPServer
from stories._hosting import run_server_from_args
class Registration(BaseModel):
username: str
plan: str | None = None
def build_server() -> MCPServer:
mcp = MCPServer("legacy-elicitation-example")
@mcp.tool(description="Register a new account by asking the user for their details.")
async def register_user(ctx: Context) -> str:
answer = await ctx.elicit("Please provide your registration details:", Registration)
if not isinstance(answer, AcceptedElicitation):
return f"registration {answer.action}"
return f"registered {answer.data.username} (plan: {answer.data.plan or 'free'})"
@mcp.tool(description="Link a third-party account by directing the user to a sign-in URL.")
async def link_account(provider: str, ctx: Context) -> str:
# elicitation_id must be unique per elicitation, not per provider — scope it to this request.
elicitation_id = f"link-{provider}-{ctx.request_context.request_id}"
answer = await ctx.elicit_url(
f"Sign in to {provider} to link your account",
url=f"https://example.com/oauth/{provider}/authorize",
elicitation_id=elicitation_id,
)
if answer.action != "accept":
return f"link {answer.action}"
# Out-of-band flow finished: tell the client which elicitation completed.
# The 2-hop `ctx.request_context.*` reach is interim; a later release shortens it.
await ctx.request_context.session.send_elicit_complete(
elicitation_id, related_request_id=ctx.request_context.request_id
)
return f"linked {provider}"
return mcp
if __name__ == "__main__":
run_server_from_args(build_server)
@@ -0,0 +1,70 @@
"""Elicitation (handshake-era push style) 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 stories._hosting import run_server_from_args
REGISTRATION_SCHEMA: types.ElicitRequestedSchema = {
"type": "object",
"properties": {
"username": {"type": "string"},
"plan": {"type": "string", "enum": ["free", "pro", "team"]},
},
"required": ["username"],
}
LINK_INPUT_SCHEMA: dict[str, Any] = {
"type": "object",
"properties": {"provider": {"type": "string"}},
"required": ["provider"],
}
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="register_user", description="Register a new account.", input_schema={"type": "object"}
),
types.Tool(
name="link_account", description="Link a third-party account.", input_schema=LINK_INPUT_SCHEMA
),
]
)
async def call_tool(ctx: ServerRequestContext[Any], params: types.CallToolRequestParams) -> types.CallToolResult:
if params.name == "register_user":
answer = await ctx.session.elicit_form(
"Please provide your registration details:", REGISTRATION_SCHEMA, related_request_id=ctx.request_id
)
if answer.action != "accept" or answer.content is None:
return types.CallToolResult(content=[types.TextContent(text=f"registration {answer.action}")])
text = f"registered {answer.content['username']} (plan: {answer.content.get('plan') or 'free'})"
return types.CallToolResult(content=[types.TextContent(text=text)])
assert params.name == "link_account" and params.arguments is not None
provider = params.arguments["provider"]
# elicitation_id must be unique per elicitation, not per provider — scope it to this request.
elicitation_id = f"link-{provider}-{ctx.request_id}"
answer = await ctx.session.elicit_url(
f"Sign in to {provider} to link your account",
url=f"https://example.com/oauth/{provider}/authorize",
elicitation_id=elicitation_id,
related_request_id=ctx.request_id,
)
if answer.action != "accept":
return types.CallToolResult(content=[types.TextContent(text=f"link {answer.action}")])
await ctx.session.send_elicit_complete(elicitation_id, related_request_id=ctx.request_id)
return types.CallToolResult(content=[types.TextContent(text=f"linked {provider}")])
return Server("legacy-elicitation-example", on_list_tools=list_tools, on_call_tool=call_tool)
if __name__ == "__main__":
run_server_from_args(build_server)