phi-agent 0.18.1

phi-agent — Rust AI Agent runtime framework: orchestration, sessions, streaming built-in. You define tools, prompts, domain knowledge.
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
use std::path::Path;
use std::sync::Arc;

use agent_base::{
    AgentError, AgentResult, AgentRuntime, ChatMessage, ReasoningEffort, RunOutcome, RuntimeEvent, SafetyConfig,
    SessionId,
};

use agent_works::AgentBuilder;

use crate::agent::builder::base_agent_builder;

/// phi-agent configuration (tool-agnostic).
///
/// This config covers model and safety settings only. Tools are registered
/// externally on [`agent_works::AgentBuilder`] — phi-agent itself never bundles tools
/// beyond kernel tools (multi-agent, skills) which are opt-in via feature flags.
#[derive(Clone, Default)]
pub struct PhiAgentConfig {
    /// Model name passed to the LLM provider (e.g. `"opus"`, `"gpt-4o"`).
    pub model: String,
    /// Enable extended thinking / chain-of-thought.
    pub enable_thinking: bool,
    /// Token budget for thinking (provider-dependent). `None` means use the
    /// provider default.
    pub thinking_budget: Option<u64>,
    /// Reasoning intensity: Low / Medium / High / XHigh.
    pub thinking_effort: ReasoningEffort,
    /// Per-turn safety limits (max tool calls, max consecutive failures, etc.).
    pub safety: SafetyConfig,
    /// React-loop iteration cap for a single run (one user input).
    /// `None` means use the builder default (200 in [`base_agent_builder`]).
    pub max_turns: Option<u32>,
}

/// A built Agent instance.
///
/// Wraps [`AgentRuntime`] with common operations behind a simpler API.
///
/// ## Example
///
/// ```ignore
/// let agent = PhiAgent::build(builder, config)?;
/// let session = agent.create_session().await;
/// agent.run_turn(session, "Hello!", |event| renderer.render(event)).await?;
/// ```
#[derive(Clone)]
pub struct PhiAgent {
    runtime: AgentRuntime,
    /// The configuration this agent was built with.
    pub config: PhiAgentConfig,
    /// MCP hub for runtime server management. Only available with the `mcp` feature.
    #[cfg(feature = "mcp")]
    mcp_hub: Arc<tokio::sync::Mutex<Option<Arc<agent_works::mcp::EnhancedMcpHub>>>>,
    /// Multi-agent runtime (if multi-agent is enabled).
    #[cfg(feature = "multi-agent")]
    ma_runtime: Option<Arc<agent_works::multi_agent::MultiAgentRuntime>>,
}

impl PhiAgent {
    /// Create a pre-configured AgentBuilder.
    ///
    /// Equivalent to `base_agent_builder(llm_client).system_prompt(system_prompt)`,
    /// after which you register tools, middleware, and approval handlers,
    /// then call [`Self::build`].
    ///
    /// # Example
    ///
    /// ```ignore
    /// use phi_agent::PhiAgent;
    /// use phi_agent::build_system_prompt;
    /// use std::sync::Arc;
    ///
    /// // Create your LLM provider (e.g., via llm_unified::create_provider)
    /// let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!();
    ///
    /// let builder = PhiAgent::builder(llm_client, build_system_prompt());
    /// ```
    pub fn builder(llm_client: Arc<dyn agent_base::llm_trait::LlmProvider>, system_prompt: String) -> AgentBuilder {
        base_agent_builder(llm_client).system_prompt(system_prompt)
    }

