rho-coding-agent 3.12.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
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
//! A run serves its agent Rho's tools as an MCP server carried over the ACP
//! connection: the agent discovers, lists and calls them with `mcp/message`,
//! and the run refuses what is not its own server's or session's.

use super::{AgentToolCall, AgentTools, McpToolNaming};
use crate::acp_runtime::{
    permission::PermissionDecision,
    policy::AcpProtocol,
    scripted_agent::{
        Record, Script, ScriptedAgent, StdioMcp, StdioMcpScript, Step, V2Script, V2Step,
    },
    session::run_on_channel,
    test_support::*,
};
use crate::run_artifacts::AttachmentEvent;
use agent_client_protocol::{
    v1::schema::{
        ContentChunk, PermissionOption, PermissionOptionKind, SessionUpdate, StopReason, ToolCall,
        ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
    },
    v2::schema as v2,
    Channel,
};
use futures_util::future::BoxFuture;
use pretty_assertions::assert_eq;
use rmcp::model::{CallToolResult, ContentBlock, Tool};
use serde_json::{json, Map, Value};
use std::sync::Arc;

/// One tool, `echo`, whose result is the call it heard.
struct Echo;

impl AgentTools for Echo {
    fn list(&self) -> Vec<Tool> {
        vec![Tool::new("echo", "Echoes the call", Arc::new(Map::new()))]
    }

    fn call(&self, call: AgentToolCall) -> BoxFuture<'static, CallToolResult> {
        let heard = json!({
            "name": call.name,
            "arguments": call.arguments,
            "toolCall": call.cards.key(),
        });
        Box::pin(
            async move { CallToolResult::success(vec![ContentBlock::text(heard.to_string())]) },
        )
    }
}

/// An `mcp/message` envelope for Rho's server, in the MCP revision
/// claude-agent-acp sends.
fn envelope(method: &str, params: Value, session: Option<&str>, tool_call: Option<&str>) -> Value {
    let mut params = params;
    params["_meta"] = json!({"io.modelcontextprotocol/protocolVersion": "2026-07-28"});
    let mut envelope = json!({
        "serverId": "$server",
        "requestId": method,
        "method": method,
        "params": params,
    });
    if let Some(session) = session {
        envelope["sessionId"] = json!(session);
    }
    if let Some(tool_call) = tool_call {
        envelope["toolCallId"] = json!(tool_call);
    }
    envelope
}

fn mcp(method: &str, params: Value, session: Option<&str>, tool_call: Option<&str>) -> Step {
    Step::Mcp {
        envelope: envelope(method, params, session, tool_call),
    }
}

fn end() -> Vec<Step> {
    vec![
        Step::Update {
            update: Box::new(SessionUpdate::AgentMessageChunk(ContentChunk::new(
                "done".to_owned().into(),
            ))),
        },
        Step::Stop {
            reason: StopReason::EndTurn,
        },
    ]
}

/// Runs `script` with `Echo` served, under a policy that rejects every ask
/// it decides and asks for the protocol the script's agent speaks; returns
/// what the agent recorded.
async fn serve(script: Script, resume: Option<&str>) -> (Record, Vec<AttachmentEvent>) {
    let dir = tempfile::tempdir().unwrap();
    let mut request = request(dir.path(), None);
    request.overrides.agent_tools = Some(Arc::new(Echo));
    request.overrides.resume = resume.map(str::to_owned);
    let mut policy = TestPolicy::new(dir.path());
    policy.decision = PermissionDecision::Reject;
    if script.v2.is_some() {
        policy.protocol = AcpProtocol::V2;
    }
    let (client, agent) = Channel::duplex();
    let (fake, record, _signals) = ScriptedAgent::new(script);
    tokio::time::timeout(TEST_BUDGET, async {
        let (client, agent) =
            tokio::join!(run_on_channel(request, policy, client), fake.run(agent));
        client.unwrap();
        agent.unwrap();
    })
    .await
    .expect("ACP runtime/agent finished");
    let record = std::mem::take(&mut *record.lock().unwrap());
    let (_, events) = read_artifacts(dir.path());
    (record, events)
}

