[skip ci] wip: preserve Hermes crank development checkpoint

Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
Hermes DevOps committed 2026-10-25 08:05:37 +00:00
1 parent 1b6db09bd1
commit 301dce301a
357 files changed
+118831 -5113

No files matched your search

@@ -0,0 +1,619 @@
//! Duplicate-carrier hygiene: conflicting/identical duplicate protocol-version headers, duplicate
//! `Mcp-Name`/method carriers and duplicate session carriers, with the era-correct diagnostic.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
//!
//! Split out of the accepted `carriers` group as the plan's documented alternative: the merged file
//! measured 1018 body lines, above the enforced 1000-line health ceiling.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, DuplicateSessionCarrierEra, LEGACY_REVISION, MODERN_REVISION,
counted_call_params, counted_tool, duplicated_header, endpoint, modern_post,
modern_request_with_params,
};
/// R12: two conflicting `MCP-Protocol-Version` header lines are an ambiguous identity and must be
/// rejected before dispatch instead of silently using the first value. Our policy (recorded for the
/// accepted matrix): conflicting duplicate identity carriers are rejected; identical duplicates carry
/// no ambiguity and are served.
#[tokio::test]
async fn r12_conflicting_duplicate_protocol_version_headers_are_rejected_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(120),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
for order in [
[MODERN_REVISION, LEGACY_REVISION],
[LEGACY_REVISION, MODERN_REVISION],
] {
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.headers(duplicated_header("mcp-protocol-version", order))
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
400,
"conflicting duplicate version headers ({order:?}) must be rejected, not resolved by order"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an ambiguous identity must not reach the upstream"
);
}
#[tokio::test]
async fn r12_identical_duplicate_protocol_version_headers_are_served() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(121),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.headers(duplicated_header(
"mcp-protocol-version",
[MODERN_REVISION, MODERN_REVISION],
))
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
200,
"identical duplicate version headers carry no ambiguity"
);
assert_eq!(fixture.calls.load(Ordering::SeqCst), 1);
}
/// Assert the era-correct structured diagnostic for a single-fault version-carrier rejection.
///
/// Every R28 probe sends a request whose **only** fault is the `MCP-Protocol-Version` carrier: the body
/// carries the complete modern `_meta` identity, the JSON-RPC id and the `Mcp-Method`/`Mcp-Name` headers
/// are valid, and the upstream counter is asserted by each probe. `protocol-era-matrix.md` row 17 requires
/// the era-correct structured error for every malformed carrier (modern shape: `-32020`), and the modern
/// rows 2/5/6 require the same JSON-RPC id plus the `error.data` correlation proven by R6.
///
/// Defect this oracle pins: `resolve_request_identity`
/// (`crates/crank-community-mcp/src/protocol/mod.rs` 511-519) turns both an unreadable/ambiguous header
/// (`Err(status)` from `singleton_header`) and a blank header value into a **bare** `400` with an empty
/// body, so the required JSON-RPC diagnostic is missing on both members of that branch.
fn assert_carrier_rejection_is_structured(
status: u16,
raw: &str,
id: i64,
correlation: &str,
case: &str,
) {
assert_eq!(
status, 400,
"{case}: a malformed carrier must be a safe rejection"
);
assert!(
!raw.trim().is_empty(),
"{case}: matrix row 17 requires the era-correct structured error for a malformed carrier, but \
the response body was empty"
);
let body: Value = serde_json::from_str(raw).unwrap_or_else(|error| {
panic!("{case}: the carrier diagnostic must be JSON-RPC, got {raw:?}: {error}")
});
assert_eq!(
body["jsonrpc"], "2.0",
"{case}: the carrier diagnostic must be a complete JSON-RPC 2.0 envelope, got {body}"
);
assert_eq!(
body["id"],
json!(id),
"{case}: the carrier diagnostic must keep the JSON-RPC request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"{case}: matrix row 17 requires the era-correct structured error (modern shape: -32020), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"{case}: the structured error must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"{case}: the carrier diagnostic must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"{case}: a rejected request must not carry a `result` key at all, got {body}"
);
assert!(
body["result"].is_null(),
"{case}: a rejected request must not carry a result, got {body}"
);
}
/// R28 probe A: a `MCP-Protocol-Version` value the era resolver rejects on its own — empty,
/// whitespace-only or unparsable. Single fault: the carrier value.
async fn assert_modern_carrier_value_is_a_structured_mismatch(value: &str, correlation: &str) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![
("MCP-Protocol-Version", value.to_owned()),
("Mcp-Method", "tools/call".to_owned()),
("Mcp-Name", COUNTED_TOOL_NAME.to_owned()),
];
let message = modern_request_with_params(
Some(130),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, Some(correlation)).await;
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_carrier_rejection_is_structured(
status,
&raw,
130,
correlation,
&format!("version carrier {value:?} ({correlation})"),
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an identity diagnostic must not reach the upstream"
);
}
/// R28: an **empty** `MCP-Protocol-Version` value on an otherwise valid modern request.
#[tokio::test]
async fn r28_modern_empty_protocol_version_header_is_a_structured_mismatch() {
assert_modern_carrier_value_is_a_structured_mismatch("", "r28-empty-carrier").await;
}
/// R28: a **whitespace-only** version value is the same single-fault class as the empty one.
#[tokio::test]
async fn r28_modern_whitespace_protocol_version_header_is_a_structured_mismatch() {
assert_modern_carrier_value_is_a_structured_mismatch(" ", "r28-whitespace-carrier").await;
}
/// R28: an **unparsable** (non-blank) version value. Same row-17 obligation as the blank value, but this
/// one is already resolved by the header/body mismatch branch (`protocol/mod.rs` 543-550), so it is
/// expected **existing GREEN**: it separates the bare-`400` defect from the well-formed-value paths and
/// pins that a malformed carrier must not be answered as `-32022` or as an unknown revision.
#[tokio::test]
async fn r28_modern_malformed_protocol_version_header_is_a_structured_mismatch() {
assert_modern_carrier_value_is_a_structured_mismatch("not-a-version", "r28-malformed-carrier")
.await;
}
/// R28 probe B: two **conflicting** `MCP-Protocol-Version` carriers in one request whose body carries a
/// valid modern identity. The pair cannot be resolved to one era, so `protocol-era-matrix.md` row 17
/// (era-correct structured error) applies to the same `Err(status)` branch as the unreadable value. The
/// duplicate policy itself ("identical duplicates are served") is the accepted R12 record; the matrix has
/// no separate duplicate row and the existing R12 test asserts only the status, so the diagnostic shape is
/// pinned here. Single fault: the ambiguity of the carrier, one order at a time.
async fn assert_conflicting_duplicate_carriers_are_a_structured_mismatch(
order: [&'static str; 2],
correlation: &str,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(131),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation)
.headers(duplicated_header("mcp-protocol-version", order))
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_carrier_rejection_is_structured(
status,
&raw,
131,
correlation,
&format!("conflicting carriers {order:?}"),
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an ambiguous identity must not reach the upstream"
);
}
/// R28: the modern value first, the legacy value second.
#[tokio::test]
async fn r28_modern_conflicting_duplicate_protocol_headers_modern_first_are_a_structured_mismatch()
{
assert_conflicting_duplicate_carriers_are_a_structured_mismatch(
[MODERN_REVISION, LEGACY_REVISION],
"r28-duplicate-modern-first",
)
.await;
}
/// R28: the same conflicting pair in the opposite order — the rejection must not depend on header order.
#[tokio::test]
async fn r28_modern_conflicting_duplicate_protocol_headers_legacy_first_are_a_structured_mismatch()
{
assert_conflicting_duplicate_carriers_are_a_structured_mismatch(
[LEGACY_REVISION, MODERN_REVISION],
"r28-duplicate-legacy-first",
)
.await;
}
/// R28 probe C: an **unreadable** carrier value. HTTP/1.1 allows `obs-text` (bytes `0x80-0xFF`) in a field
/// value, so a non-UTF-8 byte sequence is a real, transferable value that reaches the server and fails
/// `HeaderValue::to_str()` inside `singleton_header` (`transport.rs` 185-190) — the second member of the
/// `Err(status)` branch. Single fault: the carrier value only.
#[tokio::test]
async fn r28_modern_unreadable_protocol_version_header_is_a_structured_mismatch() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(132),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let mut carrier = reqwest::header::HeaderMap::new();
carrier.append(
reqwest::header::HeaderName::from_static("mcp-protocol-version"),
reqwest::header::HeaderValue::from_bytes(&[b'2', 0x30, 0x32, 0x36, 0xf8, 0xfe]).unwrap(),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", "r28-unreadable-carrier")
.headers(carrier)
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_carrier_rejection_is_structured(
status,
&raw,
132,
"r28-unreadable-carrier",
"unreadable version carrier",
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an identity diagnostic must not reach the upstream"
);
}
/// R12 (session carrier half): two conflicting session identifiers are the same ambiguity class and
/// must be rejected instead of resolving to the first value.
#[tokio::test]
async fn r12_conflicting_duplicate_session_headers_are_rejected() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let message = json!({ "jsonrpc": "2.0", "id": 122, "method": "tools/list", "params": {} });
let response = endpoint
.client
.post(&endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.headers(duplicated_header(
"mcp-session-id",
[session.as_str(), "session-that-never-existed"],
))
.header("MCP-Protocol-Version", LEGACY_REVISION)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
400,
"conflicting duplicate session identifiers must be rejected"
);
}
/// Review pass 6 (P3 / matrix rows 16-17): conflicting duplicate `MCP-Session-Id` carriers are
/// rejected in `mcp_post_response` (`app.rs` 820-823) through `transport.rs::singleton_header` with
/// a **bare** `400` and an empty body, before era resolution, envelope validation, rate limiting and
/// any dispatch.
///
/// Row 17 requires the era-correct structured diagnostic for an ambiguous carrier, and the era must
/// be read from the rest of the request, never guessed from the ambiguous value. The duplicate
/// *version*-carrier case already does exactly that
/// (`protocol/mod.rs::malformed_carrier_response` 441-448); this oracle pins the same contract for
/// the session carrier: modern shape → `400` + `-32020` with the request id and correlation, legacy
/// shape → a numeric legacy error that is neither `-32020` nor `-32022`. `GET`/`DELETE` keep their
/// separate lifecycle admission and are deliberately untouched.
async fn assert_duplicate_session_carrier_rejection(
session_values: [&str; 2],
correlation: &str,
id: i64,
era: DuplicateSessionCarrierEra,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let mut request = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation)
.headers(duplicated_header("mcp-session-id", session_values));
let message = match era {
DuplicateSessionCarrierEra::Modern => {
request = request
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME);
modern_request_with_params(
Some(id as u64),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
)
}
DuplicateSessionCarrierEra::Legacy => {
request = request.header("MCP-Protocol-Version", LEGACY_REVISION);
json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": counted_call_params(COUNTED_TOOL_NAME)
})
}
};
let response = request.json(&message).send().await.unwrap();
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"an ambiguous session carrier must be a safe rejection ({correlation}), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"row 17 requires the era-correct structured diagnostic for an ambiguous session carrier \
({correlation}), but the response body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the ambiguous-session diagnostic must be JSON-RPC ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the ambiguous-session diagnostic must be a JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"],
json!(id),
"the ambiguous-session diagnostic must keep the request id ({correlation}), got {body}"
);
match era {
DuplicateSessionCarrierEra::Modern => assert_eq!(
body["error"]["code"],
json!(-32020),
"a request whose dominant identity is modern answers the modern shape ({correlation}), \
got {body}"
),
DuplicateSessionCarrierEra::Legacy => {
assert!(
body["error"]["code"].is_i64(),
"the legacy shape must carry a numeric code ({correlation}), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32020),
"the modern HeaderMismatch code must not be guessed for a legacy-shaped ambiguity \
({correlation}), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32022),
"the modern UnsupportedProtocolVersion code must not be guessed for a legacy-shaped \
ambiguity ({correlation}), got {body}"
);
}
}
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the diagnostic must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the diagnostic must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a result ({correlation}), got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an ambiguous identity must not reach the upstream ({correlation})"
);
}
/// Review pass 6 (P3): the modern request, first header value order.
#[tokio::test]
async fn review6_p3_modern_duplicate_session_carrier_first_order_is_structured() {
assert_duplicate_session_carrier_rejection(
["review6-p3-session-a", "review6-p3-session-b"],
"review6-p3-modern-a-first",
141,
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 6 (P3): the modern request, reversed header value order — the outcome must not depend
/// on which of the two conflicting values comes first.
#[tokio::test]
async fn review6_p3_modern_duplicate_session_carrier_second_order_is_structured() {
assert_duplicate_session_carrier_rejection(
["review6-p3-session-b", "review6-p3-session-a"],
"review6-p3-modern-b-first",
142,
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 6 (P3): the legacy-shaped request, first header value order.
#[tokio::test]
async fn review6_p3_legacy_duplicate_session_carrier_first_order_is_legacy_shaped() {
assert_duplicate_session_carrier_rejection(
["review6-p3-session-a", "review6-p3-session-b"],
"review6-p3-legacy-a-first",
143,
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
/// Review pass 6 (P3): the legacy-shaped request, reversed header value order.
#[tokio::test]
async fn review6_p3_legacy_duplicate_session_carrier_second_order_is_legacy_shaped() {
assert_duplicate_session_carrier_rejection(
["review6-p3-session-b", "review6-p3-session-a"],
"review6-p3-legacy-b-first",
144,
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
@@ -0,0 +1,757 @@
//! JSON-RPC envelope validity: notifications versus requests, invalid/missing envelope fields,
//! request-id correlation of errors and duplicate `mcp method`/`mcp name` carriers.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, LEGACY_REVISION, META_CLIENT_CAPABILITIES, META_CLIENT_INFO,
MODERN_REVISION, UNKNOWN_REVISION, approved_revisions, counted_call_params, counted_tool,
duplicated_header, endpoint, json_body, modern_call_headers, modern_headers, modern_meta,
modern_post, modern_request_with_params, pending_approvals,
};
/// Review pass 6 (P1 / matrix row 4): modern-specific request metadata without **any** version
/// carrier must be rejected as a header-validation failure instead of being admitted as legacy.
///
/// Defect this oracle pins: `resolve_request_identity` (`protocol/mod.rs` 568-642) reads only the
/// `_meta` version field and the `MCP-Protocol-Version` header. A request whose `_meta` carries the
/// modern-specific `clientCapabilities`/`clientInfo` keys but no version at all yields an effective
/// identity of `None`, so it is admitted as `Legacy` (`638-641`) and a **live initialized legacy
/// session** executes it as a legacy `tools/call`. Row 4 requires a rejection before any adapter
/// admission; the modern era defines a header-validation failure as `400` + `-32020`
/// `HeaderMismatch`, the same shape this resolver already emits for a modern identity with a missing
/// version header (`648-653`) and for a missing `_meta` version (`492-497`).
///
/// The probe is repeated once so row 21 (a repeated request has the same outcome and leaves no
/// residual state) is asserted observably, and the counted upstream proves that no legacy outbound
/// call happened.
#[tokio::test]
async fn review6_p1_modern_metadata_without_version_carrier_is_rejected_before_legacy_admission() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let session = initialize_session(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
)
.await;
let headers = vec![("MCP-Session-Id", session.clone())];
let message = modern_request_with_params(
Some(140),
"tools/call",
json!({
"name": COUNTED_TOOL_NAME,
"arguments": { "email": "review6-p1@example.com" },
"_meta": {
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: { "name": "crank-atdd-client", "version": "0.1.0" }
}
}),
);
for attempt in 1..=2 {
let response = modern_post(
&fixture.endpoint,
&headers,
message.clone(),
Some("review6-p1"),
)
.await;
let status = response.status().as_u16();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"attempt {attempt}: a rejected request must not mint a session"
);
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"attempt {attempt}: modern `_meta` without a version carrier must be rejected before \
legacy admission (matrix row 4), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"attempt {attempt}: row 4 requires a structured rejection, but the response body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"attempt {attempt}: the row-4 rejection must be a JSON-RPC envelope, got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"attempt {attempt}: the rejection must be a JSON-RPC 2.0 envelope, got {body}"
);
assert_eq!(
body["id"],
json!(140),
"attempt {attempt}: the rejection must keep the request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"attempt {attempt}: a modern identity without its required version carrier is a \
header-validation failure (matrix row 4), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"attempt {attempt}: the rejection must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!("review6-p1"),
"attempt {attempt}: the rejection must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"attempt {attempt}: a rejected request must not carry a result, got {body}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"modern-specific metadata without a version carrier must not be executed as a legacy request"
);
// Review pass 7 (G3, matrix row 21 valid follow-up): after the repeated rejection the same live
// initialized legacy session must still serve a valid legacy request. This is the narrow
// valid-follow-up half of row 21 — it is not a session-store dump or a full persisted-state
// equality oracle, and it claims no more than "the rejected requests left the session usable".
let follow_up = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 141,
"method": "tools/call",
"params": {
"name": COUNTED_TOOL_NAME,
"arguments": { "email": "review7-p1-follow-up@example.com" }
}
}),
)
.await;
assert!(
follow_up["error"].is_null(),
"a valid legacy follow-up on the same live session must be served, got {follow_up}"
);
assert_eq!(
follow_up["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the valid follow-up must return the published business payload, got {follow_up}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"the valid follow-up must perform exactly one additional outbound call"
);
}
/// R5/R15: a valid modern notification (no `id`) must be acknowledged with exactly `202` and an empty
/// body — not a JSON-RPC result and not an error envelope. Invalid envelopes (e.g. a foreign `id`) are
/// R10's business and are covered separately.
#[tokio::test]
async fn r5_modern_notification_is_not_executed_as_request() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let message = modern_request_with_params(None, "tools/list", json!({}));
let response = modern_post(&endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
202,
"a valid notification is acknowledged with 202"
);
let body = response.text().await.unwrap();
assert!(
body.is_empty(),
"a notification acknowledgement must have an empty body, got {body:?}"
);
}
/// R6: era errors must keep the existing request correlation data.
///
/// Single fault: the unknown revision is carried identically in the header and in the body `_meta`,
/// while the remaining metadata (`clientCapabilities`, `clientInfo`) and `Mcp-Method` stay valid, so the
/// only defect in play is the unsupported revision itself (`-32022`, not a mismatch).
#[tokio::test]
async fn r6_error_data_preserves_request_correlation() {
let endpoint = endpoint().await;
let headers = modern_headers(UNKNOWN_REVISION, "tools/list");
let message = modern_request_with_params(
Some(70),
"tools/list",
json!({ "_meta": modern_meta(UNKNOWN_REVISION) }),
);
let response = modern_post(&endpoint, &headers, message, Some("r6-correlation-check")).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["error"]["code"],
json!(-32022),
"an identically unknown header/body revision is an unsupported-version error, got {body}"
);
let data = &body["error"]["data"];
assert_eq!(
data["requested"],
json!(UNKNOWN_REVISION),
"the requested revision must be reported, got {body}"
);
let mut supported: Vec<String> = data["supported"]
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
supported.sort();
let mut approved = approved_revisions();
approved.sort();
assert_eq!(
supported, approved,
"the supported list must survive alongside the correlation, got {body}"
);
assert_eq!(
data["request_id"],
json!("r6-correlation-check"),
"the unsupported-version error must keep the request correlation, got {body}"
);
}
#[tokio::test]
async fn r6_mismatch_error_data_preserves_request_correlation() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let message = modern_request_with_params(
Some(71),
"tools/list",
json!({ "_meta": modern_meta(LEGACY_REVISION) }),
);
let response = modern_post(&endpoint, &headers, message, Some("r6-mismatch-check")).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
let data = &body["error"]["data"];
assert_eq!(
data["request_id"],
json!("r6-mismatch-check"),
"the mismatch error must keep the request correlation, got {body}"
);
assert!(
data["details"].is_string(),
"the mismatch detail must survive alongside the correlation, got {body}"
);
}
/// R5/R15: a mutating notification (no `id`) must be acknowledged with exactly `202` and an empty body,
/// must not be dispatched and must not reach the upstream.
#[tokio::test]
async fn r5_modern_mutating_notification_is_not_dispatched_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let message =
modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME));
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
202,
"a mutating notification is acknowledged with 202"
);
let body = response.text().await.unwrap();
assert!(
body.is_empty(),
"a notification acknowledgement must have an empty body, got {body:?}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a mutating notification must not perform the outbound request"
);
}
/// R10: a modern request must be a well-formed JSON-RPC request before any tool dispatch. The pinned
/// modern schema types the request `id` as `string | number` (`RequestId`), so a missing or foreign
/// `jsonrpc` field and an object/boolean `id` are invalid requests — the JSON syntax being extractable
/// says nothing about the envelope.
#[tokio::test]
async fn r10_modern_missing_jsonrpc_field_is_rejected_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(110),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message.as_object_mut().unwrap().remove("jsonrpc");
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"a message without the `jsonrpc` field is not a valid JSON-RPC request"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert!(
body["id"].is_null(),
"an undeterminable request id must be reported as null, got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an invalid envelope must not reach the upstream"
);
}
#[tokio::test]
async fn r10_modern_wrong_jsonrpc_version_is_rejected_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(111),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message["jsonrpc"] = json!("1.0");
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0, "got {body}");
}
#[tokio::test]
async fn r10_modern_non_scalar_request_id_is_rejected_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
for foreign_id in [json!({}), json!(true), json!([1, 2])] {
let mut message = modern_request_with_params(
Some(112),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message["id"] = foreign_id.clone();
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"the pinned request id is `string | number`, so {foreign_id} is invalid"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert!(
!body["id"].is_object() && !body["id"].is_boolean() && !body["id"].is_array(),
"the response must not echo an arbitrary id value, got {body}"
);
}
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R10 (approval half): an invalid envelope on an approval-gated operation must neither call the
/// upstream nor create a pending approval request.
#[tokio::test]
async fn r10_modern_invalid_envelope_creates_no_pending_approval() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(113),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message["jsonrpc"] = json!("1.0");
// R21: the persisted registry state is the proof, not the absence of an id in the response body.
let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert!(
!body.to_string().contains("approval_"),
"an invalid envelope must not produce a pending approval, got {body}"
);
let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
assert_eq!(
after, before,
"an invalid envelope must not persist a pending approval request"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an invalid envelope must not perform the outbound request"
);
}
/// R10 (correlation): an invalid envelope must still answer with the request correlation the ingress
/// already established, and the safe response id must stay null.
#[tokio::test]
async fn r10_invalid_envelope_keeps_request_correlation() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(115),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message.as_object_mut().unwrap().remove("jsonrpc");
let response = modern_post(
&fixture.endpoint,
&headers,
message,
Some("r10-envelope-correlation"),
)
.await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert_eq!(
body["error"]["data"]["request_id"],
json!("r10-envelope-correlation"),
"an invalid envelope must keep the ingress correlation, got {body}"
);
assert!(body["id"].is_null(), "got {body}");
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R10 (id null): a present but null id is not a valid request id under the pinned `string | number`
/// contract and must never be acknowledged as a notification — no `202`, no dispatch, no outbound.
#[tokio::test]
async fn r10_null_request_id_is_not_a_notification() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(116),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
message["id"] = Value::Null;
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"a null id must be an invalid request, not a notification acknowledgement"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an invalid envelope must not reach the upstream"
);
}
/// R13: a message without `method` and without `Mcp-Method` currently matches `None == None` and is
/// routed to unknown-method dispatch. It is an invalid request and must be rejected as such, not
/// answered as an unknown method with a `-32601` result.
#[tokio::test]
async fn r13_absent_method_with_valid_modern_identity_is_an_invalid_request() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())];
let message = json!({
"jsonrpc": "2.0",
"id": 130,
"params": { "_meta": modern_meta(MODERN_REVISION) }
});
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"a message without a method is an invalid request, not an unknown method"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert!(
body["result"].is_null(),
"an invalid request must not be answered with a result, got {body}"
);
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn r13_non_string_method_is_an_invalid_request() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())];
let message = json!({
"jsonrpc": "2.0",
"id": 131,
"method": 42,
"params": { "_meta": modern_meta(MODERN_REVISION) }
});
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32600), "got {body}");
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R19: matrix row 18 — notifications do not inherit the mandatory request headers. A valid modern
/// notification (no id, valid `_meta`, valid protocol identity) without `Mcp-Method` must be
/// acknowledged with `202` and an empty body, and must not reach the upstream. The request case with a
/// missing method header stays rejected (`r7_modern_missing_mcp_method_is_rejected`).
#[tokio::test]
async fn r19_modern_notification_without_mcp_method_is_acknowledged() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())];
let message =
modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME));
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
202,
"a notification does not carry the mandatory request headers"
);
let body = response.text().await.unwrap();
assert!(
body.is_empty(),
"a notification acknowledgement must have an empty body, got {body:?}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a notification must not perform the outbound request"
);
}
/// R22: a conflicting duplicate `Mcp-Method` is an ambiguous method declaration and must be rejected
/// with `400 -32020`, the preserved correlation and no outbound request.
#[tokio::test]
async fn r22_conflicting_duplicate_mcp_method_is_rejected() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(160),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.headers(duplicated_header(
"mcp-method",
["tools/call", "tools/list"],
))
.header("Mcp-Name", COUNTED_TOOL_NAME)
.header("x-request-id", "r22-duplicate-mcp-method")
.json(&message)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert_eq!(
body["error"]["data"]["request_id"],
json!("r22-duplicate-mcp-method"),
"got {body}"
);
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R22: a conflicting duplicate `Mcp-Name` is rejected the same way.
#[tokio::test]
async fn r22_conflicting_duplicate_mcp_name_is_rejected() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(161),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "tools/call")
.headers(duplicated_header(
"mcp-name",
[COUNTED_TOOL_NAME, "some_other_tool"],
))
.json(&message)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R22: identical duplicates carry no ambiguity and keep working (accepted current semantics).
#[tokio::test]
async fn r22_identical_duplicate_mcp_method_is_served() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let message = modern_request_with_params(
Some(162),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.headers(duplicated_header(
"mcp-method",
["tools/call", "tools/call"],
))
.header("Mcp-Name", COUNTED_TOOL_NAME)
.json(&message)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), 200);
assert_eq!(fixture.calls.load(Ordering::SeqCst), 1);
}
@@ -0,0 +1,465 @@
//! Shared harness of the `revision_matrix` module: endpoint bootstrap, oracle fixtures and
//! request builders used by two or more of the thematic submodules (`negotiation`, `session_guards`,
//! `duplicate_carriers`, `envelope`, `method_name`, `tools_call`, `result_shapes`).
//!
//! The bodies were moved verbatim out of `revision_matrix.rs` (Story 3.6, kanban t_987bf309); no
//! literal, ordering, timeout or assertion changed.
use super::super::common::*;
use axum::http::header;
use axum::{Json, Router};
use crank_core::PlatformApiKeyScope;
use crank_registry::{PostgresRegistry, PublishRequest};
use serde_json::{Value, json};
use std::sync::Arc;
use std::{path::PathBuf, time::Duration};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
pub(super) const MODERN_REVISION: &str = "2026-07-28";
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
pub(super) const UNKNOWN_REVISION: &str = "1999-01-01";
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
pub(super) fn fixture(name: &str) -> Value {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/mcp-revisions")
.join(name);
let raw = std::fs::read_to_string(&path).unwrap_or_else(|error| {
panic!(
"oracle fixture must be readable at {}: {error}",
path.display()
)
});
serde_json::from_str(&raw).unwrap()
}
pub(super) fn wire_case(case_id: &str) -> Value {
fixture("wire-identity-cases.json")["cases"]
.as_array()
.unwrap()
.iter()
.find(|case| case["id"] == case_id)
.cloned()
.unwrap_or_else(|| panic!("wire identity case {case_id} must exist in the oracle"))
}
pub(super) fn oracle_status(case_id: &str) -> u16 {
wire_case(case_id)["expected_status"].as_u64().unwrap() as u16
}
pub(super) fn approved_revisions() -> Vec<String> {
fixture("supported-revisions.json")["revisions"]
.as_array()
.unwrap()
.iter()
.map(|entry| entry["revision"].as_str().unwrap().to_owned())
.collect()
}
/// A complete, schema-shaped modern request: required `_meta` (protocol version, client capabilities,
/// client info) plus the standard identity headers. Built once here so every modern case shares the
/// same valid metadata shape.
pub(super) fn modern_meta(revision: &str) -> Value {
json!({
META_PROTOCOL_VERSION: revision,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: { "name": "crank-atdd-client", "version": "0.1.0" }
})
}
pub(super) fn modern_request(id: u64, method: &str, revision: &str, with_meta: bool) -> Value {
let mut params = json!({});
if with_meta {
params["_meta"] = modern_meta(revision);
}
json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })
}
pub(super) fn modern_headers(revision: &str, method: &str) -> Vec<(&'static str, String)> {
vec![
("MCP-Protocol-Version", revision.to_owned()),
("Mcp-Method", method.to_owned()),
]
}
pub(super) fn tools_list_request(id: u64) -> Value {
json!({ "jsonrpc": "2.0", "id": id, "method": "tools/list", "params": {} })
}
pub(super) struct Endpoint {
pub(super) registry: PostgresRegistry,
pub(super) client: reqwest::Client,
pub(super) mcp_url: String,
pub(super) api_key: String,
}
pub(super) async fn endpoint() -> Endpoint {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_create_lead");
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-rest").await;
let api_key = create_platform_api_key(
&registry,
"sales-rest",
"mcp-rest",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
Endpoint {
registry,
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, "sales-rest"),
api_key,
}
}
pub(super) async fn json_body(response: reqwest::Response) -> Value {
let status = response.status();
let body = response.text().await.unwrap();
serde_json::from_str(&body).unwrap_or_else(|error| {
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
})
}
// ---------------------------------------------------------------------------------------------
// Independent code-review regressions (R1-R9). Test-only: no production change is made here.
// Each case is single-fault and asserts observable HTTP/JSON-RPC behaviour of the delivered
// build slice. A failure means the review defect is reproduced on the current build.
// ---------------------------------------------------------------------------------------------
pub(super) fn modern_call_headers(method: &str, name: &str) -> Vec<(&'static str, String)> {
vec![
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
("Mcp-Method", method.to_owned()),
("Mcp-Name", name.to_owned()),
]
}
pub(super) fn modern_request_with_params(id: Option<u64>, method: &str, mut extra: Value) -> Value {
// Only supply the standard modern metadata when the caller did not build its own `_meta`,
// so single-fault cases can omit or corrupt exactly one field.
if extra.get("_meta").is_none() {
extra["_meta"] = modern_meta(MODERN_REVISION);
}
let mut message = json!({ "jsonrpc": "2.0", "method": method, "params": extra });
if let Some(id) = id {
message["id"] = json!(id);
}
message
}
pub(super) async fn modern_post(
endpoint: &Endpoint,
headers: &[(&'static str, String)],
message: Value,
request_id: Option<&str>,
) -> reqwest::Response {
let mut all: Vec<(&str, &str)> = headers
.iter()
.map(|(name, value)| (*name, value.as_str()))
.collect();
if let Some(request_id) = request_id {
all.push(("x-request-id", request_id));
}
post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&all,
message,
)
.await
}
/// Test-only counted upstream: every lead request increments the counter, so a test can prove that an
/// approval-pending tool call performed **no** outbound request.
pub(super) async fn spawn_counted_lead_upstream(
calls: Arc<std::sync::atomic::AtomicUsize>,
) -> String {
use axum::routing::post;
let handler_calls = Arc::clone(&calls);
let app = Router::new().route(
"/crm/leads",
post(move |Json(payload): Json<Value>| {
let calls = Arc::clone(&handler_calls);
async move {
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Json(json!({ "id": "lead_123", "email": payload["email"] }))
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
format!("http://{address}")
}
// ---------------------------------------------------------------------------------------------
// R1 dispatch-safety regressions (test-first for the production fix): the modern era must not
// become an unsafe path once `tools/call` is dispatched without a session.
// ---------------------------------------------------------------------------------------------
pub(super) const COUNTED_TOOL_NAME: &str = "crm_counted_lead";
pub(super) struct CountedTool {
pub(super) endpoint: Endpoint,
pub(super) calls: Arc<std::sync::atomic::AtomicUsize>,
}
/// Test-only fixture: a published operation behind a counted upstream, with the given approval policy
/// and platform-key scopes. Every upstream request increments the counter, so a test can prove that a
/// rejected or pending call performed no outbound request.
pub(super) async fn counted_tool(
approval_policy: Option<crank_core::OperationApprovalPolicy>,
scopes: &[PlatformApiKeyScope],
) -> CountedTool {
use std::sync::atomic::AtomicUsize;
let calls = Arc::new(AtomicUsize::new(0));
let upstream_base_url = spawn_counted_lead_upstream(Arc::clone(&calls)).await;
let registry = test_registry().await;
let mut operation = test_operation(&upstream_base_url, COUNTED_TOOL_NAME);
operation.execution_config.approval_policy = approval_policy;
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-gated").await;
let api_key = create_platform_api_key(&registry, "sales-gated", "mcp-gated", scopes).await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-gated");
CountedTool {
endpoint: Endpoint {
registry,
client,
mcp_url,
api_key,
},
calls,
}
}
pub(super) fn counted_call_params(name: &str) -> Value {
json!({ "name": name, "arguments": { "email": "counted@example.com" } })
}
// ---------------------------------------------------------------------------------------------
// Review pass 2 regressions (R10-R15). Test-only stage: production is read-only here.
// ---------------------------------------------------------------------------------------------
/// Duplicate identity carriers are sent as real duplicate HTTP header lines (one `HeaderMap` with two
/// appended values, transmitted through `reqwest::RequestBuilder::headers`). The assertions below are
/// what settle whether both values actually arrive: a conflicting pair must be rejected, and the
/// pre-fix code that silently reads only the first value cannot pass them.
pub(super) fn duplicated_header(
name: &'static str,
values: [&str; 2],
) -> reqwest::header::HeaderMap {
let mut map = reqwest::header::HeaderMap::new();
let name = reqwest::header::HeaderName::from_static(name);
for value in values {
map.append(
name.clone(),
reqwest::header::HeaderValue::from_str(value).unwrap(),
);
}
map
}
/// Era of a request whose session carrier is ambiguous, read from the non-carrier part of the
/// request only — never guessed from the ambiguous value itself.
#[derive(Clone, Copy)]
pub(super) enum DuplicateSessionCarrierEra {
Modern,
Legacy,
}
// ---------------------------------------------------------------------------------------------
// Review pass 3 regressions (R16, R19-R22). Test-only stage: production is read-only here.
// ---------------------------------------------------------------------------------------------
/// Pending approval requests persisted for the fixture agent, read from the registry (never inferred
/// from a response body).
pub(super) async fn pending_approvals(registry: &PostgresRegistry, agent_slug: &str) -> usize {
registry
.list_pending_approval_requests_for_agent(
&test_workspace_id(),
&crank_core::AgentId::new(format!("agent_{agent_slug}")),
)
.await
.unwrap()
.len()
}
// ---------------------------------------------------------------------------------------------
// Review pass 4 regressions (R23-R25, R27). Test-only stage: production is read-only here.
//
// Source of every modern-only requirement — pinned public schema, commit
// 1f520964b295d58494d944f2aea8a5ab51c79f77, `schema/2026-07-28/schema.ts`:
// 223-235 `Result { _meta?; resultType: ResultType; [key: string]: unknown }` — the doc comment of
// `resultType` says "Servers implementing this protocol version MUST include this field";
// an absent `resultType` is only tolerated on results produced by *earlier* revisions.
// 287-290 `JSONRPCResultResponse { jsonrpc; id: RequestId; result: Result }`
// 534 `EmptyResult = Result`
// 1068 `PaginatedResult extends Result { nextCursor?: Cursor }`
// 1081 `CacheableResult extends Result { ttlMs: number; cacheScope: "public" | "private" }`
// 1779 `ListToolsResult extends PaginatedResult, CacheableResult { tools: Tool[] }`
// 1809 `CallToolResult extends Result { content: ContentBlock[]; structuredContent?; isError? }`
// 678-707 `DiscoverResult extends CacheableResult { ...; capabilities: ServerCapabilities }`
// The legacy era keeps its own earlier schema, so these tests never require modern-only fields on a
// legacy result.
// ---------------------------------------------------------------------------------------------
/// R25: every modern success result must satisfy the pinned `Result` contract.
///
/// Tightened oracle: `ResultType` is `"complete" | "input_required" | string`, but every result served
/// by this slice is a synchronous, fully computed result, so the exact value is `"complete"`. An
/// arbitrary non-empty string is not accepted.
pub(super) fn require_modern_result_type(result: &Value, method: &str) {
assert!(
result.is_object(),
"a modern success result must be an object, method={method} got {result}"
);
assert_eq!(
result.get("resultType").and_then(Value::as_str),
Some("complete"),
"the pinned `Result.resultType` is mandatory and must be \"complete\" for a synchronous \
modern success result, method={method} got {result}"
);
}
/// R25: a Search-mode agent over the counted operation with the given approval policy, so a proxy
/// (`call_tool`) case can be observed through real registry and outbound state.
pub(super) async fn counted_search_agent(
approval_policy: Option<crank_core::OperationApprovalPolicy>,
) -> CountedTool {
use crank_core::{ToolAccessMode, ToolGroup, ToolSearchSettings, ToolSelectionPolicy};
use std::sync::atomic::AtomicUsize;
let calls = Arc::new(AtomicUsize::new(0));
let upstream_base_url = spawn_counted_lead_upstream(Arc::clone(&calls)).await;
let registry = test_registry().await;
let mut operation = test_operation(&upstream_base_url, COUNTED_TOOL_NAME);
operation.execution_config.approval_policy = approval_policy;
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_with_policy(
&registry,
"sales-proxy",
vec![binding_for_operation(&operation)],
ToolSelectionPolicy {
mode: ToolAccessMode::Search,
groups: vec![ToolGroup {
id: "crm".to_owned(),
name: "CRM".to_owned(),
description: "CRM operations".to_owned(),
tool_names: vec![COUNTED_TOOL_NAME.to_owned()],
}],
search: ToolSearchSettings { max_results: 5 },
},
)
.await;
let api_key = create_platform_api_key(
&registry,
"sales-proxy",
"mcp-proxy",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
CountedTool {
endpoint: Endpoint {
registry,
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, "sales-proxy"),
api_key,
},
calls,
}
}
/// The pinned `call_tool` wrapper schema advertises `arguments` as a **required object**
/// (`manifest.rs` `CALL_TOOL_NAME` definition: `required: ["name", "arguments", "catalog_revision"]`,
/// `arguments: { "type": "object" }`). The proxy consumer deserializes the inner `arguments` with
/// `#[serde(default)]` into a `Value`, so a missing key becomes `null` and an array/scalar is accepted
/// as is — the nested `object` requirement of the advertised schema is not enforced before the
/// approval decision.
pub(super) fn proxy_call_params(catalog_revision: &str, inner: Option<Value>) -> Value {
let mut wrapper = json!({
"name": COUNTED_TOOL_NAME,
"catalog_revision": catalog_revision,
});
if let Some(inner) = inner {
wrapper["arguments"] = inner;
}
wrapper
}
@@ -0,0 +1,288 @@
//! Required `Mcp-Name`/method identity on modern requests, and the ordering rule that the name is
//! checked before an unsupported-method dispatch.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use serde_json::{Value, json};
use super::harness::{
MODERN_REVISION, endpoint, json_body, modern_headers, modern_post, modern_request_with_params,
};
/// R7: missing or mismatched `Mcp-Method` is a validation failure.
#[tokio::test]
async fn r7_modern_missing_mcp_method_is_rejected() {
let endpoint = endpoint().await;
let headers = vec![("MCP-Protocol-Version", MODERN_REVISION.to_owned())];
let message = modern_request_with_params(Some(80), "tools/list", json!({}));
let response = modern_post(&endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["id"],
json!(80),
"the request id must be preserved, got {body}"
);
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert!(body["result"].is_null(), "got {body}");
}
#[tokio::test]
async fn r7_modern_mismatched_mcp_method_is_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let message = modern_request_with_params(Some(81), "server/discover", json!({}));
let response = modern_post(&endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["id"],
json!(81),
"the request id must be preserved, got {body}"
);
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert!(body["result"].is_null(), "got {body}");
}
/// R9: an unknown RPC on the modern era answers `404` + `-32601` with the request id preserved.
#[tokio::test]
async fn r9_modern_unknown_rpc_is_method_not_found() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/unsupported_thing");
let message = modern_request_with_params(Some(90), "tools/unsupported_thing", json!({}));
let response = modern_post(&endpoint, &headers, message, Some("r9-unknown-rpc")).await;
assert_eq!(response.status().as_u16(), 404);
let body = json_body(response).await;
assert_eq!(
body["id"],
json!(90),
"the request id must be preserved, got {body}"
);
assert_eq!(body["error"]["code"], json!(-32601), "got {body}");
assert!(body["result"].is_null(), "got {body}");
}
/// Review pass 6 (P5 / matrix row 6): `Mcp-Name` is a **required** modern header for `tools/call`,
/// `resources/read` and `prompts/get` (`streamable-http.mdx` "Standard Request Headers"), and its
/// validation must happen **before** the business dispatch. Both standard Resource/Prompt requests
/// implement their handler now (stories 3.8 and 3.14), so the missing/mismatched halves assert the
/// `-32020` header diagnostic and a correctly declared name reaches the implemented handler.
async fn modern_standard_method_name_outcome(
method: &'static str,
params: Value,
declared_name: Option<&str>,
correlation: &str,
) -> (u16, String) {
let endpoint = endpoint().await;
let mut headers = modern_headers(MODERN_REVISION, method);
if let Some(name) = declared_name {
headers.push(("Mcp-Name", name.to_owned()));
}
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(150), method, params),
Some(correlation),
)
.await;
let status = response.status().as_u16();
(status, response.text().await.unwrap())
}
/// The `Mcp-Name` half of the row-6 oracle: a missing or mismatched required name header is a
/// `400` + `-32020` `HeaderMismatch` that keeps the request id, the request correlation and no result.
///
/// Review pass 7 (G2): the correlation assertion was missing entirely here even though the build
/// walkthrough claimed it was present on this half; the complete envelope is now pinned for both
/// standard names.
fn assert_required_name_header_is_a_structured_mismatch(
status: u16,
raw: &str,
correlation: &str,
case: &str,
) {
assert_eq!(
status, 400,
"{case}: row 6 requires a header-validation failure for a missing/mismatched `Mcp-Name`, got {raw}"
);
let body: Value = serde_json::from_str(raw).unwrap_or_else(|error| {
panic!(
"{case}: the `Mcp-Name` diagnostic must be a JSON-RPC envelope, got {raw:?}: {error}"
)
});
assert_eq!(body["jsonrpc"], "2.0", "{case}: got {body}");
assert_eq!(
body["id"],
json!(150),
"{case}: the diagnostic must keep the request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"{case}: row 6 returns `-32020` `HeaderMismatch`, got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"{case}: the diagnostic must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"{case}: the diagnostic must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"{case}: a rejected request must not carry a result, got {body}"
);
}
/// Review pass 6 (P5): `resources/read` takes its `Mcp-Name` from `params.uri`. Since Story 3.8 the
/// method is implemented, so the name is validated before the Resource handler rather than before the
/// unsupported-method answer.
#[tokio::test]
async fn review6_p5_modern_resources_read_requires_mcp_name_before_resource_dispatch() {
let uri = "crank://operations/crm_create_lead";
let missing = "review6-p5-resources-missing-name";
let (status, raw) =
modern_standard_method_name_outcome("resources/read", json!({ "uri": uri }), None, missing)
.await;
assert_required_name_header_is_a_structured_mismatch(
status,
&raw,
missing,
"resources/read missing name",
);
let mismatched = "review6-p5-resources-mismatched-name";
let (status, raw) = modern_standard_method_name_outcome(
"resources/read",
json!({ "uri": uri }),
Some("crank://operations/other"),
mismatched,
)
.await;
assert_required_name_header_is_a_structured_mismatch(
status,
&raw,
mismatched,
"resources/read mismatched name",
);
let valid = "review6-p5-resources-valid-name";
let (status, raw) = modern_standard_method_name_outcome(
"resources/read",
json!({ "uri": uri }),
Some(uri),
valid,
)
.await;
// Story 3.8: `resources/read` is an implemented capability, so a correctly declared name reaches
// the Resource handler. An unbound URI is answered by one safe, non-disclosing outcome instead of
// the era-correct unsupported-method answer.
assert_eq!(
status, 200,
"a correctly declared `Mcp-Name` must reach the Resource handler, got {raw}"
);
let body: Value = serde_json::from_str(&raw).expect("the safe answer is a JSON-RPC envelope");
assert_eq!(body["jsonrpc"], "2.0", "got {body}");
assert_eq!(
body["id"],
json!(150),
"the answer must keep the request id: {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32602),
"an unbound Resource URI is safe invalid params, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(valid),
"the safe answer must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"a denied Resource read must not carry a result, got {body}"
);
}
/// Review pass 6 (P5): `prompts/get` takes its `Mcp-Name` from `params.name`.
#[tokio::test]
async fn review6_p5_modern_prompts_get_requires_mcp_name_before_unsupported_dispatch() {
let missing = "review6-p5-prompts-missing-name";
let (status, raw) = modern_standard_method_name_outcome(
"prompts/get",
json!({ "name": "crm_create_lead" }),
None,
missing,
)
.await;
assert_required_name_header_is_a_structured_mismatch(
status,
&raw,
missing,
"prompts/get missing name",
);
let mismatched = "review6-p5-prompts-mismatched-name";
let (status, raw) = modern_standard_method_name_outcome(
"prompts/get",
json!({ "name": "crm_create_lead" }),
Some("crm_other_lead"),
mismatched,
)
.await;
assert_required_name_header_is_a_structured_mismatch(
status,
&raw,
mismatched,
"prompts/get mismatched name",
);
let valid = "review6-p5-prompts-valid-name";
let (status, raw) = modern_standard_method_name_outcome(
"prompts/get",
json!({ "name": "crm_create_lead" }),
Some("crm_create_lead"),
valid,
)
.await;
// Story 3.14 implements the standard Prompt requests, so a correctly declared name no longer
// reaches the unsupported-method answer: it is a business answer for a Prompt that this Agent
// does not bind, and the row-6 header diagnostic is still asserted on the two halves above.
assert_eq!(
status, 200,
"a correctly declared `prompts/get` name must reach the implemented handler, got {raw}"
);
let body: Value =
serde_json::from_str(&raw).expect("the business answer is a JSON-RPC envelope");
assert_eq!(body["error"]["code"], json!(-32602), "got {body}");
assert_eq!(
body["error"]["message"],
json!("the requested prompt is not available"),
"an unbound Prompt name stays a safe business answer, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(valid),
"the safe answer must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"an unbound Prompt must not carry a result, got {body}"
);
}
@@ -0,0 +1,890 @@
//! Revision negotiation on the real endpoint: modern stateless discovery, legacy
//! initialize/tools-list, withdrawn revisions, unknown/mismatched/missing identity, the negative
//! "no experimental surface" oracle and the minimal client.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use serde_json::{Value, json};
use super::harness::{
LEGACY_REVISION, META_CLIENT_CAPABILITIES, META_CLIENT_INFO, META_PROTOCOL_VERSION,
MODERN_REVISION, UNKNOWN_REVISION, approved_revisions, endpoint, fixture, json_body,
modern_headers, modern_meta, modern_post, modern_request, modern_request_with_params,
oracle_status, require_modern_result_type, tools_list_request, wire_case,
};
/// Exact-descriptor assertion driven by an independent projection fixture
/// (`expected-advertised-capabilities.json`): the current scope may advertise exactly what is
/// implemented, and deferred capabilities must not appear. A generic official-key allowlist would
/// not prove that (TL finding on the descriptor oracle).
fn assert_advertised_descriptor(capabilities: &serde_json::Map<String, Value>, body: &Value) {
let expected = fixture("expected-advertised-capabilities.json");
let mut expected_keys: Vec<String> = expected["expected_keys"]
.as_array()
.unwrap()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
expected_keys.sort();
let mut actual_keys: Vec<String> = capabilities.keys().cloned().collect();
actual_keys.sort();
assert_eq!(
actual_keys, expected_keys,
"the advertised descriptor must equal the implemented current scope, got {body}"
);
for forbidden in expected["must_not_be_advertised"].as_array().unwrap() {
let key = forbidden.as_str().unwrap();
assert!(
!capabilities.contains_key(key),
"capability {key:?} is not implemented in the current scope and must not be advertised, got {body}"
);
}
// R8: compare the subfeatures as well, not only the key set.
let expected_descriptor = expected["expected_descriptor"]
.as_object()
.expect("the projection fixture must carry the expected descriptor");
assert_eq!(
&Value::Object(capabilities.clone()),
&Value::Object(expected_descriptor.clone()),
"advertised subfeatures must equal the independent golden descriptor, got {body}"
);
}
fn header_refs<'a>(headers: &'a [(&'static str, String)]) -> Vec<(&'static str, &'a str)> {
headers
.iter()
.map(|(name, value)| (*name, value.as_str()))
.collect()
}
fn initialize_request(revision: &str) -> Value {
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": { "protocolVersion": revision, "capabilities": {} }
})
}
/// AT-3.1-04: the modern stateless revision is served and `server/discover` is mandatory.
///
/// Golden coverage from the pinned schema: exact `supportedVersions`, `serverInfo`, revision-correct
/// `resultType` handling, cache hints, and the complete advertised capability descriptor (no
/// experimental or extension surface in the current scope). One positive status alone is **not**
/// treated as full AC-04 evidence.
#[tokio::test]
async fn at_3_1_04_modern_discover_is_served_without_a_session() {
let endpoint = endpoint().await;
let expected = oracle_status("wm-01");
assert_eq!(expected, 200);
let headers = modern_headers(MODERN_REVISION, "server/discover");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(15, "server/discover", MODERN_REVISION, true),
)
.await;
assert_eq!(
response.status().as_u16(),
expected,
"modern `server/discover` must be served"
);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"the modern stateless era must not mint a session"
);
let body = json_body(response).await;
let result = &body["result"];
let mut supported: Vec<String> = result["supportedVersions"]
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
supported.sort();
let mut approved = approved_revisions();
approved.sort();
assert_eq!(
supported, approved,
"discover must advertise exactly the approved revisions, got {body}"
);
// Pinned `DiscoverResult` places the server identity inside `result._meta`, not on the result
// object itself; the pinned prose makes it a SHOULD for the server to include it.
let server_info = &result["_meta"]["io.modelcontextprotocol/serverInfo"];
assert!(
server_info["name"].is_string() && server_info["version"].is_string(),
"discover must return `_meta['io.modelcontextprotocol/serverInfo']` with name and version, got {body}"
);
assert!(
result.get("serverInfo").is_none(),
"serverInfo must not be projected onto the result object itself, got {body}"
);
// The pinned revision treats an absent resultType as "complete".
assert!(
result.get("resultType").is_none() || result["resultType"] == json!("complete"),
"resultType must be absent or `complete` for a successful discover, got {body}"
);
// `ttlMs` and `cacheScope` are non-optional fields of the pinned `CacheableResult` that
// `DiscoverResult` extends, and both appear in the pinned discover example.
assert!(
result["ttlMs"].is_u64(),
"discover must carry the required cache TTL hint, got {body}"
);
assert!(
matches!(result["cacheScope"].as_str(), Some("public" | "private")),
"discover must carry the required cache scope, got {body}"
);
let capabilities = result["capabilities"]
.as_object()
.unwrap_or_else(|| panic!("capabilities must be an object, got {body}"));
assert_advertised_descriptor(capabilities, &body);
}
/// AT-3.1-04: a second, independent modern request is served without discover/session priming.
#[tokio::test]
async fn at_3_1_04_modern_request_is_served_without_priming() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(16, "tools/list", MODERN_REVISION, true),
)
.await;
assert_eq!(
response.status().as_u16(),
200,
"a complete modern request must be served without priming"
);
assert!(response.headers().get("MCP-Session-Id").is_none());
let body = json_body(response).await;
assert_eq!(body["result"]["tools"][0]["name"], "crm_create_lead");
}
/// AT-3.1-05: the legacy `2025-11-25` session lifecycle keeps working (existing correct behaviour).
#[tokio::test]
async fn at_3_1_05_legacy_initialize_and_tools_list_stay_green() {
let endpoint = endpoint().await;
assert_eq!(oracle_status("wm-06"), 200);
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let tools = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
tools_list_request(2),
)
.await;
assert_eq!(tools["result"]["tools"][0]["name"], "crm_create_lead");
}
/// AT-3.1-02: the withdrawn `2025-03-26` revision is rejected and mints no session.
#[tokio::test]
async fn at_3_1_02_withdrawn_2025_03_26_initialize_is_rejected() {
let endpoint = endpoint().await;
let expected = oracle_status("wm-10");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
initialize_request("2025-03-26"),
)
.await;
assert_eq!(
response.status().as_u16(),
expected,
"a withdrawn revision must be rejected with {expected}"
);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a rejected revision must not mint a session"
);
}
/// AT-3.1-02: the withdrawn `2025-06-18` revision is rejected as well.
#[tokio::test]
async fn at_3_1_02_withdrawn_2025_06_18_initialize_is_rejected() {
let endpoint = endpoint().await;
let expected = oracle_status("wm-11");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
initialize_request("2025-06-18"),
)
.await;
assert_eq!(
response.status().as_u16(),
expected,
"a withdrawn revision must be rejected with {expected}"
);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a rejected revision must not mint a session"
);
}
/// AT-3.1-06 (wm-05): an unknown revision, identical in header and body, yields `-32022` with the
/// supported list. All other required metadata stays valid, so this is a single-fault case.
#[tokio::test]
async fn at_3_1_06_unsupported_version_yields_structured_error() {
let endpoint = endpoint().await;
let case = wire_case("wm-05");
assert_eq!(case["expected_error"], "UnsupportedProtocolVersion");
let headers = modern_headers(UNKNOWN_REVISION, "tools/list");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(17, "tools/list", UNKNOWN_REVISION, true),
)
.await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["error"]["code"], -32022,
"unknown revision must use the era-correct error code, got {body}"
);
let mut supported: Vec<String> = body["error"]["data"]["supported"]
.as_array()
.cloned()
.unwrap_or_default()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
supported.sort();
let mut approved = approved_revisions();
approved.sort();
assert_eq!(
supported, approved,
"the error must advertise exactly the supported revisions, got {body}"
);
}
/// AT-3.1-06 (wm-02): a known version in the header that differs from the body version is a
/// mismatch (`-32020`), not an unsupported-version error.
#[tokio::test]
async fn at_3_1_06_header_body_version_mismatch_is_rejected() {
let endpoint = endpoint().await;
let case = wire_case("wm-02");
assert_eq!(case["expected_error"], "HeaderMismatch");
let headers = modern_headers(MODERN_REVISION, "tools/list");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(18, "tools/list", LEGACY_REVISION, true),
)
.await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(
body["error"]["code"], -32020,
"a header/body version mismatch must use the header-mismatch code, got {body}"
);
}
/// AT-3.1-06 (wm-03): a modern header without the required body `_meta` is rejected.
#[tokio::test]
async fn at_3_1_06_modern_header_without_required_meta_is_rejected() {
let endpoint = endpoint().await;
assert_eq!(oracle_status("wm-03"), 400);
let headers = modern_headers(MODERN_REVISION, "tools/list");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
modern_request(19, "tools/list", MODERN_REVISION, false),
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"a modern header without the required body metadata must be rejected"
);
assert!(response.headers().get("MCP-Session-Id").is_none());
}
/// AT-3.1-06 (wm-04): an incomplete `_meta` (missing required client capabilities) is rejected.
#[tokio::test]
async fn at_3_1_06_modern_request_without_required_metadata_is_rejected() {
let endpoint = endpoint().await;
assert_eq!(oracle_status("wm-04"), 400);
let headers = modern_headers(MODERN_REVISION, "tools/list");
let incomplete = json!({
"jsonrpc": "2.0",
"id": 20,
"method": "tools/list",
"params": { "_meta": { META_PROTOCOL_VERSION: MODERN_REVISION } }
});
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&header_refs(&headers),
incomplete,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"missing required client capabilities must be rejected"
);
}
/// AT-3.1-06 / AT-3.1-02 (wm-12): a legacy `initialize` with an unknown revision must not mint a
/// session, must not return a successful initialize result, and must never echo the withdrawn
/// `2025-03-26` as the served identity.
///
/// The pinned legacy prose does not pin an HTTP status for an unsupported *body* version on
/// `initialize`, so this case deliberately asserts behaviour instead of guessing a status code.
#[tokio::test]
async fn at_3_1_06_legacy_initialize_unknown_revision_is_rejected() {
let endpoint = endpoint().await;
let case = wire_case("wm-12");
assert_eq!(case["expected"], "no_session_and_no_withdrawn_identity");
assert_eq!(case["status_not_pinned"], true);
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
initialize_request(UNKNOWN_REVISION),
)
.await;
let status = response.status();
let echoed = response
.headers()
.get("MCP-Protocol-Version")
.map(|value| value.to_str().unwrap().to_owned());
let session_header = response.headers().get("MCP-Session-Id").is_some();
assert!(
!session_header,
"an unknown revision must not mint a session"
);
assert_ne!(
echoed.as_deref(),
Some("2025-03-26"),
"the withdrawn revision must never be echoed as the served identity"
);
let body = json_body(response).await;
if status.is_success() {
assert!(
body["error"].is_object(),
"a 2xx response for an unknown revision must still carry a JSON-RPC error, got {body}"
);
assert!(
body["result"].is_null(),
"an unknown revision must not produce an initialize result, got {body}"
);
}
}
/// AT-3.1-06 (wm-13) / AT-3.1-02: an authenticated request that carries no identity at all
/// (no initialization, no verified session, no version header, no `_meta`) must fail instead of
/// being served as a withdrawn revision. This replaces the earlier internal-constant assertion.
#[tokio::test]
async fn at_3_1_06_request_without_any_identity_is_rejected() {
let endpoint = endpoint().await;
assert_eq!(oracle_status("wm-13"), 400);
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
tools_list_request(21),
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"a request without any protocol identity must be rejected"
);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"an unidentified request must not mint a session"
);
let echoed = response
.headers()
.get("MCP-Protocol-Version")
.map(|value| value.to_str().unwrap().to_owned());
assert_ne!(
echoed.as_deref(),
Some("2025-03-26"),
"the withdrawn revision must never be echoed as the served identity"
);
}
/// AT-3.1-09 (advertisement half): the negotiated capability descriptor never contains an
/// experimental or extension surface, and unknown RPC/extension methods are not dispatchable.
#[tokio::test]
async fn at_3_1_09_no_extension_surface_is_advertised_or_dispatched() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
// 1. the actual negotiated capabilities from the real initialize response
let capabilities_response = endpoint
.client
.post(&endpoint.mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.json(&initialize_request(LEGACY_REVISION))
.send()
.await
.unwrap();
let capabilities_body = json_body(capabilities_response).await;
let advertised = capabilities_body["result"]["capabilities"]
.as_object()
.cloned()
.unwrap_or_default();
assert_advertised_descriptor(&advertised, &capabilities_body);
// 2. an unknown extension method must not be dispatchable
let unknown_method = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 30,
"method": "io.modelcontextprotocol/tasks/list",
"params": {}
}),
)
.await;
assert!(
unknown_method["error"].is_object(),
"an unknown extension method must be rejected, got {unknown_method}"
);
// 3. a name that is not a registered tool must not be dispatched
let denied = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 31,
"method": "tools/call",
"params": { "name": "experimental_unknown_extension", "arguments": {} }
}),
)
.await;
assert!(
denied["error"].is_object(),
"an unregistered identifier must be denied, got {denied}"
);
}
/// AT-3.1-10: a minimal client that declares no optional capabilities still lists and calls Tools.
#[tokio::test]
async fn at_3_1_10_minimal_client_still_lists_and_calls_tools() {
let endpoint = endpoint().await;
let session = initialize_session_with_capabilities(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
json!({}),
)
.await;
let tools = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
tools_list_request(22),
)
.await;
assert_eq!(tools["result"]["tools"][0]["name"], "crm_create_lead");
let call = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 23,
"method": "tools/call",
"params": {
"name": "crm_create_lead",
"arguments": { "email": "minimal@example.com" }
}
}),
)
.await;
assert_eq!(
call["result"]["structuredContent"],
json!({ "id": "lead_123" })
);
}
/// R2: each **required** modern metadata carrier is validated independently (single-fault cases).
/// The optional `clientInfo` is covered by the corrected oracle below (review pass 6, P4).
#[tokio::test]
async fn r2_modern_missing_body_version_is_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let mut meta = modern_meta(MODERN_REVISION);
meta.as_object_mut().unwrap().remove(META_PROTOCOL_VERSION);
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(50), "tools/list", json!({ "_meta": meta })),
None,
)
.await;
assert_eq!(response.status().as_u16(), 400);
assert!(response.headers().get("MCP-Session-Id").is_none());
let body = json_body(response).await;
assert!(body["error"].is_object(), "got {body}");
assert!(body["result"].is_null(), "got {body}");
}
/// R2 (corrected in review pass 6, P4): `clientInfo` is **optional** in the pinned modern request
/// metadata. `RequestMetaObject` declares it as `"io.modelcontextprotocol/clientInfo"?:
/// Implementation` and its prose says clients **SHOULD** include it unless specifically configured
/// not to, while `protocolVersion` and `clientCapabilities` are declared required
/// (`build/review6/pinned-modern-schema.ts:63-98`, pinned by SHA-256
/// `742750af0bb8c716e7030c4977c992b55d1adc4407e9e66997db5846baedc2cd`).
///
/// The earlier derived oracle promoted that SHOULD to a MUST: `validate_modern_metadata`
/// (`protocol/mod.rs` 516-533) rejects an absent `clientInfo`, so a source-correct modern request is
/// refused today. Correcting this invalid oracle is **not** permission to relax the required
/// metadata: a `clientInfo` that is present but malformed (wrong type, or missing `name`/`version`)
/// is still rejected, and those cases stay asserted separately above.
#[tokio::test]
async fn r2_modern_request_without_optional_client_info_is_served() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let mut meta = modern_meta(MODERN_REVISION);
meta.as_object_mut().unwrap().remove(META_CLIENT_INFO);
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(51), "tools/list", json!({ "_meta": meta })),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
200,
"a modern request whose only deviation is the omitted **optional** `clientInfo` must be \
served (pinned `RequestMetaObject` marks it optional)"
);
let body = json_body(response).await;
assert!(
body["error"].is_null(),
"omitting the optional `clientInfo` must not produce a JSON-RPC error, got {body}"
);
assert_eq!(
body["result"]["tools"][0]["name"], "crm_create_lead",
"the served result must keep the published tool payload, got {body}"
);
require_modern_result_type(&body["result"], "tools/list (without clientInfo)");
}
#[tokio::test]
async fn r2_modern_client_info_without_name_or_version_is_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
for incomplete in [json!({}), json!({ "name": "crank-atdd-client" })] {
let mut meta = modern_meta(MODERN_REVISION);
meta[META_CLIENT_INFO] = incomplete.clone();
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(52), "tools/list", json!({ "_meta": meta })),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"clientInfo {incomplete} must be rejected"
);
}
}
#[tokio::test]
async fn r2_modern_client_info_or_capabilities_of_wrong_type_are_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
for (key, value) in [
(META_CLIENT_INFO, json!("not-an-object")),
(META_CLIENT_CAPABILITIES, json!("not-an-object")),
] {
let mut meta = modern_meta(MODERN_REVISION);
meta[key] = value.clone();
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(53), "tools/list", json!({ "_meta": meta })),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"{key} with value {value} must be rejected"
);
}
}
/// R2: body-only modern identity without the required version header must be rejected.
#[tokio::test]
async fn r2_modern_identity_without_version_header_is_rejected() {
let endpoint = endpoint().await;
let headers = vec![("Mcp-Method", "tools/list".to_owned())];
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(54), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"the modern era requires the negotiated version header"
);
assert!(response.headers().get("MCP-Session-Id").is_none());
}
/// R3: legacy `initialize` must admit only the legacy revision.
#[tokio::test]
async fn r3_legacy_initialize_with_modern_body_version_is_rejected() {
let endpoint = endpoint().await;
let response = modern_post(&endpoint, &[], initialize_request(MODERN_REVISION), None).await;
assert_eq!(response.status().as_u16(), 400);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a modern body version must not mint a legacy session"
);
}
#[tokio::test]
async fn r3_legacy_header_with_modern_initialize_body_is_rejected() {
let endpoint = endpoint().await;
let headers = vec![("MCP-Protocol-Version", LEGACY_REVISION.to_owned())];
let response = modern_post(
&endpoint,
&headers,
initialize_request(MODERN_REVISION),
None,
)
.await;
assert_eq!(response.status().as_u16(), 400);
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a conflicting modern body version must not mint a session"
);
}
#[tokio::test]
async fn r3_modern_identity_with_legacy_initialize_body_is_rejected() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "initialize");
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(
Some(55),
"initialize",
json!({ "protocolVersion": LEGACY_REVISION, "capabilities": {} }),
),
None,
)
.await;
let status = response.status().as_u16();
assert!(
status == 400 || status == 404,
"a legacy initialize body must not be admitted by the modern era, got {status}"
);
assert!(response.headers().get("MCP-Session-Id").is_none());
}
/// Review pass 6 (P2 / matrix rows 14-15): a legacy `initialize` that names a withdrawn revision in
/// **both** carriers it can use — the `MCP-Protocol-Version` header and `params.protocolVersion` —
/// must stay legacy-shaped.
///
/// Defect this oracle pins: with an equal withdrawn identity the resolver takes the `other` branch
/// (`protocol/mod.rs` 665) and answers the modern `-32022` `UnsupportedProtocolVersionError`, while
/// the same withdrawn revision without a header is answered with the legacy `-32602` (`626-630`).
/// Row 14 forbids imposing the modern `-32022` contract on a legacy `initialize`; row 15 forbids an
/// implicit fallback into a withdrawn revision. The exact legacy code is deliberately **not** pinned
/// (the local contract names none for this path) — only the modern codes are excluded.
async fn assert_legacy_initialize_with_withdrawn_revision_is_legacy_shaped(
revision: &str,
correlation: &str,
) {
let endpoint = endpoint().await;
let headers = vec![("MCP-Protocol-Version", revision.to_owned())];
let message = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": { "protocolVersion": revision, "capabilities": {} }
});
let response = modern_post(&endpoint, &headers, message, Some(correlation)).await;
let status = response.status().as_u16();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a withdrawn `initialize` must not mint a session ({correlation})"
);
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"a withdrawn `initialize` revision must be rejected safely ({correlation}), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"matrix rows 14/15 require a structured legacy error ({correlation}), but the response body \
was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the legacy initialize rejection must be a JSON-RPC envelope ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the legacy rejection must be a JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"],
json!(1),
"the legacy rejection must keep the request id ({correlation}), got {body}"
);
assert!(
body["error"]["code"].is_i64(),
"the legacy rejection must carry a numeric JSON-RPC code ({correlation}), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32022),
"the modern UnsupportedProtocolVersionError must not be imposed on a withdrawn legacy \
`initialize` (row 14, {correlation}), got {body}"
);
assert_ne!(
body["error"]["code"],
json!(-32020),
"the modern HeaderMismatch code must not be imposed on a legacy `initialize` (row 14, \
{correlation}), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the legacy rejection must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the legacy rejection must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected `initialize` must not carry a result ({correlation}), got {body}"
);
}
/// Review pass 6 (P2): withdrawn revision `2025-03-26` in both legacy carriers.
#[tokio::test]
async fn review6_p2_legacy_initialize_with_withdrawn_2025_03_26_is_legacy_shaped() {
assert_legacy_initialize_with_withdrawn_revision_is_legacy_shaped(
"2025-03-26",
"review6-p2-withdrawn-2025-03-26",
)
.await;
}
/// Review pass 6 (P2): withdrawn revision `2025-06-18` in both legacy carriers.
#[tokio::test]
async fn review6_p2_legacy_initialize_with_withdrawn_2025_06_18_is_legacy_shaped() {
assert_legacy_initialize_with_withdrawn_revision_is_legacy_shaped(
"2025-06-18",
"review6-p2-withdrawn-2025-06-18",
)
.await;
}
@@ -0,0 +1,579 @@
//! Result shapes: envelope object, required cacheable/paginated fields, `CallToolResult` fields and
//! the legacy result shapes.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, META_CLIENT_CAPABILITIES, MODERN_REVISION, counted_call_params,
counted_search_agent, counted_tool, endpoint, json_body, modern_call_headers, modern_headers,
modern_meta, modern_post, modern_request, modern_request_with_params, proxy_call_params,
require_modern_result_type, tools_list_request,
};
/// R14 (verification gap, expected current GREEN): a modern Elicitation-mode operation must fail
/// closed with `approval_elicitation_not_supported` whether or not the request `_meta` client
/// capabilities declare elicitation — the stateless era has no elicitation channel, and the policy is
/// never converted into a Custom approval.
#[tokio::test]
async fn r14_modern_elicitation_mode_fails_closed_without_outbound() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Elicitation,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: Some("Подтвердите выполнение операции.".to_owned()),
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
for declared_capabilities in [json!({}), json!({ "elicitation": {} })] {
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut meta = modern_meta(MODERN_REVISION);
meta[META_CLIENT_CAPABILITIES] = declared_capabilities.clone();
let message = modern_request_with_params(
Some(140),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let mut message = message;
message["params"]["_meta"] = meta;
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
200,
"got {declared_capabilities}"
);
let text = response.text().await.unwrap();
assert!(
text.contains("approval_elicitation_not_supported"),
"an elicitation-mode policy must fail closed, got {text}"
);
assert!(
text.contains("\"isError\":true"),
"a fail-closed approval must be reported as a tool error, got {text}"
);
assert!(
!text.contains("approval_id"),
"an elicitation-mode policy must not be converted into a pending Custom approval, got {text}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a fail-closed approval must not perform the outbound request"
);
}
/// R25: `CacheableResult.cacheScope` is the pinned enum `"public" | "private"` (not any string).
fn require_cache_scope(result: &Value, method: &str) {
let scope = result.get("cacheScope").and_then(Value::as_str);
assert!(
matches!(scope, Some("public") | Some("private")),
"`CacheableResult.cacheScope` must be one of the pinned enum values, method={method} got \
{result}"
);
}
/// R25: `CacheableResult.ttlMs` is a non-negative number (the pinned schema marks `@minimum 0`).
fn require_ttl_ms(result: &Value, method: &str) {
assert!(
result
.get("ttlMs")
.and_then(Value::as_f64)
.is_some_and(|value| value >= 0.0),
"`CacheableResult.ttlMs` must be a non-negative number, method={method} got {result}"
);
}
/// R25: the mandatory `content` array of `CallToolResult` must be non-empty and carry a text block, i.e.
/// the projection may add result fields but must not degrade the business payload.
///
/// Review pass 6 (P8): the pinned `ContentBlock` union discriminates its members by `type`, so a block
/// whose payload happens to carry a `text` field is not evidence of a text block. The oracle now
/// asserts the `type: "text"` discriminator on the first block as well, while keeping the existing
/// non-empty-array and non-empty-payload assertions.
fn require_call_tool_content(result: &Value, method: &str) {
let content = result.get("content").and_then(Value::as_array);
assert!(
content.is_some_and(|blocks| !blocks.is_empty()),
"`CallToolResult.content` must be a non-empty array, method={method} got {result}"
);
let first = content.and_then(|blocks| blocks.first());
assert_eq!(
first
.and_then(|block| block.get("type"))
.and_then(Value::as_str),
Some("text"),
"the first `CallToolResult.content` block must carry the pinned `type: \"text\"` \
discriminator, method={method} got {result}"
);
assert!(
first
.and_then(|block| block.get("text"))
.and_then(Value::as_str)
.is_some_and(|text| !text.is_empty()),
"the first content block must keep a non-empty text payload, method={method} got {result}"
);
}
/// R24: the pinned `JSONRPCResultResponse` types `result` as `Result` (an object). The previous guard
/// checked the response id only, so a success response with a non-object `result` was acknowledged.
/// The object requirement stays on the era-agnostic wire envelope and deliberately does **not** require
/// the modern `resultType` inside an incoming result: a client implementing an earlier revision must
/// stay acceptable, which the pinned doc comment states explicitly.
#[tokio::test]
async fn r24_wire_response_result_must_be_an_object() {
let endpoint = endpoint().await;
for body in [
json!({ "jsonrpc": "2.0", "id": 1, "result": null }),
json!({ "jsonrpc": "2.0", "id": 1, "result": [] }),
json!({ "jsonrpc": "2.0", "id": 1, "result": [1, 2] }),
json!({ "jsonrpc": "2.0", "id": 1, "result": 5 }),
json!({ "jsonrpc": "2.0", "id": 1, "result": "text" }),
json!({ "jsonrpc": "2.0", "id": 1, "result": true }),
] {
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
body.clone(),
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"a non-object `result` is an invalid request, got {body}"
);
let payload = json_body(response).await;
assert_eq!(payload["error"]["code"], json!(-32600), "got {payload}");
assert!(
payload["id"].is_null(),
"an invalid request must answer with a null id, got {payload}"
);
}
for body in [
json!({ "jsonrpc": "2.0", "id": 1, "result": {} }),
json!({ "jsonrpc": "2.0", "id": 1, "result": { "value": 1 } }),
json!({ "jsonrpc": "2.0", "id": 1, "result": { "resultType": "complete" } }),
] {
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
body.clone(),
)
.await;
assert_eq!(
response.status().as_u16(),
202,
"an object `result` stays acknowledged, got {body}"
);
assert!(
response.text().await.unwrap().is_empty(),
"an acknowledgement carries no body, got {body}"
);
}
}
/// R25: `server/discover` already carries the complete `DiscoverResult` shape — the consolidated
/// modern result check must not regress it.
#[tokio::test]
async fn r25_modern_discover_result_carries_required_cacheable_fields() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "server/discover");
let response = modern_post(
&endpoint,
&headers,
modern_request(200, "server/discover", MODERN_REVISION, true),
None,
)
.await;
assert_eq!(response.status().as_u16(), 200);
let body = json_body(response).await;
let result = &body["result"];
require_modern_result_type(result, "server/discover");
require_ttl_ms(result, "server/discover");
require_cache_scope(result, "server/discover");
assert!(
result["capabilities"].is_object(),
"`DiscoverResult.capabilities` is mandatory, got {result}"
);
}
/// R25: `ping` is not enumerated in the pinned method list, but every modern success response is a
/// `JSONRPCResultResponse` whose `result` must be a `Result`, so the emitted `resultType` requirement
/// still applies to it.
#[tokio::test]
async fn r25_modern_ping_result_carries_result_type() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "ping");
let response = modern_post(
&endpoint,
&headers,
modern_request(201, "ping", MODERN_REVISION, true),
None,
)
.await;
assert_eq!(response.status().as_u16(), 200);
let body = json_body(response).await;
require_modern_result_type(&body["result"], "ping");
}
/// R25: `tools/list` must satisfy `ListToolsResult extends PaginatedResult, CacheableResult`, i.e. the
/// mandatory `resultType`, `ttlMs`, `cacheScope` and `tools`. `nextCursor` stays optional.
#[tokio::test]
async fn r25_modern_tools_list_result_carries_required_paginated_cacheable_fields() {
let endpoint = endpoint().await;
let headers = modern_headers(MODERN_REVISION, "tools/list");
let response = modern_post(
&endpoint,
&headers,
modern_request(202, "tools/list", MODERN_REVISION, true),
None,
)
.await;
assert_eq!(response.status().as_u16(), 200);
let body = json_body(response).await;
let result = &body["result"];
assert_eq!(
result["tools"][0]["name"], "crm_create_lead",
"the tool list payload must not be degraded by the wire projection, got {result}"
);
require_modern_result_type(result, "tools/list");
require_ttl_ms(result, "tools/list");
require_cache_scope(result, "tools/list");
}
/// R25: the direct `tools/call` success result must satisfy `CallToolResult extends Result`, i.e. carry
/// `resultType` and the mandatory `content` array while keeping its business fields. The counted fixture
/// is used so the assertion covers the real upstream round-trip (the echoed request value) and the
/// outbound counter, exactly as the `call_tool` proxy case does.
#[tokio::test]
async fn r25_modern_direct_tool_call_result_carries_call_tool_result_fields() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let direct = modern_post(
&fixture.endpoint,
&headers,
modern_request_with_params(
Some(203),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
),
None,
)
.await;
assert_eq!(direct.status().as_u16(), 200);
let direct_body = json_body(direct).await;
let direct_result = &direct_body["result"];
require_call_tool_content(direct_result, "tools/call (direct)");
assert_eq!(
direct_result["structuredContent"],
json!({ "id": "lead_123" }),
"the real upstream business output must survive the wire projection exactly (the fixture's \
`output_mapping` projects `$.response.body.id` only), got {direct_result}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"a served direct call must perform exactly one outbound request"
);
assert_eq!(
direct_result["isError"], false,
"the business error flag must survive the wire projection, got {direct_result}"
);
require_modern_result_type(direct_result, "tools/call (direct)");
}
/// R25: the Custom pending-approval result is served through `tools/call` too, so it must satisfy the
/// same `CallToolResult` contract (separate case so a fix that only touches one path is visible).
#[tokio::test]
async fn r25_modern_pending_approval_result_carries_call_tool_result_fields() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
let custom_policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let custom_fixture = counted_tool(
Some(custom_policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let custom_headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let pending = modern_post(
&custom_fixture.endpoint,
&custom_headers,
modern_request_with_params(
Some(204),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
),
None,
)
.await;
assert_eq!(pending.status().as_u16(), 200);
let pending_body = json_body(pending).await;
let pending_result = &pending_body["result"];
assert_eq!(
pending_result["structuredContent"]["status"], "approval_required",
"the fixture must produce the pending outcome, got {pending_body}"
);
require_call_tool_content(pending_result, "tools/call (approval_required)");
assert!(
pending_result["structuredContent"]["approval_id"]
.as_str()
.is_some_and(|value| value.starts_with("approval_")),
"the pending approval id must survive the wire projection, got {pending_result}"
);
require_modern_result_type(pending_result, "tools/call (approval_required)");
}
/// R25: the fail-closed Elicitation error result is also a `tools/call` result and must satisfy
/// `CallToolResult` (`content` plus `isError: true` marking the tool-level error).
#[tokio::test]
async fn r25_modern_elicitation_error_result_carries_call_tool_result_fields() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
let elicitation_policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Elicitation,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: Some("Подтвердите выполнение операции.".to_owned()),
};
let elicitation_fixture = counted_tool(
Some(elicitation_policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let elicitation_headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let elicitation = modern_post(
&elicitation_fixture.endpoint,
&elicitation_headers,
modern_request_with_params(
Some(205),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
),
None,
)
.await;
assert_eq!(elicitation.status().as_u16(), 200);
let elicitation_body = json_body(elicitation).await;
let elicitation_result = &elicitation_body["result"];
assert_eq!(
elicitation_result["isError"], true,
"the fixture must fail closed, got {elicitation_body}"
);
require_call_tool_content(elicitation_result, "tools/call (elicitation fail-closed)");
assert_eq!(
elicitation_result["structuredContent"]["error"]["code"],
"approval_elicitation_not_supported",
"the business error code must survive the wire projection, got {elicitation_result}"
);
require_modern_result_type(elicitation_result, "tools/call (elicitation fail-closed)");
}
/// R25: the Search-mode meta tool `search_tools` is served through `tools/call`, so its success result
/// must satisfy `CallToolResult` as well.
#[tokio::test]
async fn r25_modern_search_tools_result_carries_call_tool_result_fields() {
let fixture = counted_search_agent(None).await;
let search_headers = modern_call_headers("tools/call", "search_tools");
let search = modern_post(
&fixture.endpoint,
&search_headers,
modern_request_with_params(
Some(206),
"tools/call",
json!({ "name": "search_tools", "arguments": { "query": "counted" } }),
),
None,
)
.await;
assert_eq!(search.status().as_u16(), 200);
let search_body = json_body(search).await;
let search_result = &search_body["result"];
let hits = search_result["structuredContent"]["tools"]
.as_array()
.unwrap_or_else(|| panic!("the search result must carry a tools array, got {search_body}"));
assert!(
hits.iter().any(|hit| hit["name"] == COUNTED_TOOL_NAME),
"the search must return the actually published fixture tool {COUNTED_TOOL_NAME} (a bare \
`is_array` check is satisfied by an empty list), got {search_body}"
);
assert!(
search_result["structuredContent"]["catalog_revision"]
.as_str()
.is_some_and(|value| value.starts_with("agent-version-1-catalog-revision-")),
"the search result must carry the real published catalog revision, got {search_result}"
);
require_call_tool_content(search_result, "tools/call (search_tools)");
require_modern_result_type(search_result, "tools/call (search_tools)");
}
/// R25: the `call_tool` proxy success result (same table as the direct call, separately exercised).
#[tokio::test]
async fn r25_modern_call_tool_proxy_result_carries_call_tool_result_fields() {
use std::sync::atomic::Ordering;
let fixture = counted_search_agent(None).await;
let search_headers = modern_call_headers("tools/call", "search_tools");
let search = modern_post(
&fixture.endpoint,
&search_headers,
modern_request_with_params(
Some(206),
"tools/call",
json!({ "name": "search_tools", "arguments": { "query": "counted" } }),
),
None,
)
.await;
let search_body = json_body(search).await;
let catalog_revision = search_body["result"]["structuredContent"]["catalog_revision"]
.as_str()
.expect("the real search result must carry a catalog revision")
.to_owned();
let calls_before_proxy = fixture.calls.load(Ordering::SeqCst);
let proxy_headers = modern_call_headers("tools/call", "call_tool");
let proxy = modern_post(
&fixture.endpoint,
&proxy_headers,
modern_request_with_params(
Some(207),
"tools/call",
json!({
"name": "call_tool",
"arguments": proxy_call_params(
&catalog_revision,
Some(json!({ "email": "proxy@example.com" })),
),
}),
),
None,
)
.await;
assert_eq!(proxy.status().as_u16(), 200);
let proxy_body = json_body(proxy).await;
let proxy_result = &proxy_body["result"];
assert_eq!(
proxy_result["isError"], false,
"the proxy fixture must execute, got {proxy_body}"
);
require_call_tool_content(proxy_result, "tools/call (call_tool proxy)");
assert_eq!(
proxy_result["structuredContent"],
json!({ "id": "lead_123" }),
"the real upstream business output must survive the `call_tool` proxy exactly (a bare \
`is_object` check is satisfied by any object; the fixture's `output_mapping` projects \
`$.response.body.id` only), got {proxy_result}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
calls_before_proxy + 1,
"a served proxy call must perform exactly one outbound request"
);
require_modern_result_type(proxy_result, "tools/call (call_tool proxy)");
}
/// R25: the legacy era keeps its own earlier result schema. These assertions only require the legacy
/// fields that the legacy era already serves; they deliberately say nothing about modern-only fields,
/// so a later modern fix may add `resultType` to shared code without breaking this test.
#[tokio::test]
async fn r25_legacy_result_shapes_stay_legacy() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let ping = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({ "jsonrpc": "2.0", "id": 220, "method": "ping", "params": {} }),
)
.await;
assert!(
ping["result"].is_object(),
"a legacy ping result stays an object, got {ping}"
);
assert!(
ping["error"].is_null(),
"a legacy ping must not become an error, got {ping}"
);
let listed = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
tools_list_request(221),
)
.await;
assert!(
listed["result"]["tools"].is_array(),
"the legacy `tools/list` result keeps its `tools`, got {listed}"
);
let call = post_jsonrpc(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0", "id": 222, "method": "tools/call",
"params": { "name": "crm_create_lead", "arguments": { "email": "legacy-shape@example.com" } }
}),
)
.await;
assert!(
call["result"]["content"].is_array() && call["result"]["isError"].is_boolean(),
"the legacy `tools/call` result keeps `content` and `isError`, got {call}"
);
}
@@ -0,0 +1,382 @@
//! Review pass 8 identity regressions — `review8_identity` child module of `revision_matrix`.
//!
//! Bounded test-only maintenance (kanban t_f6b289ab, Story 3.1 / Gitea #8; TL triage
//! `build/review9-triage/TL-TRIAGE.md`): the three review-8 F1/F2 regressions moved verbatim
//! out of the parent module file, and their business parameters now come from the shared
//! `counted_call_params` factory. No assertion, input, header or wire expectation changed; the
//! shared parent helpers are reached through `super`.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, LEGACY_REVISION, META_CLIENT_CAPABILITIES, META_CLIENT_INFO,
MODERN_REVISION, counted_call_params, counted_tool, duplicated_header, modern_post,
};
// ---------------------------------------------------------------------------------------------
// Review pass 8 — test-only regression for two residual protocol-root defects (F1/F2).
//
// Both oracles pin the **expected** era-correct behaviour of the current binding contract
// (`protocol-era-matrix.md`, CURRENT binding section). This stage changes no production code: it
// demonstrates the behaviour of the accepted freeze on the real endpoint and hands the complete
// oracle to TL review. F1 and F2 are two distinct observed product paths, not the full set of
// reviewer candidates, and neither is a Story/Epic/release qualification.
// ---------------------------------------------------------------------------------------------
/// A modern-specific request `_meta` with **no** version field.
///
/// `clientInfo` is a valid *optional* carrier in the pinned `RequestMetaObject`, so the
/// client-info-less variant is deliberately part of the F1 oracle instead of being treated as a
/// second defect: the rejection is required for the modern-specific identity as such, not for the
/// optional field.
fn review8_modern_meta_without_version(with_client_info: bool) -> Value {
let mut meta = json!({ META_CLIENT_CAPABILITIES: {} });
if with_client_info {
meta[META_CLIENT_INFO] = json!({ "name": "crank-review8-client", "version": "0.1.0" });
}
meta
}
/// Review pass 8 (F1 / matrix rows 4 and 16): an explicit **legacy** `MCP-Protocol-Version` header
/// must not turn a modern-specific request into a legacy admission.
///
/// Static trace of the accepted freeze (`crates/crank-community-mcp/src/protocol/mod.rs`):
/// `:623-643` reads `_meta` and finds no version field → `meta_version = None`; `:671` makes the
/// *effective* identity the legacy header value, so the missing-modern-version guard `:673-706`
/// (including its `declares_modern_metadata` check at `:678`) is skipped entirely; `:726-729`
/// selects `RequestEra::Legacy`. `app.rs` then accepts that header against the live legacy session
/// (`:866-895`), authorizes the valid write credential (`:902-905`) and reaches the real catalog
/// dispatch (`:1000-1041`), which performs the outbound call.
///
/// Binding row 4 ("modern `_meta` present without a version field → reject as header validation
/// failure") and row 16 (mixed carriers are rejected for the era identified by the dominant
/// carrier, with no hidden session and no partial state) require the opposite: a `400` + `-32020`
/// `HeaderMismatch` **before** any adapter or session admission — no business dispatch, no session
/// minting, no approval conversion.
///
/// The probe is bounded to the two metadata variants (client capabilities only, and client
/// capabilities plus a valid optional `clientInfo`) and is preceded by two positive controls on the
/// same live session (a plain legacy call and a legacy call with an ordinary non-modern `_meta`
/// key). The controls prove that the fixture, the session and the write credential are valid, so
/// the rejection cannot be explained by a malformed probe, and they pin that an ordinary `_meta`
/// stays permitted for the legacy era.
#[tokio::test]
async fn review8_f1_legacy_version_header_does_not_bypass_missing_modern_version_rejection() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let session = initialize_session(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
)
.await;
// Positive control 1: a plain valid legacy `tools/call` on the same live session. This is the
// accepted legacy behaviour and must stay GREEN before and after any F1 repair.
//
// The business parameters come from the shared `counted_call_params` factory and only the
// stage-specific email is overridden, so the request body keeps exactly the previous shape (M2).
let mut plain_params = counted_call_params(COUNTED_TOOL_NAME);
plain_params["arguments"]["email"] = json!("review8-f1-control-plain@example.com");
let plain = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 811,
"method": "tools/call",
"params": plain_params
}),
)
.await;
assert!(
plain["error"].is_null(),
"the plain legacy positive control must be served, got {plain}"
);
assert_eq!(
plain["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the plain legacy positive control must return the published business payload, got {plain}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"the plain legacy positive control must perform exactly one outbound call"
);
// Positive control 2: the same valid legacy call with an ordinary (non-modern) `_meta` key. The
// legacy era requires no client metadata, and a fix for F1 must not ban every `_meta` object.
// Same shared factory, same fixed email override and the same explicit ordinary `_meta` probe.
let mut ordinary_params = counted_call_params(COUNTED_TOOL_NAME);
ordinary_params["arguments"]["email"] = json!("review8-f1-control-ordinary-meta@example.com");
ordinary_params["_meta"] = json!({ "crank.probe": "ordinary" });
let ordinary_meta = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0",
"id": 812,
"method": "tools/call",
"params": ordinary_params
}),
)
.await;
assert!(
ordinary_meta["error"].is_null(),
"an ordinary non-modern `_meta` must not break a valid legacy call, got {ordinary_meta}"
);
assert_eq!(
ordinary_meta["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the ordinary-`_meta` positive control must return the published business payload, got \
{ordinary_meta}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
2,
"the second positive control must perform exactly one additional outbound call"
);
let calls_before_probe = fixture.calls.load(Ordering::SeqCst);
// The probe: an otherwise valid legacy-shaped `tools/call` whose `_meta` carries the
// modern-specific client identity without any version field, plus the explicit legacy version
// header on the same initialized session.
for (variant, with_client_info, id, correlation) in [
(
"clientCapabilities only",
false,
813_i64,
"review8-f1-capabilities-only",
),
(
"clientCapabilities plus clientInfo",
true,
814_i64,
"review8-f1-client-info",
),
] {
let headers = vec![
("MCP-Session-Id", session.clone()),
("MCP-Protocol-Version", LEGACY_REVISION.to_owned()),
];
let mut probe_params = counted_call_params(COUNTED_TOOL_NAME);
probe_params["arguments"]["email"] = json!("review8-f1@example.com");
// The adversarial modern-specific `_meta` stays exactly what it was: the same builder, still
// without any version carrier, so the probe only adds it to the shared business shape.
probe_params["_meta"] = review8_modern_meta_without_version(with_client_info);
let probe = json!({
"jsonrpc": "2.0",
"id": id,
"method": "tools/call",
"params": probe_params
});
let response = modern_post(&fixture.endpoint, &headers, probe, Some(correlation)).await;
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"{variant}: a rejected request must not mint a session"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"{variant}: modern `_meta` without a version carrier must be rejected even when a \
legacy version header is present (matrix rows 4/16), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"{variant}: the row-4 rejection must be a structured diagnostic, but the body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"{variant}: the row-4 rejection must be a JSON-RPC envelope, got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"{variant}: the rejection must be a JSON-RPC 2.0 envelope, got {body}"
);
assert_eq!(
body["id"],
json!(id),
"{variant}: the rejection must keep the request id, got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"{variant}: a modern-specific identity without its required version carrier is a \
header-validation failure (matrix row 4), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"{variant}: the rejection must carry a non-empty message, got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"{variant}: the rejection must preserve the request correlation, got {body}"
);
assert!(
body.get("result").is_none(),
"{variant}: a rejected request must not carry a result, got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
calls_before_probe,
"{variant}: modern-specific metadata without a version carrier must not be executed as a \
legacy request"
);
}
}
/// Review pass 8 (F2 / matrix rows 3, 16 and 17): the era of an ambiguous `MCP-Session-Id` carrier
/// is read from the unambiguous part of the request, and a valid modern `MCP-Protocol-Version`
/// header is such a marker.
///
/// Static trace of the accepted freeze: `app.rs` `:827-830` projects
/// `protocol::ambiguous_session_carrier_response` (`protocol/mod.rs` `:480-488`) **before** era
/// resolution, and that projection asks `declares_modern_identity` (`:495-508`), which inspects only
/// the `Mcp-Method` header and the request `_meta`. A request that carries
/// `MCP-Protocol-Version: 2026-07-28` but no `Mcp-Method` and no `_meta` is therefore diagnosed in
/// the **legacy** shape (`:486` → `error_response` `:312-318`, `400` + `-32602`). Row 3 forbids
/// exactly that: "a modern header never routes the request into the legacy branch", and row 17
/// requires the era-correct structured diagnostic for an ambiguous carrier.
///
/// This is a compound *diagnostic* failure, not a successful modern admission: the request is
/// intentionally missing its required modern metadata and `Mcp-Method` header, so the expected
/// outcome stays a rejection — but the modern one (row 3/17: `400` + `-32020`) instead of a legacy
/// `-32602`. No result, no session minting and no outbound request in either shape.
async fn assert_modern_version_header_selects_the_modern_carrier_diagnostic(
session_values: [&'static str; 2],
correlation: &str,
id: Value,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(None, &[PlatformApiKeyScope::Read]).await;
let message = json!({
"jsonrpc": "2.0",
"id": id.clone(),
"method": "tools/list",
"params": {}
});
let response = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation)
.headers(duplicated_header("mcp-session-id", session_values))
.header("MCP-Protocol-Version", MODERN_REVISION)
.json(&message)
.send()
.await
.unwrap();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"an ambiguous session carrier must not mint a session ({correlation})"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"an ambiguous session carrier is a safe rejection ({correlation}), got {raw}"
);
assert!(
!raw.trim().is_empty(),
"row 17 requires the era-correct structured diagnostic for an ambiguous session carrier \
({correlation}), but the response body was empty"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the ambiguous-session diagnostic must be JSON-RPC ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the ambiguous-session diagnostic must be a JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"], id,
"the ambiguous-session diagnostic must keep the request id ({correlation}), got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32020),
"matrix row 3: a request carrying a valid unambiguous modern version header must not be \
diagnosed in the legacy shape ({correlation}), got {body}"
);
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the diagnostic must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the diagnostic must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a result ({correlation}), got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an ambiguous identity must not reach the upstream ({correlation})"
);
}
/// Review pass 8 (F2): the numeric request id, first conflicting-value order.
#[tokio::test]
async fn review8_f2_modern_version_header_selects_the_modern_carrier_diagnostic() {
assert_modern_version_header_selects_the_modern_carrier_diagnostic(
["review8-f2-session-a", "review8-f2-session-b"],
"review8-f2-numeric-id",
json!(1),
)
.await;
}
/// Review pass 8 (F2, bounded sibling): the same compound diagnostic with a valid `string` request id
/// and the opposite conflicting-value order. The pinned `RequestId` is `string | number`, so the
/// diagnostic must keep the modern era shape and preserve the valid string id as well — this is one
/// bounded projection, not a cross-product of era × id × order.
#[tokio::test]
async fn review8_f2_string_request_id_keeps_the_modern_carrier_diagnostic() {
assert_modern_version_header_selects_the_modern_carrier_diagnostic(
["review8-f2-session-b", "review8-f2-session-a"],
"review8-f2-string-id",
json!("review8-f2-string"),
)
.await;
}
@@ -0,0 +1,424 @@
//! Session-carrier guards: an ambiguous or unusable `MCP-Session-Id` is rejected by the same
//! structured diagnostic per era, and never echoes the invalid value.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use serde_json::{Value, json};
use super::harness::{
COUNTED_TOOL_NAME, DuplicateSessionCarrierEra, LEGACY_REVISION, MODERN_REVISION,
counted_call_params, counted_tool, duplicated_header, endpoint, json_body, modern_headers,
modern_post, modern_request_with_params, oracle_status, tools_list_request,
};
/// AT-3.1-11 (wm-07): without a version header a live legacy session establishes the revision.
#[tokio::test]
async fn at_3_1_11_subsequent_request_without_version_header_keeps_session_revision() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[("MCP-Session-Id", session.as_str())],
tools_list_request(10),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-07"),
"a live legacy session with no version header must still be served"
);
let echoed = response
.headers()
.get("MCP-Protocol-Version")
.map(|value| value.to_str().unwrap().to_owned());
assert_eq!(
echoed.as_deref(),
Some(LEGACY_REVISION),
"the negotiated session revision must identify the era"
);
}
/// AT-3.1-11 (wm-08): a session-requiring era rejects a request without the session header.
#[tokio::test]
async fn at_3_1_11_subsequent_request_without_session_header_is_rejected() {
let endpoint = endpoint().await;
let _session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[("MCP-Protocol-Version", LEGACY_REVISION)],
tools_list_request(11),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-08"),
"a request without the required session header must be rejected"
);
}
/// AT-3.1-11 (wm-09 / wm-14): a terminated session is answered with `404`, never resurrected.
#[tokio::test]
async fn at_3_1_11_terminated_session_is_rejected_with_not_found() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let deleted = endpoint
.client
.delete(&endpoint.mcp_url)
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.header("MCP-Session-Id", &session)
.header("MCP-Protocol-Version", LEGACY_REVISION)
.header(header::ORIGIN, "https://crank.example.com")
.send()
.await
.unwrap();
assert!(
deleted.status().is_success() || deleted.status().as_u16() == 405,
"session termination must be accepted or explicitly unsupported, got {}",
deleted.status()
);
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[
("MCP-Session-Id", session.as_str()),
("MCP-Protocol-Version", LEGACY_REVISION),
],
tools_list_request(12),
)
.await;
assert_eq!(
response.status().as_u16(),
oracle_status("wm-09"),
"a terminated session must be answered with 404 and never restored"
);
}
/// R4: conflicting/modern identity with a session carrier must be rejected before dispatch.
#[tokio::test]
async fn r4_modern_identity_with_unknown_session_header_is_rejected() {
let endpoint = endpoint().await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", "session-that-never-existed".to_owned()));
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(60), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"an unknown session carrier must not be ignored by the modern path"
);
let body = json_body(response).await;
assert!(body["result"].is_null(), "got {body}");
}
#[tokio::test]
async fn r4_modern_identity_with_live_legacy_session_header_is_rejected() {
let endpoint = endpoint().await;
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", session.clone()));
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(61), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"mixed modern identity plus a legacy session carrier must be rejected"
);
}
/// R4 (observable half only): a modern request carrying an unknown session id must be rejected for the
/// carrier conflict. The quota question itself stays **NOT PROVEN** — it needs an observable counter over
/// the session-keyed limiter, which this harness does not expose.
#[tokio::test]
async fn r4_mixed_carrier_rejection_is_observable_quota_is_not_proven() {
let endpoint = endpoint().await;
let mut headers = modern_headers(MODERN_REVISION, "tools/list");
headers.push(("MCP-Session-Id", "quota-probe-session".to_owned()));
let first = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(62), "tools/list", json!({})),
None,
)
.await;
assert_eq!(
first.status().as_u16(),
400,
"a modern request with an unknown session carrier must be rejected"
);
}
/// The two ways `session_id_from_headers` (`transport.rs` 227-229 → `singleton_header` 177-194)
/// reports an unusable `MCP-Session-Id`. Both surface as the same `Err(_status)` projection branch in
/// `mcp_post_response` (`app.rs` 827-830), so they are one root class for the diagnostic.
enum UnusableSessionCarrier {
/// Two conflicting session values: the carrier cannot identify the era or the session.
Conflicting([&'static str; 2]),
/// A non-text value. HTTP/1.1 allows `obs-text` (bytes `0x80-0xFF`) in a field value, so this is a
/// real transferable value that fails `HeaderValue::to_str()` inside `singleton_header`.
Unreadable,
}
/// Review pass 7 (G1): an otherwise-valid request whose `id` is **not** a valid request id must never
/// have that value echoed back.
///
/// `mcp_post_response` projects the ambiguous/unusable-session diagnostic (`app.rs` 827-830 →
/// `protocol::ambiguous_session_carrier_response` 461-468) **before** the single JSON-RPC envelope
/// guard (`app.rs` 832-837), and that projection reads the raw body id through `jsonrpc::request_id`
/// (`jsonrpc.rs` 32-33). The pinned `RequestId` is `string | number`, and the established
/// invalid-request convention answers with a `null` id precisely because an unvalidated value must
/// never be echoed (`protocol/mod.rs` 164-170).
///
/// This oracle pins that safety property only: the era-correct diagnostic keeps one of the existing
/// structured codes (modern `-32020` or the invalid-request `-32600`; legacy numeric and never
/// `-32020`/`-32022`) and the id is `null` instead of `{}`/`true`/`[]`. It deliberately invents no new
/// compound-case code and does not require the envelope guard to move; the valid-id shapes stay the
/// accepted P3 contract.
async fn assert_unusable_session_carrier_never_echoes_an_invalid_id(
carrier: UnusableSessionCarrier,
correlation: &str,
invalid_id: Value,
era: DuplicateSessionCarrierEra,
) {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let mut request = fixture
.endpoint
.client
.post(&fixture.endpoint.mcp_url)
.header(
reqwest::header::ACCEPT,
"application/json, text/event-stream",
)
.header(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", fixture.endpoint.api_key),
)
.header("x-request-id", correlation);
request = match carrier {
UnusableSessionCarrier::Conflicting(values) => {
request.headers(duplicated_header("mcp-session-id", values))
}
UnusableSessionCarrier::Unreadable => {
let mut headers = reqwest::header::HeaderMap::new();
headers.append(
reqwest::header::HeaderName::from_static("mcp-session-id"),
reqwest::header::HeaderValue::from_bytes(&[b'x', 0xf8, 0xfe]).unwrap(),
);
request.headers(headers)
}
};
// The request is otherwise valid for its era: only the session carrier and the id are faulty.
let mut message = match era {
DuplicateSessionCarrierEra::Modern => {
request = request
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "tools/call")
.header("Mcp-Name", COUNTED_TOOL_NAME);
modern_request_with_params(None, "tools/call", counted_call_params(COUNTED_TOOL_NAME))
}
DuplicateSessionCarrierEra::Legacy => {
request = request.header("MCP-Protocol-Version", LEGACY_REVISION);
json!({
"jsonrpc": "2.0",
"method": "tools/call",
"params": counted_call_params(COUNTED_TOOL_NAME)
})
}
};
message["id"] = invalid_id.clone();
let response = request.json(&message).send().await.unwrap();
assert!(
response.headers().get("MCP-Session-Id").is_none(),
"a rejected request must not mint a session ({correlation})"
);
let status = response.status().as_u16();
let raw = response.text().await.unwrap();
assert_eq!(
status, 400,
"an unusable session carrier must be a safe rejection ({correlation}), got {raw}"
);
let body: Value = serde_json::from_str(&raw).unwrap_or_else(|error| {
panic!(
"the unusable-session diagnostic must be JSON-RPC ({correlation}), got {raw:?}: {error}"
)
});
assert_eq!(
body["jsonrpc"], "2.0",
"the diagnostic must be a complete JSON-RPC 2.0 envelope ({correlation}), got {body}"
);
assert_eq!(
body["id"],
Value::Null,
"an invalid request id must never be echoed; the established invalid-request convention \
answers with a null id ({correlation}), got {body}"
);
assert!(
!body["id"].is_object() && !body["id"].is_boolean() && !body["id"].is_array(),
"the response id must never be the unvalidated value ({correlation}), got {body}"
);
let code = body["error"]["code"].clone();
assert!(
code.is_i64(),
"the diagnostic must carry a numeric JSON-RPC error code ({correlation}), got {body}"
);
assert_ne!(
code,
json!(-32022),
"the UnsupportedProtocolVersion code is reserved for a well-formed unknown identity \
({correlation}), got {body}"
);
match era {
DuplicateSessionCarrierEra::Modern => assert!(
code == json!(-32020) || code == json!(-32600),
"the modern shape keeps an existing structured code (header mismatch or invalid \
request) ({correlation}), got {body}"
),
DuplicateSessionCarrierEra::Legacy => assert_ne!(
code,
json!(-32020),
"the modern HeaderMismatch code must not be imposed on a legacy-sourced rejection \
({correlation}), got {body}"
),
}
assert!(
body["error"]["message"]
.as_str()
.is_some_and(|message| !message.trim().is_empty()),
"the diagnostic must carry a non-empty message ({correlation}), got {body}"
);
assert_eq!(
body["error"]["data"]["request_id"],
json!(correlation),
"the diagnostic must preserve the request correlation ({correlation}), got {body}"
);
assert!(
body.get("result").is_none(),
"a rejected request must not carry a result ({correlation}), got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an unusable identity must not reach the upstream ({correlation})"
);
}
/// Review pass 7 (G1): modern identity, conflicting session carriers (a first), invalid object id.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-modern-object-id",
json!({}),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): the same modern case with the conflicting values in the opposite order and a
/// boolean id — the outcome must not depend on the header order or on the id's invalid kind.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_boolean_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-b", "review7-g1-session-a"]),
"review7-g1-modern-boolean-id",
json!(true),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): the third invalid id kind (an array) on the modern identity.
#[tokio::test]
async fn review7_g1_modern_ambiguous_session_carrier_with_array_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-modern-array-id",
json!([]),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
/// Review pass 7 (G1): legacy identity, conflicting session carriers, invalid object id. The legacy
/// diagnostic stays legacy-shaped and must still never echo the invalid id.
#[tokio::test]
async fn review7_g1_legacy_ambiguous_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-a", "review7-g1-session-b"]),
"review7-g1-legacy-object-id",
json!({}),
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
/// Review pass 7 (G1): the legacy case, reversed order, array id.
#[tokio::test]
async fn review7_g1_legacy_ambiguous_session_carrier_with_array_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Conflicting(["review7-g1-session-b", "review7-g1-session-a"]),
"review7-g1-legacy-array-id",
json!([]),
DuplicateSessionCarrierEra::Legacy,
)
.await;
}
/// Review pass 7 (G1): an **unreadable** (non-text) session carrier reaches the same projection branch,
/// so the same no-echo guarantee is pinned for it.
#[tokio::test]
async fn review7_g1_modern_unreadable_session_carrier_with_object_id_is_safe() {
assert_unusable_session_carrier_never_echoes_an_invalid_id(
UnusableSessionCarrier::Unreadable,
"review7-g1-modern-unreadable-carrier",
json!({}),
DuplicateSessionCarrierEra::Modern,
)
.await;
}
@@ -0,0 +1,904 @@
//! `tools/call` authorization and arguments: read-only keys, missing/mismatched/unknown/encoded
//! tool names, wire-response shape, inner-arguments shape of the proxy path and the approval-side
//! side-effect guards.
//!
//! Tests moved verbatim from `revision_matrix.rs` (Story 3.6, kanban t_987bf309); only the module
//! prefix changed.
use super::super::common::*;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use crank_registry::{PostgresRegistry, PublishRequest};
use serde_json::{Value, json};
use std::sync::Arc;
use std::{path::PathBuf, time::Duration};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use super::harness::{
COUNTED_TOOL_NAME, Endpoint, MODERN_REVISION, counted_call_params, counted_search_agent,
counted_tool, endpoint, json_body, modern_call_headers, modern_post,
modern_request_with_params, pending_approvals, proxy_call_params, spawn_counted_lead_upstream,
};
/// R1: a valid modern `tools/call` must return the same published tool result as the legacy era.
#[tokio::test]
async fn r1_modern_tools_call_returns_the_published_tool_result() {
let endpoint = endpoint().await;
let headers = modern_call_headers("tools/call", "crm_create_lead");
let message = modern_request_with_params(
Some(40),
"tools/call",
json!({
"name": "crm_create_lead",
"arguments": { "email": "modern@example.com" }
}),
);
let response = modern_post(&endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
200,
"a valid modern tools/call must be served"
);
let body = json_body(response).await;
assert!(
body["error"].is_null(),
"a valid modern tools/call must not return a JSON-RPC error, got {body}"
);
assert_eq!(
body["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"the modern era must return the same business result as the legacy era, got {body}"
);
assert_eq!(body["result"]["isError"], false, "got {body}");
}
/// R1 (approval parity half): a real Custom-approval operation plus a counted upstream. The legacy era
/// defines the pinned pending outcome; the modern era must reach the same pending outcome and must not
/// perform the outbound call while approval is pending.
#[tokio::test]
async fn r1_modern_custom_approval_pending_before_outbound() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::{sync::Arc, sync::atomic::Ordering};
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let upstream_base_url = spawn_counted_lead_upstream(Arc::clone(&calls)).await;
let registry = test_registry().await;
let mut operation = test_operation(&upstream_base_url, "crm_requires_human_approval");
operation.execution_config.approval_policy = Some(OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
});
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-gated").await;
let api_key = create_platform_api_key(
&registry,
"sales-gated",
"mcp-gated",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "sales-gated");
let call_params = json!({
"name": "crm_requires_human_approval",
"arguments": { "email": "ada@example.com" }
});
// Legacy oracle: the pinned pending outcome on the same operation.
let session = initialize_session(&client, &mcp_url, &api_key).await;
let legacy = post_jsonrpc(
&client,
&mcp_url,
&api_key,
Some(&session),
json!({ "jsonrpc": "2.0", "id": 42, "method": "tools/call", "params": call_params.clone() }),
)
.await;
assert_eq!(
legacy["result"]["structuredContent"]["status"], "approval_required",
"the legacy era is the pinned oracle for the approval outcome, got {legacy}"
);
assert_eq!(
calls.load(Ordering::SeqCst),
0,
"the legacy pending outcome must not perform the outbound call"
);
// Modern era: same operation, same expectation, no session.
let endpoint = Endpoint {
registry: registry.clone(),
client,
mcp_url,
api_key,
};
let headers = modern_call_headers("tools/call", "crm_requires_human_approval");
let response = modern_post(
&endpoint,
&headers,
modern_request_with_params(Some(43), "tools/call", call_params),
None,
)
.await;
assert_eq!(
response.status().as_u16(),
200,
"the modern era must serve an approval-gated tool call"
);
let modern = json_body(response).await;
assert_eq!(
modern["result"]["structuredContent"]["status"], "approval_required",
"the modern era must reach the same pending outcome as the legacy oracle, got {modern}"
);
assert_eq!(modern["result"]["isError"], false, "got {modern}");
assert!(
modern["result"]["structuredContent"]["approval_id"]
.as_str()
.is_some_and(|value| value.starts_with("approval_")),
"a pending approval id must be returned, got {modern}"
);
assert_eq!(
calls.load(Ordering::SeqCst),
0,
"a pending approval must not perform the outbound call while awaiting approval"
);
}
/// R1: a read-only platform key must not reach a mutating modern tool call, and no outbound request may
/// happen before the scope check.
#[tokio::test]
async fn r1_modern_tools_call_with_read_only_key_is_unauthorized_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(None, &[PlatformApiKeyScope::Read]).await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let message = modern_request_with_params(
Some(100),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
let status = response.status().as_u16();
assert!(
status == 401 || status == 403,
"a read-only key must not perform a mutating tool call, got {status}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"the scope check must run before any outbound request"
);
}
/// R1: `Mcp-Name` is required for `tools/call`; a missing header is a header-validation failure.
#[tokio::test]
async fn r1_modern_tools_call_rejects_missing_mcp_name_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = vec![
("MCP-Protocol-Version", MODERN_REVISION.to_owned()),
("Mcp-Method", "tools/call".to_owned()),
];
let message = modern_request_with_params(
Some(101),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
400,
"a missing required `Mcp-Name` header must be rejected"
);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"header validation must run before any outbound request"
);
}
/// R1: a `Mcp-Name` that does not match the body value must be rejected before dispatch.
#[tokio::test]
async fn r1_modern_tools_call_rejects_mismatched_mcp_name_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", "some_other_tool");
let message = modern_request_with_params(
Some(102),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 400);
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32020), "got {body}");
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a mismatched name must not reach the upstream"
);
}
/// R1: an unknown tool is reported without any outbound request.
#[tokio::test]
async fn r1_modern_tools_call_rejects_unknown_tool_without_outbound() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", "crm_missing_tool");
let message = modern_request_with_params(
Some(103),
"tools/call",
counted_call_params("crm_missing_tool"),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
let body = json_body(response).await;
assert_eq!(body["error"]["code"], json!(-32602), "got {body}");
assert!(body["result"].is_null(), "got {body}");
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"an unknown tool must not reach the upstream"
);
}
/// R1: the sentinel-encoded `Mcp-Name` must be decoded before the comparison, and a matching encoded
/// name must be served like a plain one.
#[tokio::test]
async fn r1_modern_tools_call_accepts_sentinel_encoded_mcp_name() {
use std::sync::atomic::Ordering;
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", "=?base64?Y3JtX2NvdW50ZWRfbGVhZA==?=");
let message = modern_request_with_params(
Some(104),
"tools/call",
counted_call_params(COUNTED_TOOL_NAME),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(
response.status().as_u16(),
200,
"a correctly encoded `Mcp-Name` must be accepted"
);
let body = json_body(response).await;
assert_eq!(
body["result"]["structuredContent"],
json!({ "id": "lead_123" }),
"got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
1,
"a matching encoded name must reach the upstream exactly once"
);
}
/// R16: the wire-response branch of the envelope guard must validate the response shape too. Pinned
/// schema: a success response carries `id: RequestId` (`string | number`) plus `result`; an error
/// response carries `error: Error { code: number; message: string }` and may omit the id — the two are
/// exclusive, and neither may be a foreign type. A malformed response must be `400 -32600`, not `202`.
///
/// R27 adds the single-fault `message` cases of the same `Error` shape: a correct numeric `code` with an
/// absent or non-string `message` is still an invalid response (this is a verification gap, not a new
/// defect — the same guard already covers it).
#[tokio::test]
async fn r16_malformed_wire_response_is_rejected() {
let endpoint = endpoint().await;
let malformed = [
json!({ "jsonrpc": "2.0", "id": 1, "error": null }),
json!({ "jsonrpc": "2.0", "id": 1, "error": false }),
json!({ "jsonrpc": "2.0", "id": 1, "result": {}, "error": { "code": -32000, "message": "x" } }),
json!({ "jsonrpc": "2.0", "id": {}, "result": {} }),
json!({ "jsonrpc": "2.0", "result": {} }),
json!({ "jsonrpc": "2.0", "id": 1, "error": { "message": "missing code" } }),
// R27 single-fault cases: the numeric `code` is correct, only `message` is wrong/absent.
json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000 } }),
json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": 42 } }),
json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": null } }),
];
for (index, body) in malformed.iter().enumerate() {
let request_id = format!("r16-malformed-response-{index}");
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[("x-request-id", request_id.as_str())],
body.clone(),
)
.await;
assert_eq!(
response.status().as_u16(),
400,
"a malformed response envelope must be rejected, got {body}"
);
let payload = json_body(response).await;
assert_eq!(payload["error"]["code"], json!(-32600), "got {payload}");
assert!(
payload["id"].is_null(),
"an invalid request must answer with a null id, got {payload}"
);
if index == 0 {
assert_eq!(
payload["error"]["data"]["request_id"],
json!(request_id),
"the rejection must keep the ingress correlation, got {payload}"
);
}
}
}
/// R16 (positive half): legitimate wire responses keep the existing acknowledgement policy.
#[tokio::test]
async fn r16_valid_wire_response_is_acknowledged() {
let endpoint = endpoint().await;
for body in [
json!({ "jsonrpc": "2.0", "id": 1, "result": {} }),
json!({ "jsonrpc": "2.0", "id": "req-1", "result": { "ok": true } }),
json!({ "jsonrpc": "2.0", "id": 1, "error": { "code": -32000, "message": "boom" } }),
json!({ "jsonrpc": "2.0", "error": { "code": -32000, "message": "boom" } }),
] {
let response = post_jsonrpc_with_headers(
&endpoint.client,
&endpoint.mcp_url,
&endpoint.api_key,
&[],
body.clone(),
)
.await;
assert_eq!(
response.status().as_u16(),
202,
"a well-formed wire response stays acknowledged, got {body}"
);
assert!(
response.text().await.unwrap().is_empty(),
"an acknowledgement carries no body, got {body}"
);
}
}
/// R20: the pinned `CallToolRequest.params.arguments` is an optional object, so an array or scalar
/// arguments value is invalid params — and it must be rejected **before** an approval policy can
/// persist a pending request. The registry state is read around the calls, not inferred from the
/// response. Omitted arguments keep their existing behaviour (`r20_modern_tools_call_without_arguments_is_preserved`).
#[tokio::test]
async fn r20_modern_tools_call_with_non_object_arguments_creates_no_pending_approval() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
let mut observed = Vec::new();
for bad_arguments in [json!([1, 2]), json!(5), json!("not-an-object")] {
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(150),
"tools/call",
json!({ "name": COUNTED_TOOL_NAME }),
);
message["params"]["arguments"] = bad_arguments.clone();
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
let body = json_body(response).await;
observed.push((bad_arguments, body));
}
// The registry state is checked first: it is the authoritative proof that a malformed arguments
// shape did not create a pending approval request.
let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
assert_eq!(
after, before,
"no pending approval request may be persisted for a malformed arguments shape; observed: {observed:?}"
);
for (bad_arguments, body) in observed {
assert_eq!(
body["error"]["code"],
json!(-32602),
"arguments {bad_arguments} must be invalid params, got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"a malformed arguments shape must not yield a pending approval, got {body}"
);
}
assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
}
/// R20 (preserved behaviour): omitting `arguments` entirely stays a valid method call — it reaches the
/// operation's own input validation instead of being rejected as an invalid `tools/call` parameter
/// shape. The fixture operation requires `email`, so the runtime answers `input_schema_invalid`; the
/// point of the regression is that the *method* shape was accepted (`error` is null, no `-32602`), which
/// the R20 fix must not change.
#[tokio::test]
async fn r20_modern_tools_call_without_arguments_is_preserved() {
let fixture = counted_tool(
None,
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let message = modern_request_with_params(
Some(151),
"tools/call",
json!({ "name": COUNTED_TOOL_NAME }),
);
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
assert_eq!(response.status().as_u16(), 200);
let body = json_body(response).await;
assert!(
body["error"].is_null(),
"omitted arguments are not a parameter-shape error, got {body}"
);
assert_eq!(body["result"]["isError"], true, "got {body}");
assert_eq!(
body["result"]["structuredContent"]["error"]["code"],
json!("input_schema_invalid"),
"the fixture operation requires `email`, got {body}"
);
}
/// R20 (fix, corrected oracle): an explicit `null` is *not* an omitted `arguments`. The pinned
/// `CallToolRequest.params.arguments` is an optional object, and an explicit null is not an object, so
/// the method param shape must be rejected as invalid params before any approval is persisted.
#[tokio::test]
async fn r20_modern_tools_call_with_null_arguments_is_rejected() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
let headers = modern_call_headers("tools/call", COUNTED_TOOL_NAME);
let mut message = modern_request_with_params(
Some(152),
"tools/call",
json!({ "name": COUNTED_TOOL_NAME }),
);
message["params"]["arguments"] = Value::Null;
let response = modern_post(&fixture.endpoint, &headers, message, None).await;
let body = json_body(response).await;
// Registry state first: it is the authoritative proof that no pending approval was persisted.
let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
assert_eq!(
after, before,
"an explicit null arguments must not persist a pending approval request; got {body}"
);
assert_eq!(
body["error"]["code"],
json!(-32602),
"an explicit null `arguments` is not an object and must be invalid params, got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"an explicit null must not reach the approval path, got {body}"
);
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"no outbound request may happen for an invalid params shape"
);
}
/// R20 (same defect class, legacy sibling): the shared `tools/call` param shape protects the legacy era
/// too, so a non-object `arguments` on a real legacy session is invalid params without a pending
/// approval or an outbound request. The legacy exposure may predate this slice; the test records the
/// current behaviour of the shared guard rather than claiming a new legacy regression.
#[tokio::test]
async fn r20_legacy_tools_call_with_non_object_arguments_is_rejected() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_tool(
Some(policy),
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
let session = initialize_session(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
)
.await;
let mut observed = Vec::new();
for bad_arguments in [json!([1, 2]), json!(7), Value::Null] {
let payload = json!({
"jsonrpc": "2.0",
"id": 153,
"method": "tools/call",
"params": { "name": COUNTED_TOOL_NAME, "arguments": bad_arguments.clone() },
});
let response = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
payload,
)
.await;
observed.push((bad_arguments, response));
}
let after = pending_approvals(&fixture.endpoint.registry, "sales-gated").await;
assert_eq!(
after, before,
"the legacy era must not persist a pending approval for a malformed arguments shape; observed: {observed:?}"
);
for (bad_arguments, body) in observed {
assert_eq!(
body["error"]["code"],
json!(-32602),
"legacy arguments {bad_arguments} must be invalid params, got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"the legacy era must not reach the approval path, got {body}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"no legacy outbound request may happen for an invalid params shape"
);
}
/// R23 (legacy era): a `call_tool` proxy call whose inner `arguments` violates the advertised required
/// object must be rejected as invalid params before any approval is persisted.
///
/// Provenance: the proxy consumer is shared by both eras, so this bypass pre-existed the modern
/// revision work — it is recorded here as a reproduced defect, not as a new modern-era regression.
#[tokio::test]
async fn r23_legacy_proxy_inner_arguments_shape_is_rejected_before_approval() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_search_agent(Some(policy)).await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-proxy").await;
let session = initialize_session(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
)
.await;
let search = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0", "id": 700, "method": "tools/call",
"params": { "name": "search_tools", "arguments": { "query": "counted" } }
}),
)
.await;
let catalog_revision = search["result"]["structuredContent"]["catalog_revision"]
.as_str()
.expect("the real search result must carry a catalog revision")
.to_owned();
let mut observed = Vec::new();
for inner in [
Some(Value::Null),
Some(json!([1, 2])),
Some(json!(5)),
Some(json!("not-an-object")),
Some(json!(true)),
None,
] {
let payload = json!({
"jsonrpc": "2.0", "id": 701, "method": "tools/call",
"params": {
"name": "call_tool",
"arguments": proxy_call_params(&catalog_revision, inner.clone()),
}
});
let response = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
payload,
)
.await;
observed.push((inner, response));
}
// Registry state first: it is the authoritative proof that no pending approval was persisted.
let after = pending_approvals(&fixture.endpoint.registry, "sales-proxy").await;
assert_eq!(
after, before,
"an inner arguments shape that violates the advertised `call_tool` schema must not persist a \
pending approval; observed: {observed:?}"
);
for (inner, body) in observed {
assert_eq!(
body["error"]["code"],
json!(-32602),
"inner arguments {inner:?} must be rejected by the existing invalid-arguments contract, \
got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"the proxy must not reach the approval path, got {body}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a malformed proxy call must not reach the upstream"
);
// Positive half: a nested object keeps the real proxy approval outcome.
let accepted = post_jsonrpc(
&fixture.endpoint.client,
&fixture.endpoint.mcp_url,
&fixture.endpoint.api_key,
Some(&session),
json!({
"jsonrpc": "2.0", "id": 702, "method": "tools/call",
"params": {
"name": "call_tool",
"arguments": proxy_call_params(&catalog_revision, Some(json!({}))),
}
}),
)
.await;
assert_eq!(
accepted["result"]["structuredContent"]["status"], "approval_required",
"a valid nested object must keep the Custom approval outcome, got {accepted}"
);
assert_eq!(
pending_approvals(&fixture.endpoint.registry, "sales-proxy").await,
before + 1,
"the accepted proxy call must persist exactly one pending approval"
);
}
/// R23 (modern era): the same nested bypass through the modern stateless path.
#[tokio::test]
async fn r23_modern_proxy_inner_arguments_shape_is_rejected_before_approval() {
use crank_core::{
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
OperationApprovalRiskLevel,
};
use std::sync::atomic::Ordering;
let policy = OperationApprovalPolicy {
required: true,
mode: OperationApprovalMode::Custom,
risk_level: OperationApprovalRiskLevel::Dangerous,
ttl_seconds: 300,
show_payload_preview: true,
payload_preview_mode: OperationApprovalPayloadPreviewMode::MaskedJson,
elicitation_message: None,
};
let fixture = counted_search_agent(Some(policy)).await;
let before = pending_approvals(&fixture.endpoint.registry, "sales-proxy").await;
let search_headers = modern_call_headers("tools/call", "search_tools");
let search = modern_post(
&fixture.endpoint,
&search_headers,
modern_request_with_params(
Some(710),
"tools/call",
json!({ "name": "search_tools", "arguments": { "query": "counted" } }),
),
None,
)
.await;
assert_eq!(search.status().as_u16(), 200);
let search_body = json_body(search).await;
let catalog_revision = search_body["result"]["structuredContent"]["catalog_revision"]
.as_str()
.expect("the real search result must carry a catalog revision")
.to_owned();
let headers = modern_call_headers("tools/call", "call_tool");
let mut observed = Vec::new();
for inner in [
Some(Value::Null),
Some(json!([1, 2])),
Some(json!(5)),
Some(json!("not-an-object")),
None,
] {
let response = modern_post(
&fixture.endpoint,
&headers,
modern_request_with_params(
Some(711),
"tools/call",
json!({
"name": "call_tool",
"arguments": proxy_call_params(&catalog_revision, inner.clone()),
}),
),
None,
)
.await;
assert_eq!(response.status().as_u16(), 200, "got {inner:?}");
let body = json_body(response).await;
observed.push((inner, body));
}
let after = pending_approvals(&fixture.endpoint.registry, "sales-proxy").await;
assert_eq!(
after, before,
"an inner arguments shape that violates the advertised `call_tool` schema must not persist a \
pending approval on the modern path; observed: {observed:?}"
);
for (inner, body) in observed {
assert_eq!(
body["error"]["code"],
json!(-32602),
"inner arguments {inner:?} must be rejected by the existing invalid-arguments contract, \
got {body}"
);
assert!(
!body.to_string().contains("approval_id"),
"the proxy must not reach the approval path, got {body}"
);
}
assert_eq!(
fixture.calls.load(Ordering::SeqCst),
0,
"a malformed proxy call must not reach the upstream"
);
let accepted = modern_post(
&fixture.endpoint,
&headers,
modern_request_with_params(
Some(712),
"tools/call",
json!({
"name": "call_tool",
"arguments": proxy_call_params(&catalog_revision, Some(json!({ "email": "proxy@example.com" }))),
}),
),
None,
)
.await;
let accepted_body = json_body(accepted).await;
assert_eq!(
accepted_body["result"]["structuredContent"]["status"], "approval_required",
"a valid nested object must keep the Custom approval outcome, got {accepted_body}"
);
assert_eq!(
pending_approvals(&fixture.endpoint.registry, "sales-proxy").await,
before + 1,
"the accepted proxy call must persist exactly one pending approval"
);
}