rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! Tools a run serves its agent as one MCP server, [`SERVER_NAME`], carried
//! over the ACP connection itself (MCP-over-ACP, an agent that advertises
//! `mcpCapabilities.acp`), or over a stdio bridge to an agent that takes no
//! server there ([`bridge`]).
//!
//! The run declares the server on `session/new` and on `session/resume`,
//! as an `acp` transport with an id of its own, since each run is a new
//! agent process. The agent then sends each MCP request to Rho as an
//! `mcp/message` request on the connection the driver already owns, so
//! that transport needs no listener, socket or token: only the agent this
//! run started can call, and only while the run lasts. Recorded against
//! claude-agent-acp 0.114.0 (Claude Code 2.1.333), which bridges the server
//! to Claude Code and sends, in MCP 2026-07-28 with no `initialize`:
//! - `server/discover` and `tools/list`, without a session, while
//!   `session/new` is still unanswered;
//! - `tools/call`, naming the session and the agent's tool call
//!   (`toolCallId`) it runs for.
//!
//! The binding is Rho's own rather than the SDK's MCP-over-ACP server
//! (agent-client-protocol 5.6.1): on v1 only a new session can attach that
//! server (`SessionBuilder::with_mcp_server`), not a resumed one, and its
//! session handler is crate-private. Once the SDK attaches a server on
//! resume, this binding can go.
//!
//! An agent that takes no MCP server over its connection (agy, Antigravity's
//! ACP server 1.5.21, advertises no `mcpCapabilities`) is declared a stdio
//! server instead, whose command relays to the run's private endpoint, a
//! connection to which must first present the run's token ([`bridge`]).
//!
//! What a tool does, and whether it may, is the [`AgentTools`] owner's: the
//! binding only checks the envelope. Each call draws its own card in the
//! run's journal, under the agent's tool call ([`CallCards`]), in place of
//! the card the agent shows for it.

use std::{
    future::Future,
    sync::{Arc, OnceLock},
};

use agent_client_protocol::{
    mcp_server::MCP_SERVER_UNAVAILABLE,
    v1::schema::{
        McpError, McpServer, McpServerAcp, McpServerAcpId, MessageMcpRequest, MessageMcpResponse,
        SessionId, SessionUpdate, ToolCallId,
    },
    Agent, ConnectionTo, Error, Protocol, Responder, UntypedMessage,
};
use futures_util::future::BoxFuture;
use rho_tools::cancellation::RunCancellation;
use rmcp::model::{
    CallToolRequestParams, CallToolResult, DiscoverResult, ErrorCode, Implementation,
    ListToolsResult, ProtocolVersion, RequestMetaObject, ServerCapabilities, ServerConfig, Tool,
};
use serde_json::{json, Map, Value};
use tokio::{sync::mpsc, time::Instant};

use crate::cli_runtime::agent_event::{AgentEvent, ServedCard};
use own_calls::OwnCalls;

mod announced;
pub(crate) mod bridge;
mod own_calls;
mod parked;

/// The name the agent knows the server by, which it prefixes the tools'
/// names with ([`McpToolNaming`]).
pub(crate) const SERVER_NAME: &str = "rho";

/// How an agent's runtime names the tools of [`SERVER_NAME`]: `mcp`, the
/// server's name and the tool's, joined by its separator, as Claude Code's
/// `mcp__rho__<tool>`. Each runtime's policy owns its own.
///
/// A separator that server and tool names may themselves hold, as agy's
/// `_`, makes a name ambiguous: a server `rho_watch`'s tool `pull_request`
/// reads back as rho's `watch_pull_request`. Reading a name back is sound
/// only where the agent sees no server but rho's, as each runtime ensures.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct McpToolNaming {
    separator: &'static str,
}

impl McpToolNaming {
    /// The naming that joins its parts with `separator`.
    pub(crate) const fn separated_by(separator: &'static str) -> Self {
        Self { separator }
    }

    /// What the agent calls the server's tool `tool`.
    pub(crate) fn name_of(self, tool: &str) -> String {
        let separator = self.separator;
        format!("mcp{separator}{SERVER_NAME}{separator}{tool}")
    }

    /// The server's tool the agent's `name` names, if it names one.
    pub(crate) fn tool_of(self, name: &str) -> Option<&str> {
        name.strip_prefix("mcp")?
            .strip_prefix(self.separator)?
            .strip_prefix(SERVER_NAME)?
            .strip_prefix(self.separator)
    }
}

/// The ACP method that carries an MCP request to a server the client
/// declared.
pub(super) const MCP_MESSAGE: &str = "mcp/message";

