zeph-core 0.18.0

Core agent loop, configuration, context builder, metrics, and vault for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use super::{Agent, Channel, LlmProvider};

impl<C: Channel> Agent<C> {
    pub(super) async fn handle_mcp_command(
        &mut self,
        args: &str,
    ) -> Result<(), super::error::AgentError> {
        let parts: Vec<&str> = args.split_whitespace().collect();
        match parts.first().copied() {
            Some("add") => self.handle_mcp_add(&parts[1..]).await,
            Some("list") => self.handle_mcp_list().await,
            Some("tools") => self.handle_mcp_tools(parts.get(1).copied()).await,
            Some("remove") => self.handle_mcp_remove(parts.get(1).copied()).await,
            _ => {
                self.channel
                    .send("Usage: /mcp add|list|tools|remove")
                    .await?;
                Ok(())
            }
        }
    }

    #[allow(clippy::too_many_lines)]
    async fn handle_mcp_add(&mut self, args: &[&str]) -> Result<(), super::error::AgentError> {
        if args.len() < 2 {
            self.channel
                .send("Usage: /mcp add <id> <command> [args...] | /mcp add <id> <url>")
                .await?;
            return Ok(());
        }

        let Some(ref manager) = self.mcp.manager else {
            self.channel.send("MCP is not enabled.").await?;
            return Ok(());
        };

        let target = args[1];
        let is_url = target.starts_with("http://") || target.starts_with("https://");

        // SEC-MCP-01: validate command against allowlist (stdio only)
        if !is_url
            && !self.mcp.allowed_commands.is_empty()
            && !self.mcp.allowed_commands.iter().any(|c| c == target)
        {
            self.channel
                .send(&format!(
                    "Command '{target}' is not allowed. Permitted: {}",
                    self.mcp.allowed_commands.join(", ")
                ))
                .await?;
            return Ok(());
        }

        // SEC-MCP-03: enforce server limit
        let current_count = manager.list_servers().await.len();
        if current_count >= self.mcp.max_dynamic {
            self.channel
                .send(&format!(
                    "Server limit reached ({}/{}).",
                    current_count, self.mcp.max_dynamic
                ))
                .await?;
            return Ok(());
        }

        let transport = if is_url {
            zeph_mcp::McpTransport::Http {
                url: target.to_owned(),
                headers: std::collections::HashMap::new(),
            }
        } else {
            zeph_mcp::McpTransport::Stdio {
                command: target.to_owned(),
                args: args[2..].iter().map(|&s| s.to_owned()).collect(),
                env: std::collections::HashMap::new(),
            }
        };

        let entry = zeph_mcp::ServerEntry {
            id: args[0].to_owned(),
            transport,
            timeout: std::time::Duration::from_secs(30),
            trust_level: zeph_mcp::McpTrustLevel::Untrusted,
            tool_allowlist: Vec::new(),
            expected_tools: Vec::new(),
        };

        let _ = self.channel.send_status("connecting to mcp...").await;
        match manager.add_server(&entry).await {
            Ok(tools) => {
                let _ = self.channel.send_status("").await;
                let count = tools.len();
                self.mcp
                    .server_outcomes
                    .push(zeph_mcp::ServerConnectOutcome {
                        id: entry.id.clone(),
                        connected: true,
                        tool_count: count,
                        error: String::new(),
                    });
                self.mcp.tools.extend(tools);
                self.sync_mcp_executor_tools();
                self.mcp.pruning_cache.reset();
                self.rebuild_semantic_index().await;
                self.sync_mcp_registry().await;
                let mcp_total = self.mcp.tools.len();
                let mcp_server_count = self.mcp.server_outcomes.len();
                let mcp_connected_count = self
                    .mcp
                    .server_outcomes
                    .iter()
                    .filter(|o| o.connected)
                    .count();
                let mcp_servers: Vec<crate::metrics::McpServerStatus> = self
                    .mcp
                    .server_outcomes
                    .iter()
                    .map(|o| crate::metrics::McpServerStatus {
                        id: o.id.clone(),
                        status: if o.connected {
                            crate::metrics::McpServerConnectionStatus::Connected
                        } else {
                            crate::metrics::McpServerConnectionStatus::Failed
                        },
                        tool_count: o.tool_count,
                        error: o.error.clone(),
                    })
                    .collect();
                self.update_metrics(|m| {
                    m.mcp_tool_count = mcp_total;
                    m.mcp_server_count = mcp_server_count;
                    m.mcp_connected_count = mcp_connected_count;
                    m.mcp_servers = mcp_servers;
                });
                self.channel
                    .send(&format!(
                        "Connected MCP server '{}' ({count} tool(s))",
                        entry.id
                    ))
                    .await?;
                Ok(())
            }
            Err(e) => {
                let _ = self.channel.send_status("").await;
                tracing::warn!(server_id = entry.id, "MCP add failed: {e:#}");
                self.channel
                    .send(&format!("Failed to connect server '{}': {e}", entry.id))
                    .await?;
                Ok(())
            }
        }
    }

