causa-extension 0.2.0

Causa extensions — DynamicToolSource adapters (MCP, …) over the causa-kernel ports
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! `mcp` — a first-class MCP client.
//!
//! Wraps the official Rust SDK [`rmcp`](https://docs.rs/rmcp) so external
//! MCP servers' tools enter the kernel's `ToolSurface` next to local Rust
//! tools. The module depends on `causa-kernel` alone (plus
//! rmcp) and exposes only kernel port vocabulary — the same layering as
//! `causa-provider` implementing `ModelGateway`.
//!
//! # Layout
//!
//! - [`McpToolSource`] implements the kernel's `DynamicToolSource` port
//!   over stdio (child process), Streamable HTTP, or an arbitrary
//!   in-process I/O pair.
//! - Tools are namespaced `mcp_{server_id}_{tool}` so identically-named
//!   tools on different servers cannot collide.
//! - `tools/list_changed` notifications bump the source's version, which
//!   the executor-side cache in `causa-runtime` keys on.
//!
//! # Connecting
//!
//! Local MCP server as a child process (stdio):
//!
//! ```ignore
//! use causa_extension::McpToolSource;
//!
//! let mut command = tokio::process::Command::new("uvx");
//! command.args(["mcp-server-fetch"]);
//! let source = McpToolSource::connect_stdio("fetch", command).await?;
//!
//! // With the executor (causa-runtime): the tools enter the turn's
//! // ToolSurface under the `mcp_fetch_*` namespace, cached until the
//! // server notifies `tools/list_changed`.
//! executor.register_dynamic(std::sync::Arc::new(source))?;
//! ```
//!
//! The child inherits the host's stderr. To keep a server's log out of a
//! terminal the host draws, or to read it, choose where it goes:
//!
//! ```ignore
//! let (reader, writer) = std::io::pipe()?;
//! let source = McpToolSource::connect_stdio_with_stderr("fetch", command, writer).await;
//! // Read `reader` (a blocking reader) whether or not the connect succeeded.
//! ```
//!
//! Remote MCP server (Streamable HTTP) with a static bearer token:
//!
//! ```ignore
//! let source = McpToolSource::connect_http(
//!     "remote",
//!     "https://mcp.example.com/mcp",
//!     Some(std::env::var("MCP_TOKEN")?),
//! ).await?;
//! executor.register_dynamic(std::sync::Arc::new(source))?;
//! ```
//!
//! A server that asks for other headers, such as an API key header, gets
//! them on every request:
//!
//! ```ignore
//! let source = McpToolSource::connect_http_with_headers(
//!     "remote",
//!     "https://mcp.example.com/mcp",
//!     [("X-API-Key", std::env::var("MCP_API_KEY")?)],
//! ).await?;
//! ```
//!
//! # Namespacing
//!
//! Every tool is exposed as `mcp_{server_id}_{tool}`, so identically-named
//! tools on different servers cannot collide. The executor routes by
//! listing membership (a source is dispatched exactly the names it
//! advertised in the surface); this source de-namespaces the call before
//! invoking and rejects names outside its namespace.
//!
//! # Safety notes
//!
//! External tools are an injection surface: their output is model-visible
//! input and their effects are host-executed. Hosts should keep the
//! approval policy in a `ToolBatchProcessor` registered in the executor
//! before-processing chain, for dynamic-source and local tools alike.
#![deny(unsafe_code)]

use async_trait::async_trait;
use causa_kernel::{
    ArtifactHint, ArtifactKind, ArtifactStore, CallControl, DynamicToolSource, MediaRef,
    SourceError, ToolCallContext, ToolDefinition, ToolDescription, ToolExecutionError, ToolHints,
    ToolOutput, ToolResultPayload, ToolResultStatus,
};
use http::{HeaderName, HeaderValue};
use rmcp::handler::client::ClientHandler;
use rmcp::model::ContentBlock;
use rmcp::service::{NotificationContext, RoleClient, RunningService, ServiceExt};
use rmcp::transport::StreamableHttpClientTransport;
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