/// The MCP revision the binding speaks; claude-agent-acp's binding sends
/// no other.
const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::V_2026_07_28;

/// The tools a run serves its agent. The owner decides what each call may
/// do, as its own tool calls would; the agent's own permission asks for
/// them are approved (see [`super::AcpAgentPolicy::agent_tool`]).
///
/// A call's work must stop once its cancellation fires, since the run that
/// served it ended. The run may drop the call's future before then, so
/// work that outlives a poll must watch the token rather than rely on the
/// future being polled.
///
/// The owner also hears what the agent waits on: each of its requests to
/// the tools, while it is blocked on it ([`Self::request`]), and how many
/// tool calls of its own it has in progress ([`Self::agent_calls`]).
pub(crate) trait AgentTools: Send + Sync {
    /// The tools, as `tools/list` lists them.
    fn list(&self) -> Vec<Tool>;
    /// Whether [`Self::list`] lists a tool called `name`. Every permission
    /// ask and every call asks; override it where listing is costly.
    fn serves(&self, name: &str) -> bool {
        self.list().iter().any(|tool| tool.name == name)
    }
    /// Runs one call of a tool [`Self::serves`]. A tool's own failure is a
    /// result with `is_error`, not a missing one.
    fn call(&self, call: AgentToolCall) -> BoxFuture<'static, CallToolResult>;
    /// One of the agent's requests to the tools is outstanding: a
    /// `tools/call`, on either transport, or the bridge's `await`. The agent
    /// is blocked on it until it has the answer, while a call it started
    /// may run on past its answer (a call the bridge parks). The owner
    /// hears of it before the binding serves the request, and readies the
    /// answer, with whatever must settle before the agent goes on, before
    /// it goes back ([`AgentRequest::answer_by`]). The default readies at
    /// once.
    fn request(&self) -> AgentRequest {
        AgentRequest::ready()
    }
    /// The agent's own tool calls in progress, of tools other than these,
    /// now number `running`: each from its announcement until the agent
    /// ends it, and none once the run ends. Such a call may go on while the
    /// agent waits on these tools, as a Claude Code Task subagent does,
    /// making model requests of its own. The default ignores it.
    fn agent_calls(&self, _running: usize) {}
}

/// One of the agent's requests to its run's tools, outstanding: the agent
/// is blocked on its answer ([`AgentTools::request`]). It counts as
/// outstanding until [`Self::answer_by`] readies the answer or gives up on
/// readying it, or it drops, as when the run ends first.
#[must_use = "a request readies its answer before the answer goes back"]
pub(crate) struct AgentRequest {
    /// Readies the answer once polled: the owner's work, which must start
    /// only when first polled, and whose drop, polled or not, must stop
    /// the request counting.
    answer: BoxFuture<'static, ()>,
    /// The owner hears that the answer went back before `answer` readied
    /// it, and says what the run shows of that, if anything.
    overdue: Box<dyn FnOnce() -> Option<String> + Send>,
}

/// How a request's answer went back ([`AgentRequest::answer_by`]).
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Readied {
    /// Readied.
    Ready,
    /// Before the owner readied it, its transport's deadline passed, with
    /// the owner's notice of that for the run to show, if it has one.
    Overdue { notice: Option<String> },
}

impl AgentRequest {
    /// The request that `answer` readies the answer to, and `overdue` hears
    /// went back unreadied. `answer` must do nothing until first polled (an
    /// `async` block, which runs only once polled), and stop counting the
    /// request once polled or dropped.
    pub(crate) fn new(
        answer: BoxFuture<'static, ()>,
        overdue: Box<dyn FnOnce() -> Option<String> + Send>,
    ) -> Self {
        Self { answer, overdue }
    }

    /// A request nothing counts, whose answer is ready at once.
    pub(crate) fn ready() -> Self {
        Self::new(Box::pin(std::future::ready(())), Box::new(|| None))
    }

    /// Readies the request's answer to go back to the agent, whose next
    /// model request may follow it, by the transport's `deadline`, past
    /// which the answer is lost: resolves once it may go, or at `deadline`,
    /// readying given up on, so that it goes anyway. Without a deadline,
    /// waits as long as readying takes.
    pub(crate) async fn answer_by(self, deadline: Option<Instant>) -> Readied {
        let Self { answer, overdue } = self;
        let Some(deadline) = deadline else {
            answer.await;
            return Readied::Ready;
        };
        // Readying stops, its work dropped, before the owner hears.
        match tokio::time::timeout_at(deadline, answer).await {
            Ok(()) => Readied::Ready,
            Err(_elapsed) => Readied::Overdue { notice: overdue() },
        }
    }
}