    /// Build from an AgentBuilder.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// use std::sync::Arc;
    ///
    /// // Create your LLM provider (e.g., via llm_unified::create_provider)
    /// let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!();
    /// let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    ///
    /// let config = PhiAgentConfig {
    ///     model: "gpt-4o".into(),
    ///     enable_thinking: true,
    ///     ..Default::default()
    /// };
    /// let agent = PhiAgent::build(builder, config)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn build(builder: AgentBuilder, config: PhiAgentConfig) -> AgentResult<Self> {
        let (runtime, ma_runtime) = builder.build_with_ma()?;
        // Consumed by the struct below under the multi-agent feature; the
        // discard keeps the default-features build clippy-clean.
        #[cfg(not(feature = "multi-agent"))]
        let _ = ma_runtime;
        Ok(Self {
            runtime,
            config,
            #[cfg(feature = "mcp")]
            mcp_hub: Arc::new(tokio::sync::Mutex::new(None)),
            #[cfg(feature = "multi-agent")]
            ma_runtime,
        })
    }

    /// Get the multi-agent runtime (if multi-agent is enabled).
    ///
    /// Returns `None` if multi-agent support was not configured during build.
    #[cfg(feature = "multi-agent")]
    pub fn multi_agent_runtime(&self) -> Option<&Arc<agent_works::multi_agent::MultiAgentRuntime>> {
        self.ma_runtime.as_ref()
    }

    /// Create an agent session.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// let session = agent.create_session().await;
    /// println!("Session id: {}", session.id);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn create_session(&self) -> SessionId {
        self.runtime.create_session().await
    }

    /// Execute one turn.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use phi_agent::create_stdout_renderer;
    /// # use std::sync::Arc;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// let session = agent.create_session().await;
    /// let renderer = create_stdout_renderer();
    ///
    /// let outcome = agent
    ///     .run_turn(session, "What is 2+2?", |event| renderer.render(event))
    ///     .await?;
    /// println!("Turn completed: {:?}", outcome);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run_turn<F>(&self, session_id: SessionId, query: &str, on_event: F) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        self.runtime.run_turn(session_id, query, on_event).await
    }

    /// Like `run_turn`, but the query is pushed as an **ephemeral** user
    /// message: the LLM sees it for this turn only, then turn-end cleanup
    /// removes it from memory and persistence. Used for skill-body
    /// injection — history keeps only the original command.
    pub async fn run_turn_ephemeral_input<F>(
        &self,
        session_id: SessionId,
        query: &str,
        on_event: F,
    ) -> AgentResult<RunOutcome>
    where
        F: FnMut(RuntimeEvent) -> AgentResult<()> + Send + 'static,
    {
        self.runtime.run_turn_ephemeral_input(session_id, query, on_event).await
    }

    /// The pristine build-time system prompt (async — safe inside a runtime).
    /// Hosts that bake session state into the prompt (e.g. skill activation)
    /// capture this once and append to it, never recompose.
    pub async fn system_prompt(&self) -> Option<String> {
        self.runtime.system_prompt().await
    }

    /// Replace the session's system prompt (the first non-ephemeral System
    /// message). phimint uses this to re-bake the prompt when a session-scope
    /// skill is activated — the body joins an "Active Skills" section.
    pub async fn set_system_prompt(&self, session_id: &SessionId, prompt: impl Into<String>) -> AgentResult<()> {
        self.runtime.set_system_prompt(session_id, prompt).await
    }

    /// Cancel the currently executing turn.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use std::sync::Arc;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// let agent_clone = agent.clone();
    /// let session = agent.create_session().await;
    ///
    /// // Run the turn in a separate task
    /// let handle = tokio::spawn(async move {
    ///     agent_clone.run_turn(session, "count to 100", |_| Ok(())).await
    /// });
    ///
    /// // Cancel after a short delay
    /// tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    /// agent.cancel();
    /// # Ok(())
    /// # }
    /// ```
    pub fn cancel(&self) {
        self.runtime.cancel();
    }

    /// Check whether the agent has been cancelled.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use std::sync::Arc;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// assert!(!agent.is_cancelled());
    /// agent.cancel();
    /// assert!(agent.is_cancelled());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_cancelled(&self) -> bool {
        self.runtime.is_cancelled()
    }

    /// Set the reasoning effort.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use phi_agent::ReasoningEffort;
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use std::sync::Arc;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// // Switch to high reasoning effort mid-conversation
    /// agent.set_reasoning_effort(ReasoningEffort::High).await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_reasoning_effort(&self, effort: ReasoningEffort) {
        self.runtime.set_reasoning_effort(effort).await;
    }

    /// Access the underlying runtime (for advanced use like hook registration).
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// let runtime = agent.runtime();
    /// let event_rx = runtime.subscribe_runtime_events();
    /// println!("Subscribed to events, receiver lag: {}", event_rx.len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn runtime(&self) -> &AgentRuntime {
        &self.runtime
    }

    /// List all registered tools with their metadata, sorted by name.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use std::sync::Arc;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// let tools = agent.list_tools().await;
    /// for tool in &tools {
    ///     println!("{} - {} ({})", tool.name, tool.description, tool.origin);
    /// }
    /// println!("{} tools registered", tools.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_tools(&self) -> Vec<agent_base::ToolMetadata> {
        let tools = self.runtime.tools_mut();
        let registry = tools.read().await;
        registry.metadatas()
    }

    /// Create a new session and inject historical messages for resume.
    ///
    /// Creates a fresh session (which receives a fresh System prompt), then
    /// replaces the chat messages with `[fresh_system] + messages`.  The
    /// caller must ensure `messages` contains **no** `System` messages — use
    /// [`crate::session::load_session_messages`] which filters them out automatically.
    ///
    /// # Errors
    /// Returns an error if `messages` is empty / System-only, or if the
    /// combined sequence fails `validate_message_sequence` (e.g. dangling
    /// tool calls).  Again, [`crate::session::load_session_messages`] sanitizes all of this.
    pub async fn resume_session(&self, messages: Vec<ChatMessage>) -> AgentResult<SessionId> {
        let session_id = self.create_session().await;
        self.runtime()
            .with_session_mut(&session_id, |s| {
                // Keep the fresh system prompt that create_session wrote.
                let fresh_system = s.chat_messages().first().cloned();
                let mut merged = Vec::new();
                if let Some(sys) = fresh_system {
                    merged.push(sys);
                }
                merged.extend(messages);
                s.set_chat_messages(merged).map_err(AgentError::config_error)
            })
            .await??;
        Ok(session_id)
    }

    /// One-step session switch: resolve → load messages → resume.
    ///
    /// Given a session directory (from the picker), resolves the session context,
    /// loads historical messages, and creates a new agent session with those
    /// messages. Returns the new session ID, the loaded messages (for transcript
    /// replay), and the resolved context.
    pub async fn switch_to_session(
        &self,
        picked_session_dir: &Path,
        base_dir: &Path,
    ) -> AgentResult<(SessionId, Vec<ChatMessage>, crate::session::SessionContext)> {
        let picked_id = picked_session_dir.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
        let ctx = crate::session::resolve_session(Some(&picked_id), base_dir)?;
        let messages = crate::session::load_session_messages(&ctx.session_dir)
            .map_err(|e| AgentError::config_error(e.to_string()))?;
        let new_id = self.resume_session(messages.clone()).await?;
        Ok((new_id, messages, ctx))
    }
}

