//! `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(®istry, &operation, "sales-gated").await; let api_key = create_platform_api_key( ®istry, "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" ); }