Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f9c4cb568 | ||
|
|
61378224b2 | ||
|
|
1b51d44121 | ||
|
|
077be3b069 |
No files matched your search
@@ -835,14 +835,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,25 @@ 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_result: AtomicUsize,
|
||||
sdk_discover_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
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 +372,32 @@ 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;
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
@@ -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,88 @@
|
||||
//! Typed negotiation results; admission and session lifecycle remain in the HTTP adapter.
|
||||
|
||||
use rmcp::model::{
|
||||
CacheScope, DiscoverResult, Implementation, InitializeResult, ProtocolVersion,
|
||||
ServerCapabilities,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::advertised_server_capabilities;
|
||||
use crate::jsonrpc::SUPPORTED_PROTOCOL_VERSIONS;
|
||||
|
||||
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_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,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,7 +6,7 @@ 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 key: String,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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. Входной InitializeParams parser с прежней tolerance, 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