/// One `tools/call` the agent made.
#[derive(Debug)]
pub(crate) struct AgentToolCall {
    pub(crate) name: String,
    pub(crate) arguments: Map<String, Value>,
    /// Fires once the run that served the call ends. Cancellation is per
    /// run only: the binding does not take MCP's per-request
    /// `notifications/cancelled`.
    pub(crate) cancellation: RunCancellation,
    /// Where the call draws its card.
    pub(crate) cards: CallCards,
}

/// Where one call draws its card: the run's journal, which its clients
/// follow and a reopen replays, under the agent's tool call, whose own card
/// the run holds back (see [`AgentEvent::ServedToolCall`]). The run draws
/// what it hears before each later message of the agent's, so the agent's
/// end of the call never overtakes the card. Once the run ended, nothing
/// draws.
#[derive(Clone, Debug)]
pub(crate) struct CallCards {
    key: ToolCallId,
    events: mpsc::UnboundedSender<AgentEvent>,
}

impl CallCards {
    /// The card's key: the agent's tool call, or one of the run's own for a
    /// call the agent named none for.
    pub(crate) fn key(&self) -> &ToolCallId {
        &self.key
    }

    /// Draws `card` on the call's card.
    pub(crate) fn draw(&self, card: ServedCard) {
        // The run ended: nobody follows it any more.
        let _ = self.events.send(AgentEvent::Served {
            call: self.key.clone(),
            card,
        });
    }

    /// The cards of the agent's tool call `key`, drawn into `events`, for
    /// a test of what a served call draws without a run.
    #[cfg(test)]
    pub(crate) fn for_test(key: &str, events: mpsc::UnboundedSender<AgentEvent>) -> Self {
        Self {
            key: ToolCallId::new(key.to_owned()),
            events,
        }
    }
}

/// What both of a run's transports call the tools through.
#[derive(Clone)]
struct ToolCalls {
    tools: Arc<dyn AgentTools>,
    /// Fires as the run ends, for every call still running.
    over: RunCancellation,
    /// What the run renders: where calls draw their cards.
    events: mpsc::UnboundedSender<AgentEvent>,
}

impl ToolCalls {
    /// The cards drawn under the agent's tool call `key`.
    fn cards(&self, key: ToolCallId) -> CallCards {
        CallCards {
            key,
            events: self.events.clone(),
        }
    }

    /// The agent's tool call `key` draws no card: it shows on another
    /// call's ([`AgentEvent::ServedHidden`]).
    fn hide(&self, key: ToolCallId) {
        // The run ended: nobody follows it any more.
        let _ = self.events.send(AgentEvent::ServedHidden(key));
    }

    /// Starts a call of tool `name` with `arguments`, whose card is drawn
    /// under `key`, one of the run's own when the agent named none; `Err`,
    /// MCP's unknown tool message, for a tool the run does not serve.
    fn start(
        &self,
        name: String,
        arguments: Map<String, Value>,
        key: Option<ToolCallId>,
    ) -> Result<BoxFuture<'static, CallToolResult>, String> {
        if !self.tools.serves(&name) {
            return Err(format!("Unknown tool: {name}"));
        }
        let key = key.unwrap_or_else(|| {
            ToolCallId::new(format!("rho-call-{}", uuid::Uuid::new_v4().simple()))
        });
        Ok(self.tools.call(AgentToolCall {
            name,
            arguments,
            cancellation: self.over.clone(),
            cards: self.cards(key),
        }))
    }

    /// Serves one of the agent's requests to the tools with `work`, the
    /// agent blocked on it from now ([`AgentTools::request`]) until `work`
    /// has its answer and the tools readied it, or the transport's
    /// `deadline` for the answer passed, or the run ended. An answer the
    /// deadline hurried goes back unreadied, and the run shows the tools'
    /// notice of it; once the run ended, nobody hears the answer.
    async fn serve_blocking<T>(
        &self,
        deadline: Option<Instant>,
        work: impl Future<Output = T>,
    ) -> T {
        let request = self.tools.request();
        let answer = work.await;
        let readied = tokio::select! {
            biased;
            () = self.over.cancelled() => return answer,
            readied = request.answer_by(deadline) => readied,
        };
        match readied {
            Readied::Overdue {
                notice: Some(notice),
            } => {
                // Ignored: once the run ended, nobody hears it.
                let _ = self.events.send(AgentEvent::Notice(notice));
            }
            Readied::Overdue { notice: None } | Readied::Ready => {}
        }
        answer
    }
}

