//! 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 { 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(®istry, &operation, "sales-rest").await; let api_key = create_platform_api_key( ®istry, "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, 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, ) -> String { use axum::routing::post; let handler_calls = Arc::clone(&calls); let app = Router::new().route( "/crm/leads", post(move |Json(payload): Json| { 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, } /// 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, 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(®istry, &operation, "sales-gated").await; let api_key = create_platform_api_key(®istry, "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, ) -> 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( ®istry, "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( ®istry, "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 { let mut wrapper = json!({ "name": COUNTED_TOOL_NAME, "catalog_revision": catalog_revision, }); if let Some(inner) = inner { wrapper["arguments"] = inner; } wrapper }