// ── MCP Runtime Management (Phase 1.2) ──

#[cfg(feature = "mcp")]
impl PhiAgent {
    /// Get or lazily initialize the MCP hub.
    async fn get_or_init_hub(&self) -> Arc<agent_works::mcp::EnhancedMcpHub> {
        let mut guard = self.mcp_hub.lock().await;
        if let Some(ref hub) = *guard {
            return hub.clone();
        }
        let hub = Arc::new(agent_works::mcp::EnhancedMcpHub::new());
        *guard = Some(hub.clone());
        hub
    }

    /// Dynamically attach an MCP server at runtime.
    ///
    /// Adds the server config, connects, discovers tools, and registers them
    /// into the agent's `ToolRegistry`. Tools are registered with the
    /// `mcp.<server_name>.<tool_name>` naming convention.
    ///
    /// Returns an error if the server cannot be connected or tools cannot be
    /// discovered. On failure, the server config is rolled back (removed from
    /// the hub) so a partial entry is never left behind.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use phi_agent::McpServerConfig;
    /// # use std::sync::Arc;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// // Attach a filesystem MCP server at runtime
    /// agent
    ///     .attach_mcp(McpServerConfig {
    ///         name: "filesystem".into(),
    ///         transport: phi_agent::McpTransport::Stdio {
    ///             command: "npx".into(),
    ///             args: vec!["-y".into(), "@modelcontextprotocol/server-filesystem".into(), "/tmp".into()],
    ///             env: Default::default(),
    ///         },
    ///     })
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Performance note
    ///
    /// Currently calls `hub.register_all()` which re-registers all servers'
    /// tools (O(total-servers)). For the common case this is fine because
    /// re-registration is a no-op HashMap insert. A future optimization would
    /// register only the newly attached server's tools.
    pub async fn attach_mcp(&self, config: agent_works::mcp::McpServerConfig) -> AgentResult<()> {
        let name = config.name.clone();
        let hub = self.get_or_init_hub().await;

        // Add server config and attempt connection
        hub.add_server(config);
        if let Err(e) = hub.connect_one(&name).await {
            hub.remove_server(&name).await;
            return Err(e);
        }

        // Discover tools; rollback on failure
        let discovered = match hub.discover_all().await {
            Ok(d) => d,
            Err(e) => {
                hub.remove_server(&name).await;
                return Err(e);
            },
        };

        // Register only the newly attached server's tools
        let tools = self.runtime.tools_mut();
        let mut registry = tools.write().await;
        hub.register_server(&mut registry, &name).await;

        let count: usize = discovered.iter().filter(|(n, _)| n == &name).map(|(_, t)| t.len()).sum();
        if count == 0 {
            tracing::warn!(
                server_name = %name,
                "attached MCP server but discovered zero tools — server may be misconfigured"
            );
        }
        tracing::info!(server_name = %name, tool_count = count, "attached MCP server at runtime");
        Ok(())
    }

