feat!: add server discovery and negotiation (SEP-2575) (#973)

* feat!: add server discovery and negotiation

* feat!: make protocol unions extensible

* ci: add discovery conformance coverage
This commit is contained in:
Dale Seo 2026-07-16 13:47:30 -04:00 • committed by GitHub
commit 3549e86d28
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 1325 additions and 98 deletions

View file

@ -37,7 +37,7 @@ jobs:
- name: Test conformance server
run: cargo test -p mcp-conformance --bin conformance-server
- name: Start conformance server
- name: Start 2025-11-25 server
run: |
PORT=8001 ./target/debug/conformance-server &
echo $! > server.pid
@ -50,7 +50,7 @@ jobs:
echo "conformance server did not become ready" >&2
exit 1
- name: Run server conformance suite
- name: Run 2025-11-25 server suite
run: |
npx -y "@modelcontextprotocol/conformance@${CONFORMANCE_VERSION}" server \
--url http://127.0.0.1:8001/mcp \
@ -59,7 +59,7 @@ jobs:
# These pass today but are excluded from the default "active" suite;
# run them explicitly so regressions are still caught.
- name: Run pending scenarios
- name: Run 2025-11-25 pending scenarios
run: |
for scenario in json-schema-2020-12 server-sse-polling; do
npx -y "@modelcontextprotocol/conformance@${CONFORMANCE_VERSION}" server \
@ -68,7 +68,7 @@ jobs:
-o conformance-results
done
- name: Start draft conformance server
- name: Start draft server
run: |
STATELESS=1 PORT=8002 ./target/debug/conformance-server &
echo $! > draft-server.pid
@ -81,27 +81,85 @@ jobs:
echo "draft conformance server did not become ready" >&2
exit 1
- name: Run draft SEP scenarios
# Run discovery separately until #985 enables the full draft suite.
- name: Run SEP-2575 discovery contract
run: |
endpoint=http://127.0.0.1:8002/mcp
common_headers=(
-H "Content-Type: application/json"
-H "Accept: application/json, text/event-stream"
-H "Mcp-Method: server/discover"
)
discover_response="$(
curl --fail-with-body --silent --show-error \
"${common_headers[@]}" \
-H "MCP-Protocol-Version: 2026-07-28" \
--data '{
"jsonrpc": "2.0",
"id": "discover",
"method": "server/discover",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {
"name": "conformance-workflow",
"version": "1.0.0"
},
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}' \
"$endpoint"
)"
jq -e '
.result.resultType == "complete" and
(.result.supportedVersions | index("2026-07-28") != null) and
(.result.capabilities | type == "object") and
(.result.serverInfo.name | type == "string") and
.result.ttlMs == 0 and
.result.cacheScope == "private"
' <<<"$discover_response"
status="$(
curl --silent --show-error \
--output /tmp/unsupported-version.json \
--write-out "%{http_code}" \
"${common_headers[@]}" \
-H "MCP-Protocol-Version: 2099-01-01" \
--data '{
"jsonrpc": "2.0",
"id": "unsupported",
"method": "server/discover",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2099-01-01",
"io.modelcontextprotocol/clientInfo": {
"name": "conformance-workflow",
"version": "1.0.0"
},
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}' \
"$endpoint"
)"
test "$status" = "400"
jq -e '
.id == "unsupported" and
.error.code == -32022 and
.error.data.requested == "2099-01-01" and
(.error.data.supported | index("2026-07-28") != null)
' /tmp/unsupported-version.json
# Keep this explicit list until the full draft suite is enabled by #985.
- name: Run supported draft server scenarios
run: |
for scenario in \
sep-2164-resource-not-found \
caching \
http-header-validation \
http-custom-header-server-validation \
; do
npx -y "@modelcontextprotocol/conformance@${DRAFT_CONFORMANCE_VERSION}" server \
--url http://127.0.0.1:8002/mcp \
--scenario "$scenario" \
--spec-version draft \
-o conformance-results
done
# SEP-2322 MRTR scenarios (spec 2026-07-28). They speak the stateless
# lifecycle (bare JSON-RPC POSTs, no initialize handshake), so they run
# against the stateless draft server.
- name: Run SEP-2322 MRTR scenarios
run: |
for scenario in \
input-required-result-basic-elicitation \
input-required-result-basic-sampling \
input-required-result-basic-list-roots \
@ -120,17 +178,15 @@ jobs:
npx -y "@modelcontextprotocol/conformance@${DRAFT_CONFORMANCE_VERSION}" server \
--url http://127.0.0.1:8002/mcp \
--scenario "$scenario" \
--spec-version draft \
-o conformance-results
done
- name: Stop draft conformance server
- name: Stop conformance servers
if: always()
run: kill "$(cat draft-server.pid)" 2>/dev/null || true
- name: Stop conformance server
if: always()
run: kill "$(cat server.pid)" 2>/dev/null || true
run: |
kill "$(cat draft-server.pid)" 2>/dev/null || true
kill "$(cat server.pid)" 2>/dev/null || true
- name: Upload results
if: always()
@ -154,7 +210,7 @@ jobs:
- name: Build conformance binaries
run: cargo build -p mcp-conformance
- name: Run full client conformance suite
- name: Run 2025-11-25 client suite
run: |
npx -y "@modelcontextprotocol/conformance@${CONFORMANCE_VERSION}" client \
--command "$(pwd)/target/debug/conformance-client" \
@ -163,7 +219,7 @@ jobs:
-o conformance-client-results/full
# SEP-2322 MRTR client scenario (spec 2026-07-28).
- name: Run SEP-2322 MRTR client scenario
- name: Run draft SEP-2322 client scenario
run: |
npx -y "@modelcontextprotocol/conformance@${DRAFT_CONFORMANCE_VERSION}" client \
--command "$(pwd)/target/debug/conformance-client" \

View file