/// Client handler that counts `tools/list_changed` notifications — the
/// change signal the executor-side cache keys on.
#[derive(Debug, Default)]
struct McpClientHandler {
    list_version: Arc<AtomicU64>,
}

impl ClientHandler for McpClientHandler {
    async fn on_tool_list_changed(&self, _context: NotificationContext<RoleClient>) {
        self.list_version.fetch_add(1, Ordering::SeqCst);
    }
}

/// MCP server catalog as a kernel [`DynamicToolSource`]. One instance per
/// server connection, shared behind the executor's `Arc`.
///
/// `server_id` becomes part of every model-facing tool name
/// (`mcp_{server_id}_{tool}`) — keep it non-empty `[A-Za-z0-9_-]` so names
/// stay provider-callable (debug builds assert this).
///
/// Error classification follows the gateway discipline: connection
/// failures and timeouts are `Unavailable`/`TimedOut` (transient);
/// protocol violations are `Protocol` (permanent).
///
/// Listing caches live executor-side (in `causa-runtime`, keyed on
/// [`DynamicToolSource::version`]); this source re-lists on every
/// `describe()` or `list()` call and stays a thin transport adapter.
pub struct McpToolSource {
    server_id: String,
    namespace: String,
    service: RunningService<RoleClient, McpClientHandler>,
    list_version: Arc<AtomicU64>,
}

impl std::fmt::Debug for McpToolSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpToolSource")
            .field("server_id", &self.server_id)
            .field("list_version", &self.list_version.load(Ordering::SeqCst))
            .finish()
    }
}

impl McpToolSource {
    fn build(
        server_id: String,
        service: RunningService<RoleClient, McpClientHandler>,
        list_version: Arc<AtomicU64>,
    ) -> Self {
        debug_assert!(
            !server_id.is_empty()
                && server_id
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
            "server_id must be non-empty [A-Za-z0-9_-], got: {server_id}"
        );
        Self {
            namespace: format!("mcp_{}_", server_id),
            server_id,
            service,
            list_version,
        }
    }

    /// Connect to a local MCP server spawned as a child process (stdio
    /// transport). `command` is the server launch command; stdio frames
    /// the JSON-RPC session.
    ///
    /// rmcp owns the child and kills it during shutdown. A host that may
    /// end its runtime before [`close`](Self::close) finishes should set
    /// `kill_on_drop(true)` on `command` as a backstop.
    ///
    /// The child inherits the host's stderr, so whatever the server logs
    /// is written to the host's terminal. A host that draws the terminal
    /// itself, or wants the server's output (for example the reason a
    /// server failed to start), uses
    /// [`connect_stdio_with_stderr`](Self::connect_stdio_with_stderr).
    pub async fn connect_stdio(
        server_id: impl Into<String>,
        command: tokio::process::Command,
    ) -> Result<Self, SourceError> {
        Self::connect_stdio_with_stderr(server_id, command, std::process::Stdio::inherit()).await
    }