/// The `mcpServers` each session setup request declared, with a server id
/// shaped as a run's own (`rho-` and a UUID) replaced by `"<server>"`, and
/// for the stdio bridge's, this executable, by the path it was started
/// from, by `"<rho>"`, its endpoint by `"<endpoint>"` and a 256-bit hex
/// token by `"<token>"`.
fn declared(record: &Record) -> Vec<(String, Value)> {
    let rho = crate::daemon::started_path().unwrap();
    record
        .declared_servers()
        .into_iter()
        .map(|(method, mut servers)| {
            for server in &mut servers {
                let id = server["serverId"].as_str().unwrap_or_default();
                let own = id
                    .strip_prefix("rho-")
                    .is_some_and(|uuid| uuid::Uuid::try_parse(uuid).is_ok());
                if own {
                    server["serverId"] = json!("<server>");
                }
                if server["command"] == json!(rho) {
                    server["command"] = json!("<rho>");
                }
                if server["args"][1].is_string() {
                    server["args"][1] = json!("<endpoint>");
                }
                let token = server["env"][0]["value"].as_str().unwrap_or_default();
                if token.len() == 64 && token.bytes().all(|byte| byte.is_ascii_hexdigit()) {
                    server["env"][0]["value"] = json!("<token>");
                }
            }
            (method, Value::Array(servers))
        })
        .collect()
}

fn mcp_replies(record: &Record) -> Vec<Value> {
    record
        .replies
        .iter()
        .filter(|reply| reply["method"] == "mcp/message")
        .cloned()
        .collect()
}

// Covers: an agent that takes MCP over ACP is declared Rho's server on
// `session/new`; it discovers and lists the tools without a session while
// `session/new` is still unanswered, as claude-agent-acp does; the
// run approves its permission ask for a served tool although the policy
// rejects every ask it decides, and a call reaches the tools with its
// arguments and the agent's tool call id, its result going back as the MCP
// result.
// Owner: ACP driver (MCP-over-ACP server).
#[tokio::test]
async fn a_run_serves_its_tools_over_the_connection() {
    let (record, _) = serve(
        Script {
            mcp_over_acp: true,
            setup_mcp: vec![
                envelope("server/discover", json!({}), None, None),
                envelope("tools/list", json!({}), None, None),
            ],
            turns: vec![[
                vec![
                    Step::Permission {
                        call: Box::new(
                            ToolCallUpdate::new("call-1", ToolCallUpdateFields::new())
                                .meta(json!({"tool": "echo"}).as_object().cloned()),
                        ),
                        options: vec![
                            PermissionOption::new("yes", "Allow", PermissionOptionKind::AllowOnce),
                            PermissionOption::new("no", "Reject", PermissionOptionKind::RejectOnce),
                        ],
                    },
                    mcp(
                        "tools/call",
                        json!({"name": "echo", "arguments": {"text": "hi"}}),
                        Some("$session"),
                        Some("call-1"),
                    ),
                ],
                end(),
            ]
            .concat()],
            ..Script::default()
        },
        None,
    )
    .await;

    assert_eq!(
        declared(&record),
        vec![(
            "session/new".to_owned(),
            json!([{"type": "acp", "name": "rho", "serverId": "<server>"}])
        )]
    );
    assert_eq!(
        mcp_replies(&record),
        vec![
            json!({"method": "mcp/message", "result": {"result": {
                "resultType": "complete",
                "supportedVersions": ["2026-07-28"],
                "capabilities": {"tools": {}},
                "ttlMs": 0,
                "cacheScope": "private",
                "_meta": {"io.modelcontextprotocol/serverInfo": {
                    "name": "rho",
                    "version": env!("CARGO_PKG_VERSION"),
                }},
            }}}),
            json!({"method": "mcp/message", "result": {"result": {
                "resultType": "complete",
                "tools": [{
                    "name": "echo",
                    "description": "Echoes the call",
                    "inputSchema": {},
                }],
            }}}),
            json!({"method": "mcp/message", "result": {"result": {
                "resultType": "complete",
                "content": [{
                    "type": "text",
                    "text": json!({
                        "name": "echo",
                        "arguments": {"text": "hi"},
                        "toolCall": "call-1",
                    }).to_string(),
                }],
                "isError": false,
            }}}),
        ]
    );
    let permission = record
        .replies
        .iter()
        .find(|reply| reply["method"] == "session/request_permission")
        .unwrap();
    assert_eq!(
        permission["result"]["outcome"],
        json!({"outcome": "selected", "optionId": "yes"})
    );
}