@ -1,6 +1,6 @@
// Sampling/Roots/Logging are SEP-2577-deprecated; internal references are expected.
#![expect(deprecated)]
use std::sync::Arc;
use std::{borrow::Cow, sync::Arc};
use crate::{
error::ErrorData as McpError,
@ -30,11 +30,46 @@ impl<H: ServerHandler> Service<RoleServer> for H {
let mrtr_supported = protocol_version
.as_ref()
.is_some_and(|v| v.as_str() >= ProtocolVersion::V_2026_07_28.as_str());
let requested_version = context.meta.protocol_version();
let uses_inline_negotiation = !matches!(&request, ClientRequest::InitializeRequest(_));
if uses_inline_negotiation && let Some(requested_version) = requested_version.as_ref() {
let supported_versions = self.supported_protocol_versions();
if !supported_versions.contains(requested_version) {
return Err(McpError::unsupported_protocol_version(
requested_version.clone(),
&supported_versions,
));
}
}
if matches!(&request, ClientRequest::DiscoverRequest(_)) {
if requested_version.is_none() {
return Err(McpError::invalid_params(
"server/discover requires protocolVersion in request _meta",
None,
));
}
if context.meta.client_info().is_none() {
return Err(McpError::invalid_params(
"server/discover requires clientInfo in request _meta",
None,
));
}
if context.meta.client_capabilities().is_none() {
return Err(McpError::invalid_params(
"server/discover requires clientCapabilities in request _meta",
None,
));
}
}
let result = match request {
ClientRequest::InitializeRequest(request) => self
.initialize(request.params, context)
.await
.map(ServerResult::InitializeResult),
ClientRequest::DiscoverRequest(_request) => self
.discover(context)
.await
.map(ServerResult::DiscoverResult),
ClientRequest::PingRequest(_request) => {
self.ping(context).await.map(ServerResult::empty)
}
@ -225,6 +260,20 @@ macro_rules! server_handler_methods {
);
std::future::ready(Ok(info))
}
/// Return the protocol versions supported by this server.
fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
Cow::Borrowed(ProtocolVersion::KNOWN_VERSIONS)
}
/// Return this server's discovery information.
fn discover(
&self,
context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<DiscoverResult, McpError>> + MaybeSendFuture + '_ {
std::future::ready(Ok(DiscoverResult::from_server_info(
self.supported_protocol_versions().into_owned(),
self.get_info(),
)))
}
fn complete(
&self,
request: CompleteRequestParams,
@ -479,6 +528,17 @@ macro_rules! impl_server_handler_for_wrapper {
(**self).initialize(request, context)
}
fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
(**self).supported_protocol_versions()
}
fn discover(
&self,
context: RequestContext<RoleServer>,
) -> impl Future<Output = Result<DiscoverResult, McpError>> + MaybeSendFuture + '_ {
(**self).discover(context)
}
fn complete(
&self,
request: CompleteRequestParams,

View file

@ -19,7 +19,7 @@ pub use handler::server::wrapper::Json;
#[cfg(any(feature = "client", feature = "server"))]
pub use service::{Peer, Service, ServiceError, ServiceExt};
#[cfg(feature = "client")]
pub use service::{RoleClient, serve_client};
pub use service::{RoleClient, select_protocol_version, serve_client};
#[cfg(feature = "server")]
pub use service::{RoleServer, serve_server};

View file

@ -524,6 +524,10 @@ pub struct JsonRpcNotification<N = Notification> {
pub struct ErrorCode(pub i32);
impl ErrorCode {
/// The request used a protocol version the server does not support.
pub const UNSUPPORTED_PROTOCOL_VERSION: Self = Self(-32022);
/// Processing the request requires a client capability that was not declared.
pub const MISSING_REQUIRED_CLIENT_CAPABILITY: Self = Self(-32021);
pub const HEADER_MISMATCH: Self = Self(-32020);
pub const RESOURCE_NOT_FOUND: Self = Self(-32002);
pub const INVALID_REQUEST: Self = Self(-32600);
@ -573,6 +577,30 @@ impl ErrorData {
pub fn header_mismatch(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::HEADER_MISMATCH, message, data)
}
/// Create an unsupported-protocol-version error.
pub fn unsupported_protocol_version(
requested: ProtocolVersion,
supported: &[ProtocolVersion],
) -> Self {
Self::new(
ErrorCode::UNSUPPORTED_PROTOCOL_VERSION,
"Unsupported protocol version",
Some(serde_json::json!({
"requested": requested,
"supported": supported,
})),
)
}
/// Create a missing-required-capability error.
pub fn missing_required_client_capability(required: ClientCapabilities) -> Self {
Self::new(
ErrorCode::MISSING_REQUIRED_CLIENT_CAPABILITY,
"Missing required client capability",
Some(serde_json::json!({
"requiredCapabilities": required,
})),
)
}
pub fn parse_error(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::PARSE_ERROR, message, data)
}
@ -1000,6 +1028,112 @@ impl InitializeResult {
pub type ServerInfo = InitializeResult;
pub type ClientInfo = InitializeRequestParams;
const_string!(DiscoverRequestMethod = "server/discover");
/// Parameters for [`DiscoverRequest`].
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Default)]
#[serde(deny_unknown_fields)]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct DiscoverRequestParams {}
#[cfg(feature = "schemars")]
#[derive(schemars::JsonSchema)]
#[expect(dead_code, reason = "schema-only representation of request parameters")]
struct DiscoverRequestParamsSchema {
#[schemars(rename = "_meta")]
meta: RequestMetaObject,
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for DiscoverRequestParams {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("DiscoverRequestParams")
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
DiscoverRequestParamsSchema::json_schema(generator)
}
}
/// A request for the server's supported protocol versions and capabilities.
pub type DiscoverRequest = Request<DiscoverRequestMethod, DiscoverRequestParams>;
/// The server's response to a [`DiscoverRequest`].
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct DiscoverResult {
/// Identifies how the result should be parsed.
pub result_type: ResultType,
/// Protocol versions implemented by this server.
pub supported_versions: Vec<ProtocolVersion>,
/// Capabilities provided by this server.
pub capabilities: ServerCapabilities,
/// Information about the server implementation.
pub server_info: Implementation,
/// Optional guidance for using the server.
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Option<String>,
/// How long clients may consider this response fresh, in milliseconds.
pub ttl_ms: u64,
/// Whether the cached result may be shared across authorization contexts.
pub cache_scope: CacheScope,
/// Protocol-level response metadata.
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
pub meta: Option<MetaObject>,
}
impl DiscoverResult {
/// Create a non-cacheable private discovery result.
pub fn new(
supported_versions: Vec<ProtocolVersion>,
capabilities: ServerCapabilities,
server_info: Implementation,
) -> Self {
Self {
result_type: ResultType::COMPLETE,
supported_versions,
capabilities,
server_info,
instructions: None,
ttl_ms: 0,
cache_scope: CacheScope::Private,
meta: None,
}
}
/// Create a discovery result from the server's initialization information.
pub fn from_server_info(
supported_versions: Vec<ProtocolVersion>,
server_info: ServerInfo,
) -> Self {
let ServerInfo {
capabilities,
server_info,
instructions,
meta,
..
} = server_info;
let mut result = Self::new(supported_versions, capabilities, server_info);
result.instructions = instructions;
result.meta = meta;
result
}
/// Set the cache lifetime hint in milliseconds.
pub fn with_ttl_ms(mut self, ttl_ms: u64) -> Self {
self.ttl_ms = ttl_ms;
self
}
/// Set the cache scope.
pub fn with_cache_scope(mut self, cache_scope: CacheScope) -> Self {
self.cache_scope = cache_scope;
self
}
}
#[allow(clippy::derivable_impls)]
impl Default for ServerInfo {
fn default() -> Self {
@ -3765,7 +3899,7 @@ macro_rules! ts_union {
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
#[expect(clippy::exhaustive_enums, reason = "intentionally exhaustive")]
#[non_exhaustive]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum $U {
$($declared)*
@ -3795,6 +3929,7 @@ ts_union!(
export type ClientRequest =
| PingRequest
| InitializeRequest
| DiscoverRequest
| CompleteRequest
| SetLevelRequest
| GetPromptRequest
@ -3818,6 +3953,7 @@ impl ClientRequest {
match &self {
ClientRequest::PingRequest(r) => r.method.as_str(),
ClientRequest::InitializeRequest(r) => r.method.as_str(),
ClientRequest::DiscoverRequest(r) => r.method.as_str(),
ClientRequest::CompleteRequest(r) => r.method.as_str(),
ClientRequest::SetLevelRequest(r) => r.method.as_str(),
ClientRequest::GetPromptRequest(r) => r.method.as_str(),
@ -3889,6 +4025,7 @@ ts_union!(
ts_union!(
export type ServerResult =
| DiscoverResult
| InitializeResult
| CompleteResult
| GetPromptResult

View file

@ -189,6 +189,7 @@ variant_extension! {
ClientRequest: RequestMetaObject {
PingRequest
InitializeRequest
DiscoverRequest
CompleteRequest
SetLevelRequest
GetPromptRequest

View file

@ -10,17 +10,19 @@ use crate::{
ArgumentInfo, CallToolRequest, CallToolRequestParams, CallToolResponse, CallToolResult,
CancelledNotification, CancelledNotificationParam, ClientInfo, ClientJsonRpcMessage,
ClientNotification, ClientRequest, ClientResult, CompleteRequest, CompleteRequestParams,
CompleteResult, CompletionContext, CompletionInfo, DEFAULT_MRTR_MAX_ROUNDS, ErrorData,
GetExtensions, GetMeta, GetPromptRequest, GetPromptRequestParams, GetPromptResponse,
GetPromptResult, InitializeRequest, InitializedNotification, InputRequest,
InputRequiredResult, InputResponses, JsonRpcResponse, ListPromptsRequest,
ListPromptsResult, ListResourceTemplatesRequest, ListResourceTemplatesResult,
ListResourcesRequest, ListResourcesResult, ListToolsRequest, ListToolsResult,
NumberOrString, PaginatedRequestParams, ProgressNotification, ProgressNotificationParam,
CompleteResult, CompletionContext, CompletionInfo, DEFAULT_MRTR_MAX_ROUNDS,
DiscoverRequest, DiscoverRequestParams, DiscoverResult, ErrorData, GetExtensions, GetMeta,
GetPromptRequest, GetPromptRequestParams, GetPromptResponse, GetPromptResult,
InitializeRequest, InitializedNotification, InputRequest, InputRequiredResult,
InputResponses, JsonRpcResponse, ListPromptsRequest, ListPromptsResult,
ListResourceTemplatesRequest, ListResourceTemplatesResult, ListResourcesRequest,
ListResourcesResult, ListToolsRequest, ListToolsResult, NumberOrString,
PaginatedRequestParams, ProgressNotification, ProgressNotificationParam, ProtocolVersion,
ReadResourceRequest, ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult,
Reference, RequestId, RootsListChangedNotification, ServerInfo, ServerJsonRpcMessage,
ServerNotification, ServerRequest, ServerResult, SetLevelRequest, SetLevelRequestParams,
SubscribeRequest, SubscribeRequestParams, UnsubscribeRequest, UnsubscribeRequestParams,
Reference, RequestId, RequestMetaObject, RootsListChangedNotification, ServerInfo,
ServerJsonRpcMessage, ServerNotification, ServerRequest, ServerResult, SetLevelRequest,
SetLevelRequestParams, SubscribeRequest, SubscribeRequestParams, UnsubscribeRequest,
UnsubscribeRequestParams,
},
transport::DynamicTransportError,
};
@ -147,6 +149,19 @@ where
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct RoleClient;
/// Select the first client-preferred protocol version supported by the server.
///
/// Returns `None` when no version is shared.
pub fn select_protocol_version(
client_preference: &[ProtocolVersion],
server_supported: &[ProtocolVersion],
) -> Option<ProtocolVersion> {
client_preference
.iter()
.find(|version| server_supported.contains(version))
.cloned()
}
impl ServiceRole for RoleClient {
type Req = ClientRequest;
type Resp = ClientResult;
@ -363,6 +378,22 @@ macro_rules! method {
}
impl Peer<RoleClient> {
/// Discover the server's supported protocol versions and capabilities.
///
/// The high-level client currently exposes this peer only after initialization;
/// pre-initialization probing is planned as follow-up work.
pub async fn discover(&self, meta: RequestMetaObject) -> Result<DiscoverResult, ServiceError> {
let mut request = DiscoverRequest::new(DiscoverRequestParams {});
request.extensions.insert(meta);
let result = self
.send_request(ClientRequest::DiscoverRequest(request))
.await?;
match result {
ServerResult::DiscoverResult(result) => Ok(result),
_ => Err(ServiceError::UnexpectedResponse),
}
}
/// Send one `tools/call` request and return either a final result or an MRTR
/// `InputRequiredResult` without driving any follow-up rounds.
pub async fn call_tool_once(

View file

@ -16,10 +16,10 @@ use super::session::{
use crate::{
RoleServer,
model::{
ClientCapabilities, ClientJsonRpcMessage, ClientNotification, ClientRequest, ErrorData,
GetExtensions, Implementation, InitializeRequest, InitializeRequestParams,
InitializedNotification, JsonObject, JsonRpcError, ProtocolVersion, RequestId,
ServerJsonRpcMessage,
ClientCapabilities, ClientJsonRpcMessage, ClientNotification, ClientRequest, ErrorCode,
ErrorData, GetExtensions, GetMeta, Implementation, InitializeRequest,
InitializeRequestParams, InitializedNotification, JsonObject, JsonRpcError,
ProtocolVersion, RequestId, ServerJsonRpcMessage,
},
serve_server,
service::serve_directly,
@ -199,7 +199,10 @@ impl StreamableHttpServerConfig {
/// Per the MCP 2025-06-18 spec:
/// - If the header is present but contains an unsupported version, return 400 Bad Request.
/// - If the header is absent, assume `2025-03-26` for backwards compatibility (no error).
fn validate_protocol_version_header(headers: &http::HeaderMap) -> Result<(), BoxResponse> {
fn validate_protocol_version_header(
headers: &http::HeaderMap,
allow_unknown: bool,
) -> Result<(), BoxResponse> {
if let Some(value) = headers.get(HEADER_MCP_PROTOCOL_VERSION) {
let version_str = value.to_str().map_err(|_| {
Response::builder()
@ -215,7 +218,7 @@ fn validate_protocol_version_header(headers: &http::HeaderMap) -> Result<(), Box
let is_known = ProtocolVersion::KNOWN_VERSIONS
.iter()
.any(|v| v.as_str() == version_str);
if !is_known {
if !allow_unknown && !is_known {
return Err(Response::builder()
.status(http::StatusCode::BAD_REQUEST)
.body(
@ -230,6 +233,15 @@ fn validate_protocol_version_header(headers: &http::HeaderMap) -> Result<(), Box
Ok(())
}
fn message_has_per_request_protocol_version(message: &ClientJsonRpcMessage) -> bool {
match message {
ClientJsonRpcMessage::Request(request) => {
request.request.get_meta().protocol_version().is_some()
}
_ => false,
}
}
fn invalid_request_jsonrpc_response(
id: Option<RequestId>,
message: impl Into<Cow<'static, str>>,
@ -243,6 +255,19 @@ fn invalid_request_jsonrpc_response(
.expect("valid response")
}
fn invalid_params_jsonrpc_response(
id: Option<RequestId>,
message: impl Into<Cow<'static, str>>,
) -> BoxResponse {
let err = JsonRpcError::new(id, ErrorData::invalid_params(message, None));
let body = serde_json::to_vec(&err).expect("serialize JsonRpcError");
Response::builder()
.status(http::StatusCode::BAD_REQUEST)
.header(http::header::CONTENT_TYPE, JSON_MIME_TYPE)
.body(Full::new(Bytes::from(body)).boxed())
.expect("valid response")
}
#[expect(
clippy::result_large_err,
reason = "BoxResponse is intentionally large; matches other handlers in this file"
@ -278,6 +303,83 @@ fn validate_header_matches_init_body(
Ok(())
}
#[expect(
clippy::result_large_err,
reason = "BoxResponse is intentionally large; matches other handlers in this file"
)]
fn validate_request_protocol_version_meta(
headers: &HeaderMap,
message: &ClientJsonRpcMessage,
) -> Result<(), BoxResponse> {
let ClientJsonRpcMessage::Request(request) = message else {
return Ok(());
};
if matches!(&request.request, ClientRequest::InitializeRequest(_)) {
return Ok(());
}
let is_discover = matches!(&request.request, ClientRequest::DiscoverRequest(_));
let Some(meta_version) = request.request.get_meta().protocol_version() else {
if is_discover {
return Err(invalid_params_jsonrpc_response(
Some(request.id.clone()),
"Invalid params: server/discover requires protocolVersion in request _meta",
));
}
return Ok(());
};
let Some(header_version) = headers
.get(HEADER_MCP_PROTOCOL_VERSION)
.and_then(|value| value.to_str().ok())
else {
return Err(invalid_request_jsonrpc_response(
Some(request.id.clone()),
"Invalid Request: request _meta protocolVersion requires MCP-Protocol-Version header",
));
};
if header_version != meta_version.as_str() {
return Err(header_mismatch_jsonrpc_response(
Some(request.id.clone()),
format!(
"MCP-Protocol-Version header ({header_version}) does not match request _meta protocolVersion ({meta_version})"
),
));
}
Ok(())
}
fn jsonrpc_http_status(message: &ServerJsonRpcMessage) -> http::StatusCode {
let ServerJsonRpcMessage::Error(error) = message else {
return http::StatusCode::OK;
};
// Modern per-request HTTP treats invalid params as a malformed request.
// Legacy requests bypass this mapper and retain HTTP 200 JSON-RPC errors.
match error.error.code {
ErrorCode::UNSUPPORTED_PROTOCOL_VERSION
| ErrorCode::MISSING_REQUIRED_CLIENT_CAPABILITY
| ErrorCode::INVALID_PARAMS => http::StatusCode::BAD_REQUEST,
ErrorCode::METHOD_NOT_FOUND => http::StatusCode::NOT_FOUND,
_ => http::StatusCode::OK,
}
}
fn jsonrpc_message_response(
message: ServerJsonRpcMessage,
map_protocol_status: bool,
) -> Result<BoxResponse, BoxResponse> {
let status = if map_protocol_status {
jsonrpc_http_status(&message)
} else {
http::StatusCode::OK
};
let body =
serde_json::to_vec(&message).map_err(internal_error_response("serialize json response"))?;
Ok(Response::builder()
.status(status)
.header(http::header::CONTENT_TYPE, JSON_MIME_TYPE)
.body(Full::new(Bytes::from(body)).boxed())
.expect("valid response"))
}
fn header_mismatch_jsonrpc_response(
id: Option<RequestId>,
message: impl Into<Cow<'static, str>>,
@ -739,6 +841,51 @@ where
(self.service_factory)()
}
// The HTTP status must be known before opening an SSE stream.
async fn serve_negotiated_request_directly(
&self,
service: S,
mut request: crate::model::JsonRpcRequest<ClientRequest>,
parts: http::request::Parts,
) -> Result<BoxResponse, BoxResponse> {
let peer_info = Self::peer_info_for_stateless_request(&request, &parts.headers);
request.request.extensions_mut().insert(parts);
let (transport, mut receiver) =
OneshotTransport::<RoleServer>::new(ClientJsonRpcMessage::Request(request));
let service = serve_directly(service, transport, peer_info);
tokio::spawn(async move {
let _ = service.waiting().await;
});
let cancel = self.config.cancellation_token.child_token();
let first = tokio::select! {
message = receiver.recv() => message,
_ = cancel.cancelled() => None,
}
.ok_or_else(|| {
internal_error_response("empty response")(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"no response message received from handler",
))
})?;
if self.config.json_response || jsonrpc_http_status(&first) != http::StatusCode::OK {
return jsonrpc_message_response(first, true);
}
let stream = futures::stream::once(async move { first })
.chain(ReceiverStream::new(receiver))
.map(|message| {
tracing::trace!(?message);
ServerSseMessage::from_message(message)
});
Ok(sse_stream_response(
stream,
self.config.sse_keep_alive,
self.config.cancellation_token.child_token(),
))
}
/// Returns the cached input schema for `name`, constructing a service once
/// per name to read its `ServerHandler::get_tool` definition. Used to
/// validate SEP-2243 `Mcp-Param-*` headers against the request body.
@ -1061,7 +1208,7 @@ where
}
}
// Validate MCP-Protocol-Version header (per 2025-06-18 spec)
validate_protocol_version_header(&parts.headers)?;
validate_protocol_version_header(&parts.headers, false)?;
// check if last event id is provided
let last_event_id = parts
.headers
@ -1191,7 +1338,9 @@ where
}
// Validate MCP-Protocol-Version header (per 2025-06-18 spec)
validate_protocol_version_header(&part.headers)?;
let has_per_request_version = message_has_per_request_protocol_version(&message);
validate_protocol_version_header(&part.headers, has_per_request_version)?;
validate_request_protocol_version_meta(&part.headers, &message)?;
// Validate SEP-2243 standard headers against the body
validate_standard_headers(&part.headers, &message, |name| self.tool_schema(name))?;
@ -1236,6 +1385,29 @@ where
}
}
} else {
if matches!(
&message,
ClientJsonRpcMessage::Request(request)
if matches!(&request.request, ClientRequest::DiscoverRequest(_))
) {
validate_protocol_version_header(
&part.headers,
message_has_per_request_protocol_version(&message),
)?;
validate_standard_headers(&part.headers, &message, |name| {
self.tool_schema(name)
})?;
validate_request_protocol_version_meta(&part.headers, &message)?;
let ClientJsonRpcMessage::Request(request) = message else {
unreachable!("guarded as a request above");
};
let service = self
.get_service()
.map_err(internal_error_response("get service"))?;
return self
.serve_negotiated_request_directly(service, request, part)
.await;
}
// Capture init params for external store persistence before
// extensions are injected (which would require Clone).
let stored_init_params = match &mut message {
@ -1330,6 +1502,7 @@ where
// Stateless mode:
// - on initialize: the header (if present) must match `params.protocolVersion`
// - on every other request: the header must name a known version.
let has_per_request_version = message_has_per_request_protocol_version(&message);
match &message {
ClientJsonRpcMessage::Request(req) => {
if let ClientRequest::InitializeRequest(init_req) = &req.request {
@ -1339,20 +1512,28 @@ where
Some(req.id.clone()),
)?;
} else {
validate_protocol_version_header(&part.headers)?;
validate_protocol_version_header(&part.headers, has_per_request_version)?;
}
}
_ => {
validate_protocol_version_header(&part.headers)?;
validate_protocol_version_header(&part.headers, has_per_request_version)?;
}
}
// Validate SEP-2243 standard headers against the body
validate_standard_headers(&part.headers, &message, |name| self.tool_schema(name))?;
validate_request_protocol_version_meta(&part.headers, &message)?;
let service = self
.get_service()
.map_err(internal_error_response("get service"))?;
match message {
ClientJsonRpcMessage::Request(mut request) => {
let negotiates_per_request = has_per_request_version
|| matches!(&request.request, ClientRequest::DiscoverRequest(_));
if negotiates_per_request {
return self
.serve_negotiated_request_directly(service, request, part)
.await;
}
// Build a peer_info so context.protocol_version() works inside handlers.
// serve_directly skips the handshake and receives None by default, making
// protocol_version() always return None in stateless mode. We reconstruct it:
@ -1453,7 +1634,7 @@ where
.expect("valid response"));
};
// Validate MCP-Protocol-Version header (per 2025-06-18 spec)
validate_protocol_version_header(request.headers())?;
validate_protocol_version_header(request.headers(), false)?;
// close session
self.session_manager
.close_session(&session_id)

View file

@ -562,6 +562,22 @@
"CustomResult": {
"description": "A catch-all response either side can use for custom requests."
},
"DiscoverRequestMethod": {
"type": "string",
"format": "const",
"const": "server/discover"
},
"DiscoverRequestParams": {
"type": "object",
"properties": {
"_meta": {
"$ref": "#/definitions/RequestMetaObject"
}
},
"required": [
"_meta"
]
},
"ElicitResult": {
"description": "The result returned by a client in response to an elicitation request.\n\nContains the user's decision (accept/decline/cancel) and optionally their input data\nif they chose to accept the request.",
"type": "object",
@ -1120,6 +1136,9 @@
{
"$ref": "#/definitions/Request4"
},
{
"$ref": "#/definitions/Request5"
},
{
"$ref": "#/definitions/RequestOptionalParam"
},
@ -1129,9 +1148,6 @@
{
"$ref": "#/definitions/RequestOptionalParam3"
},
{
"$ref": "#/definitions/Request5"
},
{
"$ref": "#/definitions/Request6"
},
@ -1141,21 +1157,24 @@
{
"$ref": "#/definitions/Request8"
},
{
"$ref": "#/definitions/RequestOptionalParam4"
},
{
"$ref": "#/definitions/Request9"
},
{
"$ref": "#/definitions/RequestOptionalParam5"
"$ref": "#/definitions/RequestOptionalParam4"
},
{
"$ref": "#/definitions/Request10"
},
{
"$ref": "#/definitions/RequestOptionalParam5"
},
{
"$ref": "#/definitions/Request11"
},
{
"$ref": "#/definitions/Request12"
},
{
"$ref": "#/definitions/CustomRequest"
}
@ -1548,6 +1567,22 @@
]
},
"Request10": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
"method": {
"$ref": "#/definitions/GetTaskMethod"
},
"params": {
"$ref": "#/definitions/GetTaskParams"
}
},
"required": [
"method",
"params"
]
},
"Request11": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1563,7 +1598,7 @@
"params"
]
},
"Request11": {
"Request12": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1580,6 +1615,22 @@
]
},
"Request2": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
"method": {
"$ref": "#/definitions/DiscoverRequestMethod"
},
"params": {
"$ref": "#/definitions/DiscoverRequestParams"
}
},
"required": [
"method",
"params"
]
},
"Request3": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1595,7 +1646,7 @@
"params"
]
},
"Request3": {
"Request4": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1611,7 +1662,7 @@
"params"
]
},
"Request4": {
"Request5": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1627,7 +1678,7 @@
"params"
]
},
"Request5": {
"Request6": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1643,7 +1694,7 @@
"params"
]
},
"Request6": {
"Request7": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1659,7 +1710,7 @@
"params"
]
},
"Request7": {
"Request8": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1675,7 +1726,7 @@
"params"
]
},
"Request8": {
"Request9": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1691,22 +1742,6 @@
"params"
]
},
"Request9": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
"method": {
"$ref": "#/definitions/GetTaskMethod"
},
"params": {
"$ref": "#/definitions/GetTaskParams"
}
},
"required": [
"method",
"params"
]
},
"RequestMetaObject": {
"description": "Metadata reserved by MCP on requests. Extension keys are also allowed.",
"type": "object",

View file

@ -562,6 +562,22 @@
"CustomResult": {
"description": "A catch-all response either side can use for custom requests."
},
"DiscoverRequestMethod": {
"type": "string",
"format": "const",
"const": "server/discover"
},
"DiscoverRequestParams": {
"type": "object",
"properties": {
"_meta": {
"$ref": "#/definitions/RequestMetaObject"
}
},
"required": [
"_meta"
]
},
"ElicitResult": {
"description": "The result returned by a client in response to an elicitation request.\n\nContains the user's decision (accept/decline/cancel) and optionally their input data\nif they chose to accept the request.",
"type": "object",
@ -1120,6 +1136,9 @@
{
"$ref": "#/definitions/Request4"
},
{
"$ref": "#/definitions/Request5"
},
{
"$ref": "#/definitions/RequestOptionalParam"
},
@ -1129,9 +1148,6 @@
{
"$ref": "#/definitions/RequestOptionalParam3"
},
{
"$ref": "#/definitions/Request5"
},
{
"$ref": "#/definitions/Request6"
},
@ -1141,21 +1157,24 @@
{
"$ref": "#/definitions/Request8"
},
{
"$ref": "#/definitions/RequestOptionalParam4"
},
{
"$ref": "#/definitions/Request9"
},
{
"$ref": "#/definitions/RequestOptionalParam5"
"$ref": "#/definitions/RequestOptionalParam4"
},
{
"$ref": "#/definitions/Request10"
},
{
"$ref": "#/definitions/RequestOptionalParam5"
},
{
"$ref": "#/definitions/Request11"
},
{
"$ref": "#/definitions/Request12"
},
{
"$ref": "#/definitions/CustomRequest"
}
@ -1548,6 +1567,22 @@
]
},
"Request10": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
"method": {
"$ref": "#/definitions/GetTaskMethod"
},
"params": {
"$ref": "#/definitions/GetTaskParams"
}
},
"required": [
"method",
"params"
]
},
"Request11": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1563,7 +1598,7 @@
"params"
]
},
"Request11": {
"Request12": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1580,6 +1615,22 @@
]
},
"Request2": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
"method": {
"$ref": "#/definitions/DiscoverRequestMethod"
},
"params": {
"$ref": "#/definitions/DiscoverRequestParams"
}
},
"required": [
"method",
"params"
]
},
"Request3": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1595,7 +1646,7 @@
"params"
]
},
"Request3": {
"Request4": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1611,7 +1662,7 @@
"params"
]
},
"Request4": {
"Request5": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1627,7 +1678,7 @@
"params"
]
},
"Request5": {
"Request6": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1643,7 +1694,7 @@
"params"
]
},
"Request6": {
"Request7": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1659,7 +1710,7 @@
"params"
]
},
"Request7": {
"Request8": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1675,7 +1726,7 @@
"params"
]
},
"Request8": {
"Request9": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
@ -1691,22 +1742,6 @@
"params"
]
},
"Request9": {
"description": "Represents a JSON-RPC request with method, parameters, and extensions.\n\nThis is the core structure for all MCP requests, containing:\n- `method`: The name of the method being called\n- `params`: The parameters for the method\n- `extensions`: Additional context data (similar to HTTP headers)",
"type": "object",
"properties": {
"method": {
"$ref": "#/definitions/GetTaskMethod"
},
"params": {
"$ref": "#/definitions/GetTaskParams"
}
},
"required": [
"method",
"params"
]
},
"RequestMetaObject": {
"description": "Metadata reserved by MCP on requests. Extension keys are also allowed.",
"type": "object",

View file

@ -743,6 +743,83 @@
"CustomResult": {
"description": "A catch-all response either side can use for custom requests."
},
"DiscoverResult": {
"description": "The server's response to a [`DiscoverRequest`].",
"type": "object",
"properties": {
"_meta": {
"description": "Protocol-level response metadata.",
"anyOf": [
{
"$ref": "#/definitions/MetaObject"
},
{
"type": "null"
}
]
},
"cacheScope": {
"description": "Whether the cached result may be shared across authorization contexts.",
"allOf": [
{
"$ref": "#/definitions/CacheScope"
}
]
},
"capabilities": {
"description": "Capabilities provided by this server.",
"allOf": [
{
"$ref": "#/definitions/ServerCapabilities"
}
]
},
"instructions": {
"description": "Optional guidance for using the server.",
"type": [
"string",
"null"
]
},
"resultType": {
"description": "Identifies how the result should be parsed.",
"allOf": [
{
"$ref": "#/definitions/ResultType"
}
]
},
"serverInfo": {
"description": "Information about the server implementation.",
"allOf": [
{
"$ref": "#/definitions/Implementation"
}
]
},
"supportedVersions": {
"description": "Protocol versions implemented by this server.",
"type": "array",
"items": {
"$ref": "#/definitions/ProtocolVersion"
}
},
"ttlMs": {
"description": "How long clients may consider this response fresh, in milliseconds.",
"type": "integer",
"format": "uint64",
"minimum": 0
}
},
"required": [
"resultType",
"supportedVersions",
"capabilities",
"serverInfo",
"ttlMs",
"cacheScope"
]
},
"ElicitRequestParams": {
"description": "Parameters for creating an elicitation request to gather user input.\n\nThis structure contains everything needed to request interactive input from a user:\n- A human-readable message explaining what information is needed\n- A type-safe schema defining the expected structure of the response\n\n# Example\n1. Form-based elicitation request\n```rust\nuse rmcp::model::*;\n\nlet params = ElicitRequestParams::FormElicitationParams {\n meta: None,\n message: \"Please provide your email\".to_string(),\n requested_schema: ElicitationSchema::builder()\n .required_email(\"email\")\n .build()\n .unwrap(),\n};\n```\n2. URL-based elicitation request\n```rust\nuse rmcp::model::*;\nlet params = ElicitRequestParams::UrlElicitationParams {\n meta: None,\n message: \"Please provide your feedback at the following URL\".to_string(),\n url: \"https://example.com/feedback\".to_string(),\n elicitation_id: \"unique-id-123\".to_string(),\n};\n```",
"anyOf": [
@ -3194,6 +3271,9 @@
},
"ServerResult": {
"anyOf": [
{
"$ref": "#/definitions/DiscoverResult"
},
{
"$ref": "#/definitions/InitializeResult"
},

View file

@ -743,6 +743,83 @@
"CustomResult": {
"description": "A catch-all response either side can use for custom requests."
},
"DiscoverResult": {
"description": "The server's response to a [`DiscoverRequest`].",
"type": "object",
"properties": {
"_meta": {
"description": "Protocol-level response metadata.",
"anyOf": [
{
"$ref": "#/definitions/MetaObject"
},
{
"type": "null"
}
]
},
"cacheScope": {
"description": "Whether the cached result may be shared across authorization contexts.",
"allOf": [
{
"$ref": "#/definitions/CacheScope"
}
]
},
"capabilities": {
"description": "Capabilities provided by this server.",
"allOf": [
{
"$ref": "#/definitions/ServerCapabilities"
}
]
},
"instructions": {
"description": "Optional guidance for using the server.",
"type": [
"string",
"null"
]
},
"resultType": {
"description": "Identifies how the result should be parsed.",
"allOf": [
{
"$ref": "#/definitions/ResultType"
}
]
},
"serverInfo": {
"description": "Information about the server implementation.",
"allOf": [
{
"$ref": "#/definitions/Implementation"
}
]
},
"supportedVersions": {
"description": "Protocol versions implemented by this server.",
"type": "array",
"items": {
"$ref": "#/definitions/ProtocolVersion"
}
},
"ttlMs": {
"description": "How long clients may consider this response fresh, in milliseconds.",
"type": "integer",
"format": "uint64",
"minimum": 0
}
},
"required": [
"resultType",
"supportedVersions",
"capabilities",
"serverInfo",
"ttlMs",
"cacheScope"
]
},
"ElicitRequestParams": {
"description": "Parameters for creating an elicitation request to gather user input.\n\nThis structure contains everything needed to request interactive input from a user:\n- A human-readable message explaining what information is needed\n- A type-safe schema defining the expected structure of the response\n\n# Example\n1. Form-based elicitation request\n```rust\nuse rmcp::model::*;\n\nlet params = ElicitRequestParams::FormElicitationParams {\n meta: None,\n message: \"Please provide your email\".to_string(),\n requested_schema: ElicitationSchema::builder()\n .required_email(\"email\")\n .build()\n .unwrap(),\n};\n```\n2. URL-based elicitation request\n```rust\nuse rmcp::model::*;\nlet params = ElicitRequestParams::UrlElicitationParams {\n meta: None,\n message: \"Please provide your feedback at the following URL\".to_string(),\n url: \"https://example.com/feedback\".to_string(),\n elicitation_id: \"unique-id-123\".to_string(),\n};\n```",
"anyOf": [
@ -3194,6 +3271,9 @@
},
"ServerResult": {
"anyOf": [
{
"$ref": "#/definitions/DiscoverResult"
},
{
"$ref": "#/definitions/InitializeResult"
},

View file

@ -0,0 +1,108 @@
use rmcp::model::{
ClientCapabilities, ClientJsonRpcMessage, ClientRequest, DiscoverResult, ErrorCode, ErrorData,
JsonRpcRequest, JsonRpcResponse, ProtocolVersion, ServerJsonRpcMessage, ServerResult,
};
use serde_json::json;
#[test]
fn discover_request_deserializes_with_request_meta() {
let message: ClientJsonRpcMessage = serde_json::from_value(json!({
"jsonrpc": "2.0",
"id": 1,
"method": "server/discover",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientInfo": {
"name": "test-client",
"version": "1.0.0"
},
"io.modelcontextprotocol/clientCapabilities": {}
}
}
}))
.expect("discover request should deserialize");
let ClientJsonRpcMessage::Request(JsonRpcRequest { request, .. }) = message else {
panic!("expected request");
};
let ClientRequest::DiscoverRequest(request) = request else {
panic!("expected discover request");
};
assert_eq!(
request
.extensions
.get::<rmcp::model::RequestMetaObject>()
.and_then(|meta| meta.protocol_version()),
Some(ProtocolVersion::V_2026_07_28)
);
}
#[test]
fn discover_result_deserializes_to_typed_variant() {
let message: ServerJsonRpcMessage = serde_json::from_value(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {
"resultType": "complete",
"supportedVersions": ["2025-11-25", "2026-07-28"],
"capabilities": { "tools": {} },
"serverInfo": {
"name": "test-server",
"version": "1.0.0"
},
"ttlMs": 0,
"cacheScope": "private"
}
}))
.expect("discover result should deserialize");
let ServerJsonRpcMessage::Response(JsonRpcResponse { result, .. }) = message else {
panic!("expected response");
};
let ServerResult::DiscoverResult(DiscoverResult {
supported_versions, ..
}) = result
else {
panic!("expected discover result");
};
assert_eq!(
supported_versions,
vec![ProtocolVersion::V_2025_11_25, ProtocolVersion::V_2026_07_28]
);
}
#[test]
fn unsupported_protocol_version_error_matches_draft_schema() {
let error = ErrorData::unsupported_protocol_version(
ProtocolVersion::V_2026_07_28,
&[ProtocolVersion::V_2025_11_25],
);
assert_eq!(error.code, ErrorCode::UNSUPPORTED_PROTOCOL_VERSION);
assert_eq!(
error.data,
Some(json!({
"requested": "2026-07-28",
"supported": ["2025-11-25"]
}))
);
}
#[test]
fn missing_required_capability_error_matches_draft_schema() {
let required = ClientCapabilities::builder().enable_elicitation().build();
let error = ErrorData::missing_required_client_capability(required);
assert_eq!(error.code, ErrorCode::MISSING_REQUIRED_CLIENT_CAPABILITY);
assert_eq!(
error.data,
Some(json!({
"requiredCapabilities": {
"elicitation": {}
}
}))
);
}

View file

@ -0,0 +1,77 @@
#![cfg(all(feature = "client", not(feature = "local")))]
use rmcp::{
ClientHandler, ServerHandler, ServiceExt,
model::{
ClientCapabilities, Implementation, ProtocolVersion, RequestMetaObject, ServerCapabilities,
ServerInfo,
},
select_protocol_version,
};
#[derive(Clone, Default)]
struct DiscoveryServer;
impl ServerHandler for DiscoveryServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(Implementation::new("discovery-server", "1.0.0"))
}
}
#[derive(Clone, Default)]
struct DiscoveryClient;
impl ClientHandler for DiscoveryClient {}
#[test]
fn select_protocol_version_uses_client_preference_order() {
let selected = select_protocol_version(
&[ProtocolVersion::V_2026_07_28, ProtocolVersion::V_2025_11_25],
&[ProtocolVersion::V_2025_11_25, ProtocolVersion::V_2026_07_28],
);
assert_eq!(selected, Some(ProtocolVersion::V_2026_07_28));
}
#[test]
fn select_protocol_version_returns_none_without_overlap() {
let selected = select_protocol_version(
&[ProtocolVersion::V_2026_07_28],
&[ProtocolVersion::V_2025_11_25],
);
assert_eq!(selected, None);
}
#[tokio::test]
async fn client_discover_helper_returns_typed_result() {
let (server_transport, client_transport) = tokio::io::duplex(4096);
tokio::spawn(async move {
let _ = DiscoveryServer
.serve(server_transport)
.await
.expect("server should start")
.waiting()
.await;
});
let client = DiscoveryClient
.serve(client_transport)
.await
.expect("client should connect");
let mut meta = RequestMetaObject::new();
meta.set_protocol_version(ProtocolVersion::V_2026_07_28);
meta.set_client_info(Implementation::new("discovery-client", "1.0.0"));
meta.set_client_capabilities(ClientCapabilities::default());
let result = client
.discover(meta)
.await
.expect("discover should succeed");
assert_eq!(
result.server_info,
Implementation::new("discovery-server", "1.0.0")
);
client.cancel().await.expect("client should cancel");
}