    /// Like [`connect_stdio`](Self::connect_stdio), with the child's stderr
    /// sent to `stderr` instead of the host's. A `stderr` setting on
    /// `command` itself is not used.
    ///
    /// rmcp owns the child and kills it during shutdown, as with
    /// [`connect_stdio`](Self::connect_stdio); set `kill_on_drop(true)` on
    /// `command` when the host may end its runtime before
    /// [`close`](Self::close) finishes.
    ///
    /// Pass [`Stdio::null()`](std::process::Stdio::null) to drop it, a
    /// [`File`](std::fs::File) to log it, or the writing end of
    /// [`std::io::pipe`] to read it: the reading end stays with the host,
    /// so the server's last words are readable even when the connect
    /// fails. The host's copy of the writing end is closed once the child
    /// is spawned, so the reading end reaches end of file when the server
    /// exits. `Stdio::piped()` gives the host nothing to read; its reading
    /// end is dropped here.
    pub async fn connect_stdio_with_stderr(
        server_id: impl Into<String>,
        command: tokio::process::Command,
        stderr: impl Into<std::process::Stdio>,
    ) -> Result<Self, SourceError> {
        let server_id = server_id.into();
        let list_version = Arc::new(AtomicU64::new(0));
        let (transport, _) = rmcp::transport::TokioChildProcess::builder(command)
            .stderr(stderr)
            .spawn()
            .map_err(|e| SourceError::Unavailable(e.to_string()))?;
        let handler = McpClientHandler {
            list_version: list_version.clone(),
        };
        let service = handler
            .serve(transport)
            .await
            .map_err(|e| SourceError::Unavailable(e.to_string()))?;
        Ok(Self::build(server_id, service, list_version))
    }

    /// Connect to a remote MCP server over Streamable HTTP. `auth_token`
    /// (v1 static authorization) is sent as a Bearer header on every
    /// request when present; OAuth flows stay out of scope until the
    /// rmcp `auth` feature is adopted here.
    ///
    /// A server that asks for another header (an API key header, another
    /// `Authorization` scheme, a tenant header) is reached with
    /// [`connect_http_with_headers`](Self::connect_http_with_headers).
    pub async fn connect_http(
        server_id: impl Into<String>,
        uri: impl Into<String>,
        auth_token: Option<String>,
    ) -> Result<Self, SourceError> {
        let mut config = StreamableHttpClientTransportConfig::with_uri(uri.into());
        if let Some(token) = auth_token {
            config = config.auth_header(token);
        }
        Self::serve_http(server_id.into(), config).await
    }