    async fn handle_mcp_list(&mut self) -> Result<(), super::error::AgentError> {
        use std::fmt::Write;

        let Some(ref manager) = self.mcp.manager else {
            self.channel.send("MCP is not enabled.").await?;
            return Ok(());
        };

        let server_ids = manager.list_servers().await;
        if server_ids.is_empty() {
            self.channel.send("No MCP servers connected.").await?;
            return Ok(());
        }

        let mut output = String::from("Connected MCP servers:\n");
        let mut total = 0usize;
        for id in &server_ids {
            let count = self.mcp.tools.iter().filter(|t| t.server_id == *id).count();
            total += count;
            let _ = writeln!(output, "- {id} ({count} tools)");
        }
        let _ = write!(output, "Total: {total} tool(s)");

        self.channel.send(&output).await?;
        Ok(())
    }

    async fn handle_mcp_tools(
        &mut self,
        server_id: Option<&str>,
    ) -> Result<(), super::error::AgentError> {
        use std::fmt::Write;

        let Some(server_id) = server_id else {
            self.channel.send("Usage: /mcp tools <server_id>").await?;
            return Ok(());
        };

        let tools: Vec<_> = self
            .mcp
            .tools
            .iter()
            .filter(|t| t.server_id == server_id)
            .collect();

        if tools.is_empty() {
            self.channel
                .send(&format!("No tools found for server '{server_id}'."))
                .await?;
            return Ok(());
        }

        let mut output = format!("Tools for '{server_id}' ({} total):\n", tools.len());
        for t in &tools {
            if t.description.is_empty() {
                let _ = writeln!(output, "- {}", t.name);
            } else {
                let _ = writeln!(output, "- {} — {}", t.name, t.description);
            }
        }
        self.channel.send(&output).await?;
        Ok(())
    }

    async fn handle_mcp_remove(
        &mut self,
        server_id: Option<&str>,
    ) -> Result<(), super::error::AgentError> {
        let Some(server_id) = server_id else {
            self.channel.send("Usage: /mcp remove <id>").await?;
            return Ok(());
        };

        let Some(ref manager) = self.mcp.manager else {
            self.channel.send("MCP is not enabled.").await?;
            return Ok(());
        };

        match manager.remove_server(server_id).await {
            Ok(()) => {
                let before = self.mcp.tools.len();
                self.mcp.tools.retain(|t| t.server_id != server_id);
                let removed = before - self.mcp.tools.len();
                self.mcp.server_outcomes.retain(|o| o.id != server_id);
                self.sync_mcp_executor_tools();
                self.mcp.pruning_cache.reset();
                self.rebuild_semantic_index().await;
                self.sync_mcp_registry().await;
                let mcp_total = self.mcp.tools.len();
                let mcp_server_count = self.mcp.server_outcomes.len();
                let mcp_connected_count = self
                    .mcp
                    .server_outcomes
                    .iter()
                    .filter(|o| o.connected)
                    .count();
                let mcp_servers: Vec<crate::metrics::McpServerStatus> = self
                    .mcp
                    .server_outcomes
                    .iter()
                    .map(|o| crate::metrics::McpServerStatus {
                        id: o.id.clone(),
                        status: if o.connected {
                            crate::metrics::McpServerConnectionStatus::Connected
                        } else {
                            crate::metrics::McpServerConnectionStatus::Failed
                        },
                        tool_count: o.tool_count,
                        error: o.error.clone(),
                    })
                    .collect();
                self.update_metrics(|m| {
                    m.mcp_tool_count = mcp_total;
                    m.mcp_server_count = mcp_server_count;
                    m.mcp_connected_count = mcp_connected_count;
                    m.mcp_servers = mcp_servers;
                    m.active_mcp_tools
                        .retain(|name| !name.starts_with(&format!("{server_id}:")));
                });
                self.channel
                    .send(&format!(
                        "Disconnected MCP server '{server_id}' (removed {removed} tools)"
                    ))
                    .await?;
                Ok(())
            }
            Err(e) => {
                tracing::warn!(server_id, "MCP remove failed: {e:#}");
                self.channel
                    .send(&format!("Failed to remove server '{server_id}': {e}"))
                    .await?;
                Ok(())
            }
        }
    }

