greentic-mcp-client 1.2.1

Client for remote MCP servers over Streamable HTTP (JSON-RPC 2.0)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Sans-io MCP (Streamable HTTP / JSON-RPC 2.0) protocol helpers.
//! No network or WIT imports — usable from native hosts and wasm guests alike.

use crate::error::{ProtoError, ServerError, ToolCallError};
use serde_json::{Value, json};

/// MCP protocol revision this crate speaks by default.
pub const PROTOCOL_VERSION: &str = "2025-06-18";

/// Build a JSON-RPC `initialize` request.
#[must_use]
pub fn build_initialize(
    id: u64,
    protocol_version: &str,
    client_name: &str,
    client_version: &str,
) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "method": "initialize",
        "params": {
            "protocolVersion": protocol_version,
            "capabilities": {},
            "clientInfo": { "name": client_name, "version": client_version }
        }
    })
}

/// Build the `notifications/initialized` notification (no id).
#[must_use]
pub fn build_initialized() -> Value {
    json!({ "jsonrpc": "2.0", "method": "notifications/initialized" })
}

/// Build a JSON-RPC `tools/list` request.
#[must_use]
pub fn build_tools_list(id: u64) -> Value {
    json!({ "jsonrpc": "2.0", "id": id, "method": "tools/list", "params": {} })
}

/// Build a JSON-RPC `tools/call` request.
#[must_use]
pub fn build_tools_call(id: u64, name: &str, arguments: &Value) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "method": "tools/call",
        "params": { "name": name, "arguments": arguments }
    })
}

/// Consider one fully-accumulated SSE event payload. Returns `Some(value)`
/// when it is the JSON-RPC envelope matching `expected_id`; otherwise records
/// the first result/error-bearing envelope as `fallback` and returns `None`.
fn sse_consider(data: &str, expected_id: u64, fallback: &mut Option<Value>) -> Option<Value> {
    let value = serde_json::from_str::<Value>(data.trim()).ok()?;
    let has_body = value.get("result").is_some() || value.get("error").is_some();
    if !has_body {
        return None;
    }
    if value.get("id").and_then(Value::as_u64) == Some(expected_id) {
        return Some(value);
    }
    if fallback.is_none() {
        *fallback = Some(value);
    }
    None
}

/// Parse a JSON-RPC response from an HTTP body, unwrapping SSE framing when
/// the response is `text/event-stream`. Returns the JSON-RPC envelope whose
/// `id` matches `expected_id` (falling back to the first envelope carrying a
/// result or error if no id matches).
pub fn parse_jsonrpc_response(
    content_type: &str,
    body: &[u8],
    expected_id: u64,
) -> Result<Value, ProtoError> {
    let text = std::str::from_utf8(body)?;

    if content_type
        .to_ascii_lowercase()
        .contains("text/event-stream")
    {
        let mut current = String::new();
        let mut fallback: Option<Value> = None;
        for line in text.lines() {
            if line.is_empty() {
                if let Some(matched) = sse_consider(&current, expected_id, &mut fallback) {
                    return Ok(matched);
                }
                current.clear();
                continue;
            }
            if let Some(payload) = line.trim_start().strip_prefix("data:") {
                let payload = payload.strip_prefix(' ').unwrap_or(payload);
                if !current.is_empty() {
                    current.push('\n');
                }
                current.push_str(payload);
            }
        }
        // Trailing event when the stream does not end with a blank line.
        if let Some(matched) = sse_consider(&current, expected_id, &mut fallback) {
            return Ok(matched);
        }
        fallback.ok_or(ProtoError::NoEnvelope)
    } else {
        Ok(serde_json::from_str::<Value>(text)?)
    }
}