    /// Connect to a remote MCP server over Streamable HTTP, sending
    /// `headers` with every request of the session: each POST, the event
    /// stream GET and the session DELETE sent on [`close`](Self::close).
    /// A bearer token is one of them, as `("Authorization", "Bearer …")`.
    ///
    /// The headers are checked before connecting. Each of these returns
    /// [`SourceError::Protocol`] and opens no connection:
    ///
    /// - a name or value that is not a valid HTTP header;
    /// - a name given twice, compared without case;
    /// - a name the transport writes itself: `Accept`, `Content-Type`,
    ///   `Last-Event-Id`, and every name starting with `Mcp-`
    ///   (`Mcp-Session-Id`, `MCP-Protocol-Version`, …).
    ///
    /// The error names the header and never contains its value. Every
    /// value is marked sensitive, so it is hidden from `Debug` output.
    pub async fn connect_http_with_headers<I, K, V>(
        server_id: impl Into<String>,
        uri: impl Into<String>,
        headers: I,
    ) -> Result<Self, SourceError>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let custom_headers = parse_headers(headers)?;
        let config = StreamableHttpClientTransportConfig::with_uri(uri.into())
            .custom_headers(custom_headers);
        Self::serve_http(server_id.into(), config).await
    }

    async fn serve_http(
        server_id: String,
        config: StreamableHttpClientTransportConfig,
    ) -> Result<Self, SourceError> {
        let list_version = Arc::new(AtomicU64::new(0));
        let transport = StreamableHttpClientTransport::from_config(config);
        let handler = McpClientHandler {
            list_version: list_version.clone(),
        };
        let service = handler
            .serve(transport)
            .await
            .map_err(|e| SourceError::Unavailable(e.to_string()))?;
        Ok(Self::build(server_id, service, list_version))
    }

    /// Connect over an arbitrary byte stream — the in-process server
    /// path (tests, embedded servers). `io` is the client side of a
    /// connected pipe: writes go to the server, reads carry the server's
    /// output.
    pub async fn connect_io<I>(server_id: impl Into<String>, io: I) -> Result<Self, SourceError>
    where
        I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
    {
        let server_id = server_id.into();
        let list_version = Arc::new(AtomicU64::new(0));
        let handler = McpClientHandler {
            list_version: list_version.clone(),
        };
        let service = handler
            .serve(io)
            .await
            .map_err(|e| SourceError::Unavailable(e.to_string()))?;
        Ok(Self::build(server_id, service, list_version))
    }

    /// Shut the underlying session down. Best-effort: this call signals
    /// cancellation before it starts waiting, then waits up to two seconds
    /// for rmcp's `RunningService::cancel` to finish — the session-cleanup
    /// DELETE of a Streamable HTTP transport can hang when it races with
    /// the service being torn down (notably the axum `StreamableHttpService`
    /// test fixture wrapped in a `capture_auth` middleware — see
    /// `tests/integration.rs`), so the wait is bounded.
    ///
    /// The bound limits the wait, not the shutdown. Cancellation is already
    /// signalled, so rmcp drains in-flight responses for up to two seconds
    /// while this call waits, then closes the transport. A timeout only
    /// detaches the join handle; cleanup continues in a background task.
    /// For stdio, closing the transport shuts the child's stdin and rmcp
    /// kills the child if it is still running three seconds later, so the
    /// worst case from this call to the kill is about five seconds. An `Ok`
    /// return means the wait ended, not that the server exited.
    ///
    /// A host that may end its runtime before that background cleanup
    /// finishes should set `kill_on_drop(true)` on the
    /// `tokio::process::Command` passed to
    /// [`connect_stdio`](Self::connect_stdio) or
    /// [`connect_stdio_with_stderr`](Self::connect_stdio_with_stderr):
    /// rmcp runs that kill in a task of its own, which may never run once
    /// the runtime stops, while `kill_on_drop` kills the child when its
    /// handle is dropped.
    pub async fn close(self) -> Result<(), SourceError> {
        // Move the service into the timed future so a timeout leaves the
        // shutdown to rmcp: dropping it signals cancellation and the
        // background task finishes the cleanup.
        let server_id = self.server_id.clone();
        let service = self.service;
        match tokio::time::timeout(std::time::Duration::from_secs(2), service.cancel()).await {
            Ok(Ok(_)) => Ok(()),
            Ok(Err(e)) => Err(SourceError::Unavailable(e.to_string())),
            Err(_) => {
                tracing::warn!(
                    server_id = %server_id,
                    "MCP close wait timed out; rmcp continues session cleanup in the background"
                );
                Ok(())
            }
        }
    }

    /// The tool name this source answers to for `tool`.
    pub fn namespaced(&self, tool: &str) -> String {
        format!("{}{}", self.namespace, tool)
    }

    /// Strip the namespace prefix; `None` when the call does not belong
    /// to this server.
    fn denamespace<'a>(&self, tool_name: &'a str) -> Option<&'a str> {
        tool_name.strip_prefix(&self.namespace)
    }

    fn map_service_error(e: rmcp::ServiceError) -> SourceError {
        match e {
            rmcp::ServiceError::Timeout { .. }
            | rmcp::ServiceError::TransportSend(_)
            | rmcp::ServiceError::TransportClosed => SourceError::Unavailable(e.to_string()),
            _ => SourceError::Protocol(e.to_string()),
        }
    }

    fn map_invoke_error(e: rmcp::ServiceError) -> ToolExecutionError {
        match e {
            rmcp::ServiceError::Timeout { .. } => ToolExecutionError::TimedOut,
            rmcp::ServiceError::Cancelled { .. } => ToolExecutionError::Cancelled,
            rmcp::ServiceError::TransportSend(_) | rmcp::ServiceError::TransportClosed => {
                ToolExecutionError::Unavailable(e.to_string())
            }
            _ => ToolExecutionError::Protocol(e.to_string()),
        }
    }
}

#[async_trait]
impl DynamicToolSource for McpToolSource {
    fn id(&self) -> &str {
        &self.server_id
    }

