Compare commits

...
Author SHA1 Message Date
dependabot[bot]
dbd2382755
chore(deps): update rstest requirement from 0.26.1 to 0.27.0 (#1276)
Some checks failed
CI / Lint Commit Messages (push) Has been cancelled
CI / Code Formatting (push) Has been cancelled
CI / Lint with Clippy (push) Has been cancelled
CI / SemVer Check (push) Has been cancelled
CI / Public API Check (push) Has been cancelled
CI / spell check with typos (push) Has been cancelled
CI / Check MSRV (push) Has been cancelled
CI / Run Tests (push) Has been cancelled
CI / Run Tests (no local feature) (push) Has been cancelled
CI / Code Coverage (push) Has been cancelled
CI / Example test (push) Has been cancelled
CI / Security Audit (push) Has been cancelled
CI / Generate Documentation (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
CodeQL / Analyze-1 (push) Has been cancelled
CodeQL / Analyze-2 (push) Has been cancelled
CodeQL / Analyze-3 (push) Has been cancelled
Conformance / server (push) Has been cancelled
Conformance / client (push) Has been cancelled
Release-plz / Release-plz release (push) Has been cancelled
Release-plz / Release-plz PR (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
CI / Release crates (push) Has been cancelled
Updates the requirements on [rstest](https://github.com/la10736/rstest) to permit the latest version.
- [Release notes](https://github.com/la10736/rstest/releases)
- [Changelog](https://github.com/la10736/rstest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/la10736/rstest/compare/v0.26.1...v0.27.0)

---
updated-dependencies:
- dependency-name: rstest
  dependency-version: 0.27.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-18 13:47:35 -04:00
dependabot[bot]
9f7ace357a
chore(deps): bump the codeql-action group with 4 updates (#1277)
Bumps the codeql-action group with 4 updates: [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/autobuild](https://github.com/github/codeql-action), [github/codeql-action/analyze](https://github.com/github/codeql-action) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action).


Updates `github/codeql-action/init` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](cdf488f595...b96794f015)

Updates `github/codeql-action/autobuild` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](cdf488f595...b96794f015)

Updates `github/codeql-action/analyze` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](cdf488f595...b96794f015)

Updates `github/codeql-action/upload-sarif` from 4.37.3 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](e4fba868fa...b96794f015)

---
updated-dependencies:
- dependency-name: github/codeql-action/init
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: codeql-action
- dependency-name: github/codeql-action/autobuild
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: codeql-action
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: codeql-action
- dependency-name: github/codeql-action/upload-sarif
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: codeql-action
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-18 13:47:13 -04:00
dependabot[bot]
011f281ced
chore(deps): bump astral-sh/setup-uv from 10.0.1 to 10.1.0 (#1278)
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 10.0.1 to 10.1.0.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](20cfd1bf94...bec219d24c)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-version: 10.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-18 13:46:56 -04:00
dependabot[bot]
0cfbe7f453
chore(deps): bump taiki-e/install-action from 2.87.6 to 2.87.12 (#1279)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.87.6 to 2.87.12.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](7b8d4719ee...3f74d7c16a)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.87.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-18 13:46:37 -04:00
github-actions[bot]
fd7811fdaa
chore: release v3.4.0 (#1258)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-09-15 11:37:39 -04:00
Dale Seo
0550e13c1b
fix(rmcp): use ServerConfig in cancellation test (#1273) 2026-09-15 11:18:33 -04:00
Auro
b037c0fa88
fix(rmcp): route peer cancellation by lifecycle (#1262)
* 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>
2026-09-14 16:22:57 -04:00
Dale Seo
d481cb0eec
fix: run first pre-init request in service loop (#1263) 2026-09-14 15:45:05 -04:00
Dale Seo
47fcdf4b57
fix(auth): let url origin decide prm discovery (#1264) 2026-09-14 15:30:52 -04:00
Dale Seo
165ff92df1
feat(model): add ServerConfig and ClientConfig (#1266) 2026-09-14 15:30:41 -04:00
Jack Amadeo
fbfc5cc96e
ci: add OpenSSF Scorecard analysis (#1214) 2026-09-14 12:01:32 -04:00
Teddy Tennant
3075dc9152
fix(model): deprecate ServerInfo and ClientInfo aliases (#1156)
* 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.
2026-09-12 12:11:30 -04:00
easyinplay
a5d1169e20
fix(auth): ignore non-metadata JSON when probing for protected resource metadata (#1204)
* 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>
2026-09-12 11:21:03 -04:00
Sebastien Tardif
4fa84a5130
fix: do not treat malformed JSON 200 as Accepted for requests (#1208)
* 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>
2026-09-12 10:42:12 -04:00
voidstack
b86995aebd
fix(streamable-http-server): map handler-generated HeaderMismatch to HTTP 400 (#1259)
`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>
2026-09-11 20:54:40 -04:00
Luca
e27c5d1c24
fix(http): enforce Origin validation semantics (#1192)
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>
2026-09-10 21:38:27 -04:00
github-actions[bot]
3e636cab26
chore: release v3.3.0 (#1252)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-09-10 11:23:32 -04:00
Jack Amadeo
b2c90b1edc
ci: pin commitlint dependencies (#1217) 2026-09-10 10:05:55 -04:00
ump45nose
46db531df9
fix(sse): saturate exponential reconnect backoff to avoid overflow panic (#1231)
* 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.
2026-09-09 21:24:29 -04:00
dependabot[bot]
744b9f904c
chore(deps): bump crate-ci/typos (#1249)
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1a51d4b5a03bb97576af186c813af67e9137ba7c to d43b6c087ac471e2ea7b8af622ff15f05c0c365b.
- [Release notes](https://github.com/crate-ci/typos/releases)
- [Changelog](https://github.com/crate-ci/typos/blob/master/CHANGELOG.md)
- [Commits](1a51d4b5a0...d43b6c087a)

---
updated-dependencies:
- dependency-name: crate-ci/typos
  dependency-version: d43b6c087ac471e2ea7b8af622ff15f05c0c365b
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-08 20:24:44 -04:00
dependabot[bot]
e8a0d7099a
chore(deps): bump taiki-e/install-action from 2.86.7 to 2.87.6 (#1250)
Bumps [taiki-e/install-action](https://github.com/taiki-e/install-action) from 2.86.7 to 2.87.6.
- [Release notes](https://github.com/taiki-e/install-action/releases)
- [Changelog](https://github.com/taiki-e/install-action/blob/main/CHANGELOG.md)
- [Commits](b6ff580856...7b8d4719ee)

---
updated-dependencies:
- dependency-name: taiki-e/install-action
  dependency-version: 2.87.6
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-08 20:24:09 -04:00
Dale Seo
6fa40536de
fix: resolve clippy warnings across workspace (#1195)
* 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.
2026-09-08 19:05:29 -04:00
Dale Seo
f9a68bfa5c
feat: add ServerHandler::negotiate_initialize (#1247) 2026-09-08 19:05:04 -04:00
Dale Seo
7d14f3a8a2
feat(macros): reject empty tool_router (#1233)
Closes #1174

Claude-Session: https://claude.ai/code/session_017tyTJfwGpE8fidbZSRi6uU
2026-09-08 19:04:40 -04:00
Dale Seo
04c2f3fac9
fix(auth): unify refresh checks and error handling (#1236)
* fix(auth): unify refresh checks and error handling

Claude-Session: https://claude.ai/code/session_011pHFfoTygeG84mCDXzCcmw

* test(auth): add live authorization-server checks

Claude-Session: https://claude.ai/code/session_011pHFfoTygeG84mCDXzCcmw
2026-09-08 19:04:15 -04:00
Dale Seo
add9cbeab5
ci: bump codeql-action to 4.37.9 and group updates (#1240) 2026-09-08 10:38:30 -04:00
Nick Steele
302319861a
feat(auth): add enterprise refresh-token and ID-JAG exchanges (#1234)
* 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
2026-09-04 15:04:08 -04:00
dependabot[bot]
3b5ca4dd3f
chore(deps): bump astral-sh/setup-uv from 7.6.0 to 10.0.1 (#1238)
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 7.6.0 to 10.0.1.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](37802adc94...20cfd1bf94)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-version: 10.0.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-02 07:01:50 +09:00
dependabot[bot]
42cf8d9fa3
chore(deps): update process-wrap requirement from 9.0 to 10.0 (#1229)
Updates the requirements on [process-wrap](https://github.com/watchexec/process-wrap) to permit the latest version.
- [Changelog](https://github.com/watchexec/process-wrap/blob/main/CHANGELOG.md)
- [Commits](https://github.com/watchexec/process-wrap/compare/v9.0.0...v10.0.0)

---
updated-dependencies:
- dependency-name: process-wrap
  dependency-version: 10.0.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-01 23:13:12 +09:00
94 changed files with 6149 additions and 860 deletions

View file

@ -21,6 +21,10 @@ updates:
# Mark PRs as CI related change.
- T-CI
open-pull-requests-limit: 3
groups:
codeql-action:
patterns:
- "github/codeql-action*"
commit-message:
prefix: "chore"
include: "scope"

View file

@ -31,12 +31,10 @@ jobs:
node-version: '22'
- name: Install commitlint
run: |
npm install --save-dev @commitlint/cli @commitlint/config-conventional
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
run: npm install --global @commitlint/cli@20.4.3 @commitlint/config-conventional@20.4.3
- name: Lint commit messages
run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose
run: commitlint --extends @commitlint/config-conventional --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose
fmt:
name: Code Formatting
@ -61,9 +59,17 @@ jobs:
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
- name: Run clippy
- name: Run clippy (all features)
run: cargo clippy --all-targets --all-features -- -D warnings
- name: Run clippy (all features except local)
run: |
FEATURES=$(cargo metadata --no-deps --format-version 1 \
| jq -r '[.packages[] | select(.name == "rmcp") | .features | keys[]
| select(startswith("__") | not)
| select(. != "local")] | join(",")')
cargo clippy --package rmcp --all-targets --no-default-features --features "$FEATURES" -- -D warnings
semver:
name: SemVer Check
runs-on: ubuntu-latest
@ -79,7 +85,7 @@ jobs:
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
- name: Install cargo-semver-checks
uses: taiki-e/install-action@b6ff580856c41316412a0b9b60540fbc6f8c82cc # v2.86.7
uses: taiki-e/install-action@3f74d7c16a4242f1c95561e98edc25d36adb4375 # v2.87.12
with:
tool: cargo-semver-checks
@ -133,7 +139,7 @@ jobs:
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
- name: Install cargo-public-api
uses: taiki-e/install-action@b6ff580856c41316412a0b9b60540fbc6f8c82cc # v2.86.7
uses: taiki-e/install-action@3f74d7c16a4242f1c95561e98edc25d36adb4375 # v2.87.12
with:
tool: cargo-public-api
@ -206,7 +212,7 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Spell Check Repo
uses: crate-ci/typos@1a51d4b5a03bb97576af186c813af67e9137ba7c # master
uses: crate-ci/typos@d43b6c087ac471e2ea7b8af622ff15f05c0c365b # master
msrv:
name: Check MSRV
@ -245,7 +251,7 @@ jobs:
node-version: '22'
- name: Install uv
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
- name: Install Rust
uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable
@ -274,7 +280,7 @@ jobs:
node-version: '22'
- name: Install uv
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
- name: Install Rust
uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable
@ -310,7 +316,7 @@ jobs:
node-version: '22'
- name: Install uv
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
- name: Install Rust
uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable
@ -345,7 +351,7 @@ jobs:
node-version: '22'
- name: Install uv
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
- name: Install Rust
uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable

View file

@ -27,13 +27,13 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Initialize CodeQL
uses: github/codeql-action/init@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
with:
languages: ${{ matrix.language }}
config-file: ./.github/codeql/codeql-config.yml
- name: Autobuild
uses: github/codeql-action/autobuild@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
uses: github/codeql-action/autobuild@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@ff2f1c621b7f889edc0d3c761ac2e6a3f8cdb0dd # v4.37.7
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0

48
.github/workflows/scorecard.yml vendored Normal file
View file

@ -0,0 +1,48 @@
# OpenSSF Scorecard supply-chain security analysis.
name: Scorecard supply-chain security
on:
branch_protection_rule:
schedule:
- cron: '5 23 * * 5'
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions: read-all
jobs:
analysis:
name: Scorecard analysis
runs-on: ubuntu-latest
permissions:
security-events: write
id-token: write
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run analysis
uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
with:
results_file: results.sarif
results_format: sarif
# Publishing only succeeds on the default branch. PR and manual runs
# still validate the analysis and produce SARIF without publishing.
publish_results: ${{ github.event_name != 'pull_request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}
- name: Upload SARIF artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: scorecard-results
path: results.sarif
retention-days: 5
- name: Upload to code scanning
uses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
with:
sarif_file: results.sarif

View file

@ -4,13 +4,13 @@ default-members = ["crates/rmcp", "crates/rmcp-macros"]
resolver = "2"
[workspace.dependencies]
rmcp = { version = "3.2.0", path = "./crates/rmcp" }
rmcp-macros = { version = "3.2.0", path = "./crates/rmcp-macros" }
rmcp = { version = "3.4.0", path = "./crates/rmcp" }
rmcp-macros = { version = "3.4.0", path = "./crates/rmcp-macros" }
[workspace.package]
edition = "2024"
rust-version = "1.88"
version = "3.2.0"
version = "3.4.0"
authors = ["4t145 <u4t145@163.com>"]
license = "Apache-2.0"
repository = "https://github.com/modelcontextprotocol/rust-sdk/"

View file

@ -99,10 +99,10 @@ Use [`ClientServiceExt::serve_with_lifecycle`](crates/rmcp/src/service/client.rs
select another lifecycle explicitly:
```rust, ignore
use rmcp::{ClientInfo, ClientLifecycleMode, ClientServiceExt, ProtocolVersion};
use rmcp::{ClientLifecycleMode, ClientServiceExt, ProtocolVersion, model::ClientConfig};
// Start directly with server/discover and include client metadata on every request.
let client = ClientInfo::default()
let client = ClientConfig::default()
.serve_with_lifecycle(
transport,
ClientLifecycleMode::Discover {
@ -113,7 +113,7 @@ let client = ClientInfo::default()
// Or probe the discover lifecycle and fall back when a legacy server reports
// that server/discover is not implemented or does not respond within 10 seconds.
let client = ClientInfo::default()
let client = ClientConfig::default()
.serve_with_lifecycle(
transport,
ClientLifecycleMode::Auto {
@ -369,8 +369,8 @@ use serde_json::json;
struct MyServer;
impl ServerHandler for MyServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_resources()
.build(),
@ -582,8 +582,8 @@ impl MyServer {
#[prompt_handler]
impl ServerHandler for MyServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(ServerCapabilities::builder().enable_prompts().build())
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_prompts().build())
}
}
```
@ -934,8 +934,8 @@ Enable the logging capability, handle level changes from the client, and send lo
use rmcp::{ServerHandler, model::*, service::RequestContext};
impl ServerHandler for MyServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_logging()
.build(),
@ -1007,8 +1007,8 @@ Enable the completions capability and implement the `complete()` handler. Use `r
use rmcp::{ErrorData as McpError, ServerHandler, model::*, service::RequestContext, RoleServer};
impl ServerHandler for MyServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_completions()
.enable_prompts()
@ -1253,8 +1253,8 @@ use rmcp::{
};
impl ServerHandler for MyServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_tools()
.enable_tool_list_changed()
@ -1584,7 +1584,7 @@ use rmcp::transport::StreamableHttpClientTransport;
// Defaults are stateless-friendly.
let transport = StreamableHttpClientTransport::from_uri("http://localhost:8000/mcp");
let client = ClientInfo::default().serve(transport).await?;
let client = ClientConfig::default().serve(transport).await?;
```
**Example:** [`examples/servers/src/counter_streamhttp.rs`](examples/servers/src/counter_streamhttp.rs) (server), [`examples/clients/src/streamable_http.rs`](examples/clients/src/streamable_http.rs) (client)
@ -1638,7 +1638,7 @@ server example). The client transport connects with a single URI:
use rmcp::transport::StreamableHttpClientTransport;
let transport = StreamableHttpClientTransport::from_uri("http://localhost:8000/mcp");
let client = ClientInfo::default().serve(transport).await?;
let client = ClientConfig::default().serve(transport).await?;
```
The client allows up to 16 ordinary http POSTs at once. Configure this with
@ -1742,10 +1742,10 @@ knows what the other supports. Declare yours with the `ServerCapabilities`
builder in `get_info()`:
```rust,ignore
use rmcp::model::{ServerCapabilities, ServerInfo};
use rmcp::model::{ServerCapabilities, ServerConfig};
fn get_info(&self) -> ServerInfo {
ServerInfo::new(
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_tools()
.enable_prompts()

View file

@ -19,6 +19,7 @@ rmcp = { path = "../crates/rmcp", features = [
"elicitation",
"auth",
"auth-client-credentials-jwt",
"auth-enterprise-managed",
"request-state",
"transport-streamable-http-server",
"transport-streamable-http-client-reqwest",
@ -31,6 +32,7 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
axum = { version = "0.8", features = ["macros"] }
anyhow = "1"
oauth2 = { version = "5.0", default-features = false }
reqwest = { version = "0.13", features = ["json"] }
urlencoding = "2"
url = "2"

View file

@ -1,3 +1,10 @@
#![expect(
deprecated,
reason = "The conformance suite still exercises deprecated sampling scenarios"
)]
use anyhow::Context;
use oauth2::{ClientSecret, RefreshToken};
use rmcp::{
ClientHandler, ClientLifecycleMode, ClientServiceExt, ErrorData, RoleClient, ServiceExt,
model::*,
@ -6,7 +13,8 @@ use rmcp::{
AuthClient, AuthorizationManager, StreamableHttpClientTransport,
auth::{
AuthorizationCallback, AuthorizationRequest, ClientCredentialsConfig,
InMemoryCredentialStore, JwtSigningAlgorithm, OAuthState,
InMemoryCredentialStore, JwtSigningAlgorithm, OAuthState, default_oauth_http_client,
enterprise::{EmaAuthorizationServer, EmaClientAuthentication, EmaExchangeRequest},
},
streamable_http_client::StreamableHttpClientTransportConfig,
},
@ -36,6 +44,17 @@ struct ConformanceContext {
private_key_pem: Option<String>,
#[serde(default)]
signing_algorithm: Option<String>,
// enterprise-managed-authorization-refresh-token
#[serde(default)]
idp_client_id: Option<String>,
#[serde(default)]
idp_client_secret: Option<String>,
#[serde(default)]
idp_refresh_token: Option<String>,
#[serde(default)]
idp_issuer: Option<String>,
#[serde(default)]
idp_token_endpoint: Option<String>,
}
fn load_context() -> ConformanceContext {
@ -55,8 +74,8 @@ impl ClientHandler for BasicClientHandler {}
struct ElicitationDefaultsClientHandler;
impl ClientHandler for ElicitationDefaultsClientHandler {
fn get_info(&self) -> ClientInfo {
let mut info = ClientInfo::default();
fn get_info(&self) -> ClientConfig {
let mut info = ClientConfig::default();
info.capabilities.elicitation = Some(
ElicitationCapability::new()
.with_form(FormElicitationCapability::new().with_schema_validation(true)),
@ -144,8 +163,8 @@ impl ClientHandler for ElicitationDefaultsClientHandler {
struct FullClientHandler;
impl ClientHandler for FullClientHandler {
fn get_info(&self) -> ClientInfo {
let mut info = ClientInfo::default();
fn get_info(&self) -> ClientConfig {
let mut info = ClientConfig::default();
info.capabilities.elicitation = Some(
ElicitationCapability::new()
.with_form(FormElicitationCapability::new().with_schema_validation(true)),
@ -760,6 +779,66 @@ async fn run_client_credentials_jwt(
Ok(())
}
/// Exchange the fixture's IdP refresh token, then exercise authenticated MCP access.
async fn run_ema_refresh_token_client(
server_url: &str,
ctx: &ConformanceContext,
) -> anyhow::Result<()> {
let manager = AuthorizationManager::new(server_url).await?;
let metadata = manager.resolve_metadata().await?.metadata;
let idp = EmaAuthorizationServer::new(
ctx.idp_issuer.as_deref().context("Missing idp_issuer")?,
ctx.idp_token_endpoint
.as_deref()
.context("Missing idp_token_endpoint")?,
ctx.idp_client_id
.as_deref()
.context("Missing idp_client_id")?,
)
.with_client_authentication(EmaClientAuthentication::ClientSecretBasic(
ClientSecret::new(
ctx.idp_client_secret
.clone()
.context("Missing idp_client_secret")?,
),
));
let resource_as = EmaAuthorizationServer::new(
metadata
.issuer
.context("Missing authorization server issuer")?,
metadata.token_endpoint,
ctx.client_id.as_deref().context("Missing client_id")?,
)
.with_client_authentication(EmaClientAuthentication::ClientSecretBasic(
ClientSecret::new(ctx.client_secret.clone().context("Missing client_secret")?),
));
let refresh_token = RefreshToken::new(
ctx.idp_refresh_token
.clone()
.context("Missing idp_refresh_token")?,
);
let http = default_oauth_http_client()?;
let token = EmaExchangeRequest::new(idp, resource_as, server_url, &refresh_token)
.with_scopes(manager.select_scopes(None, &[]))
.exchange(&http, &http)
.await?;
let transport = StreamableHttpClientTransport::from_config(
StreamableHttpClientTransportConfig::with_uri(server_url)
.auth_header(token.access_token.secret()),
);
let client = BasicClientHandler
.serve_with_lifecycle(transport, conformance_lifecycle())
.await?;
let tools = client.list_tools(Default::default()).await?;
for tool in tools.tools {
let args = build_tool_arguments(&tool);
client.call_tool(call_tool_params(tool.name, args)).await?;
}
client.cancel().await?;
Ok(())
}
/// Cross-app access flow (SEP-1046 extension).
async fn run_cross_app_access_client(
server_url: &str,
@ -1110,6 +1189,11 @@ async fn run_scenario(
"auth/client-credentials-basic" => run_client_credentials_basic(server_url, ctx).await?,
"auth/client-credentials-jwt" => run_client_credentials_jwt(server_url, ctx).await?,
// Auth - enterprise-managed authorization with a refresh-token subject
"auth/enterprise-managed-authorization-refresh-token" => {
run_ema_refresh_token_client(server_url, ctx).await?
}
// Auth - cross-app access
"auth/cross-app-access-complete-flow" => {
run_cross_app_access_client(server_url, ctx).await?

View file

@ -704,8 +704,8 @@ impl ServerHandler for ConformanceServer {
(name == "test_custom_header").then(custom_header_tool)
}
fn get_info(&self) -> ServerInfo {
ServerInfo::new(
fn get_info(&self) -> ServerConfig {
ServerConfig::new(
ServerCapabilities::builder()
.enable_prompts()
.enable_prompts_list_changed()
@ -1744,7 +1744,9 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("Starting conformance server on {}", bind_addr);
let server = ConformanceServer::new();
let config = StreamableHttpServerConfig::default();
let config = StreamableHttpServerConfig::default()
.with_allowed_origins([format!("http://{bind_addr}")])
.enforce_origin_validation();
let service = StreamableHttpService::new(
move || Ok(server.clone()),
LocalSessionManager::default().into(),

View file

@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [3.4.0](https://github.com/modelcontextprotocol/rust-sdk/compare/rmcp-macros-v3.3.0...rmcp-macros-v3.4.0) - 2026-09-15
### Added
- *(model)* add ServerConfig and ClientConfig ([#1266](https://github.com/modelcontextprotocol/rust-sdk/pull/1266))
### Fixed
- *(model)* deprecate ServerInfo and ClientInfo aliases ([#1156](https://github.com/modelcontextprotocol/rust-sdk/pull/1156))
## [3.3.0](https://github.com/modelcontextprotocol/rust-sdk/compare/rmcp-macros-v3.2.0...rmcp-macros-v3.3.0) - 2026-09-10
### Added
- *(macros)* reject empty tool_router ([#1233](https://github.com/modelcontextprotocol/rust-sdk/pull/1233))
## [3.2.0](https://github.com/modelcontextprotocol/rust-sdk/compare/rmcp-macros-v3.1.4...rmcp-macros-v3.2.0) - 2026-08-31
### Added

View file

@ -56,6 +56,7 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> TokenStream {
/// | `router` | `Ident` | The name of the router function to be generated. Defaults to `tool_router`. |
/// | `vis` | `Visibility` | The visibility of the generated router function. Defaults to empty. |
/// | `server_handler` | `flag` | When set, also emits `#[::rmcp::tool_handler]` on `impl ServerHandler for Self` so you can omit a separate `#[tool_handler]` block. |
/// | `allow_empty` | `flag` | When set, accepts an impl block with no `#[tool]` fn. Without it, an empty router is a compile error. |
///
/// ## Example
///
@ -122,6 +123,37 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> TokenStream {
/// }
/// }
/// ```
///
/// ### Empty routers
///
/// Collecting tools is this attribute's whole purpose, so an impl block with no `#[tool]` fn is a
/// compile error rather than a router that silently serves nothing. Pass `allow_empty` when that
/// is what you want:
///
/// ```rust,ignore
/// #[tool_router(allow_empty)]
/// impl MyToolHandler {}
/// ```
///
/// The usual way to hit this by accident is a `macro_rules!` helper *inside* the impl block. An
/// attribute macro receives the unexpanded item, so `#[tool]` fns produced by such a helper are
/// invisible to `#[tool_router]`. Let the `macro_rules!` emit the whole annotated impl instead:
///
/// ```rust,ignore
/// macro_rules! define_tools {
/// ($($name:ident => $description:literal),* $(,)?) => {
/// #[tool_router]
/// impl MyToolHandler {
/// $(
/// #[tool(description = $description)]
/// async fn $name(&self) -> String { stringify!($name).to_owned() }
/// )*
/// }
/// };
/// }
///
/// define_tools!(my_tool => "what my tool does");
/// ```
#[proc_macro_attribute]
pub fn tool_router(attr: TokenStream, input: TokenStream) -> TokenStream {
tool_router::tool_router(attr.into(), input.into())
@ -185,8 +217,8 @@ pub fn tool_router(attr: TokenStream, input: TokenStream) -> TokenStream {
/// ```rust,ignore
/// #[tool_handler]
/// impl ServerHandler for MyToolHandler {
/// fn get_info(&self) -> ServerInfo {
/// ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
/// fn get_info(&self) -> ServerConfig {
/// ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
/// }
/// }
/// ```

View file

@ -116,7 +116,7 @@ pub(crate) enum CallerCapability {
Prompts,
}
/// Build a `get_info()` method that returns `ServerInfo` with the appropriate capabilities.
/// Build a `get_info()` method that returns `ServerConfig` with the appropriate capabilities.
///
/// The caller declares its own capability via `caller`. Sibling handler attributes
/// (`prompt_handler`, `tool_handler`) are detected automatically
@ -157,8 +157,8 @@ pub(crate) fn build_get_info(
}
syn::parse2::<ImplItem>(quote! {
fn get_info(&self) -> rmcp::model::ServerInfo {
rmcp::model::ServerInfo::new(
fn get_info(&self) -> rmcp::model::ServerConfig {
rmcp::model::ServerConfig::new(
rmcp::model::ServerCapabilities::builder()
#(#capability_calls)*
.build()

View file

@ -17,6 +17,8 @@ pub struct ToolRouterAttribute {
/// When set, also emit `#[::rmcp::tool_handler]` on `impl ServerHandler for Self` so callers
/// can skip a separate `#[tool_handler]` block (expanded in a later macro pass).
pub server_handler: bool,
/// When set, accept an impl block with no `#[tool]` fn instead of reporting an error.
pub allow_empty: bool,
}
impl Default for ToolRouterAttribute {
@ -25,6 +27,7 @@ impl Default for ToolRouterAttribute {
router: format_ident!("tool_router"),
vis: None,
server_handler: false,
allow_empty: false,
}
}
}
@ -35,6 +38,7 @@ pub fn tool_router(attr: TokenStream, input: TokenStream) -> syn::Result<TokenSt
router,
vis,
server_handler,
allow_empty,
} = ToolRouterAttribute::from_list(&attr_args)?;
let mut item_impl = syn::parse2::<ItemImpl>(input)?;
// find all function marked with `#[rmcp::tool]`
@ -58,6 +62,19 @@ pub fn tool_router(attr: TokenStream, input: TokenStream) -> syn::Result<TokenSt
}
})
.collect();
if tool_attr_fns.is_empty() && !allow_empty {
return Err(syn::Error::new_spanned(
&item_impl.self_ty,
format!(
"`#[tool_router]` found no `#[tool]` fn in this impl block, so `Self::{router}()` \
would serve no tools\n\
note: a `macro_rules!` invocation inside the impl block is not expanded before \
this attribute runs, so any `#[tool]` fn it generates is invisible here; let the \
`macro_rules!` emit the whole `#[tool_router] impl` instead\n\
note: use `#[tool_router(allow_empty)]` if an empty router is intended"
),
));
}
let mut routers = Vec::with_capacity(tool_attr_fns.len());
for handler in tool_attr_fns {
let tool_attr_fn_ident = format_ident!("{handler}_tool_attr");
@ -111,6 +128,7 @@ mod test {
router,
vis,
server_handler,
allow_empty,
} = ToolRouterAttribute::from_list(&attr_args)?;
assert_eq!(router.to_string(), "test_router");
assert!(vis.is_some(), "vis = \"pub(crate)\" should parse");
@ -118,6 +136,10 @@ mod test {
!server_handler,
"server_handler should default to false when omitted"
);
assert!(
!allow_empty,
"allow_empty should default to false when omitted"
);
Ok(())
}
@ -137,4 +159,54 @@ mod test {
assert!(server_handler);
Ok(())
}
#[test]
fn tool_router_rejects_an_impl_without_directly_visible_tool_fns() {
let input = quote! {
impl Probe {
a_capability!(broadcast = "what a capability would own");
}
};
let message = tool_router(TokenStream::new(), input)
.expect_err("an impl with no `#[tool]` fn should not compile")
.to_string();
assert!(
message.contains("`Self::tool_router()` would serve no tools"),
"{message}"
);
assert!(message.contains("macro_rules!"), "{message}");
assert!(message.contains("allow_empty"), "{message}");
}
#[test]
fn tool_router_names_the_custom_router_fn_when_it_is_empty() {
let message = tool_router(quote! { router = custom_router }, quote! { impl Probe {} })
.expect_err("an impl with no `#[tool]` fn should not compile")
.to_string();
assert!(
message.contains("`Self::custom_router()` would serve no tools"),
"{message}"
);
}
#[test]
fn tool_router_accepts_an_impl_with_a_tool_fn() -> syn::Result<()> {
let input = quote! {
impl Probe {
#[tool(description = "probe")]
async fn probe(&self) -> String { "probed".to_owned() }
}
};
let generated = tool_router(TokenStream::new(), input)?.to_string();
assert!(generated.contains("with_route"), "{generated}");
Ok(())
}
#[test]
fn tool_router_allow_empty_generates_a_router_without_routes() -> syn::Result<()> {
let generated = tool_router(quote! { allow_empty }, quote! { impl Probe {} })?.to_string();
assert!(generated.contains("fn tool_router"), "{generated}");
assert!(!generated.contains("with_route"), "{generated}");
Ok(())
}
}

View file

@ -7,6 +7,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [3.4.0](https://github.com/modelcontextprotocol/rust-sdk/compare/rmcp-v3.3.0...rmcp-v3.4.0) - 2026-09-15
### Added
- *(model)* add ServerConfig and ClientConfig ([#1266](https://github.com/modelcontextprotocol/rust-sdk/pull/1266))
### Fixed
- *(rmcp)* use ServerConfig in cancellation test ([#1273](https://github.com/modelcontextprotocol/rust-sdk/pull/1273))
- *(rmcp)* route peer cancellation by lifecycle ([#1262](https://github.com/modelcontextprotocol/rust-sdk/pull/1262))
- run first pre-init request in service loop ([#1263](https://github.com/modelcontextprotocol/rust-sdk/pull/1263))
- *(auth)* let url origin decide prm discovery ([#1264](https://github.com/modelcontextprotocol/rust-sdk/pull/1264))
- *(model)* deprecate ServerInfo and ClientInfo aliases ([#1156](https://github.com/modelcontextprotocol/rust-sdk/pull/1156))
- *(auth)* ignore non-metadata JSON when probing for protected resource metadata ([#1204](https://github.com/modelcontextprotocol/rust-sdk/pull/1204))
- do not treat malformed JSON 200 as Accepted for requests ([#1208](https://github.com/modelcontextprotocol/rust-sdk/pull/1208))
- *(streamable-http-server)* map handler-generated HeaderMismatch to HTTP 400 ([#1259](https://github.com/modelcontextprotocol/rust-sdk/pull/1259))
- *(http)* enforce Origin validation semantics ([#1192](https://github.com/modelcontextprotocol/rust-sdk/pull/1192))
## [3.3.0](https://github.com/modelcontextprotocol/rust-sdk/compare/rmcp-v3.2.0...rmcp-v3.3.0) - 2026-09-10
### Added
- add ServerHandler::negotiate_initialize ([#1247](https://github.com/modelcontextprotocol/rust-sdk/pull/1247))
- *(macros)* reject empty tool_router ([#1233](https://github.com/modelcontextprotocol/rust-sdk/pull/1233))
- *(auth)* add enterprise refresh-token and ID-JAG exchanges ([#1234](https://github.com/modelcontextprotocol/rust-sdk/pull/1234))
### Fixed
- *(sse)* saturate exponential reconnect backoff to avoid overflow panic ([#1231](https://github.com/modelcontextprotocol/rust-sdk/pull/1231))
- resolve clippy warnings across workspace ([#1195](https://github.com/modelcontextprotocol/rust-sdk/pull/1195))
- *(auth)* unify refresh checks and error handling ([#1236](https://github.com/modelcontextprotocol/rust-sdk/pull/1236))
### Other
- *(deps)* update process-wrap requirement from 9.0 to 10.0 ([#1229](https://github.com/modelcontextprotocol/rust-sdk/pull/1229))
## [3.2.0](https://github.com/modelcontextprotocol/rust-sdk/compare/rmcp-v3.1.4...rmcp-v3.2.0) - 2026-08-31
### Added

View file

@ -18,6 +18,7 @@ exhaustive_enums = "warn"
features = [
"auth",
"auth-client-credentials-jwt",
"auth-enterprise-managed",
"base64",
"client",
"client-side-sse",
@ -87,7 +88,7 @@ url = { version = "2.4", optional = true }
tower-service = { version = "0.3", optional = true }
# for child process transport
process-wrap = { version = "9.0", features = ["tokio1"], optional = true }
process-wrap = { version = "10.0", features = ["tokio1"], optional = true }
# for cross-platform executable path resolution
which = { version = "8", optional = true }
@ -196,10 +197,11 @@ transport-streamable-http-server-session = [
tower = ["dep:tower-service"]
auth = ["dep:async-trait", "dep:oauth2", "__reqwest", "dep:url"]
auth-client-credentials-jwt = ["auth", "dep:jsonwebtoken", "uuid"]
auth-enterprise-managed = ["auth", "base64"]
schemars = ["dep:schemars"]
[dev-dependencies]
tokio = { version = "1", features = ["full"] }
tokio = { version = "1", features = ["full", "test-util"] }
schemars = { version = "1.1.0", features = ["chrono04"] }
axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] }
hyper = { version = "1", features = ["server", "http1"] }
@ -213,7 +215,7 @@ tracing-subscriber = { version = "0.3", features = [
"fmt",
] }
async-trait = "0.1"
rstest = "0.26.1"
rstest = "0.27.0"
[[test]]
name = "test_tool_macros"
required-features = ["server", "client"]
@ -346,6 +348,15 @@ name = "test_streamable_http_4xx_error_body"
required-features = ["transport-streamable-http-client", "transport-streamable-http-client-reqwest"]
path = "tests/test_streamable_http_4xx_error_body.rs"
[[test]]
name = "test_streamable_http_malformed_json_request"
required-features = [
"client",
"transport-streamable-http-client",
"transport-streamable-http-client-reqwest",
]
path = "tests/test_streamable_http_malformed_json_request.rs"
[[test]]
name = "test_custom_request"

View file

@ -24,6 +24,7 @@ For **getting started**, **usage guides**, and **full MCP feature documentation*
| `macros` | `#[tool]` / `#[prompt]` macros (re-exports [`rmcp-macros`](../rmcp-macros)) | ✅ |
| `schemars` | JSON Schema generation for tool definitions | |
| `auth` | OAuth 2.0 authentication support | |
| `auth-enterprise-managed` | EMA/XAA refresh-token and ID-JAG exchanges for registered public and confidential clients (includes `auth`) | |
| `elicitation` | Elicitation support | |
### Transport features
@ -45,6 +46,10 @@ For **getting started**, **usage guides**, and **full MCP feature documentation*
| `reqwest-native-tls` | Uses platform-native TLS (OpenSSL / Secure Transport / SChannel) |
| `reqwest-tls-no-provider` | Uses rustls without a default crypto provider (bring your own) |
For enterprise-managed authorization, enable `auth-enterprise-managed` and a TLS
backend such as `reqwest`. See the [EMA/XAA guide](../../docs/OAUTH_SUPPORT.md#enterprise-managed-authorization-emaxaa)
for client authentication and an MCP connection example.
## Transports
The transport layer is pluggable. Two built-in pairs cover the most common cases:

View file

@ -274,8 +274,8 @@ macro_rules! client_handler_methods {
std::future::ready(())
}
fn get_info(&self) -> ClientInfo {
ClientInfo::default()
fn get_info(&self) -> ClientConfig {
ClientConfig::default()
}
};
}
@ -292,12 +292,12 @@ pub trait ClientHandler: Sized + 'static {
client_handler_methods!();
}
/// Do nothing, with default client info.
/// Do nothing, with the default client config.
impl ClientHandler for () {}
/// Do nothing, with a specific client info.
impl ClientHandler for ClientInfo {
fn get_info(&self) -> ClientInfo {
/// Do nothing, with a specific client config.
impl ClientHandler for ClientConfig {
fn get_info(&self) -> ClientConfig {
self.clone()
}
}
@ -422,7 +422,7 @@ macro_rules! impl_client_handler_for_wrapper {
(**self).on_custom_notification(notification, context)
}
fn get_info(&self) -> ClientInfo {
fn get_info(&self) -> ClientConfig {
(**self).get_info()
}
}

View file

@ -321,16 +321,59 @@ macro_rules! server_handler_methods {
context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<InitializeResult, McpError>> + MaybeSendFuture + '_ {
context.peer.set_peer_info(request.clone());
std::future::ready(self.negotiate_initialize(&request))
}
/// Build the `initialize` response for `request`, negotiating the
/// protocol version against [`Self::supported_protocol_versions`].
///
/// This is the whole body of the default [`Self::initialize`] minus its
/// `set_peer_info` side effect, so a server that overrides `initialize`
/// to add its own can call this instead of restating the negotiation
/// rule:
///
/// ```
/// use rmcp::{
/// ErrorData as McpError, RoleServer, ServerHandler,
/// model::{InitializeRequestParams, InitializeResult, ServerConfig},
/// service::RequestContext,
/// };
///
/// struct MyServer;
///
/// impl ServerHandler for MyServer {
/// fn get_info(&self) -> ServerConfig {
/// ServerConfig::default()
/// }
///
/// async fn initialize(
/// &self,
/// request: InitializeRequestParams,
/// context: RequestContext<RoleServer>,
/// ) -> Result<InitializeResult, McpError> {
/// // ... record telemetry, register the peer, etc.
/// context.peer.set_peer_info(request.clone());
/// self.negotiate_initialize(&request)
/// }
/// }
/// ```
///
/// # Errors
///
/// Returns [`ErrorCode::UNSUPPORTED_PROTOCOL_VERSION`] when this server
/// supports no version that still has an `initialize` handshake.
///
/// [`ErrorCode::UNSUPPORTED_PROTOCOL_VERSION`]: crate::model::ErrorCode::UNSUPPORTED_PROTOCOL_VERSION
fn negotiate_initialize(
&self,
request: &InitializeRequestParams,
) -> Result<InitializeResult, McpError> {
let mut info = self.get_info();
let negotiated = negotiate_protocol_version(
info.protocol_version = negotiate_protocol_version(
&request.protocol_version,
std::mem::take(&mut info.protocol_version),
&self.supported_protocol_versions(),
);
std::future::ready(negotiated.map(|version| {
info.protocol_version = version;
info
}))
)?;
Ok(info)
}
/// Return the protocol versions supported by this server.
///
@ -339,6 +382,10 @@ macro_rules! server_handler_methods {
/// list is advertised by [`Self::discover`], bounds what `initialize`
/// negotiation may agree to, and is what per-request versions are
/// validated against.
///
/// To support everything up to some ceiling, use
/// [`ProtocolVersion::known_up_to`] rather than filtering
/// [`ProtocolVersion::KNOWN_VERSIONS`] by hand.
fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
Cow::Borrowed(ProtocolVersion::KNOWN_VERSIONS)
}
@ -553,8 +600,8 @@ macro_rules! server_handler_methods {
std::future::ready(())
}
fn get_info(&self) -> ServerInfo {
ServerInfo::default()
fn get_info(&self) -> ServerConfig {
ServerConfig::default()
}
/// SEP-2663 `tasks/get`: return the current [`DetailedTask`] state.
@ -621,6 +668,13 @@ macro_rules! impl_server_handler_for_wrapper {
(**self).initialize(request, context)
}
fn negotiate_initialize(
&self,
request: &InitializeRequestParams,
) -> Result<InitializeResult, McpError> {
(**self).negotiate_initialize(request)
}
fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
(**self).supported_protocol_versions()
}
@ -785,7 +839,7 @@ macro_rules! impl_server_handler_for_wrapper {
(**self).on_custom_notification(notification, context)
}
fn get_info(&self) -> ServerInfo {
fn get_info(&self) -> ServerConfig {
(**self).get_info()
}

View file

@ -177,7 +177,7 @@ impl ProtocolVersion {
/// First protocol version that requires SEP-2243 standard HTTP headers.
pub const STANDARD_HEADERS: Self = Self::V_2026_07_28;
/// All protocol versions known to this SDK.
/// All protocol versions known to this SDK, oldest first.
pub const KNOWN_VERSIONS: &[Self] = &[
Self::V_2024_11_05,
Self::V_2025_03_26,
@ -190,6 +190,43 @@ impl ProtocolVersion {
pub fn as_str(&self) -> &str {
&self.0
}
/// The known versions up to and including `max`, oldest first.
///
/// Servers that implement every revision up to some ceiling can return
/// this from `supported_protocol_versions` instead of filtering
/// [`Self::KNOWN_VERSIONS`] by hand. `max` itself need not be a known
/// version; the result is empty when it predates all of them.
///
/// The result borrows from [`Self::KNOWN_VERSIONS`], so call it directly
/// in the method body — it needs no `static` and no `LazyLock`:
///
/// ```rust,ignore
/// const MAX_SUPPORTED: ProtocolVersion = ProtocolVersion::V_2025_11_25;
///
/// fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
/// Cow::Borrowed(ProtocolVersion::known_up_to(&MAX_SUPPORTED))
/// }
/// ```
///
/// ```
/// # use rmcp::model::ProtocolVersion;
/// assert_eq!(
/// ProtocolVersion::known_up_to(&ProtocolVersion::V_2025_06_18),
/// &[
/// ProtocolVersion::V_2024_11_05,
/// ProtocolVersion::V_2025_03_26,
/// ProtocolVersion::V_2025_06_18,
/// ],
/// );
/// ```
pub fn known_up_to(max: &Self) -> &'static [Self] {
let count = Self::KNOWN_VERSIONS
.iter()
.take_while(|version| version.as_str() <= max.as_str())
.count();
&Self::KNOWN_VERSIONS[..count]
}
}
impl Serialize for ProtocolVersion {
@ -1082,7 +1119,58 @@ impl InitializeResult {
}
}
/// A server's own configuration: the protocol version, capabilities,
/// implementation identity, and instructions it advertises to clients.
///
/// This is what `ServerHandler::get_info` returns. It is an alias for
/// [`InitializeResult`] because the same value is sent as the `initialize`
/// response on the wire.
///
/// # Examples
///
/// ```
/// use rmcp::model::{ServerCapabilities, ServerConfig};
///
/// let config = ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
/// .with_instructions("Call `add` to sum two numbers.");
/// assert!(config.capabilities.tools.is_some());
/// ```
pub type ServerConfig = InitializeResult;
/// A client's own configuration: the protocol version, capabilities, and
/// implementation identity it advertises to servers.
///
/// This is what `ClientHandler::get_info` returns. It is an alias for
/// [`InitializeRequestParams`] because the same value is sent as the
/// `initialize` request on the wire.
///
/// # Examples
///
/// ```
/// use rmcp::model::{ClientCapabilities, ClientConfig, Implementation};
///
/// let config = ClientConfig::new(
/// ClientCapabilities::builder().enable_elicitation().build(),
/// Implementation::new("my-client", "1.0.0"),
/// );
/// assert!(config.capabilities.elicitation.is_some());
/// ```
pub type ClientConfig = InitializeRequestParams;
/// Deprecated alias for [`ServerConfig`].
///
/// The name collides with the protocol's `serverInfo` field, which is only the
/// [`Implementation`] identity, so `server_info.server_info` was easy to
/// misread (#1082).
#[deprecated(note = "use `ServerConfig` instead")]
pub type ServerInfo = InitializeResult;
/// Deprecated alias for [`ClientConfig`].
///
/// The name collides with the protocol's `clientInfo` field, which is only the
/// [`Implementation`] identity, so `client_info.client_info` was easy to
/// misread (#1082).
#[deprecated(note = "use `ClientConfig` instead")]
pub type ClientInfo = InitializeRequestParams;
/// Information negotiated about a server peer.
@ -1242,18 +1330,18 @@ impl DiscoverResult {
self
}
/// Create a discovery result from the server's initialization information.
/// Create a discovery result from the server's configuration.
pub fn from_server_info(
supported_versions: Vec<ProtocolVersion>,
server_info: ServerInfo,
server_config: ServerConfig,
) -> Self {
let ServerInfo {
let ServerConfig {
capabilities,
server_info,
instructions,
meta,
..
} = server_info;
} = server_config;
let mut result = Self {
result_type: ResultType::COMPLETE,
supported_versions,
@ -1295,9 +1383,9 @@ impl ServerPeerInfo {
}
#[allow(clippy::derivable_impls)]
impl Default for ServerInfo {
impl Default for InitializeResult {
fn default() -> Self {
ServerInfo {
InitializeResult {
protocol_version: ProtocolVersion::default(),
capabilities: ServerCapabilities::default(),
server_info: Implementation::from_build_env(),
@ -1308,9 +1396,9 @@ impl Default for ServerInfo {
}
#[allow(clippy::derivable_impls)]
impl Default for ClientInfo {
impl Default for InitializeRequestParams {
fn default() -> Self {
ClientInfo {
InitializeRequestParams {
meta: None,
protocol_version: ProtocolVersion::default(),
capabilities: ClientCapabilities::default(),
@ -4643,6 +4731,51 @@ mod tests {
use super::*;
#[test]
fn known_versions_are_ordered_oldest_first() {
// `known_up_to` walks the list as a sorted prefix.
assert!(
ProtocolVersion::KNOWN_VERSIONS
.windows(2)
.all(|pair| pair[0].as_str() < pair[1].as_str())
);
}
#[test]
fn known_up_to_includes_the_ceiling_itself() {
assert_eq!(
ProtocolVersion::known_up_to(&ProtocolVersion::V_2024_11_05),
&[ProtocolVersion::V_2024_11_05]
);
}
#[test]
fn known_up_to_the_newest_version_yields_every_known_version() {
assert_eq!(
ProtocolVersion::known_up_to(&ProtocolVersion::V_2026_07_28),
ProtocolVersion::KNOWN_VERSIONS
);
}
#[test]
fn known_up_to_an_unknown_ceiling_stops_at_the_versions_below_it() {
let unknown = ProtocolVersion(Cow::Borrowed("2025-07-01"));
assert_eq!(
ProtocolVersion::known_up_to(&unknown),
&[
ProtocolVersion::V_2024_11_05,
ProtocolVersion::V_2025_03_26,
ProtocolVersion::V_2025_06_18,
]
);
}
#[test]
fn known_up_to_a_ceiling_below_every_known_version_is_empty() {
let ancient = ProtocolVersion(Cow::Borrowed("1999-01-01"));
assert!(ProtocolVersion::known_up_to(&ancient).is_empty());
}
#[cfg(feature = "transport-streamable-http-client")]
#[test]
fn transport_closed_marker_accepts_only_the_process_local_token() {

View file

@ -136,6 +136,14 @@ pub trait ServiceRole: std::fmt::Debug + Send + Sync + 'static + Copy + Clone {
fn peer_cancelled_params(_notification: &Self::PeerNot) -> Option<&CancelledNotificationParam> {
None
}
#[doc(hidden)]
fn peer_cancels_subscriptions(_peer: &Peer<Self>) -> bool {
false
}
#[doc(hidden)]
fn is_subscription_request(_request: &Self::Req) -> bool {
false
}
/// Invalidate any response cache affected by an inbound peer notification.
///
/// The serve loop calls this for every notification *before* subscription
@ -522,6 +530,10 @@ impl ProgressNotificationToken for ServerNotification {
}
type Responder<T> = tokio::sync::oneshot::Sender<T>;
struct PendingResponse<T> {
responder: Responder<T>,
is_subscription: bool,
}
type ProgressTimeoutWatchers = Arc<tokio::sync::RwLock<HashMap<ProgressToken, mpsc::Sender<()>>>>;
type SubscriptionChannel<N> = (mpsc::Sender<N>, usize);
type SubscriptionChannelMap<N> = HashMap<RequestId, SubscriptionChannel<N>>;
@ -1298,7 +1310,14 @@ where
{
let (peer, peer_rx) = Peer::new(Arc::new(AtomicU32RequestIdProvider::default()), peer_info);
R::configure_direct_peer(&peer, &service.get_info());
serve_inner(service, transport.into_transport(), peer, peer_rx, ct)
serve_inner(
service,
transport.into_transport(),
peer,
peer_rx,
VecDeque::new(),
ct,
)
}
/// Spawn a task that may hold `!Send` state when the `local` feature is active.
@ -1323,12 +1342,19 @@ where
tokio::task::spawn_local(future)
}
/// Run the service loop over `transport`.
///
/// `initial_messages` are messages the caller already read from `transport`
/// (e.g. the first request of an `initialize`-less session). They are
/// dispatched by the loop, in order, before anything else is read from the
/// transport, so that their handlers run with the loop draining `peer_rx`.
#[instrument(skip_all)]
fn serve_inner<R, S, T>(
service: S,
transport: T,
peer: Peer<R>,
mut peer_rx: tokio::sync::mpsc::Receiver<PeerSinkMessage<R>>,
initial_messages: VecDeque<RxJsonRpcMessage<R>>,
ct: CancellationToken,
) -> RunningService<R, S>
where
@ -1348,7 +1374,7 @@ where
}
let mut local_responder_pool =
HashMap::<RequestId, Responder<Result<R::PeerResp, ServiceError>>>::new();
HashMap::<RequestId, PendingResponse<Result<R::PeerResp, ServiceError>>>::new();
let mut local_ct_pool = HashMap::<RequestId, CancellationToken>::new();
let shared_service = Arc::new(service);
// for return
@ -1361,7 +1387,7 @@ where
let current_span = tracing::Span::current();
let handle = spawn_service_task(async move {
let mut transport = transport.into_transport();
let mut batch_messages = VecDeque::<RxJsonRpcMessage<R>>::new();
let mut batch_messages = initial_messages;
let mut send_task_set = tokio::task::JoinSet::<SendTaskResult>::new();
let mut response_send_tasks = tokio::task::JoinSet::<()>::new();
#[derive(Debug)]
@ -1445,7 +1471,7 @@ where
Event::SendTaskResult(SendTaskResult::Request { id, result }) => {
if let Err(e) = result
&& let Some(responder) = local_responder_pool.remove(&id) {
let _ = responder.send(Err(ServiceError::TransportSend(e)));
let _ = responder.responder.send(Err(ServiceError::TransportSend(e)));
}
}
Event::SendTaskResult(SendTaskResult::Notification {
@ -1463,7 +1489,7 @@ where
&& let Some(request_id) = &param.request_id
&& let Some(responder) = local_responder_pool.remove(request_id) {
tracing::info!(id = %request_id, reason = param.reason, "cancelled");
let _response_result = responder.send(Err(ServiceError::Cancelled {
let _response_result = responder.responder.send(Err(ServiceError::Cancelled {
reason: param.reason.clone(),
}));
}
@ -1500,7 +1526,10 @@ where
id,
responder,
}) => {
local_responder_pool.insert(id.clone(), responder);
local_responder_pool.insert(id.clone(), PendingResponse {
responder,
is_subscription: R::is_subscription_request(&request),
});
let send = transport.send(JsonRpcMessage::request(request, id.clone()));
{
let id = id.clone();
@ -1601,31 +1630,38 @@ where
})) => {
tracing::info!(?notification, "received notification");
R::invalidate_response_cache(&peer, &notification).await;
let cancellation_request_id =
let subscription_id =
if let Some(cancelled) = R::peer_cancelled_params(&notification) {
let request_id = cancelled.request_id.clone();
if let Some(request_id) = request_id.as_ref() {
if R::IS_CLIENT {
if let Some(responder) =
local_responder_pool.remove(request_id)
// Modern servers cancel listen requests; legacy peers cancel
// requests they originated, even when both directions share an ID.
if R::peer_cancels_subscriptions(&peer) {
if let Some(request_id) = request_id.as_ref() {
if local_responder_pool.get(request_id)
.is_some_and(|pending| pending.is_subscription)
&& let Some(pending) = local_responder_pool.remove(request_id)
{
let _ = responder.send(Err(ServiceError::Cancelled {
let _ = pending.responder.send(Err(ServiceError::Cancelled {
reason: cancelled.reason.clone(),
}));
} else {
tracing::debug!(%request_id, "ignoring cancellation of unknown subscription");
continue;
}
} else if let Some(ct) = local_ct_pool.remove(request_id) {
}
request_id
} else {
if let Some(request_id) = request_id.as_ref()
&& let Some(ct) = local_ct_pool.remove(request_id)
{
tracing::info!(id = %request_id, reason = cancelled.reason, "cancelled");
ct.cancel();
}
None
}
request_id
} else {
None
notification.get_meta().subscription_id()
};
let subscription_id = notification
.get_meta()
.subscription_id()
.or(cancellation_request_id);
if let Some(subscription_id) = subscription_id
&& let Some((sender, capacity)) =
peer.subscription_sender(&subscription_id)
@ -1642,7 +1678,7 @@ where
&& let Some(responder) =
local_responder_pool.remove(&subscription_id)
{
let _ = responder
let _ = responder.responder
.send(Err(ServiceError::SubscriptionLagged { capacity }));
}
peer.unregister_subscription(&subscription_id);
@ -1694,7 +1730,7 @@ where
if let Some(responder) =
remove_pending_request(&mut local_responder_pool, &id)
{
let response_result = responder.send(Ok(result));
let response_result = responder.responder.send(Ok(result));
if let Err(_error) = response_result {
tracing::warn!(%id, "Error sending response");
}
@ -1715,7 +1751,7 @@ where
} else {
ServiceError::McpError(error)
};
let _response_result = responder.send(Err(service_error));
let _response_result = responder.responder.send(Err(service_error));
if let Err(_error) = _response_result {
tracing::warn!(%id, "Error sending response");
}
@ -1749,6 +1785,17 @@ where
// Then drain any handler responses still in the channel
// (handlers that finished after the loop broke).
while let Some(m) = sink_proxy_rx.recv().await {
if let Some(id) = match &m {
JsonRpcMessage::Response(response) => Some(&response.id),
JsonRpcMessage::Error(error) => error.id.as_ref(),
_ => None,
} {
let Some(ct) = local_ct_pool.remove(id) else {
tracing::debug!(%id, "dropping response for cancelled request");
continue;
};
ct.cancel();
}
if let Err(error) = transport.send(m).await {
tracing::error!(%error, "failed to send pending response during drain");
break;

Some files were not shown because too many files have changed in this diff Show more