// Covers: on ACP v2 too, the run approves the agent's permission ask for a
// call of a tool it serves although the policy rejects every ask it
// decides, while the policy's rejection answers any other ask; the call
// reaches the tools under the agent's tool call, whose own card waits while
// it runs.
// Owner: ACP v2 client (MCP-over-ACP server).
#[tokio::test]
async fn a_v2_run_allows_and_serves_its_own_tools() {
    // The fake names the tool a call is of in its `_meta.tool`.
    let echo_call = || {
        v2::ToolCallUpdate::new("call-1")
            .title("echo".to_owned())
            .status(v2::ToolCallStatus::Pending)
            .meta(json!({"tool": "echo"}).as_object().cloned())
    };
    let (record, events) = serve(
        Script {
            v2: Some(V2Script {
                mcp_over_acp: true,
                turns: vec![vec![
                    V2Step::Running,
                    V2Step::Update {
                        session: None,
                        update: Box::new(v2::SessionUpdate::ToolCallUpdate(echo_call())),
                    },
                    V2Step::Permission {
                        title: "echo".into(),
                        call: Some(Box::new(echo_call())),
                    },
                    V2Step::Permission {
                        title: "Edit a.txt".into(),
                        call: Some(Box::new(
                            v2::ToolCallUpdate::new("edit-1").name("Edit".to_owned()),
                        )),
                    },
                    V2Step::Mcp {
                        envelope: envelope(
                            "tools/call",
                            json!({"name": "echo", "arguments": {"text": "hi"}}),
                            Some("$session"),
                            Some("call-1"),
                        ),
                    },
                    V2Step::Update {
                        session: None,
                        update: Box::new(v2::SessionUpdate::AgentMessageChunk(
                            v2::ContentChunk::new("working".to_owned().into(), "message"),
                        )),
                    },
                    V2Step::Update {
                        session: None,
                        update: Box::new(v2::SessionUpdate::ToolCallUpdate(
                            v2::ToolCallUpdate::new("call-1").status(v2::ToolCallStatus::Completed),
                        )),
                    },
                    V2Step::Idle { stop_reason: None },
                ]],
                ..V2Script::default()
            }),
            ..Script::default()
        },
        None,
    )
    .await;
    let permissions: Vec<_> = record
        .replies
        .iter()
        .filter(|reply| reply["method"] == "session/request_permission")
        .map(|reply| reply["result"]["outcome"].clone())
        .collect();
    assert_eq!(
        permissions,
        vec![
            json!({"outcome": "selected", "optionId": "allow"}),
            json!({"outcome": "selected", "optionId": "reject"}),
        ]
    );
    assert_eq!(
        mcp_replies(&record),
        vec![json!({"method": "mcp/message", "result": {"result": {
            "resultType": "complete",
            "content": [{
                "type": "text",
                "text": json!({
                    "name": "echo",
                    "arguments": {"text": "hi"},
                    "toolCall": "call-1",
                }).to_string(),
            }],
            "isError": false,
        }}})]
    );
    // The agent's card for the served call is held while it runs, so the
    // text the agent sent after the call started comes first.
    let order: Vec<_> = events
        .iter()
        .filter_map(|event| match event {
            AttachmentEvent::AssistantTextDelta(_) => Some("text"),
            AttachmentEvent::ToolStarted { .. } => Some("call card"),
            _ => None,
        })
        .collect();
    assert_eq!(order, vec!["text", "call card"]);
}