    /// Bumped by `tools/list_changed` notifications. The executor
    /// re-lists only when this differs from its cached snapshot.
    fn version(&self) -> u64 {
        self.list_version.load(Ordering::SeqCst)
    }

    async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError> {
        Ok(self
            .describe()
            .await?
            .into_iter()
            .map(|description| description.definition)
            .collect())
    }

    /// Lists the tools with the hints their annotations declare:
    /// `readOnlyHint`, `destructiveHint`, `idempotentHint` and
    /// `openWorldHint` map one to one. A hint the server leaves out stays
    /// undeclared; the MCP specification's defaults are not filled in, and
    /// the annotation `title` is not carried.
    async fn describe(&self) -> Result<Vec<ToolDescription>, SourceError> {
        let listed = self
            .service
            .list_tools(None)
            .await
            .map_err(Self::map_service_error)?;
        Ok(listed
            .tools
            .into_iter()
            .map(|tool| {
                let hints = tool
                    .annotations
                    .as_ref()
                    .map(annotation_hints)
                    .unwrap_or_default();
                ToolDescription::new(ToolDefinition::new(
                    self.namespaced(tool.name.as_ref()),
                    tool.description.map(|d| d.to_string()).unwrap_or_default(),
                    serde_json::Value::Object((*tool.input_schema).clone()),
                ))
                .with_hints(hints)
            })
            .collect())
    }

    async fn invoke(
        &self,
        call: &ToolCallContext,
        control: &CallControl,
        store: Option<&dyn ArtifactStore>,
    ) -> Result<ToolResultPayload, ToolExecutionError> {
        Self::invoke_inner(self, call, control, store).await
    }
}

/// Headers the Streamable HTTP transport writes itself; a host value would
/// clash with the transport's own. Every `Mcp-` name is the protocol's.
const TRANSPORT_HEADERS: [&str; 3] = ["accept", "content-type", "last-event-id"];

/// Turn host headers into rmcp's map, rejecting what rmcp would reject
/// only on the first request, or would let through and break the session.
/// Messages name the header and never quote a value.
fn parse_headers<I, K, V>(headers: I) -> Result<HashMap<HeaderName, HeaderValue>, SourceError>
where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<str>,
    V: AsRef<str>,
{
    let mut parsed = HashMap::new();
    for (name, value) in headers {
        let name = name.as_ref();
        let header = HeaderName::try_from(name)
            .map_err(|_| SourceError::Protocol(format!("invalid header name {name:?}")))?;
        if TRANSPORT_HEADERS.contains(&header.as_str()) || header.as_str().starts_with("mcp-") {
            return Err(SourceError::Protocol(format!(
                "header {name} is set by the MCP transport"
            )));
        }
        let mut value = HeaderValue::try_from(value.as_ref())
            .map_err(|_| SourceError::Protocol(format!("invalid value for header {name}")))?;
        value.set_sensitive(true);
        if parsed.insert(header, value).is_some() {
            return Err(SourceError::Protocol(format!(
                "header {name} is given more than once"
            )));
        }
    }
    Ok(parsed)
}

/// The kernel hints an MCP tool's annotations declare.
fn annotation_hints(annotations: &rmcp::model::ToolAnnotations) -> ToolHints {
    let mut hints = ToolHints::default();
    hints.read_only = annotations.read_only_hint;
    hints.destructive = annotations.destructive_hint;
    hints.idempotent = annotations.idempotent_hint;
    hints.open_world = annotations.open_world_hint;
    hints
}