/// One tool surfaced by a remote MCP `tools/list`.
#[derive(Debug, Clone, PartialEq)]
pub struct McpToolDef {
    pub name: String,
    /// The tool's human-readable display name, when the server offers one.
    ///
    /// `name` is an IDENTIFIER — servers routinely emit
    /// `runner.example.aws_demo_macos_meridian_insurance_commercial_quote` —
    /// and the MCP spec's own display guidance is to prefer `title` and fall
    /// back to `name`. Dropping it, as this crate did, left every consumer
    /// showing the identifier with no way to know a better label existed: a
    /// Greentic flow author picking a tool saw only 60-character slugs, and no
    /// change in the designer could have recovered the label, because it never
    /// crossed this boundary.
    ///
    /// `None` means the server offered neither `title` nor the older
    /// `annotations.title`, which is conformant — both are optional — so a
    /// consumer must still be able to render `name` alone. It is deliberately
    /// NOT defaulted to `name`: "the server named this tool" and "we are
    /// showing the identifier because there was nothing else" are different
    /// facts, and a consumer that wants to mark the second (a secondary line,
    /// a dimmer face) cannot if this crate collapses them.
    pub title: Option<String>,
    pub description: String,
    /// JSON Schema for the tool arguments; `{}` when the server omits it.
    pub input_schema: Value,
    /// JSON Schema for what the tool RETURNS, when the server advertises one.
    ///
    /// `None` is the normal case — `outputSchema` is optional in the MCP spec,
    /// so a server that omits it is conformant and callers must cope. It is
    /// deliberately `Option<Value>` rather than defaulting to `{}` like
    /// `input_schema`: absent and "declared empty" mean different things to a
    /// caller that wants to know a tool's field names, and collapsing them
    /// would make the two indistinguishable.
    ///
    /// Callers use it to know what a tool's result actually contains. Without
    /// it they can only guess: a Greentic flow referenced
    /// `{{node.mcp_quote.outputs.annual_premium}}` and another
    /// `{{node.mcp_quote.annual_premium}}`, and both rendered blank with no
    /// error, because nothing could tell anyone the real field names.
    pub output_schema: Option<Value>,
}

/// Successful `tools/call` payload.
#[derive(Debug, Clone, PartialEq)]
pub struct ToolOutput {
    /// `structuredContent` when the server returned one.
    pub structured: Option<Value>,
    /// Concatenated text `content` blocks (may be empty).
    pub text: String,
}

impl ToolOutput {
    /// `structuredContent` when present, else the joined text as a JSON string.
    #[must_use]
    pub fn to_value(&self) -> Value {
        match &self.structured {
            Some(v) => v.clone(),
            None => Value::String(self.text.clone()),
        }
    }
}

/// Map a `tools/list` result into tool definitions. Tools without a name are
/// dropped; a missing `inputSchema` becomes `{}`; `title` falls back to
/// `annotations.title` and then to absent.
#[must_use]
pub fn map_tools_list(result: &Value) -> Vec<McpToolDef> {
    let Some(tools) = result.get("tools").and_then(Value::as_array) else {
        return Vec::new();
    };
    tools
        .iter()
        .filter_map(|tool| {
            let name = tool.get("name").and_then(Value::as_str)?.to_string();
            // Spec precedence: `title` first, then the older
            // `annotations.title`, which is where the field lived before it was
            // promoted onto the tool itself and is still what older servers
            // send. An empty string is treated as absent — a server that
            // serialises `"title": ""` has not supplied a label, and letting it
            // through would render a blank picker row that no consumer could
            // tell from a bug in itself.
            let title = tool
                .get("title")
                .and_then(Value::as_str)
                .or_else(|| {
                    tool.get("annotations")
                        .and_then(|a| a.get("title"))
                        .and_then(Value::as_str)
                })
                .filter(|t| !t.trim().is_empty())
                .map(ToString::to_string);
            let description = tool
                .get("description")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string();
            let input_schema = tool
                .get("inputSchema")
                .cloned()
                .unwrap_or_else(|| json!({}));
            // Passed through verbatim, including a non-object: this crate
            // reports what the server said, and a caller that cares whether the
            // schema is well-formed can see it and say so. Silently normalising
            // it here would hide a broken server from every caller at once.
            //
            // An explicit `"outputSchema": null` is the ONE thing normalised,
            // because it is not a declaration — it is the absence of one,
            // spelled out. Several MCP SDKs serialise optional fields as
            // explicit nulls, and `serde_json`'s `get` distinguishes them from a
            // missing key: without this filter such a server yields
            // `Some(Value::Null)`, i.e. "declared a schema", and a consumer that
            // validates the shape reports "expected a JSON object, got null"
            // against a perfectly conformant peer.
            let output_schema = tool
                .get("outputSchema")
                .filter(|value| !value.is_null())
                .cloned();
            Some(McpToolDef {
                name,
                title,
                description,
                input_schema,
                output_schema,
            })
        })
        .collect()
}

/// Extract a `tools/call` result. Honors the MCP `isError` flag (mapped to
/// `Err`); keeps structured content and joined text blocks separately.
pub fn extract_tool_output(result: &Value) -> Result<ToolOutput, ToolCallError> {
    let is_error = result
        .get("isError")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let structured = result.get("structuredContent").cloned();
    let mut parts: Vec<String> = Vec::new();
    if let Some(content) = result.get("content").and_then(Value::as_array) {
        for block in content {
            if let Some(text) = block.get("text").and_then(Value::as_str) {
                parts.push(text.to_string());
            }
        }
    }
    let text = parts.join("\n");
    if is_error {
        let message = match &structured {
            Some(v) => v.to_string(),
            None if text.is_empty() => "tool call returned isError".to_string(),
            None => text,
        };
        return Err(ToolCallError { message });
    }
    Ok(ToolOutput { structured, text })
}