    /// Dynamically detach an MCP server at runtime.
    ///
    /// Unregisters all tools belonging to this server from the agent's
    /// `ToolRegistry`, disconnects the server, and removes its config
    /// from the hub.
    ///
    /// This is a no-op if the server is not attached.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use phi_agent::McpServerConfig;
    /// # use std::sync::Arc;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// # agent.attach_mcp(McpServerConfig {
    /// #     name: "filesystem".into(),
    /// #     transport: phi_agent::McpTransport::Stdio {
    /// #         command: "npx".into(), args: vec!["-y".into(), "@modelcontextprotocol/server-filesystem".into(), "/tmp".into()],
    /// #         env: Default::default(),
    /// #     },
    /// # }).await?;
    /// // Detach the server — tools are unregistered, connection is closed
    /// agent.detach_mcp("filesystem").await;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Concurrency note
    ///
    /// There is a TOCTOU window between collecting tool names (read lock) and
    /// removing them (write lock). If another thread re-attaches a server with
    /// the same name during this window, its tools may be prematurely removed.
    /// In practice this race is harmless: the new attach will re-register tools
    /// on the next turn, and tool calls in flight will fail with a clear error
    /// since `hub.remove_server` disconnects clients.
    pub async fn detach_mcp(&self, name: &str) {
        let hub = {
            let guard = self.mcp_hub.lock().await;
            match *guard {
                Some(ref hub) => hub.clone(),
                None => return,
            }
        };

        // Collect tool names matching the mcp.<server>.<tool> prefix.
        // NOTE: the "mcp.<server>.<tool>" naming convention is defined by
        // agent_works::mcp::McpToolAdapter. If that convention changes, this
        // prefix must be updated.
        let mcp_prefix = format!("mcp.{}.", name);
        let tool_names: Vec<String> = {
            let tools = self.runtime.tools_mut();
            let registry = tools.read().await;
            registry.metadatas().iter().filter(|m| m.name.starts_with(&mcp_prefix)).map(|m| m.name.clone()).collect()
        };

        // Unregister tools from the runtime
        if !tool_names.is_empty() {
            let tools = self.runtime.tools_mut();
            let mut registry = tools.write().await;
            for tool_name in &tool_names {
                registry.remove(tool_name);
            }
        }

        // Remove the server from the hub (disconnects clients)
        hub.remove_server(name).await;

        tracing::info!(
            server_name = %name,
            tool_count = tool_names.len(),
            "detached MCP server at runtime"
        );
    }

    // ── MCP Server (Phase 4.1) ──