impl McpToolSource {
    /// The shared invoke body: `store` is the host's artifact store for
    /// media ingest — with one, MCP image, audio and binary resource
    /// content is persisted and returned as [`MediaRef`]s on the result;
    /// without one, each degrades to a placeholder line of text.
    async fn invoke_inner(
        &self,
        call: &ToolCallContext,
        control: &CallControl,
        store: Option<&dyn ArtifactStore>,
    ) -> Result<ToolResultPayload, ToolExecutionError> {
        // 1. De-namespace; a foreign call is an executor routing bug.
        let Some(tool_name) = self.denamespace(&call.input.tool_name) else {
            return Err(ToolExecutionError::UnknownTool(
                call.input.tool_name.clone(),
            ));
        };
        let arguments = match &call.input.arguments {
            serde_json::Value::Object(map) => Some(map.clone()),
            serde_json::Value::Null => None,
            other => {
                return Err(ToolExecutionError::Protocol(format!(
                    "MCP tool arguments must be an object, got: {other}"
                )));
            }
        };
        let mut params = rmcp::model::CallToolRequestParams::new(Cow::Owned(tool_name.to_string()));
        if let Some(args) = arguments {
            params = params.with_arguments(args);
        }

        // 2. Race the call against the shared cancellation token and the
        //    effective call deadline — the same control-plane semantics
        //    local tools get.
        let deadline = control.deadline();
        let token = control.cancellation_token().clone();
        let result = tokio::select! {
            biased;
            _ = token.cancelled() => return Err(ToolExecutionError::Cancelled),
            r = async {
                match deadline {
                    Some(deadline) => {
                        tokio::time::timeout_at(deadline.into(), self.service.call_tool(params))
                            .await
                            .map_err(|_| ToolExecutionError::TimedOut)?
                            .map_err(Self::map_invoke_error)
                    }
                    None => self
                        .service
                        .call_tool(params)
                        .await
                        .map_err(Self::map_invoke_error),
                }
            } => r?,
        };

        // 3. Translate the MCP result: text becomes the observation;
        //    images, audio and binary resources persist into the host's
        //    store and return as media references, with one line of text
        //    naming each; `is_error` results become Failed outcomes the
        //    model reads. Bytes never enter the text: without a store, or
        //    when the ingest fails, only a placeholder line remains.
        let mut parts: Vec<String> = Vec::new();
        let mut media: Vec<MediaRef> = Vec::new();
        for block in result.content {
            match block {
                ContentBlock::Text(t) => parts.push(t.text),
                ContentBlock::Image(image) => {
                    let ingest =
                        Ingest::run(&image.data, &image.mime_type, None, store, call).await;
                    parts.push(ingest.describe("image", &image.mime_type));
                    media.extend(ingest.into_media());
                }
                ContentBlock::Audio(audio) => {
                    let ingest =
                        Ingest::run(&audio.data, &audio.mime_type, None, store, call).await;
                    parts.push(ingest.describe("audio", &audio.mime_type));
                    media.extend(ingest.into_media());
                }
                ContentBlock::Resource(embedded) => match embedded.resource {
                    rmcp::model::ResourceContents::TextResourceContents {
                        uri,
                        text: inner,
                        ..
                    } => parts.push(format!("[resource {uri}]\n{inner}")),
                    rmcp::model::ResourceContents::BlobResourceContents {
                        uri,
                        mime_type,
                        blob,
                        ..
                    } => {
                        let mime_type =
                            mime_type.unwrap_or_else(|| "application/octet-stream".to_owned());
                        let name = resource_name_from_uri(&uri);
                        let ingest = Ingest::run(&blob, &mime_type, name, store, call).await;
                        parts.push(ingest.describe("resource", &format!("{uri} ({mime_type})")));
                        media.extend(ingest.into_media());
                    }
                    other => parts.push(format!(
                        "[resource: {} — unsupported contents]",
                        serialized_field(serde_json::to_value(&other), "uri")
                    )),
                },
                ContentBlock::ResourceLink(link) => parts.push(format!("[link: {}]", link.uri)),
                other => parts.push(format!(
                    "[unsupported content: {}]",
                    serialized_field(serde_json::to_value(&other), "type")
                )),
            }
        }
        let text = parts.join("\n");
        let content = match result.structured_content {
            Some(value) => value,
            None => serde_json::Value::String(text),
        };
        let status = if result.is_error.unwrap_or(false) {
            ToolResultStatus::Failed
        } else {
            ToolResultStatus::Succeeded
        };
        Ok(
            ToolResultPayload::new(call.call_block_id, status, ToolOutput::new(content))
                .with_media(media),
        )
    }
}

