* fix(http): reduce latency on subsequent StreamableHttp calls
* refactor: rely on stream drain for connection reuse
* refactor: clean up comments and naming
* fix: restore pool_max_idle_per_host(0) for Linux
* feat(transport): add which_command for cross-platform executable resolution
Adds a `which_command()` helper that resolves executable paths via the
`which` crate before constructing a `tokio::process::Command`. This fixes
Windows failures where `.cmd` shim scripts (e.g. `npx.cmd`) are not
found by `Command::new()` without a fully-qualified path.
Closes#456
* refactor(transport): move which_command behind opt-in feature flag
Address review feedback: the `which` dependency is now gated behind a
separate `which-command` feature flag instead of being bundled into
`transport-child-process`. Users on Linux/macOS who don't need
cross-platform executable resolution no longer pull in the extra crate.
Also fixes the doc example import path to use the re-exported
`rmcp::transport::which_command`.
The `local` feature relaxes Send+Sync bounds, which causes items
gated behind `cfg(not(feature = "local"))` to be excluded when
docs.rs builds with all-features. Replace `all-features = true`
with an explicit feature list that omits `local`.
Signed-off-by: majiayu000 <1835304752@qq.com>
* feat(transport): add Unix domain socket client for streamable HTTP
MCP hosts in Kubernetes environments with Envoy sidecars need to route
HTTP through Unix domain sockets because DNS-based URIs only resolve
via the proxy. Adds UnixSocketHttpClient implementing StreamableHttpClient
using hyper over tokio::net::UnixStream, gated behind the
transport-streamable-http-client-unix-socket feature.
Also extracts RESERVED_HEADERS, extract_scope_from_header, and
validate_custom_header into common/http_header.rs to share header
validation logic between the reqwest and unix socket implementations.
* fix(transport): address review feedback for unix socket transport
- Document one-connection-per-request behavior on UnixSocketHttpClient
- Reject empty socket paths and bare '@' in constructor with assert
- Add explicit dep:http to unix-socket feature for self-documenting deps
- Document MCP-Protocol-Version exception on RESERVED_HEADERS constant
- Fix test catch-all to echo request id instead of hardcoding 1
- Remove leftover sleep(100ms) in test_unix_socket_custom_headers
- Add blank line before macro comment in Cargo.toml
* fix(transport): fix CI failures for unix socket transport
- Use std::io::Error::other() instead of Error::new(ErrorKind::Other)
to satisfy clippy::io_other_error on newer nightly
- Use #[tokio::test(flavor = "current_thread")] for unix socket tests
since axum's serve(UnixListener) requires spawn_local
- Gate validate_custom_header behind client-side-sse feature since it
references http::HeaderName which isn't available with default features
* fix(transport): fix CI failures for unix socket transport
axum::serve(UnixListener) uses spawn_local on Linux, which panics
outside a LocalSet. Replace with manual hyper HTTP/1.1 server that
accepts connections directly from the UnixListener, avoiding the
spawn_local requirement entirely.
* fix(transport): skip unix socket tests when local feature is enabled
The local feature causes ().serve(transport) to use spawn_local, which
requires a LocalSet. Gate the integration tests with not(feature = "local")
to match every other integration test in the repo.
* feat: add configuration for transparent session re-init
* fix: in ci revert running tests without local until all tests pass
* fix: pr comments
* fix: documentation
* fix(rmcp): surface JSON-RPC error bodies on HTTP 4xx responses
When a server returns a 4xx status with Content-Type: application/json,
attempt to deserialize the body as a ServerJsonRpcMessage before falling
back to UnexpectedServerResponse. This allows JSON-RPC error payloads
carried on HTTP error responses to be surfaced as McpError instead of
being lost in a transport-level error string.
Fixes#724
* fix(rmcp): surface JSON-RPC error bodies on HTTP 4xx responses
When a server returns a 4xx status with Content-Type: application/json,
attempt to deserialize the body as a ServerJsonRpcMessage before falling
back to UnexpectedServerResponse. This allows JSON-RPC error payloads
carried on HTTP error responses to be surfaced as McpError instead of
being lost in a transport-level error string.
Fixes#724
* fix(rmcp): only accept JsonRpcMessage::Error on non-success responses
* 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>
* 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>
* 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.
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
* feat: add prompt support with typed argument handling
- Implement #[prompt], #[prompt_router], and #[prompt_handler] macros
- Add automatic JSON schema generation from Rust types for arguments
- Support flexible async handler signatures with automatic adaptation
- Create PromptRouter for efficient prompt dispatch
- Include comprehensive tests and example implementation
This enables MCP servers to provide reusable prompt templates that
LLMs can discover and invoke with strongly-typed parameters, similar
to the existing tool system but optimized for prompt use cases.
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor: unify parameter handling between tools and prompts
- Replace Arguments<T> with Parameters<T> for consistent API
- Create shared common module for tool/prompt utilities
- Modernize async handling with futures::future::BoxFuture
- Move cached_schema_for_type to common module for reuse
- Update error types from rmcp::Error to rmcp::ErrorData
- Add comprehensive trait implementations for parameter extraction
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
* refactor: extract Parameters wrapper to shared module and unify trait usage
- Move Parameters type from common.rs to dedicated wrapper/parameters.rs module
- Unify extractor traits by using FromContextPart for both tools and prompts
- Remove duplicate FromToolCallContextPart and FromPromptContextPart traits
- Add structured output support to Json wrapper with IntoCallToolResult impl
- Improve error messages with more descriptive panic for schema serialization
- Update all imports across codebase to use new module path
- Clean up trailing whitespace and formatting inconsistencies
This consolidates parameter extraction logic and reduces code duplication
between tool and prompt handlers while maintaining backward compatibility.
* chore: remove committed .egg-info directory and update gitignore
* docs: fix documentation formatting
* fix: add reqwest dependency to transport-streamable-http-client feature
- Fix compilation error when using transport-streamable-http-client feature due to missing dependency
- Move From<reqwest::Error> implementation to reqwest module
* feat(rmcp): enhance transport features by decoupling reqwest
- Added reqwest features for reqwest-based implementations.
- Updated documentation
- Modified error handling in SSE transport to use `String` for content type.
- Updated examples to include new features
* feat(rmcp): enhance transport features by decoupling reqwest
- Added reqwest features for reqwest-based implementations
- Updated documentation
- Modified error handling in SSE transport to use `String`
- Updated examples to include new features
* feat: implement MCP elicitation support for interactive user input
Adds comprehensive elicitation functionality according to MCP 2025-06-18 specification:
Core Features:
- ElicitationAction enum (Accept, Decline, Cancel)
- CreateElicitationRequestParam and CreateElicitationResult structures
- Protocol version V_2025_06_18 with elicitation methods
- Full JSON-RPC integration with method constants
Capabilities Integration:
- ElicitationCapability with schema validation support
- ClientCapabilities builder pattern integration
- enable_elicitation() and enable_elicitation_schema_validation() methods
Handler Support:
- create_elicitation method in ClientHandler and ServerHandler traits
- Integration with existing request/response union types
- Async/await compatible implementation
Service Layer:
- Basic create_elicitation method via macro expansion
- Four convenience methods for common scenarios:
* elicit_confirmation() - yes/no questions
* elicit_text_input() - string input with optional requirements
* elicit_choice() - selection from multiple options
* elicit_structured_input() - complex data via JSON Schema
Comprehensive Testing:
- 11 test cases covering all functionality aspects
- JSON serialization/deserialization validation
- MCP specification compliance verification
- Error handling and edge cases
- Performance benchmarks
- Capabilities integration tests
All tests pass and code follows project standards.
* feat: add typed elicitation API with enhanced error handling
- Add new 'elicitation' feature that depends on 'client' and 'schemars'
- Implement elicit<T>() method for type-safe elicitation with automatic schema generation
- Remove convenience methods (elicit_confirmation, elicit_text_input, elicit_choice)
- Add ElicitationError enum with detailed error variants:
- Service: underlying service errors
- UserDeclined: user cancelled or declined request
- ParseError: response parsing failed with context
- NoContent: no response content provided
- Update documentation with comprehensive examples and error handling
- Add comprehensive tests for typed elicitation and error handling
* fix: correct elicitation direction to comply with MCP 2025-06-18
- Remove CreateElicitationRequest from ClientRequest - clients cannot initiate elicitation
- Move elicit methods from client to server - servers now request user input
- Add comprehensive direction tests verifying Server→Client→Server flow
- Maintain CreateElicitationResult in ClientResult for proper responses
- Update handlers to reflect correct message routing
- Add elicitation feature flag for typed schema generation
Fixes elicitation direction to match specification where servers request
interactive user input from clients, not the reverse.
* feat: add elicitation capability checking for server methods
- Add supports_elicitation() method to check client capabilities
- Add CapabilityNotSupported error variant to ElicitationError
- Update elicit_structured_input() to check capabilities before execution
- Update elicit<T>() method to check capabilities before execution
- Add comprehensive tests for capability checking functionality
- Tests verify that servers check client capabilities before sending elicitation requests
- Ensures compliance with MCP 2025-06-18 specification requirement
* fix: json rpc message schema
* fix: doc tests
* fix: cargo nightly fmt checks
* fix: clippy
* refactor: separate elicitation methods into dedicated impl block for RoleServer
- Move (supports_elicitation, elicit_structured_input, elicit) to separate impl block
- Move ElicitationError definition to elicitation methods section
- Keep base methods (create_message, list_roots, notify_*) in main impl block with macro
- Add section comments to distinguish general and elicitation-specific methods
* revert: rollback LATEST protocol version to V_2025_03_26
* fix: remove protocol version assertions
- Remove assertions for V_2025_06_18 protocol version
* fix: fmt checks
* feat: add timeout support for elicitation methods
- Add peer_req_with_timeout macro variants for timeout-enabled methods
- Implement create_elicitation_with_timeout() method
- Implement elicit_with_timeout() for typed elicitation with timeout
- Refactor elicit() to use elicit_with_timeout() internally
- Add 8 comprehensive timeout tests covering validation, error handling, and realistic scenarios
- Fix elicitation feature dependencies in Cargo.toml
- Add proper feature gates for elicitation-specific code
* feat: add timeout validation to prevent DoS attacks
- Add InvalidTimeout error variant for comprehensive validation
- Implement validate_timeout function with security limits (1ms-300s)
- Integrate validation into peer_req_with_timeout macros
- Add comprehensive security tests for timeout validation
- Prevent DoS attacks through unreasonable timeout values
* feat: separate UserDeclined and UserCancelled elicitation errors
According to MCP specification and PR feedback, decline and cancel
actions should be handled differently:
- UserDeclined: explicit user rejection (clicked "Decline", "No", etc.)
- UserCancelled: dismissal without explicit choice (closed dialog, Escape, etc.)
Changes:
- Split ElicitationError::UserDeclined into two distinct error types
- Update error handling logic to map each ElicitationAction correctly
- Improve documentation with proper action semantics
- Add comprehensive tests for new error types and action mapping
- Update examples to demonstrate proper error handling
This provides better error granularity allowing servers to handle
explicit declines vs cancellations appropriately as per MCP spec.
* feat: add compile-time type safety for elicitation methods
Add ElicitationSafe trait and elicit_safe\! macro to ensure elicit<T>()
methods are only used with types that generate appropriate JSON object
schemas, addressing type safety concerns from PR feedback.
Features:
- ElicitationSafe marker trait for compile-time constraints
- elicit_safe\! macro for opt-in type safety declaration
- Updated elicit<T> and elicit_with_timeout<T> to require ElicitationSafe bound
- Comprehensive documentation with examples and rationale
- Full test coverage for new type safety features
This prevents common mistakes like:
- elicit::<String>() - primitives not suitable for object schemas
- elicit::<Vec<i32>>() - arrays don't match client expectations
Breaking change: Existing code must add elicit_safe\!(TypeName) declarations
for types used with elicit methods. This is an intentional safety improvement.
* Revert "feat: add timeout validation to prevent DoS attacks"
This reverts commit 829624212b4fb55ec32566329af7ec195c987ef5.
* fix: correct doctest example in elicit_safe macro documentation
- Remove invalid async/await usage in doctest example
- Comment out the actual usage line to show intent without compilation errors
- Maintain clear documentation of the macro's purpose and usage
* refactor: remove redundant elicitation direction tests
- Remove test_elicitation_not_in_client_request (duplicated functionality)
- Remove redundant ServerRequest match in test_elicitation_direction_server_to_client
- Direction compliance is already verified by the remaining comprehensive test
- Reduces test fragility and maintenance burden
* feat: add elicitation example with user name collection
- Add elicitation server example demonstrating real MCP usage
- Implement greet_user tool with context.peer.elicit::<T>() API
- Show type-safe elicitation with elicit_safe! macro
- Include reset_name tool and MCP Inspector instructions
- Update examples documentation and dependencies
* fix: add Default impl to ElicitationServer for clippy
Resolves clippy::new_without_default warning by implementing
Default trait for ElicitationServer struct.
* refactor: refactor tool macros and router implementation
- Updated the `#[tool(tool_box)]` macro to `#[tool_router]` across various modules for consistency.
- Enhanced the `Calculator`, `Counter`, and `GenericService` structs to utilize `ToolRouter` for handling tool calls.
- Introduced `Parameters` struct for better parameter handling in tool functions.
- Added new methods for listing tools and calling tools in server handlers.
- Improved test cases to reflect changes in tool routing and parameter handling.
- Updated documentation and examples to align with the new router structure.
* fix: fix fmt and build error
* fix: fix test failure
* docs: documents for macros, fix ci
* fix: fix ci
* fix: fix wrongly replaced documents
* fix: remove useless file
* fix: change the parameter format for tool_router
* fix: update extract_doc_line to handle existing documentation and clean up unused code in server handler
* doc: update document for macro and examples
* doc: update readme and add contribute guide
* fix: fix type