    pub(super) async fn append_mcp_prompt(&mut self, query: &str, system_prompt: &mut String) {
        let matched_tools = self.match_mcp_tools(query).await;
        let active_mcp: Vec<String> = matched_tools
            .iter()
            .map(zeph_mcp::McpTool::qualified_name)
            .collect();
        let mcp_total = self.mcp.tools.len();
        let (mcp_server_count, mcp_connected_count) = if self.mcp.server_outcomes.is_empty() {
            let connected = self
                .mcp
                .tools
                .iter()
                .map(|t| &t.server_id)
                .collect::<std::collections::HashSet<_>>()
                .len();
            (connected, connected)
        } else {
            let total = self.mcp.server_outcomes.len();
            let connected = self
                .mcp
                .server_outcomes
                .iter()
                .filter(|o| o.connected)
                .count();
            (total, connected)
        };
        self.update_metrics(|m| {
            m.active_mcp_tools = active_mcp;
            m.mcp_tool_count = mcp_total;
            m.mcp_server_count = mcp_server_count;
            m.mcp_connected_count = mcp_connected_count;
        });
        // When native tool_use is active, MCP tools flow through the executor chain
        // as ToolDefinitions — skip text prompt injection to avoid duplication.
        if self.provider.supports_tool_use() {
            return;
        }
        if !matched_tools.is_empty() {
            let tool_names: Vec<&str> = matched_tools.iter().map(|t| t.name.as_str()).collect();
            tracing::debug!(
                skills = ?self.skill_state.active_skill_names,
                mcp_tools = ?tool_names,
                "matched items"
            );
            let tools_prompt = zeph_mcp::format_mcp_tools_prompt(&matched_tools);
            if !tools_prompt.is_empty() {
                system_prompt.push_str("\n\n");
                system_prompt.push_str(&tools_prompt);
            }
        }
    }

    async fn match_mcp_tools(&self, query: &str) -> Vec<zeph_mcp::McpTool> {
        let Some(ref registry) = self.mcp.registry else {
            return self.mcp.tools.clone();
        };
        let provider = self.embedding_provider.clone();
        registry
            .search(query, self.skill_state.max_active_skills, |text| {
                let owned = text.to_owned();
                let p = provider.clone();
                Box::pin(async move { p.embed(&owned).await })
            })
            .await
    }

    #[cfg(test)]
    pub(crate) fn mcp_tool_count(&self) -> usize {
        self.mcp.tools.len()
    }

    /// Poll the watch receiver for tool list updates from `tools/list_changed` notifications.
    ///
    /// Called once per agent turn, before processing user input. When the tool list has changed,
    /// updates `mcp.tools`, syncs the executor, and schedules a registry sync.
    /// If no receiver is set (MCP disabled), or no change has occurred, this is a no-op.
    pub(super) async fn check_tool_refresh(&mut self) {
        let Some(ref mut rx) = self.mcp.tool_rx else {
            return;
        };
        if !rx.has_changed().unwrap_or(false) {
            return;
        }
        let new_tools = rx.borrow_and_update().clone();
        if new_tools.is_empty() {
            // Guard against replacing a non-empty initial tool list with the watch's empty
            // initial value. The watch is only updated after a real tools/list_changed event.
            return;
        }
        tracing::info!(
            tools = new_tools.len(),
            "tools/list_changed: agent tool list refreshed"
        );
        self.mcp.tools = new_tools;
        self.sync_mcp_executor_tools();
        self.mcp.pruning_cache.reset();
        self.rebuild_semantic_index().await;
        self.sync_mcp_registry().await;
        let mcp_total = self.mcp.tools.len();
        let mcp_servers = self
            .mcp
            .tools
            .iter()
            .map(|t| &t.server_id)
            .collect::<std::collections::HashSet<_>>()
            .len();
        self.update_metrics(|m| {
            m.mcp_tool_count = mcp_total;
            m.mcp_server_count = mcp_servers;
        });
    }

    /// Write the **full** `self.mcp.tools` set to the shared executor `RwLock`.
    ///
    /// This is the first of two writers to `mcp.shared_tools`.  Within a turn
    /// this method must run **before** `apply_pruned_mcp_tools`, which writes the
    /// pruned subset.  The normal call order guarantees this: tool-list change
    /// events (notify, `/mcp add`, `/mcp remove`) call this method, and pruning
    /// runs later inside `rebuild_system_prompt`.
    /// See also: `McpState::shared_tools` doc comment.
    pub(super) fn sync_mcp_executor_tools(&self) {
        if let Some(ref shared) = self.mcp.shared_tools {
            let mut guard = shared
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            guard.clone_from(&self.mcp.tools);
        }
    }