/// The result of storing one piece of MCP binary content (image, audio or
/// blob resource) in the host's artifact store.
enum Ingest {
    /// Persisted; the reference is keyed by the store-assigned artifact id.
    Stored(MediaRef),
    /// No store is wired for this call.
    NoStore,
    /// A store is wired, but the base64 is malformed or the persist failed.
    Failed,
}

impl Ingest {
    /// Decode `data` and persist the raw bytes, tagged with the call's
    /// provenance, as an artifact of `media_type`.
    async fn run(
        data: &str,
        media_type: &str,
        name: Option<String>,
        store: Option<&dyn ArtifactStore>,
        call: &ToolCallContext,
    ) -> Self {
        use base64::Engine as _;
        let Some(store) = store else {
            return Self::NoStore;
        };
        let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(data) else {
            return Self::Failed;
        };
        let hint = ArtifactHint::new(
            call.input.tool_name.clone(),
            call.call_block_id,
            ArtifactKind::Binary,
        );
        match store.persist(&bytes, hint).await {
            Ok(artifact) => {
                let mut media_ref = MediaRef::new(media_type, artifact.id);
                if let Some(name) = name {
                    media_ref = media_ref.with_name(name);
                }
                Self::Stored(media_ref)
            }
            Err(_) => Self::Failed,
        }
    }

    /// The line of observation text standing for the content: `kind` is
    /// `image`, `audio` or `resource`, and `label` names it (its MIME type,
    /// plus the uri for a resource).
    fn describe(&self, kind: &str, label: &str) -> String {
        match self {
            Self::Stored(reference) => {
                format!("[{kind} attached: {label} — asset {}]", reference.reference)
            }
            Self::NoStore => format!("[{kind}: {label} — no media store available]"),
            Self::Failed => format!("[{kind}: {label} — could not be stored]"),
        }
    }

    fn into_media(self) -> Option<MediaRef> {
        match self {
            Self::Stored(reference) => Some(reference),
            Self::NoStore | Self::Failed => None,
        }
    }
}

/// One string field of an MCP value this adapter does not translate, read
/// from its serialized form; `unknown` when absent. Never formats the whole
/// value, which may carry base64 bytes.
fn serialized_field(value: serde_json::Result<serde_json::Value>, key: &str) -> String {
    value
        .ok()
        .and_then(|value| value.get(key)?.as_str().map(str::to_owned))
        .unwrap_or_else(|| "unknown".to_owned())
}

/// Extracts a file name from a resource URI by stripping query and fragment
/// components and taking the trailing path segment after the last slash.
/// Returns `None` if the segment is empty or no slash is present.
fn resource_name_from_uri(uri: &str) -> Option<String> {
    let path = match uri.find(['?', '#']) {
        Some(idx) => &uri[..idx],
        None => uri,
    };
    let idx = path.rfind('/')?;
    let segment = &path[idx + 1..];
    (!segment.is_empty()).then(|| segment.to_owned())
}

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

    #[test]
    fn resource_name_from_uri_extracts_name_or_none() {
        assert_eq!(
            resource_name_from_uri("file:///memo.pdf").as_deref(),
            Some("memo.pdf")
        );
        assert_eq!(
            resource_name_from_uri("https://h/a/b.pdf?x=1#y").as_deref(),
            Some("b.pdf")
        );
        assert_eq!(resource_name_from_uri("mem://"), None);
        assert_eq!(resource_name_from_uri("file:///memo/"), None);
        assert_eq!(
            resource_name_from_uri("https://example.com/dir/?foo=1"),
            None
        );
    }
}