Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
163b519979 | ||
|
|
65144fd8c6 | ||
|
|
66bb135398 | ||
|
|
0de1e94df4 | ||
|
|
7a1fc0d761 | ||
|
|
156a849087 | ||
|
|
a4cf5ed8cf | ||
|
|
326f209bc5 | ||
|
|
c32e24b268 | ||
|
|
ca126004af |
No files matched your search
@@ -12,10 +12,7 @@ use super::rmcp_dispatch::{
|
||||
};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
is_notification, jsonrpc_error, jsonrpc_result, method_name, negotiated_protocol_version,
|
||||
params, request_id,
|
||||
},
|
||||
jsonrpc::{jsonrpc_error, jsonrpc_result, negotiated_protocol_version, params, request_id},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, MethodHandler,
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
|
||||
@@ -81,7 +78,20 @@ pub(super) async fn handle_modern_request(
|
||||
// matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have
|
||||
// already run at this point, so this early return cannot admit a malformed identity or a session
|
||||
// conflict, and the notification is never dispatched.
|
||||
if is_notification(message) {
|
||||
let envelope = match crate::protocol::decode_dispatch_envelope(message) {
|
||||
Ok(Some(envelope)) => envelope,
|
||||
_ => {
|
||||
return internal_jsonrpc_error(
|
||||
message,
|
||||
"admitted dispatch envelope could not be decoded",
|
||||
);
|
||||
}
|
||||
};
|
||||
let method = envelope.method();
|
||||
let notification = envelope.is_notification();
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_dispatch_envelope_consumed();
|
||||
if notification {
|
||||
return crate::protocol::modern_notification_response();
|
||||
}
|
||||
|
||||
@@ -89,15 +99,14 @@ pub(super) async fn handle_modern_request(
|
||||
Ok(declared_method) => declared_method,
|
||||
Err(response) => return *response,
|
||||
};
|
||||
if declared_method != method_name(message) {
|
||||
if declared_method != method {
|
||||
return crate::protocol::modern_header_mismatch_response(message);
|
||||
}
|
||||
|
||||
// R5/F5: the same registration-backed dispatch as the legacy adapter. The handler is decided by
|
||||
// the owning registration (not by a literal method list inside this adapter), and a method whose
|
||||
// capability is not eligible in this revision is never served here.
|
||||
let dispatch =
|
||||
crate::protocol::dispatch_decision(method_name(message).unwrap_or_default(), version);
|
||||
let dispatch = crate::protocol::dispatch_decision(method.unwrap_or_default(), version);
|
||||
match dispatch {
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Discover,
|
||||
@@ -121,7 +130,7 @@ pub(super) async fn handle_modern_request(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_result(
|
||||
version,
|
||||
json!({ "protocolVersion": version }),
|
||||
crate::protocol::ping_result(&json!({"method": "ping"}), version),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
@@ -851,6 +860,7 @@ pub(super) async fn handle_initialized_notification(
|
||||
state: Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
headers: &HeaderMap,
|
||||
notification: rmcp::model::ClientNotification,
|
||||
) -> Response {
|
||||
match session_id_from_headers(headers) {
|
||||
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
|
||||
@@ -858,6 +868,15 @@ pub(super) async fn handle_initialized_notification(
|
||||
if session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug =>
|
||||
{
|
||||
let rmcp::model::ClientNotification::InitializedNotification(initialized) =
|
||||
notification
|
||||
else {
|
||||
unreachable!("initialized handler requires the SDK initialized variant")
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialized_notification_consumed(&initialized);
|
||||
#[cfg(not(test))]
|
||||
let _ = initialized;
|
||||
match state
|
||||
.sessions
|
||||
.mark_initialized(&session_id, OffsetDateTime::now_utc())
|
||||
|
||||
@@ -73,12 +73,52 @@ pub(crate) struct CounterSet {
|
||||
sdk_signal_notification: AtomicUsize,
|
||||
sdk_jsonrpc_response: AtomicUsize,
|
||||
sdk_jsonrpc_error: AtomicUsize,
|
||||
sdk_ping_request: AtomicUsize,
|
||||
sdk_ping_result: AtomicUsize,
|
||||
sdk_inbound_response_decoded: AtomicUsize,
|
||||
sdk_inbound_error_decoded: AtomicUsize,
|
||||
sdk_inbound_response_consumed: AtomicUsize,
|
||||
sdk_inbound_error_consumed: AtomicUsize,
|
||||
sdk_dispatch_decoded: AtomicUsize,
|
||||
sdk_dispatch_consumed: AtomicUsize,
|
||||
sdk_initialized_decoded: AtomicUsize,
|
||||
sdk_initialized_consumed: AtomicUsize,
|
||||
sdk_initialize_input: AtomicUsize,
|
||||
sdk_initialize_result: AtomicUsize,
|
||||
sdk_discover_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
pub(crate) fn sdk_inbound_response_decoded(&self) -> usize {
|
||||
self.sdk_inbound_response_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_inbound_error_decoded(&self) -> usize {
|
||||
self.sdk_inbound_error_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_inbound_response_consumed(&self) -> usize {
|
||||
self.sdk_inbound_response_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_inbound_error_consumed(&self) -> usize {
|
||||
self.sdk_inbound_error_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_dispatch_decoded(&self) -> usize {
|
||||
self.sdk_dispatch_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_dispatch_consumed(&self) -> usize {
|
||||
self.sdk_dispatch_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_initialized_decoded(&self) -> usize {
|
||||
self.sdk_initialized_decoded.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_initialized_consumed(&self) -> usize {
|
||||
self.sdk_initialized_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_ping_request(&self) -> usize {
|
||||
self.sdk_ping_request.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_ping_result(&self) -> usize {
|
||||
self.sdk_ping_result.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_initialize_input(&self) -> usize {
|
||||
self.sdk_initialize_input.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -410,6 +450,69 @@ pub(crate) fn sdk_initialize_input_consumed(_params: &rmcp::model::InitializeReq
|
||||
#[path = "../rmcp_initialize_input_runtime_tests.rs"]
|
||||
mod rmcp_initialize_input_runtime_tests;
|
||||
|
||||
/// Mark only where a real SDK PingRequest is consumed by the shared runtime ping seam.
|
||||
pub(crate) fn sdk_ping_request_consumed(_request: &rmcp::model::PingRequest) {
|
||||
increment(|counters| &counters.sdk_ping_request);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing the real SDK ping result.
|
||||
pub(crate) fn sdk_ping_result_serialized() {
|
||||
increment(|counters| &counters.sdk_ping_result);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_ping_runtime_tests.rs"]
|
||||
mod rmcp_ping_runtime_tests;
|
||||
|
||||
/// Mark immediately after typed method-projection decode, not variant consumption.
|
||||
pub(crate) fn sdk_initialized_notification_decoded(
|
||||
_notification: &rmcp::model::InitializedNotification,
|
||||
) {
|
||||
increment(|counters| &counters.sdk_initialized_decoded);
|
||||
}
|
||||
|
||||
/// Mark inside the matched SDK variant, after guards and immediately before session mutation.
|
||||
pub(crate) fn sdk_initialized_notification_consumed(
|
||||
_notification: &rmcp::model::InitializedNotification,
|
||||
) {
|
||||
increment(|counters| &counters.sdk_initialized_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_initialized_runtime_tests.rs"]
|
||||
mod rmcp_initialized_runtime_tests;
|
||||
|
||||
/// Mark after successful SDK envelope decode, independently of routing consumption.
|
||||
pub(crate) fn sdk_dispatch_envelope_decoded() {
|
||||
increment(|counters| &counters.sdk_dispatch_decoded);
|
||||
}
|
||||
|
||||
/// Mark only when decoded method/kind selects the existing registry-backed route.
|
||||
pub(crate) fn sdk_dispatch_envelope_consumed() {
|
||||
increment(|counters| &counters.sdk_dispatch_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_dispatch_runtime_tests.rs"]
|
||||
mod rmcp_dispatch_runtime_tests;
|
||||
|
||||
/// Mark only after a real SDK success-response from_value succeeds.
|
||||
pub(crate) fn sdk_inbound_response_decoded() {
|
||||
increment(|c| &c.sdk_inbound_response_decoded);
|
||||
}
|
||||
/// Mark only after a real SDK error-response from_value succeeds.
|
||||
pub(crate) fn sdk_inbound_error_decoded() {
|
||||
increment(|c| &c.sdk_inbound_error_decoded);
|
||||
}
|
||||
/// Mark inside the matched typed SDK success variant that selects ACK.
|
||||
pub(crate) fn sdk_inbound_response_consumed() {
|
||||
increment(|c| &c.sdk_inbound_response_consumed);
|
||||
}
|
||||
/// Mark inside the matched typed SDK error variant that selects ACK.
|
||||
pub(crate) fn sdk_inbound_error_consumed() {
|
||||
increment(|c| &c.sdk_inbound_error_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_response_runtime_tests.rs"]
|
||||
mod rmcp_response_runtime_tests;
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
@@ -278,6 +278,17 @@ async fn mcp_post_response(
|
||||
Err(_status) => return ambiguous_session_carrier_response(headers, message),
|
||||
};
|
||||
|
||||
// Responses ACK before era/session resolution, but must not bypass fresh credentials.
|
||||
// Method-bearing messages retain their existing scoped authorization path below.
|
||||
if message
|
||||
.as_object()
|
||||
.is_some_and(|object| !object.contains_key("method"))
|
||||
&& let Err(error) =
|
||||
require_traced_machine_access(&state, path, headers, PlatformApiKeyScope::Read).await
|
||||
{
|
||||
return error.into_response();
|
||||
}
|
||||
|
||||
// Single JSON-RPC envelope guard: only a well-formed message reaches era resolution, dispatch,
|
||||
// approval or any outbound request. Syntactically valid JSON is not the same as a valid envelope.
|
||||
let envelope = match crate::protocol::validate_jsonrpc_envelope(message) {
|
||||
|
||||
@@ -30,10 +30,7 @@ use super::rmcp_dispatch::{
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
|
||||
method_name, params, request_id,
|
||||
},
|
||||
jsonrpc::{LEGACY_PROTOCOL_VERSION, jsonrpc_error, jsonrpc_result, params, request_id},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
|
||||
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
|
||||
@@ -65,10 +62,20 @@ pub(super) async fn handle_legacy_request(
|
||||
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
|
||||
// really reaches its handler and removing a descriptor removes the dispatch.
|
||||
let registration_revision = protocol_version.unwrap_or(LEGACY_PROTOCOL_VERSION);
|
||||
let dispatch = crate::protocol::dispatch_decision(
|
||||
method_name(message).unwrap_or_default(),
|
||||
registration_revision,
|
||||
);
|
||||
let envelope = match crate::protocol::decode_dispatch_envelope(message) {
|
||||
Ok(Some(envelope)) => envelope,
|
||||
_ => {
|
||||
return internal_jsonrpc_error(
|
||||
message,
|
||||
"admitted dispatch envelope could not be decoded",
|
||||
);
|
||||
}
|
||||
};
|
||||
let method = envelope.method();
|
||||
let dispatch =
|
||||
crate::protocol::dispatch_decision(method.unwrap_or_default(), registration_revision);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_dispatch_envelope_consumed();
|
||||
match dispatch {
|
||||
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
|
||||
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
|
||||
@@ -78,17 +85,23 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Method,
|
||||
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
|
||||
} if envelope.is_request() => handle_initialize(state, path, message, response_mode).await,
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Lifecycle,
|
||||
kind: Kind::Notification,
|
||||
} if is_notification(message) => {
|
||||
handle_initialized_notification(state, path, headers).await
|
||||
} if envelope.is_notification() => {
|
||||
handle_initialized_notification(
|
||||
state,
|
||||
path,
|
||||
headers,
|
||||
crate::protocol::initialized_notification(message),
|
||||
)
|
||||
.await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Ping,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -98,7 +111,10 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
json!({ "protocolVersion": session.protocol_version }),
|
||||
crate::protocol::ping_result(
|
||||
&json!({"method": "ping"}),
|
||||
&session.protocol_version,
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -108,7 +124,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -177,7 +193,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ToolCall,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -235,13 +251,13 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Cancelled,
|
||||
kind: Kind::Notification,
|
||||
} if is_notification(message) => {
|
||||
} if envelope.is_notification() => {
|
||||
handle_cancelled_notification(&state, path, headers, message, credential).await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -310,7 +326,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceRead,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -391,7 +407,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceTemplateList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -463,7 +479,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptList,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -528,7 +544,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::PromptGet,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -626,7 +642,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Completion,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -705,7 +721,7 @@ pub(super) async fn handle_legacy_request(
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
} if envelope.is_request() => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
@@ -751,10 +767,10 @@ pub(super) async fn handle_legacy_request(
|
||||
}
|
||||
// A notification whose method the registration does not map to this adapter's handlers is
|
||||
// acknowledged without being dispatched, exactly as before.
|
||||
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
||||
_ if envelope.is_notification() => StatusCode::ACCEPTED.into_response(),
|
||||
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
|
||||
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
|
||||
_ => match method_name(message) {
|
||||
_ => match method {
|
||||
Some(method) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Generic SDK envelopes for routing after the authoritative Crank admission guard.
|
||||
|
||||
use rmcp::model::{JsonRpcNotification, JsonRpcRequest};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum DispatchEnvelope {
|
||||
Request(JsonRpcRequest<Value>),
|
||||
Notification(JsonRpcNotification<Value>),
|
||||
}
|
||||
|
||||
impl DispatchEnvelope {
|
||||
pub(crate) fn method(&self) -> Option<&str> {
|
||||
let payload = match self {
|
||||
Self::Request(envelope) => &envelope.request,
|
||||
Self::Notification(envelope) => &envelope.notification,
|
||||
};
|
||||
payload.get("method").and_then(Value::as_str)
|
||||
}
|
||||
|
||||
pub(crate) fn is_request(&self) -> bool {
|
||||
matches!(self, Self::Request(_))
|
||||
}
|
||||
|
||||
pub(crate) fn is_notification(&self) -> bool {
|
||||
matches!(self, Self::Notification(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// Call only after `validate_jsonrpc_envelope`; responses use the separate response SDK classifier.
|
||||
/// Params and extensions stay in the raw message, not in this routing-only projection.
|
||||
pub(crate) fn decode_dispatch_envelope(
|
||||
message: &Value,
|
||||
) -> Result<Option<DispatchEnvelope>, serde_json::Error> {
|
||||
let Some(method) = message.get("method") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut projection = json!({"jsonrpc": message.get("jsonrpc"), "method": method});
|
||||
let envelope = if let Some(id) = message.get("id") {
|
||||
// SDK ids are string/i64; the surrogate must never leave this routing-only envelope.
|
||||
projection["id"] = if id.is_number() && id.as_i64().is_none() {
|
||||
json!(0)
|
||||
} else {
|
||||
id.clone()
|
||||
};
|
||||
DispatchEnvelope::Request(serde_json::from_value(projection)?)
|
||||
} else {
|
||||
DispatchEnvelope::Notification(serde_json::from_value(projection)?)
|
||||
};
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_dispatch_envelope_decoded();
|
||||
Ok(Some(envelope))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn arbitrary_method_ignores_params_and_mixed_extra_fields() {
|
||||
for params in [
|
||||
None,
|
||||
Some(json!({})),
|
||||
Some(json!({
|
||||
"_meta": {"clientInfo": false}, "extension": [null, 3]
|
||||
})),
|
||||
] {
|
||||
let mut message = json!({
|
||||
"jsonrpc": "2.0", "id": "request", "method": "private/arbitrary",
|
||||
"result": false, "error": [1], "extension": {"anything": true}
|
||||
});
|
||||
if let Some(params) = params {
|
||||
message["params"] = params;
|
||||
}
|
||||
let original = message.clone();
|
||||
let envelope = decode_dispatch_envelope(&message)
|
||||
.expect("admitted request decodes")
|
||||
.expect("request envelope");
|
||||
assert_eq!(envelope.method(), Some("private/arbitrary"));
|
||||
assert!(envelope.is_request());
|
||||
assert!(!envelope.is_notification());
|
||||
let DispatchEnvelope::Request(request) = envelope else {
|
||||
panic!("request must retain its SDK variant");
|
||||
};
|
||||
assert_eq!(request.request, json!({"method": "private/arbitrary"}));
|
||||
assert_eq!(message, original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_ids_preserve_raw_value_and_only_surrogate_sdk_incompatible_numbers() {
|
||||
for (id, sdk_id) in [
|
||||
(json!("string-id"), json!("string-id")),
|
||||
(json!(i64::MIN), json!(i64::MIN)),
|
||||
(json!(i64::MAX), json!(i64::MAX)),
|
||||
(json!(u64::MAX), json!(0)),
|
||||
(json!(1.25), json!(0)),
|
||||
(json!(1.0), json!(0)),
|
||||
] {
|
||||
let message = json!({"jsonrpc": "2.0", "id": id, "method": "arbitrary"});
|
||||
let original = message.clone();
|
||||
let DispatchEnvelope::Request(request) = decode_dispatch_envelope(&message)
|
||||
.expect("admitted id decodes")
|
||||
.expect("request envelope")
|
||||
else {
|
||||
panic!("id-bearing method must be a request");
|
||||
};
|
||||
assert_eq!(serde_json::to_value(request.id).expect("SDK id"), sdk_id);
|
||||
assert_eq!(message, original);
|
||||
assert_eq!(message.to_string(), original.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notification_kind_is_independent_of_method_and_ignored_fields() {
|
||||
let message = json!({
|
||||
"jsonrpc": "2.0", "method": "private/arbitrary", "params": {},
|
||||
"result": {}, "error": {}, "extension": 42
|
||||
});
|
||||
let original = message.clone();
|
||||
let envelope = decode_dispatch_envelope(&message)
|
||||
.expect("notification decodes")
|
||||
.expect("notification envelope");
|
||||
assert_eq!(envelope.method(), Some("private/arbitrary"));
|
||||
assert!(!envelope.is_request());
|
||||
assert!(envelope.is_notification());
|
||||
let DispatchEnvelope::Notification(notification) = envelope else {
|
||||
panic!("notification must retain its SDK variant");
|
||||
};
|
||||
assert_eq!(
|
||||
notification.notification,
|
||||
json!({"method": "private/arbitrary"})
|
||||
);
|
||||
assert_eq!(message, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incoming_success_and_error_responses_do_not_enter_method_dispatch() {
|
||||
for message in [
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": {}}),
|
||||
json!({"jsonrpc": "2.0", "id": "id", "error": {"code": -1, "message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": "error"}}),
|
||||
] {
|
||||
assert!(
|
||||
decode_dispatch_envelope(&message)
|
||||
.expect("response bypass")
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use rmcp::model::{
|
||||
CacheScope, DiscoverResult, Implementation, InitializeRequestParams, InitializeResult,
|
||||
ProtocolVersion, ServerCapabilities,
|
||||
PingRequest, ProtocolVersion, ServerCapabilities, ServerResult,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -45,6 +45,36 @@ fn restore_registry_extensions(result: &mut Value, advertised: Value) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn initialized_notification(message: &Value) -> rmcp::model::ClientNotification {
|
||||
// Admission already checked the envelope; ignored params must not acquire SDK constraints.
|
||||
let notification: rmcp::model::InitializedNotification =
|
||||
serde_json::from_value(serde_json::json!({"method": message["method"]}))
|
||||
.expect("registry dispatched a validated initialized notification");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_initialized_notification_decoded(¬ification);
|
||||
notification.into()
|
||||
}
|
||||
|
||||
pub(crate) fn ping_result(message: &Value, revision: &str) -> Value {
|
||||
// Ping params were ignored after admission; do not add SDK constraints to extensions.
|
||||
let request: PingRequest = serde_json::from_value(serde_json::json!({
|
||||
"method": message["method"]
|
||||
}))
|
||||
.expect("registry dispatched a validated ping request");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_ping_request_consumed(&request);
|
||||
let result = match rmcp::model::ClientRequest::from(request) {
|
||||
rmcp::model::ClientRequest::PingRequest(_) => ServerResult::empty(()),
|
||||
_ => unreachable!("typed ping can only dispatch ping"),
|
||||
};
|
||||
let mut result = serde_json::to_value(result).expect("SDK ping result is serializable");
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_ping_result_serialized();
|
||||
// Crank keeps the admitted/session revision in addition to the SDK's empty ping result.
|
||||
result["protocolVersion"] = Value::String(revision.to_owned());
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn initialize_result(revision: &str, name: &str, version: &str) -> Value {
|
||||
let advertised = advertised_server_capabilities(revision);
|
||||
let result = InitializeResult::new(capabilities(&advertised))
|
||||
|
||||
@@ -26,13 +26,17 @@ use crate::transport::{json_response, protocol_version_from_headers, singleton_h
|
||||
|
||||
mod command;
|
||||
mod completion;
|
||||
mod dispatch_sdk;
|
||||
mod lifecycle_sdk;
|
||||
mod logging;
|
||||
mod prompts;
|
||||
mod registry;
|
||||
mod resources;
|
||||
mod response_sdk;
|
||||
mod signals;
|
||||
|
||||
pub(crate) use dispatch_sdk::decode_dispatch_envelope;
|
||||
|
||||
pub(crate) use command::{
|
||||
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
|
||||
ToolsListCommand, ToolsOutcome, handle_tools_command,
|
||||
@@ -41,7 +45,9 @@ 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 lifecycle_sdk::{
|
||||
discover_result, initialize_params, initialize_result, initialized_notification, ping_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,
|
||||
@@ -86,50 +92,6 @@ fn is_valid_request_id(id: &Value) -> bool {
|
||||
id.is_string() || id.is_number()
|
||||
}
|
||||
|
||||
/// The pinned error object: `Error { code: number; message: string; data?: unknown }`.
|
||||
fn is_valid_error_object(error: Option<&Value>) -> bool {
|
||||
let Some(Value::Object(error)) = error else {
|
||||
return false;
|
||||
};
|
||||
error.get("code").is_some_and(Value::is_number)
|
||||
&& error.get("message").is_some_and(Value::is_string)
|
||||
}
|
||||
|
||||
/// Classify a wire response (a message without `method`).
|
||||
///
|
||||
/// Pinned shapes are exclusive: a success response carries `result: Result` (an object) and a required
|
||||
/// `id: RequestId`, an error response carries `error: Error` and may omit the id (a present id must
|
||||
/// still be a `RequestId`). Both together, neither, a foreign id, a non-object `result` or a malformed
|
||||
/// error object are all invalid requests rather than an acknowledgement.
|
||||
///
|
||||
/// The `result` value is required to be an object because the pinned `JSONRPCResultResponse` types it as
|
||||
/// `Result`; the modern `resultType` member is deliberately **not** required here, because an incoming
|
||||
/// response may come from a client implementing an earlier revision.
|
||||
fn classify_wire_response(object: &serde_json::Map<String, Value>) -> Option<EnvelopeKind> {
|
||||
match (object.contains_key("result"), object.contains_key("error")) {
|
||||
(true, false) => {
|
||||
if !matches!(object.get("result"), Some(Value::Object(_))) {
|
||||
return None;
|
||||
}
|
||||
object
|
||||
.get("id")
|
||||
.filter(|id| is_valid_request_id(id))
|
||||
.map(|_| EnvelopeKind::Response)
|
||||
}
|
||||
(false, true) => {
|
||||
if !is_valid_error_object(object.get("error")) {
|
||||
return None;
|
||||
}
|
||||
match object.get("id") {
|
||||
None => Some(EnvelopeKind::Response),
|
||||
Some(id) if is_valid_request_id(id) => Some(EnvelopeKind::Response),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pinned modern wire projection of a success result.
|
||||
///
|
||||
/// `JSONRPCResultResponse.result` is a `Result`, and this revision requires the `resultType` member
|
||||
@@ -255,7 +217,7 @@ pub(crate) fn validate_jsonrpc_envelope(message: &Value) -> Result<EnvelopeKind,
|
||||
}
|
||||
}
|
||||
Some(_) => Err(rejected(invalid_request_response())),
|
||||
None => match classify_wire_response(object) {
|
||||
None => match response_sdk::classify_response(message) {
|
||||
Some(kind) => Ok(kind),
|
||||
None => Err(rejected(invalid_request_response())),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
//! SDK classification of inbound responses, without narrowing the admitted wire numbers.
|
||||
|
||||
use rmcp::model::{JsonRpcError, JsonRpcResponse};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::EnvelopeKind;
|
||||
|
||||
enum ResponseEnvelope {
|
||||
Success(JsonRpcResponse<Value>),
|
||||
Error(JsonRpcError),
|
||||
}
|
||||
|
||||
/// Only the no-method branch of the envelope guard calls this helper.
|
||||
pub(super) fn classify_response(message: &Value) -> Option<EnvelopeKind> {
|
||||
match decode_response(message)? {
|
||||
ResponseEnvelope::Success(JsonRpcResponse { result, .. }) => {
|
||||
// The generic SDK result must still satisfy the pinned object-only contract.
|
||||
if !result.is_object() {
|
||||
return None;
|
||||
}
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_inbound_response_consumed();
|
||||
Some(EnvelopeKind::Response)
|
||||
}
|
||||
ResponseEnvelope::Error(JsonRpcError { .. }) => {
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_inbound_error_consumed();
|
||||
Some(EnvelopeKind::Response)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_response(message: &Value) -> Option<ResponseEnvelope> {
|
||||
let object = message.as_object()?;
|
||||
if object.get("jsonrpc")?.as_str()? != "2.0" || object.contains_key("method") {
|
||||
return None;
|
||||
}
|
||||
let id = object.get("id");
|
||||
if id.is_some_and(|id| !id.is_string() && !id.is_number()) {
|
||||
return None;
|
||||
}
|
||||
let mut projection = json!({"jsonrpc": "2.0"});
|
||||
if let Some(id) = id {
|
||||
// SDK ids are string/i64; this surrogate stays in the classification-only clone.
|
||||
projection["id"] = if id.is_number() && id.as_i64().is_none() {
|
||||
json!(0)
|
||||
} else {
|
||||
id.clone()
|
||||
};
|
||||
}
|
||||
match (object.get("result"), object.get("error")) {
|
||||
(Some(result), None) if result.is_object() && id.is_some() => {
|
||||
projection["result"] = result.clone();
|
||||
let response = serde_json::from_value::<JsonRpcResponse<Value>>(projection).ok()?;
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_inbound_response_decoded();
|
||||
Some(ResponseEnvelope::Success(response))
|
||||
}
|
||||
(None, Some(error)) if error.is_object() => {
|
||||
let code = error.get("code")?;
|
||||
if !code.is_number() || !error.get("message")?.is_string() {
|
||||
return None;
|
||||
}
|
||||
projection["error"] = error.clone();
|
||||
// SDK codes are i32; validate the original number before projecting only that field.
|
||||
if code
|
||||
.as_i64()
|
||||
.and_then(|code| i32::try_from(code).ok())
|
||||
.is_none()
|
||||
{
|
||||
projection["error"]["code"] = json!(0);
|
||||
}
|
||||
let error = serde_json::from_value::<JsonRpcError>(projection).ok()?;
|
||||
#[cfg(test)]
|
||||
crate::app::dispatch_observer::sdk_inbound_error_decoded();
|
||||
Some(ResponseEnvelope::Error(error))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accepts_response_shapes_without_constraining_params_or_extensions() {
|
||||
for message in [
|
||||
json!({"jsonrpc": "2.0", "id": "", "result": {}}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": {"resultType": false},
|
||||
"params": false, "extension": [null, 1]}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": ""}}),
|
||||
json!({"jsonrpc": "2.0", "id": "id", "error": {
|
||||
"code": -1, "message": "error", "data": [null, {"nested": true}]
|
||||
}, "params": [], "extension": false}),
|
||||
] {
|
||||
let original = message.to_string();
|
||||
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
|
||||
assert_eq!(message.to_string(), original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_shapes_before_sdk_projection() {
|
||||
for message in [
|
||||
Value::Null,
|
||||
json!([]),
|
||||
json!({"id": 1, "result": {}}),
|
||||
json!({"jsonrpc": "1.0", "id": 1, "result": {}}),
|
||||
json!({"jsonrpc": "2.0"}),
|
||||
json!({"jsonrpc": "2.0", "result": {}}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": {}, "error": null}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": null}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": []}),
|
||||
json!({"jsonrpc": "2.0", "id": 1, "result": true}),
|
||||
json!({"jsonrpc": "2.0", "error": null}),
|
||||
json!({"jsonrpc": "2.0", "error": []}),
|
||||
json!({"jsonrpc": "2.0", "error": {"message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": "-1", "message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": null, "message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": true, "message": "error"}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1}}),
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": false}}),
|
||||
json!({"jsonrpc": "2.0", "method": null, "id": 1, "result": {}}),
|
||||
json!({"jsonrpc": "2.0", "method": "request", "id": 1, "result": {}}),
|
||||
] {
|
||||
assert_eq!(classify_response(&message), None, "{message}");
|
||||
}
|
||||
for id in [Value::Null, json!(true), json!([]), json!({})] {
|
||||
for payload in [
|
||||
json!({"result": {}}),
|
||||
json!({"error": {"code": -1, "message": "e"}}),
|
||||
] {
|
||||
let mut message = payload;
|
||||
message["jsonrpc"] = json!("2.0");
|
||||
message["id"] = id.clone();
|
||||
assert_eq!(classify_response(&message), None, "{message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_projection_preserves_raw_json_and_executes_typed_variants() {
|
||||
let numbers = [
|
||||
json!(i64::MIN),
|
||||
json!(i64::MAX),
|
||||
json!(u64::MAX),
|
||||
json!(i32::MIN),
|
||||
json!(i32::MAX),
|
||||
json!(2147483648_i64),
|
||||
json!(-2147483649_i64),
|
||||
json!(1.25),
|
||||
json!(1.0),
|
||||
json!(-0.0),
|
||||
json!(f64::MAX),
|
||||
];
|
||||
for number in numbers {
|
||||
let sdk_id = if number.as_i64().is_some() {
|
||||
number.clone()
|
||||
} else {
|
||||
json!(0)
|
||||
};
|
||||
let sdk_code = if number
|
||||
.as_i64()
|
||||
.and_then(|n| i32::try_from(n).ok())
|
||||
.is_some()
|
||||
{
|
||||
number.clone()
|
||||
} else {
|
||||
json!(0)
|
||||
};
|
||||
for error in [false, true] {
|
||||
let mut message = json!({"jsonrpc": "2.0", "id": number});
|
||||
if error {
|
||||
message["error"] = json!({"code": number, "message": "e", "data": number});
|
||||
} else {
|
||||
message["result"] = json!({"nested": [number, null]});
|
||||
}
|
||||
let original = message.to_string();
|
||||
match decode_response(&message).expect("numeric wire shape decodes") {
|
||||
ResponseEnvelope::Success(response) => {
|
||||
assert!(!error);
|
||||
assert_eq!(serde_json::to_value(response.id).unwrap(), sdk_id);
|
||||
assert_eq!(response.result, message["result"]);
|
||||
}
|
||||
ResponseEnvelope::Error(response) => {
|
||||
assert!(error);
|
||||
assert_eq!(serde_json::to_value(response.id).unwrap(), sdk_id);
|
||||
assert_eq!(serde_json::to_value(response.error.code).unwrap(), sdk_code);
|
||||
assert_eq!(response.error.data.as_ref(), Some(&number));
|
||||
}
|
||||
}
|
||||
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
|
||||
assert_eq!(message.to_string(), original);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_error_keeps_optional_id_and_arbitrary_data() {
|
||||
for data in [
|
||||
Value::Null,
|
||||
json!(true),
|
||||
json!(1.0),
|
||||
json!("text"),
|
||||
json!([]),
|
||||
json!({}),
|
||||
] {
|
||||
let message =
|
||||
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": "e", "data": data}});
|
||||
let ResponseEnvelope::Error(error) = decode_response(&message).unwrap() else {
|
||||
panic!("error must retain its SDK variant");
|
||||
};
|
||||
assert_eq!(error.id, None);
|
||||
// SDK Option<Value> maps explicit null to None; classification never rewrites the wire.
|
||||
assert_eq!(
|
||||
error.error.data,
|
||||
if data.is_null() { None } else { Some(data) }
|
||||
);
|
||||
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! #107 generic dispatch: existing wire GREEN precedes independent SDK RED assertions.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, atomic::Ordering};
|
||||
#[path = "rmcp_dispatch_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::*;
|
||||
|
||||
async fn success_control() -> Vec<[usize; 2]> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = prepared(&h, revision).await;
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for id in [
|
||||
json!("dispatch/Ю"),
|
||||
json!(18446744073709551615u64),
|
||||
json!(3.25),
|
||||
] {
|
||||
for method in ["tools/list", "ping"] {
|
||||
let mut message = payload(revision, method, id.clone());
|
||||
// Legacy params remain absent; modern identity metadata remains mandatory.
|
||||
message["extension"] = json!({"future":[null,true]});
|
||||
message["result"] = json!({"ignored":true});
|
||||
message["error"] = json!({"ignored":"not an error envelope"});
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let response = request(&h, revision, session.as_deref(), accept, message)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["jsonrpc"], "2.0");
|
||||
assert_eq!(wire["id"], id, "lossless response correlation");
|
||||
assert!(wire.get("error").is_none(), "{wire}");
|
||||
if method == "tools/list" {
|
||||
assert_eq!(wire["result"]["tools"][0]["name"], TOOL_NAME);
|
||||
assert_eq!(wire["result"]["tools"].as_array().unwrap().len(), 1);
|
||||
} else {
|
||||
let result = if revision == MODERN_REVISION {
|
||||
json!({"protocolVersion":revision,"resultType":"complete"})
|
||||
} else {
|
||||
json!({"protocolVersion":revision})
|
||||
};
|
||||
assert_eq!(wire, json!({"jsonrpc":"2.0","id":id,"result":result}));
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(wire["result"]["resultType"], "complete");
|
||||
assert_eq!(h.sessions.snapshot(), ops, "no modern session access");
|
||||
}
|
||||
assert_deltas(
|
||||
method,
|
||||
entries,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(
|
||||
1,
|
||||
usize::from(revision == MODERN_REVISION),
|
||||
usize::from(revision == LEGACY_REVISION),
|
||||
usize::from(method == "tools/list"),
|
||||
),
|
||||
);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN 24 HTTP requests after legacy handshake / modern discovery; SDK deltas={deltas:?}"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wire_positive_control_json_sse_ids_tolerance_and_routes() {
|
||||
success_control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sdk_envelope_decoded_on_successful_http() {
|
||||
let deltas = success_control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[0]).collect::<Vec<_>>(),
|
||||
vec![1; 24],
|
||||
"successful HTTP must decode a real SDK request envelope"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sdk_envelope_consumed_for_registry_routing_on_successful_http() {
|
||||
let deltas = success_control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[1]).collect::<Vec<_>>(),
|
||||
vec![1; 24],
|
||||
"decoded SDK method/kind must drive registry routing, not decode-and-discard"
|
||||
);
|
||||
}
|
||||
|
||||
async fn notification_control() -> Vec<[usize; 2]> {
|
||||
let h = endpoint().await;
|
||||
let response = request(
|
||||
&h,
|
||||
LEGACY_REVISION,
|
||||
None,
|
||||
"application/json",
|
||||
legacy_initialize(1),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let _ = body(response, false).await;
|
||||
for method in ["notifications/initialized", "unknown/notification"] {
|
||||
let mut wrong_kind = json!({"jsonrpc":"2.0","id":"wrong-kind","method":method});
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = request(
|
||||
&h,
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
"application/json",
|
||||
wrong_kind.clone(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(body(response, false).await["error"]["code"], -32601);
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&session).await.unwrap().initialized);
|
||||
wrong_kind.as_object_mut().unwrap().remove("id");
|
||||
if method.starts_with("unknown") {
|
||||
ack(request(
|
||||
&h,
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
"application/json",
|
||||
wrong_kind,
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap())
|
||||
.await;
|
||||
assert!(!h.sessions.retained(&session).await.unwrap().initialized);
|
||||
}
|
||||
}
|
||||
let before = sdk(&h.counters);
|
||||
ack(request(
|
||||
&h,
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap())
|
||||
.await;
|
||||
assert!(h.sessions.retained(&session).await.unwrap().initialized);
|
||||
let after = sdk(&h.counters);
|
||||
let mut deltas = vec![[after[0] - before[0], after[1] - before[1]]];
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
for method in [
|
||||
"notifications/initialized",
|
||||
"unknown/notification",
|
||||
"tools/call",
|
||||
] {
|
||||
let mut message = payload(MODERN_REVISION, method, json!(1));
|
||||
message.as_object_mut().unwrap().remove("id");
|
||||
let mut req = request(&h, MODERN_REVISION, None, "application/json", message)
|
||||
.build()
|
||||
.unwrap();
|
||||
req.headers_mut().remove("Mcp-Method");
|
||||
req.headers_mut().remove("Mcp-Name");
|
||||
let before = sdk(&h.counters);
|
||||
ack(reqwest::Client::new().execute(req).await.unwrap()).await;
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
}
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
eprintln!("existing GREEN notification kind/state/early ACK; SDK deltas={deltas:?}");
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_order_and_legacy_registered_kind_wire_control() {
|
||||
notification_control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sdk_notification_kind_consumed_on_successful_http() {
|
||||
assert_eq!(
|
||||
notification_control().await,
|
||||
vec![[1, 1]; 4],
|
||||
"SDK notification variant must drive legacy handshake / modern early ACK"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejection_controls_never_enter_service_or_outbound() {
|
||||
let h = endpoint().await;
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = prepared(&h, revision).await;
|
||||
let base = payload(revision, "tools/list", json!("reject"));
|
||||
let mut malformed = base.clone();
|
||||
malformed["jsonrpc"] = json!("1.0");
|
||||
let mut bad_params = base.clone();
|
||||
bad_params["params"] = json!([]);
|
||||
let mut bad_meta = base.clone();
|
||||
bad_meta["params"] = json!({"_meta":false});
|
||||
let unknown = payload(revision, "unknown/request", json!("reject"));
|
||||
let wrong_era = payload(
|
||||
revision,
|
||||
if revision == MODERN_REVISION {
|
||||
"initialize"
|
||||
} else {
|
||||
"server/discover"
|
||||
},
|
||||
json!("reject"),
|
||||
);
|
||||
for (message, status, code) in [
|
||||
(malformed, 400, -32600),
|
||||
(bad_params, 400, -32600),
|
||||
(bad_meta, 400, -32020),
|
||||
(
|
||||
unknown,
|
||||
if revision == MODERN_REVISION {
|
||||
404
|
||||
} else {
|
||||
200
|
||||
},
|
||||
-32601,
|
||||
),
|
||||
(
|
||||
wrong_era,
|
||||
if revision == MODERN_REVISION {
|
||||
404
|
||||
} else {
|
||||
200
|
||||
},
|
||||
-32601,
|
||||
),
|
||||
] {
|
||||
let entries = h.counters.snapshot();
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = request(
|
||||
&h,
|
||||
revision,
|
||||
session.as_deref(),
|
||||
"application/json",
|
||||
message.clone(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status().as_u16(), status, "{revision} {message}");
|
||||
let wire = body(response, false).await;
|
||||
assert_eq!(wire["error"]["code"], code, "{revision} {message}: {wire}");
|
||||
assert!(wire.get("result").is_none());
|
||||
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (header, value) in [("Mcp-Method", "ping"), ("Mcp-Name", "wrong-tool")] {
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let message = json!({"jsonrpc":"2.0","id":"headers","method":"tools/call","params":{"name":TOOL_NAME,"arguments":{"email":"dispatch@example.com"},"_meta":modern_meta()}});
|
||||
let response = request(&h, MODERN_REVISION, None, "application/json", message)
|
||||
.header(header, value)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
assert!(body(response, false).await.get("error").is_some());
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = request(
|
||||
&h,
|
||||
"2099-01-01",
|
||||
None,
|
||||
"application/json",
|
||||
payload(LEGACY_REVISION, "tools/list", json!(1)),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
assert!(body(response, false).await.get("error").is_some());
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observer_independent_positive_control() {
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
super::sdk_dispatch_envelope_decoded();
|
||||
super::sdk_dispatch_envelope_consumed();
|
||||
assert_eq!(sdk(&a), [0, 0]);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
super::sdk_dispatch_envelope_decoded();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
super::sdk_dispatch_envelope_consumed();
|
||||
})
|
||||
);
|
||||
assert_eq!(sdk(&a), [1, 0]);
|
||||
assert_eq!(sdk(&b), [0, 1]);
|
||||
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
assert_eq!(b.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Narrow HTTP helpers; all app/auth/catalog/upstream fixtures remain shared.
|
||||
use super::*;
|
||||
|
||||
pub(super) async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("dispatch_owner", "t_e862066c").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
pub(super) fn sdk(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_dispatch_decoded(), c.sdk_dispatch_consumed()]
|
||||
}
|
||||
|
||||
pub(super) fn payload(revision: &str, method: &str, id: Value) -> Value {
|
||||
let mut message = json!({"jsonrpc":"2.0","id":id,"method":method});
|
||||
if revision == MODERN_REVISION {
|
||||
message["params"] = json!({"_meta":modern_meta()});
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
pub(super) fn request(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
accept: &str,
|
||||
message: Value,
|
||||
) -> reqwest::RequestBuilder {
|
||||
h.request(revision, session, &h.key, accept, message)
|
||||
.header("x-request-id", "dispatch-atdd")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn body(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.headers()["x-request-id"], "dispatch-atdd");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
assert!(
|
||||
response.headers()["content-type"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with(if sse {
|
||||
"text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
})
|
||||
);
|
||||
let raw = tokio::time::timeout(std::time::Duration::from_secs(6), response.text())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
if sse {
|
||||
let frames: Vec<Value> = raw
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("data:"))
|
||||
.map(|l| serde_json::from_str(l.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "one terminal SSE frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn ack(response: reqwest::Response) {
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
pub(super) async fn prepared(h: &Endpoint, revision: &str) -> Option<String> {
|
||||
if revision == LEGACY_REVISION {
|
||||
return h.session(revision).await;
|
||||
}
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = request(
|
||||
h,
|
||||
revision,
|
||||
None,
|
||||
"application/json",
|
||||
payload(revision, "server/discover", json!(1)),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
let wire = body(response, false).await;
|
||||
assert_eq!(
|
||||
wire["result"]["supportedVersions"],
|
||||
json!([MODERN_REVISION, LEGACY_REVISION])
|
||||
);
|
||||
assert_eq!(wire["result"]["resultType"], "complete");
|
||||
assert!(wire.get("error").is_none(), "{wire}");
|
||||
assert_eq!(h.sessions.snapshot(), ops);
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Initialized HTTP transition against the existing PostgreSQL store, not an SDK session manager.
|
||||
use super::*;
|
||||
use crate::session::{PostgresTransportSessionStore, TransportSessionStore};
|
||||
use crate::session::{SessionState, SessionStoreError};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
struct FaultStore {
|
||||
inner: PostgresTransportSessionStore,
|
||||
fail_get: AtomicBool,
|
||||
fail_mark: AtomicBool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for FaultStore {
|
||||
async fn create(
|
||||
&self,
|
||||
revision: &str,
|
||||
workspace: &str,
|
||||
agent: &str,
|
||||
elicitation: bool,
|
||||
now: OffsetDateTime,
|
||||
expires: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
self.inner
|
||||
.create(revision, workspace, agent, elicitation, now, expires)
|
||||
.await
|
||||
}
|
||||
async fn get(&self, id: &str) -> Result<Option<SessionState>, SessionStoreError> {
|
||||
if self.fail_get.load(Ordering::SeqCst) {
|
||||
return Err(SessionStoreError {
|
||||
details: "test read failure".into(),
|
||||
});
|
||||
}
|
||||
self.inner.get(id).await
|
||||
}
|
||||
async fn mark_initialized(
|
||||
&self,
|
||||
id: &str,
|
||||
now: OffsetDateTime,
|
||||
) -> Result<bool, SessionStoreError> {
|
||||
if self.fail_mark.load(Ordering::SeqCst) {
|
||||
return Err(SessionStoreError {
|
||||
details: "test mark failure".into(),
|
||||
});
|
||||
}
|
||||
self.inner.mark_initialized(id, now).await
|
||||
}
|
||||
async fn delete(&self, id: &str) -> Result<bool, SessionStoreError> {
|
||||
self.inner.delete(id).await
|
||||
}
|
||||
async fn cleanup_expired(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.cleanup_expired(now).await
|
||||
}
|
||||
async fn active_count(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.active_count(now).await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_durable_transition_reconnect_and_store_failures() {
|
||||
crank_test_support::postgres_schema_url_for_task("initialized_durable", "t_9c033310").await;
|
||||
let registry = test_registry().await;
|
||||
let pool = registry.pool().clone();
|
||||
let store = Arc::new(FaultStore {
|
||||
inner: PostgresTransportSessionStore::from_pool(pool.clone())
|
||||
.await
|
||||
.unwrap(),
|
||||
fail_get: AtomicBool::new(false),
|
||||
fail_mark: AtomicBool::new(false),
|
||||
});
|
||||
let h = Endpoint::started_with_store(Some(store.clone())).await;
|
||||
let response = post(&h, None, "application/json", legacy_initialize(80)).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let id = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let before = store.get(&id).await.unwrap().unwrap();
|
||||
assert!(!before.initialized);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(sdk(&h.counters), [1, 1]);
|
||||
let restarted = PostgresTransportSessionStore::from_pool(pool.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let after = restarted.get(&id).await.unwrap().unwrap();
|
||||
assert!(after.initialized);
|
||||
assert_eq!(after.id, before.id);
|
||||
assert_eq!(after.workspace_slug, before.workspace_slug);
|
||||
assert_eq!(after.agent_slug, before.agent_slug);
|
||||
assert_eq!(after.protocol_version, before.protocol_version);
|
||||
assert_eq!(after.created_at, before.created_at);
|
||||
assert_eq!(after.expires_at, before.expires_at);
|
||||
assert_eq!(after.supports_elicitation, before.supports_elicitation);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","id":81,"method":"ping"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert!(body(response, false).await.get("error").is_none());
|
||||
|
||||
let pending = store
|
||||
.create(
|
||||
LEGACY_REVISION,
|
||||
WORKSPACE_SLUG,
|
||||
AGENT_SLUG,
|
||||
false,
|
||||
OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
store.fail_mark.store(true, Ordering::SeqCst);
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&pending),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 500);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(sdk(&h.counters), [counts[0] + 1, counts[1] + 1]);
|
||||
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
|
||||
store.fail_mark.store(false, Ordering::SeqCst);
|
||||
|
||||
// Fail reads without touching registry/auth tables; admission must stop before the SDK.
|
||||
store.fail_get.store(true, Ordering::SeqCst);
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&pending),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 500);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
store.fail_get.store(false, Ordering::SeqCst);
|
||||
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_foreign_and_revision_guards_leave_state_untouched() {
|
||||
let h = endpoint().await;
|
||||
for (revision, workspace, agent) in [
|
||||
(LEGACY_REVISION, "foreign-workspace", AGENT_SLUG),
|
||||
(LEGACY_REVISION, WORKSPACE_SLUG, "foreign-agent"),
|
||||
("2024-11-05", WORKSPACE_SLUG, AGENT_SLUG),
|
||||
(MODERN_REVISION, WORKSPACE_SLUG, AGENT_SLUG),
|
||||
] {
|
||||
let id = h
|
||||
.sessions
|
||||
.create(
|
||||
revision,
|
||||
workspace,
|
||||
agent,
|
||||
false,
|
||||
OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let state = h.sessions.retained(&id).await.unwrap();
|
||||
let ops = h.sessions.snapshot();
|
||||
let counts = sdk(&h.counters);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
if workspace != WORKSPACE_SLUG || agent != AGENT_SLUG {
|
||||
404
|
||||
} else {
|
||||
400
|
||||
}
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), counts[1]);
|
||||
if workspace == WORKSPACE_SLUG && agent == AGENT_SLUG {
|
||||
assert_eq!(h.counters.sdk_initialized_decoded(), counts[0]);
|
||||
}
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert_eq!(h.sessions.retained(&id).await.unwrap(), state);
|
||||
}
|
||||
let id = initialize(&h, "application/json").await;
|
||||
let counts = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.header("MCP-Session-Id", "conflicting-session")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
h.registry
|
||||
.revoke_platform_api_key_for_agent(
|
||||
&workspace_id(),
|
||||
&agent_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_progress_other"),
|
||||
&OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let counts = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&id),
|
||||
&h.other_key,
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 401);
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
assert_eq!(h.sessions.snapshot().create, ops.create);
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! #107 initialized: real HTTP wire control, independent SDK decode and consumption oracles.
|
||||
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};
|
||||
|
||||
#[path = "rmcp_initialized_durable_tests.rs"]
|
||||
mod durable;
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("initialized_owner", "t_9c033310").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
fn sdk(c: &CounterSet) -> [usize; 2] {
|
||||
[c.sdk_initialized_decoded(), c.sdk_initialized_consumed()]
|
||||
}
|
||||
|
||||
async fn post(
|
||||
h: &Endpoint,
|
||||
session: Option<&str>,
|
||||
accept: &str,
|
||||
payload: Value,
|
||||
) -> reqwest::Response {
|
||||
h.request(LEGACY_REVISION, session, &h.key, accept, payload)
|
||||
.header("x-request-id", "initialized-atdd")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn correlation(response: &reqwest::Response) {
|
||||
assert_eq!(response.headers()["x-request-id"], "initialized-atdd");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
}
|
||||
|
||||
async fn body(response: reqwest::Response, sse: bool) -> Value {
|
||||
correlation(&response);
|
||||
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(|l| l.strip_prefix("data:"))
|
||||
.map(|l| serde_json::from_str(l.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "one terminal SSE frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
async fn initialize(h: &Endpoint, accept: &str) -> String {
|
||||
let response = post(h, None, accept, legacy_initialize(71)).await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
let id = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["id"], 71);
|
||||
assert_eq!(wire["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
assert!(wire.get("error").is_none());
|
||||
let state = h.sessions.retained(&id).await.expect("retained session");
|
||||
assert!(!state.initialized);
|
||||
assert_eq!(state.workspace_slug, WORKSPACE_SLUG);
|
||||
assert_eq!(state.agent_slug, AGENT_SLUG);
|
||||
id
|
||||
}
|
||||
|
||||
async fn control() -> Vec<[usize; 2]> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for params in [
|
||||
None,
|
||||
Some(json!({})),
|
||||
Some(json!({"ignored":[null,true],
|
||||
"protocolVersion":false,"capabilities":42,"_meta":{"future":[]}})),
|
||||
] {
|
||||
let id = initialize(&h, accept).await;
|
||||
let untouched = initialize(&h, "application/json").await;
|
||||
let before_state = h.sessions.retained(&id).await.unwrap();
|
||||
let mut notification = json!({"jsonrpc":"2.0","method":"notifications/initialized",
|
||||
"extension":{"future":[null,42]}});
|
||||
if let Some(params) = params {
|
||||
notification["params"] = params;
|
||||
}
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let admission = h.counters.snapshot();
|
||||
let response = post(&h, Some(&id), accept, notification.clone()).await;
|
||||
assert_eq!(response.status(), 202);
|
||||
correlation(&response);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_session_ops(
|
||||
"initialized",
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 2,
|
||||
create: 0,
|
||||
mark_initialized: 1,
|
||||
},
|
||||
);
|
||||
assert_deltas(
|
||||
"initialized",
|
||||
admission,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(1, 0, 1, 0),
|
||||
);
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push([after[0] - before[0], after[1] - before[1]]);
|
||||
let state = h.sessions.retained(&id).await.unwrap();
|
||||
assert!(state.initialized);
|
||||
assert_eq!(state.id, before_state.id);
|
||||
assert_eq!(state.workspace_slug, before_state.workspace_slug);
|
||||
assert_eq!(state.agent_slug, before_state.agent_slug);
|
||||
assert_eq!(state.protocol_version, before_state.protocol_version);
|
||||
assert_eq!(state.created_at, before_state.created_at);
|
||||
assert_eq!(state.expires_at, before_state.expires_at);
|
||||
assert_eq!(
|
||||
state.supports_elicitation,
|
||||
before_state.supports_elicitation
|
||||
);
|
||||
assert!(state.updated_at >= before_state.updated_at);
|
||||
assert!(!h.sessions.retained(&untouched).await.unwrap().initialized);
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&id),
|
||||
accept,
|
||||
json!({"jsonrpc":"2.0","id":"tools/Ю","method":"tools/list"}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
let wire = body(response, accept.starts_with("text/event-stream")).await;
|
||||
assert_eq!(wire["id"], "tools/Ю");
|
||||
assert!(wire.get("error").is_none());
|
||||
assert_eq!(wire["result"]["tools"][0]["name"], TOOL_NAME);
|
||||
eprintln!(
|
||||
"existing GREEN initialize -> initialized -> tools/list accept={accept} notification={notification}; SDK delta={:?}",
|
||||
deltas.last().unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
deltas
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_wire_handshake_tolerance_and_scoped_state() {
|
||||
control().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_sdk_decoded_on_real_http_handshake() {
|
||||
let deltas = control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[0]).collect::<Vec<_>>(),
|
||||
vec![1; 6],
|
||||
"real HTTP initialized must decode the SDK InitializedNotification"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_sdk_variant_consumed_by_session_transition() {
|
||||
let deltas = control().await;
|
||||
assert_eq!(
|
||||
deltas.iter().map(|d| d[1]).collect::<Vec<_>>(),
|
||||
vec![1; 6],
|
||||
"matched ClientNotification variant must drive the real scoped session mutation, not just decode"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_admission_and_wrong_kind_never_mutate_or_consume() {
|
||||
let h = endpoint().await;
|
||||
let id = initialize(&h, "application/json").await;
|
||||
let mut wrong_initialize = legacy_initialize(72);
|
||||
wrong_initialize.as_object_mut().unwrap().remove("id");
|
||||
let mut wrong_initialized = initialized_notification();
|
||||
wrong_initialized["id"] = json!(73);
|
||||
let mut cases = vec![
|
||||
(wrong_initialize, 202, None),
|
||||
(wrong_initialized, 200, Some(-32601)),
|
||||
];
|
||||
for params in [json!(null), json!(true), json!(42), json!("bad"), json!([])] {
|
||||
cases.push((
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":params}),
|
||||
400,
|
||||
Some(-32600),
|
||||
));
|
||||
}
|
||||
for meta in [
|
||||
json!(null),
|
||||
json!(false),
|
||||
json!(42),
|
||||
json!("bad"),
|
||||
json!([]),
|
||||
] {
|
||||
cases.push((
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":meta}}),
|
||||
400,
|
||||
Some(-32020),
|
||||
));
|
||||
}
|
||||
cases.push((
|
||||
json!({"jsonrpc":"1.0","method":"notifications/initialized"}),
|
||||
400,
|
||||
Some(-32600),
|
||||
));
|
||||
for (payload, status, code) in cases {
|
||||
let ops = h.sessions.snapshot();
|
||||
let before = sdk(&h.counters);
|
||||
let response = post(&h, Some(&id), "application/json", payload.clone()).await;
|
||||
assert_eq!(response.status().as_u16(), status, "{payload}");
|
||||
if let Some(code) = code {
|
||||
let wire = body(response, false).await;
|
||||
assert_eq!(wire["error"]["code"], code, "{payload}: {wire}");
|
||||
assert!(wire.get("result").is_none());
|
||||
} else {
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
}
|
||||
let after = h.sessions.snapshot();
|
||||
assert_eq!(after.create, ops.create);
|
||||
assert_eq!(after.mark_initialized, ops.mark_initialized);
|
||||
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
|
||||
assert_eq!(
|
||||
sdk(&h.counters),
|
||||
before,
|
||||
"rejected before SDK decode/consume: {payload}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_missing_unknown_sessions_and_modern_never_consume() {
|
||||
let h = endpoint().await;
|
||||
for (session, status) in [(None, 400), (Some("unknown-session"), 404)] {
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = post(&h, session, "application/json", initialized_notification()).await;
|
||||
assert_eq!(response.status().as_u16(), status);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), 0);
|
||||
}
|
||||
let ops = h.sessions.snapshot();
|
||||
let response = h.request(MODERN_REVISION, None, &h.key, "application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":modern_meta()}}))
|
||||
.send().await.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(
|
||||
h.sessions.snapshot(),
|
||||
ops,
|
||||
"modern signal never accesses storage"
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_consumed(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_observer_independent_positive_control() {
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
let notification: rmcp::model::InitializedNotification =
|
||||
serde_json::from_value(json!({"method":"notifications/initialized"})).unwrap();
|
||||
super::sdk_initialized_notification_decoded(¬ification);
|
||||
super::sdk_initialized_notification_consumed(¬ification);
|
||||
assert_eq!(sdk(&a), [0, 0]);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
super::sdk_initialized_notification_decoded(¬ification);
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
super::sdk_initialized_notification_consumed(¬ification);
|
||||
})
|
||||
);
|
||||
assert_eq!(sdk(&a), [1, 0]);
|
||||
assert_eq!(sdk(&b), [0, 1], "decode alone never proves consumption");
|
||||
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
assert_eq!(b.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! #107 ping: existing wire GREEN is independent from the SDK execution oracle.
|
||||
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};
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("ping_owner", "t_83746dc7").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
|
||||
fn ping(revision: &str, extended: bool) -> Value {
|
||||
let mut payload = json!({"jsonrpc":"2.0","id":"ping/Ю","method":"ping"});
|
||||
if revision == MODERN_REVISION || extended {
|
||||
payload["params"] = json!({"_meta":if revision == MODERN_REVISION {
|
||||
modern_meta()
|
||||
} else { json!({}) }});
|
||||
}
|
||||
if extended {
|
||||
payload["params"]["ignored"] = json!([null, {"future":true}]);
|
||||
payload["params"]["_meta"]["future"] = json!(42);
|
||||
payload["extension"] = json!({"nested":[false]});
|
||||
}
|
||||
payload
|
||||
}
|
||||
|
||||
async fn wire_body(response: reqwest::Response, sse: bool) -> Value {
|
||||
assert_eq!(response.headers()["x-request-id"], "ping-atdd");
|
||||
assert_eq!(
|
||||
response.headers()["x-trace-id"],
|
||||
"11111111111111111111111111111111"
|
||||
);
|
||||
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(|line| serde_json::from_str(line.trim()).unwrap())
|
||||
.collect();
|
||||
assert_eq!(frames.len(), 1, "one terminal frame: {raw}");
|
||||
frames.into_iter().next().unwrap()
|
||||
} else {
|
||||
serde_json::from_str(&raw).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn correlated(request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
|
||||
request.header("x-request-id", "ping-atdd").header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
}
|
||||
|
||||
async fn success_control(revision: &str) -> Vec<(usize, usize)> {
|
||||
let h = endpoint().await;
|
||||
// The existing fixture performs real initialize -> initialized for legacy only.
|
||||
let session = h.session(revision).await;
|
||||
let mut sdk = vec![];
|
||||
for (accept, extended) in [
|
||||
("application/json", false),
|
||||
("text/event-stream, application/json", true),
|
||||
] {
|
||||
let counters = h.counters.snapshot();
|
||||
let ops = h.sessions.snapshot();
|
||||
let before = (h.counters.sdk_ping_request(), h.counters.sdk_ping_result());
|
||||
let response = correlated(h.request(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
&h.key,
|
||||
accept,
|
||||
ping(revision, extended),
|
||||
))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
let wire = wire_body(response, accept.starts_with("text/event-stream")).await;
|
||||
let result = if revision == MODERN_REVISION {
|
||||
json!({"protocolVersion":revision,"resultType":"complete"})
|
||||
} else {
|
||||
json!({"protocolVersion":revision})
|
||||
};
|
||||
assert_eq!(wire, json!({"jsonrpc":"2.0","id":"ping/Ю","result":result}));
|
||||
assert_deltas(
|
||||
"ping",
|
||||
counters,
|
||||
h.counters.snapshot(),
|
||||
Snapshot::new(
|
||||
1,
|
||||
usize::from(revision == MODERN_REVISION),
|
||||
usize::from(revision == LEGACY_REVISION),
|
||||
0,
|
||||
),
|
||||
);
|
||||
assert_session_ops(
|
||||
"ping",
|
||||
ops,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 2 * usize::from(revision == LEGACY_REVISION),
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
sdk.push((
|
||||
h.counters.sdk_ping_request() - before.0,
|
||||
h.counters.sdk_ping_result() - before.1,
|
||||
));
|
||||
eprintln!(
|
||||
"existing GREEN ping revision={revision} accept={accept} extended={extended}; SDK delta={:?}",
|
||||
sdk.last().unwrap()
|
||||
);
|
||||
}
|
||||
sdk
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_wire_json_sse_tolerance_and_session_contract() {
|
||||
success_control(LEGACY_REVISION).await;
|
||||
success_control(MODERN_REVISION).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_sdk_legacy_request_and_result() {
|
||||
assert_eq!(
|
||||
success_control(LEGACY_REVISION).await,
|
||||
vec![(1, 1); 2],
|
||||
"successful legacy HTTP ping must consume SDK request and serialize SDK result"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_sdk_modern_request_and_result() {
|
||||
assert_eq!(
|
||||
success_control(MODERN_REVISION).await,
|
||||
vec![(1, 1); 2],
|
||||
"successful stateless HTTP ping must consume SDK request and serialize SDK result"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_guards_never_enter_sdk() {
|
||||
let h = endpoint().await;
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let mut payload = ping(revision, true);
|
||||
if revision == MODERN_REVISION {
|
||||
payload["params"]["_meta"] = Value::Null;
|
||||
}
|
||||
let response = correlated(h.request(revision, None, &h.key, "application/json", payload))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400);
|
||||
if revision == LEGACY_REVISION {
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
} else {
|
||||
let wire = wire_body(response, false).await;
|
||||
assert_eq!(wire["id"], "ping/Ю");
|
||||
assert_eq!(wire["error"]["code"], -32020);
|
||||
assert!(wire.get("result").is_none());
|
||||
}
|
||||
assert_eq!(
|
||||
(h.counters.sdk_ping_request(), h.counters.sdk_ping_result()),
|
||||
(0, 0)
|
||||
);
|
||||
eprintln!("existing GREEN pre-seam guard revision={revision}; SDK=(0,0)");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ping_observer_positive_control() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
let request: rmcp::model::PingRequest =
|
||||
serde_json::from_value(json!({"method":"ping"})).unwrap();
|
||||
observe(c.clone(), async {
|
||||
super::sdk_ping_request_consumed(&request);
|
||||
assert_eq!((c.sdk_ping_request(), c.sdk_ping_result()), (1, 0));
|
||||
super::sdk_ping_result_serialized();
|
||||
assert_eq!((c.sdk_ping_request(), c.sdk_ping_result()), (1, 1));
|
||||
})
|
||||
.await;
|
||||
super::sdk_ping_request_consumed(&request);
|
||||
super::sdk_ping_result_serialized();
|
||||
observe(Arc::new(CounterSet::default()), async {
|
||||
super::sdk_ping_request_consumed(&request);
|
||||
super::sdk_ping_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
(c.sdk_ping_request(), c.sdk_ping_result()),
|
||||
(1, 1),
|
||||
"scope isolation and out-of-scope no-op"
|
||||
);
|
||||
assert_eq!(c.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -26,6 +26,9 @@ impl Drop for Endpoint {
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
Self::started_with_store(None).await
|
||||
}
|
||||
pub async fn started_with_store(store: Option<crate::session::SharedSessionStore>) -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("progress_owner", "t_d65dd129").await;
|
||||
let registry = test_registry().await;
|
||||
let gate = Arc::new(Semaphore::new(0));
|
||||
@@ -103,7 +106,7 @@ impl Endpoint {
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
sessions.clone(),
|
||||
store.unwrap_or_else(|| sessions.clone()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let scope = counters.clone();
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
//! #107 inbound responses: wire compatibility and independent SDK execution oracles.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::{CounterSet, Snapshot, observe, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, atomic::Ordering};
|
||||
|
||||
async fn endpoint() -> Endpoint {
|
||||
crank_test_support::postgres_schema_url_for_task("response_owner", "t_d427ee76").await;
|
||||
Endpoint::started().await
|
||||
}
|
||||
fn sdk(c: &CounterSet) -> [usize; 4] {
|
||||
[
|
||||
c.sdk_inbound_response_decoded(),
|
||||
c.sdk_inbound_error_decoded(),
|
||||
c.sdk_inbound_response_consumed(),
|
||||
c.sdk_inbound_error_consumed(),
|
||||
]
|
||||
}
|
||||
fn request(
|
||||
h: &Endpoint,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
accept: &str,
|
||||
raw: &str,
|
||||
) -> reqwest::RequestBuilder {
|
||||
// Reuse the HTTP fixture without its request-only modern method/name headers.
|
||||
let mut req = h
|
||||
.request(LEGACY_REVISION, session, &h.key, accept, json!({}))
|
||||
.header("x-request-id", "response-atdd")
|
||||
.body(raw.to_owned())
|
||||
.build()
|
||||
.unwrap();
|
||||
req.headers_mut()
|
||||
.insert("MCP-Protocol-Version", revision.parse().unwrap());
|
||||
reqwest::RequestBuilder::from_parts(reqwest::Client::new(), req)
|
||||
}
|
||||
async fn ack(response: reqwest::Response) {
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.headers().get("content-type").is_none());
|
||||
assert!(response.headers().get("MCP-Session-Id").is_none());
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
}
|
||||
async fn no_effects(h: &Endpoint, ops: SessionOps, entries: Snapshot) {
|
||||
assert_eq!(
|
||||
h.sessions.snapshot(),
|
||||
ops,
|
||||
"response ACK must not access sessions"
|
||||
);
|
||||
let after = h.counters.snapshot();
|
||||
assert_eq!(
|
||||
(after.era_modern, after.era_legacy, after.tools_service),
|
||||
(
|
||||
entries.era_modern,
|
||||
entries.era_legacy,
|
||||
entries.tools_service
|
||||
)
|
||||
);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 0);
|
||||
assert!(
|
||||
h.history("response-atdd").await.is_empty(),
|
||||
"no domain invocation"
|
||||
);
|
||||
}
|
||||
async fn success_control(error: bool) -> Vec<[usize; 4]> {
|
||||
let h = endpoint().await;
|
||||
let mut deltas = vec![];
|
||||
let numbers = [
|
||||
"-9223372036854775808",
|
||||
"9223372036854775807",
|
||||
"18446744073709551615",
|
||||
"3.25",
|
||||
"1.0",
|
||||
"-0.0",
|
||||
"1.7976931348623157e308",
|
||||
"-1.7976931348623157e308",
|
||||
"5e-324",
|
||||
];
|
||||
let mut ids = vec!["\"reply/Ю\""];
|
||||
ids.extend(numbers);
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for session in [None, Some("nonexistent-response-session")] {
|
||||
for (index, id) in ids.iter().enumerate() {
|
||||
let messages = if error {
|
||||
let code = numbers[index % numbers.len()];
|
||||
let data = [
|
||||
"null",
|
||||
"true",
|
||||
"3.25",
|
||||
"\"text\"",
|
||||
"[]",
|
||||
"{}",
|
||||
"[null,true,{\"nested\":1}]",
|
||||
][index % 7];
|
||||
vec![
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"error":{{"code":{code},"message":"failed","data":{data}}},"params":false,"extension":[]}}"#
|
||||
),
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","error":{{"code":{code},"message":"failed"}},"params":{{"_meta":false}}}}"#
|
||||
),
|
||||
]
|
||||
} else {
|
||||
vec![format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"result":{{"arbitrary":[null,true,3]}},"params":false,"extension":[]}}"#
|
||||
)]
|
||||
};
|
||||
for raw in messages {
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
ack(request(&h, revision, session, accept, &raw)
|
||||
.send()
|
||||
.await
|
||||
.unwrap())
|
||||
.await;
|
||||
no_effects(&h, ops, entries).await;
|
||||
let after = sdk(&h.counters);
|
||||
deltas.push(std::array::from_fn(|i| after[i] - before[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("existing wire GREEN error={error}; SDK deltas={deltas:?}");
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn wire_success_and_error_ack_without_session_or_modern_metadata() {
|
||||
success_control(false).await;
|
||||
success_control(true).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn sdk_success_response_decoded_and_consumed_after_http_ack() {
|
||||
let deltas = success_control(false).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [1, 0, 1, 0]),
|
||||
"real SDK success decode/typed variant consumption required; actual={deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn sdk_error_response_decoded_and_consumed_after_http_ack() {
|
||||
let deltas = success_control(true).await;
|
||||
assert!(
|
||||
deltas.iter().all(|d| *d == [0, 1, 0, 1]),
|
||||
"real SDK error decode/typed variant consumption required; actual={deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn malformed_responses_reject_before_sdk_or_effects() {
|
||||
let h = endpoint().await;
|
||||
let mut cases = vec![
|
||||
json!({}),
|
||||
json!({"jsonrpc":"2.0","id":1}),
|
||||
json!({"jsonrpc":"2.0","id":1,"result":{},"error":{"code":1,"message":"x"}}),
|
||||
json!({"jsonrpc":"2.0","result":{}}),
|
||||
json!({"id":1,"result":{}}),
|
||||
json!({"jsonrpc":2,"id":1,"result":{}}),
|
||||
json!({"jsonrpc":"2.0","id":1,"result":3}),
|
||||
json!({"jsonrpc":"2.0","error":{}}),
|
||||
json!({"jsonrpc":"2.0","error":{"code":1,"message":3}}),
|
||||
];
|
||||
for value in [Value::Null, json!(true), json!([]), json!({}), json!("bad")] {
|
||||
for field in ["jsonrpc", "result", "id"] {
|
||||
if (field == "result" && value.is_object()) || (field == "id" && value.is_string()) {
|
||||
continue;
|
||||
}
|
||||
let mut m = json!({"jsonrpc":"2.0","id":1,"result":{}});
|
||||
m[field] = value.clone();
|
||||
cases.push(m);
|
||||
}
|
||||
for field in ["error", "code", "message", "id"] {
|
||||
if (field == "error" && value.is_object())
|
||||
|| (field == "message" && value.is_string())
|
||||
|| (field == "id" && value.is_string())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut m = json!({"jsonrpc":"2.0","id":1,"error":{"code":1,"message":"x"}});
|
||||
if ["code", "message"].contains(&field) {
|
||||
m["error"][field] = value.clone();
|
||||
} else {
|
||||
m[field] = value.clone();
|
||||
}
|
||||
cases.push(m);
|
||||
}
|
||||
}
|
||||
for missing in ["code", "message"] {
|
||||
let mut m = json!({"jsonrpc":"2.0","error":{"code":1,"message":"x"}});
|
||||
m["error"].as_object_mut().unwrap().remove(missing);
|
||||
cases.push(m);
|
||||
}
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for m in &cases {
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let response = request(&h, revision, None, "application/json", &m.to_string())
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 400, "{m}");
|
||||
let wire: Value = response.json().await.unwrap();
|
||||
assert_eq!(wire["error"]["code"], -32600, "{m}: {wire}");
|
||||
assert_eq!(wire["id"], Value::Null);
|
||||
assert!(wire.get("result").is_none());
|
||||
assert_eq!(sdk(&h.counters), before);
|
||||
no_effects(&h, ops, entries).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn admission_guards_precede_response_ack_and_sdk() {
|
||||
let h = endpoint().await;
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for raw in [
|
||||
r#"{"jsonrpc":"2.0","id":1,"result":{}}"#,
|
||||
r#"{"jsonrpc":"2.0","error":{"code":1,"message":"x"}}"#,
|
||||
] {
|
||||
for guard in ["origin", "accept", "ambiguous"] {
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let before = sdk(&h.counters);
|
||||
let mut req = request(&h, revision, None, "application/json", raw)
|
||||
.build()
|
||||
.unwrap();
|
||||
let expected = match guard {
|
||||
"origin" => {
|
||||
req.headers_mut()
|
||||
.insert("origin", "https://evil.example".parse().unwrap());
|
||||
403
|
||||
}
|
||||
"accept" => {
|
||||
req.headers_mut()
|
||||
.insert("accept", "text/plain".parse().unwrap());
|
||||
406
|
||||
}
|
||||
_ => {
|
||||
req.headers_mut()
|
||||
.append("MCP-Session-Id", "one".parse().unwrap());
|
||||
req.headers_mut()
|
||||
.append("MCP-Session-Id", "two".parse().unwrap());
|
||||
400
|
||||
}
|
||||
};
|
||||
let response = reqwest::Client::new().execute(req).await.unwrap();
|
||||
assert_eq!(response.status().as_u16(), expected, "{guard}");
|
||||
let _ = response.bytes().await.unwrap();
|
||||
assert_eq!(sdk(&h.counters), before);
|
||||
no_effects(&h, ops, entries).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn authentication_and_revocation_precede_response_ack() {
|
||||
let h = endpoint().await;
|
||||
let mut statuses = vec![];
|
||||
for revoked in [false, true] {
|
||||
if revoked {
|
||||
h.registry
|
||||
.revoke_platform_api_key(
|
||||
&workspace_id(),
|
||||
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
||||
&time::OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
for raw in [
|
||||
r#"{"jsonrpc":"2.0","id":1,"result":{}}"#,
|
||||
r#"{"jsonrpc":"2.0","error":{"code":1,"message":"x"}}"#,
|
||||
] {
|
||||
let before = sdk(&h.counters);
|
||||
let ops = h.sessions.snapshot();
|
||||
let entries = h.counters.snapshot();
|
||||
let mut req = request(&h, revision, None, "application/json", raw)
|
||||
.build()
|
||||
.unwrap();
|
||||
if !revoked {
|
||||
req.headers_mut().remove("authorization");
|
||||
}
|
||||
let response = reqwest::Client::new().execute(req).await.unwrap();
|
||||
statuses.push(response.status().as_u16());
|
||||
let _ = response.bytes().await.unwrap();
|
||||
assert_eq!(sdk(&h.counters), before);
|
||||
no_effects(&h, ops, entries).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
statuses,
|
||||
vec![401; 8],
|
||||
"missing/revoked credentials must reject before ACK and SDK"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn method_bearing_messages_keep_priority_over_response_fields() {
|
||||
let h = endpoint().await;
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = h.session(revision).await;
|
||||
for notification in [false, true] {
|
||||
let mut m = json!({"jsonrpc":"2.0","method":"ping","id":7,"result":false,"error":[],"extension":null});
|
||||
if notification {
|
||||
m.as_object_mut().unwrap().remove("id");
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
m["params"] = json!({"_meta":modern_meta()});
|
||||
}
|
||||
let before = sdk(&h.counters);
|
||||
let response = h
|
||||
.request(revision, session.as_deref(), &h.key, "application/json", m)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
if notification {
|
||||
ack(response).await;
|
||||
} else {
|
||||
assert_eq!(response.status(), 200);
|
||||
let wire: Value = response.json().await.unwrap();
|
||||
assert_eq!(wire["id"], 7);
|
||||
assert!(wire["result"].is_object());
|
||||
assert!(wire.get("error").is_none());
|
||||
}
|
||||
assert_eq!(sdk(&h.counters), before, "not an inbound response");
|
||||
}
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn observer_positive_control_is_task_scoped_and_independent() {
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
super::sdk_inbound_response_decoded();
|
||||
super::sdk_inbound_error_decoded();
|
||||
super::sdk_inbound_response_consumed();
|
||||
super::sdk_inbound_error_consumed();
|
||||
assert_eq!(sdk(&a), [0; 4]);
|
||||
tokio::join!(
|
||||
observe(a.clone(), async {
|
||||
super::sdk_inbound_response_decoded();
|
||||
super::sdk_inbound_error_consumed();
|
||||
}),
|
||||
observe(b.clone(), async {
|
||||
super::sdk_inbound_error_decoded();
|
||||
super::sdk_inbound_response_consumed();
|
||||
})
|
||||
);
|
||||
assert_eq!(sdk(&a), [1, 0, 0, 1]);
|
||||
assert_eq!(sdk(&b), [0, 1, 1, 0]);
|
||||
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
|
||||
}
|
||||
@@ -49,6 +49,14 @@ Envelopes-срез #107 на базе rc.25/rmcp3.9.0 заменяет handwritt
|
||||
|
||||
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 не завершены.
|
||||
|
||||
Ping-срез #107 на базе rc.28/rmcp3.9.0 подключает обе штатные HTTP ветки к общему `protocol/lifecycle_sdk.rs::ping_result`: проекция уже допущенного метода декодируется в `PingRequest`, его SDK request variant выбирает `ServerResult::empty(())`, а сериализованный SDK результат поступает в прежний JSON/SSE terminal. Удалены два handwritten ping result builder; Crank добавляет прежний `protocolVersion` из legacy session либо modern identity, а modern result projection сохраняется. Игнорируемые params/extensions не получают новых SDK ограничений. Legacy initialized-session guard остаётся перед helper; modern ping не обращается к sessions. Runtime ATDD отдельно подтверждает SDK request/result execution и прежние wire/status/headers/id/correlation обеих revisions; affected regressions проверяют session/admission/method/revocation guards. Generic dispatch, session storage/TTL/reconnect, admission/auth и transport остаются прежними; полный #107, feature qualification и production deployment не завершены.
|
||||
|
||||
Initialized-срез #107 на базе rc.29/rmcp3.9.0 подключает штатный legacy HTTP handshake к `InitializedNotification` и `ClientNotification`: после registry/admission проекция метода декодируется SDK, а matched initialized variant после прежних session/scope guards разрешает существующий durable `mark_initialized`. Игнорируемые params/extensions, 202 с пустым телом, JSON/SSE и modern no-session поведение сохранены; SDK SessionManager не используется. Runtime-тесты отдельно наблюдают decoding и consumption, проверяют PostgreSQL reconnect и отказ store на чтении/записи. Это только lifecycle-срез, не завершение #107.
|
||||
|
||||
Envelope-dispatch-срез #107 на базе rc.30/rmcp3.9.0 подключает обе действующие HTTP ветки `app/dispatch.rs` и `app/legacy_dispatch.rs` к общему `protocol/dispatch_sdk.rs`: после прежних admission/auth guards минимальная проекция декодируется в настоящие `JsonRpcRequest<Value>`/`JsonRpcNotification<Value>`. SDK payload method выбирает прежний `registry::dispatch_decision`, SDK variant определяет request/notification routing вместо повторных raw-JSON predicates. Второй таблицы методов нет; registry остаётся policy gate revisions/capabilities/registered kind. Modern notification ACK по-прежнему предшествует request-only Mcp-Method/Mcp-Name checks и не обращается к sessions/domain. Params и ignored extensions/result/error остаются вне routing projection; SDK-incompatible числовые ID получают только внутренний surrogate, исходные ID/числовая форма остаются в raw message для wire/correlation/cancellation ownership. Для выбранного registry Ping handler typed projection использует canonical ping, сохраняя registered alias semantics. Runtime HTTP ATDD отдельно проверяет SDK decode/consumption и прежний JSON/SSE wire; affected registry/admission, durable initialized/reconnect, progress/cancel и auth guards проверяются без замены storage/transport. Это перенос только generic request/notification envelope routing: domain/generic handler execution, inbound response/error envelopes и их shape validation, session storage/TTL/reconnect, transport и feature qualification остаются вне среза. Полный #107 остаётся open; #108/4.7 и production switch не запускаются.
|
||||
|
||||
Inbound-response-срез #107 на базе rc.31/rmcp3.9.0 подключает no-method ветку общего envelope guard к `protocol/response_sdk.rs`: реальные `JsonRpcResponse<Value>`/`JsonRpcError` определяют response classification и ранний HTTP202 ACK штатного `build_app` POST обеих revisions. Сохранены object-only result без обязательного resultType, exclusivity result/error, optional error id, произвольные data/params/extensions и любые JSON number id/code; только SDK-несовместимые числа получают внутренние surrogates после проверки исходного wire-предиката, raw message не меняется. Заменён handwritten response classifier/error-object parser. Обнаруженный ATDD обход credentials ранним ACK устранён свежей read-авторизацией no-method сообщений до SDK decode; порядок method-bearing запросов не меняется. Origin/Accept/ambiguous carrier checks предшествуют decode/ACK, ACK остаётся до era/session resolution без session/domain вызовов. HTTP wire и SDK decoded/consumed oracles проверяются отдельно. Domain/generic handler execution, session storage/TTL/reconnect, transport и feature qualification остаются вне среза; полный #107 остаётся open, #108/4.7/production не запускаются.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
||||
|
||||
Reference in new issue
Block a user