* fix(rmcp-macros): use re-exported serde_json path in task_handler
Replace bare `::serde_json::` with `::rmcp::serde_json::` in
task_handler.rs to prevent compilation errors in crates that don't
directly depend on serde_json.
Fixes#487
* Update crates/rmcp-macros/src/task_handler.rs
---------
Co-authored-by: Dale Seo <5466341+DaleSeo@users.noreply.github.com>
The `#[task_handler]` macro generates code using deprecated type aliases
(`PaginatedRequestParam`, `CallToolRequestParam`, `GetTaskInfoParam`,
`GetTaskResultParam`, `CancelTaskParam`) that were renamed to `*Params`
in rmcp 0.13.0. This causes 5 deprecation warnings for every crate
using the macro.
Update all references to use the canonical `*Params` names:
- `PaginatedRequestParam` → `PaginatedRequestParams`
- `CallToolRequestParam` → `CallToolRequestParams`
- `GetTaskInfoParam` → `GetTaskInfoParams`
- `GetTaskResultParam` → `GetTaskResultParams`
- `CancelTaskParam` → `CancelTaskParams`
Also fix the corresponding doc examples in `lib.rs`.
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
* fix(auth): pass WWW-Authenticate scopes to DCR registration request
When an MCP server returns a 401 with `WWW-Authenticate: Bearer scope="..."`,
the scopes are parsed but never included in the Dynamic Client Registration
(DCR) request. Per RFC 7591, the DCR request should include a `scope` field
so the authorization server knows what scopes the client intends to use.
Servers that enforce scope-matching between registration and authorization
will reject the flow without this.
Changes:
- Add optional `scope` field to `ClientRegistrationRequest` with
`skip_serializing_if` for backward compatibility
- Update `register_client()` to accept scopes parameter and include
them in the DCR request body and returned `OAuthClientConfig`
- Thread scopes from `AuthorizationSession::new()` into both
`register_client()` call sites
- Re-export `oauth2::TokenResponse` trait so consumers can extract
scopes from token responses
- Add serialization tests for the new `scope` field
* refactor(auth): change register_client to accept &[&str] instead of &[String]
Avoids unnecessary Vec<String> allocation in callers that already have &[&str].
* fix(auth): make ClientRegistrationRequest crate-private
* refactor(auth): stop re-exporting oauth2 TokenResponse trait
* style(auth): merge TokenResponse into grouped oauth2 import
Fix nightly rustfmt check by consolidating the separate
`use oauth2::TokenResponse` into the existing `use oauth2::{...}` block.
* fix: builder with_* methods take T instead of Option<T>
* fix: emit conditional builder calls for optional fields in macros
* fix: convert with_task, with_stop_reason, with_logger, with_content to proper builders
* fix: update test callers for new builder signatures
* fix: simplify make_task helper and remove unused import
* fix: update sampling_stdio example for new with_stop_reason signature
* fix: make annotations and execution Option<Expr> consistent with other fields
* fix: remove unused none_expr import
* feat(auth): support returning extra fields that may be returned from token generation
exchange_code_for_token and refresh_token now return a StandardTokenResponse which includes
any additionalfields which might have been sent by the vendor
BREAKING CHANGE: Return type of exchange_code_for_token and refresh_token has changed
and may require code changes.
* fix: doc links
* docs: add prose documentation for core features to meet conformance
* docs: remove static coverage badge and svg
* docs: rewrite Chinese README to match current English README
* feat(streamable-http): add json_response option for stateless server mode
Adds `json_response: bool` field to `StreamableHttpServerConfig`.
When true and `stateful_mode` is false, the server returns
`Content-Type: application/json` directly instead of `text/event-stream`,
eliminating SSE framing overhead for simple request-response patterns.
This completes server-side JSON response support (client-side was added
in #540) and contributes to the stateless server goals of SEP-1442 (#526).
Backwards-compatible: `json_response: false` (default) preserves all
existing SSE behaviour unchanged, and `stateful_mode: true` is unaffected.
Benchmark evidence (50 VUs, 5min, 2 CPUs):
- RPS: 770 → 1139 (+48%)
- get_user_cart latency: 41ms → 0.76ms (-98%)
- checkout latency: 41ms → 0.55ms (-99%)
- Zero regressions, zero errors
* fix(tower): add cancellation awareness and logging to JSON response path
* fix(test): add missing Default to StreamableHttpServerConfig in concurrent streams test
Made-with: Cursor
* fix(streamable-http): return 409 Conflict when standalone SSE stream already active
LocalSessionWorker::resume() unconditionally replaced self.common.tx on
every GET request, orphaning the receiver the first SSE stream was
reading from. All subsequent server-to-client notifications were sent to
the new sender while the original client was still listening on the old,
now-dead receiver. notify_tool_list_changed().await returned Ok(())
silently.
This is triggered by VS Code's MCP extension which reconnects SSE every
~5 minutes with the same session ID.
Fix: Check tx.is_closed() before replacing the common channel sender.
If an active stream exists, return SessionError::Conflict which is
propagated as HTTP 409 Conflict. This matches the TypeScript SDK
behavior (streamableHttp.ts:423).
Signed-off-by: Mohammod Al Amin Ashik <maa.ashik00@gmail.com>
* fix(streamable-http): handle resume with completed request-wise channel
When a client sends GET with Last-Event-ID from a completed POST SSE
response, the request-wise channel no longer exists in tx_router.
Previously this returned ChannelClosed -> 500, causing clients like
Cursor to enter an infinite re-initialization loop.
Now falls back to the common channel when the request-wise channel is
completed, per MCP spec: "Resumption applies regardless of how the
original stream was initiated (POST or GET)."
* fix: allow SSE channel replacement instead of 409 Conflict
Per MCP spec §Streamable HTTP, "The client MAY remain connected to
multiple SSE streams simultaneously." Returning 409 Conflict when a
second GET arrives causes Cursor to enter an infinite re-initialization
loop (~3s cycle).
Instead of rejecting, replace the old common channel sender. Dropping
the old sender closes the old receiver, cleanly terminating the
previous SSE stream so the client can reconnect on the new stream.
This fixes both code paths:
- GET with Last-Event-ID from a completed POST SSE response
- GET without Last-Event-ID (standalone stream reconnection)
* fix: skip cache replay when replacing active SSE stream
When a client opens a new GET SSE stream while a previous one is
still active, the old sender is dropped (terminating the old stream)
and a new channel is created. Previously, sync() replayed all cached
events to the new stream, but the client already received those events
on the old stream. This caused an infinite notification loop:
1. Client receives notifications (e.g. ResourceListChanged)
2. Old SSE stream dies (sender replaced)
3. Client reconnects after sse_retry (3s)
4. sync() replays cached notifications the client already handled
5. Client processes them again → goto 2
Fix: check tx.is_closed() BEFORE replacing the sender. If the old
stream was still alive, skip replay entirely — the client already has
those events. Only replay when the old stream was genuinely dead
(network failure, timeout) so the client catches up on missed events.
* fix: use shadow channels to prevent SSE reconnect loops
When POST SSE responses include a `retry` field, the browser's
EventSource automatically reconnects via GET after the stream ends.
This creates multiple competing EventSource connections that each
replace the common channel sender, killing the other stream's receiver.
Both reconnect every sse_retry seconds, creating an infinite loop.
Instead of always replacing the common channel, check if the primary
is still active. If so, create a "shadow" stream — an idle SSE
connection kept alive by keep-alive pings that doesn't receive
notifications or interfere with the primary channel.
Also removes cache replay (sync) on common channel resume, as
replaying server-initiated list_changed notifications causes clients
to re-process old signals.
Signed-off-by: Myko Ash <myko@mcpmux.com>
Signed-off-by: Mohammod Al Amin Ashik <maa.ashik00@gmail.com>
* test: comprehensive shadow channel tests (15 cases)
Rewrite test suite for SSE channel replacement fix:
- Shadow creation: standalone GET returns 200, multiple GETs coexist
- Dead primary: replacement, notification delivery, repeated cycles
- Notification routing: primary receives, shadow does not
- Resume paths: completed request-wise, common alive/dead
- Real scenarios: Cursor leapfrog, VS Code reconnect
- Edge cases: invalid session, missing header, shadow cleanup
Fix Accept header bug (was missing text/event-stream for
notifications/initialized POST, causing 406 rejection).
* fix: use correct HTTP status codes for session errors per MCP spec
MCP spec (2025-11-25) section "Session Management" requires:
- Missing session ID header → 400 Bad Request (not 401)
- Unknown/terminated session → 404 Not Found (not 401)
Using 401 Unauthorized caused MCP clients (e.g. VS Code) to
trigger full OAuth re-authentication on server restart, instead
of simply re-initializing the session.
Signed-off-by: Mohammod Al Amin Ashik <maa.ashik00@gmail.com>
* fix: address review feedback — remove dead Conflict variant, restore sync on resume, rename test
- Remove unused SessionError::Conflict and dead string-matching in tower.rs
(leftover from abandoned 409 approach)
- Restore sync() replay when replacing a dead primary common channel so
server-initiated requests and cached notifications are not lost on reconnect
- Rename test from test_sse_channel_replacement_bug to test_sse_concurrent_streams
per reviewer suggestion (describe what tests verify, not what triggered them)
- Add test for cache replay on dead primary replacement
- Use generic "MCP clients" in comments instead of specific client names
Signed-off-by: Mohammod Al Amin Ashik <maa.ashik00@gmail.com>
* fix: use minimal buffer for shadow streams and cap at 32
- Shadow streams only receive SSE keep-alive pings, so use capacity 1
instead of full channel_capacity
- Cap shadow_txs at 32 to prevent unbounded growth from misbehaving
clients, dropping the oldest shadow when the limit is reached
- Add test verifying primary works after exceeding shadow limit
Signed-off-by: Mohammod Al Amin Ashik <maa.ashik00@gmail.com>
* fix: remove redundant single-component `use reqwest` import
Fixes clippy::single_component_path_imports lint error in
test_sse_concurrent_streams.rs.
---------
Signed-off-by: Mohammod Al Amin Ashik <maa.ashik00@gmail.com>
Signed-off-by: Myko Ash <myko@mcpmux.com>
Co-authored-by: Mohammod Al Amin Ashik <maa.ashik00@gmail.com>
ToolRouter::list_all() and PromptRouter::list_all() iterate over a
HashMap, which returns items in non-deterministic order. Since list_all()
backs the tools/list and prompts/list MCP protocol responses, this causes
MCP clients to receive differently-ordered results across calls and
process restarts, leading to intermittent tool discovery failures.
Sort the output alphabetically by name to guarantee stable ordering.
* feat: add support for custom HTTP headers in StreamableHttpClient
* feat: implement reserved header checks for custom HTTP headers in StreamableHttpClient
* chore(deps): update rand requirement from 0.9 to 0.10
Updates the requirements on [rand](https://github.com/rust-random/rand) to permit the latest version.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/compare/rand_core-0.9.1...0.10.0)
---
updated-dependencies:
- dependency-name: rand
dependency-version: 0.10.0
dependency-type: direct:production
...
Signed-off-by: dependabot[bot] <support@github.com>
* fix: update rand import from Rng to RngExt for rand 0.10 compatibility
In rand 0.10, the Rng trait was renamed to RngExt. This updates the
imports in the example servers to use the new trait name.
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Alex Hancock <alexhancock@block.xyz>
* feat(auth): add token_endpoint_auth_method to OAuthClientConfig
Some OAuth providers (e.g. HubSpot) require client credentials to be
sent as POST body parameters (client_secret_post) instead of via HTTP
Basic Auth header. The oauth2 crate defaults to BasicAuth, and rmcp
had no way to override this, causing TokenExchangeFailed errors.
Add an optional `token_endpoint_auth_method` field to OAuthClientConfig
that accepts "client_secret_post" (RequestBody) and "client_secret_basic"
(BasicAuth). Unknown values are silently ignored, preserving the default.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(auth): derive token_endpoint_auth_method from server metadata
Move auth method selection from per-client config to server's
AuthorizationMetadata, which is the correct OAuth 2.0 approach.
Servers like HubSpot advertise token_endpoint_auth_methods_supported
in their metadata; reading it from there avoids manual configuration
and prevents TokenExchangeFailed errors with non-BasicAuth providers.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refactor(auth): read token_endpoint_auth_methods_supported from additional_fields
Move token_endpoint_auth_methods_supported out of AuthorizationMetadata
as an explicit field and read it from the serde(flatten) additional_fields
HashMap instead. This avoids serializing `null` when the field is absent,
which broke Zod validation in downstream consumers like MCP Inspector.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* feat(auth): prefer basic auth when both methods supported and improve test assertions
When token_endpoint_auth_methods_supported contains both client_secret_post
and client_secret_basic, default to basic auth per RFC 6749 §2.3.1.
Update configure_client tests to assert actual AuthType instead of is_some().
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* style(auth): apply cargo fmt formatting
* style(auth): apply nightly cargo fmt import grouping
* revert: undo .gitignore change
---------
Co-authored-by: Anar Azadaliyev <anar.azadaliye@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* refactor: remove unused axum dependency from server-side-http feature
The `server-side-http` feature included `dep:axum` but axum was never
actually used in the rmcp library source code (0 references found).
The `StreamableHttpService` is a tower service that works with any
HTTP server framework. Users can choose to use:
- axum (via `Router::nest_service()` or `fallback_service()`)
- hyper directly (via `hyper_util::service::TowerToHyperService`)
- any other tower-compatible HTTP server
This change removes the unnecessary transitive dependency, giving users
more flexibility in their choice of HTTP server framework.
Examples that use axum already have their own explicit axum dependency
in their Cargo.toml, so they continue to work unchanged.
* refactor: move axum to dev-dependencies with minimal features
- Remove axum from library dependencies (not used in library source)
- Add axum to dev-dependencies for tests with minimal features:
default-features = false, features = ["http1", "tokio"]
- Examples have their own axum dependency and are unaffected
This addresses review feedback from @ofek to use minimal features,
while ensuring axum is only bundled for running rmcp's own tests,
not for downstream users.
Add reqwest-native-tls feature flag to allow users to choose between
rustls (default) and native-tls for HTTP transports.
native-tls uses platform-native TLS implementations:
- OpenSSL on Linux
- Secure Transport on macOS
- SChannel on Windows
This is particularly useful for Linux distribution packagers who need
to link against system TLS libraries (e.g., OpenSSL) rather than
bundling a separate TLS implementation. Linking against system libs
ensures security updates are applied system-wide and satisfies
distribution packaging policies.
Updated documentation to explain the available TLS backend options.
Add support for MCP extension capabilities in both ClientCapabilities
and ServerCapabilities structs, as specified in SEP-1724.
Changes:
- Add ExtensionCapabilities type alias (BTreeMap<String, JsonObject>)
- Add 'extensions' field to ClientCapabilities struct
- Add 'extensions' field to ServerCapabilities struct
- Update builder macros and impl blocks for both structs
- Add comprehensive tests for extension capabilities
- Update JSON schema test fixtures
This enables clients to advertise extension support during initialize,
such as:
{
"capabilities": {
"extensions": {
"io.modelcontextprotocol/ui": {
"mimeTypes": ["text/html;profile=mcp-app"]
}
}
}
}
Closes#530
Move CustomRequest and CustomResult to end of their respective untagged
enums to ensure specific task variants match before catch-all custom types.
Add deny_unknown_fields to GetTaskInfoResult to prevent matching arbitrary
JSON objects.
Fixes issue where tasks/get, tasks/list, tasks/result, and tasks/cancel
incorrectly deserialized as CustomRequest instead of their typed variants.
Use `#![doc = include_str!("../README.md")]` to display README as crate
documentation on docs.rs for both `rmcp` and `rmcp-macros`.
Changes to support this:
- Fix code examples to compile as doc tests (`rust,no_run`)
- Fix broken rustdoc links with explicit `crate::` paths
- Add "Structured Output" section and examples link to rmcp README
- Simplify rmcp-macros README to a summary table with doc links
- Fix grammar throughout
- Add CSS to hide GitHub badges when rendered as rustdoc
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* feat: implement SEP-1319 Decouple Request Payload from RPC Methods
* test: update tests
* fix: update handler trait methods to use new types
* fix: update examples
* fix: correct deprecation version
* fix: update wrapper macros to use new *Params type names
* feat!: implement ServerHandler for Box<H> and Arc<H> where H is a ServerHandler
* feat!: implement ClientHandler for Box<H> and Arc<H> where H is a ClientHandler
* test: test Box and Arc have blanket implementations for handler traits
* refactor: deduplicate blanket implementations with macros
This PR primarily fixes#572 by enabling graceful shutdown without consuming self. While implementing this, I noticed delete_session() is spawned as a background task, which means close() may return before HTTP session cleanup completes. Since this is part of the same shutdown lifecycle and can cause resource leaks/races, I'm including a small, localized fix to ensure cleanup is completed before close() returns. If maintainers prefer, I can split the cleanup timing change into a follow-up PR.
Changes:
- Add close(&mut self) for graceful shutdown without consuming
- Add close_with_timeout() for bounded shutdown operations
- Add is_closed() to check connection state
- Move HTTP delete_session from background spawn to inline cleanup
- Add 5-second timeout on session cleanup to prevent indefinite hangs
- Add Drop impl with debug log if dropped without explicit close
Fixes#572
* fix: add OpenID Connect discovery support per spec-2025-11-25 4.3
Previously only tried OAuth 2.0 endpoints. Now tries OAuth first, then
OpenID Connect Discovery 1.0 in the spec-mandated priority order.
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
* fix: format auth.rs test assertions
Reformat assert_eq! statements to satisfy rustfmt checks in CI.
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
---------
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
#580 and #556 introduced support for custom notifications,
so this PR takes the next logical step and adds support for custom requests:
- Introduces `CustomRequest` and `CustomResult` model types, wires them into the client/server
request and result unions, and allows `ClientRequest::method()` to return the dynamic method
name.
- Implements serde and meta handling for `CustomRequest` so `_meta` is carried through
extensions; adds default `on_custom_request` handlers that return `METHOD_NOT_FOUND` unless
overridden.
- Updates JSON schema fixtures to include the new request/result shapes and `EmptyObject`
strictness.
- Adds tests for custom request roundtrips and end-to-end client↔server handling.
- Focused integration test in `crates/rmcp/tests/test_custom_request.rs`.
For additional testing, I used this locally to update Codex to use a custom
request instead of a custom notification so that it gets an "ack" from the MCP
server to ensure it has processed the update before sending more messages:
https://github.com/openai/codex/pull/8142.
https://github.com/modelcontextprotocol/rust-sdk/pull/556 introduced support for
custom client notifications, so this PR makes the complementary change, adding
support for custom server notifications.
MCP clients, particularly ones that offer "experimental" capabilities,
may wish to handle custom server notifications that are not part of the
standard MCP specification. This change introduces a new
`CustomServerNotification` type that allows a client to process
such custom notifications.
- introduces `CustomServerNotification` to carry arbitrary methods/params while
still preserving meta/extensions; wires it into the `ServerNotification` union
and `serde` so `params` can be decoded with `params_as`
- allows client handlers to receive custom notifications via a new
`on_custom_notification` hook
- adds integration coverage that sends a custom server notification end-to-end
and asserts the client sees the method and payload
Test:
```shell
cargo test -p rmcp --features client test_custom_server_notification_reaches_client
```
* feat(auth): add cimd support for SEP-991
add cimd support for url-based client ids
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
* test(auth): add unit tests for is_https_url helper
Add test coverage for is_https_url helper to validate HTTPS scheme, non-root paths,
and reject http, javascript, data schemes, and invalid inputs per SEP-991 requirements.
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
* feat(example): add CIMD OAuth server for SEP-991 testing
Implements a new server example (servers_cimd_auth_streamhttp) that
demonstrates CIMD (Client ID Metadata Document) support for URL-based
client IDs. The server validates client_id URLs, fetches and validates
client metadata documents, and provides OAuth 2.0 authorization endpoints
with MCP integration for end-to-end testing.
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
* fix(oauth): add CORS headers to token endpoint
Add CORS headers to token endpoint to allow cross-origin requests from browsers
during OAuth authorization code exchange flow.
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
* refactor: improve is_https_url function and consolidate tests
- Improve is_https_url function formatting and readability
- Merge all test cases into single test_is_https_url_scenarios function
- Add missing test case for "https://" URL
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
* refactor: use map_err instead of match for error handling in auth.rs
Replace the verbose match statement with
map_err for more idiomatic
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
* feat: add client-metadata.json
Add client metadata file for SEP-991 CIMD
authentication support
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
---------
Signed-off-by: tanish111 <tanishdesai37@gmail.com>
SSE transport has been removed from the MCP specification in favor of
streamable HTTP. This removes all SSE-specific transport code:
- Remove `transport-sse-client` and `transport-sse-server` features
- Remove `SseClientTransport` and `SseServer` types
- Remove SSE-specific examples (`counter_sse`, `counter_sse_directly`)
- Migrate auth examples from SSE to streamable HTTP
- Update tests to remove SSE transport usage
- Update documentation
BREAKING CHANGE: The following have been removed:
- `transport-sse-client` feature
- `transport-sse-client-reqwest` feature
- `transport-sse-server` feature
- `SseClientTransport` type
- `SseServer` type
- `sse_client` and `sse_server` modules
Users should migrate to streamable HTTP transport which provides
equivalent functionality. See `StreamableHttpClientTransport` and
`StreamableHttpService` for the replacement APIs.
Ref: https://github.com/modelcontextprotocol/rust-sdk/pull/561#issuecomment-3576551699
MCP servers, particularly ones that offer "experimental" capabilities,
may wish to handle custom client notifications that are not part of the
standard MCP specification. This change introduces a new
`CustomClientNotification` type that allows a server to process
such custom notifications.
- introduces `CustomClientNotification` to carry arbitrary methods/params while
still preserving meta/extensions; wires it into the `ClientNotification` union
and `serde` so `params` can be decoded with `params_as`
- allows server handlers to receive custom notifications via a new
`on_custom_notification` hook
- adds integration coverage that sends a custom client notification end-to-end
and asserts the server sees the method and payload
Test:
```shell
cargo test -p rmcp --features client test_custom_client_notification_reaches_server
```
What this enables:
- Clients can accept either Server-Sent Events (SSE) or JSON responses
- Flexible content negotiation based on server preferences
- Improved interoperability with different MCP server implementations
auth.rs was using an in-memory expires-at which is only set on initial token exchange.
Instead, this PR switches it to use the expires-at set in the credentials that are passed in.
* feat: add type-safe elicitation schema support (#465)
Implement type-safe schema definitions for MCP elicitation requests,
replacing generic `JsonObject` with strongly-typed primitive schemas
per the [MCP 2025-06-18 specification](https://spec.modelcontextprotocol.io/specification/2025-06-18/server/elicitation/).
Features:
- Type-safe schema hierarchy (`StringSchema`, `NumberSchema`, `IntegerSchema`, `BooleanSchema`)
- Builder pattern with fluent API and 20+ convenience methods
- Build-time validation ensuring required fields exist in properties
- Private fields enforcing invariants through validated constructors
- Comprehensive validation support (range, length, format, enums)
- Typed property methods for cleaner schema construction
Benefits:
- Compile-time type safety prevents invalid schema construction
- 60-70% reduction in boilerplate through convenience methods
- Enforces MCP specification requirement for primitive-only properties
- Better IDE autocomplete and type inference
- Runtime validation catches schema errors early
Breaking changes:
- `CreateElicitationRequestParam.requested_schema` changed from `JsonObject` to `ElicitationSchema`
- `ElicitationSchemaBuilder::build()` now returns `Result` instead of direct value
Fixes#465
* fix: fix RMCP compliance
* feat: add conversion methods to ElicitationSchema
Add from_json_schema() and from_type() methods to ElicitationSchema
for easier type-to-schema conversion. This addresses feedback about
improving ergonomics when working with generated schemas.
Also make all struct fields public for better flexibility.
* chore: change `StringFormat` to enum
* fix(oauth): attach bearer token to all streaming http requests
* fix(typo): fix an unrelated typo
There was an errant typo in the CHANGELOG that is breaking CI
Many MCP Servers use client_name for a variety of things including:
* Whitelisting
* Logos
* Copy shown directly on the page
* etc
As a result, it's important for MCP Clients to be able to override the client name.
This change makes the `tool` macro's output safe for the `missing_docs` lint, by
emitting a doc comment for the generated `[tool]_tool_attr` function. This doc
comment is emitted regardless of whether the tool function is public, for simplicity.
We are building an MCP server using `rmcp` and discovered that the current crate
was not compatible with the `#![deny(missing_docs)]` lint which we use everywhere.
Tested by modifying the `test_tool_macros.rs` test to use `#![deny(missing_docs)]`
and adding doc comments to all pub fns and structs in that file.
None.
Fixes#438.
Co-authored-by: RobJellinghaus <rjellinghaus@live.com>
Commit 452fe2c broke `Reference::for_prompt` where it missed
the field `title` for `struct PromptReference`, which broke
the build.
This commit fixes that.
* fix: handle logging and ping in handshake
We handle the initialization process more robustly.
- Allow logging and ping
- For other messages, we simply ignore it instead of rejecting right away
* fix: inject context to notification handler
* feat: implement MCP completion specification 2025-06-18
Complete implementation of MCP completion specification with performance optimizations:
Core Features:
- Add CompletionContext for context-aware completion with previously resolved arguments
- Implement CompletionProvider trait with async support and dyn compatibility
- Create DefaultCompletionProvider with optimized fuzzy matching algorithm
- Add comprehensive validation and helper methods to CompletionInfo
- Update ServerHandler to handle completion/complete requests
- Add client convenience methods for prompt and resource completion
Performance Optimizations:
- Zero-allocation fuzzy matching using index-based scoring
- Top-k selection with select_nth_unstable instead of full sorting
- Pre-allocated vectors to avoid reallocations during matching
- Char-based case-insensitive matching to minimize string operations
- 5-8x performance improvement for large candidate sets
API Design:
- Context-aware completion supporting multi-argument scenarios
- Type-safe validation with MAX_VALUES limit (100 per MCP spec)
- Helper methods: with_all_values, with_pagination, validate
- Reference convenience methods: for_prompt, for_resource
- Client methods: complete_prompt_argument, complete_resource_argument
Testing:
- 17 comprehensive tests covering all functionality
- Schema compliance tests for MCP 2025-06-18 specification
- Performance tests with <100ms target for 1000 candidates
- Edge case and validation tests
Schema Updates:
- Add CompletionContext to JSON schema
- Update CompleteRequestParam with optional context field
- Maintain backward compatibility with existing API
* test: add comprehensive fuzzy matching tests for completion
Add three new test cases to enhance coverage of fuzzy matching algorithm:
- test_fuzzy_matching_with_typos_and_missing_chars: Tests subsequence matching
with real-world scenarios including abbreviated patterns, case-insensitive
matching, and complex file/package name completion
- test_fuzzy_matching_scoring_priority: Validates scoring system prioritizes
exact matches > prefix matches > substring matches > subsequence matches
- test_fuzzy_matching_edge_cases: Covers boundary conditions including
single character queries, oversized queries, and repeated characters
These tests ensure robust fuzzy search functionality for MCP completion
specification implementation with proper handling of user typos and
incomplete input patterns.
* feat: improve completion algorithms, add comprehensive tests and example
- Enhance fuzzy matching algorithm with acronym support for multi-word entries
- Add comprehensive scoring system for better relevance ranking
- Implement multi-level matching: exact, prefix, word prefix, acronym, substring
- Add context-aware completion scoring with proper priority ordering
- Optimize performance through efficient character-by-character matching
- Support case-insensitive acronym matching
- Improve code quality with clippy fixes and async fn syntax
- Add comprehensive test suite covering edge cases and acronym matching
- Create completion example server demonstrating weather-related prompts
* fix(test): typos
* refactor: improve completion API and replace example with SQL query builder
- Remove DefaultCompletionProvider from library core
- Move completion logic to examples following review feedback
- Update CompletionContext.argument_names() to return Iterator for better performance
- Replace tech search example with SQL query builder demonstrating progressive completion
- Add context-aware completion that adapts based on filled arguments
- Use proper Option types for optional SQL fields (columns, where_clause, values)
- Demonstrate real-world value of argument_names() method for dynamic completion flow
The SQL query builder showcases:
• Progressive field availability based on operation type
• Context validation using argument_names()
• Proper Optional field handling
• Smart completion that guides user through multi-step form
* fix: fmt
The JSON-RPC 2.0 specification allows the ID field to be any JSON number,
including negative integers and large values. The previous u32 implementation
was limited to 0-4,294,967,295 and couldn't handle negative IDs.
Changes:
- Changed NumberOrString::Number from u32 to i64 to support full JSON number range
- Updated deserializer to handle both signed and unsigned integers
- Modified AtomicU32Provider to use AtomicU64 internally with i64 conversion
- Fixed progress token handling in meta.rs for i64 values
- Added comprehensive test for negative and large request IDs
This ensures full compliance with the JSON-RPC 2.0 specification.
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-authored-by: Claude <noreply@anthropic.com>
* feat: add _meta to content blocks and embedded resources; update schemas
* feat: set default protocol version; add _meta to content blocks/resources; update schemas
* chore: format content.rs via rustfmt
* chore(protocol): keep LATEST at 2025-03-26 per review until full 2025-06-18 compliance
* feat(prompt): add constructors with optional meta for image and resource
- Keep text helper; meta is currently ignored for text until schema supports it.
* refactor(prompt): simplify constructors so meta is optional; remove duplicate non-meta variants
* fix: modify code comment about version
* refactor(prompt): rename meta parameters in new_resource function for clarity