// Covers: the run answers only its own server and session. A request for
// another server is refused as unavailable (-33001); a call naming another
// session, or none, is refused as invalid; inside the binding, another MCP
// revision, an unknown tool and an unknown method are MCP errors.
// Owner: ACP driver (MCP-over-ACP server).
#[tokio::test]
async fn a_run_refuses_what_its_server_does_not_serve() {
    let other_server = Step::Mcp {
        envelope: json!({
            "serverId": "rho-someone-else",
            "requestId": "1",
            "method": "tools/list",
            "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28"}},
        }),
    };
    let old_revision = Step::Mcp {
        envelope: json!({
            "serverId": "$server",
            "requestId": "2",
            "method": "tools/list",
            "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2025-06-18"}},
        }),
    };
    let echo = json!({"name": "echo", "arguments": {}});
    let (record, _) = serve(
        Script {
            mcp_over_acp: true,
            turns: vec![[
                vec![
                    other_server,
                    mcp("tools/call", echo.clone(), Some("another-session"), None),
                    mcp("tools/call", echo, None, None),
                    old_revision,
                    mcp(
                        "tools/call",
                        json!({"name": "bash"}),
                        Some("$session"),
                        None,
                    ),
                    mcp("prompts/list", json!({}), None, None),
                ],
                end(),
            ]
            .concat()],
            ..Script::default()
        },
        None,
    )
    .await;

    let codes: Vec<(Option<i64>, Option<i64>)> = mcp_replies(&record)
        .iter()
        .map(|reply| {
            (
                reply["error"]["code"].as_i64(),
                reply["result"]["error"]["code"].as_i64(),
            )
        })
        .collect();
    assert_eq!(
        codes,
        vec![
            (Some(-33001), None),
            (Some(-32602), None),
            (Some(-32602), None),
            (None, Some(-32022)),
            (None, Some(-32602)),
            (None, Some(-32601)),
        ]
    );
}

// Covers: a later turn's process, resuming the agent's session, declares the
// server again, since the agent process is new; an agent that takes no MCP
// over ACP is declared the stdio bridge instead, rho relaying to the run
// with the run's token, on `session/new` and on `session/resume` alike, and
// the resumed session's agent reaches the tools through it. Kills: the
// resume declaring no server (a resumed agy session gets no tools), the
// bridge not listening by the time `session/resume` goes out.
// Owner: ACP driver (MCP server declaration).
#[tokio::test]
async fn each_setup_declares_the_server_to_an_agent_that_takes_it() {
    let (resumed, _) = serve(
        Script {
            mcp_over_acp: true,
            turns: vec![],
            resumed_turns: Some(vec![end()]),
            ..Script::default()
        },
        Some("earlier-session"),
    )
    .await;
    assert_eq!(
        declared(&resumed),
        vec![(
            "session/resume".to_owned(),
            json!([{"type": "acp", "name": "rho", "serverId": "<server>"}])
        )]
    );

    let (record, _) = serve(
        Script {
            turns: vec![end()],
            ..Script::default()
        },
        None,
    )
    .await;
    assert_eq!(
        declared(&record),
        vec![(
            "session/new".to_owned(),
            json!([{
                "name": "rho",
                "command": "<rho>",
                "args": ["__session-tools", "<endpoint>"],
                "env": [{"name": "RHO_SESSION_TOOLS_TOKEN", "value": "<token>"}],
            }])
        )]
    );

    let (resumed, _) = serve(
        Script {
            stdio_mcp: Some(StdioMcpScript {
                how: StdioMcp::Connect,
                setup: vec![stdio_request(1, "tools/list", json!({}))],
            }),
            turns: vec![],
            resumed_turns: Some(vec![end()]),
            ..Script::default()
        },
        Some("earlier-session"),
    )
    .await;
    let listed: Vec<Value> = resumed
        .replies
        .iter()
        .filter(|reply| reply["method"] == "stdio/mcp")
        .map(|reply| reply["result"]["result"]["tools"][0]["name"].clone())
        .collect();
    assert_eq!(
        (declared(&resumed), listed),
        (
            vec![(
                "session/resume".to_owned(),
                json!([{
                    "name": "rho",
                    "command": "<rho>",
                    "args": ["__session-tools", "<endpoint>"],
                    "env": [{"name": "RHO_SESSION_TOOLS_TOKEN", "value": "<token>"}],
                }])
            )],
            vec![json!("echo")],
        )
    );
}

/// The `_meta` agy 1.5.21 sends with each MCP request over stdio, in the
/// MCP revision without `initialize`.
fn agy_meta() -> Value {
    json!({
        "io.modelcontextprotocol/clientCapabilities": {"elicitation": {"form": {}, "url": {}}},
        "io.modelcontextprotocol/clientInfo": {"name": "antigravity-client", "version": "v1.0.0"},
        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
    })
}