/// Return the `result` object, or the typed error a JSON-RPC `error` carries.
pub fn extract_result(envelope: &Value) -> Result<Value, crate::error::McpError> {
    if let Some(error) = envelope.get("error") {
        let code = error.get("code").and_then(Value::as_i64).unwrap_or(0);
        let message = error
            .get("message")
            .and_then(Value::as_str)
            .unwrap_or("unknown error")
            .to_string();
        return Err(ServerError { code, message }.into());
    }
    envelope
        .get("result")
        .cloned()
        .ok_or(crate::error::McpError::Proto(ProtoError::MissingResult))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn initialize_has_protocol_and_client_info() {
        let req = build_initialize(1, PROTOCOL_VERSION, "test-client", "9.9.9");
        assert_eq!(req["jsonrpc"], "2.0");
        assert_eq!(req["id"], 1);
        assert_eq!(req["method"], "initialize");
        assert_eq!(req["params"]["protocolVersion"], "2025-06-18");
        assert_eq!(req["params"]["clientInfo"]["name"], "test-client");
        assert_eq!(req["params"]["clientInfo"]["version"], "9.9.9");
    }

    #[test]
    fn initialized_is_a_notification_without_id() {
        let req = build_initialized();
        assert_eq!(req["method"], "notifications/initialized");
        assert!(req.get("id").is_none());
    }

    #[test]
    fn tools_list_shape() {
        let req = build_tools_list(2);
        assert_eq!(req["id"], 2);
        assert_eq!(req["method"], "tools/list");
    }

    #[test]
    fn tools_call_carries_name_and_arguments() {
        let req = build_tools_call(
            2,
            "get_issue",
            &json!({ "owner": "o", "repo": "r", "issue_number": 1 }),
        );
        assert_eq!(req["method"], "tools/call");
        assert_eq!(req["params"]["name"], "get_issue");
        assert_eq!(req["params"]["arguments"]["repo"], "r");
    }

    #[test]
    fn parses_plain_json_response() {
        let body = br#"{"jsonrpc":"2.0","id":2,"result":{"tools":[]}}"#;
        let value = parse_jsonrpc_response("application/json", body, 2).unwrap();
        assert_eq!(value["id"], 2);
        assert!(value["result"]["tools"].is_array());
    }

    #[test]
    fn unwraps_sse_response_and_matches_id() {
        let body =
            b"event: message\ndata: {\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"ok\":true}}\n\n";
        let value = parse_jsonrpc_response("text/event-stream; charset=utf-8", body, 2).unwrap();
        assert_eq!(value["result"]["ok"], true);
    }

    #[test]
    fn sse_picks_matching_id_among_multiple_events() {
        let body = b"data: {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"first\":true}}\n\ndata: {\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"second\":true}}\n\n";
        let value = parse_jsonrpc_response("text/event-stream", body, 2).unwrap();
        assert_eq!(value["result"]["second"], true);
    }

    #[test]
    fn sse_concatenates_multiline_data() {
        let body = b"data: {\"jsonrpc\":\"2.0\",\"id\":2,\ndata: \"result\":{\"ok\":true}}\n\n";
        let value = parse_jsonrpc_response("text/event-stream", body, 2).unwrap();
        assert_eq!(value["result"]["ok"], true);
    }

    #[test]
    fn sse_with_only_notifications_is_no_envelope() {
        let body = b"data: {\"jsonrpc\":\"2.0\",\"method\":\"ping\"}\n\n";
        let err = parse_jsonrpc_response("text/event-stream", body, 2).unwrap_err();
        assert!(matches!(err, ProtoError::NoEnvelope));
    }

    #[test]
    fn malformed_json_body_is_decode_error() {
        let err = parse_jsonrpc_response("application/json", b"{not json", 2).unwrap_err();
        assert!(matches!(err, ProtoError::Decode(_)));
    }

    #[test]
    fn extract_result_returns_result() {
        let env = json!({ "jsonrpc": "2.0", "id": 2, "result": { "x": 1 } });
        assert_eq!(extract_result(&env).unwrap()["x"], 1);
    }

    #[test]
    fn extract_result_surfaces_server_error() {
        let env = json!({ "jsonrpc": "2.0", "id": 2, "error": { "code": -32602, "message": "bad params" } });
        let err = extract_result(&env).unwrap_err();
        match err {
            crate::error::McpError::Server(ServerError { code, message }) => {
                assert_eq!(code, -32602);
                assert_eq!(message, "bad params");
            }
            other => panic!("expected Server error, got: {other}"),
        }
    }

    #[test]
    fn extract_result_missing_both_is_proto_error() {
        let env = json!({ "jsonrpc": "2.0", "id": 2 });
        let err = extract_result(&env).unwrap_err();
        assert!(matches!(
            err,
            crate::error::McpError::Proto(ProtoError::MissingResult)
        ));
    }

    #[test]
    fn maps_tools_list_with_value_schema() {
        let result = json!({
            "tools": [
                { "name": "get_issue", "description": "Get an issue",
                  "inputSchema": { "type": "object", "properties": { "repo": { "type": "string" } } } },
                { "name": "search_code", "description": "Search code", "inputSchema": { "type": "object" } }
            ]
        });
        let defs = map_tools_list(&result);
        assert_eq!(defs.len(), 2);
        assert_eq!(defs[0].name, "get_issue");
        assert_eq!(defs[0].input_schema["properties"]["repo"]["type"], "string");
    }

    /// The display name a consumer should show. `name` is an identifier, and a
    /// picker rendering it is showing the operator a slug — so a `title` the
    /// server did offer must not be dropped at this boundary.
    #[test]
    fn map_tools_list_carries_the_tool_title() {
        let result = json!({"tools": [{
            "name": "runner.example.aws_demo_macos_meridian_insurance_commercial_quote",
            "title": "Meridian Commercial Insurance Quote",
            "description": "", "inputSchema": {}
        }]});
        let tools = map_tools_list(&result);
        assert_eq!(
            tools[0].title.as_deref(),
            Some("Meridian Commercial Insurance Quote")
        );
    }

    /// `title` was promoted onto the tool itself; before that it lived under
    /// `annotations`. Servers on the older shape are still out there, and their
    /// label is just as real — so the fallback is part of the contract, not a
    /// courtesy.
    #[test]
    fn map_tools_list_falls_back_to_the_annotations_title() {
        let result = json!({"tools": [{
            "name": "create_quote", "description": "", "inputSchema": {},
            "annotations": {"title": "Create Quote"}
        }]});
        assert_eq!(
            map_tools_list(&result)[0].title.as_deref(),
            Some("Create Quote")
        );
    }

    /// The newer field wins when a server sends both, so a peer that has
    /// migrated is not held to whatever it left behind in `annotations`.
    #[test]
    fn map_tools_list_prefers_the_tool_title_over_the_annotations_one() {
        let result = json!({"tools": [{
            "name": "t", "title": "New", "description": "", "inputSchema": {},
            "annotations": {"title": "Old"}
        }]});
        assert_eq!(map_tools_list(&result)[0].title.as_deref(), Some("New"));
    }

    /// Both fields are OPTIONAL, so their absence is the common case and must
    /// stay `None` rather than being defaulted to `name` — a consumer has to be
    /// able to tell "the server labelled this" from "we are falling back to the
    /// identifier", which is exactly the distinction it needs to render the two
    /// differently.
    #[test]
    fn map_tools_list_leaves_an_absent_title_as_none() {
        let result = json!({"tools": [{"name": "t", "description": "", "inputSchema": {}}]});
        assert_eq!(map_tools_list(&result)[0].title, None);
    }

    /// An empty or whitespace-only title is not a label. Letting it through
    /// paints a blank row in a picker, which reads as a bug in the consumer
    /// rather than as a server that supplied nothing.
    #[test]
    fn map_tools_list_treats_a_blank_title_as_absent() {
        let blank =
            json!({"tools": [{"name": "t", "title": "   ", "description": "", "inputSchema": {}}]});
        let empty =
            json!({"tools": [{"name": "t", "title": "", "description": "", "inputSchema": {}}]});
        assert_eq!(map_tools_list(&blank)[0].title, None);
        assert_eq!(map_tools_list(&empty)[0].title, None);
    }

    /// A server that advertises `outputSchema` must have it carried through —
    /// this is the only way a caller can know what fields a tool returns.
    #[test]
    fn map_tools_list_carries_the_output_schema() {
        let result = json!({"tools": [{
            "name": "create_quote",
            "description": "",
            "inputSchema": {"type": "object"},
            "outputSchema": {"type": "object", "properties": {"annual_premium": {"type": "number"}}}
        }]});
        let tools = map_tools_list(&result);
        assert_eq!(tools.len(), 1);
        assert_eq!(
            tools[0]
                .output_schema
                .as_ref()
                .and_then(|s| s.pointer("/properties/annual_premium/type")),
            Some(&json!("number")),
            "the advertised output schema must survive: {:?}",
            tools[0].output_schema
        );
    }

    /// A server that spells the absent field as an explicit null has declared
    /// NOTHING, and must be indistinguishable from one that omitted it.
    /// `serde_json` does distinguish them, so without a filter this is
    /// `Some(Value::Null)` — "declared a schema" — and a consumer validating the
    /// shape reports a malformed schema against a conformant peer.
    #[test]
    fn map_tools_list_treats_an_explicit_null_output_schema_as_absent() {
        let explicit = json!({"tools": [{
            "name": "t", "description": "", "inputSchema": {}, "outputSchema": null
        }]});
        let omitted = json!({"tools": [{"name": "t", "description": "", "inputSchema": {}}]});
        assert_eq!(map_tools_list(&explicit)[0].output_schema, None);
        assert_eq!(
            map_tools_list(&explicit)[0].output_schema,
            map_tools_list(&omitted)[0].output_schema,
            "an explicit null and an omitted field must be the same answer"
        );
    }

    /// `outputSchema` is OPTIONAL in the MCP spec, so its absence is normal and
    /// must stay distinguishable from a server that declared an empty one —
    /// hence `None`, not `{}`.
    #[test]
    fn map_tools_list_leaves_an_absent_output_schema_as_none() {
        let result = json!({"tools": [{"name": "t", "description": "", "inputSchema": {}}]});
        let tools = map_tools_list(&result);
        assert_eq!(tools[0].output_schema, None);
    }

    /// Reported verbatim rather than normalised: a caller that cares whether
    /// the schema is well-formed can only say so if it can see what arrived.
    #[test]
    fn map_tools_list_passes_a_malformed_output_schema_through() {
        let result = json!({"tools": [{
            "name": "t", "description": "", "inputSchema": {}, "outputSchema": "not-an-object"
        }]});
        let tools = map_tools_list(&result);
        assert_eq!(tools[0].output_schema, Some(json!("not-an-object")));
    }

    #[test]
    fn map_tools_list_missing_tools_returns_empty() {
        assert!(map_tools_list(&json!({})).is_empty());
    }

    #[test]
    fn map_tools_list_drops_tool_without_name() {
        let result = json!({ "tools": [
            { "name": "good_tool", "description": "ok" },
            { "description": "no name here" }
        ]});
        let defs = map_tools_list(&result);
        assert_eq!(defs.len(), 1);
        assert_eq!(defs[0].name, "good_tool");
    }

    #[test]
    fn map_tools_list_missing_schema_defaults_to_empty_object() {
        let result = json!({ "tools": [{ "name": "t", "description": "d" }] });
        let defs = map_tools_list(&result);
        assert_eq!(defs[0].input_schema, json!({}));
    }

    #[test]
    fn extract_tool_output_joins_text_content() {
        let result = json!({ "content": [ { "type": "text", "text": "line1" }, { "type": "text", "text": "line2" } ] });
        let out = extract_tool_output(&result).unwrap();
        assert_eq!(out.text, "line1\nline2");
        assert!(out.structured.is_none());
        assert_eq!(out.to_value(), json!("line1\nline2"));
    }

    #[test]
    fn extract_tool_output_keeps_structured_content() {
        let result = json!({ "structuredContent": { "number": 7 }, "content": [ { "type": "text", "text": "also text" } ] });
        let out = extract_tool_output(&result).unwrap();
        assert_eq!(out.structured, Some(json!({ "number": 7 })));
        assert_eq!(out.text, "also text");
        assert_eq!(out.to_value(), json!({ "number": 7 }));
    }

    #[test]
    fn extract_tool_output_is_error_maps_to_err() {
        let result =
            json!({ "isError": true, "content": [ { "type": "text", "text": "not found" } ] });
        let err = extract_tool_output(&result).unwrap_err();
        assert_eq!(err.message, "not found");
    }

    #[test]
    fn extract_tool_output_is_error_without_payload_has_default_message() {
        let result = json!({ "isError": true });
        let err = extract_tool_output(&result).unwrap_err();
        assert_eq!(err.message, "tool call returned isError");
    }

    #[test]
    fn extract_tool_output_empty_content_returns_empty_ok() {
        let result = json!({ "content": [] });
        let out = extract_tool_output(&result).unwrap();
        assert_eq!(out.text, "");
    }
}