    /// Write the **pruned** tool subset to the shared executor `RwLock`.
    ///
    /// This is the second of two writers to `mcp.shared_tools`.  Must only be
    /// called **after** `sync_mcp_executor_tools` has established the full tool
    /// set for the current turn (guaranteed by call-site ordering: pruning runs
    /// inside `rebuild_system_prompt`, after any tool-list change events).
    ///
    /// `self.mcp.tools` (the full set) is intentionally **not** modified: it is
    /// retained for cache key computation and for restoration when the next turn
    /// triggers a cache reset.
    ///
    /// This method must **NOT** call `sync_mcp_executor_tools` internally —
    /// doing so would overwrite the pruned subset with the full set.
    /// See also: `McpState::shared_tools` doc comment.
    pub(in crate::agent) fn apply_pruned_mcp_tools(&self, pruned: Vec<zeph_mcp::McpTool>) {
        debug_assert!(
            pruned.iter().all(|p| self
                .mcp
                .tools
                .iter()
                .any(|t| t.server_id == p.server_id && t.name == p.name)),
            "pruned set must be a subset of self.mcp.tools"
        );
        if let Some(ref shared) = self.mcp.shared_tools {
            let mut guard = shared
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *guard = pruned;
        }
    }

    pub(super) async fn sync_mcp_registry(&mut self) {
        let Some(ref mut registry) = self.mcp.registry else {
            return;
        };
        if !self.embedding_provider.supports_embeddings() {
            return;
        }
        let provider = self.embedding_provider.clone();
        let embed_fn = |text: &str| -> zeph_mcp::registry::EmbedFuture {
            let owned = text.to_owned();
            let p = provider.clone();
            Box::pin(async move { p.embed(&owned).await })
        };
        if let Err(e) = registry
            .sync(&self.mcp.tools, &self.skill_state.embedding_model, embed_fn)
            .await
        {
            tracing::warn!("failed to sync MCP tool registry: {e:#}");
        }
    }

    /// Build (or rebuild) the in-memory semantic tool index for embedding-based discovery.
    /// Build the initial semantic tool index after agent construction.
    ///
    /// Must be called once after `with_mcp` and `with_mcp_discovery` are applied,
    /// before the first user turn.  Subsequent rebuilds happen automatically on
    /// tool list change events (`check_tool_refresh`, `/mcp add`, `/mcp remove`).
    pub async fn init_semantic_index(&mut self) {
        self.rebuild_semantic_index().await;
    }

    /// Rebuild the in-memory semantic tool index.
    ///
    /// Only runs when `discovery_strategy == Embedding`.  On failure (all embeddings fail),
    /// sets `semantic_index = None` and logs at WARN — the caller falls back to all tools.
    ///
    /// Called at:
    /// - initial setup via `init_semantic_index()`
    /// - `tools/list_changed` notification
    /// - `/mcp add` and `/mcp remove`
    pub(in crate::agent) async fn rebuild_semantic_index(&mut self) {
        if self.mcp.discovery_strategy != zeph_mcp::ToolDiscoveryStrategy::Embedding {
            return;
        }

        if self.mcp.tools.is_empty() {
            self.mcp.semantic_index = None;
            return;
        }

        // Resolve embedding provider: dedicated discovery provider → primary embedding provider.
        let provider = self
            .mcp
            .discovery_provider
            .clone()
            .unwrap_or_else(|| self.embedding_provider.clone());

        let embed_fn = provider.embed_fn();

        match zeph_mcp::SemanticToolIndex::build(&self.mcp.tools, &embed_fn).await {
            Ok(idx) => {
                tracing::info!(
                    indexed = idx.len(),
                    total = self.mcp.tools.len(),
                    "semantic tool index built"
                );
                self.mcp.semantic_index = Some(idx);
            }
            Err(e) => {
                tracing::warn!(
                    "semantic tool index build failed, falling back to all tools: {e:#}"
                );
                self.mcp.semantic_index = None;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::agent_tests::{
        MockChannel, MockToolExecutor, create_test_registry, mock_provider,
    };
    use super::*;

    #[tokio::test]
    async fn handle_mcp_command_unknown_subcommand_shows_usage() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        agent.handle_mcp_command("unknown").await.unwrap();

        let sent = agent.channel.sent_messages();
        assert!(
            sent.iter().any(|s| s.contains("Usage: /mcp")),
            "expected usage message, got: {sent:?}"
        );
    }

    #[tokio::test]
    async fn handle_mcp_list_no_manager_shows_disabled() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        agent.handle_mcp_command("list").await.unwrap();

        let sent = agent.channel.sent_messages();
        assert!(
            sent.iter().any(|s| s.contains("MCP is not enabled")),
            "expected not-enabled message, got: {sent:?}"
        );
    }

    #[tokio::test]
    async fn handle_mcp_tools_no_server_id_shows_usage() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        agent.handle_mcp_command("tools").await.unwrap();

        let sent = agent.channel.sent_messages();
        assert!(
            sent.iter().any(|s| s.contains("Usage: /mcp tools")),
            "expected tools usage message, got: {sent:?}"
        );
    }

