//! 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}" ); }