Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8068fd7910 | ||
|
|
2f9c4cb568 | ||
|
|
61378224b2 |
No files matched your search
@@ -5,7 +5,7 @@
|
||||
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); it is called from
|
||||
//! `app/endpoint.rs`, so the entry points are `pub(super)`. No behaviour changed.
|
||||
|
||||
use super::request::{InitializeParams, ToolCallParams};
|
||||
use super::request::ToolCallParams;
|
||||
use super::response::take_confirmation_token;
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
@@ -777,7 +777,8 @@ pub(super) async fn handle_initialize(
|
||||
message: &Value,
|
||||
response_mode: ResponseMode,
|
||||
) -> Response {
|
||||
let initialize_params: InitializeParams = match serde_json::from_value(params(message)) {
|
||||
let raw_params = params(message);
|
||||
let initialize_params = match crate::protocol::initialize_params(&raw_params) {
|
||||
Ok(value) => value,
|
||||
Err(_error) => {
|
||||
return transport_response(
|
||||
@@ -789,7 +790,10 @@ pub(super) async fn handle_initialize(
|
||||
);
|
||||
}
|
||||
};
|
||||
let Some(protocol_version) = negotiated_protocol_version(&initialize_params.protocol_version)
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialize_input_consumed(&initialize_params);
|
||||
let Some(protocol_version) =
|
||||
negotiated_protocol_version(initialize_params.protocol_version.as_str())
|
||||
else {
|
||||
// A revision outside the approved window is rejected without minting a session and without
|
||||
// echoing any withdrawn revision as the served identity.
|
||||
@@ -810,9 +814,9 @@ pub(super) async fn handle_initialize(
|
||||
};
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
|
||||
let supports_elicitation = initialize_params
|
||||
.capabilities
|
||||
.get("elicitation")
|
||||
let supports_elicitation = raw_params
|
||||
.get("capabilities")
|
||||
.and_then(|capabilities| capabilities.get("elicitation"))
|
||||
.is_some_and(Value::is_object);
|
||||
let session_id = match state
|
||||
.sessions
|
||||
@@ -835,14 +839,7 @@ pub(super) async fn handle_initialize(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!( {
|
||||
"protocolVersion": protocol_version,
|
||||
"capabilities": crate::protocol::advertised_server_capabilities(protocol_version),
|
||||
"serverInfo": {
|
||||
"name": SERVER_NAME,
|
||||
"version": SERVER_VERSION
|
||||
}
|
||||
}),
|
||||
crate::protocol::initialize_result(protocol_version, SERVER_NAME, SERVER_VERSION),
|
||||
),
|
||||
response_mode,
|
||||
Some(&session_id),
|
||||
|
||||
@@ -73,9 +73,21 @@ pub(crate) struct CounterSet {
|
||||
sdk_signal_notification: AtomicUsize,
|
||||
sdk_jsonrpc_response: AtomicUsize,
|
||||
sdk_jsonrpc_error: AtomicUsize,
|
||||
sdk_initialize_input: AtomicUsize,
|
||||
sdk_initialize_result: AtomicUsize,
|
||||
sdk_discover_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
pub(crate) fn sdk_initialize_input(&self) -> usize {
|
||||
self.sdk_initialize_input.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_initialize_result(&self) -> usize {
|
||||
self.sdk_initialize_result.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_discover_result(&self) -> usize {
|
||||
self.sdk_discover_result.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_jsonrpc_response(&self) -> usize {
|
||||
self.sdk_jsonrpc_response.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -377,6 +389,27 @@ pub(crate) fn sdk_jsonrpc_error_serialized() {
|
||||
#[path = "../rmcp_envelopes_runtime_tests.rs"]
|
||||
mod rmcp_envelopes_runtime_tests;
|
||||
|
||||
/// Mark only after successfully serializing a real rmcp InitializeResult.
|
||||
pub(crate) fn sdk_initialize_result_serialized() {
|
||||
increment(|counters| &counters.sdk_initialize_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real rmcp DiscoverResult.
|
||||
pub(crate) fn sdk_discover_result_serialized() {
|
||||
increment(|counters| &counters.sdk_discover_result);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_lifecycle_negotiation_runtime_tests.rs"]
|
||||
mod rmcp_lifecycle_negotiation_runtime_tests;
|
||||
|
||||
/// Mark only where SDK protocol_version is consumed by initialize negotiation, not at DTO creation.
|
||||
pub(crate) fn sdk_initialize_input_consumed(_params: &rmcp::model::InitializeRequestParams) {
|
||||
increment(|counters| &counters.sdk_initialize_input);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_initialize_input_runtime_tests.rs"]
|
||||
mod rmcp_initialize_input_runtime_tests;
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
@@ -1,14 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct InitializeParams {
|
||||
#[serde(rename = "protocolVersion")]
|
||||
pub(super) protocol_version: String,
|
||||
#[serde(default)]
|
||||
pub(super) capabilities: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct ToolCallParams {
|
||||
pub(super) name: String,
|
||||
|
||||
@@ -122,6 +122,17 @@ pub(super) struct CountedSessionStore {
|
||||
counters: Arc<SessionCounters>,
|
||||
}
|
||||
|
||||
impl CountedSessionStore {
|
||||
pub(super) fn snapshot(&self) -> SessionOps {
|
||||
self.counters.snapshot()
|
||||
}
|
||||
|
||||
/// Inspect retained state without incrementing the HTTP request's session-read oracle.
|
||||
pub(super) async fn retained(&self, id: &str) -> Option<SessionState> {
|
||||
self.inner.get(id).await.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for CountedSessionStore {
|
||||
async fn create(
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Typed negotiation results; admission and session lifecycle remain in the HTTP adapter.
|
||||
|
||||
use rmcp::model::{
|
||||
CacheScope, DiscoverResult, Implementation, InitializeRequestParams, InitializeResult,
|
||||
ProtocolVersion, ServerCapabilities,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::advertised_server_capabilities;
|
||||
use crate::jsonrpc::SUPPORTED_PROTOCOL_VERSIONS;
|
||||
|
||||
pub(crate) fn initialize_params(
|
||||
params: &Value,
|
||||
) -> Result<InitializeRequestParams, serde_json::Error> {
|
||||
// Only protocolVersion was validated here; ignored client fields must not acquire SDK constraints.
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"protocolVersion": params.get("protocolVersion"),
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "", "version": ""}
|
||||
}))
|
||||
}
|
||||
|
||||
fn protocol_version(revision: &str) -> ProtocolVersion {
|
||||
serde_json::from_value(Value::String(revision.to_owned()))
|
||||
.expect("served protocol revisions are strings")
|
||||
}
|
||||
|
||||
fn capabilities(advertised: &Value) -> ServerCapabilities {
|
||||
serde_json::from_value(advertised.clone())
|
||||
.expect("registry capability fragments match SDK capability shapes")
|
||||
}
|
||||
|
||||
fn restore_registry_extensions(result: &mut Value, advertised: Value) {
|
||||
let capabilities = result["capabilities"]
|
||||
.as_object_mut()
|
||||
.expect("SDK server capabilities serialize as an object");
|
||||
// SDK ServerCapabilities has no flattened map for extra registry capability names.
|
||||
for (name, settings) in advertised
|
||||
.as_object()
|
||||
.expect("registry capabilities are an object")
|
||||
{
|
||||
capabilities
|
||||
.entry(name.clone())
|
||||
.or_insert_with(|| settings.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn initialize_result(revision: &str, name: &str, version: &str) -> Value {
|
||||
let advertised = advertised_server_capabilities(revision);
|
||||
let result = InitializeResult::new(capabilities(&advertised))
|
||||
.with_protocol_version(protocol_version(revision))
|
||||
.with_server_info(Implementation::new(name, version));
|
||||
let mut result = serde_json::to_value(result)
|
||||
.expect("SDK initialize result with registry capabilities is serializable");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_initialize_result_serialized();
|
||||
restore_registry_extensions(&mut result, advertised);
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn discover_result(revision: &str, name: &str, version: &str) -> Value {
|
||||
let advertised = advertised_server_capabilities(revision);
|
||||
let result = DiscoverResult::new(
|
||||
SUPPORTED_PROTOCOL_VERSIONS
|
||||
.iter()
|
||||
.map(|revision| protocol_version(revision))
|
||||
.collect(),
|
||||
capabilities(&advertised),
|
||||
)
|
||||
.with_server_info(Implementation::new(name, version))
|
||||
.with_ttl_ms(0)
|
||||
.with_cache_scope(CacheScope::Private);
|
||||
let mut result = serde_json::to_value(result)
|
||||
.expect("SDK discovery result with registry capabilities is serializable");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_discover_result_serialized();
|
||||
restore_registry_extensions(&mut result, advertised);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn lifecycle_sdk_retains_extra_registry_capabilities_without_replacing_sdk_fields() {
|
||||
let advertised =
|
||||
json!({"tools":{"listChanged":false}, "inert_test_capability":{"enabled":true}});
|
||||
let mut result = serde_json::to_value(InitializeResult::new(capabilities(&advertised)))
|
||||
.expect("typed result serializes");
|
||||
assert_eq!(
|
||||
result["capabilities"],
|
||||
json!({"tools":{"listChanged":false}})
|
||||
);
|
||||
restore_registry_extensions(&mut result, advertised.clone());
|
||||
assert_eq!(result["capabilities"], advertised);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ use crate::transport::{json_response, protocol_version_from_headers, singleton_h
|
||||
|
||||
mod command;
|
||||
mod completion;
|
||||
mod lifecycle_sdk;
|
||||
mod logging;
|
||||
mod prompts;
|
||||
mod registry;
|
||||
@@ -40,6 +41,7 @@ pub(crate) use completion::{
|
||||
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
||||
handle_completion_command,
|
||||
};
|
||||
pub(crate) use lifecycle_sdk::{discover_result, initialize_params, initialize_result};
|
||||
pub(crate) use logging::{
|
||||
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
||||
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
|
||||
@@ -844,20 +846,3 @@ pub(crate) fn resolve_request_identity(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pinned `DiscoverResult` for `server/discover` of the revision the caller serves.
|
||||
pub(crate) fn discover_result(revision: &str, server_name: &str, server_version: &str) -> Value {
|
||||
json!({
|
||||
"resultType": "complete",
|
||||
"supportedVersions": SUPPORTED_PROTOCOL_VERSIONS,
|
||||
"capabilities": advertised_server_capabilities(revision),
|
||||
"_meta": {
|
||||
crate::jsonrpc::META_SERVER_INFO_KEY: {
|
||||
"name": server_name,
|
||||
"version": server_version,
|
||||
}
|
||||
},
|
||||
"ttlMs": 0,
|
||||
"cacheScope": "private"
|
||||
})
|
||||
}
|
||||
@@ -1,28 +1,11 @@
|
||||
//! #107 envelope migration: independent real HTTP wire and SDK participation controls.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
use axum::{body::Body, response::Response};
|
||||
use futures_util::{StreamExt, stream};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
// Reuse the existing real build_app, published catalog, auth and loopback execution fixture.
|
||||
#[path = "rmcp_progress_cancel_http_support.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod fixtures;
|
||||
use fixtures::Endpoint;
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
(body.into_data_stream(), counters),
|
||||
|(mut body, counters)| async move {
|
||||
observe(counters.clone(), body.next())
|
||||
.await
|
||||
.map(|chunk| (chunk, (body, counters)))
|
||||
},
|
||||
);
|
||||
Response::from_parts(parts, Body::from_stream(body))
|
||||
}
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
|
||||
fn counts(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_jsonrpc_response(), c.sdk_jsonrpc_error()]
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
//! #107 initialize input: existing wire tolerance GREEN, independent SDK-consumption RED.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
const ACCEPTS: [&str; 2] = ["application/json", "text/event-stream, application/json"];
|
||||
const TRACE: &str = "11111111111111111111111111111111";
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("initialize_input_owner", "t_ffc30fcd").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
async fn post(h: &Endpoint, params: Option<Value>, accept: &str) -> reqwest::Response {
|
||||
let mut payload = json!({"jsonrpc":"2.0","id":"initialize/Ю","method":"initialize"});
|
||||
if let Some(params) = params {
|
||||
payload["params"] = params;
|
||||
}
|
||||
h.request(LEGACY_REVISION, None, &h.key, accept, payload)
|
||||
.header("x-request-id", "initialize-input")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn body(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.headers()["x-request-id"], "initialize-input");
|
||||
assert_eq!(response.headers()["x-trace-id"], TRACE);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
})
|
||||
);
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data:"))
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "exactly one terminal SSE frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_shapes() -> Vec<(&'static str, Value, bool)> {
|
||||
let mut cases = vec![(
|
||||
"capabilities omitted",
|
||||
json!({"protocolVersion":LEGACY_REVISION}),
|
||||
false,
|
||||
)];
|
||||
for (name, caps, elicitation) in [
|
||||
("null capabilities", Value::Null, false),
|
||||
("boolean capabilities", json!(true), false),
|
||||
("number capabilities", json!(7), false),
|
||||
("string capabilities", json!("caps"), false),
|
||||
("array capabilities", json!([{"elicitation":{}}]), false),
|
||||
("empty capabilities", json!({}), false),
|
||||
("null elicitation", json!({"elicitation":null}), false),
|
||||
("boolean elicitation", json!({"elicitation":true}), false),
|
||||
("number elicitation", json!({"elicitation":1}), false),
|
||||
("string elicitation", json!({"elicitation":"yes"}), false),
|
||||
("array elicitation", json!({"elicitation":[]}), false),
|
||||
("empty elicitation object", json!({"elicitation":{}}), true),
|
||||
(
|
||||
"extended elicitation",
|
||||
json!({"elicitation":{"form":{},"future":42},"future":[1]}),
|
||||
true,
|
||||
),
|
||||
] {
|
||||
cases.push((
|
||||
name,
|
||||
json!({"protocolVersion":LEGACY_REVISION,"capabilities":caps}),
|
||||
elicitation,
|
||||
));
|
||||
}
|
||||
for info in [
|
||||
Value::Null,
|
||||
json!(42),
|
||||
json!([]),
|
||||
json!({"name":false,"version":null}),
|
||||
json!({"name":"client","version":"1","future":true}),
|
||||
] {
|
||||
cases.push((
|
||||
"ignored clientInfo and extensions",
|
||||
json!({"protocolVersion":LEGACY_REVISION,
|
||||
"clientInfo":info,"unknown":{"nested":[null,1]},"_meta":{"future":true}}),
|
||||
false,
|
||||
));
|
||||
}
|
||||
cases
|
||||
}
|
||||
|
||||
async fn valid_control() -> Vec<usize> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for accept in ACCEPTS {
|
||||
for (name, params, elicitation) in valid_shapes() {
|
||||
let ops = h.sessions.snapshot();
|
||||
let admission = h.counters.snapshot();
|
||||
let sdk = h.counters.sdk_initialize_input();
|
||||
let response = post(&h, Some(params), accept).await;
|
||||
assert_eq!(response.status(), 200, "{name}");
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
let id = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert!(!id.is_empty());
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["jsonrpc"], "2.0");
|
||||
assert_eq!(wire["id"], "initialize/Ю");
|
||||
assert_eq!(wire["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
assert!(wire.get("error").is_none());
|
||||
assert_deltas(
|
||||
name,
|
||||
admission,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
assert_session_ops(
|
||||
name,
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 1,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
let state = h
|
||||
.sessions
|
||||
.retained(&id)
|
||||
.await
|
||||
.expect("retained session, not a discarded DTO");
|
||||
assert_eq!(state.id, id);
|
||||
assert_eq!(state.protocol_version, LEGACY_REVISION);
|
||||
assert_eq!(state.workspace_slug, WORKSPACE_SLUG);
|
||||
assert_eq!(state.agent_slug, AGENT_SLUG);
|
||||
assert_eq!(state.supports_elicitation, elicitation, "{name}");
|
||||
assert!(!state.initialized);
|
||||
assert_eq!(state.updated_at, state.created_at);
|
||||
assert_eq!(
|
||||
(state.expires_at.unwrap() - state.created_at).whole_milliseconds(),
|
||||
86_400_000
|
||||
);
|
||||
deltas.push(h.counters.sdk_initialize_input() - sdk);
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert!(h.sessions.retained(&id).await.unwrap().initialized);
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let result = json_body(response).await;
|
||||
assert!(
|
||||
result.get("error").is_none(),
|
||||
"initialized opens a protected request: {result}"
|
||||
);
|
||||
assert_eq!(result["result"]["tools"][0]["name"], TOOL_NAME);
|
||||
eprintln!("existing GREEN {name}; accept={accept}; elicitation={elicitation}");
|
||||
}
|
||||
}
|
||||
eprintln!("SDK input consumption deltas={deltas:?}");
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_wire_tolerance_and_retained_sessions() {
|
||||
valid_control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_sdk_consumed_by_negotiation() {
|
||||
let deltas = valid_control().await;
|
||||
assert!(!deltas.is_empty());
|
||||
assert_eq!(
|
||||
deltas,
|
||||
vec![1; valid_shapes().len() * ACCEPTS.len()],
|
||||
"real HTTP initialize must consume SDK InitializeRequestParams.protocol_version in negotiation"
|
||||
);
|
||||
}
|
||||
|
||||
// Current HTTP envelope admission rejects sequence params before serde's derived struct decoder.
|
||||
// Pin that observed boundary instead of imposing a new object-only check in the SDK decoder.
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_wire_invalid_shapes_and_admission() {
|
||||
let h = endpoint().await;
|
||||
for accept in ACCEPTS {
|
||||
for params in [
|
||||
None,
|
||||
Some(json!({})),
|
||||
Some(json!({"protocolVersion":null})),
|
||||
Some(json!({"protocolVersion":true})),
|
||||
Some(json!({"protocolVersion":42})),
|
||||
Some(json!({"protocolVersion":[]})),
|
||||
Some(json!({"protocolVersion":{}})),
|
||||
] {
|
||||
rejection(
|
||||
&h,
|
||||
params,
|
||||
accept,
|
||||
200,
|
||||
-32602,
|
||||
"invalid initialize parameters",
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
for params in [
|
||||
json!(null),
|
||||
json!(true),
|
||||
json!(42),
|
||||
json!("bad"),
|
||||
json!([]),
|
||||
json!([LEGACY_REVISION]),
|
||||
json!([LEGACY_REVISION, {}]),
|
||||
json!([LEGACY_REVISION, {}, {}]),
|
||||
] {
|
||||
rejection(
|
||||
&h,
|
||||
Some(params),
|
||||
accept,
|
||||
400,
|
||||
-32600,
|
||||
"invalid JSON-RPC request",
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
for version in ["2025-03-26", "2025-06-18", "2099-01-01", ""] {
|
||||
rejection(
|
||||
&h,
|
||||
Some(json!({"protocolVersion":version})),
|
||||
accept,
|
||||
400,
|
||||
-32602,
|
||||
&format!("unsupported protocol version {version}"),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
for meta in [Value::Null, json!(true), json!(42), json!("bad"), json!([])] {
|
||||
rejection(
|
||||
&h,
|
||||
Some(json!({"protocolVersion":LEGACY_REVISION,"_meta":meta})),
|
||||
accept,
|
||||
400,
|
||||
-32020,
|
||||
"protocol identity mismatch",
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn rejection(
|
||||
h: &Endpoint,
|
||||
params: Option<Value>,
|
||||
accept: &str,
|
||||
status: u16,
|
||||
code: i64,
|
||||
message: &str,
|
||||
admission_only: bool,
|
||||
) {
|
||||
let ops = h.sessions.snapshot();
|
||||
let admission = h.counters.snapshot();
|
||||
let sdk = h.counters.sdk_initialize_input();
|
||||
let response = post(h, params.clone(), accept).await;
|
||||
assert_eq!(response.status().as_u16(), status, "params={params:?}");
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
// Only HTTP 200 dispatch errors use SSE; HTTP 400 stays JSON regardless of Accept.
|
||||
let sse = status == 200 && !admission_only && accept.starts_with("text/event-stream");
|
||||
let wire = body(response, sse).await;
|
||||
assert_eq!(wire["jsonrpc"], "2.0");
|
||||
assert_eq!(
|
||||
wire["id"],
|
||||
if code == -32600 {
|
||||
Value::Null
|
||||
} else {
|
||||
json!("initialize/Ю")
|
||||
}
|
||||
);
|
||||
assert_eq!(wire["error"]["code"], code, "params={params:?}; {wire}");
|
||||
assert_eq!(wire["error"]["message"], message);
|
||||
assert!(wire.get("result").is_none());
|
||||
// Initialize errors are constructed in the request scope, including terminal SSE errors.
|
||||
assert_eq!(wire["error"]["data"]["request_id"], "initialize-input");
|
||||
assert_eq!(wire["error"]["data"]["trace_id"], TRACE);
|
||||
if code == -32020 {
|
||||
assert_eq!(
|
||||
wire["error"]["data"]["details"],
|
||||
"request _meta must be an object"
|
||||
);
|
||||
}
|
||||
assert_deltas(
|
||||
"reject",
|
||||
admission,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(1, 0, usize::from(!admission_only), 0),
|
||||
);
|
||||
assert_session_ops(
|
||||
"reject",
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
if !message.starts_with("unsupported protocol version") {
|
||||
assert_eq!(
|
||||
h.counters.sdk_initialize_input(),
|
||||
sdk,
|
||||
"malformed input never reaches SDK consumption"
|
||||
);
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN reject params={params:?}; accept={accept}; status={status}; code={code}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_sdk_unsupported_revision_uses_same_allowlist() {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for accept in ACCEPTS {
|
||||
for version in ["2025-03-26", "2025-06-18", "2099-01-01", ""] {
|
||||
let sdk = h.counters.sdk_initialize_input();
|
||||
rejection(
|
||||
&h,
|
||||
Some(json!({"protocolVersion":version})),
|
||||
accept,
|
||||
400,
|
||||
-32602,
|
||||
&format!("unsupported protocol version {version}"),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
deltas.push(h.counters.sdk_initialize_input() - sdk);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
deltas,
|
||||
vec![1; 8],
|
||||
"unsupported strings must reach the same SDK-backed negotiation, without minting sessions"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_initialize_input_observer_positive_control() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
let params: rmcp::model::InitializeRequestParams = serde_json::from_value(json!({
|
||||
"protocolVersion":LEGACY_REVISION,"capabilities":{},"clientInfo":{"name":"control","version":"1"}
|
||||
})).unwrap();
|
||||
observe(c.clone(), async {
|
||||
super::admission_enter();
|
||||
super::sdk_initialize_input_consumed(¶ms);
|
||||
assert_eq!(c.sdk_initialize_input(), 1);
|
||||
assert_eq!(
|
||||
c.sdk_initialize_result(),
|
||||
0,
|
||||
"input and output are independent"
|
||||
);
|
||||
})
|
||||
.await;
|
||||
assert_eq!(c.snapshot(), Snapshot::new(1, 0, 0, 0));
|
||||
super::sdk_initialize_input_consumed(¶ms);
|
||||
assert_eq!(c.sdk_initialize_input(), 1, "out-of-scope call is a no-op");
|
||||
observe(Arc::new(CounterSet::default()), async {
|
||||
super::sdk_initialize_input_consumed(¶ms);
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
c.sdk_initialize_input(),
|
||||
1,
|
||||
"another request scope is isolated"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! #107 negotiation results: existing HTTP wire GREEN, independent SDK execution oracle RED.
|
||||
use super::{CounterSet, observe, support::*};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
|
||||
fn sdk_counts(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_initialize_result(), c.sdk_discover_result()]
|
||||
}
|
||||
|
||||
fn capabilities() -> Value {
|
||||
// Pin the reviewed advertisement, not a call to the builder under test or SDK defaults.
|
||||
json!({"completions":{},"logging":{},"prompts":{"listChanged":true},
|
||||
"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}})
|
||||
}
|
||||
|
||||
fn expected_result(revision: &str) -> Value {
|
||||
let server = json!({"name":"crank-mcp-server","version":env!("CARGO_PKG_VERSION")});
|
||||
if revision == LEGACY_REVISION {
|
||||
json!({"protocolVersion":LEGACY_REVISION,"capabilities":capabilities(),"serverInfo":server})
|
||||
} else {
|
||||
json!({"resultType":"complete","supportedVersions":["2026-07-28","2025-11-25"],
|
||||
"capabilities":capabilities(),"_meta":{"io.modelcontextprotocol/serverInfo":server},
|
||||
"ttlMs":0,"cacheScope":"private"})
|
||||
}
|
||||
}
|
||||
|
||||
async fn wire(response: reqwest::Response, revision: &str, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert_eq!(response.headers()["x-request-id"], "negotiation-request");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
let content_type = response.headers()["content-type"].to_str().unwrap();
|
||||
assert!(content_type.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
}));
|
||||
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let body: Value = if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("data:"))
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
frames.len(),
|
||||
1,
|
||||
"one terminal, no unsolicited notifications: {raw}"
|
||||
);
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
body,
|
||||
json!({"jsonrpc":"2.0","id":id,"result":expected_result(revision)}),
|
||||
"exact result/envelope fields and omissions (including title/icons/instructions/defaults)"
|
||||
);
|
||||
body
|
||||
}
|
||||
|
||||
async fn control(revision: &str) -> Vec<[usize; 2]> {
|
||||
crank_test_support::postgres_schema_url_for_task("negotiation_owner", "t_99aa603c").await;
|
||||
let h = Endpoint::started().await;
|
||||
let mut deltas = vec![];
|
||||
// Accept order selects JSON or a single terminal SSE frame on the real transport.
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
let id = json!("negotiation/Ю");
|
||||
let payload = if revision == LEGACY_REVISION {
|
||||
let mut initialize = legacy_initialize(1);
|
||||
initialize["id"] = id.clone();
|
||||
initialize
|
||||
} else {
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"server/discover","params":{"_meta":modern_meta()}})
|
||||
};
|
||||
let before = sdk_counts(&h.counters);
|
||||
let admission_before = h.counters.snapshot();
|
||||
let response = h
|
||||
.request(revision, None, &h.key, accept, payload)
|
||||
.header("x-request-id", "negotiation-request")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let session = response
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.map(|v| v.to_str().unwrap().to_owned());
|
||||
if revision == LEGACY_REVISION {
|
||||
assert!(
|
||||
!session
|
||||
.as_deref()
|
||||
.expect("initialize creates a session")
|
||||
.is_empty()
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
session, None,
|
||||
"stateless discovery never creates a session carrier"
|
||||
);
|
||||
}
|
||||
wire(
|
||||
response,
|
||||
revision,
|
||||
&id,
|
||||
accept.starts_with("text/event-stream"),
|
||||
)
|
||||
.await;
|
||||
assert_deltas(
|
||||
"negotiation admission positive control",
|
||||
admission_before,
|
||||
h.counters.snapshot(),
|
||||
if revision == LEGACY_REVISION {
|
||||
super::Snapshot::new(1, 0, 1, 0)
|
||||
} else {
|
||||
super::Snapshot::new(1, 1, 0, 0)
|
||||
},
|
||||
);
|
||||
let after = sdk_counts(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
if let Some(session) = session {
|
||||
let response = h
|
||||
.request(
|
||||
revision,
|
||||
Some(&session),
|
||||
&h.key,
|
||||
accept,
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
// Prove the minted session can authorize the next protected request.
|
||||
let response = h
|
||||
.request(
|
||||
revision,
|
||||
Some(&session),
|
||||
&h.key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","id":2,"method":"ping"}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(
|
||||
json_body(response).await,
|
||||
json!({"jsonrpc":"2.0","id":2,"result":{"protocolVersion":LEGACY_REVISION}})
|
||||
);
|
||||
}
|
||||
}
|
||||
eprintln!("existing GREEN lifecycle negotiation wire {revision}; SDK deltas={deltas:?}");
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_sdk_legacy() {
|
||||
assert_eq!(
|
||||
control(LEGACY_REVISION).await,
|
||||
vec![[1, 0]; 2],
|
||||
"real HTTP initialize must serialize SDK InitializeResult (not admission/envelope only)"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_sdk_modern() {
|
||||
assert_eq!(
|
||||
control(MODERN_REVISION).await,
|
||||
vec![[0, 1]; 2],
|
||||
"real HTTP discovery must serialize SDK DiscoverResult (not admission/envelope only)"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_observer_positive_control() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
observe(c.clone(), async {
|
||||
super::admission_enter();
|
||||
super::sdk_initialize_result_serialized();
|
||||
assert_eq!(
|
||||
sdk_counts(&c),
|
||||
[1, 0],
|
||||
"initialize and discovery are separate markers"
|
||||
);
|
||||
super::sdk_discover_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(sdk_counts(&c), [1, 1]);
|
||||
assert_eq!(c.snapshot(), super::Snapshot::new(1, 0, 0, 0));
|
||||
super::sdk_initialize_result_serialized();
|
||||
super::sdk_discover_result_serialized();
|
||||
assert_eq!(sdk_counts(&c), [1, 1], "out-of-scope markers are no-ops");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_lifecycle_negotiation_wire_session_operations() {
|
||||
crank_test_support::postgres_schema_url_for_task("negotiation_sessions_owner", "t_99aa603c")
|
||||
.await;
|
||||
let h = Harness::started().await;
|
||||
// Existing counted-session fixture supplies independent get/create/initialized oracles.
|
||||
run_valid_legacy_initialize(&h, 10, "legacy create exactly once").await;
|
||||
let session = h.initialize_legacy_session().await;
|
||||
run_valid_legacy_call(
|
||||
&h,
|
||||
&session,
|
||||
11,
|
||||
"negotiation@example.test",
|
||||
"initialized session works",
|
||||
)
|
||||
.await;
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
let before = h.session_ops();
|
||||
let admission_before = h.snapshot();
|
||||
let response = h
|
||||
.post(
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "server/discover"),
|
||||
("Accept", accept),
|
||||
("x-request-id", "negotiation-request"),
|
||||
(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
),
|
||||
],
|
||||
&json!({"jsonrpc":"2.0","id":"discovery","method":"server/discover",
|
||||
"params":{"_meta":modern_meta()}}),
|
||||
)
|
||||
.await;
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
wire(response, MODERN_REVISION, &json!("discovery"), false).await;
|
||||
assert_deltas(
|
||||
"modern discovery",
|
||||
admission_before,
|
||||
h.snapshot(),
|
||||
super::Snapshot::new(1, 1, 0, 0),
|
||||
);
|
||||
assert_session_ops(
|
||||
"stateless discovery",
|
||||
before,
|
||||
h.session_ops(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,10 @@ use crank_runtime::{
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub(in crate::app::dispatch_observer) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub sessions: Arc<CountedSessionStore>,
|
||||
pub key: String,
|
||||
pub other_key: String,
|
||||
pub gate: Arc<Semaphore>,
|
||||
@@ -90,6 +91,7 @@ impl Endpoint {
|
||||
.await
|
||||
.unwrap();
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let sessions = Arc::new(CountedSessionStore::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
@@ -101,7 +103,7 @@ impl Endpoint {
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
sessions.clone(),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let scope = counters.clone();
|
||||
@@ -125,6 +127,7 @@ impl Endpoint {
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
sessions,
|
||||
key,
|
||||
other_key,
|
||||
gate,
|
||||
|
||||
@@ -5,7 +5,7 @@ use futures_util::{StreamExt, stream};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_progress_cancel_http_support.rs"]
|
||||
mod fixtures;
|
||||
pub(super) mod fixtures;
|
||||
use fixtures::Endpoint;
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
|
||||
@@ -47,6 +47,8 @@ Catalog-change signals/subscriptions-срез #107 на базе rc.24/rmcp3.9.0
|
||||
|
||||
Envelopes-срез #107 на базе rc.25/rmcp3.9.0 заменяет handwritten `jsonrpc_result`/`jsonrpc_error` в `jsonrpc.rs` сериализацией настоящих `JsonRpcResponse<Value>` и `JsonRpcError`/`ErrorData`. Уже подключённые consumers — общий `build_app` HTTP JSON и lifecycle SSE terminal обеих revisions; новые dispatch/transport пути не добавляются. Локальная projection+restore сразу возвращает исходные JSON id (включая null, u64 и точную floating-point форму) и i64 error code, которые SDK-типы не представляют полностью; произвольный result и omission error.data сохраняются. Прежний guard correlation не меняется: JSON protocol errors содержат correlation data, lifecycle SSE terminal errors по-прежнему её опускают. Runtime wire controls и отдельный SDK oracle проверяют success/protocol error, а affected regressions — admission, revoked credentials, tool isError и cancellation. Входная валидация, safe response id, auth, статусы/headers, очереди/сессии и transport остаются прежними; это не завершение #107, feature qualification или production deployment.
|
||||
|
||||
Negotiation-results-срез #107 на базе rc.26/rmcp3.9.0 заменяет handwritten ответы legacy `initialize` и modern `server/discover` на настоящие `InitializeResult`/`DiscoverResult` в `protocol/lifecycle_sdk.rs`. Уже подключённый потребитель — штатный `build_app` HTTP JSON/SSE. Версии и их порядок заданы прежним allowlist, capabilities поступают только из registry; server identity, omissions и discovery ttlMs=0/cacheScope=private сохранены. SDK `ServerCapabilities` не представляет дополнительные top-level имена registry: после typed serialization восстанавливаются только отсутствующие ключи, без замены SDK-known полей. HTTP ATDD отдельно проверяет прежний wire и SDK execution, legacy initialize→initialized→защищённый вызов и отсутствие session operations у modern discovery; affected regression сохраняет frozen advertisement, unsupported revision rejection, auth/revocation/Agent scope и legacy transport lifecycle. Следующий initialize-input-срез на базе rc.27 заменяет `app/request.rs::InitializeParams` декодированием настоящего `InitializeRequestParams` в `protocol/lifecycle_sdk.rs`: штатный `handle_initialize` использует SDK `protocol_version` в прежнем allowlist. Локальная projection передаёт только protocolVersion с инертными обязательными SDK capabilities/clientInfo; исходные ignored clientInfo/extensions не валидируются, а raw capabilities сохраняют прежний object-предикат elicitation. HTTP admission (включая запрет sequence params и malformed _meta) остаётся до SDK. Отдельный typed runtime oracle и JSON/SSE tolerance/session ATDD подтверждают использование результата SDK, отсутствие новых отказов и прежний initialize→initialized→защищённый вызов. Generic dispatch/ping, session storage/TTL/reconnect, admission/auth и transport не переносились. Существующий SSE error.data omission не исправляется; полный #107, feature qualification и production deployment не завершены.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
||||
|
||||
Reference in new issue
Block a user