    /// Convert this agent into an MCP server that external orchestrators can call.
    ///
    /// # Example
    ///
    /// ```ignore
    /// # use phi_agent::{PhiAgent, PhiAgentConfig, base_agent_builder, build_system_prompt};
    /// # use phi_agent::{McpServeConfig, McpServerTransport};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let llm_client: Arc<dyn agent_base::llm_trait::LlmProvider> = todo!("create your LLM provider");
    /// # let builder = base_agent_builder(llm_client).system_prompt(build_system_prompt());
    /// # let agent = PhiAgent::build(builder, PhiAgentConfig::default())?;
    /// // Expose the agent as an MCP server via stdio
    /// let mcp_server = agent.into_mcp_server(McpServeConfig {
    ///     transport: McpServerTransport::Stdio,
    ///     name: "phi-agent".into(),
    ///     version: "1.0.0".into(),
    /// });
    /// // External orchestrators (LangGraph, CrewAI, etc.) can now call
    /// // the agent's tools through the MCP protocol
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_mcp_server(&self, config: agent_works::mcp::McpServeConfig) -> agent_works::mcp::McpServer {
        agent_works::mcp::McpServer::new(self.runtime.clone(), config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prompt::build_system_prompt;
    use async_trait::async_trait;
    use futures_core::Stream;
    use std::pin::Pin;
    use std::task::{Context, Poll};

    struct StubClient;

    /// Yields one `Text` chunk, one `Stop` chunk, then ends — a minimal valid
    /// LLM response that lets the react loop complete a turn.
    struct StopStream {
        state: u8,
    }

    impl Stream for StopStream {
        type Item = Result<agent_base::StreamChunk, agent_base::llm_trait::LlmError>;

        fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            match self.state {
                0 => {
                    self.state = 1;
                    Poll::Ready(Some(Ok(agent_base::StreamChunk::Text("hello".to_string()))))
                },
                1 => {
                    self.state = 2;
                    Poll::Ready(Some(Ok(agent_base::StreamChunk::Stop { finish_reason: Some("stop".to_string()) })))
                },
                _ => Poll::Ready(None),
            }
        }
    }

    #[async_trait]
    impl agent_base::llm_trait::LlmProvider for StubClient {
        async fn stream(
            &self,
            _request: agent_base::llm_trait::ChatRequest,
        ) -> Result<agent_base::llm_trait::ChatStream, agent_base::llm_trait::LlmError> {
            Ok(agent_base::llm_trait::ChatStream::new(Box::pin(StopStream { state: 0 })))
        }
        async fn chat(
            &self,
            _request: agent_base::llm_trait::ChatRequest,
        ) -> Result<agent_base::llm_trait::ChatResponse, agent_base::llm_trait::LlmError> {
            Ok(agent_base::llm_trait::ChatResponse {
                content: "stub".to_string(),
                reasoning_content: None,
                tool_calls: vec![],
                usage: agent_base::UsageInfo::default(),
                finish_reason: agent_base::llm_trait::response::FinishReason::Stop,
                raw: None,
                thinking_signature: None,
            })
        }
        fn capabilities(&self) -> agent_base::llm_trait::Capabilities {
            agent_base::llm_trait::Capabilities::default()
        }
        fn info(&self) -> agent_base::llm_trait::ProviderInfo {
            agent_base::llm_trait::ProviderInfo { name: "stub".to_string(), model: "stub".to_string(), version: None }
        }
    }

    fn client() -> Arc<dyn agent_base::llm_trait::LlmProvider> {
        Arc::new(StubClient)
    }

    fn build_agent() -> PhiAgent {
        let builder = PhiAgent::builder(client(), build_system_prompt());
        PhiAgent::build(builder, PhiAgentConfig::default()).unwrap()
    }

    #[test]
    fn test_phi_agent_config_default() {
        let cfg = PhiAgentConfig::default();
        assert!(cfg.model.is_empty());
        assert!(!cfg.enable_thinking);
        assert!(cfg.thinking_budget.is_none());
        assert!(cfg.max_turns.is_none());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_builder_and_build() {
        let builder = PhiAgent::builder(client(), "custom prompt".to_string());
        let agent = PhiAgent::build(builder, PhiAgentConfig::default()).unwrap();
        let _ = agent.runtime();
        assert!(agent.config.model.is_empty());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_delegate_methods() {
        let agent = build_agent();

        let session = agent.create_session().await;
        agent.set_reasoning_effort(agent_base::ReasoningEffort::High).await;

        let tools = agent.list_tools().await;
        let _ = tools;

        // A turn with the stub client's Text+Stop stream should complete.
        let outcome = agent.run_turn(session, "hi", |_| Ok(())).await;
        assert!(outcome.is_ok());

        assert!(!agent.is_cancelled());
        agent.cancel();
        assert!(agent.is_cancelled());
    }

    #[cfg(feature = "mcp")]
    #[tokio::test(flavor = "multi_thread")]
    async fn test_into_mcp_server() {
        let agent = build_agent();
        let server = agent.into_mcp_server(agent_works::mcp::McpServeConfig::default());
        let _ = server;
    }

    #[cfg(feature = "mcp")]
    #[tokio::test(flavor = "multi_thread")]
    async fn test_attach_mcp_connection_failure_rolls_back() {
        let agent = build_agent();
        // A Stdio transport with a nonexistent command fails at `McpClient::new`
        // (process spawn), which surfaces as an attach error and rolls back.
        let config = agent_works::mcp::McpServerConfig {
            name: "bogus".to_string(),
            transport: agent_works::mcp::McpTransport::Stdio {
                command: "definitely-not-a-real-command-xyz".to_string(),
                args: vec![],
            },
            auto_reconnect: false,
        };
        // Spawn failure → attach fails and rolls the server back.
        assert!(agent.attach_mcp(config).await.is_err());
    }

    #[cfg(feature = "mcp")]
    #[tokio::test(flavor = "multi_thread")]
    async fn test_detach_mcp_noop_when_not_attached() {
        let agent = build_agent();
        // No hub initialized → detach is a no-op.
        agent.detach_mcp("never-attached").await;
    }

    // ── Phase 2: resume_session tests ──

    #[tokio::test(flavor = "multi_thread")]
    async fn test_resume_session_preserves_fresh_system_prompt() {
        let agent = build_agent();

        // Simulate a conversation: User + Assistant.
        let historical = vec![
            ChatMessage::User { content: "what is 2+2?".to_string(), images: vec![], ephemeral: false },
            ChatMessage::Assistant {
                content: Some("4".to_string()),
                reasoning_content: None,
                thinking_signature: None,
                tool_calls: None,
            },
        ];

        let session_id = agent.resume_session(historical).await.unwrap();

        // The session should contain: [System(fresh), User, Assistant].
        let msgs = agent.runtime().get_messages(&session_id).await.unwrap();
        assert!(msgs.len() >= 3, "expected at least System + User + Assistant, got {}", msgs.len());

        // First message must be the fresh System prompt.
        assert!(
            matches!(&msgs[0], ChatMessage::System { content, .. } if !content.is_empty()),
            "first message must be a non-empty System prompt, got {:?}",
            msgs[0]
        );

        // The historical messages follow.
        assert!(matches!(&msgs[1], ChatMessage::User { content, .. } if content == "what is 2+2?"));
        assert!(matches!(&msgs[2], ChatMessage::Assistant { content, .. } if content.as_deref() == Some("4")));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_resume_session_rejects_empty_messages() {
        let agent = build_agent();

        // Empty messages → validate_message_sequence fails (no sendable message).
        let err = agent.resume_session(vec![]).await.unwrap_err();
        assert!(
            matches!(err, agent_base::AgentError::ConfigError(_)),
            "expected ConfigError for empty messages, got {:?}",
            err
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_resume_session_roundtrip_with_persist() {
        use crate::session::{load_session_messages, persist_window_messages};

        let agent = build_agent();

        // Persist a conversation to disk, then load and resume.
        let tmp = tempfile::TempDir::new().unwrap();
        let messages = vec![
            ChatMessage::User { content: "hello".to_string(), images: vec![], ephemeral: false },
            ChatMessage::Assistant {
                content: Some("hi!".to_string()),
                reasoning_content: Some("thinking...".to_string()),
                thinking_signature: Some("sig".to_string()),
                tool_calls: None,
            },
        ];
        persist_window_messages(tmp.path(), &messages).unwrap();

        let loaded = load_session_messages(tmp.path()).unwrap();
        let session_id = agent.resume_session(loaded).await.unwrap();

        let msgs = agent.runtime().get_messages(&session_id).await.unwrap();
        // System + User + Assistant
        assert!(msgs.len() >= 3);

        // System is fresh (not the persisted one — there was none).
        assert!(matches!(&msgs[0], ChatMessage::System { .. }));

        // Assistant reasoning_content was stripped during load.
        if let ChatMessage::Assistant { reasoning_content, thinking_signature, .. } = &msgs[2] {
            assert!(reasoning_content.is_none());
            assert!(thinking_signature.is_none());
        } else {
            panic!("expected Assistant at index 2");
        }
    }
}