/// An MCP request over stdio, `id`, as agy sends it.
fn stdio_request(id: u64, method: &str, mut params: Value) -> Value {
    params["_meta"] = agy_meta();
    json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})
}

/// agy's announcement of its call `id` of MCP tool `name`, as `step`.
fn agy_call(id: &str, name: &str) -> (Step, Step) {
    let fields = ToolCallUpdateFields::new()
        .name(name.to_owned())
        .kind(ToolKind::Other)
        .title(format!("Run {name}"));
    let announced = Step::Update {
        update: Box::new(SessionUpdate::ToolCall(
            ToolCall::new(id.to_owned(), format!("Run {name}"))
                .name(name.to_owned())
                .kind(ToolKind::Other)
                .status(ToolCallStatus::InProgress),
        )),
    };
    let asked = Step::Permission {
        call: Box::new(ToolCallUpdate::new(id.to_owned(), fields)),
        options: vec![
            PermissionOption::new("allow", "Allow", PermissionOptionKind::AllowOnce),
            PermissionOption::new("deny", "Deny", PermissionOptionKind::RejectOnce),
        ],
    };
    (announced, asked)
}

// Covers: an agent that takes MCP servers only over stdio (agy) reaches the
// run's tools through the bridge: its MCP client discovers rho's server in
// the revision agy speaks and lists the run's tools and `await`; its
// permission ask for a served tool, named only in the call's `name`, is
// approved although the policy rejects every ask it decides; and its MCP
// call, which names no tool call, runs keyed by the agent's announcement of
// it (whose card the served card then replaces: the renderer's served-call
// tests). Kills: the bridge not declared (no stdio replies), discovery not
// offering agy's revision, `await` left unlisted, the ask left to the
// policy (rejected), the call drawn under a key of its own (`toolCall` is a
// `rho-call-` key).
// Owner: ACP driver (stdio bridge).
#[tokio::test]
async fn a_run_serves_its_tools_over_the_stdio_bridge() {
    let (announced, asked) = agy_call("call-1", "mcp_rho_echo");
    let (record, _) = serve(
        Script {
            stdio_mcp: Some(StdioMcpScript {
                how: StdioMcp::Connect,
                setup: vec![
                    stdio_request(1, "server/discover", json!({})),
                    stdio_request(2, "tools/list", json!({})),
                ],
            }),
            turns: vec![[
                vec![
                    announced,
                    asked,
                    Step::StdioMcp {
                        message: stdio_request(
                            3,
                            "tools/call",
                            json!({"name": "echo", "arguments": {"text": "hi"}}),
                        ),
                    },
                ],
                end(),
            ]
            .concat()],
            ..Script::default()
        },
        None,
    )
    .await;

    let replies: Vec<Value> = record
        .replies
        .iter()
        .filter(|reply| reply["method"] == "stdio/mcp")
        .map(|reply| reply["result"].clone())
        .collect();
    // Each MCP result in order, `null` past the last.
    let result = |at: usize| {
        replies
            .get(at)
            .map_or(Value::Null, |reply| reply["result"].clone())
    };
    let discovered = result(0);
    let offers_agys_revision = discovered["supportedVersions"]
        .as_array()
        .is_some_and(|versions| versions.contains(&json!("2026-07-28")));
    let listed: Vec<Value> = result(1)["tools"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|tool| tool["name"].clone())
        .collect();
    let permission = record
        .replies
        .iter()
        .find(|reply| reply["method"] == "session/request_permission")
        .map(|reply| reply["result"]["outcome"].clone());
    assert_eq!(
        (
            replies.len(),
            offers_agys_revision,
            discovered["_meta"]["io.modelcontextprotocol/serverInfo"].clone(),
            listed,
            permission,
            result(2)["content"].clone(),
        ),
        (
            3,
            true,
            json!({"name": "rho", "version": env!("CARGO_PKG_VERSION")}),
            vec![json!("echo"), json!("await")],
            Some(json!({"outcome": "selected", "optionId": "allow"})),
            json!([{
                "type": "text",
                "text": json!({
                    "name": "echo",
                    "arguments": {"text": "hi"},
                    "toolCall": "call-1",
                }).to_string(),
            }]),
        ),
        "{replies:#?}"
    );
}

