//! Story 3.8 (AT-3.8-01..05): real MCP endpoint fixtures for published static Resources. //! //! Everything here uses the existing loopback MCP server, the real PostgreSQL registry and the //! sanctioned `CommunityMachineCredentialVerifier` — no `route.fulfill`, no stubbed backend, no fake //! service. Fixture data is bounded and test-owned. //! //! Resource fixture rows are seeded with SQL and exact published bytes written through the real //! `ArtifactStore` (the same `put`/content-addressed contract the admin-api publishes with) into a //! test-owned root. The row shapes are exactly the V16/V17 contracts (`resources`, //! `resource_versions`, `resource_publications`, `artifact_*`). //! //! BUILD SEAM (Story 3.8): `build_app_with_artifacts` gives the MCP app the artifact store of its //! root (the same seam the admin-api already has via `storage_root`); the existing constructors keep //! working and fail `resources/read` closed. The production read path //! (`resolve_resource_publication` + `resource_wire`) is the same code the endpoint runs. #![allow(dead_code)] use std::{ fs, io, os::unix::fs::PermissionsExt, path::{Path, PathBuf}, sync::{ Arc, Mutex, atomic::{AtomicU64, Ordering}, }, time::Duration, }; use base64::{Engine as _, engine::general_purpose::STANDARD}; use crank_artifacts::ArtifactStore; use crank_community_mcp::{ auth::CommunityMachineCredentialVerifier, build_app_with_artifacts, session::InMemorySessionStore, }; use crank_core::ResponseCacheStore; use crank_core::ids::ResourceId; use crank_core::{ Agent, AgentId, AgentStatus, AgentVersion, PlatformApiKeyScope, ToolSelectionPolicy, Workspace, WorkspaceId, WorkspaceStatus, }; use crank_registry::model::resource::ArchiveResourceRequest; use crank_registry::{ AgentResourceBinding, CreateAgentRequest, CreateWorkspaceRequest, PostgresRegistry, PublishAgentRequest, PublishRequest, SaveAgentCatalogConfigRequest, }; use crank_runtime::{ InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto, }; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use time::OffsetDateTime; use tracing_subscriber::{filter::LevelFilter, fmt::MakeWriter}; use super::super::common::*; pub(super) const MODERN_REVISION: &str = "2026-07-28"; pub(super) const LEGACY_REVISION: &str = "2025-11-25"; const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion"; const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities"; const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo"; static NEXT_ROOT: AtomicU64 = AtomicU64::new(0); /// Private, test-owned artifact root (0700) removed on drop. pub(super) struct TestRoot(PathBuf); impl TestRoot { fn new(name: &str) -> Self { let path = std::env::temp_dir().join(format!( "crank-mcp-static-resources-{name}-{}-{}", std::process::id(), NEXT_ROOT.fetch_add(1, Ordering::Relaxed) )); fs::create_dir(&path).expect("artifact root must be creatable"); fs::set_permissions(&path, fs::Permissions::from_mode(0o700)) .expect("artifact root must be private"); Self(path) } pub(super) fn path(&self) -> &Path { &self.0 } } impl Drop for TestRoot { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } } /// One seeded static Resource. `kind` is the typed kind, never sniffed from bytes. pub(super) struct SeedResource { pub(super) resource_id: ResourceId, pub(super) uri: String, pub(super) name: String, pub(super) kind: &'static str, pub(super) mime_type: &'static str, pub(super) sensitivity: &'static str, pub(super) bytes: Vec, } impl SeedResource { pub(super) fn text(id: &str, uri: &str, name: &str, body: &str) -> Self { Self::new(id, uri, name, "text", "text/plain", body.as_bytes()) } pub(super) fn json(id: &str, uri: &str, name: &str, body: &str) -> Self { Self::new(id, uri, name, "json", "application/json", body.as_bytes()) } /// `image/png` bytes that are *valid UTF-8*: a text/JSON conversion would silently succeed, so /// the read result proves the typed kind decides `blob` vs `text` (no content sniffing). pub(super) fn binary(id: &str, uri: &str, name: &str, bytes: &[u8]) -> Self { Self::new(id, uri, name, "binary", "image/png", bytes) } fn new( id: &str, uri: &str, name: &str, kind: &'static str, mime_type: &'static str, bytes: &[u8], ) -> Self { Self { resource_id: ResourceId::new(id), uri: uri.to_owned(), name: name.to_owned(), kind, mime_type, sensitivity: "internal", bytes: bytes.to_vec(), } } } pub(super) struct BoundResource { pub(super) id: ResourceId, pub(super) uri: String, pub(super) name: String, pub(super) bytes: Vec, } impl BoundResource { fn from_seed(seed: &SeedResource) -> Self { Self { id: seed.resource_id.clone(), uri: seed.uri.clone(), name: seed.name.clone(), bytes: seed.bytes.clone(), } } } pub(super) struct ResourceEndpoint { pub(super) registry: PostgresRegistry, pub(super) client: reqwest::Client, pub(super) mcp_url: String, pub(super) api_key: String, pub(super) tool_name: String, pub(super) agent_id: AgentId, pub(super) draft_agent_id: AgentId, pub(super) root: TestRoot, pub(super) artifact_store: ArtifactStore, pub(super) text: BoundResource, pub(super) json: BoundResource, pub(super) binary: BoundResource, pub(super) unbound_uri: String, pub(super) unbound_name: String, pub(super) draft_uri: String, pub(super) draft_name: String, pub(super) foreign_uri: String, } impl ResourceEndpoint { pub(super) fn bound_uris(&self) -> Vec { vec![ self.text.uri.clone(), self.json.uri.clone(), self.binary.uri.clone(), ] } /// Digest-derived physical blob path of exact published bytes. pub(super) fn blob_path(&self, bytes: &[u8]) -> PathBuf { let digest = digest_hex(bytes); self.root .path() .join("sha256") .join(&digest[..2]) .join(&digest) } /// Replace the published binary blob with different bytes of the same length (corruption). pub(super) fn corrupt_binary_blob(&self) { let path = self.blob_path(&self.binary.bytes); fs::remove_file(&path).expect("published blob must be removable in a test-owned root"); fs::write(&path, vec![b'x'; self.binary.bytes.len()]) .expect("corrupt blob must be writable"); fs::set_permissions(&path, fs::Permissions::from_mode(0o444)) .expect("corrupt blob must stay read-only like a published blob"); } /// Remove the published binary blob entirely (a missing artifact, not a corrupt one). pub(super) fn delete_binary_blob(&self) { fs::remove_file(self.blob_path(&self.binary.bytes)) .expect("a test-owned published blob must be removable"); } /// Make the publication size claim inconsistent with the stored blob, modelling tampered /// metadata that must be denied before any byte is read. The table check constraint already /// forbids a claim above the artifact-store ceiling, so an oversize row cannot be created at all; /// this exercises the same pre-read integrity decision with a valid-but-wrong size. pub(super) async fn inconsistent_text_publication_size(&self) { sqlx::query( "update resource_publications set size_bytes = $4 where workspace_id = $1 and resource_id = $2 and version = $3", ) .bind(test_workspace_id().as_str()) .bind(self.text.id.as_str()) .bind(1_i32) .bind(1_i64) .execute(self.registry.pool()) .await .expect("publication size metadata must be updatable in a test-owned fixture"); } /// Archive the bound text Resource through the accepted Story 3.7 registry transition. pub(super) async fn archive_text(&self) { let current = self .registry .get_resource_draft(test_workspace_id().as_str(), &self.text.id) .await .expect("bound Resource must be readable before archive"); self.registry .archive_resource(ArchiveResourceRequest { workspace_id: test_workspace_id(), resource_id: self.text.id.clone(), expected_updated_at: current.resource.updated_at, archived_at: OffsetDateTime::now_utc(), }) .await .expect("an active published Resource must archive"); } } /// Local constructor seam for tests that need to observe the real runtime cache. It deliberately /// mirrors the production constructor arguments without changing the shared integration harness. fn build_resource_test_app( registry: PostgresRegistry, artifact_store: ArtifactStore, cache: Option>, ) -> axum::Router { let runtime = crank_runtime::community_with_outbound_policy( crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]), ) .build(); let runtime = cache.map_or(runtime.clone(), |cache| { runtime.with_response_cache_store(cache) }); build_app_with_artifacts( registry, Duration::from_millis(0), None, SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(), runtime, RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()), Arc::new(InMemoryCoordinationStateStore::default()), Arc::new(InMemorySessionStore::default()), Arc::new(CommunityMachineCredentialVerifier), 16, artifact_store, ) } /// Standard fixture without response caching, retaining the historical behavior of existing tests. pub(super) async fn standard_endpoint(name: &str) -> ResourceEndpoint { standard_endpoint_with_cache(name, None).await } /// Standard real-registry fixture with an explicitly injected response cache when requested. pub(super) async fn standard_endpoint_with_cache( name: &str, cache: Option>, ) -> ResourceEndpoint { let registry = test_registry().await; let root = TestRoot::new(name); let artifact_store = ArtifactStore::open(root.path()).expect("the test artifact root must open"); // A published tool keeps the tools/list positive control meaningful on this exact endpoint. let upstream = spawn_upstream_server().await; let operation = test_operation(&upstream, "crm_resources_probe"); 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::now_utc(), published_by: Some("alice"), }) .await .unwrap(); let text = SeedResource::text( "res_bound_text", "crank://resources/bound-text", "bound_text", "bound text v1\n", ); let json = SeedResource::json( "res_bound_json", "crank://resources/bound-json", "bound_json", r#"{"kind":"bound","version":1}"#, ); let binary = SeedResource::binary( "res_bound_binary", "crank://resources/bound-binary", "bound_binary", b"PNG-but-valid-utf8-bytes", ); let unbound = SeedResource::text( "res_unbound_text", "crank://resources/unbound-text", "unbound_text", "unbound text v1\n", ); let draft = SeedResource::text( "res_draft_text", "crank://resources/draft-text", "draft_text", "draft text v1\n", ); let foreign = SeedResource::text( "res_foreign_text", "crank://resources/foreign-text", "foreign_text", "foreign text v1\n", ); seed_workspace(®istry).await; for (seed, status) in [ (&text, "published"), (&json, "published"), (&binary, "published"), (&unbound, "published"), (&draft, "draft"), ] { seed_resource( ®istry, &artifact_store, test_workspace_id().as_str(), seed, status, ) .await; } seed_resource( ®istry, &artifact_store, "ws_other", &foreign, "published", ) .await; let agent_slug = name; let agent_id = AgentId::new(format!("agent_{agent_slug}")); let draft_agent_slug = format!("{name}-draft"); let draft_agent_id = AgentId::new(format!("agent_{draft_agent_slug}")); create_draft_agent(®istry, agent_slug).await; create_draft_agent(®istry, &draft_agent_slug).await; registry .save_agent_catalog_config(SaveAgentCatalogConfigRequest { workspace_id: &test_workspace_id(), agent_id: &agent_id, agent_version: 1, bindings: &[binding_for_operation(&operation)], tool_selection_policy: &ToolSelectionPolicy::default(), resource_bindings: &[ AgentResourceBinding { resource_id: text.resource_id.clone(), resource_version: 1, }, AgentResourceBinding { resource_id: json.resource_id.clone(), resource_version: 1, }, AgentResourceBinding { resource_id: binary.resource_id.clone(), resource_version: 1, }, ], expected_state: None, }) .await .expect("draft Resource bindings must be saved"); registry .publish_agent(PublishAgentRequest { workspace_id: &test_workspace_id(), agent_id: &agent_id, version: 1, published_at: &OffsetDateTime::now_utc(), published_by: Some("alice"), expected_state: None, }) .await .expect("the Resource-bound Agent must publish"); let api_key = create_platform_api_key( ®istry, agent_slug, "mcp-resources", &[PlatformApiKeyScope::Read], ) .await; let base_url = spawn_mcp_server(build_resource_test_app( registry.clone(), artifact_store.clone(), cache, )) .await; ResourceEndpoint { registry, client: reqwest::Client::new(), mcp_url: agent_mcp_url(&base_url, agent_slug), api_key, tool_name: operation.name.clone(), agent_id, draft_agent_id, root, artifact_store, text: BoundResource::from_seed(&text), json: BoundResource::from_seed(&json), binary: BoundResource::from_seed(&binary), unbound_uri: unbound.uri, unbound_name: unbound.name, draft_uri: draft.uri, draft_name: draft.name, foreign_uri: foreign.uri, } } /// A published Agent with no Resource bindings at all: the empty `resources/list` page control. /// The endpoint is otherwise the same real loopback MCP server + real registry + artifact root. pub(super) struct EmptyResourceEndpoint { pub(super) client: reqwest::Client, pub(super) mcp_url: String, pub(super) api_key: String, _root: TestRoot, _artifact_store: ArtifactStore, } pub(super) async fn empty_resource_endpoint(name: &str) -> EmptyResourceEndpoint { let registry = test_registry().await; let root = TestRoot::new(name); let artifact_store = ArtifactStore::open(root.path()).expect("the test artifact root must open"); create_draft_agent(®istry, name).await; registry .publish_agent(PublishAgentRequest { workspace_id: &test_workspace_id(), agent_id: &test_agent_id(name), version: 1, published_at: &OffsetDateTime::now_utc(), published_by: Some("alice"), expected_state: None, }) .await .expect("a Resource-free Agent must publish at registry level"); let api_key = create_platform_api_key( ®istry, name, "mcp-resources-empty", &[PlatformApiKeyScope::Read], ) .await; let base_url = spawn_mcp_server(build_test_app_with_artifacts( registry, Duration::from_millis(0), None, artifact_store.clone(), )) .await; EmptyResourceEndpoint { client: reqwest::Client::new(), mcp_url: agent_mcp_url(&base_url, name), api_key, _root: root, _artifact_store: artifact_store, } } async fn seed_workspace(registry: &PostgresRegistry) { let now = OffsetDateTime::now_utc(); registry .create_workspace(CreateWorkspaceRequest { workspace: &Workspace { id: WorkspaceId::new("ws_other"), slug: "other".to_owned(), display_name: "other".to_owned(), status: WorkspaceStatus::Active, settings: json!({}), created_at: now, updated_at: now, }, }) .await .expect("foreign workspace must be created"); } async fn create_draft_agent(registry: &PostgresRegistry, slug: &str) { let now = OffsetDateTime::now_utc(); let agent_id = AgentId::new(format!("agent_{slug}")); let agent = Agent { id: agent_id.clone(), workspace_id: test_workspace_id(), slug: slug.to_owned(), display_name: slug.to_owned(), description: "Story 3.8 static Resource fixture".to_owned(), status: AgentStatus::Draft, current_draft_version: 1, latest_published_version: None, created_at: now, updated_at: now, published_at: None, }; let version = AgentVersion { agent_id, version: 1, status: AgentStatus::Draft, instructions: json!({}), tool_selection_policy: ToolSelectionPolicy::default(), created_at: now, }; registry .create_agent(CreateAgentRequest { agent: &agent, version: &version, bindings: &[], }) .await .expect("draft Agent must be created"); } /// Seed one exact Resource row set (`resources` + current `resource_versions` + owning blob/source and, /// for `published`, the immutable `resource_publications` snapshot). The bytes are written through the /// real `ArtifactStore`, so the fixture never re-implements the storage layout. async fn seed_resource( registry: &PostgresRegistry, artifact_store: &ArtifactStore, workspace: &str, seed: &SeedResource, status: &str, ) { let stored = artifact_store .put(&seed.bytes) .expect("fixture bytes must be published into the test artifact root"); let digest = stored.artifact_ref.digest_hex().to_owned(); let source_id = format!("src_{}", seed.resource_id.as_str()); let size = i64::try_from(stored.size_bytes).expect("bounded fixture bytes"); let pool = registry.pool(); sqlx::query( "insert into artifact_blobs (digest, artifact_ref, size_bytes, storage_lifecycle, created_at, updated_at) values ($1, $2, $3, 'available', now(), now())", ) .bind(&digest) .bind(format!("sha256:{digest}")) .bind(size) .execute(pool) .await .expect("fixture blob metadata must insert"); sqlx::query( "insert into artifact_sources (workspace_id, source_id, blob_digest, mime_type, sensitivity, lifecycle, created_at, updated_at) values ($1, $2, $3, $4, $5, 'active', now(), now())", ) .bind(workspace) .bind(&source_id) .bind(&digest) .bind(seed.mime_type) .bind(seed.sensitivity) .execute(pool) .await .expect("fixture artifact source must insert"); sqlx::query( "insert into resources (workspace_id, resource_id, uri, name, description, status, kind, current_draft_version, created_at, updated_at) values ($1, $2, $3, $4, '', $5, $6, 1, now(), now())", ) .bind(workspace) .bind(seed.resource_id.as_str()) .bind(&seed.uri) .bind(&seed.name) .bind(status) .bind(seed.kind) .execute(pool) .await .expect("fixture Resource row must insert"); sqlx::query( "insert into resource_versions (workspace_id, resource_id, version, kind, mime_type, size_bytes, digest, sensitivity, artifact_source_id, created_at, superseded_at) values ($1, $2, 1, $3, $4, $5, $6, $7, $8, now(), null)", ) .bind(workspace) .bind(seed.resource_id.as_str()) .bind(seed.kind) .bind(seed.mime_type) .bind(size) .bind(&digest) .bind(seed.sensitivity) .bind(&source_id) .execute(pool) .await .expect("fixture Resource version must insert"); if status == "published" { sqlx::query( "insert into resource_publications (workspace_id, resource_id, version, uri, name, description, kind, mime_type, size_bytes, digest, sensitivity, artifact_source_id, published_at) values ($1, $2, 1, $3, $4, '', $5, $6, $7, $8, $9, $10, now())", ) .bind(workspace) .bind(seed.resource_id.as_str()) .bind(&seed.uri) .bind(&seed.name) .bind(seed.kind) .bind(seed.mime_type) .bind(size) .bind(&digest) .bind(seed.sensitivity) .bind(&source_id) .execute(pool) .await .expect("fixture Resource publication must insert"); } } pub(super) fn digest_hex(bytes: &[u8]) -> String { format!("{:x}", Sha256::digest(bytes)) } /// Revisions come from the checked-in oracle, never from memory. pub(super) fn supported_revisions() -> Vec { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../../tests/fixtures/mcp-revisions/supported-revisions.json"); let raw = fs::read_to_string(&path).unwrap_or_else(|error| { panic!( "revision oracle must be readable at {}: {error}", path.display() ) }); serde_json::from_str::(&raw).expect("revision oracle must be JSON")["revisions"] .as_array() .expect("revision oracle must list revisions") .iter() .map(|entry| { entry["revision"] .as_str() .expect("revision string") .to_owned() }) .collect() } pub(super) fn modern_meta(revision: &str) -> Value { json!({ META_PROTOCOL_VERSION: revision, META_CLIENT_CAPABILITIES: {}, META_CLIENT_INFO: { "name": "crank-atdd-resources", "version": "0.1.0" } }) } /// `resources/list` over one supported revision on the standard fixture endpoint. pub(super) async fn list_resources( endpoint: &ResourceEndpoint, revision: &str, params: Value, ) -> reqwest::Response { list_resources_at( &endpoint.client, &endpoint.mcp_url, &endpoint.api_key, revision, params, ) .await } /// `resources/list` over one supported revision: modern is stateless (identity in headers + `_meta`), /// legacy goes through the accepted initialize/session handshake. pub(super) async fn list_resources_at( client: &reqwest::Client, mcp_url: &str, api_key: &str, revision: &str, params: Value, ) -> reqwest::Response { if revision == LEGACY_REVISION { let session = initialize_session(client, mcp_url, api_key).await; post_jsonrpc_response( client, mcp_url, api_key, Some(&session), None, json!({ "jsonrpc": "2.0", "id": 11, "method": "resources/list", "params": params }), ) .await } else { let mut params = params; params["_meta"] = modern_meta(revision); let headers = [ ("MCP-Protocol-Version", revision), ("Mcp-Method", "resources/list"), ]; post_jsonrpc_with_headers( client, mcp_url, api_key, &headers, json!({ "jsonrpc": "2.0", "id": 11, "method": "resources/list", "params": params }), ) .await } } /// `resources/templates/list` over one supported revision on the standard fixture endpoint. pub(super) async fn list_resource_templates( endpoint: &ResourceEndpoint, revision: &str, ) -> reqwest::Response { list_resource_templates_with_params(endpoint, revision, json!({})).await } pub(super) async fn list_resource_templates_with_params( endpoint: &ResourceEndpoint, revision: &str, mut params: Value, ) -> reqwest::Response { if !params.is_object() { params = json!({}); } if revision == LEGACY_REVISION { let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await; post_jsonrpc_response( &endpoint.client, &endpoint.mcp_url, &endpoint.api_key, Some(&session), None, json!({ "jsonrpc": "2.0", "id": 31, "method": "resources/templates/list", "params": params }), ).await } else { params .as_object_mut() .unwrap() .insert("_meta".to_owned(), modern_meta(revision)); let headers = [ ("MCP-Protocol-Version", revision), ("Mcp-Method", "resources/templates/list"), ]; post_jsonrpc_with_headers( &endpoint.client, &endpoint.mcp_url, &endpoint.api_key, &headers, json!({ "jsonrpc": "2.0", "id": 31, "method": "resources/templates/list", "params": params }), ).await } } /// `resources/read` over one supported revision, with the required modern `Mcp-Name` equal to the URI. pub(super) async fn read_resource( endpoint: &ResourceEndpoint, revision: &str, uri: &str, request_id: Option<&str>, ) -> reqwest::Response { if revision == LEGACY_REVISION { let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await; post_jsonrpc_response( &endpoint.client, &endpoint.mcp_url, &endpoint.api_key, Some(&session), request_id, json!({ "jsonrpc": "2.0", "id": 21, "method": "resources/read", "params": { "uri": uri } }), ) .await } else { let mut headers = vec![ ("MCP-Protocol-Version", revision), ("Mcp-Method", "resources/read"), ("Mcp-Name", uri), ]; if let Some(request_id) = request_id { headers.push(("x-request-id", request_id)); } post_jsonrpc_with_headers( &endpoint.client, &endpoint.mcp_url, &endpoint.api_key, &headers, json!({ "jsonrpc": "2.0", "id": 21, "method": "resources/read", "params": { "uri": uri, "_meta": modern_meta(revision) } }), ) .await } } /// Same modern read without any credential: authorization must reject before any Resource lookup. pub(super) async fn read_resource_without_credentials( endpoint: &ResourceEndpoint, uri: &str, ) -> reqwest::Response { endpoint .client .post(&endpoint.mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header("MCP-Protocol-Version", MODERN_REVISION) .header("Mcp-Method", "resources/read") .header("Mcp-Name", uri) .json(&json!({ "jsonrpc": "2.0", "id": 31, "method": "resources/read", "params": { "uri": uri, "_meta": modern_meta(MODERN_REVISION) } })) .send() .await .expect("unauthenticated request must reach the server") } /// The same credential-less read in the legacy era: the session-based revision must reject it at the /// transport authorization stage as well. pub(super) async fn read_resource_without_credentials_legacy( endpoint: &ResourceEndpoint, uri: &str, ) -> reqwest::Response { endpoint .client .post(&endpoint.mcp_url) .header( reqwest::header::ACCEPT, "application/json, text/event-stream", ) .header("MCP-Protocol-Version", LEGACY_REVISION) .json(&json!({ "jsonrpc": "2.0", "id": 32, "method": "resources/read", "params": { "uri": uri } })) .send() .await .expect("unauthenticated request must reach the server") } 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}") }) } pub(super) fn result_of<'a>(body: &'a Value, what: &str) -> &'a Value { body.get("result").unwrap_or_else(|| { panic!("{what} must return a JSON-RPC result (missing product capability?), got {body}") }) } pub(super) fn error_code(body: &Value) -> i64 { body["error"]["code"] .as_i64() .unwrap_or_else(|| panic!("expected a JSON-RPC error, got {body}")) } pub(super) fn listed_uris(result: &Value) -> Vec { result["resources"] .as_array() .unwrap_or_else(|| { panic!("resources/list result must carry a resources array, got {result}") }) .iter() .map(|resource| { resource["uri"] .as_str() .unwrap_or_else(|| panic!("listed resource must carry a uri, got {resource}")) .to_owned() }) .collect() } pub(super) fn base64_of(bytes: &[u8]) -> String { STANDARD.encode(bytes) } /// Collects per-revision failures so one run proves the RED/GREEN state for *every* supported MCP /// revision instead of stopping at the first one. #[derive(Default)] pub(super) struct RevisionChecks { failures: Vec, } impl RevisionChecks { pub(super) fn require(&mut self, condition: bool, message: impl FnOnce() -> String) { if !condition { self.failures.push(message()); } } pub(super) fn result<'a>( &mut self, body: &'a Value, revision: &str, what: &str, ) -> Option<&'a Value> { match body.get("result") { Some(result) => Some(result), None => { self.failures.push(format!( "{what} on {revision} must return a JSON-RPC result, got {body}" )); None } } } pub(super) fn finish(self) { assert!( self.failures.is_empty(), "failures:\n---\n{}", self.failures.join("\n---\n") ); } } /// In-process log capture: proves the read telemetry keeps identity and carries no Resource content. #[derive(Clone, Default)] pub(super) struct CapturedLogs { buffer: Arc>>, } impl CapturedLogs { pub(super) fn install(&self) -> tracing::subscriber::DefaultGuard { let subscriber = tracing_subscriber::fmt() .with_max_level(LevelFilter::INFO) .with_ansi(false) .with_writer(LogWriter(Arc::clone(&self.buffer))) .finish(); tracing::subscriber::set_default(subscriber) } pub(super) fn output(&self) -> String { String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap_or_default() } } struct LogWriter(Arc>>); impl<'a> MakeWriter<'a> for LogWriter { type Writer = LogGuard; fn make_writer(&'a self) -> Self::Writer { LogGuard(Arc::clone(&self.0)) } } struct LogGuard(Arc>>); impl io::Write for LogGuard { fn write(&mut self, bytes: &[u8]) -> io::Result { self.0.lock().unwrap().extend_from_slice(bytes); Ok(bytes.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }