Compare commits

...
Author SHA1 Message Date
bsodfather 8068fd7910 refactor(mcp): parse legacy initialize protocol version through SDK
CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Successful in 31m1s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
2026-11-12 13:43:04 +00:00
bsodfather 2f9c4cb568 refactor(mcp): serialize negotiation results through rmcp SDK
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 31m21s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 2s
CI / Deploy (pull_request) Skipped
2026-11-12 10:48:24 +00:00
bsodfather 61378224b2 Merge pull request 'MCP: SDK success/error envelopes with preserved wire contract' (#129) from delivery/rmcp107-envelopes into main
CI / UI Checks (push) Successful in 9s
CI / Rust Checks (push) Successful in 30m11s
CI / Rust Feature Validation (push) Skipped
CI / Frontend E2E (push) Skipped
CI / Community Image Smoke (push) Skipped
CI / Required Checks (push) Successful in 1s
CI / Deploy (push) Skipped
Community Release / release (push) Successful in 50m47s
2026-11-12 08:23:58 +00:00
bsodfather 1b51d44121 refactor(mcp): serialize success and error envelopes through SDK
CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Successful in 30m13s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
2026-11-12 07:52:03 +00:00
13 changed files with 1329 additions and 59 deletions

No files matched your search

+11 -14
View File
@@ -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),
@@ -71,9 +71,29 @@ pub(crate) struct CounterSet {
sdk_subscriptions_listen: AtomicUsize,
sdk_subscriptions_acknowledged: AtomicUsize,
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)
}
pub(crate) fn sdk_jsonrpc_error(&self) -> usize {
self.sdk_jsonrpc_error.load(Ordering::SeqCst)
}
pub(crate) fn sdk_subscriptions_listen(&self) -> usize {
self.sdk_subscriptions_listen.load(Ordering::SeqCst)
}
@@ -356,6 +376,40 @@ pub(crate) fn sdk_signal_notification_serialized() {
#[path = "../rmcp_signals_runtime_tests.rs"]
mod rmcp_signals_runtime_tests;
/// Mark only immediately after successfully serializing a real SDK JsonRpcResponse.
pub(crate) fn sdk_jsonrpc_response_serialized() {
increment(|counters| &counters.sdk_jsonrpc_response);
}
/// Mark only immediately after successfully serializing a real SDK JsonRpcError.
pub(crate) fn sdk_jsonrpc_error_serialized() {
increment(|counters| &counters.sdk_jsonrpc_error);
}
#[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(
+125 -17
View File
@@ -1,3 +1,6 @@
use rmcp::model::{
ErrorCode, ErrorData, JsonRpcError, JsonRpcResponse, JsonRpcVersion2_0, RequestId,
};
use serde_json::{Value, json};
/// The two approved MCP revisions (`docs/`-approved window of 2026-10-11).
@@ -60,28 +63,50 @@ pub fn is_response(message: &Value) -> bool {
&& (message.get("result").is_some() || message.get("error").is_some())
}
fn projected_sdk_id(id: &Value) -> RequestId {
match id {
Value::String(value) => RequestId::String(value.as_str().into()),
Value::Number(value) => RequestId::Number(value.as_i64().unwrap_or(0)),
_ => RequestId::Number(0),
}
}
pub fn jsonrpc_result(id: Value, result: Value) -> Value {
json!({
"jsonrpc": "2.0",
"id": id,
"result": result
})
let sdk = JsonRpcResponse::<Value> {
jsonrpc: JsonRpcVersion2_0,
id: projected_sdk_id(&id),
result,
};
let mut wire = serde_json::to_value(sdk).expect("SDK response contains only JSON values");
#[cfg(test)]
crate::app::dispatch_observer::sdk_jsonrpc_response_serialized();
// SDK RequestId cannot preserve the full Value domain or floating-point form.
wire["id"] = id;
wire
}
pub fn jsonrpc_error(id: Value, code: i64, message: impl Into<String>) -> Value {
let mut error = json!({
"code": code,
"message": message.into()
});
let (request_id, trace_id) = crank_observability::current_request_correlation();
if request_id.is_some() && trace_id.is_some() {
error["data"] = correlated_error_data(json!({}));
}
json!({
"jsonrpc": "2.0",
"id": id,
"error": error
})
let data = if request_id.is_some() && trace_id.is_some() {
Some(correlated_error_data(json!({})))
} else {
None
};
let sdk = JsonRpcError::new(
Some(projected_sdk_id(&id)),
ErrorData::new(
ErrorCode(i32::try_from(code).unwrap_or(0)),
message.into(),
data,
),
);
let mut wire = serde_json::to_value(sdk).expect("SDK error contains only JSON values");
#[cfg(test)]
crate::app::dispatch_observer::sdk_jsonrpc_error_serialized();
// Restore the helper's wider id/code contract before exposing the SDK envelope.
wire["id"] = id;
wire["error"]["code"] = Value::from(code);
wire
}
pub fn correlated_error_data(mut data: Value) -> Value {
@@ -104,3 +129,86 @@ pub fn negotiated_protocol_version(requested: &str) -> Option<&'static str> {
.copied()
.find(|version| *version == requested)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jsonrpc_preserves_helper_values_and_numeric_forms() {
let values = [
json!(""),
json!("Юникод"),
json!(i64::MIN),
json!(i64::MAX),
json!(9007199254740993_u64),
json!(u64::MAX),
json!(1.5),
json!(1.0),
json!(-0.0),
Value::Null,
json!(true),
json!([null, u64::MAX]),
json!({"extension": {"nested": null}}),
];
for id in &values {
for result in &values {
let actual = jsonrpc_result(id.clone(), result.clone());
let expected = json!({"jsonrpc": "2.0", "id": id, "result": result});
assert_eq!(actual, expected);
assert_eq!(actual.to_string(), expected.to_string());
}
for code in [
i64::MIN,
i64::from(i32::MIN) - 1,
i64::from(i32::MIN),
-32602,
0,
i64::from(i32::MAX),
i64::from(i32::MAX) + 1,
i64::MAX,
] {
for message in ["", "Ошибка Ю"] {
let actual = jsonrpc_error(id.clone(), code, message);
let expected = json!({"jsonrpc": "2.0", "id": id,
"error": {"code": code, "message": message}});
assert_eq!(actual, expected);
assert_eq!(actual.to_string(), expected.to_string());
}
}
}
}
#[tokio::test]
async fn jsonrpc_error_requires_complete_valid_correlation() {
use crank_observability::{current_request_correlation, with_request_correlation};
let request_id = "request-123";
let trace_id = "1234567890abcdef1234567890abcdef";
for (request, trace) in [("", ""), (request_id, ""), ("", trace_id)] {
with_request_correlation(request.into(), trace.into(), async {
assert_eq!(current_request_correlation(), (None, None));
assert_eq!(
jsonrpc_error(Value::Null, -32602, "error"),
json!({"jsonrpc": "2.0", "id": null,
"error": {"code": -32602, "message": "error"}})
);
})
.await;
}
with_request_correlation(request_id.into(), trace_id.into(), async {
assert_eq!(
jsonrpc_error(Value::Null, i64::MAX, "Ошибка"),
json!({"jsonrpc": "2.0", "id": null, "error": {
"code": i64::MAX, "message": "Ошибка",
"data": {"request_id": request_id, "trace_id": trace_id}}})
);
assert_eq!(
correlated_error_data(json!({"extension": [null, u64::MAX]})),
json!({"extension": [null, u64::MAX],
"request_id": request_id, "trace_id": trace_id})
);
})
.await;
assert_eq!(current_request_correlation(), (None, None));
}
}
@@ -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);
}
}
+2 -17
View File
@@ -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"
})
}
@@ -0,0 +1,331 @@
//! #107 envelope migration: independent real HTTP wire and SDK participation controls.
use super::{CounterSet, observe, support::*};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
// Reuse the existing real build_app, published catalog, auth and loopback execution fixture.
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
fn counts(c: &CounterSet) -> [usize; 2] {
[c.sdk_jsonrpc_response(), c.sdk_jsonrpc_error()]
}
async fn wire(
response: reqwest::Response,
revision: &str,
id: &Value,
sse: bool,
session: Option<&str>,
) -> Value {
assert_eq!(
response.status(),
200,
"envelope id={id}, SSE={sse}, revision={revision}"
);
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
assert_eq!(
response
.headers()
.get("MCP-Session-Id")
.map(|v| v.to_str().unwrap()),
if sse { session } else { None }
);
let request_id = response.headers()["x-request-id"]
.to_str()
.unwrap()
.to_owned();
let trace_id = response.headers()["x-trace-id"]
.to_str()
.unwrap()
.to_owned();
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();
let terminals: Vec<_> = frames.iter().filter(|f| f.get("id").is_some()).collect();
assert_eq!(terminals.len(), 1, "one terminal envelope: {raw}");
assert_eq!(frames.last(), Some(terminals[0]), "terminal must be last");
for frame in &frames[..frames.len() - 1] {
assert_eq!(frame["method"], "notifications/progress");
assert_eq!(frame["params"]["progressToken"], "envelope-stream");
}
terminals[0].clone()
} else {
serde_json::from_str(&raw).unwrap()
};
assert_eq!(body["jsonrpc"], "2.0");
assert_eq!(body["id"], *id);
assert_eq!(
body["id"].to_string(),
id.to_string(),
"preserve numeric form"
);
assert_eq!(
body.as_object().unwrap().len(),
3,
"no envelope extensions: {body}"
);
assert!(body.get("method").is_none());
if let Some(error) = body.get("error") {
assert!(
body.get("result").is_none(),
"protocol error, not tool isError"
);
assert_eq!(error["code"], -32602);
if sse {
// Existing stream polling has no request correlation scope; preserve omission.
assert!(
error.get("data").is_none(),
"existing SSE omission: {error}"
);
assert_eq!(error.as_object().unwrap().len(), 2);
} else {
assert_eq!(
error["data"],
json!({"request_id":request_id,"trace_id":trace_id})
);
assert_eq!(error.as_object().unwrap().len(), 3);
}
} else {
assert!(body.get("result").is_some());
}
body
}
async fn control(revision: &str) -> Vec<[usize; 2]> {
// Own the process-wide disposable DB before the reused fixture's older ownership hint.
crank_test_support::postgres_schema_url_for_task("envelopes_owner", "t_b27f5c9d").await;
let h = Endpoint::started().await;
let session = h.session(revision).await;
let mut deltas = vec![];
for id in [
json!("opaque/Ю"),
json!(""),
json!(i64::MIN),
json!(i64::MAX),
json!(9007199254740993_u64),
json!(u64::MAX),
json!(1.5),
json!(1.0),
json!(-0.0),
] {
for invalid in [false, true] {
let mut params = if invalid {
json!({"cursor":"not-a-cursor"})
} else {
json!({"cursor":"1"})
};
if revision == MODERN_REVISION {
params["_meta"] = modern_meta();
}
let before = counts(&h.counters);
let response = h
.request(
revision,
session.as_deref(),
&h.key,
"application/json",
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":params}),
)
.send()
.await
.unwrap();
let body = wire(response, revision, &id, false, session.as_deref()).await;
if invalid {
assert_eq!(body["error"]["message"], "invalid tools/list cursor");
} else {
let mut expected = json!({"tools":[]});
if revision == MODERN_REVISION {
expected["resultType"] = json!("complete");
expected["cacheScope"] = json!("private");
expected["ttlMs"] = json!(0);
}
assert_eq!(
body["result"], expected,
"empty result and omission of nextCursor"
);
}
let after = counts(&h.counters);
deltas.push([after[0] - before[0], after[1] - before[1]]);
}
}
// Both revisions support streamed calls with the combined Accept negotiation.
// Missing tool resolves inside the shared Tools command, after the stream opens.
for sse in [false, true] {
for invalid in [false, true] {
let id = if invalid {
json!(u64::MAX)
} else {
json!(-0.0)
};
let mut params =
json!({"name":TOOL_NAME,"arguments":{"email":"envelopes@example.test"}});
if revision == MODERN_REVISION {
params["_meta"] = modern_meta();
}
if invalid {
params["name"] = json!("missing_tool");
} else {
h.gate.add_permits(1);
}
if sse {
params["_meta"]["progressToken"] = json!("envelope-stream");
}
let before = counts(&h.counters);
let mut request = h
.request(
revision,
session.as_deref(),
&h.key,
if sse {
"text/event-stream, application/json"
} else {
"application/json"
},
json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":params}),
)
.build()
.unwrap();
if revision == MODERN_REVISION {
request.headers_mut().insert(
"Mcp-Name",
if invalid { "missing_tool" } else { TOOL_NAME }
.parse()
.unwrap(),
);
}
let response = reqwest::Client::new().execute(request).await.unwrap();
let body = wire(response, revision, &id, sse, session.as_deref()).await;
if invalid {
assert_eq!(body["error"]["message"], "tool missing_tool was not found");
} else {
assert_eq!(
body["result"].as_object().unwrap().len(),
if revision == MODERN_REVISION { 4 } else { 3 }
);
assert_eq!(body["result"]["isError"], false);
assert_eq!(
body["result"]["structuredContent"],
json!({"id":"lead_progress"})
);
assert_eq!(
body["result"]["content"],
json!([{"type":"text","text":serde_json::to_string_pretty(&json!({"id":"lead_progress"})).unwrap()}])
);
if revision == MODERN_REVISION {
assert_eq!(body["result"]["resultType"], "complete");
} else {
assert!(body["result"].get("resultType").is_none());
}
}
let after = counts(&h.counters);
deltas.push([after[0] - before[0], after[1] - before[1]]);
}
}
eprintln!(
"existing GREEN envelopes wire {revision}: exact id forms, JSON success/protocol error, terminal SSE success/protocol error; SDK deltas={deltas:?}"
);
deltas
}
#[tokio::test]
async fn rmcp_envelopes_wire_legacy() {
control(LEGACY_REVISION).await;
}
#[tokio::test]
async fn rmcp_envelopes_wire_modern() {
control(MODERN_REVISION).await;
}
#[tokio::test]
async fn rmcp_envelopes_sdk_legacy() {
let actual = control(LEGACY_REVISION).await;
let expected: Vec<_> = (0..actual.len())
.map(|i| if i % 2 == 0 { [1, 0] } else { [0, 1] })
.collect();
assert_eq!(
actual, expected,
"real SDK envelope serialization after complete HTTP body"
);
}
#[tokio::test]
async fn rmcp_envelopes_sdk_modern() {
let actual = control(MODERN_REVISION).await;
let expected: Vec<_> = (0..actual.len())
.map(|i| if i % 2 == 0 { [1, 0] } else { [0, 1] })
.collect();
assert_eq!(
actual, expected,
"real SDK envelope serialization after complete HTTP body"
);
}
#[tokio::test]
async fn rmcp_envelopes_observer_positive_control() {
let c = Arc::new(CounterSet::default());
observe(c.clone(), async {
super::sdk_jsonrpc_response_serialized();
super::sdk_jsonrpc_error_serialized();
})
.await;
assert_eq!(counts(&c), [1, 1]);
super::sdk_jsonrpc_response_serialized();
super::sdk_jsonrpc_error_serialized();
assert_eq!(counts(&c), [1, 1], "out-of-scope markers are no-ops");
}
#[test]
fn rmcp_envelopes_helper_lossless_control() {
use crate::jsonrpc::{jsonrpc_error, jsonrpc_result};
let values = [
json!(null),
json!(""),
json!("Ю"),
json!(i64::MIN),
json!(i64::MAX),
json!(9007199254740993_u64),
json!(u64::MAX),
json!(1.5),
json!(1.0),
json!(-0.0),
json!([null, {"nested":u64::MAX}]),
json!({"x":null}),
];
for id in &values {
for result in &values {
let actual = jsonrpc_result(id.clone(), result.clone());
let expected = json!({"jsonrpc":"2.0","id":id,"result":result});
assert_eq!(actual, expected);
assert_eq!(actual.to_string(), expected.to_string());
}
for code in [
i64::MIN,
i32::MIN as i64 - 1,
i32::MIN as i64,
-32602,
i32::MAX as i64,
i32::MAX as i64 + 1,
i64::MAX,
] {
for message in ["", "Ошибка Ю"] {
let actual = jsonrpc_error(id.clone(), code, message);
let expected =
json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}});
assert_eq!(actual, expected, "data absent outside correlation scope");
assert_eq!(actual.to_string(), expected.to_string());
}
}
}
}
@@ -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(&params);
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(&params);
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(&params);
})
.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 {
+4
View File
@@ -45,6 +45,10 @@ Progress/cancel-срез #107 на базе rc.23/rmcp3.9.0 подключает
Catalog-change signals/subscriptions-срез #107 на базе rc.24/rmcp3.9.0 использует прежний `protocol/signals.rs` watcher: штатный modern `subscriptions/listen` декодирует notifications через `SubscriptionsListenRequestParams`/`SubscriptionFilter`, а acknowledgment и три list-change notification сериализуются настоящими SDK notification types в `protocol/signals_sdk.rs`. Тонкая входная projection сохраняет прежний запрет explicit null известных filter fields и игнорирование extensions; `_meta` по-прежнему проверяется только HTTP admission до decoder. SDK `NotificationMetaObject` хранит исходный JSON subscriptionId без сужения через RequestId; legacy frames остаются без params, modern ack первым сообщает только true accepted subset. URI-content subscriptions остаются unsupported, bounds32/2048 и64-byte id bound сохранены. Ближайший потребитель уже подключён: действующий `build_app` modern listen SSE и legacy GET SSE после committed catalog changes. HTTP ATDD независимо проверяет SDK execution и wire обеих revisions; прежние signals integration сохраняют Resource/Prompt/Tool delivery, scope, coalescing/recovery. Handwritten filter field DTO и frame builders заменены; fingerprint, watcher timing/queue/drop, auth/session/ownership/TTL/capabilities и transport не меняются. Полный #107, external-client/feature qualification и production deployment этим срезом не завершены.
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.