/// One run's server, on its agent's connection or, for an agent that
/// takes none there, over the stdio bridge.
pub(super) struct Served {
    calls: ToolCalls,
    server_id: McpServerAcpId,
    /// The agent's session, once set up: a call over the connection must
    /// name it.
    session: OnceLock<SessionId>,
    /// The stdio bridge, once the run opened one in place of serving over
    /// the connection.
    bridge: OnceLock<bridge::Bridge>,
    /// The agent's tool calls of its own in progress, whose count the
    /// tools hear ([`AgentTools::agent_calls`]).
    own_calls: OwnCalls,
}

/// Ends a run's calls when dropped, however the run ends: returning,
/// failing, panicking, or being dropped itself. The tools then hear that
/// the agent has no call of its own in progress any more.
pub(super) struct EndsCalls {
    over: RunCancellation,
    tools: Arc<dyn AgentTools>,
}

impl Drop for EndsCalls {
    fn drop(&mut self) {
        self.over.cancel();
        self.tools.agent_calls(0);
    }
}

impl Served {
    /// The run's server, whose calls draw their cards through `events`, which
    /// the run renders, and the guard that ends its calls with the run.
    pub(super) fn new(
        tools: Arc<dyn AgentTools>,
        events: mpsc::UnboundedSender<AgentEvent>,
    ) -> (Arc<Self>, EndsCalls) {
        let calls_over = RunCancellation::new();
        let ends_calls = EndsCalls {
            over: calls_over.clone(),
            tools: Arc::clone(&tools),
        };
        let served = Self {
            calls: ToolCalls {
                tools,
                over: calls_over,
                events,
            },
            // A run's own id: no other run's agent can address it.
            server_id: McpServerAcpId::new(format!("rho-{}", uuid::Uuid::new_v4().simple())),
            session: OnceLock::new(),
            bridge: OnceLock::new(),
            own_calls: OwnCalls::default(),
        };
        (Arc::new(served), ends_calls)
    }

    /// Serves the tools over the stdio bridge rather than the connection,
    /// for an agent that takes no MCP server there. Its endpoint lasts as
    /// long as the run's calls do. `Err` says why no bridge could open.
    pub(super) fn open_bridge(&self) -> Result<(), String> {
        let bridge = bridge::Bridge::open(self.calls.clone())?;
        let first = self.bridge.set(bridge);
        debug_assert!(
            first.is_ok(),
            "a run opens one bridge, before it declares the server"
        );
        Ok(())
    }

    /// The `mcpServers` entry the session's setup request declares.
    pub(super) fn declaration(&self) -> McpServer {
        match self.bridge.get() {
            Some(bridge) => McpServer::Stdio(bridge.declaration()),
            None => McpServer::Acp(McpServerAcp::new(SERVER_NAME, self.server_id.clone())),
        }
    }

    /// The agent's session is set up as `session`.
    pub(super) fn set_up(&self, session: SessionId) {
        let _ = self.session.set(session);
    }

    /// Whether the server serves a tool called `name`: the bridge's
    /// [`bridge::AWAIT_TOOL`] too.
    pub(super) fn serves(&self, name: &str) -> bool {
        self.calls.tools.serves(name) || self.bridge.get().is_some_and(|bridge| bridge.serves(name))
    }

    /// The agent's `update`, `tool` being the served tool it announces a
    /// call of, if any. The bridge's MCP calls, which name no tool call,
    /// draw their cards under these announcements (see [`announced`]);
    /// over the connection, each call names its own. The tools hear how
    /// many calls of its own the agent has in progress as that changes
    /// ([`OwnCalls`]).
    pub(super) fn heard(&self, update: &SessionUpdate, tool: Option<&str>) {
        if let Some(bridge) = self.bridge.get() {
            bridge.heard(update, tool);
        }
        if let Some(running) = self.own_calls.hear(update, tool) {
            self.calls.tools.agent_calls(running);
        }
    }

    /// The answer to one `mcp/message` request. An `Err` is the binding's
    /// own refusal (the ACP error of the request); an MCP error travels
    /// inside the answer.
    async fn answer(self: Arc<Self>, params: Value) -> Result<Value, Error> {
        let request: MessageMcpRequest = serde_json::from_value(params)
            .map_err(|source| Error::invalid_params().data(source.to_string()))?;
        self.check(&request)?;
        let answer = self.serve(request).await;
        Ok(serde_json::to_value(answer).expect("MCP answers serialize"))
    }