    #[tokio::test]
    async fn handle_mcp_remove_no_server_id_shows_usage() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        agent.handle_mcp_command("remove").await.unwrap();

        let sent = agent.channel.sent_messages();
        assert!(
            sent.iter().any(|s| s.contains("Usage: /mcp remove")),
            "expected remove usage message, got: {sent:?}"
        );
    }

    #[tokio::test]
    async fn handle_mcp_remove_no_manager_shows_disabled() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        // "remove server-id" but no manager
        agent.handle_mcp_command("remove my-server").await.unwrap();

        let sent = agent.channel.sent_messages();
        assert!(
            sent.iter().any(|s| s.contains("MCP is not enabled")),
            "expected not-enabled message, got: {sent:?}"
        );
    }

    #[tokio::test]
    async fn handle_mcp_add_insufficient_args_shows_usage() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        // "add" with only 1 arg (needs at least 2)
        agent.handle_mcp_command("add server-id").await.unwrap();

        let sent = agent.channel.sent_messages();
        assert!(
            sent.iter().any(|s| s.contains("Usage: /mcp add")),
            "expected add usage message, got: {sent:?}"
        );
    }

    #[tokio::test]
    async fn handle_mcp_tools_with_unknown_server_shows_no_tools() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        // mcp.tools is empty, so any server will have no tools
        agent
            .handle_mcp_command("tools nonexistent-server")
            .await
            .unwrap();

        let sent = agent.channel.sent_messages();
        assert!(
            sent.iter().any(|s| s.contains("No tools found")),
            "expected no-tools message, got: {sent:?}"
        );
    }

    #[tokio::test]
    async fn mcp_tool_count_starts_at_zero() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let agent = Agent::new(provider, channel, registry, None, 5, executor);

        assert_eq!(agent.mcp_tool_count(), 0);
    }

    #[tokio::test]
    async fn check_tool_refresh_no_rx_is_noop() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
        // No tool_rx set; check_tool_refresh should be a no-op.
        agent.check_tool_refresh().await;
        assert_eq!(agent.mcp_tool_count(), 0);
    }

    #[tokio::test]
    async fn check_tool_refresh_no_change_is_noop() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        let (tx, rx) = tokio::sync::watch::channel(Vec::new());
        agent.mcp.tool_rx = Some(rx);
        // No changes sent; has_changed() returns false.
        agent.check_tool_refresh().await;
        assert_eq!(agent.mcp_tool_count(), 0);
        drop(tx);
    }

    #[tokio::test]
    async fn check_tool_refresh_with_empty_initial_value_does_not_replace_tools() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);
        agent.mcp.tools = vec![zeph_mcp::McpTool {
            server_id: "srv".into(),
            name: "existing_tool".into(),
            description: String::new(),
            input_schema: serde_json::json!({}),
        }];

        let (_tx, rx) = tokio::sync::watch::channel(Vec::<zeph_mcp::McpTool>::new());
        agent.mcp.tool_rx = Some(rx);
        // has_changed() is false for a fresh receiver; tools unchanged.
        agent.check_tool_refresh().await;
        assert_eq!(agent.mcp_tool_count(), 1);
    }

    #[tokio::test]
    async fn check_tool_refresh_applies_update() {
        let provider = mock_provider(vec![]);
        let channel = MockChannel::new(vec![]);
        let registry = create_test_registry();
        let executor = MockToolExecutor::no_tools();
        let mut agent = Agent::new(provider, channel, registry, None, 5, executor);

        let (tx, rx) = tokio::sync::watch::channel(Vec::<zeph_mcp::McpTool>::new());
        agent.mcp.tool_rx = Some(rx);

        let new_tools = vec![zeph_mcp::McpTool {
            server_id: "srv".into(),
            name: "refreshed_tool".into(),
            description: String::new(),
            input_schema: serde_json::json!({}),
        }];
        tx.send(new_tools).unwrap();

        agent.check_tool_refresh().await;
        assert_eq!(agent.mcp_tool_count(), 1);
        assert_eq!(agent.mcp.tools[0].name, "refreshed_tool");
    }
}