Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8068fd7910 |
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
|
//! 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.
|
//! `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::response::take_confirmation_token;
|
||||||
use super::rmcp_dispatch::{
|
use super::rmcp_dispatch::{
|
||||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||||
@@ -777,7 +777,8 @@ pub(super) async fn handle_initialize(
|
|||||||
message: &Value,
|
message: &Value,
|
||||||
response_mode: ResponseMode,
|
response_mode: ResponseMode,
|
||||||
) -> Response {
|
) -> 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,
|
Ok(value) => value,
|
||||||
Err(_error) => {
|
Err(_error) => {
|
||||||
return transport_response(
|
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 {
|
else {
|
||||||
// A revision outside the approved window is rejected without minting a session and without
|
// A revision outside the approved window is rejected without minting a session and without
|
||||||
// echoing any withdrawn revision as the served identity.
|
// echoing any withdrawn revision as the served identity.
|
||||||
@@ -810,9 +814,9 @@ pub(super) async fn handle_initialize(
|
|||||||
};
|
};
|
||||||
let now = OffsetDateTime::now_utc();
|
let now = OffsetDateTime::now_utc();
|
||||||
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
|
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
|
||||||
let supports_elicitation = initialize_params
|
let supports_elicitation = raw_params
|
||||||
.capabilities
|
.get("capabilities")
|
||||||
.get("elicitation")
|
.and_then(|capabilities| capabilities.get("elicitation"))
|
||||||
.is_some_and(Value::is_object);
|
.is_some_and(Value::is_object);
|
||||||
let session_id = match state
|
let session_id = match state
|
||||||
.sessions
|
.sessions
|
||||||
|
|||||||
@@ -73,11 +73,15 @@ pub(crate) struct CounterSet {
|
|||||||
sdk_signal_notification: AtomicUsize,
|
sdk_signal_notification: AtomicUsize,
|
||||||
sdk_jsonrpc_response: AtomicUsize,
|
sdk_jsonrpc_response: AtomicUsize,
|
||||||
sdk_jsonrpc_error: AtomicUsize,
|
sdk_jsonrpc_error: AtomicUsize,
|
||||||
|
sdk_initialize_input: AtomicUsize,
|
||||||
sdk_initialize_result: AtomicUsize,
|
sdk_initialize_result: AtomicUsize,
|
||||||
sdk_discover_result: AtomicUsize,
|
sdk_discover_result: AtomicUsize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CounterSet {
|
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 {
|
pub(crate) fn sdk_initialize_result(&self) -> usize {
|
||||||
self.sdk_initialize_result.load(Ordering::SeqCst)
|
self.sdk_initialize_result.load(Ordering::SeqCst)
|
||||||
}
|
}
|
||||||
@@ -398,6 +402,14 @@ pub(crate) fn sdk_discover_result_serialized() {
|
|||||||
#[path = "../rmcp_lifecycle_negotiation_runtime_tests.rs"]
|
#[path = "../rmcp_lifecycle_negotiation_runtime_tests.rs"]
|
||||||
mod rmcp_lifecycle_negotiation_runtime_tests;
|
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) {
|
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||||
let _ = OBSERVER.try_with(|counters| {
|
let _ = OBSERVER.try_with(|counters| {
|
||||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||||
|
|||||||
@@ -1,14 +1,6 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
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)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
pub(super) struct ToolCallParams {
|
pub(super) struct ToolCallParams {
|
||||||
pub(super) name: String,
|
pub(super) name: String,
|
||||||
|
|||||||
@@ -122,6 +122,17 @@ pub(super) struct CountedSessionStore {
|
|||||||
counters: Arc<SessionCounters>,
|
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]
|
#[async_trait::async_trait]
|
||||||
impl TransportSessionStore for CountedSessionStore {
|
impl TransportSessionStore for CountedSessionStore {
|
||||||
async fn create(
|
async fn create(
|
||||||
|
|||||||
@@ -1,14 +1,25 @@
|
|||||||
//! Typed negotiation results; admission and session lifecycle remain in the HTTP adapter.
|
//! Typed negotiation results; admission and session lifecycle remain in the HTTP adapter.
|
||||||
|
|
||||||
use rmcp::model::{
|
use rmcp::model::{
|
||||||
CacheScope, DiscoverResult, Implementation, InitializeResult, ProtocolVersion,
|
CacheScope, DiscoverResult, Implementation, InitializeRequestParams, InitializeResult,
|
||||||
ServerCapabilities,
|
ProtocolVersion, ServerCapabilities,
|
||||||
};
|
};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use super::advertised_server_capabilities;
|
use super::advertised_server_capabilities;
|
||||||
use crate::jsonrpc::SUPPORTED_PROTOCOL_VERSIONS;
|
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 {
|
fn protocol_version(revision: &str) -> ProtocolVersion {
|
||||||
serde_json::from_value(Value::String(revision.to_owned()))
|
serde_json::from_value(Value::String(revision.to_owned()))
|
||||||
.expect("served protocol revisions are strings")
|
.expect("served protocol revisions are strings")
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ pub(crate) use completion::{
|
|||||||
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
|
||||||
handle_completion_command,
|
handle_completion_command,
|
||||||
};
|
};
|
||||||
pub(crate) use lifecycle_sdk::{discover_result, initialize_result};
|
pub(crate) use lifecycle_sdk::{discover_result, initialize_params, initialize_result};
|
||||||
pub(crate) use logging::{
|
pub(crate) use logging::{
|
||||||
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
||||||
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
|
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
|
||||||
|
|||||||
@@ -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"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ use tokio::sync::Semaphore;
|
|||||||
pub(in crate::app::dispatch_observer) struct Endpoint {
|
pub(in crate::app::dispatch_observer) struct Endpoint {
|
||||||
pub registry: crank_registry::PostgresRegistry,
|
pub registry: crank_registry::PostgresRegistry,
|
||||||
pub counters: Arc<CounterSet>,
|
pub counters: Arc<CounterSet>,
|
||||||
|
pub sessions: Arc<CountedSessionStore>,
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub other_key: String,
|
pub other_key: String,
|
||||||
pub gate: Arc<Semaphore>,
|
pub gate: Arc<Semaphore>,
|
||||||
@@ -90,6 +91,7 @@ impl Endpoint {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let counters = Arc::new(CounterSet::default());
|
let counters = Arc::new(CounterSet::default());
|
||||||
|
let sessions = Arc::new(CountedSessionStore::default());
|
||||||
let app = crate::build_app(
|
let app = crate::build_app(
|
||||||
registry.clone(),
|
registry.clone(),
|
||||||
Duration::ZERO,
|
Duration::ZERO,
|
||||||
@@ -101,7 +103,7 @@ impl Endpoint {
|
|||||||
.build(),
|
.build(),
|
||||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
sessions.clone(),
|
||||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||||
);
|
);
|
||||||
let scope = counters.clone();
|
let scope = counters.clone();
|
||||||
@@ -125,6 +127,7 @@ impl Endpoint {
|
|||||||
Self {
|
Self {
|
||||||
registry,
|
registry,
|
||||||
counters,
|
counters,
|
||||||
|
sessions,
|
||||||
key,
|
key,
|
||||||
other_key,
|
other_key,
|
||||||
gate,
|
gate,
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ 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.
|
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 не завершены.
|
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 не завершены.
|
||||||
|
|
||||||
Проверяемый результат:
|
Проверяемый результат:
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user