    /// Refuses a request for another server, or a call for another
    /// session than the run's.
    fn check(&self, request: &MessageMcpRequest) -> Result<(), Error> {
        if request.server_id != self.server_id {
            return Err(Error::new(
                MCP_SERVER_UNAVAILABLE,
                format!("no MCP server `{}` on this connection", request.server_id),
            ));
        }
        // Discovery and listing act on nothing, and come before the session
        // exists.
        if request.method != "tools/call" {
            return Ok(());
        }
        match (&request.session_id, self.session.get()) {
            (Some(named), Some(own)) if named == own => Ok(()),
            (named, _) => Err(Error::invalid_params().data(json!({
                "sessionId": named,
                "reason": "a tools/call must name the session this run set up",
            }))),
        }
    }

    async fn serve(&self, request: MessageMcpRequest) -> MessageMcpResponse {
        let MessageMcpRequest {
            method,
            params,
            tool_call_id,
            ..
        } = request;
        let params = Value::Object(params.unwrap_or_default());
        let version = params
            .get("_meta")
            .cloned()
            .and_then(|meta| serde_json::from_value::<RequestMetaObject>(meta).ok())
            .and_then(|meta| meta.protocol_version());
        if version.as_ref() != Some(&PROTOCOL_VERSION) {
            return mcp_error(
                ErrorCode::UNSUPPORTED_PROTOCOL_VERSION,
                "Unsupported protocol version".into(),
                Some(json!({"supported": [PROTOCOL_VERSION], "requested": version})),
            );
        }
        let result = match method.as_str() {
            "server/discover" => to_value(DiscoverResult::from_server_info(
                vec![PROTOCOL_VERSION],
                server_config(),
            )),
            "tools/list" => to_value(ListToolsResult::with_all_items(self.calls.tools.list())),
            "tools/call" => {
                let params: CallToolRequestParams = match serde_json::from_value(params) {
                    Ok(params) => params,
                    Err(source) => {
                        return mcp_error(ErrorCode::INVALID_PARAMS, source.to_string(), None)
                    }
                };
                // The agent is blocked on the call until its answer goes
                // back. claude-agent-acp relays the call with no limit on
                // it that is known, so the answer goes back once readied,
                // however long that takes.
                let ended = self.calls.serve_blocking(/*deadline*/ None, async {
                    let started = self.calls.start(
                        params.name.into_owned(),
                        params.arguments.unwrap_or_default(),
                        tool_call_id,
                    )?;
                    Ok::<_, String>(started.await)
                });
                match ended.await {
                    Ok(result) => to_value(result),
                    Err(message) => return mcp_error(ErrorCode::INVALID_PARAMS, message, None),
                }
            }
            other => {
                let message = format!("Method not found: {other}");
                return mcp_error(ErrorCode::METHOD_NOT_FOUND, message, None);
            }
        };
        MessageMcpResponse::success(result)
    }
}

/// What the server says of itself, on both transports: it serves tools,
/// and is rho's [`SERVER_NAME`], at this version.
fn server_config() -> ServerConfig {
    ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
        .with_server_info(Implementation::new(SERVER_NAME, env!("CARGO_PKG_VERSION")))
}

/// Answers one [`MCP_MESSAGE`] request, with or without a session, off the
/// dispatch loop: a call can wait on a person for as long as the turn
/// lasts.
pub(super) fn answer<Marker: Protocol>(
    served: Option<&Arc<Served>>,
    request: UntypedMessage,
    responder: Responder<Value, Marker>,
    cx: &ConnectionTo<Agent>,
) -> Result<(), Error> {
    let Some(served) = served else {
        return responder.respond_with_error(Error::new(
            MCP_SERVER_UNAVAILABLE,
            "the run serves no MCP server",
        ));
    };
    let answer = Arc::clone(served).answer(request.params);
    cx.spawn(async move {
        match answer.await {
            Ok(answer) => responder.respond(answer),
            Err(refused) => responder.respond_with_error(refused),
        }
    })
}

fn mcp_error(code: ErrorCode, message: String, data: Option<Value>) -> MessageMcpResponse {
    let error = McpError::new(code.0, message);
    MessageMcpResponse::error(match data {
        Some(data) => error.data(data),
        None => error,
    })
}

/// The wire form of an MCP result type, which always serializes.
fn to_value(result: impl serde::Serialize) -> Value {
    serde_json::to_value(result).expect("MCP result types serialize")
}

#[cfg(test)]
#[path = "agent_tools_tests.rs"]
mod tests;