/// One tool, `wait`, that says when a call starts and runs until the run's
/// cancellation stops it, then says so.
struct Waits {
    started: tokio::sync::mpsc::UnboundedSender<()>,
    stopped: tokio::sync::mpsc::UnboundedSender<()>,
}

impl AgentTools for Waits {
    fn list(&self) -> Vec<Tool> {
        vec![Tool::new("wait", "Waits", Arc::new(Map::new()))]
    }

    fn call(&self, call: AgentToolCall) -> BoxFuture<'static, CallToolResult> {
        let (started, stopped) = (self.started.clone(), self.stopped.clone());
        // Work runs on a task of its own, as a host's tools do: the run may
        // drop the future it was handed.
        let work = tokio::spawn(async move {
            let _ = started.send(());
            call.cancellation.cancelled().await;
            let _ = stopped.send(());
        });
        Box::pin(async move {
            let _ = work.await;
            CallToolResult::error(vec![ContentBlock::text("cancelled")])
        })
    }
}

// Covers: a call still running when the run is cancelled stops: the run
// fires its cancellation rather than leaving the tool running.
// Owner: ACP driver (MCP-over-ACP server).
#[tokio::test]
async fn a_call_stops_when_its_run_ends() {
    let dir = tempfile::tempdir().unwrap();
    let mut request = request(dir.path(), None);
    let (started_tx, mut started) = tokio::sync::mpsc::unbounded_channel();
    let (stopped_tx, mut stopped) = tokio::sync::mpsc::unbounded_channel();
    request.overrides.agent_tools = Some(Arc::new(Waits {
        started: started_tx,
        stopped: stopped_tx,
    }));
    let cancellation = request.cancellation.clone();
    let (client, agent) = Channel::duplex();
    let (fake, _record, _signals) = ScriptedAgent::new(Script {
        mcp_over_acp: true,
        turns: vec![vec![
            mcp(
                "tools/call",
                json!({"name": "wait"}),
                Some("$session"),
                None,
            ),
            Step::Hang,
        ]],
        ..Script::default()
    });
    tokio::time::timeout(TEST_BUDGET, async {
        let cancel = async {
            started.recv().await.expect("the call started");
            cancellation.cancel();
        };
        let (client, _agent, ()) = tokio::join!(
            run_on_channel(request, TestPolicy::new(dir.path()), client),
            fake.run(agent),
            cancel
        );
        client.unwrap();
        stopped.recv().await.expect("the call stopped");
    })
    .await
    .expect("cancelled run stopped its call");
}

// Covers: each runtime's naming of rho's tools reads back the tool it
// named, and names no tool for another server's name, one whose server
// merely starts with rho's, the other runtime's separator, or a built-in
// tool. Kills: a separator check dropped or a prefix loosened (another
// server's tool read as rho's, so the agent's ask for it approved unasked).
// Owner: MCP tool naming (Claude Code `__`, agy `_`).
#[test]
fn each_naming_reads_back_only_rhos_tools() {
    let claude: McpToolNaming = crate::claude_runtime::MCP_TOOL_NAMING;
    let agy: McpToolNaming = crate::antigravity_runtime::policy::MCP_TOOL_NAMING;
    let foreign = [
        "mcp__github__search",
        "mcp_github_search",
        "mcp__rhodes__search",
        "mcp_rhodes_search",
        "Bash",
        "run_command",
    ];
    let mut read = Vec::new();
    for (naming, other) in [(claude, agy), (agy, claude)] {
        let name = naming.name_of("questionnaire");
        let named = foreign
            .iter()
            .filter(|foreign| naming.tool_of(foreign).is_some())
            .count()
            + usize::from(naming.tool_of(&other.name_of("questionnaire")).is_some());
        read.push((naming.tool_of(&name).map(str::to_owned), name, named));
    }

    assert_eq!(
        read,
        vec![
            (
                Some("questionnaire".to_owned()),
                "mcp__rho__questionnaire".to_owned(),
                0
            ),
            (
                Some("questionnaire".to_owned()),
                "mcp_rho_questionnaire".to_owned(),
                0
            ),
        ]
    );
}