View file

@ -0,0 +1,346 @@
#![cfg(all(
not(feature = "local"),
feature = "reqwest",
feature = "transport-streamable-http-server"
))]
use std::borrow::Cow;
use rmcp::{
ServerHandler,
model::{Implementation, ProtocolVersion, ServerCapabilities, ServerInfo},
transport::streamable_http_server::{
StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
},
};
use serde_json::json;
use tokio_util::sync::CancellationToken;
#[derive(Clone, Default)]
struct DiscoveryServer;
impl ServerHandler for DiscoveryServer {
fn get_info(&self) -> ServerInfo {
ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(Implementation::new("discovery-server", "1.0.0"))
.with_instructions("Use the tools carefully")
}
fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
Cow::Borrowed(&[ProtocolVersion::V_2025_11_25])
}
}
async fn spawn_server(json_response: bool) -> (reqwest::Client, String, CancellationToken) {
spawn_server_with_stateful_mode(json_response, false).await
}
async fn spawn_server_with_stateful_mode(
json_response: bool,
stateful_mode: bool,
) -> (reqwest::Client, String, CancellationToken) {
let cancellation_token = CancellationToken::new();
let config = StreamableHttpServerConfig::default()
.with_stateful_mode(stateful_mode)
.with_json_response(json_response)
.with_sse_keep_alive(None)
.with_cancellation_token(cancellation_token.clone());
let service: StreamableHttpService<DiscoveryServer, LocalSessionManager> =
StreamableHttpService::new(|| Ok(DiscoveryServer), Default::default(), config);
let router = axum::Router::new().nest_service("/mcp", service);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let address = listener.local_addr().expect("listener should have address");
tokio::spawn({
let cancellation_token = cancellation_token.clone();
async move {
let _ = axum::serve(listener, router)
.with_graceful_shutdown(async move {
cancellation_token.cancelled_owned().await;
})
.await;
}
});
(
reqwest::Client::new(),
format!("http://{address}/mcp"),
cancellation_token,
)
}
fn discover_body(version: Option<&str>) -> serde_json::Value {
let meta = version.map(|version| {
json!({
"io.modelcontextprotocol/protocolVersion": version,
"io.modelcontextprotocol/clientInfo": {
"name": "test-client",
"version": "1.0.0"
},
"io.modelcontextprotocol/clientCapabilities": {}
})
});
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "server/discover",
"params": meta.map(|meta| json!({ "_meta": meta })).unwrap_or_else(|| json!({}))
})
}
async fn post_discover(
client: &reqwest::Client,
url: &str,
header_version: &str,
body_version: Option<&str>,
) -> reqwest::Response {
client
.post(url)
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", header_version)
.header("Mcp-Method", "server/discover")
.json(&discover_body(body_version))
.send()
.await
.expect("discover request should send")
}
#[tokio::test]
async fn discover_returns_server_metadata_without_session() {
let (client, url, cancellation_token) = spawn_server(true).await;
let response = post_discover(&client, &url, "2025-11-25", Some("2025-11-25")).await;
assert_eq!(response.status(), 200);
let body: serde_json::Value = response.json().await.expect("response should be JSON");
assert_eq!(
body["result"],
json!({
"resultType": "complete",
"supportedVersions": ["2025-11-25"],
"capabilities": { "tools": {} },
"serverInfo": {
"name": "discovery-server",
"version": "1.0.0"
},
"instructions": "Use the tools carefully",
"ttlMs": 0,
"cacheScope": "private"
})
);
cancellation_token.cancel();
}
#[tokio::test]
async fn discover_does_not_require_initialization_in_stateful_mode() {
let (client, url, cancellation_token) = spawn_server_with_stateful_mode(true, true).await;
let response = post_discover(&client, &url, "2025-11-25", Some("2025-11-25")).await;
assert_eq!(response.status(), 200);
assert!(response.headers().get("Mcp-Session-Id").is_none());
cancellation_token.cancel();
}
#[tokio::test]
async fn discover_rejects_unsupported_version_with_http_400() {
let (client, url, cancellation_token) = spawn_server(true).await;
let response = post_discover(&client, &url, "2026-07-28", Some("2026-07-28")).await;
assert_eq!(response.status(), 400);
let body: serde_json::Value = response.json().await.expect("response should be JSON");
assert_eq!(body["error"]["code"], -32022);
assert_eq!(
body["error"]["data"],
json!({
"requested": "2026-07-28",
"supported": ["2025-11-25"]
})
);
cancellation_token.cancel();
}
#[tokio::test]
async fn discover_rejects_unknown_version_with_typed_error() {
let (client, url, cancellation_token) = spawn_server(true).await;
let response = post_discover(&client, &url, "2099-01-01", Some("2099-01-01")).await;
assert_eq!(response.status(), 400);
let body: serde_json::Value = response.json().await.expect("response should be JSON");
assert_eq!(body["error"]["code"], -32022);
cancellation_token.cancel();
}
#[tokio::test]
async fn regular_request_rejects_server_unsupported_meta_version() {
let (client, url, cancellation_token) = spawn_server(true).await;
let body = json!({
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28"
}
}
});
let response = client
.post(&url)
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", "2026-07-28")
.header("Mcp-Method", "tools/list")
.json(&body)
.send()
.await
.expect("request should send");
assert_eq!(response.status(), 400);
let body: serde_json::Value = response.json().await.expect("response should be JSON");
assert_eq!(body["error"]["code"], -32022);
cancellation_token.cancel();
}
#[tokio::test]
async fn unknown_rpc_uses_http_404_for_per_request_protocol() {
let (client, url, cancellation_token) = spawn_server(true).await;
let body = json!({
"jsonrpc": "2.0",
"id": 3,
"method": "unknown/method",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2025-11-25"
}
}
});
let response = client
.post(&url)
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", "2025-11-25")
.json(&body)
.send()
.await
.expect("request should send");
assert_eq!(response.status(), 404);
cancellation_token.cancel();
}
#[tokio::test]
async fn legacy_unknown_rpc_preserves_http_200_jsonrpc_error() {
let (client, url, cancellation_token) = spawn_server(true).await;
let body = json!({
"jsonrpc": "2.0",
"id": 5,
"method": "unknown/method",
"params": {}
});
let response = client
.post(&url)
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", "2025-11-25")
.json(&body)
.send()
.await
.expect("request should send");
assert_eq!(response.status(), 200);
let body: serde_json::Value = response.json().await.expect("response should be JSON");
assert_eq!(body["error"]["code"], -32601);
cancellation_token.cancel();
}
#[tokio::test]
async fn discover_rejects_header_meta_version_mismatch() {
let (client, url, cancellation_token) = spawn_server(true).await;
let response = post_discover(&client, &url, "2026-07-28", Some("2025-11-25")).await;
assert_eq!(response.status(), 400);
cancellation_token.cancel();
}
#[tokio::test]
async fn discover_rejects_missing_request_meta() {
let (client, url, cancellation_token) = spawn_server(true).await;
let response = post_discover(&client, &url, "2025-11-25", None).await;
assert_eq!(response.status(), 400);
let body: serde_json::Value = response.json().await.expect("response should be JSON");
assert_eq!(body["error"]["code"], -32602);
cancellation_token.cancel();
}
#[tokio::test]
async fn discover_rejects_missing_client_capabilities() {
let (client, url, cancellation_token) = spawn_server(true).await;
let body = json!({
"jsonrpc": "2.0",
"id": 4,
"method": "server/discover",
"params": {
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2025-11-25",
"io.modelcontextprotocol/clientInfo": {
"name": "test-client",
"version": "1.0.0"
}
}
}
});
let response = client
.post(&url)
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", "2025-11-25")
.json(&body)
.send()
.await
.expect("request should send");
assert_eq!(response.status(), 400);
let body: serde_json::Value = response.json().await.expect("response should be JSON");
assert_eq!(body["error"]["code"], -32602);
cancellation_token.cancel();
}
#[tokio::test]
async fn discover_error_uses_http_400_when_sse_is_configured() {
let (client, url, cancellation_token) = spawn_server(false).await;
let response = post_discover(&client, &url, "2026-07-28", Some("2026-07-28")).await;
assert_eq!(response.status(), 400);
assert_eq!(
response
.headers()
.get("Content-Type")
.and_then(|value| value.to_str().ok()),
Some("application/json")
);
cancellation_token.cancel();
}