* fix(rmcp): route peer cancellation by lifecycle
Cancel inbound legacy requests by their exact request ID. Preserve modern
subscription waiter cleanup using the peer lifecycle and outbound request kind.
Suppress cancelled handler results and errors during EOF draining without
dropping uncancelled responses during graceful shutdown.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* test(rmcp): parameterize reverse cancellation cases
Use rstest to report each startup and request ID combination independently.
Keep the existing per-case timeout and cancellation assertions.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* fix(rmcp): use canonical initialize result in cancellation test
Replace the stale ServerInfo reference after merging the upstream alias migration.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
---------
Co-authored-by: Hunter Sadler <aurokin@github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* fix(model): deprecate ServerInfo and ClientInfo aliases
Those names collide with the protocol's serverInfo/clientInfo fields,
which are only Implementation identity. Prefer InitializeResult and
InitializeRequestParams. Handler trait signatures, the tool_handler
macro output, tests, examples and docs now use the canonical types; the
aliases remain as deprecated shims for the rest of 3.x.
Fixes#1082
* fix(model): keep public signatures on the deprecated aliases
The public API check compares rendered signatures, and rustdoc records a
type alias by the name it was written with. Respelling
`ServerHandler::get_info`, `ClientHandler::get_info`,
`DiscoverResult::from_server_info` and `impl ClientHandler for ClientInfo`
onto `InitializeResult`/`InitializeRequestParams` therefore reads as
changed public items even though the aliases resolve to those exact types
and nothing downstream breaks.
Put those four signatures back on the aliases so the published API is
byte-identical, and note why at the alias definitions. The deprecation
still steers new code, and the macro output, tests, examples and docs
keep using the canonical names.
* fix(model): migrate leftover ClientInfo test sites
Two tests landed on main after the alias deprecation and still named
ClientInfo. Clippy -D warnings and the no-local feature test job both
failed on them.
* fix(auth): ignore non-metadata JSON when probing for protected resource metadata
The base URL is probed first when looking for RFC 9728 protected resource
metadata, and any 200 there is taken to mean "this URL is the metadata
document". Every field of ResourceServerMetadata is optional, so an unrelated
JSON object deserializes into an all-None value and validation then fails hard
with "Protected resource metadata missing required resource field". The error
propagates out of resolve_metadata, so the .well-known fallbacks never run.
Servers that answer GET / with a JSON health payload hit this even when they
publish valid metadata at both well-known locations.
Treat a parsed document that carries none of resource, authorization_server or
authorization_servers as a soft failure, the same way this function already
treats a non-200 status and a body that is not JSON. A document carrying any of
those fields still goes through validate_resource_metadata_resource unchanged.
This is the JSON-object half of #810, which made a non-JSON body at the base URL
a soft failure for the same reason.
* fix(auth): stop a 200 from the resource ending metadata discovery
probe_resource_metadata_url treats any 200 as "this url is the metadata
document". That holds for the .well-known candidates it is called with in the
loop, and not for the first call, which is passed the resource itself. RFC 9728
publishes the document at the well-known URI and advertises it through the
resource_metadata parameter of a WWW-Authenticate challenge, so a 200 from the
resource is the resource answering and nothing more.
Because that first probe returned Some(base_url), discovery ended before the
.well-known candidates were tried, and a valid document published there was
never reached. Rejecting the body later could not recover it: by then the
candidates had already been skipped.
Split the first probe into probe_resource_endpoint_for_challenge, which reads
only the 401 branch. The .well-known probe keeps its behaviour.
The check added in the previous commit stays. A .well-known url can also answer
200 with something that is not a metadata document, and every field of
ResourceServerMetadata being optional makes that deserialize into an all-None
value that then fails validation fatally.
resolve_metadata_reaches_the_well_known_document_past_a_non_metadata_base_url
asserts the well-known url is actually requested; without this change it fails
with the base url requested twice and the protected-resource candidate never
probed. resolve_metadata_ignores_a_well_known_url_that_is_not_a_metadata_document
covers the remaining guard; without it the run ends in the original
"Protected resource metadata missing required resource field".
* fix(auth): keep trying the well-known candidates past a non-metadata document
discover_resource_metadata_url returned the first .well-known candidate that
answered 200 and left the loop; the document itself was fetched afterwards,
outside the loop. A candidate answering 200 with something that is not metadata
is only recognised at that point, by which time the remaining candidates have
been skipped and discovery gives up with nothing.
The probe already had the body in hand and threw it away, so the winning
candidate was requested twice. Read the body where the candidate is probed
instead: a candidate that is not the document costs one request and the loop
moves on to the next one, and the candidate that is the document is requested
once.
The second half of the old function, which walks the authorization servers a
document names, is unchanged; it now takes the document as an argument so the
challenge path keeps sharing it.
resolve_metadata_tries_the_next_well_known_candidate_past_a_non_metadata_document
covers the loop; without this change the second candidate is never requested and
the run ends on the issuer of an authorization server it was never meant to
reach.
* fix(auth): report an advertised url that is not the metadata document
A WWW-Authenticate challenge naming a resource_metadata url is the server
saying the document is there. The previous commits made a document carrying
neither resource nor an authorization server reference a soft failure
everywhere, which on that path drops out of resolve_metadata_from_challenge,
continues with authorization server discovery and settles on the legacy
endpoints, silently losing the RFC 8707 resource binding the document was
supposed to carry. Before those commits it surfaced as
"Protected resource metadata missing required resource field".
Where the url came from decides what that document means. A .well-known
candidate is a guess, so its answer only rules out that candidate and the loop
goes on. An advertised url has no better alternative to move on to, so say what
the server got wrong instead of degrading quietly.
Reading a non-200 or a body that is not JSON stays a soft failure on both
paths.
resolve_metadata_from_challenge_reports_an_advertised_url_without_metadata
covers the challenge path; without this change it resolves to
LegacyEndpointFallback.
* fix(auth): let a candidate fail validation without ending discovery
parse_resource_metadata decides what a body that is not the metadata document
means from where the url came from, and it decides it on the presence of
resource, authorization_server and authorization_servers alone. What comes
after is fatal whatever the origin: validate_resource_metadata_resource
rejects a missing resource, a resource that is not a URL, one carrying a
fragment, and one that does not match the base url, and each of those
propagates out of resolve_metadata.
A .well-known candidate handled by a catch-all route reaches it. The
{"error":"not_found","resource":"/.well-known/oauth-protected-resource"} such
a route answers with carries resource, so the presence check lets it through,
and the relative path then fails to parse as a URL. That is the shape this
branch opened on, one field further along: the remaining candidates are
skipped, authorization server discovery is skipped, and the run ends on an
error instead of the legacy endpoints.
Read the body and validate it in the same place, now read_resource_metadata,
so the origin governing the first decision governs the second one as well. A
guess that fails validation rules out that candidate and the loop goes on; an
advertised url still reports what the server got wrong.
authorization_metadata_from_resource_metadata takes a document that has
already been accepted.
resolve_metadata_tries_the_next_well_known_candidate_past_an_unusable_document
covers it; without this change it fails with "Protected resource metadata
resource field is not a valid URL".
* fix(auth): keep probing the candidates when an advertised url answers nothing
An advertised url reading a non-200 or a body that is not JSON is a soft
failure: the server said the document is at that url and nothing is being
served there, which rules out the url and not the document. The .well-known
candidates are derived from the base url rather than from that pointer, so
they are still worth probing, but the pointer was read ahead of the loop and
returned out of discover_resource_metadata either way. A challenge naming
https://host/.well-known/oauth-protected-resource that 404s takes the run
straight to authorization server discovery, while the document sits unread on
https://host/mcp/.well-known/oauth-protected-resource.
Fall through to the loop instead. Carrying on past a candidate's own 401
already let one url be requested twice, because the pointer that challenge
names can be a later candidate of the same run, and it is requested again when
the loop reaches it; not returning on the first pointer adds the same overlap.
Keep the urls this run has requested and skip the ones already read.
resolve_metadata_probes_the_candidates_past_an_advertised_url_that_is_not_served
covers the fall-through; without it the run reaches the authorization server
metadata of a server it was never pointed at.
resolve_metadata_requests_an_advertised_url_that_is_also_a_candidate_once
covers the repeat.
* fix(auth): walk an authorization server named by both fields once
A protected resource metadata document can name its authorization server in
authorization_servers, and servers written against the earlier draft also fill
the singular authorization_server. Filling both with the same value is common,
and the two are concatenated into the candidate list unfiltered, so every
well-known form of that one server's discovery url is requested twice before
the walk gives up on it.
well_known_paths already keeps its candidates distinct. Do the same here,
comparing the trimmed value the loop goes on to use.
resolve_metadata_requests_an_authorization_server_named_twice_once covers it;
without this change the discovery url is requested twice.
---------
Co-authored-by: easyinplay <easyinplay@users.noreply.github.com>
* fix: do not treat malformed JSON 200 as Accepted for requests
Streamable HTTP mapped any JSON body that failed to parse as
ServerJsonRpcMessage to Accepted, which is correct for notification
POSTs. For a request the worker then waits on SSE forever, so
call_tool hangs when the server returns 200 application/json with
an empty or non-JSON-RPC body.
Signed-off-by: Sebastien Tardif <sebtardif@ncf.ca>
* fix: include a short body preview in JSON-RPC parse errors
Request POST parse failures now include a 256-byte prefix of the
unusable body so empty, HTML, and `{}` are distinguishable from the
serde diagnostic. HTTP reads bytes() then from_slice, matching Unix.
Signed-off-by: Sebastien Tardif <sebtardif@ncf.ca>
---------
Signed-off-by: Sebastien Tardif <sebtardif@ncf.ca>
`jsonrpc_http_status` maps several protocol errors (unsupported protocol
version, missing required client capability, invalid params) to HTTP 400
on the modern per-request Streamable HTTP path, but fell through to the
default HTTP 200 for `ErrorCode::HEADER_MISMATCH`. When a `ServerHandler`
returns `Err(ErrorData::header_mismatch(...))`, RMCP serialized the
correct JSON-RPC -32020 error but sent it with HTTP 200.
The legacy/transport-generated header validation path (SEP-2243
Mcp-Method/Mcp-Name/Mcp-Param-* mismatches) was unaffected, since
`header_mismatch_jsonrpc_response` constructs an HTTP 400 response
directly rather than going through `jsonrpc_http_status`. Only
handler-generated HeaderMismatch errors on the modern path hit the bug.
Add `ErrorCode::HEADER_MISMATCH` to the existing `BAD_REQUEST` match arm,
matching the Streamable HTTP server-validation rules in the 2026-07-28
spec. Added unit tests covering the mapper directly (header-mismatch to
400, method-not-found to 404, an unmapped code defaulting to 200).
Closes#1225
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Return HTTP 403 for malformed and non-UTF-8 Origin headers when validation is enabled.
Add enforce_origin_validation() for strict empty-allowlist validation while preserving the
legacy default and non-empty allowlist behavior. Configure the conformance server to opt in
explicitly.
Signed-off-by: lucarlig <luca.carlig@ibm.com>
* fix(sse): saturate exponential reconnect backoff
ExponentialBackoff::retry computed the reconnect multiplier with
2u32.pow(current_times). With max_times unset, current_times can reach
the bit width, panicking in debug builds and wrapping to a zero delay in
release builds for long-lived SSE clients. Use saturating_pow and
Duration::saturating_mul so the delay stays monotonic and panic-free.
* fix(sse): cap exponential reconnect backoff at a bounded max delay
Saturating the multiplier alone can still yield decades-long sleeps once
current_times reaches the bit width, pinning the stream in
tokio::time::sleep without reconnecting or terminating. Add an optional
max_delay (default 30s) that clamps the computed delay, keeping the
backoff monotonic and panic-free while guaranteeing the client retries.
* fix(sse): default max_delay to None to preserve unbounded backoff
Per maintainer feedback, leave ExponentialBackoff::default() unbounded so
the fix stays a pure overflow bug-fix. The saturating multiplier removes
the debug panic / release wrap from #1198, while max_delay stays opt-in
for callers that want a bounded reconnect delay.
* fix: resolve clippy warnings across workspace
* ci: also run clippy on rmcp with all features except local
--all-features enables the local feature, which cfg-gates out
tower.rs and most of the test suite, so the existing clippy step
never actually lints them.
* feat(auth): request ID-JAGs with enterprise refresh tokens
* feat(auth): exchange ID-JAGs for MCP access tokens
Redeem ID-JAGs at the approved resource authorization server and return
its bearer token, lifetime, and effective granted scopes. Preserve scope
narrowing and redacted diagnostics, and reuse the default HTTP adapter.
Support independently configured client authentication at both servers.
Document the exchange profile and test redirects and staged failures.
Partially addresses modelcontextprotocol/rust-sdk#531.
* test(conformance): cover EMA refresh-token exchange
* fix: allow concurrent streamable http requests
* fix: keep streamable http recovery responsive
Keep cancellation and replies available while old session POSTs finish.
Bound the wait for old POSTs and the replacement initialization handshake.
Do not retry interrupted POSTs because the server may have processed them.
Add regressions for recovery, queued cancellation, control timeouts, and
server replies needed by active requests.
* fix: preserve response and cancellation ordering
* refactor: clarify streamable http control flow
* fix: match stream responses against pending request ids
Match responses against all pending requests before removing a stream
registration. Keep distinct numeric and string ids separate while preserving
the existing fallback for servers that stringify numeric ids.
Add a mixed-id regression and keep a separate registration owner alive in
the abandoned-cancellation test.
* feat: make streamable http control timeouts configurable
* fix(rmcp): preserve elicitation requestedSchema $schema dialect
ElicitationSchema round-trips through ElicitationSchemaWire, which had no
field for the top-level `$schema` keyword. A dialect declared on an incoming
requestedSchema (allowed since protocol revision 2025-11-25) was therefore
accepted but silently dropped on re-serialization.
Add a `schema` field to both the public struct and the wire bridge, thread it
through the two `From` conversions, and expose a `with_schema` setter. The
field is `skip_serializing_if = "Option::is_none"`, so schemas without a
dialect serialize unchanged.
Refs #1168
* test(rmcp): regenerate server message schema snapshot for elicitation $schema
The $schema dialect field added to ElicitationSchema changes the
schemars-generated ServerJsonRpcMessage schema. Regenerate the golden
snapshot so test_server_json_rpc_message_schema passes.
* fix(rmcp): generate elicitation $schema as optional string in schemars
Use schemars(with = "String") on ElicitationSchema::$schema so
schemars generates "type": "string" instead of ["string", "null"].
The roadmap pinned a specific patch release as "the current stable
release", so it drifted out of date as soon as the next release shipped.
Reference the releases page instead of a hardcoded version, and drop the
dated status line.
Historical entries (v3.0.0 ship date, the v1.4.0 fix reference) keep
their versions since they record facts that do not change.
`ClientLifecycleMode::Auto` only fell back from `server/discover` on
`-32601`, so legacy servers that reject the probe with other codes
(`-32600`, `-32602`, implementation-defined errors) failed to connect
even though `initialize` would have succeeded.
The previous attempt (indicates_legacy_server) classified the failure
after the fact by reverse-engineering the error type. This rewrite moves
the classification into `discover_startup` itself, where the full context
(request id, response correlation, transport state) is still available.
`discover_startup` now returns `DiscoverOutcome`: `Modern` on success,
`Legacy(error)` when the probe received a complete, correlated JSON-RPC
error whose code is not a modern-era rejection. Every other failure
becomes `Err`, so `Auto` simply matches the outcome — no methods on
`ClientInitializeError`, no downcast, no transport-specific types
leaking into the generic lifecycle layer.
Additional fixes that fall out naturally:
- Response correlation is now checked in `expect_response` for both
success and error branches. Previously error responses skipped id
correlation entirely. A new `UncorrelatedErrorResponse` variant
surfaces responses that cannot be tied to the request.
- When both discover and the legacy fallback fail, a
`LegacyFallbackFailed` compound error preserves both phases instead
of discarding the discover error.
Fixes#1040.
`post_message_with_max_sse_event_size` turns a 401 or 403 carrying a
`WWW-Authenticate` header into `StreamableHttpError::AuthRequired` /
`InsufficientScope`. `get_stream_with_max_sse_event_size`, in the same file,
handles only 405 and then falls through to `error_for_status()?`, so the same
challenge becomes an opaque `StreamableHttpError::Client`.
That matters because `AuthClient::get_stream` routes through
`call_reacting_to_challenges`, whose whole purpose is to catch `AuthRequired`,
run `try_refresh_or_reauth()`, and retry once. It never sees that variant from
this path, so an expired token on the standalone SSE stream is never refreshed —
the stream just fails, while the identical expiry on `post_message` recovers
silently.
Copies the two blocks verbatim from `post_message` in the same file.
`unix_socket.rs` already does the same thing in its own `get_stream`.
Adds four tests against an axum mock server: a 401 with a challenge maps to
`AuthRequired`, a 403 maps to `InsufficientScope` with the scope extracted, a
401 *without* a challenge is still not `AuthRequired`, and 405 keeps reporting
`ServerDoesNotSupportSse`. The first two fail before this change with
`Err(Client(reqwest::Error { kind: Status(401, None) }))`; the last two pass
either way and exist to catch an over-broad fix.
`SseAutoReconnectStream::poll_next` recursed into itself for every event it
skips — control frames, data-less frames, and frames whose data fails to
deserialize — plus once more on every state transition.
The inner stream returns `Poll::Ready` for each event it can parse out of
already-buffered bytes, so a burst of skipped events has no yield point
between them. Each one adds a stack frame, and `poll_next` is a large frame.
A client connected to a server that emits a run of non-JSON `message` frames
overflows the stack and aborts the process.
Wrap the body in a `loop` and replace the four `self.poll_next(cx)` tail calls
with `continue`. `this` is re-derived from `self.as_mut().project()` at the top
of each iteration, so the borrows end cleanly per iteration; no other logic
changes. The diff is mostly the resulting re-indent — review with `?w=1`.
Adds `skipped_events_do_not_grow_the_stack`, which feeds 50,000 undeserializable
frames through the stream. Before this change it aborts with
`fatal runtime error: stack overflow` (SIGABRT); after, it passes.
Add a Ping section to the README covering both directions of the
utility: constructing and sending a PingRequest via send_request, and
the automatic default handler response (with an override example for
custom liveness logic). Links to the MCP ping spec.
Ping was the only non-experimental feature lacking user-facing
documentation and an example.
* fix(model): decode metadata-bearing input-required results
The draft permits every Result, including InputRequiredResult, to carry
_meta and recommends that servers include
io.modelcontextprotocol/serverInfo on every response. It also requires
an InputRequiredResult to contain inputRequests or requestState so the
client knows what to provide or how to resume the request.
ServerResult uses untagged deserialization and attempts CallToolResult
before InputRequiredResult. Because CallToolResult accepts _meta and
defaults missing content to an empty list, it consumed valid
input_required results carrying metadata. Unknown inputRequests and
requestState fields were then discarded, leaving clients without the
information needed to continue.
Reject resultType input_required when deserializing CallToolResult so
Serde proceeds to the InputRequiredResult variant. Add regression
coverage proving that inputRequests, requestState, and serverInfo
metadata are preserved.
Spec:
41d9e938e9/schema/draft/schema.ts (L137-L151)41d9e938e9/schema/draft/schema.ts (L198-L224)41d9e938e9/schema/draft/schema.ts (L541-L565)
Signed-off-by: Filinto Duran <1373693+filintod@users.noreply.github.com>
* incorporate feedback - close gap in inputrequired not properly checking that at least one of inputRequest or requestState is present
Signed-off-by: Filinto Duran <1373693+filintod@users.noreply.github.com>
---------
Signed-off-by: Filinto Duran <1373693+filintod@users.noreply.github.com>
* refactor(service): express SEP-2260 receive-side association as an enum
Replaces the has_pending_outbound_request bool on
enforce_peer_request_association with PeerRequestAssociation, so a
stream-separating transport can report per-request association (#1033).
Behavior-preserving: the event loop still passes the coarse signal as
Unknown.
* feat(transport): record inbound stream origin on streamable HTTP client (#1033)
The worker attaches an InboundStreamOrigin extension to each inbound
server request: Unassociated for the standalone GET stream,
OutboundRequest(id) for a POST's SSE stream. Mirror of the
OriginatingRequestId marker used by the server side.
* feat(service): enforce SEP-2260 client receive-side check per stream origin (#1033)
The event loop maps InboundStreamOrigin plus the in-flight responder
pool to PeerRequestAssociation: restricted requests arriving on the
standalone GET stream are now rejected with -32602 even while unrelated
outbound requests are in flight.
* test: end-to-end SEP-2260 stream-based enforcement over streamable HTTP (#1033)
* docs: cross-link SEP-2260 stream markers
* test: origin marker survives SSE resumption per SEP-2260 (#1033)
A POST SSE stream resumed via GET + Last-Event-ID (SEP-1699) reconnects
beneath execute_sse_stream, so requests replayed after a resume keep
their OutboundRequest origin. Pins the layering invariant: hoisting
reconnection above the marker attach point would wrongly reject
associated requests with -32602.
* docs: trim SEP-2260 comments to spec rationale
* docs: align SEP-2577 expect reason with sibling suppressions
* test: harden SEP-2260 stream-enforcement e2e (#1033)
Detect handler invocation via a channel asserted empty instead of a
panic in a spawned task (swallowed, cannot fail the test); surface
scripted-server misuse as transport errors rather than panics in the
transport task; bound the tail awaits with 5s timeouts. Correct the
header comment: a 2026-07-28 server minting a session id is not
spec-legal (SEP-2567 removes sessions and the GET endpoint) — the
scripted server is deliberately non-conforming, which is the point of
receive-side enforcement.
* test: adapt SEP-2260 association tests to ServerPeerInfo
Rebase onto 3.0.0: RoleClient::PeerInfo is now ServerPeerInfo (#1065)
and its constructor takes the protocol version directly.
* chore: add 'Copy' macro to new PeerRequestAssociation
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
---------
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
* fix: stamp server info on graceful subscription results
* fix: expose subscription server info metadata
---------
Co-authored-by: mrcs64 <9069178+mrcs64@users.noreply.github.com>
* fix(auth): preserve OAuth discovery transport errors
* refactor!: expose domain-specific boxed OAuth HTTP errors
Let custom OAuth HTTP clients preserve native error types and source chains
while keeping the type-erased boundary explicit in the public API.
BREAKING CHANGE: OAuthHttpClientError is now a boxed error alias; custom
clients should return native errors with .into() or box them directly.
---------
Co-authored-by: Theodore Ni <3806110+tjni@users.noreply.github.com>
* refactor!: refactor OAuth client authorization api
`OAuthState::start_authorization` now accepts a declarative `AuthorizationRequest`
describing the client's available identity material and selects the highest-priority
mechanism the server supports: pre-registered client information → Client ID
Metadata Documents (SEP-991) → Dynamic Client Registration.
This replaces the three mechanism-specific entry points (`start_authorization`,
`start_authorization_with_metadata_url`, `start_authorization_with_preregistered_client`),
where callers previously had to know which mechanism to pick. `AuthorizationSession::new`
is consolidated the same way, and the failure-recovery pattern from #994 (returning the
manager alongside the error so `OAuthState` recovers to `Unauthorized` on transient failures)
is now applied across all registration paths. Includes new `RecordingOAuthHttpClient`-based
tests covering the priority matrix and recovery semantics, plus updated docs, examples, and
conformance client.
* fix: dcr registration uses requested application type
* fix: error for invalid combination
* feat: implement SEP-2260 require server requests to associate with client requests
* feat(service): attach originating request id to in-handler outbound requests (SEP-2260)
Reuses the ORIGINATING_REQUEST task-local from #1027; the marker rides
the request's non-serialized Extensions so the streamable HTTP server
can route associated requests to the originating SSE stream.
* feat(transport): route associated server requests to originating SSE stream (SEP-2260)
* test: end-to-end SEP-2260 stream routing over streamable HTTP
* test: register SEP-2260 routing test with required-features; drop dead list_tools
* docs: document SEP-2260 association requirement and stream routing
* docs: fix redundant explicit link on OriginatingRequestId
* docs: note marker is role-agnostic; add reason to deprecated expect
Review follow-ups: the OriginatingRequestId rustdoc now states the marker
is attached for both roles with only the server transport reading it, and
the test's deprecation suppression carries a reason per house style.
* docs: condense inline comments to repo convention
Trims multi-line inline comments added in this branch down to the terse
one-to-two-line style used elsewhere in the codebase, keeping only the
non-obvious rationale (spec references, fallback invariant, version choice).
* docs: condense SEP-2260 rustdoc sections
Tightens the duplicated per-method association section from eleven lines
to five, and trims the marker and SessionManager docs to the same
information in fewer words.
* docs: single-source SEP-2260 caller requirements on OriginatingRequestId
* feat(service): reject unassociated server-to-client requests on the client (SEP-2260)
Implements the client receive-side of SEP-2260: restricted server
requests (sampling/createMessage, roots/list, elicitation/create)
received while the client has no outbound request in flight are
answered with -32602 invalid params instead of being dispatched to the
handler. Gated on negotiated protocol >= 2026-07-28; ping is exempt.
With a request in flight we cannot tell which one the server request
belongs to (SEP-2260 defines no wire field), so this is a deliberate
under-approximation of the spec's SHOULD; exact stream-based
enforcement for streamable HTTP needs receive-side provenance plumbing
and is left as a follow-up.
---------
Co-authored-by: Alex Hancock <alexhancock@block.xyz>
* feat!: implement SEP-2663 Tasks extension, removing the experimental 2025-11-25 tasks design
Reshape tasks from the experimental SEP-1319/1686 core-protocol feature into
the official io.modelcontextprotocol/tasks extension (SEP-2663):
Model:
- Re-model Task (statusMessage, ttlMs nullable, pollIntervalMs) and add
DetailedTask with status-discriminated payloads (inputRequests/result/error
inlined per spec)
- CreateTaskResult now flattens Task with resultType: "task";
add ResultType::TASK and CallToolResponse::Task
- Add tasks/update (UpdateTaskParams with MRTR InputResponses); tasks/get and
tasks/cancel reworked; remove tasks/list, tasks/result
- notifications/tasks now carries a full DetailedTask; removed from client
notifications (SEP-2260)
Capabilities:
- Remove core TasksCapability et al; tasks are declared via the extensions
map (enable_tasks() builders, supports_tasks() accessors)
- Remove tool-level execution.taskSupport and the _meta.task /
TaskMetadata / with_task() opt-in: task creation is server-directed and
gated on the per-request client capability
Runtime:
- Replace OperationProcessor with TaskManager: durable-before-response task
creation, input_required round-trips via tasks/update, cooperative
cancellation, TTL expiry
- Client peer helpers get_task/update_task/cancel_task
- Emit Mcp-Name routing header from params.taskId for tasks/* methods
(SEP-2243/2663)
Macros:
- Remove #[task_handler] and the tool execution() attribute
Tests/examples/docs updated; schema snapshots regenerated.
BREAKING CHANGE: the 2025-11-25 experimental tasks API is removed without a
compatibility shim. Clients that do not declare the tasks extension always
receive synchronous results.
* feat: gate tasks/* methods on the client tasks-extension capability (SEP-2663)
When the server advertises io.modelcontextprotocol/tasks but the client did
not declare it (per-request _meta clientCapabilities, or initialize-time
capabilities in session mode), tasks/get, tasks/update, and tasks/cancel now
return -32021 Missing Required Client Capability with the required extension
in the error data, instead of falling through to the handler's -32601
default. Servers that do not advertise the extension keep returning -32601.
Also add regression tests confirming that unknown taskIds yield -32602 and
that a legacy 2025-11-25 'task' param on tools/call is silently ignored.
* feat: pass SEP-2663 Tasks extension conformance suite
Conformance fixtures (conformance/src/bin/server.rs):
- Add the required fixture tools: greet (sync-only), slow_compute,
failing_job (task support: required), protocol_error_job, confirm_delete,
multi_input, and test_tool_with_task (MRTR -> task escalation), all backed
by TaskManager with server-directed task creation gated on the client's
tasks-extension capability
- Advertise io.modelcontextprotocol/tasks in server capabilities and wire
get_task/update_task/cancel_task handlers
- Task-required tools reject with -32021 when the client did not declare the
extension
SDK wire-shape fixes surfaced by the suite:
- Add resultType: "complete" to GetTaskResult and introduce TaskAckResult
so tasks/update and tasks/cancel acks carry the SEP-2322 discriminator
(spec: every non-CreateTaskResult response on the tasks surface is
resultType complete); dispatch now returns ServerResult::task_ack
- CreateTaskResult gets a strict deserializer requiring resultType: "task"
so it does not shadow task-shaped results in untagged unions
- Client update_task/cancel_task accept both TaskAckResult and EmptyResult
All 9 runnable Tasks extension server scenarios now pass (35/35 checks;
tasks-status-notifications remains upstream-skipped), so the corresponding
entries are removed from conformance/expected-failures-extensions.yaml.
2025-11-25 server suite (40/40), 2026-07-28 server suite (114/114), draft
client suite, and extensions client suite all pass their baselines.
* fix: address PR 1020 review feedback on DetailedTask schema and cooperative cancel
- DetailedTask's JsonSchema now derives from the actual flattened wire shape
(DetailedTaskWire: base Task + optional inputRequests/result/error) instead
of approximating with the base Task schema, so generated schemas for
GetTaskResult and notifications/tasks document the status-specific payload
fields. Golden message schemas regenerated.
- TaskManager::cancel_task no longer aborts the underlying future. It records
the observable cancelled state and acks immediately (spec's eventually
consistent semantics), but lets the operation keep running so it can observe
is_cancel_requested() or the error from a woken request_input() and perform
cleanup; any late result is discarded. New unit tests cover both the
cooperative-cleanup path and waking parked input requests.
* fix: make tasks/cancel truly cooperative per SEP-2663 (FEEDBACK_2)
- TaskManager::cancel_task no longer forces terminal 'cancelled'. It records
the cancellation intent, acks immediately, and wakes parked request_input
awaits, but the operation decides its own terminal state: a post-cancel
error settles as 'cancelled', while an operation that finishes its work
settles as 'completed' — per the spec, 'the task may still reach a
non-cancelled terminal status'.
- Add TaskContext::cancelled(), a watch-based await for use with
tokio::select! as the cooperative cancellation exit path.
- Correct the unsupported-notification method string from
'notifications/tasks/status' to 'notifications/tasks' and document that
task status notifications are not yet routable through subscriptions/listen
(SubscriptionFilter has no taskIds field; upstream check still skipped).
- Update conformance slow_compute fixture, task_demo example, and tests to
honor cancellation via ctx.cancelled(); lifecycle conformance still 8/8
(all 9 scenarios remain green, 35/35 checks).
* fix: sweep and evict expired tasks from TaskManager (FEEDBACK_3)
TTL handling previously only ran from get_task and only flipped overdue
non-terminal tasks to 'failed', never removing entries — an unbounded leak
for long-lived servers, and it made ttl_ms: None = 'unlimited retention'
meaningless since everything was retained forever.
- Rename expire_overdue to sweep_expired and run it from every entry point
(spawn, get_task, update_task, cancel_task).
- Track terminal_at on each entry; terminal tasks are evicted after being
retained for one further ttl_ms window past their terminal transition, so
well-behaved pollers can observe the final state before late tasks/get
calls return -32602 (spec: servers may delete expired tasks at any time,
and returning task-not-found for purged tasks is compliant behavior).
- ttl_ms: None entries are never evicted (spec: unlimited retention);
document the retention model on TaskManager, including that there is no
background sweeper.
- New tests: retention-window eviction, sweep of abandoned tasks via other
entry points, unlimited-TTL retention, and error-code assertions
(-32602) for unknown ids across get/update/cancel.
Reviewed the second feedback item (dedicated task-not-found error code)
against SEP-2663 §Protocol Errors and it is incorrect: the SEP explicitly
specifies -32602 (Invalid params) for invalid or nonexistent taskIds, which
is what unknown_task already returns. Kept -32602; strengthened tests to
assert the code.
* fix: address Copilot review feedback on PR #1020
- TaskManager: drop the JoinHandle as soon as the operation settles instead
of retaining it for the whole retention window, and only store it at spawn
time if the task is still non-terminal (avoids keeping a completed handle
that the completion path could never clear).
- Use RequestContext::client_capabilities() (which applies the initialize-time
fallback for session peers) instead of raw context.meta.client_capabilities()
in the task_demo example, the README snippet, and the test server — the
meta-only form would wrongly treat session-declared tasks clients as
unsupported.
All 9 Tasks extension conformance scenarios remain green (35/35 checks).
* fix: enforce SEP-2663 task-result gating in tools/call dispatch
A handler could return CallToolResponse::Task without checking whether the
request declared the io.modelcontextprotocol/tasks extension, sending a
CreateTaskResult to a client that cannot parse it. The SDK dispatch now
rejects that case with -32021 Missing Required Client Capability before the
response leaves the server, using RequestContext::client_capabilities()
(per-request _meta with initialize-time fallback).
Adds a regression test with a deliberately misbehaving handler that always
materializes a task; all Tasks extension conformance scenarios remain green
(35/35 checks).
* fix: align TTL boundary comparisons in sweep_expired
Copilot review: ttlMs: 0 never expired immediately because phase 1 used a
strict 'elapsed > ttl_ms' comparison, and phase 2 retained terminal tasks
at exactly the TTL boundary ('elapsed <= ttl_ms'). Treat elapsed >= ttl_ms
as expired in phase 1 and evict when elapsed >= ttl_ms in phase 2, so both
phases agree at the boundary and ttlMs: 0 expires/evicts on the first sweep.
* fix: strict TaskAckResult deserializer and TASK_REQUIRED_TOOLS consistency
- TaskAckResult carried only resultType (+ optional _meta) with a derived
Deserialize, so inside the untagged ServerResult union it greedily matched
any result object containing a resultType key, shadowing CustomResult and
losing data (verified with a probe). Replace with a strict deserializer:
deny_unknown_fields and require resultType == "complete". Regression
tests cover both the non-matching shapes and the genuine ack shape.
- Conformance fixtures: confirm_delete and multi_input rejected non-tasks
clients inline, contradicting the TASK_REQUIRED_TOOLS doc/constant. Move
them into TASK_REQUIRED_TOOLS (they park on in-task elicitation and have
no synchronous fallback) so the upfront -32021 gate is the single source
of truth, and drop the now-unreachable inline checks.
All 9 Tasks extension conformance scenarios remain green (35/35 checks).
* fix: let the operation decide its terminal state via TaskExit
After tasks/cancel, any operation error was coerced to terminal
'cancelled', masking real failures (e.g. an unrelated error landing just
after a late cancel request) and contradicting the documented 'operation
decides its own terminal state' contract.
Change TaskFuture's error type from McpError to a new TaskExit enum:
- TaskExit::Cancelled — an explicit cooperative-cancellation exit;
settles as terminal 'cancelled'.
- TaskExit::Error(McpError) — a real failure; settles as terminal
'failed' with the error inlined, even after tasks/cancel was received.
From<McpError> for TaskExit keeps '?' ergonomic in task bodies, and
request_input() now returns TaskExit directly (its wake-on-cancel path
yields TaskExit::Cancelled), so parked operations that propagate it with
'?' settle as 'cancelled' automatically.
Update the conformance fixtures, task_demo example, and tests; add a
regression test asserting a post-cancel unrelated error settles as
'failed' with its error payload preserved.
All 9 Tasks extension conformance scenarios remain green (35/35 checks).
* fix: allow TaskExit enum to be exhaustive
* fix: close spawn/shutdown race, sweep in running_task_count, clarify TTL retention docs
Addresses branch-review findings:
- spawn() raced with shutdown(): if shutdown drained the task map between
the entry insert and the JoinHandle store, the handle was dropped and the
operation kept running detached. If the entry is gone at store time, the
handle is now aborted instead.
- running_task_count() now runs the TTL sweep like every other entry point,
so it no longer reports overdue tasks as running (matching the documented
sweep-on-every-entry-point behavior). Regression test added.
- Document that terminal-task retention intentionally extends one ttl_ms
window past the terminal transition (observation grace period) beyond the
creation-based lifetime ttlMs advertises on the wire — compliant since
SEP-2663 allows deleting expired tasks at any time after the TTL.
fixes#1001.
Restores explicit dispatch arms for the ten client scenarios orphaned by #991:
standard auth flow:
- `auth/iss-*`
- `auth/offline-access-*`
- `auth/metadata-issuer-mismatch`
- `auth/authorization-server-migration`
plain connect/list client:
`json-schema-ref-no-deref`
`run_auth_client` now negotiates via `ClientLifecycleMode::Discover` —
`auth/authorization-server-migration` tracked in #879
A stateless streamable-HTTP request is one-shot (no session, no resumption),
so if the client drops the response before the handler finishes, the request
is terminal and should be cancelled. Previously the handler kept running with
its `RequestContext::ct` never firing, so long-running or destructive tools
could not observe a client disconnect.
Give each stateless request its own cancellation token via
`serve_directly_with_ct` and cancel it when the client disconnects. This covers
both stateless paths: `serve_negotiated_request_directly` (per-request version
negotiation) and the non-negotiated path. In each:
- A disconnect while the handler is still producing its first message cancels
it. The guard is disarmed once the handler emits anything, so a normal
response is never cancelled.
- The SSE response stream is wrapped in a guard that cancels the handler if the
stream is dropped before it ends naturally.
- When a negotiated request replies directly (JSON mode, or a non-OK status),
the receiver is dropped, so a still-running handler is cancelled rather than
left emitting into a closed channel. Without this its terminal send fails
before adding the termination permit and the serve loop parks forever.
Stateful (resumable) mode is intentionally left unchanged: there a disconnect
may be recovered via `Last-Event-ID`, so cancelling on disconnect would break
resumption.
Adds a regression test covering both stateless sub-modes (SSE and JSON).
* fix(auth): validate discovered metadata issuer
Validate authorization server metadata issuers against the issuer implied by
standard discovery URLs before trusting advertised endpoints.
fixes#983
* test(auth): add required issuer to authorization-server mock metadata
---------
Co-authored-by: Alex Hancock <alexhancock@block.xyz>
SEP-2350 [1] clarifies that scope accumulation is a client-side
responsibility: during re-authorization the client requests the union of
its previously requested scopes and the newly challenged scopes, because
servers report only the scopes needed for the current operation in
403 / insufficient_scope challenges (RFC 6750 §3.1), not the union of
everything granted so far.
select_base_scopes returned a single source, so a 403 challenge replaced
the previously requested scopes instead of widening them, dropping prior
permissions across step-up rounds. I make it union the previously
requested scopes, the WWW-Authenticate challenge, and the protected
resource metadata scopes (RFC 9728), treating each server-reported set as
an operational requirement for the current operation rather than an
exclusive directive; AS metadata and caller defaults only seed the
request when nothing has been requested or challenged yet.
exchange_code_for_token treats an explicit scope list as authoritative,
so a server may still narrow the grant. When the server omits scope it
has granted exactly what the client requested (RFC 6749 §5.1), so the
grant has to fall back to the scopes requested in this round, not the
previously granted set; otherwise a step-up that the server confirms by
omitting scope would silently drop the just-added permission and the
client would loop on the same 403. The widened request was not persisted
anywhere the exchange could read it, so I record it on
StoredAuthorizationState per authorization (defaulting empty for states
stored before this field existed) and resolve the grant from there. This
addresses review feedback [2] that the earlier fallback returned the
previous grant rather than the request. Deduplication preserves
first-seen order for stable, testable output. Tests cover multi-round
accumulation, dedup, resource-metadata unioning, and grant resolution
when the response omits scope. Implements [3].
[1]: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/draft/basic/authorization.mdx#L682
[2]: https://github.com/modelcontextprotocol/rust-sdk/pull/888#pullrequestreview-4454854582
[3]: https://github.com/modelcontextprotocol/rust-sdk/issues/877
Signed-off-by: Stefano Amorelli <stefano@amorelli.tech>
* feat!: add MRTR behavior support
* feat: harden SEP-2322 MRTR support
* ci: diff public API only on features common to base and head
cargo public-api builds both revisions with the same feature set, so a
feature introduced (or removed) by a PR broke the build of the other
revision. Restrict the all-features diff to features present in both the
base and head revisions.
* fix: address PR review - schema_for_output no longer validates or returns Result
- Add strip_output() that strips title/description without validating type (Dale #1)
- Change schema_for_output to return Arc<JsonObject> instead of Result (Dale #2)
- Cache only Arc<JsonObject> success values, not Result (Dale #3)
- Remove dead unwrap_or_else panic paths in with_output_schema, ToolBase, and macros
- Tighten test assertions from contains to assert_eq on type field (Dale #4)
- Update test_schema_for_output_rejects_primitive to accept_primitive (SEP-2106)
Co-authored-by: Orca <help@stably.ai>
* test(rmcp): add non-object output schema tests for SEP-2106
Add tests verifying schema_for_output accepts non-object types:
- test_tool_builder_methods: primitive (i32), array (Vec<String>), option
- test_structured_output: tool returning Json<Vec<T>> and Json<i32>
- test_json_schema_detection: Json<Vec<T>>, Result<Json<Vec<T>>,E>, Json<String>
- tool_traits: ToolBase::output_schema with Vec<AddOutput> output type
* test(rmcp): add missing edge case tests from code review
Add tests identified during code review:
- description stripping for primitive types
- composition types (Option<String> with anyOf/oneOf/null)
- cache correctness (Arc::ptr_eq for repeated calls)
- schema_for_input rejecting array types (not just primitives)
- schema_for_output accepting unit type ()
* feat!: mark schema_for_output return-type change as breaking
This introduces SEP-2106: schema_for_output no longer validates or
returns Result. The public signature changed, so bump major.
* fix: address Dale's PR review - direct schema.get assertions, remove ArrayTool
- Replace loose schema_str.contains(...) assertions with direct
schema.get("type") equality checks in test_tool_builder_methods.rs
and test_structured_output.rs
- Remove redundant ArrayTool fixture and its round-trip
serde_json::from_str test from tool_traits.rs since schema is
already Arc<JsonObject>
- Drop dead schema_str variable in test_structured_output.rs
---------
Co-authored-by: Brandon Bennett <brandonbennett@macbookair.myfiosgateway.com>
Co-authored-by: Orca <help@stably.ai>
Co-authored-by: Brandon Bennett <brandonbennett@Pursuits-Air.lan>
Re-applies #919 (reverted by #932): ToolResultContent.structured_content
becomes Option<Value> so non-object structured content is accepted,
matching CallToolResult and SEP-2106.
BREAKING CHANGE: ToolResultContent.structured_content changes from
Option<JsonObject> to Option<Value>.
* fix(auth): support oauth metadata fallbacks
* ci: run client conformance scenarios
* fix: pass full client conformance suite
* ci: run full client conformance suite
* fix: update SSE stream constructor
* fix: interpret task ttl as milliseconds
* fix: use text/plain for default text mime type
* fix: include resource param in token refresh
* test: align conformance prompt args with runner
* ci: run server conformance suite on PRs
* ci: build client bin and gate pending scenarios
`receive()` reads incoming lines with `read_until`, which is not
cancellation-safe, and it is polled inside the service loop's `select!`.
When another branch (e.g. an outgoing response) becomes ready while a
request line is only partially read, the `receive()` future is dropped
and the next call's `self.line_buf.clear()` discards the partial bytes,
so that incoming request is silently lost and never gets a response.
Under many concurrent large responses this intermittently drops requests.
Keep the partially-read bytes in `line_buf` across calls and clear it
only after a whole line has been consumed, so a cancelled read resumes
the same line instead of dropping it. The buffer is cleared (retaining
capacity) rather than reallocated per message.
Adds a regression test that fires 200 concurrent 64 KiB tool responses
over real stdio pipes and asserts no response id goes missing.
This also covers the child-process client transport, which reuses
`AsyncRwTransport`.
Per RFC 6749 section 6 and OAuth 2.1: when the server does not issue a new
refresh_token on a refresh response, the client MUST keep the existing one.
AuthorizationManager::refresh_token() was persisting the response verbatim,
dropping the previous refresh_token and forcing full re-authorization on
the next refresh.
Match the fix from python-sdk#2270: preserve the existing refresh_token
when the response omits it, replace when the server rotates.
Fixes#921
Signed-off-by: SarthakB11 <sarthak.bhardwaj21b@iiitg.ac.in>
* fix: don't respond to unparseable messages
* docs: spell 'unparsable' to satisfy typos linter
* fix: only ignore unparsable JSON, keep protocol errors visible
Classify the serde error in the receive loop: syntax/EOF errors are
unparsable input with no correlatable id (issue #938) and stay silent,
while data errors (valid JSON that doesn't match the message shape) are
real protocol errors and get an error response instead of being dropped.
Add a test covering the protocol-error path.
* fix: respond with Invalid Request for malformed protocol messages
---------
Co-authored-by: tsouth89 <tsouth89@users.noreply.github.com>
Expose typed accessors for the per-request protocol version, client info,
client capabilities, and log level entries carried in _meta without making
those fields required for older peers.
Fixes#869
* chore: bump Rust toolchain to 1.96
* ci: add cargo-public-api breaking-change check
Adds a release-type-aware `cargo-public-api` diff job that fails on
changed/removed public items unless the PR's commits mark a breaking
(major) release. This catches source-breaking API changes that
cargo-semver-checks cannot yet detect (e.g. function return-type or
field-type changes).
The spec's prompt-message ContentBlock union is
`text | image | audio | resource_link | resource`, but
PromptMessageContent omitted `Audio`. Because the enum is
`#[serde(tag = "type")]` with no catch-all, a spec-conformant
`{"type":"audio",...}` content block failed to deserialize with
"unknown variant `audio`", breaking prompts/get for any server that
returns audio prompt content (the audio analogue of #842 / #843).
The supporting AudioContent type already existed, and Audio was
already a variant of the general RawContent enum (tool results,
sampling) -- only PromptMessageContent lacked it.
Add the flattened Audio variant (mirroring Image), a
PromptMessage::new_audio constructor (mirroring new_image), and
serialization + deserialization regression tests.
Fixes#864.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(elicitation): preserve enumNames through ElicitationSchema serde round-trip
UntitledSingleSelectEnumSchema lacked deny_unknown_fields, so a legacy
enum payload containing enumNames was silently matched by that variant
(ignoring the field) rather than falling through to LegacyEnumSchema.
The enumNames array was lost on re-serialization.
Add deny_unknown_fields to UntitledSingleSelectEnumSchema so that any
unknown field (including enumNames) causes serde to try the next
untagged variant, reaching LegacyEnumSchema correctly.
Also add skip_serializing_if = "Option::is_none" to
LegacyEnumSchema::enum_names so that an untitled legacy enum without
enumNames does not serialize "enumNames": null.
Fixes#903
* test(elicitation): regenerate server schema snapshot for deny_unknown_fields
deny_unknown_fields on UntitledSingleSelectEnumSchema makes schemars
emit additionalProperties: false for that definition. Regenerate the
golden schema fixtures to match (UPDATE_SCHEMA=1 cargo test -p rmcp
--test test_message_schema --all-features).
* docs(server): document Err vs Ok(CallToolResult::error) visibility contract
The MCP spec separates two failure modes that surface very differently in
clients:
- Err(ErrorData) is a JSON-RPC protocol error. Most MCP clients render
it opaquely ("Tool result missing due to internal error") - the
caller does not see the message text.
- Ok(CallToolResult::error(content)) is a tool-level error. Clients
render the content; the caller reads the message.
The right shape for "the tool didn't work" is the latter, but Err is
what most handlers reach for because it looks like the natural Rust
return value. This commit adds rustdoc on both ServerHandler::call_tool
and CallToolResult::error pointing handlers at the correct shape, with
a worked example showing protocol errors (-32602 invalid_params) vs
tool errors (empty result, downstream failure).
This is the docs half of the visibility-contract ask. A follow-up may
introduce a typed ToolOutcome sum type to enforce the distinction at
compile time; this PR is the lower-risk version that unblocks the
class immediately.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: update crates/rmcp/src/handler/server.rs
* docs: update crates/rmcp/src/model.rs
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
* feat: implement SEP-2164 resource not found errors
* test: update protocol version utility expectations
* feat: gate not-found code at server boundary
---------
Co-authored-by: Michael Neale <michael.neale@gmail.com>
* feat(auth): specify OIDC application_type during client registration
SEP-837 [1] requires an MCP client to specify an application_type during
OIDC Dynamic Client Registration. When it is omitted, OIDC servers
default the client to "web", which conflicts with the loopback redirect
URIs that CLI and desktop clients use, so the registration can be
rejected.
I make register_client always send an application_type. It defaults to
"native" to match the loopback redirect this SDK uses, and I added
OAuthClientConfig::with_application_type so web clients can opt in. Tests
cover the serialized request body and the config default. Implements [2].
[1]: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/draft/basic/authorization.mdx#L395
[2]: https://github.com/modelcontextprotocol/rust-sdk/issues/880
Signed-off-by: Stefano Amorelli <stefano@amorelli.tech>
* chore(auth): declare application_type in client metadata document
I set application_type to "native" in the hosted client metadata
document so the URL-based client id flow and dynamic registration agree
on the client type that SEP-837 [1] expects.
[1]: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/draft/basic/authorization.mdx#L395
Signed-off-by: Stefano Amorelli <stefano@amorelli.tech>
---------
Signed-off-by: Stefano Amorelli <stefano@amorelli.tech>
SEP-2577 deprecates the Roots, Sampling, and Logging features. The
deprecation is advisory: the features stay fully functional and there is
no wire-level change. Mark the corresponding Rust APIs as deprecated so
downstream users get compiler warnings and migration guidance.
- Forward attributes through the service `method!` macros and deprecate
`Peer::create_message`, `Peer::list_roots`, `Peer::set_level`, and
`Peer::notify_logging_message`.
- Forward per-field attributes through the capability `builder!` macro and
deprecate the generated `enable_roots`, `enable_sampling`, and
`enable_logging` builders, plus the hand-written
`enable_roots_list_changed`, `enable_sampling_tools`, and
`enable_sampling_context`.
- Document the deprecation on the capability types and fields, and in the
README feature sections.
- Allow `deprecated` at the crate's own call sites so the build stays
warning-clean, and refresh the message schema snapshots.
The Resource variant of PromptMessageContent was missing #[serde(flatten)],
causing the embedded resource content block to serialize as a double-nested
shape `{ "type": "resource", "resource": { "resource": {...} } }` instead of
the spec-compliant flat shape `{ "type": "resource", "resource": {uri, mimeType, text} }`.
This caused Zod-based MCP clients (e.g. Claude Code) to reject prompts/get
responses containing embedded resource messages with InvalidUnion errors.
The Image and ResourceLink variants already use #[serde(flatten)] correctly;
only Resource was missing it.
Fix: add #[serde(flatten)] so EmbeddedResource (=Annotated<RawEmbeddedResource>)
fields _meta / annotations / resource are flattened to the content-block level,
matching the MCP spec for prompts embedded resources.
Regression test: test_prompt_message_resource_serialization_is_flat verifies
content.resource.uri is reachable and content.resource.resource is absent.
Schema snapshots regenerated via UPDATE_SCHEMA=1.
* fix(transport): downgrade idle timeout log from error to debug
Idle keep-alive timeout is normal zombie-session cleanup, not a transport failure.
Route it through a dedicated WorkerQuitReason::IdleTimeout variant.
Log it at debug level instead of treating it as a fatal error.
Remove the unused LocalSessionWorkerError::KeepAliveTimeout variant.
Closes#817
* fix(session): tolerate dead worker in close_session
Swallow SessionServiceTerminated in close_session when the worker has already exited.
This prevents a spurious ERROR log during the post-exit cleanup path in
spawn_session_worker.
* fix(transport): address PR review feedback
- deprecate KeepAliveTimeout
- harden tests
* feat(router): support runtime disabling of tools
Add methods to disable/enable tools at runtime.
Disabled tools are hidden from listing, lookup,
and execution, including in composed routers.
Closes#477
* fix(router): simplify disable tool api
* feat(router): auto-send tools/list_changed on disable/enable
* refactor(router): simplify disable_route and notifier call
The README examples used `#[tool(param)]` on function parameters,
which is not a supported syntax and fails to compile. Replace with
the `Parameters<T>` wrapper pattern that the macros actually expect.
Closes#812
In fetch_resource_metadata_from_url, a JSON parse failure on the
response body caused a fatal AuthError::MetadataError, preventing
discover_metadata() from falling through to direct
.well-known/oauth-authorization-server discovery (Strategy B).
MCP servers that return HTTP 200 with non-JSON content (e.g. HTML)
at their base URL caused the OAuth flow to abort entirely, even
when the server had a valid .well-known/oauth-authorization-server
endpoint.
Return Ok(None) on parse failure, consistent with how HTTP errors
are already handled in the same function.
* fix: include http_request_id in request-wise priming event IDs
* refactor: use Option::into_iter and usize::from for priming
* fix: retain event cache for completed request-wise channels
* fix: track completed_at for cache eviction and resume
* fix: log resume failures at warn level
* test: add completed_cache_ttl eviction test
* fix: return empty stream on failed resume
* test: add resume after completion test
* fix(http): reduce latency on subsequent StreamableHttp calls
* refactor: rely on stream drain for connection reuse
* refactor: clean up comments and naming
* fix: restore pool_max_idle_per_host(0) for Linux
AuthRequiredError, InsufficientScopeError, and DynamicTransportError
were marked #[non_exhaustive] in #715/#768 but don't have constructors
usable by external crates. Add new() for the error types and
from_parts() for DynamicTransportError (the existing new() requires a
Transport type parameter, making it unusable for test fixtures).
Fixes#805
* fix(server): remove initialized notification gate to support Streamable HTTP
The server's init handshake loop fatally rejected any request arriving
before the `notifications/initialized` message. This breaks Streamable
HTTP clients where each JSON-RPC message is a separate POST with no
ordering guarantee — `tools/list` can easily arrive before `initialized`.
Remove the ~40-line wait loop and enter `serve_inner` immediately after
sending `InitializeResult`. The `initialized` notification is now
handled as a regular notification by the main service loop, matching the
TypeScript SDK behavior (validated in typescript-sdk#578).
Also remove the now-unreachable `ExpectedInitializedNotification` error
variant from `ServerInitializeError`.
Closes#783
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(server): keep ExpectedInitializedNotification as deprecated
Retain the variant for semver compatibility — removing it would be a
breaking change caught by cargo-semver-checks. Mark it deprecated with
a note that it is never constructed and will be removed in a future
major release.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Anar Azadaliyev <anar.azadaliye@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(macros): auto-generate get_info and default router
* docs: simplify examples and docs with new defaults
* feat(macros): add tool_router(server_handler) to elide separate #[tool_handler] impl
* docs: add Tools section to README and simplify calculator examples with server_handler
* feat(transport): add which_command for cross-platform executable resolution
Adds a `which_command()` helper that resolves executable paths via the
`which` crate before constructing a `tokio::process::Command`. This fixes
Windows failures where `.cmd` shim scripts (e.g. `npx.cmd`) are not
found by `Command::new()` without a fully-qualified path.
Closes#456
* refactor(transport): move which_command behind opt-in feature flag
Address review feedback: the `which` dependency is now gated behind a
separate `which-command` feature flag instead of being bundled into
`transport-child-process`. Users on Linux/macOS who don't need
cross-platform executable resolution no longer pull in the extra crate.
Also fixes the doc example import path to use the re-exported
`rmcp::transport::which_command`.
* fix: example clients_everything_stdio
* Apply suggestion from @DaleSeo
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
---------
Co-authored-by: Alex Hancock <alexhancock@block.xyz>
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
The `local` feature relaxes Send+Sync bounds, which causes items
gated behind `cfg(not(feature = "local"))` to be excluded when
docs.rs builds with all-features. Replace `all-features = true`
with an explicit feature list that omits `local`.
Signed-off-by: majiayu000 <1835304752@qq.com>
StoredCredentials is #[non_exhaustive] but has no constructor, making
it impossible for external crates implementing CredentialStore to
construct instances without a serde roundtrip workaround. Add a new()
constructor matching the pattern used for other #[non_exhaustive]
types in this crate.
Fixes#777
* feat: add theme field to Icon
* fix: update IconThem crates/rmcp/src/model.rs (non_exhaustive)
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
* fix: update IconThem crates/rmcp/src/model.rs (eq, hash)
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
* fix: update docs with full descriptions of theme from mcp spec
---------
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
* feat(transport): add Unix domain socket client for streamable HTTP
MCP hosts in Kubernetes environments with Envoy sidecars need to route
HTTP through Unix domain sockets because DNS-based URIs only resolve
via the proxy. Adds UnixSocketHttpClient implementing StreamableHttpClient
using hyper over tokio::net::UnixStream, gated behind the
transport-streamable-http-client-unix-socket feature.
Also extracts RESERVED_HEADERS, extract_scope_from_header, and
validate_custom_header into common/http_header.rs to share header
validation logic between the reqwest and unix socket implementations.
* fix(transport): address review feedback for unix socket transport
- Document one-connection-per-request behavior on UnixSocketHttpClient
- Reject empty socket paths and bare '@' in constructor with assert
- Add explicit dep:http to unix-socket feature for self-documenting deps
- Document MCP-Protocol-Version exception on RESERVED_HEADERS constant
- Fix test catch-all to echo request id instead of hardcoding 1
- Remove leftover sleep(100ms) in test_unix_socket_custom_headers
- Add blank line before macro comment in Cargo.toml
* fix(transport): fix CI failures for unix socket transport
- Use std::io::Error::other() instead of Error::new(ErrorKind::Other)
to satisfy clippy::io_other_error on newer nightly
- Use #[tokio::test(flavor = "current_thread")] for unix socket tests
since axum's serve(UnixListener) requires spawn_local
- Gate validate_custom_header behind client-side-sse feature since it
references http::HeaderName which isn't available with default features
* fix(transport): fix CI failures for unix socket transport
axum::serve(UnixListener) uses spawn_local on Linux, which panics
outside a LocalSet. Replace with manual hyper HTTP/1.1 server that
accepts connections directly from the UnixListener, avoiding the
spawn_local requirement entirely.
* fix(transport): skip unix socket tests when local feature is enabled
The local feature causes ().serve(transport) to use spawn_local, which
requires a LocalSet. Gate the integration tests with not(feature = "local")
to match every other integration test in the repo.
The `#[serde(default)]` on `CallToolResult.content` (added in #752) made
all fields optional, causing `CallToolResult` to greedily match any JSON
object during `#[serde(untagged)]` deserialization of `ServerResult`.
Similarly, `GetTaskPayloadResult(Value)` matched everything before
`CustomResult(Value)` could be reached.
Fix by replacing derived `Deserialize` impls with custom ones:
- `CallToolResult`: require at least one known field to be present
- `GetTaskPayloadResult`: always fail (indistinguishable from
`CustomResult` in JSON; construct programmatically via `::new()`)
* feat: add configuration for transparent session re-init
* fix: in ci revert running tests without local until all tests pass
* fix: pr comments
* fix: documentation
* fix(rmcp): surface JSON-RPC error bodies on HTTP 4xx responses
When a server returns a 4xx status with Content-Type: application/json,
attempt to deserialize the body as a ServerJsonRpcMessage before falling
back to UnexpectedServerResponse. This allows JSON-RPC error payloads
carried on HTTP error responses to be surfaced as McpError instead of
being lost in a transport-level error string.
Fixes#724
* fix(rmcp): surface JSON-RPC error bodies on HTTP 4xx responses
When a server returns a 4xx status with Content-Type: application/json,
attempt to deserialize the body as a ServerJsonRpcMessage before falling
back to UnexpectedServerResponse. This allows JSON-RPC error payloads
carried on HTTP error responses to be surfaced as McpError instead of
being lost in a transport-level error string.
Fixes#724
* fix(rmcp): only accept JsonRpcMessage::Error on non-success responses
* fix(auth): redact secrets in Debug output for StoredCredentials and StoredAuthorizationState
Removes `Debug` from the derive macros on `StoredCredentials` and
`StoredAuthorizationState` and replaces them with manual `Debug` impls
that print `[REDACTED]` for sensitive fields (access/refresh tokens,
PKCE verifiers, and CSRF tokens), preventing accidental credential
leakage via `{:?}` formatters, log calls, and error chains.
Fixes#741
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test(auth): assert Debug output redacts secrets for credential types
Adds regression tests for the fix in the previous commit, verifying
that `{:?}` formatting of `StoredAuthorizationState` and
`StoredCredentials` does not emit plaintext secrets.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test(auth): address review feedback on debug redaction tests
- Remove redundant VendorExtraTokenFields from use super:: in
test_stored_credentials_debug_redacts_token_response (already
imported at module scope)
- Add assert!(debug_output.contains("created_at")) to
test_stored_authorization_state_debug_redacts_secrets to verify
non-secret fields remain visible in Debug output
- Run cargo fmt
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Update crates/rmcp/src/transport/auth.rs
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
* fix: remaining formatting issue
* fix: formatting
* fix: formatting
* fix: please
---------
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>