//! #107: real build_app endpoint controls plus a separate SDK structural seam oracle. //! No SDK transport router is used. The structural oracle alone does not prove wire parity. use std::{ sync::{ Arc, atomic::{AtomicUsize, Ordering}, }, time::Duration, }; use axum::{Router, routing::post}; use crank_core::{ AgentOperationBinding, AgentStatus, AgentVersion, PlatformApiKeyId, ToolSelectionPolicy, }; use crank_registry::{ CreateAgentDraftVersionRequest, PostgresRegistry, PublishAgentRequest, PublishRequest, }; use crank_runtime::{ InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto, }; use serde_json::{Value, json}; use super::{CounterSet, observe, sdk_tools_dispatch_enter, support::*}; #[path = "rmcp_result_runtime_tests.rs"] mod result_serialization; struct Server(tokio::task::JoinHandle<()>, String); impl Drop for Server { fn drop(&mut self) { self.0.abort(); } } async fn serve(app: Router) -> Server { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); Server( tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }), format!("http://{address}"), ) } struct Endpoint { server: Server, _upstream: Server, registry: PostgresRegistry, key: String, counters: Arc, calls: Arc, } impl Endpoint { async fn started() -> Self { // First caller owns the process-wide fixture and its atexit cleanup, including RED panics. let _ = crank_test_support::postgres_schema_url_for_task("rmcp_runtime_owner", "t_c559abb1") .await; let registry = test_registry().await; let calls = Arc::new(AtomicUsize::new(0)); let upstream = serve( Router::new() .route("/crm/leads", post(result_serialization::upstream)) .with_state(calls.clone()), ) .await; let operation = test_operation(&upstream.1); registry .create_operation(&workspace_id(), &operation, Some("alice")) .await .unwrap(); registry .publish_operation(PublishRequest { workspace_id: &workspace_id(), operation_id: &operation.id, version: 1, published_at: &test_time(), published_by: Some("alice"), }) .await .unwrap(); publish_agent(®istry, &operation).await; let key = create_api_key(®istry).await; let counters = Arc::new(CounterSet::default()); let app = crate::build_app( registry.clone(), Duration::ZERO, Some("https://crank.example.com".into()), SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(), crank_runtime::community_with_outbound_policy( crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]), ) .build(), RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()), Arc::new(InMemoryCoordinationStateStore::default()), Arc::new(crate::session::InMemorySessionStore::default()), Arc::new(crate::auth::CommunityMachineCredentialVerifier), ); let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({ let counters = counters.clone(); move |request: axum::extract::Request, next: axum::middleware::Next| { let counters = counters.clone(); async move { let response = next.run(request).await; result_serialization::observe_body(response, counters) } } })); let server = serve(app).await; Self { server, _upstream: upstream, registry, key, counters, calls, } } async fn post(&self, revision: &str, session: Option<&str>, body: &Value) -> reqwest::Response { self.post_accept(revision, session, body, "application/json") .await } async fn post_accept( &self, revision: &str, session: Option<&str>, body: &Value, accept: &str, ) -> reqwest::Response { let mut request = reqwest::Client::new() .post(format!( "{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}", self.server.1 )) .bearer_auth(&self.key) // Also guards the legacy JSON-only contract; no SSE parsing fallback here. .header("Accept", accept) .header("x-request-id", "sdk-result-wire") .header( "traceparent", "00-11111111111111111111111111111111-2222222222222222-01", ) .header("MCP-Protocol-Version", revision); if let Some(session) = session { request = request.header("MCP-Session-Id", session); } if revision == MODERN_REVISION { request = request.header("Mcp-Method", body["method"].as_str().unwrap()); if let Some(name) = body["params"]["name"].as_str() { request = request.header("Mcp-Name", name); } } request.json(body).send().await.unwrap() } async fn session(&self, revision: &str) -> Option { if revision == MODERN_REVISION { return None; } let response = self.post(revision, None, &legacy_initialize(1)).await; assert_eq!(response.status(), 200); let session = response.headers()["MCP-Session-Id"] .to_str() .unwrap() .to_owned(); let body = json_body(response).await; assert_eq!(body["result"]["protocolVersion"], revision); assert!(body["result"]["capabilities"]["tools"].is_object()); let response = self .post(revision, Some(&session), &initialized_notification()) .await; assert_eq!(response.status(), 202); Some(session) } async fn list(&self, revision: &str, session: Option<&str>, expected_name: &str) -> usize { let before = self.counters.sdk_tools_dispatch(); let mut body = json!({"jsonrpc":"2.0", "id":10, "method":"tools/list", "params":{}}); if revision == MODERN_REVISION { body["params"]["_meta"] = modern_meta(); } let calls = self.calls.load(Ordering::SeqCst); let response = self.post(revision, session, &body).await; assert_eq!(response.status(), 200); assert!( response.headers()["content-type"] .to_str() .unwrap() .starts_with("application/json") ); let body = json_body(response).await; assert_eq!(body["id"], 10); assert_eq!(body["result"]["tools"].as_array().unwrap().len(), 1); assert_eq!(body["result"]["tools"][0]["name"], expected_name); assert!(body["error"].is_null(), "{body}"); assert_eq!( self.calls.load(Ordering::SeqCst), calls, "listing must not execute upstream" ); self.counters.sdk_tools_dispatch() - before } async fn call(&self, revision: &str, session: Option<&str>, name: &str, email: &str) -> usize { let before = self.counters.sdk_tools_dispatch(); let arrivals = self.calls.load(Ordering::SeqCst); let mut body = if revision == MODERN_REVISION { modern_tool_call(11, email) } else { legacy_tool_call(11, email) }; body["params"]["name"] = json!(name); let response = self.post(revision, session, &body).await; assert_eq!(response.status(), 200); assert!( response.headers()["content-type"] .to_str() .unwrap() .starts_with("application/json") ); let body = json_body(response).await; assert_eq!(body["id"], 11); assert!(body["error"].is_null(), "{body}"); assert_ne!(body["result"]["isError"], true, "{body}"); assert_scoped_output(revision, &body, email); if revision == MODERN_REVISION { assert_eq!(body["result"]["resultType"], "complete"); } assert_eq!(self.calls.load(Ordering::SeqCst) - arrivals, 1); self.counters.sdk_tools_dispatch() - before } async fn publish_renamed_tool(&self) { let now = time::OffsetDateTime::now_utc(); let version = AgentVersion { agent_id: agent_id(), version: 2, status: AgentStatus::Draft, instructions: json!({}), tool_selection_policy: ToolSelectionPolicy::default(), created_at: now, }; let bindings = [AgentOperationBinding { operation_id: crank_core::OperationId::new("op_create_lead"), operation_version: 1, tool_name: "new_publication_tool".into(), tool_title: "New Tool".into(), tool_description_override: None, enabled: true, }]; self.registry .create_agent_draft_version(CreateAgentDraftVersionRequest { workspace_id: &workspace_id(), agent_id: &agent_id(), version: &version, bindings: &bindings, updated_at: &now, }) .await .unwrap(); self.registry .publish_agent(PublishAgentRequest { workspace_id: &workspace_id(), agent_id: &agent_id(), version: 2, published_at: &now, published_by: Some("alice"), expected_state: None, }) .await .unwrap(); } } async fn endpoint_control(revision: &str) -> [usize; 2] { let h = Endpoint::started().await; let session = h.session(revision).await; let session = session.as_deref(); let list_dispatches = h.list(revision, session, TOOL_NAME).await; let call_dispatches = h .call( revision, session, TOOL_NAME, &format!("{revision}@example.test"), ) .await; // A fresh publication must be visible without reinitialize or a new endpoint. h.publish_renamed_tool().await; h.list(revision, session, "new_publication_tool").await; h.call( revision, session, "new_publication_tool", "new-publication@example.test", ) .await; h.registry .revoke_platform_api_key( &workspace_id(), &PlatformApiKeyId::new("pk_dispatch_observer"), &time::OffsetDateTime::now_utc(), ) .await .unwrap(); let before_sdk = h.counters.sdk_tools_dispatch(); let arrivals = h.calls.load(Ordering::SeqCst); let mut denied = if revision == MODERN_REVISION { modern_tool_call(12, "denied@example.test") } else { legacy_tool_call(12, "denied@example.test") }; denied["params"]["name"] = json!("new_publication_tool"); assert_eq!(h.post(revision, session, &denied).await.status(), 401); assert_eq!( h.calls.load(Ordering::SeqCst), arrivals, "revoked credential must not execute upstream" ); assert_eq!( h.counters.sdk_tools_dispatch(), before_sdk, "revocation must reject before SDK dispatch" ); eprintln!( "existing GREEN {revision}: JSON list/call, scoped output, upstream=2, publication refresh, revoked=401/no outbound; SDK list/call deltas={:?}", [list_dispatches, call_dispatches] ); [list_dispatches, call_dispatches] } #[tokio::test] async fn rmcp_runtime_existing_wire_modern() { endpoint_control(MODERN_REVISION).await; } #[tokio::test] async fn rmcp_runtime_existing_wire_legacy() { endpoint_control(LEGACY_REVISION).await; } #[tokio::test] async fn rmcp_runtime_sdk_dispatch_modern() { let counts = endpoint_control(MODERN_REVISION).await; assert_eq!( counts, [1, 1], "real endpoint tools/list and tools/call must each enter SDK typed dispatch once (structural seam oracle)" ); } #[tokio::test] async fn rmcp_runtime_sdk_dispatch_legacy() { let counts = endpoint_control(LEGACY_REVISION).await; assert_eq!( counts, [1, 1], "real endpoint tools/list and tools/call must each enter SDK typed dispatch once (structural seam oracle)" ); } #[tokio::test] async fn rmcp_runtime_observer_is_request_scoped() { let counters = Arc::new(CounterSet::default()); sdk_tools_dispatch_enter(); assert_eq!(counters.sdk_tools_dispatch(), 0); observe(counters.clone(), async { sdk_tools_dispatch_enter(); }) .await; assert_eq!(counters.sdk_tools_dispatch(), 1); let other = Arc::new(CounterSet::default()); observe(other.clone(), async { sdk_tools_dispatch_enter(); }) .await; assert_eq!(other.sdk_tools_dispatch(), 1); assert_eq!(counters.sdk_tools_dispatch(), 1); }