🚀 The fast, Pythonic way to build MCP servers and clients.
Add guard-mode multi-round-trip tools (SEP-2322) (#4544)
Jeremiah Lowin717f3535f65d
diff --git a/docs/development/v4-notes/change-register.mdx b/docs/development/v4-notes/change-register.mdxindex 4798f7670..ab652a0a3 100644--- a/docs/development/v4-notes/change-register.mdx+++ b/docs/development/v4-notes/change-register.mdx@@ -310,12 +310,12 @@ The push-style Context features that require the server to call back into the cl| --- | --- | --- || `ctx.info` / logging notifications | Supported | Supported || Tools, resources, prompts, completions | Supported | Supported |-| `ctx.elicit` | Supported | Not yet — MRTR rewrite pending |+| `ctx.elicit` (imperative) | Supported | Not on the back-channel — use [elicitation on the modern protocol](/servers/elicitation#elicitation-on-the-modern-protocol) || `ctx.sample` / `ctx.sample_step` | Supported (deprecated) | Removed — call an LLM server-side || `ctx.list_roots` | Supported | Not yet — MRTR rewrite pending || Tasks (via the FastMCP client) | Supported | Not yet |-Tools that rely on `ctx.elicit` or `ctx.list_roots` continue to work against clients on the session-based eras. Sampling is the exception: it is deprecated on every era and will not return on modern connections (see the Deprecated entry below).+Tools that rely on `ctx.elicit` or `ctx.list_roots` continue to work against clients on the session-based eras. On the modern era, elicitation is reachable through the multi-round "guard" pattern instead (a tool returns an `InputRequiredResult`; see the New entry below). Sampling is the exception: it is deprecated on every era and will not return on modern connections (see the Deprecated entry below).Ordinary `ctx.info` usage emits an SDK-level `MCPDeprecationWarning` ("The logging capability is deprecated as of 2026-07-28 (SEP-2577)"). That warning comes from the SDK, not FastMCP, and is benign — logging keeps working on session-based connections per the matrix. `ctx.sample`/`ctx.sample_step` additionally emit a FastMCP-owned `FastMCPDeprecationWarning` (see below). The upgrade guide calls both out explicitly.@@ -343,6 +343,12 @@ A FastMCP server can emit SEP-2549 freshness hints so a caching client (`fastmcp*Verify:* `fastmcp_slim/fastmcp/server/caching.py` (`build_cache_hints`), `fastmcp_slim/fastmcp/server/server.py` (constructor params passed to `LowLevelServer(cache_hints=...)`), `tests/server/test_cache_hints.py` (unit validation + end-to-end interop with `fastmcp.Client(cache=True)`).+### Elicitation on the modern protocol (SEP-2322), guard form — New (opt-in feature)++A tool can gather client input across rounds on a `2026-07-28` call by returning an `InputRequiredResult` (see [Elicitation on the modern protocol](/servers/elicitation#elicitation-on-the-modern-protocol)). Each round is a complete request→response cycle: the tool re-runs per round and reads the client's answers off two new `Context` properties, `ctx.input_responses` (`None` on the first round) and `ctx.request_state` (the echoed opaque state) — thin passthroughs matching the SDK's mcpserver semantics. This is the modern-era elicitation path the earlier per-feature matrix flagged as "MRTR rewrite pending"; it mirrors the SDK's base guard model exactly (tool re-runs, checks whether answers are present, returns to ask for more), with no FastMCP-invented resolver or annotation layer. `fastmcp.types` gains `InputRequiredResult`, `ElicitRequest`, and `ElicitRequestFormParams` for authoring these requests. The `request_state` channel is sealed by the framework, not the author: FastMCP installs the SDK's `RequestStateBoundary` middleware on its low-level server, which seals every outgoing `request_state` and unseals and verifies every inbound echo before a tool runs — so a tool only ever sees plaintext and a tampered, expired, or foreign token is rejected with a frozen wire error. `FastMCP(request_state_security=RequestStateSecurity(keys=[...]))` supplies shared keys for multi-replica deployments; omitted, each process seals under an ephemeral key (correct single-process). Returning this result on a handshake-era (≤ 2025-11-25) connection raises a clear era error naming the mismatch rather than failing as a generic invalid result. The client half (`fastmcp.Client` at `mode="auto"`) drives the loop through its existing elicitation/sampling/roots handlers, capped by `input_required_max_rounds`.++*Verify:* `fastmcp_slim/fastmcp/server/context.py` (`input_responses`/`request_state` properties), `fastmcp_slim/fastmcp/server/low_level.py` (`RequestStateBoundary` install), `fastmcp_slim/fastmcp/server/server.py` (`request_state_security` param), `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py` (`_on_call_tool` input-required passthrough + era gate), `fastmcp_slim/fastmcp/tools/base.py` (`InputRequiredToolResult`), `tests/server/test_mrtr_guards.py`.+### The xfail register — Known gapRoughly forty `xfail` markers across the test tree (concentrated in `tests/server/tasks/`, `tests/client/tasks/`, and `test_protocol_eras.py`) are the built-in beta tracker: each names the SDK gap it waits on. They are enumerated and mapped to sdk-feedback findings on the [Known Gaps](/development/v4-notes/known-gaps) page.diff --git a/docs/development/v4-notes/feature-program.mdx b/docs/development/v4-notes/feature-program.mdxindex 57501562a..945e792d5 100644--- a/docs/development/v4-notes/feature-program.mdx+++ b/docs/development/v4-notes/feature-program.mdx@@ -30,9 +30,11 @@ In this PR, sampling still functions on the legacy eras. Users already see an SD## MRTR elicitation-**Status: Designed. Flagship feature.**+**Status: Guard form shipped (4.0). Declarative `Resolve` layer designed.**-Elicitation survives the modern era, but only declaratively. The 2026 wire envelope still carries elicitation as a multi-round input-request (MRTR — multi-round tool result). Imperative `ctx.elicit` relies on the session back-channel, which is gone on `2026-07-28` foreground calls; on the modern era, elicitation is reachable only through a declarative resolver.+Elicitation survives the modern era through multi-round-trip (MRTR). The 2026 wire envelope carries elicitation as a multi-round input-request: a tool returns an `InputRequiredResult` and re-runs per round, each round a complete request→response cycle. Imperative `ctx.elicit` relies on the session back-channel, which is gone on `2026-07-28` foreground calls; on the modern era, elicitation is reachable through MRTR instead.++The **guard form** of this is shipped in 4.0 (see [Elicitation on the modern protocol](/servers/elicitation#elicitation-on-the-modern-protocol)): a tool returns an `InputRequiredResult` and reads the client's answers off `ctx.input_responses` / `ctx.request_state`, re-running each round. It mirrors the SDK's base guard model exactly — no FastMCP-invented DX, the framework owns `request_state` sealing, and returning this result on a handshake-era connection produces a clear era error. The declarative `Resolve(...)` layer below sits *on top of* this primitive and remains designed but not yet built.The design does both, so the imperative DX survives where it can and a declarative surface covers the modern era:diff --git a/docs/development/v4-notes/protocol-2026.mdx b/docs/development/v4-notes/protocol-2026.mdxindex 709e0fd0d..d6f0ce0c9 100644--- a/docs/development/v4-notes/protocol-2026.mdx+++ b/docs/development/v4-notes/protocol-2026.mdx@@ -40,6 +40,7 @@ The complete picture of what a FastMCP v4 server and client provide on the `2026| **Distributed response caching** | `KeyValueResponseCacheStore` backs the client cache with any key-value store (Redis, memory, filetree), so a fleet of clients or proxy replicas shares cache fills across processes. || **Resource path security** | Templated resource parameters are screened for traversal, absolute paths, and null bytes before handlers run — on by default, including provider-sourced and mounted templates. || **Client protocol negotiation** | `Client(mode="auto")` probes `server/discover` and falls back to the classic handshake; the client answers multi-round-trip `input_required` requests through its existing handlers. |+| **Elicitation on the modern protocol (SEP-2322)** | Tools request user input via multi-round trips: a tool returns an `InputRequiredResult` and re-runs per round, reading the client's answers off `ctx.input_responses` / `ctx.request_state` (the [guard pattern](/servers/elicitation#elicitation-on-the-modern-protocol)). Each round is a complete request→response cycle; the framework seals `request_state` on the wire and unseals it before the tool runs, and a shared-key `request_state_security` policy carries state across replicas. On handshake-era connections returning this result produces a clear era error. || **Spec-standard errors (SEP-2164)** | Missing-resource reads return `-32602`; push-feature calls on modern connections fail with clear era-specific errors rather than generic method-not-found. || **Background tasks** | `@mcp.tool(task=True)` runs on a Redis-backed distributed runtime (Docket) with cross-replica notifications — execution infrastructure that is FastMCP's own, independent of the protocol-era task surface. || **Middleware** | Typed per-method hooks (`on_call_tool`, `on_list_tools`, …) and a suite of built-ins (auth, rate limiting, caching, error handling, logging, timing, and more). |@@ -49,4 +50,4 @@ The complete picture of what a FastMCP v4 server and client provide on the `2026## Still in the program-Two modern-era surfaces are deliberately staged rather than shipped, tracked in the [Feature Program](/development/v4-notes/feature-program): server-side multi-round-trip elicitation (the replacement for push-based `ctx.elicit` on modern connections — the client half already answers `input_required` requests) and the unified `subscriptions/listen` stream. The [Known Gaps](/development/v4-notes/known-gaps) page tracks the upstream dependencies that gate them.+Elicitation on the modern protocol is now shipped in its **guard form** — a tool returns an `InputRequiredResult` and re-runs per round to gather user input via multi-round trips (see [Elicitation on the modern protocol](/servers/elicitation#elicitation-on-the-modern-protocol)). The declarative `Resolve(...)` layer over that primitive remains staged, tracked in the [Feature Program](/development/v4-notes/feature-program), along with the unified `subscriptions/listen` stream. The [Known Gaps](/development/v4-notes/known-gaps) page tracks the upstream dependencies that gate them.diff --git a/docs/servers/elicitation.mdx b/docs/servers/elicitation.mdxindex acf29d10c..647fb662b 100644--- a/docs/servers/elicitation.mdx+++ b/docs/servers/elicitation.mdx@@ -1,7 +1,7 @@---title: User ElicitationsidebarTitle: Elicitation-description: Request structured input from users during tool execution through the MCP context.+description: Ask users for input while a tool is running, on both the handshake and modern protocols.icon: message-question---@@ -9,9 +9,9 @@ import { VersionBadge } from '/snippets/version-badge.mdx'<VersionBadge version="2.10.0" />-User elicitation allows MCP servers to request structured input from users during tool execution. Instead of requiring all inputs upfront, tools can interactively ask for missing parameters, clarification, or additional context as needed.+User elicitation allows MCP servers to request input from users during tool execution. Instead of requiring all inputs upfront, tools can interactively ask for missing parameters, clarification, or additional context as needed.-Elicitation enables tools to pause execution and request specific information from users:+Elicitation enables tools to request specific information from users mid-task:- **Missing parameters**: Ask for required information not provided initially- **Clarification requests**: Get user confirmation or choices for ambiguous scenarios@@ -20,9 +20,18 @@ Elicitation enables tools to pause execution and request specific information frFor example, a file management tool might ask "Which directory should I create?" or a data analysis tool might request "What date range should I analyze?"-## Overview+## Which approach to use-Use the `ctx.elicit()` method within any tool function to request user input. Specify the message to display and the type of response you expect.+Elicitation reaches the user two different ways, depending on the protocol era the connection negotiated:++- **On handshake-era connections (≤ 2025-11-25)**, a running tool calls [`ctx.elicit()`](#requesting-input-on-handshake-connections). The tool pauses mid-execution, the server sends a request over the session back-channel, and the tool resumes with the answer. This is the original elicitation API and the rest of this page's first half covers it in full.+- **On the modern protocol (2026-07-28)**, that back-channel is gone — server-initiated requests were removed from the wire (SEP-2577), so a tool cannot issue a request mid-execution and block on the answer. Instead a tool asks for input by *returning* a description of what it needs; each round completes normally and the client issues a new call with the answer attached. This is the [guard pattern](#elicitation-on-the-modern-protocol), covered in the second half.++The era gate is strict: `ctx.elicit()` only works on handshake connections, and the guard pattern only works on modern ones. A tool that returns a guard result on a handshake connection — or calls `ctx.elicit()` on a modern one — raises a clear era error rather than failing obscurely. A server that serves both eras may need both paths; branch on `ctx.protocol_version` to pick the right one. `fastmcp.Client` drives whichever the connection negotiated automatically.++## Requesting input on handshake connections++Use the `ctx.elicit()` method within any tool function to request user input on a handshake-era connection. Specify the message to display and the type of response you expect.```pythonfrom fastmcp import FastMCP, Context@@ -377,3 +386,193 @@ async def create_task(ctx: Context) -> str:```Default values are supported for strings, integers, numbers, booleans, and enums.++## Elicitation on the modern protocol++<VersionBadge version="4.0.0" />++The modern protocol (2026-07-28) removes the server-initiated back-channel that `ctx.elicit()` depends on (SEP-2577), so a running tool has no way to reach the user mid-execution. Elicitation reaches the user a different way: a tool asks for input by *returning* a description of what it needs. That return value completes the call normally — the result just happens to be an `InputRequiredResult` describing a request rather than a final answer. The client fulfils the request and issues a **new** tool call with the answer attached, and the tool runs again from the top, sees the answer, and either asks for the next thing or returns its final result.++Every round is a complete, independent request→response cycle: the tool holds no state between rounds, and nothing on the server stays alive waiting between them. That makes elicitation work on stateless, serverless, and load-balanced deployments where no two rounds are guaranteed to land on the same worker. A booking tool can ask for a destination, then a date, then confirm, across as many rounds as the work requires, without keeping a connection or a server-side session alive in between.++<Note>+This pattern requires an MCP **2026-07-28** connection. The `InputRequiredResult` result type does not exist on earlier protocol versions; a tool that returns one on a handshake-era connection raises a clear error (see [Protocol requirements](#protocol-requirements)). On those connections, use [`ctx.elicit()`](#requesting-input-on-handshake-connections) instead.+</Note>++### How it works++A tool that asks for input this way is a **guard**: each round it re-runs from the top, checks whether the answers it needs are present, and either asks for more or proceeds. Each of those rounds is an ordinary tool call that runs the full request path — middleware chain included — and returns a result like any other; the framework does not hold the call open between rounds. It inspects two request-scoped properties on the `Context` to decide what to do:++- `ctx.input_responses` — the client's answers to what you asked on a previous round. It is `None` on the very first round (nothing has been asked yet) and a mapping of answers on later rounds.+- `ctx.request_state` — a small opaque string you can carry from one round to the next. It is `None` on the first round and echoes back whatever you last put in `InputRequiredResult.request_state`.++To ask for input, return an `InputRequiredResult` whose `input_requests` map describes the requests to run — most commonly an elicitation. Each request has a key; the client's answer comes back under the same key in `ctx.input_responses`.++The following tool books a flight across three rounds: it asks for a destination, then asks for a date (carrying the destination forward), then confirms the booking.++```python+from fastmcp import FastMCP, Context+from fastmcp.types import InputRequiredResult, ElicitRequest, ElicitRequestFormParams++mcp = FastMCP("Booking Server")+++def ask(key: str, message: str, field: str, request_state: str | None = None) -> InputRequiredResult:+ """Build an InputRequiredResult that elicits a single text field."""+ params = ElicitRequestFormParams(+ message=message,+ requested_schema={+ "type": "object",+ "properties": {field: {"type": "string"}},+ "required": [field],+ },+ )+ elicitation = ElicitRequest(method="elicitation/create", params=params)+ return InputRequiredResult(+ result_type="input_required",+ input_requests={key: elicitation},+ request_state=request_state,+ )+++async def book_flight(ctx: Context) -> str | InputRequiredResult:+ responses = ctx.input_responses++ if responses is None:+ return ask("destination", "Where would you like to fly?", "destination")++ if "destination" in responses:+ destination = responses["destination"].content["destination"]+ return ask(+ "date",+ f"When would you like to fly to {destination}?",+ "date",+ request_state=f"dest={destination}",+ )++ destination = ctx.request_state.split("=", 1)[1]+ date = responses["date"].content["date"]+ return f"Booked a flight to {destination} on {date}"+```++The tool runs three times for one logical call. On the first run `ctx.input_responses` is `None`, so it asks for a destination. On the second run the destination is present, so it asks for a date and stashes the destination in `request_state`. On the third run the date is present, so it reads the destination back out of `ctx.request_state` and returns the booking. Each round is a fresh execution — the tool holds no state of its own between rounds; everything it needs travels on the request.++### Reading answers++Each value in `ctx.input_responses` is the client's result for one request, keyed by the key you gave it. For an elicitation, that is an `ElicitResult` with an `action` and (when accepted) `content`:++```python+async def confirm(ctx: Context) -> str:+ responses = ctx.input_responses+ if responses is None:+ return ask("ok", "Proceed?", "ok")++ answer = responses["ok"]+ if answer.action != "accept":+ return "Cancelled."+ return f"Proceeding with {answer.content['ok']}"+```++Always check `answer.action` before reading `answer.content`: a client may **decline** or **cancel**, in which case `content` is absent. A decline is a normal answer, not an error — it is delivered to your tool like any other round so you can handle it deliberately.++### Driving the loop from a client++`fastmcp.Client` drives the whole loop automatically. Point it at a 2026-era connection (`mode="auto"` negotiates one) and give it an elicitation handler; it fulfils each round's requests and retries until the tool returns its final result.++```python+from fastmcp import Client+from fastmcp.client.elicitation import ElicitResult+++async def handler(message, response_type, params, ctx):+ if "Where" in message:+ return ElicitResult(action="accept", content=response_type(destination="Paris"))+ return ElicitResult(action="accept", content=response_type(date="2026-08-01"))+++async with Client(mcp, mode="auto", elicitation_handler=handler) as client:+ result = await client.call_tool("book_flight", {})+ print(result.data) # "Booked a flight to Paris on 2026-08-01"+```++The client caps the number of rounds it will drive (`input_required_max_rounds`, default 10) so a misbehaving guard cannot loop forever; exceeding it raises an error rather than hanging.++### Carrying state across rounds++The `request_state` you return is **sealed by the framework** before it reaches the wire and **unsealed and verified** before your tool runs again. Your tool only ever mints and reads plaintext — the client receives an opaque token it cannot read, and a token that has been tampered with, has expired, or was minted by a different server is rejected before your tool sees it. You never call any crypto yourself.++Because sealing is automatic, `request_state` is a safe place to carry a computed value forward instead of re-deriving it each round. Keep it small — it round-trips through the client on every leg.++#### Multi-replica deployments++By default each server process seals under a per-process **ephemeral key**. That is correct for single-process deployments (stdio, one HTTP worker), but it means state minted by one process is rejected by another — so a horizontally scaled deployment, where consecutive rounds may land on different replicas, needs a **shared key**.++Give every replica the same key (or key ring) via `request_state_security`:++```python+import os+from fastmcp import FastMCP+from mcp.server.request_state import RequestStateSecurity++mcp = FastMCP(+ "Booking Server",+ request_state_security=RequestStateSecurity(keys=[os.environ["REQUEST_STATE_KEY"].encode()]),+)+```++Keys must be at least 32 bytes of secret randomness. `keys` is a rotation ring: `keys[0]` seals, and every key in the ring can unseal, so you can rotate without downtime by rolling `keys=[old, new]` → `keys=[new, old]` → `keys=[new]` across deployments. Generate a key with:++```bash+python -c "import secrets; print(secrets.token_hex(32))"+```++### Protocol requirements++The `InputRequiredResult` result type is part of MCP **2026-07-28** and does not exist on earlier protocol versions. If a tool returns one on a handshake-era (≤ 2025-11-25) connection, FastMCP rejects the call with a clear error naming the era mismatch rather than letting it fail as a generic invalid result:++```+Tool 'book_flight' returned an InputRequiredResult to request client input, but+the multi-round-trip result type (SEP-2322) only exists at MCP 2026-07-28; this+connection negotiated '2025-11-25'. Use ctx.elicit() for server-initiated input+on handshake-era connections.+```++If you need to support both eras, branch on `ctx.protocol_version`: return an `InputRequiredResult` on modern connections and fall back to [`ctx.elicit()`](#requesting-input-on-handshake-connections) on handshake-era ones.++### Sampling and roots++Elicitation is the most common request to carry this way, but the same mechanism carries **sampling** and **roots** requests too — the `input_requests` map can hold any of the three, and each answer comes back in `ctx.input_responses` under its key (an `ElicitResult`, `CreateMessageResult`, or `ListRootsResult`). See [Sampling](/servers/sampling) and [Client Roots](/clients/roots) for what those requests contain. `fastmcp.Client` answers all three from the handlers you already configured, so a guard tool that mixes them needs no extra client wiring.++### Middleware++Because each round is a complete request→response cycle, a multi-round tool call runs the **full middleware chain on every round**. `on_call_tool` fires once per round and `call_next(context)` returns that round's result like any other call — there is no held-open call and no special control flow to account for. Default middleware behaves sensibly with no changes: logging logs each round, timing times each round, and error-handling middleware does not fire on an asking round — an ask is a legitimate result, not an error.++An asking round returns an `InputRequiredToolResult` (a `ToolResult` subclass); the final round returns an ordinary `ToolResult`. Middleware that needs to treat the two differently identifies an ask with an `isinstance` check, and tells an initial round from a continuation round by inspecting `ctx.input_responses` (`None` on the first round, present once the client has answered):++```python+from fastmcp.server.middleware import Middleware+from fastmcp.tools import InputRequiredToolResult+++class GuardAwareMiddleware(Middleware):+ async def on_call_tool(self, context, call_next):+ ctx = context.fastmcp_context+ # Either signal marks a continuation: a state-only round carries+ # request_state with no answers, so it retries with input_responses=None.+ is_continuation = (+ ctx.input_responses is not None or ctx.request_state is not None+ )++ result = await call_next(context)++ if isinstance(result, InputRequiredToolResult):+ ... # this round asked the client for input+ else:+ ... # this round returned a final result++ return result+```++One built-in makes a deliberate exception: the [response caching middleware](/servers/middleware) never stores an `InputRequiredToolResult`, because caching an ask would replay a stale question to a later caller.diff --git a/docs/servers/sampling.mdx b/docs/servers/sampling.mdxindex d19a05c01..d77e3cb8c 100644--- a/docs/servers/sampling.mdx+++ b/docs/servers/sampling.mdx@@ -23,6 +23,10 @@ replacement on modern connections — this architectural shift is the intendedanswer.</Warning>+<Note>+This page covers `ctx.sample()`, which requests generation over the handshake-era back-channel. On the modern protocol (2026-07-28) a tool can instead request a sampling round from the client as part of a multi-round guard call — the same mechanism that carries elicitation. See [Elicitation on the modern protocol](/servers/elicitation#elicitation-on-the-modern-protocol) for how a guard tool returns `input_requests` and reads the answers back off `ctx.input_responses`.+</Note>+LLM sampling allows your MCP tools to request text generation from an LLM during execution. This enables tools to leverage AI capabilities for analysis, generation, reasoning, and more—without the client needing to orchestrate multiple calls.By default, sampling requests are routed to the client's LLM. You can also configure a fallback handler to use a specific provider (like OpenAI) when the client doesn't support sampling, or to always use your own LLM regardless of client capabilities.diff --git a/fastmcp_slim/fastmcp/server/context.py b/fastmcp_slim/fastmcp/server/context.pyindex e2c2f1977..ea4d2b228 100644--- a/fastmcp_slim/fastmcp/server/context.py+++ b/fastmcp_slim/fastmcp/server/context.py@@ -389,6 +389,57 @@ class Context:"""return fastmcp_request_ctx.get()+ def _input_response_params(+ self,+ ) -> mcp_types.InputResponseRequestParams | None:+ """The active request's multi-round-trip fields (SEP-2322), if any.++ Reads the raw params of the active wire request through the SDK's+ per-request context and reparses them as `InputResponseRequestParams`+ to recover the typed `input_responses` / `request_state`. The+ framework's request-state boundary has already unsealed `requestState`+ into plaintext by the time a handler observes it. Returns `None`+ outside a wire request (e.g. a background task) or when the params are+ not a mapping.+ """+ rc = self.request_context+ if rc is None:+ return None+ params = rc._srctx.params+ if not isinstance(params, Mapping):+ return None+ return mcp_types.InputResponseRequestParams.model_validate(dict(params))++ @property+ def input_responses(self) -> mcp_types.InputResponses | None:+ """Client responses to a prior `InputRequiredResult.input_requests`.++ The multi-round-trip guard channel (SEP-2322). A guard tool inspects+ this to decide what to do on each round: `None` on the initial round+ (nothing has been asked yet, or the client retried without responses),+ so the tool returns an `InputRequiredResult` to ask; present on a later+ round, so the tool reads the answers and proceeds. It is a mapping whose+ keys match the `input_requests` map the tool minted; each value is the+ client's result for that request (an `ElicitResult`, `CreateMessageResult`,+ or `ListRootsResult`).+ """+ params = self._input_response_params()+ return params.input_responses if params else None++ @property+ def request_state(self) -> str | None:+ """Opaque state echoed from a prior `InputRequiredResult.request_state`.++ The multi-round-trip guard channel (SEP-2322): whatever a tool put in+ `InputRequiredResult.request_state` on an earlier round is handed back+ here (as plaintext — the framework seals it on the wire and unseals it+ before the tool runs, so tampering is rejected before this is read).+ `None` on the initial round. Use it to carry a small amount of computed+ state across rounds without re-deriving it.+ """+ params = self._input_response_params()+ return params.request_state if params else None+@propertydef lifespan_context(self) -> dict[str, Any]:"""Access the server's lifespan context.diff --git a/fastmcp_slim/fastmcp/server/low_level.py b/fastmcp_slim/fastmcp/server/low_level.pyindex 5267b1c66..0c3fe5b7e 100644--- a/fastmcp_slim/fastmcp/server/low_level.py+++ b/fastmcp_slim/fastmcp/server/low_level.py@@ -21,6 +21,7 @@ from mcp.server.lowlevel.server import (Server as _Server,)from mcp.server.models import InitializationOptions+from mcp.server.request_state import RequestStateBoundary, RequestStateSecurityfrom mcp.server.session import ServerSessionfrom mcp.server.stdio import stdio_server as stdio_serverfrom mcp.shared.exceptions import MCPError@@ -256,6 +257,23 @@ class LowLevelServer(_Server[LifespanResultT]):cast("ServerMiddleware[LifespanResultT]", FastMCPServerMiddleware(fastmcp)))+ # Install the SDK's request-state boundary (SEP-2322): it seals every+ # outgoing `InputRequiredResult.request_state` at the wire and unseals+ # every inbound echo *before* any handler runs, so tool bodies only ever+ # see plaintext `ctx.request_state`. Mirrors `MCPServer.__init__`. When+ # the server was constructed without an explicit `request_state_security`+ # policy, seal under a per-process ephemeral key (single-process+ # deployments); multi-replica deployments pass a shared-key policy. The+ # low-level server always has a name (FastMCP autogenerates one), so the+ # audience claim is always populated.+ security = fastmcp._request_state_security or RequestStateSecurity.ephemeral()+ self.middleware.append(+ cast(+ "ServerMiddleware[LifespanResultT]",+ RequestStateBoundary(security, default_audience=self.name),+ )+ )+@propertydef fastmcp(self) -> FastMCP:"""Get the FastMCP instance."""diff --git a/fastmcp_slim/fastmcp/server/middleware/caching.py b/fastmcp_slim/fastmcp/server/middleware/caching.pyindex d30f4b814..92fd7f277 100644--- a/fastmcp_slim/fastmcp/server/middleware/caching.py+++ b/fastmcp_slim/fastmcp/server/middleware/caching.py@@ -22,7 +22,7 @@ from fastmcp.prompts.base import Message, Prompt, PromptResultfrom fastmcp.resources.base import Resource, ResourceContent, ResourceResultfrom fastmcp.server.dependencies import get_access_tokenfrom fastmcp.server.middleware.middleware import CallNext, Middleware, MiddlewareContext-from fastmcp.tools.base import Tool, ToolResult+from fastmcp.tools.base import InputRequiredToolResult, Tool, ToolResultfrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.types import FastMCPBaseModel@@ -413,6 +413,21 @@ class ResponseCachingMiddleware(Middleware):) is False or not self._matches_tool_cache_settings(tool_name=tool_name):return await call_next(context)+ # A multi-round continuation leg (SEP-2322) must bypass the cache+ # entirely: the cache key is built from the tool name and arguments+ # only, so a continuation shares its key with a fresh call. Reading+ # could serve a prior flow's final answer to this leg; writing would+ # serve THIS flow's final answer to a later fresh call — which would+ # then never be asked the tool's questions. Either signal marks a+ # continuation: a state-only round (request_state with no questions)+ # retries with input_responses=None but still carries request_state.+ fastmcp_ctx = context.fastmcp_context+ if fastmcp_ctx is not None and (+ fastmcp_ctx.input_responses is not None+ or fastmcp_ctx.request_state is not None+ ):+ return await call_next(context)+cache_key: str = _make_call_tool_cache_key(msg=context.message, auth_key=_get_auth_partition_key())@@ -421,6 +436,15 @@ class ResponseCachingMiddleware(Middleware):return cached_value.unwrap()tool_result: ToolResult = await call_next(context)++ # Never cache a multi-round-trip ask (SEP-2322). An+ # InputRequiredToolResult is a request for client input on this leg, not+ # a stable answer; caching it would replay a stale question to later+ # callers and bypass the tool's own per-round logic. Return it straight+ # through without storing.+ if isinstance(tool_result, InputRequiredToolResult):+ return tool_result+cacheable_tool_result: CacheableToolResult = CacheableToolResult.wrap(value=tool_result)diff --git a/fastmcp_slim/fastmcp/server/middleware/response_limiting.py b/fastmcp_slim/fastmcp/server/middleware/response_limiting.pyindex 32f08c056..204559f59 100644--- a/fastmcp_slim/fastmcp/server/middleware/response_limiting.py+++ b/fastmcp_slim/fastmcp/server/middleware/response_limiting.py@@ -9,7 +9,7 @@ import mcp_types as mtimport pydantic_corefrom mcp_types import TextContent-from fastmcp.tools.base import ToolResult+from fastmcp.tools.base import InputRequiredToolResult, ToolResultfrom .middleware import CallNext, Middleware, MiddlewareContext@@ -110,6 +110,14 @@ class ResponseLimitingMiddleware(Middleware):"""Intercept tool calls and limit response size."""result = await call_next(context)+ # A multi-round-trip ask (SEP-2322) carries no tool content to measure,+ # and truncating it would collapse the InputRequiredToolResult into a+ # plain ToolResult — the wire handler would then serialize the ask as+ # content instead of returning it as an input-required result. Pass it+ # through untouched.+ if isinstance(result, InputRequiredToolResult):+ return result+# Check if we should limit this toolif self.tools is not None and context.message.name not in self.tools:return resultdiff --git a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.pyindex 74e59ae8f..355ec0734 100644--- a/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py+++ b/fastmcp_slim/fastmcp/server/mixins/mcp_operations.py@@ -17,6 +17,7 @@ from mcp_types import (ReadResourceRequestParams,SetLevelRequestParams,)+from mcp_types.version import MODERN_PROTOCOL_VERSIONSfrom fastmcp.exceptions import (DisabledError,@@ -26,6 +27,7 @@ from fastmcp.exceptions import ()from fastmcp.server.dependencies import bind_request_context, extract_version_specfrom fastmcp.server.tasks.config import TaskMeta+from fastmcp.tools.base import InputRequiredToolResultfrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.pagination import paginate_sequencefrom fastmcp.utilities.versions import VersionSpec, dedupe_with_versions@@ -211,12 +213,27 @@ class MCPOperationsMixin:self: FastMCP,ctx: ServerRequestContext,params: CallToolRequestParams,- ) -> mcp_types.CallToolResult | mcp_types.CreateTaskResult:+ ) -> (+ mcp_types.CallToolResult+ | mcp_types.InputRequiredResult+ | mcp_types.CreateTaskResult+ ):"""Handle MCP 'tools/call' requests.Task metadata is a first-class params field (``params.task``); itspresence triggers backgrounding. The tool's ``_run()`` handles thebackgrounding decision so middleware runs before Docket.++ A guard tool (SEP-2322 multi-round-trip) requests client input by+ returning an ``InputRequiredResult`` from its body; the run machinery+ wraps that in an ``InputRequiredToolResult`` (a ``ToolResult``+ subclass), which flows back through the middleware chain as an ordinary+ result. Here we unwrap it and hand the raw ``InputRequiredResult`` to+ the runner so it reaches the wire as ``resultType: "input_required"``+ (the request-state boundary seals its ``requestState`` on egress). This+ result shape only exists at 2026-07-28; on an earlier connection the+ runner cannot serialize it, so we reject with a clear era error rather+ than let it fail as a generic "invalid result"."""with bind_request_context(ctx):key = params.name@@ -258,6 +275,23 @@ class MCPOperationsMixin:if isinstance(result, mcp_types.CreateTaskResult):return result+ if isinstance(result, InputRequiredToolResult):+ # A guard tool requested client input (SEP-2322). The+ # multi-round-trip result type only exists at 2026-07-28; on an+ # earlier connection the runner cannot serialize it, so name the+ # era problem instead of failing as a generic "invalid result".+ if ctx.protocol_version not in MODERN_PROTOCOL_VERSIONS:+ raise MCPError(+ code=INVALID_PARAMS,+ message=(+ f"Tool {key!r} returned an InputRequiredResult to request "+ "client input, but the multi-round-trip result type "+ "(SEP-2322) only exists at MCP 2026-07-28; this connection "+ f"negotiated {ctx.protocol_version!r}. Use ctx.elicit() for "+ "server-initiated input on handshake-era connections."+ ),+ )+ return result.input_requiredreturn _normalize_call_tool_result(result.to_mcp_result())async def _on_read_resource(diff --git a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.pyindex 27787d2ef..0f05c798e 100644--- a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py@@ -103,7 +103,9 @@ class FastMCPProviderTool(Tool):Passes task_meta through to the child server so it can handlebackgrounding appropriately. fn_key is already set by the parent- server before calling this method.+ server before calling this method. A child tool that requests client+ input (SEP-2322) returns an `InputRequiredToolResult`, which forwards+ through this delegation to the parent's wire handler unchanged."""# Pass exact version so child executes the correct versionversion = VersionSpec(eq=self.version) if self.version else None@@ -133,7 +135,7 @@ class FastMCPProviderTool(Tool):result = await self._server.call_tool(self._original_name, arguments, version=version)- # Result from call_tool should always be ToolResult when no task_meta+ # Result from call_tool should always be ToolResult when no task_meta.if isinstance(result, mcp_types.CreateTaskResult):raise RuntimeError("Unexpected CreateTaskResult from call_tool without task_meta"diff --git a/fastmcp_slim/fastmcp/server/providers/proxy.py b/fastmcp_slim/fastmcp/server/providers/proxy.pyindex 72f48040f..ae5d81780 100644--- a/fastmcp_slim/fastmcp/server/providers/proxy.py+++ b/fastmcp_slim/fastmcp/server/providers/proxy.py@@ -25,6 +25,7 @@ from mcp_types import (ElicitRequestFormParams,TextResourceContents,)+from mcp_types.version import MODERN_PROTOCOL_VERSIONSfrom pydantic.networks import AnyUrlfrom fastmcp.client.client import Client, SDKServer@@ -48,7 +49,8 @@ from fastmcp.server.providers.aggregate import ProviderErrorStrategyfrom fastmcp.server.providers.base import Providerfrom fastmcp.server.server import FastMCPfrom fastmcp.server.tasks.config import TaskConfig-from fastmcp.tools.base import Tool, ToolResult+from fastmcp.telemetry import inject_trace_context+from fastmcp.tools.base import InputRequiredToolResult, Tool, ToolResultfrom fastmcp.utilities.components import FastMCPComponent, get_fastmcp_metadatafrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.versions import VersionSpec, version_sort_key@@ -228,19 +230,57 @@ class ProxyTool(Tool):dict(req_ctx.meta) if req_ctx is not None and req_ctx.meta else None)- result = await client.call_tool_mcp(- name=backend_name, arguments=arguments, meta=meta- )+ if client.protocol_version in MODERN_PROTOCOL_VERSIONS:+ # Modern backend: call the session directly (not+ # `call_tool_mcp`, which would *drive* a multi-round-trip ask+ # to completion on this proxy). A guard tool's+ # `InputRequiredResult` (SEP-2322) must instead surface as a+ # result so the parent's middleware and wire seam own the+ # round. Forward the inbound request's continuation state+ # down so the backend guard tool sees the client's answers+ # on its own `ctx.input_responses` / `ctx.request_state`.+ request_meta = cast(+ "mcp_types.RequestParamsMeta | None",+ inject_trace_context(meta) or None,+ )+ result = await client._await_with_session_monitoring(+ client.session.call_tool(+ name=backend_name,+ arguments=arguments,+ meta=request_meta,+ # Forward upstream progress the same way the legacy+ # `call_tool_mcp` path does — without this handler a+ # backend tool's `ctx.report_progress()` is dropped+ # on modern proxy calls.+ progress_callback=client._progress_handler,+ input_responses=ctx.input_responses,+ request_state=ctx.request_state,+ allow_input_required=True,+ )+ )+ # A backend ask round-trips into an InputRequiredToolResult+ # so the parent's middleware observes it and the parent's+ # wire handler unwraps it (era-gated on the parent's own+ # connection).+ if isinstance(result, mcp_types.InputRequiredResult):+ return InputRequiredToolResult(result)+ tool_result = cast("mcp_types.CallToolResult", result)+ else:+ # Legacy backend: the multi-round-trip result type does not+ # exist there, so keep the original path.+ tool_result = await client.call_tool_mcp(+ name=backend_name, arguments=arguments, meta=meta+ )# Pass an upstream error result through faithfully rather than# collapsing it into a raised ToolError — this preserves the# backend's content (including non-text and structured content),# and the client still raises on isError by default.# Preserve backend's meta (includes task metadata for background tasks)return ToolResult(- content=result.content,- structured_content=result.structured_content,- meta=result.meta,- is_error=result.is_error,+ content=tool_result.content,+ structured_content=tool_result.structured_content,+ meta=tool_result.meta,+ is_error=tool_result.is_error,)def get_span_attributes(self) -> dict[str, Any]:@@ -825,6 +865,8 @@ def _create_client_factory(| dict[str, Any]| str),+ *,+ mode: str | None = None,) -> ClientFactoryT:"""Create a client factory from the given target.@@ -872,7 +914,8 @@ def _create_client_factory(return fresh_client_factoryelse:# target is not a Client, so it's compatible with ProxyClient.__init__- base_client = ProxyClient(cast(Any, target))+ client_kwargs: dict[str, Any] = {} if mode is None else {"mode": mode}+ base_client = ProxyClient(cast(Any, target), **client_kwargs)def proxy_client_factory() -> Client:return base_client.new()@@ -1135,6 +1178,13 @@ class ProxyClient(Client[ClientTransportT]):):if "name" not in kwargs:kwargs["name"] = self.generate_name()+ # ProxyClient defaults to the handshake era: a dual-era backend serves+ # both, and a single proxy session can only be one era. Handshake keeps+ # the server-initiated push forwarding (sampling / elicitation / roots,+ # via the handlers installed below) that proxies rely on. To round-trip+ # an upstream guard tool's InputRequiredResult (SEP-2322) instead, opt+ # into the modern era explicitly with `create_proxy(target, mode="auto")`+ # — the two are mutually exclusive per session.# Install context-restoring handler wrappers BEFORE super().__init__# registers them with the Client's session kwargs.self._proxy_rc_ref = [None]diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.pyindex 13ad8e8d1..b40b8ac61 100644--- a/fastmcp_slim/fastmcp/server/server.py+++ b/fastmcp_slim/fastmcp/server/server.py@@ -25,6 +25,7 @@ from key_value.aio.adapters.pydantic import PydanticAdapterfrom key_value.aio.protocols import AsyncKeyValuefrom key_value.aio.stores.memory import MemoryStorefrom mcp.server.lowlevel.server import LifespanResultT+from mcp.server.request_state import RequestStateSecurityfrom mcp.shared.exceptions import MCPErrorfrom mcp_types import (Annotations,@@ -343,6 +344,7 @@ class FastMCP(strict_input_validation: bool | None = None,list_page_size: int | None = None,resource_security: ResourceSecurity | None = DEFAULT_RESOURCE_SECURITY,+ request_state_security: RequestStateSecurity | None = None,cache_ttl: int | None = None,cache_scope: Literal["public", "private"] | None = None,tasks: bool | None = None,@@ -410,6 +412,36 @@ class FastMCP(# server-wide.self._resource_security: ResourceSecurity | None = resource_security+ # Server-level integrity policy for the multi-round-trip `requestState`+ # (SEP-2322). Consumed by the low-level server, which installs the SDK's+ # `RequestStateBoundary` middleware to seal every outgoing+ # `InputRequiredResult.request_state` and unseal every inbound echo.+ # None means "seal under a per-process ephemeral key" — correct for+ # single-process deployments; multi-replica deployments must pass a+ # policy carrying shared `keys=[...]`.+ if (+ request_state_security is not None+ and request_state_security.audience is None+ and not name # None or "" both yield a random per-replica name+ ):+ # The request-state boundary stamps an audience claim, defaulting to+ # the server name — which is auto-generated (random) when unnamed, so+ # a shared-key multi-replica policy would mint tokens no other+ # replica accepts. A policy object can't reveal whether its keys are+ # shared (ephemeral and shared-key policies both collapse into a+ # codec), so single-process customization stays allowed and the+ # multi-replica footgun is a warning, not an error.+ logger.warning(+ "request_state_security was provided without an audience on an "+ "unnamed server; if this policy's keys are shared across "+ "replicas, sealed request state will not verify between them. "+ "Pass FastMCP(name=...) or RequestStateSecurity(audience=...) "+ "for a stable audience."+ )+ self._request_state_security: RequestStateSecurity | None = (+ request_state_security+ )+# Server-level SEP-2549 cache hints, applied uniformly to every# SDK-cacheable result by the low-level server's runner (raises on# invalid ttl/scope).@@ -1223,6 +1255,11 @@ class FastMCP(ToolResult when task_meta is None.CreateTaskResult when task_meta is provided.+ A guard tool that requests client input (SEP-2322 multi-round-trip)+ returns an ``InputRequiredToolResult`` (a ``ToolResult`` subclass); it+ flows back through the middleware chain as an ordinary result and the+ wire handler unwraps it into an ``InputRequiredResult`` on the response.+Raises:NotFoundError: If tool not found or disabledToolError: If tool execution fails@@ -1250,6 +1287,14 @@ class FastMCP(message=mcp_types.CallToolRequestParams(name=name,arguments=arguments or {},+ # Reflect the continuation fields (SEP-2322) so middleware+ # reading `context.message` sees a continuation round as+ # such, not as an initial call. These are recovered from+ # the raw wire request (unsealed to plaintext by the+ # request-state boundary); they drive middleware+ # visibility only — `call_next` routes on name/arguments.+ input_responses=ctx.input_responses,+ request_state=ctx.request_state,_meta=_version_request_meta(version),),source="client",@@ -2318,6 +2363,8 @@ def create_proxy(| dict[str, Any]| str),+ *,+ mode: str | None = None,**settings: Any,) -> FastMCPProxy:"""Create a FastMCP proxy server for the given target.@@ -2333,6 +2380,11 @@ def create_proxy(- A URL string or AnyUrl- A Path to a server script- An MCPConfig or dict+ mode: Protocol-era negotiation for auto-created proxy clients (a+ non-Client target). Defaults to the handshake era; pass+ `"auto"` to negotiate the modern era so an upstream guard+ tool's `InputRequiredResult` (SEP-2322) round-trips. Ignored+ when `target` is already a `Client` (which carries its own mode).**settings: Additional settings passed to FastMCPProxy (name, etc.)Returns:@@ -2354,7 +2406,7 @@ def create_proxy(_create_client_factory,)- client_factory = _create_client_factory(target)+ client_factory = _create_client_factory(target, mode=mode)return FastMCPProxy(client_factory=client_factory,**settings,diff --git a/fastmcp_slim/fastmcp/server/tasks/requests.py b/fastmcp_slim/fastmcp/server/tasks/requests.pyindex 0cbc77aca..d04d1f25d 100644--- a/fastmcp_slim/fastmcp/server/tasks/requests.py+++ b/fastmcp_slim/fastmcp/server/tasks/requests.py@@ -30,7 +30,7 @@ from fastmcp.resources.template import ResourceTemplatefrom fastmcp.server.tasks.config import DEFAULT_POLL_INTERVAL_MS, DEFAULT_TTL_MSfrom fastmcp.server.tasks.context import get_task_scopefrom fastmcp.server.tasks.keys import parse_task_key, task_redis_prefix-from fastmcp.tools.base import Tool+from fastmcp.tools.base import InputRequiredToolResult, Toolfrom fastmcp.utilities.versions import VersionSpecif TYPE_CHECKING:@@ -336,6 +336,19 @@ async def tasks_result_handler(server: FastMCP, params: dict[str, Any]) -> Any:# Each branch merges related_task_meta with any existing _meta# (e.g. fastmcp.wrap_result) rather than overwriting it.if isinstance(component, Tool):+ if isinstance(+ raw_value, mcp_types.InputRequiredResult | InputRequiredToolResult+ ):+ raise MCPError(+ code=INTERNAL_ERROR,+ message=(+ f"Tool {component_key!r} requested input while running as a "+ "background task. Input-required (multi-round-trip) tools "+ "need a live request to answer the prompt and cannot run as "+ "tasks; remove task execution from this tool or the code path "+ "that returns an InputRequiredResult."+ ),+ )fastmcp_result = component.convert_result(raw_value)mcp_result = fastmcp_result.to_mcp_result()if isinstance(mcp_result, mcp_types.CallToolResult):diff --git a/fastmcp_slim/fastmcp/tools/__init__.py b/fastmcp_slim/fastmcp/tools/__init__.pyindex 64360b2aa..45a3f74ad 100644--- a/fastmcp_slim/fastmcp/tools/__init__.py+++ b/fastmcp_slim/fastmcp/tools/__init__.py@@ -1,7 +1,7 @@import sysfrom .function_tool import FunctionTool, tool-from .base import Tool, ToolResult+from .base import InputRequiredToolResult, Tool, ToolResultfrom .tool_transform import forward, forward_raw# Backward compat: tool.py was renamed to base.py to stop Pyright from resolving@@ -12,6 +12,7 @@ sys.modules[f"{__name__}.tool"] = sys.modules[f"{__name__}.base"]__all__ = ["FunctionTool",+ "InputRequiredToolResult","Tool","ToolResult","forward",diff --git a/fastmcp_slim/fastmcp/tools/base.py b/fastmcp_slim/fastmcp/tools/base.pyindex 011cacd27..9a5f9c6a2 100644--- a/fastmcp_slim/fastmcp/tools/base.py+++ b/fastmcp_slim/fastmcp/tools/base.py@@ -171,6 +171,44 @@ class ToolResult(BaseModel):return self.content, self.structured_content+class InputRequiredToolResult(ToolResult):+ """The full result of a single multi-round-trip leg (SEP-2322).++ The protocol is stateless: each MRTR leg is a complete request→response+ cycle. When a guard tool returns an `InputRequiredResult` from its body to+ ask the client for input, that ask is the *legitimate result* of this tool+ call — not a pause, not an error, not a third control-flow outcome. FastMCP+ wraps it in this `ToolResult` subclass so it flows through the middleware+ chain as an ordinary return value: `call_next(...)` returns it, default+ middleware completes normally on the leg, and middleware authors can+ identify an ask with a simple `isinstance(result, InputRequiredToolResult)`+ check.++ Invariant: the wrapped `InputRequiredResult` is never serialized as tool+ content. `content` is always empty; the wire handler (`_on_call_tool`)+ reads `.input_required` and returns it to the runner as the+ `input_required` result. Do not read `.content` / `.structured_content` on+ this subclass — they carry nothing.+ """++ input_required: mcp_types.InputRequiredResult = Field(+ description="The client-input request this leg resolved to (SEP-2322)"+ )++ def __init__(self, input_required: mcp_types.InputRequiredResult) -> None:+ # Bypass ToolResult's content-conversion __init__: an input-required+ # leg carries no tool content (see the invariant above), and+ # `input_required` is a required field ToolResult.__init__ can't set.+ BaseModel.__init__(+ self,+ content=[],+ structured_content=None,+ meta=None,+ is_error=False,+ input_required=input_required,+ )++class Tool(FastMCPComponent):"""Internal tool registration info."""@@ -290,6 +328,12 @@ class Tool(FastMCPComponent):`run()` can EITHER return a list of ContentBlocks, or a tuple of(list of ContentBlocks, dict of structured output).++ A tool that requests client input (SEP-2322 multi-round-trip) does so by+ returning an `InputRequiredResult` from its body; the run machinery wraps+ that in an `InputRequiredToolResult` — a `ToolResult` subclass — so it+ stays inside the declared `ToolResult` result type and flows through the+ middleware chain as an ordinary result (see `FunctionTool.run`)."""raise NotImplementedError("Subclasses must implement run()")@@ -590,4 +634,4 @@ def _convert_to_content(return [TextContent(type="text", text=default_serializer(result))]-__all__ = ["Tool", "ToolResult"]+__all__ = ["InputRequiredToolResult", "Tool", "ToolResult"]diff --git a/fastmcp_slim/fastmcp/tools/function_parsing.py b/fastmcp_slim/fastmcp/tools/function_parsing.pyindex 79967f9a2..5d43de2a2 100644--- a/fastmcp_slim/fastmcp/tools/function_parsing.py+++ b/fastmcp_slim/fastmcp/tools/function_parsing.py@@ -11,6 +11,7 @@ from typing import Annotated, Any, Generic, Union, get_args, get_origin, get_typimport mcp_typesfrom pydantic import BaseModel, PydanticSchemaGenerationError+from typing_extensions import TypeAliasTypefrom typing_extensions import TypeVar as TypeVarExtfrom fastmcp.tools.base import ToolResult, resolve_serialize_by_alias@@ -55,6 +56,103 @@ def _contains_prefab_type(tp: Any) -> bool:return False+def _unwrap_type_alias(tp: Any) -> Any:+ """Resolve a PEP 695 ``type X = ...`` alias to its underlying value.++ ``get_origin()`` returns ``None`` for a ``TypeAliasType``, so an alias that+ factors out a guard union (``type Result = str | InputRequiredResult``) — or+ a lone aliased arm — would otherwise slip past union detection. Resolving to+ ``__value__`` (repeatedly, for chained aliases) restores the concrete type.+ """+ while isinstance(tp, TypeAliasType):+ tp = tp.__value__+ return tp+++def _is_input_required_type(tp: Any) -> bool:+ """True when *tp* is the `InputRequiredResult` type (SEP-2322).++ Resolves a `TypeAliasType` and peels an `Annotated` wrapper first, so an+ aliased arm or a metadata-carrying arm such as+ ``Annotated[InputRequiredResult, Field(...)]`` is recognized as a guard+ signal, not just the bare class.+ """+ tp = _unwrap_type_alias(tp)+ if get_origin(tp) is Annotated:+ tp = _unwrap_type_alias(get_args(tp)[0])+ return isinstance(tp, type) and issubclass(tp, mcp_types.InputRequiredResult)+++def _contains_input_required(tp: Any) -> bool:+ """True when `InputRequiredResult` appears anywhere in *tp*.++ Recurses through `TypeAliasType`, `Annotated`, and unions so a guard arm is+ found even when factored through a composed alias (``str | Value`` where+ ``Value = int | InputRequiredResult``).+ """+ tp = _unwrap_type_alias(tp)+ if _is_input_required_type(tp):+ return True+ origin = get_origin(tp)+ if origin is Union or origin is types.UnionType or origin is Annotated:+ return any(_contains_input_required(a) for a in get_args(tp))+ return False+++def _residual_union_arms(tp: Any) -> list[Any]:+ """Flatten a (possibly aliased/nested) union into its non-guard arms.++ Every `InputRequiredResult` arm is dropped at any depth, and aliased union+ arms are flattened inline so the residual is a flat union of data arms.+ """+ arms: list[Any] = []+ for arm in get_args(_unwrap_type_alias(tp)):+ if _is_input_required_type(arm):+ continue+ unwrapped = _unwrap_type_alias(arm)+ arm_origin = get_origin(unwrapped)+ if arm_origin is Union or arm_origin is types.UnionType:+ arms.extend(_residual_union_arms(unwrapped))+ elif arm_origin is Annotated:+ arms.append(_strip_input_required(arm))+ else:+ arms.append(arm)+ return arms+++def _strip_input_required(tp: Any) -> Any:+ """Remove `InputRequiredResult` arms from a union return annotation.++ A guard tool typically annotates its return as ``X | InputRequiredResult``;+ the ``InputRequiredResult`` arm is a suspend signal, not output data, so it+ is dropped before schema derivation. Stripping recurses through+ `TypeAliasType` and nested unions, so a guard arm factored through an alias+ (even ``str | Value`` where ``Value = int | InputRequiredResult``) is still+ removed. A non-union annotation, or one with no such arm, is returned+ unchanged. A bare ``InputRequiredResult`` annotation (no other arm) is left+ intact and suppressed downstream like other non-serializable return types.+ """+ if not _contains_input_required(tp):+ return tp+ unwrapped = _unwrap_type_alias(tp)+ origin = get_origin(unwrapped)+ if origin is Annotated:+ # Annotated[X | InputRequiredResult, meta] — strip inside, keep metadata.+ inner, *metadata = get_args(unwrapped)+ return Annotated[(_strip_input_required(inner), *metadata)]+ if origin is not Union and origin is not types.UnionType:+ # A bare InputRequiredResult (possibly via a `type X = ...` alias): left+ # intact, but returned de-aliased so the downstream subclass/exact-type+ # suppression recognizes it and emits no output schema.+ return unwrapped+ residual = _residual_union_arms(unwrapped)+ if not residual:+ return tp+ if len(residual) == 1:+ return residual[0]+ return Union[tuple(residual)] # noqa: UP007++def _unwrap_model(tp: Any) -> type[BaseModel] | None:"""Unwrap ``Annotated`` and return the underlying Pydantic model, if any."""if get_origin(tp) is Annotated:@@ -270,6 +368,13 @@ class ParsedFunction:# Save original for return_type before any schema-related replacementoriginal_output_type = output_type+ # An `InputRequiredResult` return arm (SEP-2322 guard tools) is a+ # control-flow signal, not data: strip it so the residual arms drive+ # output-schema derivation (mirrors the SDK's func_metadata). The tool+ # body still returns it at runtime; the tool pipeline passes it through+ # to the wire without touching the output schema.+ output_type = _strip_input_required(output_type)+if output_type not in (inspect._empty, None, Any, ...):# bytes can't be represented as structured JSON output — skip schemaif _contains_bytes_type(output_type):@@ -288,6 +393,15 @@ class ParsedFunction:if is_class_member_of_type(output_type, ToolResult):output_type = _UnserializableType+ # If InputRequiredResult survives stripping in any wrapping — bare,+ # via a `type X = ...` alias, Annotated, or a subclass — it is a+ # guard-only return with no output data (a union would have had its+ # guard arms stripped above). Suppress the schema wholesale; matching+ # `run()`'s subclass-aware control handling and covering every alias+ # shape that exact-match replace_type below would miss.+ if _contains_input_required(output_type):+ output_type = _UnserializableType+# there are a variety of types that we don't want to attempt to# serialize because they are either used by FastMCP internally,# or are MCP content types that explicitly don't form structured@@ -306,6 +420,9 @@ class ParsedFunction:mcp_types.AudioContent,mcp_types.ResourceLink,mcp_types.EmbeddedResource,+ # A guard tool's suspend signal is control flow, not+ # output data (any residual bare arm is suppressed).+ mcp_types.InputRequiredResult,*_PREFAB_TYPES,),_UnserializableType,diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.pyindex dd4c236e1..70719d3f9 100644--- a/fastmcp_slim/fastmcp/tools/function_tool.py+++ b/fastmcp_slim/fastmcp/tools/function_tool.py@@ -23,6 +23,7 @@ from typing import ()import anyio+import mcp_typesfrom mcp.shared.exceptions import MCPErrorfrom mcp_types import Icon, ToolAnnotationsfrom pydantic import Field, TypeAdapter@@ -32,6 +33,7 @@ from pydantic.json_schema import SkipJsonSchemafrom fastmcp.decorators import get_fastmcp_metafrom fastmcp.exceptions import ValidationErrorfrom fastmcp.tools.base import (+ InputRequiredToolResult,Tool,ToolResult,)@@ -369,7 +371,15 @@ class FunctionTool(Tool):)async def run(self, arguments: dict[str, Any]) -> ToolResult:- """Run the tool with arguments."""+ """Run the tool with arguments.++ A tool body may return an `InputRequiredResult` (SEP-2322) to ask the+ client for input. Under the stateless multi-round-trip protocol that ask+ is the full result of this leg, so it is wrapped in an+ `InputRequiredToolResult` (a `ToolResult` subclass) rather than+ serialized as content; the ask flows through the middleware chain as an+ ordinary result and the wire handler returns it to the client unmodified.+ """from fastmcp.server.dependencies import without_injected_parameterswrapper_fn = without_injected_parameters(@@ -418,6 +428,14 @@ class FunctionTool(Tool):assert original is not Noneraise original from original.__cause__+ # An `InputRequiredResult` is the full result of this multi-round-trip+ # leg (SEP-2322), not tool-output data: wrap it in an+ # `InputRequiredToolResult` so it flows through the middleware chain as+ # an ordinary result instead of being serialized as content. The wire+ # handler reads it back out (see `_on_call_tool`).+ if isinstance(result, mcp_types.InputRequiredResult):+ return InputRequiredToolResult(result)+return self.convert_result(result)async def _execute(diff --git a/fastmcp_slim/fastmcp/tools/tool_transform.py b/fastmcp_slim/fastmcp/tools/tool_transform.pyindex 425a970b3..910b89262 100644--- a/fastmcp_slim/fastmcp/tools/tool_transform.py+++ b/fastmcp_slim/fastmcp/tools/tool_transform.py@@ -7,6 +7,7 @@ from copy import deepcopyfrom dataclasses import dataclassfrom typing import Annotated, Any, Literal, cast+import mcp_typesimport pydantic_corefrom mcp_types import ToolAnnotationsfrom pydantic import ConfigDict@@ -15,6 +16,7 @@ from pydantic.functional_validators import BeforeValidatorfrom pydantic.json_schema import SkipJsonSchemafrom fastmcp.tools.base import (+ InputRequiredToolResult,Tool,ToolResult,_convert_to_content,@@ -323,6 +325,16 @@ class TransformedTool(Tool):if inspect.isawaitable(result):result = await result+ # A multi-round-trip ask (SEP-2322) is not output data: it must+ # reach the wire handler intact, never reshaped by output_schema+ # (which would rebuild it as a plain empty ToolResult and drop the+ # input_required payload). A custom transform fn may return the raw+ # `InputRequiredResult`, like any tool body; wrap it the same way.+ if isinstance(result, InputRequiredToolResult):+ return result+ if isinstance(result, mcp_types.InputRequiredResult):+ return InputRequiredToolResult(result)+# If transform function returns ToolResult, respect our output_schema settingif isinstance(result, ToolResult):if self.output_schema is None:diff --git a/fastmcp_slim/fastmcp/types.py b/fastmcp_slim/fastmcp/types.pyindex 4b33e7cb2..c1b95322d 100644--- a/fastmcp_slim/fastmcp/types.py+++ b/fastmcp_slim/fastmcp/types.py@@ -43,6 +43,12 @@ from mcp_types import (from mcp_types import (CreateMessageResult as CreateMessageResult,)+from mcp_types import (+ ElicitRequest as ElicitRequest,+)+from mcp_types import (+ ElicitRequestFormParams as ElicitRequestFormParams,+)from mcp_types import (EmbeddedResource as EmbeddedResource,)@@ -58,6 +64,9 @@ from mcp_types import (from mcp_types import (ImageContent as ImageContent,)+from mcp_types import (+ InputRequiredResult as InputRequiredResult,+)from mcp_types import (Prompt as Prompt,)@@ -117,11 +126,14 @@ __all__ = ["Completion","ContentBlock","CreateMessageResult",+ "ElicitRequest",+ "ElicitRequestFormParams","EmbeddedResource","ErrorData","GetPromptResult","Icon","ImageContent",+ "InputRequiredResult","Prompt","PromptMessage","ReadResourceResult",diff --git a/tests/server/test_mrtr_guards.py b/tests/server/test_mrtr_guards.pynew file mode 100644index 000000000..e574b20ca--- /dev/null+++ b/tests/server/test_mrtr_guards.py@@ -0,0 +1,1015 @@+"""Server-side guard-mode multi-round-trip (MRTR, SEP-2322).++A FastMCP tool may return an ``InputRequiredResult`` as the full result of a+call: the client fulfils the embedded requests (elicitation / sampling /+roots) and calls again — a new, complete request-response cycle — with the+answers on ``ctx.input_responses`` and the echoed opaque ``ctx.request_state``.+This is the SDK's own base "guard" model — the tool runs per round and checks+whether the client's answers are present — with FastMCP mirroring its+semantics exactly.++These tests exercise the *emission* side (a FastMCP server producing the+``InputRequiredResult`` and being driven to completion) over both in-memory and+HTTP transports, plus the request-state boundary (framework-owned sealing) and+the ≤2025-11-25 era gate. The client-side *answering* path is covered by+``tests/client/client/test_input_required_driver.py``.+"""++from __future__ import annotations++from typing import Annotated++import mcp_types+import pytest+from mcp.client._input_required import InputRequiredRoundsExceededError+from mcp.server.request_state import RequestStateSecurity+from mcp.shared.exceptions import MCPError+from mcp_types import ElicitRequest, InputRequiredResult+from pydantic import Field+from typing_extensions import TypeAliasType++from fastmcp import Client, Context, FastMCP+from fastmcp.client.elicitation import ElicitResult+from fastmcp.client.transports import StreamableHttpTransport+from fastmcp.server.middleware.error_handling import ErrorHandlingMiddleware+from fastmcp.server.middleware.middleware import Middleware+from fastmcp.tools.base import InputRequiredToolResult, ToolResult+from fastmcp.utilities.tests import run_server_async+++def _elicit(key: str, message: str, field: str) -> ElicitRequest:+ """A single-field form elicitation request keyed by ``key``."""+ params = mcp_types.ElicitRequestFormParams(+ message=message,+ requested_schema={+ "type": "object",+ "properties": {field: {"type": "string"}},+ "required": [field],+ },+ )+ return ElicitRequest(method="elicitation/create", params=params)+++def _ask(+ request: ElicitRequest, key: str, request_state: str | None+) -> InputRequiredResult:+ return InputRequiredResult(+ result_type="input_required",+ input_requests={key: request},+ request_state=request_state,+ )+++def _accepted(responses: mcp_types.InputResponses, key: str) -> dict[str, object]:+ """The accepted form content for one answered elicitation.++ ``ctx.input_responses`` values are the raw SDK union+ (``ElicitResult | CreateMessageResult | ListRootsResult``); a guard tool+ narrows to the response type it asked for.+ """+ answer = responses[key]+ assert isinstance(answer, mcp_types.ElicitResult)+ assert answer.content is not None+ return dict(answer.content)+++def two_question_server(**server_kwargs) -> FastMCP:+ """A guard tool that asks two dependent questions across three rounds.++ Round 1 (no responses): ask for a destination.+ Round 2 (destination answered): ask for a date, carrying the destination+ forward through ``request_state`` (a computed value, not re-derived).+ Round 3 (date answered): read the carried destination out of+ ``request_state`` and finish.+ """+ mcp = FastMCP("guard", **server_kwargs)++ @mcp.tool+ async def book_flight(ctx: Context) -> str | InputRequiredResult:+ responses = ctx.input_responses+ if responses is None:+ return _ask(+ _elicit("destination", "Where would you like to fly?", "destination"),+ "destination",+ request_state=None,+ )+ if "destination" in responses:+ destination = _accepted(responses, "destination")["destination"]+ return _ask(+ _elicit("date", f"When to {destination}?", "date"),+ "date",+ request_state=f"dest={destination}",+ )+ assert ctx.request_state is not None+ destination = ctx.request_state.split("=", 1)[1]+ date = _accepted(responses, "date")["date"]+ return f"Booked {destination} on {date}"++ return mcp+++def _two_answer_handler(asked: list[str]):+ async def handler(message, response_type, params, ctx):+ asked.append(message)+ if "Where" in message:+ return ElicitResult(+ action="accept", content=response_type(destination="Paris")+ )+ return ElicitResult(action="accept", content=response_type(date="2026-08-01"))++ return handler+++class TestContextProperties:+ """`ctx.input_responses` / `ctx.request_state` thin passthroughs."""++ async def test_none_outside_mrtr_round(self):+ """On a plain call (no prior InputRequiredResult), both are None."""+ seen: dict[str, object] = {}+ mcp = FastMCP("x")++ @mcp.tool+ async def probe(ctx: Context) -> str:+ seen["input_responses"] = ctx.input_responses+ seen["request_state"] = ctx.request_state+ return "ok"++ async with Client(mcp, mode="auto") as client:+ await client.call_tool("probe", {})++ assert seen["input_responses"] is None+ assert seen["request_state"] is None++ async def test_none_without_request_context(self):+ """Off-request (no bound wire request) the properties are None, not a crash."""+ mcp = FastMCP("x")+ async with Context(fastmcp=mcp) as ctx:+ assert ctx.input_responses is None+ assert ctx.request_state is None+++# PEP 695 `type X = ...` aliases, built portably (the `type` statement is 3.12+).+# One factors out the whole guard union; one is a lone aliased ask arm; one is a+# composed alias whose union arm hides the guard (`str | _ComposedGuardArm`).+_AliasedGuardUnion = TypeAliasType("_AliasedGuardUnion", str | InputRequiredResult)+_AliasedAskArm = TypeAliasType("_AliasedAskArm", InputRequiredResult)+_ComposedGuardArm = TypeAliasType("_ComposedGuardArm", int | InputRequiredResult)+++class _InputRequiredSubclass(InputRequiredResult):+ """A user subclass of the guard result — still a control signal, not data."""+++class TestOutputSchema:+ """An `InputRequiredResult` return arm is control flow, not output data, so+ it is stripped from output-schema derivation."""++ def test_union_arm_stripped_keeps_data_schema(self):+ from fastmcp.tools.function_tool import FunctionTool++ def book(x: int) -> str | InputRequiredResult:+ return "ok"++ tool = FunctionTool.from_function(book)+ assert tool.output_schema is not None+ # Schema is derived from the residual `str` arm (wrapped as {"result": ...}).+ assert tool.output_schema.get("x-fastmcp-wrap-result") is True++ def test_aliased_guard_union_stripped(self):+ """A `type Result = str | InputRequiredResult` alias is unwrapped before+ stripping, so the ask arm never leaks into the output schema."""+ from fastmcp.tools.function_tool import FunctionTool++ def book(x: int) -> _AliasedGuardUnion:+ return "ok"++ tool = FunctionTool.from_function(book)+ assert tool.output_schema is not None+ assert tool.output_schema.get("x-fastmcp-wrap-result") is True++ def test_aliased_ask_arm_stripped(self):+ """A lone aliased arm (`str | AskAlias`) is recognized as a guard signal+ and stripped, leaving the data arm's schema."""+ from fastmcp.tools.function_tool import FunctionTool++ def book(x: int) -> str | _AliasedAskArm:+ return "ok"++ tool = FunctionTool.from_function(book)+ assert tool.output_schema is not None+ assert tool.output_schema.get("x-fastmcp-wrap-result") is True++ def test_composed_alias_arm_stripped(self):+ """A composed alias arm — `str | Value` where+ `Value = int | InputRequiredResult` — is recursively unwrapped so the+ hidden guard is stripped, leaving the flattened data arms (`str | int`)."""+ from typing import get_args as _get_args++ from fastmcp.tools.function_parsing import _strip_input_required++ stripped = _strip_input_required(str | _ComposedGuardArm)+ assert set(_get_args(stripped)) == {str, int}++ def test_bare_input_required_subclass_suppresses_schema(self):+ """A bare `InputRequiredResult` *subclass* is subclass-aware suppressed,+ matching `run()`'s isinstance handling, so no output schema is emitted+ for data the client can never receive."""+ from fastmcp.tools.function_tool import FunctionTool++ def suspend_only(x: int) -> _InputRequiredSubclass:+ raise NotImplementedError++ tool = FunctionTool.from_function(suspend_only)+ assert tool.output_schema is None++ def test_bare_aliased_input_required_suppresses_schema(self):+ """A bare aliased guard return (`-> _AliasedAskArm` where the alias is+ `InputRequiredResult`) is de-aliased so downstream suppression applies,+ emitting no output schema."""+ from fastmcp.tools.function_tool import FunctionTool++ def suspend_only(x: int) -> _AliasedAskArm:+ raise NotImplementedError++ tool = FunctionTool.from_function(suspend_only)+ assert tool.output_schema is None++ def test_annotated_bare_guard_returns_suppress_schema(self):+ """The wholesale suppression also covers Annotated wrappings of a bare+ guard return — including an aliased one — which exact-match replacement+ would otherwise miss."""+ from fastmcp.tools.function_tool import FunctionTool++ def annotated_plain(x: int) -> Annotated[InputRequiredResult, Field()]:+ raise NotImplementedError++ def annotated_aliased(x: int) -> Annotated[_AliasedAskArm, Field()]:+ raise NotImplementedError++ assert FunctionTool.from_function(annotated_plain).output_schema is None+ assert FunctionTool.from_function(annotated_aliased).output_schema is None++ def test_bare_input_required_return_suppresses_schema(self):+ from fastmcp.tools.function_tool import FunctionTool++ def suspend_only(x: int) -> InputRequiredResult:+ raise NotImplementedError++ tool = FunctionTool.from_function(suspend_only)+ assert tool.output_schema is None+++class TestTransformedGuard:+ """A guard tool wrapped by TransformedTool must still emit its ask: a+ non-object output_schema on the transform reshapes ordinary ToolResults,+ but an InputRequiredToolResult (which carries no output data) must pass+ through so the wire handler still returns the InputRequiredResult."""++ async def test_transformed_guard_still_asks(self):+ from fastmcp.tools.tool_transform import TransformedTool++ base = two_question_server()+ book = await base.get_tool("book_flight")+ assert book is not None++ mcp = FastMCP("transformed")+ # A non-object output_schema is exactly the transform config that+ # rebuilds ordinary ToolResults and would strip the ask.+ transformed = TransformedTool.from_tool(+ book, name="book", output_schema={"type": "string"}+ )+ mcp.add_tool(transformed)++ # The asking (first) round must reach the wire as an InputRequiredResult+ # — without the guard it would arrive as an empty terminal result.+ async with Client(mcp, mode="auto") as client:+ first = await client.session.call_tool(+ "book", {}, allow_input_required=True+ )+ assert isinstance(first, InputRequiredResult)+ assert "destination" in first.input_requests++ async def test_transform_fn_returning_raw_ask_is_wrapped(self):+ """A custom transform_fn that returns a raw InputRequiredResult (not a+ pre-wrapped InputRequiredToolResult) must still emit the ask — the+ transform path wraps it like any tool body."""+ from fastmcp.tools.tool_transform import TransformedTool++ base = two_question_server()+ book = await base.get_tool("book_flight")+ assert book is not None++ async def transform_fn(**kwargs) -> InputRequiredResult:+ return _ask(_elicit("q", "raw ask?", "q"), "q", request_state=None)++ mcp = FastMCP("raw-transform")+ transformed = TransformedTool.from_tool(+ book, name="raw", transform_fn=transform_fn+ )+ mcp.add_tool(transformed)++ async with Client(mcp, mode="auto") as client:+ first = await client.session.call_tool("raw", {}, allow_input_required=True)+ assert isinstance(first, InputRequiredResult)+ assert "q" in first.input_requests+++class TestInMemoryLoop:+ async def test_two_question_loop_completes(self):+ """Two dependent asks complete over the in-memory transport; the+ client's elicitation handler answers both rounds."""+ asked: list[str] = []+ async with Client(+ two_question_server(),+ mode="auto",+ elicitation_handler=_two_answer_handler(asked),+ ) as client:+ assert client.protocol_version == "2026-07-28"+ result = await client.call_tool("book_flight", {})++ assert asked == ["Where would you like to fly?", "When to Paris?"]+ assert result.data == "Booked Paris on 2026-08-01"++ async def test_input_responses_visible_to_tool(self):+ """A guard tool reads the client's answer out of ctx.input_responses."""+ seen: list[object] = []+ mcp = FastMCP("echo")++ @mcp.tool+ async def ask_once(ctx: Context) -> str | InputRequiredResult:+ responses = ctx.input_responses+ if responses is None:+ return _ask(_elicit("name", "Your name?", "name"), "name", None)+ content = _accepted(responses, "name")+ seen.append(content)+ return f"Hi {content['name']}"++ async def handler(message, response_type, params, ctx):+ return ElicitResult(action="accept", content=response_type(name="Ada"))++ async with Client(mcp, mode="auto", elicitation_handler=handler) as client:+ result = await client.call_tool("ask_once", {})++ assert seen == [{"name": "Ada"}]+ assert result.data == "Hi Ada"++ async def test_declined_answer_shape(self):+ """A client that declines delivers an ElicitResult with action='decline'+ and no content into ctx.input_responses (not an error)."""+ mcp = FastMCP("decline")++ @mcp.tool+ async def ask(ctx: Context) -> str | InputRequiredResult:+ responses = ctx.input_responses+ if responses is None:+ return _ask(_elicit("x", "q", "x"), "x", None)+ answer = responses["x"]+ assert isinstance(answer, mcp_types.ElicitResult)+ return f"action={answer.action} content={answer.content}"++ async def decline_handler(message, response_type, params, ctx):+ return ElicitResult(action="decline", content=None)++ async with Client(+ mcp, mode="auto", elicitation_handler=decline_handler+ ) as client:+ result = await client.call_tool("ask", {})++ assert result.data == "action=decline content=None"++ async def test_max_rounds_exceeded_raises(self):+ """A two-round guard under max_rounds=1 raises on the client driver."""+ asked: list[str] = []+ async with Client(+ two_question_server(),+ mode="auto",+ elicitation_handler=_two_answer_handler(asked),+ input_required_max_rounds=1,+ ) as client:+ with pytest.raises(InputRequiredRoundsExceededError):+ await client.call_tool("book_flight", {})+++class TestMountedServer:+ async def test_guard_tool_through_parent(self):+ """A guard tool on a mounted child completes when called through the+ parent's namespaced name — the InputRequiredToolResult forwards through+ the provider delegation and is sealed/returned at the parent's wire seam."""+ parent = FastMCP("parent")+ parent.mount(two_question_server(), namespace="sub")++ asked: list[str] = []+ async with Client(+ parent, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("sub_book_flight", {})++ assert asked == ["Where would you like to fly?", "When to Paris?"]+ assert result.data == "Booked Paris on 2026-08-01"+++def _modern_proxy(backend: FastMCP) -> FastMCP:+ """A FastMCPProxy whose backend client negotiates the modern era, so the+ backend can emit an `InputRequiredResult` (SEP-2322) for the proxy to+ round-trip rather than drive to completion internally."""+ from fastmcp.server.providers.proxy import FastMCPProxy, ProxyClient++ return FastMCPProxy(client_factory=lambda: ProxyClient(backend, mode="auto"))+++class TestProxyServer:+ async def test_guard_tool_round_trips_through_proxy(self):+ """A guard tool behind a proxy completes end-to-end: the backend's ask+ round-trips into an `InputRequiredToolResult` on the parent (rather than+ being driven to completion inside the proxy), so the parent's wire+ handler returns it to the real client, and continuation answers forward+ back down to the backend."""+ proxy = _modern_proxy(two_question_server())++ asked: list[str] = []+ async with Client(+ proxy, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("book_flight", {})++ assert asked == ["Where would you like to fly?", "When to Paris?"]+ assert result.data == "Booked Paris on 2026-08-01"++ async def test_proxy_parent_middleware_observes_ask(self):+ """The proxy round-trip is what lets the parent's own middleware see the+ ask as a result — it is not swallowed by driving inside the proxy."""+ observed: list[object] = []++ class RecordingMiddleware(Middleware):+ async def on_call_tool(self, context, call_next):+ result = await call_next(context)+ observed.append(result)+ return result++ proxy = _modern_proxy(two_question_server())+ proxy.add_middleware(RecordingMiddleware())++ asked: list[str] = []+ async with Client(+ proxy, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("book_flight", {})++ assert result.data == "Booked Paris on 2026-08-01"+ assert len(observed) == 3+ assert isinstance(observed[0], InputRequiredToolResult)+ assert isinstance(observed[1], InputRequiredToolResult)+ assert not isinstance(observed[2], InputRequiredToolResult)++ async def test_guard_round_trips_through_create_proxy_mode_auto(self):+ """The standard create_proxy(target, mode="auto") path round-trips a+ guard without a hand-built ProxyClient factory. The default stays+ handshake-era (which preserves server-initiated push forwarding); modern+ proxying is a per-call opt-in because the two eras are mutually+ exclusive on a single proxy session."""+ from fastmcp.server import create_proxy++ proxy = create_proxy(two_question_server(), mode="auto")++ asked: list[str] = []+ async with Client(+ proxy, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("book_flight", {})++ assert asked == ["Where would you like to fly?", "When to Paris?"]+ assert result.data == "Booked Paris on 2026-08-01"++ async def test_progress_forwards_through_modern_proxy(self):+ """A backend tool's `ctx.report_progress()` reaches the caller's progress+ handler even when the proxy backend negotiates the modern era — the+ modern branch forwards the proxy client's progress handler just like the+ legacy `call_tool_mcp` path does."""+ backend = FastMCP("progress-backend")++ @backend.tool+ async def report(ctx: Context) -> str:+ await ctx.report_progress(progress=1, total=2, message="halfway")+ await ctx.report_progress(progress=2, total=2, message="done")+ return "ok"++ proxy = _modern_proxy(backend)++ received: list[tuple[float, float | None, str | None]] = []++ async def progress_handler(progress, total, message):+ received.append((progress, total, message))++ async with Client(+ proxy, mode="auto", progress_handler=progress_handler+ ) as client:+ result = await client.call_tool("report", {})++ assert result.data == "ok"+ assert received == [(1, 2, "halfway"), (2, 2, "done")]+++class TestEraGate:+ async def test_legacy_connection_rejects_with_era_error(self):+ """Returning an InputRequiredResult on a ≤2025-11-25 connection produces+ a clear era error naming 2026-07-28, not a generic 'invalid result'."""+ async with Client(two_question_server(), mode="legacy") as client:+ assert client.protocol_version == "2025-11-25"+ with pytest.raises(MCPError) as excinfo:+ await client.call_tool("book_flight", {})++ message = str(excinfo.value)+ assert "2026-07-28" in message+ assert "2025-11-25" in message+ assert "InputRequiredResult" in message+++class TestRequestStateSealing:+ """The framework (SDK RequestStateBoundary middleware) owns sealing: a tool+ only ever mints/reads plaintext, and the wire value is authenticated."""++ def _one_shot_server(self) -> FastMCP:+ mcp = FastMCP("seal")++ @mcp.tool+ async def guard(ctx: Context) -> str | InputRequiredResult:+ if ctx.input_responses is None:+ return _ask(+ _elicit("x", "q", "x"), "x", request_state="PLAINTEXT-STATE"+ )+ return f"state={ctx.request_state}"++ return mcp++ async def test_wire_request_state_is_sealed(self):+ """The requestState the client receives is the sealed token, never the+ plaintext the tool minted."""+ async with Client(self._one_shot_server(), mode="auto") as client:+ first = await client.session.call_tool(+ "guard", {}, allow_input_required=True+ )+ assert isinstance(first, InputRequiredResult)+ assert first.request_state is not None+ assert first.request_state != "PLAINTEXT-STATE"+ # The SDK's AES-256-GCM codec stamps a versioned "v1." prefix.+ assert first.request_state.startswith("v1.")++ async def test_tampered_request_state_rejected(self):+ """A modified requestState echo fails the boundary's integrity check with+ the frozen wire error, before the tool runs."""+ async with Client(self._one_shot_server(), mode="auto") as client:+ first = await client.session.call_tool(+ "guard", {}, allow_input_required=True+ )+ assert isinstance(first, InputRequiredResult)+ assert first.request_state is not None+ tampered = first.request_state[:-2] + (+ "AA" if not first.request_state.endswith("AA") else "BB"+ )+ with pytest.raises(MCPError) as excinfo:+ await client.session.call_tool(+ "guard",+ {},+ input_responses={"x": {"action": "accept", "content": {"x": "v"}}},+ request_state=tampered,+ allow_input_required=True,+ )+ assert "requestState" in str(excinfo.value)++ async def test_plaintext_round_trips_to_tool(self):+ """A valid echo delivers the original plaintext back to the tool."""+ async with Client(self._one_shot_server(), mode="auto") as client:+ first = await client.session.call_tool(+ "guard", {}, allow_input_required=True+ )+ assert isinstance(first, InputRequiredResult)+ second = await client.session.call_tool(+ "guard",+ {},+ input_responses={"x": {"action": "accept", "content": {"x": "v"}}},+ request_state=first.request_state,+ allow_input_required=True,+ )+ assert isinstance(second, mcp_types.CallToolResult)+ assert second.structured_content == {"result": "state=PLAINTEXT-STATE"}+++class TestMiddlewareInteraction:+ """Each MRTR leg is a complete request→response cycle: an+ `InputRequiredResult` is the full, legitimate result of that leg, so it+ flows back through the middleware chain as an ordinary `ToolResult`+ (specifically an `InputRequiredToolResult`). Middleware observes it as a+ normal result, not an error and not control flow."""++ async def test_completes_with_error_and_broad_except_middleware(self):+ """An ask is a result, not an error, so error-handling middleware and a+ broad ``except Exception`` are simply irrelevant — `call_next` returns+ the ask, nothing is raised, and the loop completes normally.+ """++ class BroadCatchMiddleware(Middleware):+ async def on_call_tool(self, context, call_next):+ # The ask is RETURNED here, never raised, so this except never+ # fires on a guard round.+ try:+ return await call_next(context)+ except Exception as e:+ raise RuntimeError(f"swallowed: {e}") from e++ server = two_question_server()+ server.add_middleware(ErrorHandlingMiddleware())+ server.add_middleware(BroadCatchMiddleware())++ asked: list[str] = []+ async with Client(+ server, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("book_flight", {})+ assert result.data == "Booked Paris on 2026-08-01"+ assert len(asked) == 2++ async def test_middleware_observes_ask_then_final_result_per_leg(self):+ """A logging-style recording middleware sees the full chain run on every+ leg: the ask (`InputRequiredToolResult`) is the observed result on the+ two guard legs, and the terminal string is the result on the last leg.+ Three client-visible rounds ⇒ three `on_call_tool` fires."""+ observed: list[object] = []++ class RecordingMiddleware(Middleware):+ async def on_call_tool(self, context, call_next):+ result = await call_next(context)+ observed.append(result)+ return result++ server = two_question_server()+ server.add_middleware(RecordingMiddleware())++ asked: list[str] = []+ async with Client(+ server, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("book_flight", {})++ assert result.data == "Booked Paris on 2026-08-01"+ # One on_call_tool fire per leg — three legs, three observations.+ assert len(observed) == 3+ # The first two legs each return the ask as their result; middleware can+ # identify it by isinstance on the ToolResult subclass.+ assert isinstance(observed[0], InputRequiredToolResult)+ assert isinstance(observed[1], InputRequiredToolResult)+ # Each ask carries the underlying InputRequiredResult unmodified.+ assert isinstance(observed[0].input_required, InputRequiredResult)+ # The final leg returns the ordinary terminal result, not an ask.+ assert isinstance(observed[2], ToolResult)+ assert not isinstance(observed[2], InputRequiredToolResult)+ assert observed[2].structured_content == {+ "result": "Booked Paris on 2026-08-01"+ }++ async def test_continuation_leg_is_detectable_from_context(self):+ """Middleware can distinguish an initial leg from a continuation leg via+ ``context.fastmcp_context.input_responses`` — ``None`` on the first+ round, present once the client has answered."""+ input_responses_seen: list[bool] = []++ class DetectMiddleware(Middleware):+ async def on_call_tool(self, context, call_next):+ fctx = context.fastmcp_context+ assert fctx is not None+ input_responses_seen.append(fctx.input_responses is not None)+ return await call_next(context)++ server = two_question_server()+ server.add_middleware(DetectMiddleware())++ asked: list[str] = []+ async with Client(+ server, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("book_flight", {})++ assert result.data == "Booked Paris on 2026-08-01"+ # Leg 1 has no answers yet; legs 2 and 3 are continuations.+ assert input_responses_seen == [False, True, True]++ async def test_continuation_fields_populate_message(self):+ """The continuation fields (SEP-2322) appear on ``context.message``+ itself, not only on ``fastmcp_context`` — so middleware branching on the+ standard `input_responses` / `request_state` params sees a continuation+ round as such rather than as an initial call."""+ responses_seen: list[bool] = []+ state_seen: list[bool] = []++ class MessageMiddleware(Middleware):+ async def on_call_tool(self, context, call_next):+ responses_seen.append(context.message.input_responses is not None)+ state_seen.append(context.message.request_state is not None)+ return await call_next(context)++ server = two_question_server()+ server.add_middleware(MessageMiddleware())++ asked: list[str] = []+ async with Client(+ server, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("book_flight", {})++ assert result.data == "Booked Paris on 2026-08-01"+ # Answers arrive on legs 2 and 3; request_state is carried only on leg 3+ # (round 2's ask minted it), so it is absent on legs 1 and 2.+ assert responses_seen == [False, True, True]+ assert state_seen == [False, False, True]+++class TestCachingMiddlewareInteraction:+ async def test_ask_is_not_cached(self):+ """The response cache must never store an ask: two identical first-leg+ calls both reach the tool (the second is not served a stale cached+ question). A cached ask would replay a stale prompt and skip the tool's+ own per-round logic."""+ from fastmcp.server.middleware.caching import ResponseCachingMiddleware++ call_count = {"n": 0}+ mcp = FastMCP("cache-guard")++ @mcp.tool+ async def ask(ctx: Context) -> str | InputRequiredResult:+ if ctx.input_responses is None:+ call_count["n"] += 1+ return _ask(_elicit("x", "q", "x"), "x", None)+ return "done"++ mcp.add_middleware(ResponseCachingMiddleware())++ # Two independent first legs (no elicitation handler ⇒ each raises on the+ # client driver rather than completing), but both must have reached the+ # tool body — proving the ask was not served from cache.+ async with Client(mcp, mode="auto") as client:+ for _ in range(2):+ first = await client.session.call_tool(+ "ask", {}, allow_input_required=True+ )+ assert isinstance(first, InputRequiredResult)++ assert call_count["n"] == 2++ async def test_state_only_continuation_final_not_cached(self):+ """A state-only round (request_state, no questions) retries with+ input_responses=None — request_state alone must mark the continuation,+ or its terminal result would be cached under the fresh-call key."""+ from fastmcp.server.middleware.caching import ResponseCachingMiddleware++ body_runs = {"n": 0}+ mcp = FastMCP("cache-state-only")++ @mcp.tool+ async def staged(ctx: Context) -> str | InputRequiredResult:+ body_runs["n"] += 1+ if ctx.request_state is None:+ return InputRequiredResult(+ result_type="input_required",+ input_requests={},+ request_state="stage=1",+ )+ return f"done after {ctx.request_state}"++ mcp.add_middleware(ResponseCachingMiddleware())++ async with Client(mcp, mode="auto") as client:+ first = await client.session.call_tool(+ "staged", {}, allow_input_required=True+ )+ assert isinstance(first, InputRequiredResult)+ # The client echoes the (sealed) state with no responses — the+ # state-only continuation the guard must recognize.+ final = await client.session.call_tool(+ "staged",+ {},+ request_state=first.request_state,+ allow_input_required=True,+ )+ assert not isinstance(final, InputRequiredResult)+ runs_after_flow = body_runs["n"]++ # A fresh identical call must run the tool again, not be served+ # the continuation's cached final.+ fresh = await client.session.call_tool(+ "staged", {}, allow_input_required=True+ )+ assert isinstance(fresh, InputRequiredResult)++ assert body_runs["n"] == runs_after_flow + 1++ async def test_completed_flow_final_result_not_served_to_fresh_call(self):+ """A continuation leg's final result must not enter the cache: its key+ is built from name+arguments only, identical to a fresh call's — so a+ cached final would be served to the next fresh call, which would then+ never be asked the tool's questions."""+ from fastmcp.server.middleware.caching import ResponseCachingMiddleware++ body_runs = {"n": 0}+ mcp = FastMCP("cache-flow")++ @mcp.tool+ async def ask(ctx: Context) -> str | InputRequiredResult:+ body_runs["n"] += 1+ if ctx.input_responses is None:+ return _ask(_elicit("x", "q", "x"), "x", None)+ return "done"++ mcp.add_middleware(ResponseCachingMiddleware())++ async def answer(message, response_type, params, ctx):+ return ElicitResult(action="accept", content=response_type(x="a"))++ async with Client(mcp, mode="auto", elicitation_handler=answer) as client:+ first = await client.call_tool("ask", {})+ assert first.data == "done"+ runs_after_first_flow = body_runs["n"]++ # A fresh identical call must run the tool again (ask + answer),+ # not be served the previous flow's cached final answer.+ second = await client.call_tool("ask", {})+ assert second.data == "done"++ assert body_runs["n"] == runs_after_first_flow + 2+++class TestAnnotatedReturns:+ async def test_annotated_union_return_strips_guard_arm(self):+ """``Annotated[str | InputRequiredResult, ...]`` derives its output+ schema from the data arm; the guard arm is stripped inside Annotated."""+ mcp = FastMCP("AnnotatedGuard")++ @mcp.tool+ async def greet(+ ctx: Context,+ ) -> Annotated[str | InputRequiredResult, Field(description="greeting")]:+ if ctx.input_responses is None:+ return InputRequiredResult(+ input_requests={"name": _elicit("name", "Your name?", "name")},+ request_state="",+ )+ return "hello"++ tool = await mcp.get_tool("greet")+ assert tool is not None+ schema = tool.output_schema+ assert schema is not None+ # Derived from the str arm — not poisoned by the guard arm.+ assert "InputRequired" not in str(schema)++ async def test_metadata_on_guard_arm_is_stripped(self):+ """When only the guard arm carries metadata+ (``str | Annotated[InputRequiredResult, Field(...)]``), it is still+ recognized and stripped so the str arm's schema survives."""+ mcp = FastMCP("AnnotatedGuardArm")++ @mcp.tool+ async def greet(+ ctx: Context,+ ) -> str | Annotated[InputRequiredResult, Field(description="suspend")]:+ if ctx.input_responses is None:+ return InputRequiredResult(+ input_requests={"name": _elicit("name", "Your name?", "name")},+ request_state="",+ )+ return "hello"++ tool = await mcp.get_tool("greet")+ assert tool is not None+ schema = tool.output_schema+ assert schema is not None+ assert "InputRequired" not in str(schema)+++class TestRequestStateSecurityConfig:+ def test_custom_security_without_stable_audience_warns(self, caplog):+ """A supplied policy with neither an explicit audience nor a stable+ server name warns (shared keys across replicas would stamp per-replica+ random audiences) — but constructs, since single-process customization+ (e.g. an ephemeral policy with a custom ttl) is legitimate and a policy+ object cannot reveal whether its keys are shared."""+ import logging++ with caplog.at_level(logging.WARNING):+ FastMCP(request_state_security=RequestStateSecurity(keys=[b"0" * 32]))+ assert any("stable audience" in r.message for r in caplog.records)++ # An empty name is falsy → still a random per-replica name, so it must+ # warn like an omitted name (not slip through a `name is None` check).+ caplog.clear()+ with caplog.at_level(logging.WARNING):+ FastMCP(+ name="", request_state_security=RequestStateSecurity(keys=[b"0" * 32])+ )+ assert any("stable audience" in r.message for r in caplog.records)++ # Single-process customization is allowed (warns, does not raise):+ FastMCP(request_state_security=RequestStateSecurity.ephemeral(ttl=30))++ # Either remedy avoids the warning:+ caplog.clear()+ with caplog.at_level(logging.WARNING):+ FastMCP(+ name="Stable",+ request_state_security=RequestStateSecurity(keys=[b"0" * 32]),+ )+ FastMCP(+ request_state_security=RequestStateSecurity(+ keys=[b"0" * 32], audience="my-service"+ )+ )+ assert not any("stable audience" in r.message for r in caplog.records)++ async def test_explicit_shared_keys_seal_and_complete(self):+ """A server configured with explicit shared keys drives a full loop —+ the multi-replica configuration (RequestStateSecurity(keys=[...]))."""+ key = b"0" * 32+ server = two_question_server(+ request_state_security=RequestStateSecurity(keys=[key])+ )+ asked: list[str] = []+ async with Client(+ server, mode="auto", elicitation_handler=_two_answer_handler(asked)+ ) as client:+ result = await client.call_tool("book_flight", {})+ assert result.data == "Booked Paris on 2026-08-01"++ def _sealing_server(self, key: bytes) -> FastMCP:+ """A one-round guard that seals a request_state on its first ask, under+ an explicit key so state can be replayed across instances."""+ mcp = FastMCP(+ "seal-keyed",+ request_state_security=RequestStateSecurity(keys=[key]),+ )++ @mcp.tool+ async def guard(ctx: Context) -> str | InputRequiredResult:+ if ctx.input_responses is None:+ return _ask(_elicit("x", "q", "x"), "x", request_state="carried")+ return f"state={ctx.request_state}"++ return mcp++ async def test_state_from_a_different_key_is_rejected(self):+ """State minted under one key is rejected by a server holding a+ different key — the cross-instance isolation shared keys prevent."""+ async with Client(self._sealing_server(b"a" * 32), mode="auto") as client:+ first = await client.session.call_tool(+ "guard", {}, allow_input_required=True+ )+ assert isinstance(first, InputRequiredResult)+ state_from_a = first.request_state+ assert state_from_a is not None++ async with Client(self._sealing_server(b"b" * 32), mode="auto") as client:+ with pytest.raises(MCPError):+ await client.session.call_tool(+ "guard",+ {},+ input_responses={"x": {"action": "accept", "content": {"x": "v"}}},+ request_state=state_from_a,+ allow_input_required=True,+ )+++class TestTaskExecution:+ """A guard tool returns an `InputRequiredResult` as its result, which only+ makes sense against a live request that can answer the prompt. A detached+ background task has no such request, so returning a guard result from a task+ is rejected with a clear error rather than silently yielding empty content."""++ async def test_guard_result_from_task_is_rejected(self):+ mcp = FastMCP("guard-task")++ @mcp.tool(task=True)+ async def book_flight(ctx: Context) -> str | InputRequiredResult:+ return _ask(+ _elicit("date", "When?", "date"),+ key="date",+ request_state=None,+ )++ async with Client(mcp) as client:+ task = await client.call_tool("book_flight", {}, task=True)+ with pytest.raises(MCPError, match="background task"):+ await task.result()+++class TestHttpTransport:+ async def test_two_question_loop_over_http(self):+ """The full guard loop completes over Streamable HTTP with mode='auto'."""+ asked: list[str] = []+ async with run_server_async(two_question_server()) as url:+ async with Client(+ StreamableHttpTransport(url),+ mode="auto",+ elicitation_handler=_two_answer_handler(asked),+ ) as client:+ assert client.protocol_version == "2026-07-28"+ result = await client.call_tool("book_flight", {})++ assert asked == ["Where would you like to fly?", "When to Paris?"]+ assert result.data == "Booked Paris on 2026-08-01"