1use std::collections::VecDeque;
14use std::fmt;
15use std::future::Future;
16use std::path::PathBuf;
17use std::pin::Pin;
18use std::process::Stdio;
19use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering};
20use std::sync::{Arc, OnceLock, RwLock};
21use std::time::Duration;
22
23use dashmap::DashMap;
24use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
25use tokio::process::Command;
26use tokio::sync::{mpsc, oneshot, watch, Mutex};
27use tokio::task::JoinHandle;
28use tracing::Instrument;
29
30use crate::hooks::HookRegistry;
31use crate::mcp::{server_map, SdkMcpServer};
32use crate::protocol::{
33 Autocompact, CanUseToolRequest, ControlRequest, ControlRequestBody, ControlResponse, Effort,
34 ElicitationRequest, ElicitationResponse, InboundControlResponseBody, InboundMessage, Initialize,
35 OutboundControlRequest, PermissionMode, PermissionPrompts, ResultMessage, Thinking, ThinkingDisplay,
36 ToolDecision,
37 UserDialogRequest, UserDialogResponse,
38};
39
40#[derive(Debug, thiserror::Error)]
43pub enum SessionError {
44 #[error("io: {0}")]
45 Io(#[from] std::io::Error),
46 #[error("json: {0}")]
47 Json(#[from] serde_json::Error),
48 #[error("process exited (code: {code:?}); stderr tail:\n{stderr}")]
49 ProcessExited { code: Option<i32>, stderr: String },
50 #[error("session closed")]
51 Closed,
52 #[error("control request `{subtype}` failed: {error}")]
53 ControlError { subtype: String, error: String },
54 #[error("control request `{0}` timed out")]
55 ControlTimeout(String),
56 #[error("code mode: {0}")]
57 CodeMode(#[from] crate::code_mode::CodeModeError),
58 #[error("Claude Code {found} is older than {min}, the oldest version this SDK supports; run `claude update`")]
59 UnsupportedCliVersion { found: String, min: &'static str },
60}
61
62pub type Result<T> = std::result::Result<T, SessionError>;
63
64const STATE_RUNNING: u8 = 0;
65const STATE_CLOSING: u8 = 1;
66const STATE_DEAD: u8 = 2;
67
68const STDERR_TAIL_LINES: usize = 40;
69const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(60);
70pub const DEFAULT_CONTROL_TIMEOUT: Duration = Duration::from_secs(60);
72pub const MIN_CLI_VERSION: &str = "2.1.329";
74const CLOSE_GRACE: Duration = Duration::from_secs(5);
76
77type PermFuture = Pin<Box<dyn Future<Output = ToolDecision> + Send + 'static>>;
80
81#[derive(Clone)]
84pub struct CanUseTool(Arc<dyn Fn(CanUseToolRequest) -> PermFuture + Send + Sync>);
85
86impl CanUseTool {
87 pub fn new<F, Fut>(f: F) -> Self
88 where
89 F: Fn(CanUseToolRequest) -> Fut + Send + Sync + 'static,
90 Fut: Future<Output = ToolDecision> + Send + 'static,
91 {
92 Self(Arc::new(move |req| Box::pin(f(req))))
93 }
94}
95
96type ElicitFuture = Pin<Box<dyn Future<Output = ElicitationResponse> + Send + 'static>>;
97
98#[derive(Clone)]
101pub struct OnElicitation(Arc<dyn Fn(ElicitationRequest) -> ElicitFuture + Send + Sync>);
102
103impl OnElicitation {
104 pub fn new<F, Fut>(f: F) -> Self
105 where
106 F: Fn(ElicitationRequest) -> Fut + Send + Sync + 'static,
107 Fut: Future<Output = ElicitationResponse> + Send + 'static,
108 {
109 Self(Arc::new(move |req| Box::pin(f(req))))
110 }
111}
112
113type DialogFuture = Pin<Box<dyn Future<Output = UserDialogResponse> + Send + 'static>>;
114
115#[derive(Clone)]
120pub struct OnUserDialog(Arc<dyn Fn(UserDialogRequest) -> DialogFuture + Send + Sync>);
121
122impl OnUserDialog {
123 pub fn new<F, Fut>(f: F) -> Self
124 where
125 F: Fn(UserDialogRequest) -> Fut + Send + Sync + 'static,
126 Fut: Future<Output = UserDialogResponse> + Send + 'static,
127 {
128 Self(Arc::new(move |req| Box::pin(f(req))))
129 }
130}
131
132#[derive(Clone)]
134pub struct OnStderr(Arc<dyn Fn(&str) + Send + Sync>);
135
136impl OnStderr {
137 pub fn new(f: impl Fn(&str) + Send + Sync + 'static) -> Self {
138 Self(Arc::new(f))
139 }
140}
141
142#[derive(Debug, Clone, Default)]
144pub struct McpCall {
145 pub timeout: Option<Duration>,
147 pub result_not_for_model: bool,
150 pub check_permissions: bool,
153}
154
155#[derive(Debug, Clone, Default)]
157pub struct ReloadPlugins {
158 pub add_plugins: Vec<serde_json::Value>,
160 pub hold_on_cache_impact: bool,
163 pub refuse_if_busy: bool,
165}
166
167macro_rules! opaque_debug {
168 ($($t:ident),*) => {$(
169 impl fmt::Debug for $t {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 f.write_str(concat!(stringify!($t), "(..)"))
172 }
173 }
174 )*};
175}
176opaque_debug!(CanUseTool, OnElicitation, OnUserDialog, OnStderr);
177
178#[derive(Debug, Clone)]
179pub struct SessionOptions {
180 pub binary: PathBuf,
181 pub cwd: Option<PathBuf>,
183 pub model: Option<String>,
185 pub effort: Option<Effort>,
187 pub permission_mode: Option<PermissionMode>,
189 pub fallback_model: Option<String>,
192 pub thinking: Option<Thinking>,
194 pub thinking_display: Option<ThinkingDisplay>,
196 pub max_thinking_tokens: Option<u32>,
198 pub max_turns: Option<u32>,
201 pub max_budget_usd: Option<f64>,
204 pub task_budget: Option<u32>,
206 pub resume: Option<String>,
208 pub resume_session_at: Option<String>,
211 pub continue_conversation: bool,
213 pub fork_session: bool,
216 pub session_id: Option<String>,
218 pub persist_session: bool,
221 pub name: Option<String>,
223 pub code_mode: bool,
228 pub tool_search: bool,
231 pub include_partial: bool,
233 pub hooks: HookRegistry,
235 pub can_use_tool: Option<CanUseTool>,
238 pub mcp_servers: Vec<SdkMcpServer>,
241 pub allowed_tools: Vec<String>,
243 pub disallowed_tools: Vec<String>,
245 pub tools: Option<Vec<String>>,
248 pub add_dirs: Vec<PathBuf>,
250 pub strict_mcp_config: bool,
252 pub agent: Option<String>,
254 pub append_subagent_system_prompt: Option<String>,
257 pub plugin_dirs: Vec<PathBuf>,
259 pub betas: Vec<String>,
261 pub debug_file: Option<PathBuf>,
263 pub plugin_urls: Vec<String>,
265 pub files: Vec<String>,
267 pub autocompact: Option<Autocompact>,
269 pub permission_prompts: Option<PermissionPrompts>,
271 pub worktree: Option<Option<String>>,
274 pub bare: bool,
276 pub safe_mode: bool,
279 pub restricted: bool,
282 pub disable_slash_commands: bool,
284 pub brief: bool,
286 pub include_hook_events: bool,
289 pub extra_args: Vec<String>,
292 pub control_timeout: Duration,
294 pub on_elicitation: Option<OnElicitation>,
296 pub on_user_dialog: Option<OnUserDialog>,
298 pub on_stderr: Option<OnStderr>,
301 pub setting_sources: Option<Vec<String>>,
307 pub settings: Option<serde_json::Value>,
311 pub record: Option<PathBuf>,
313 pub clear_env: bool,
317 pub env: Vec<(String, String)>,
319}
320
321impl Default for SessionOptions {
322 fn default() -> Self {
323 Self {
324 binary: PathBuf::from("claude"),
325 cwd: None,
326 model: None,
327 effort: None,
328 permission_mode: None,
329 fallback_model: None,
330 thinking: None,
331 thinking_display: None,
332 max_thinking_tokens: None,
333 max_turns: None,
334 max_budget_usd: None,
335 task_budget: None,
336 resume: None,
337 resume_session_at: None,
338 continue_conversation: false,
339 fork_session: false,
340 session_id: None,
341 persist_session: true,
342 name: None,
343 code_mode: false,
344 tool_search: false,
345 include_partial: false,
346 hooks: HookRegistry::new(),
347 can_use_tool: None,
348 mcp_servers: vec![],
349 allowed_tools: vec![],
350 disallowed_tools: vec![],
351 tools: None,
352 add_dirs: vec![],
353 strict_mcp_config: false,
354 agent: None,
355 append_subagent_system_prompt: None,
356 plugin_dirs: vec![],
357 betas: vec![],
358 debug_file: None,
359 plugin_urls: vec![],
360 files: vec![],
361 autocompact: None,
362 permission_prompts: None,
363 worktree: None,
364 bare: false,
365 safe_mode: false,
366 restricted: false,
367 disable_slash_commands: false,
368 brief: false,
369 include_hook_events: false,
370 extra_args: vec![],
371 control_timeout: DEFAULT_CONTROL_TIMEOUT,
372 on_elicitation: None,
373 on_user_dialog: None,
374 on_stderr: None,
375 setting_sources: None,
376 settings: None,
377 record: None,
378 clear_env: false,
379 env: vec![],
380 }
381 }
382}
383
384pub type EventRx = mpsc::UnboundedReceiver<Arc<InboundMessage>>;
389
390#[derive(Default)]
393struct Fanout {
394 subs: Vec<mpsc::UnboundedSender<Arc<InboundMessage>>>,
395 ended: bool,
396}
397
398fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
399 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
400}
401
402type Pending = DashMap<String, oneshot::Sender<InboundControlResponseBody>>;
403
404#[derive(Debug, Clone)]
406pub(crate) struct ExitInfo {
407 pub(crate) code: Option<i32>,
408 pub(crate) stderr: String,
409}
410
411pub(crate) struct Transport {
413 pub(crate) stdin: Box<dyn AsyncWrite + Unpin + Send>,
414 pub(crate) stdout: Box<dyn AsyncRead + Unpin + Send>,
415 pub(crate) exit: Pin<Box<dyn Future<Output = ExitInfo> + Send>>,
417 pub(crate) pgid: Option<i32>,
420}
421
422#[derive(Clone)]
424pub struct Session(Arc<SessionInner>);
425
426struct SessionInner {
427 session_id: Arc<RwLock<Option<String>>>,
430 stdin_tx: Mutex<Option<mpsc::Sender<Vec<u8>>>>,
433 fanout: Arc<std::sync::Mutex<Fanout>>,
434 pending: Arc<Pending>,
436 next_request_id: AtomicU64,
437 state: Arc<AtomicU8>,
438 exit: watch::Receiver<Option<ExitInfo>>,
439 pgid: Option<i32>,
440 include_partial: bool,
441 initialize_response: OnceLock<serde_json::Value>,
442 cli_version: OnceLock<String>,
443 control_timeout: Duration,
444 responder: Arc<Responder>,
445 turns_in_flight: Arc<AtomicUsize>,
447 reader_done: watch::Receiver<bool>,
449 _tasks: [JoinHandle<()>; 3],
450}
451
452struct Responder {
454 stdin_tx: mpsc::WeakSender<Vec<u8>>,
457 hooks: HookRegistry,
458 can_use_tool: Option<CanUseTool>,
459 on_elicitation: Option<OnElicitation>,
460 on_user_dialog: Option<OnUserDialog>,
461 mcp_servers: Vec<SdkMcpServer>,
463 dynamic_mcp_servers: RwLock<Vec<SdkMcpServer>>,
465 in_flight: DashMap<String, tokio::task::AbortHandle>,
468}
469
470impl Session {
471 pub async fn spawn(opts: SessionOptions, init: Initialize) -> Result<Self> {
478 let binary = if opts.code_mode {
479 crate::code_mode::patched_binary(&opts.binary).await?
480 } else {
481 opts.binary.clone()
482 };
483 let mut cmd = Command::new(&binary);
484 if opts.clear_env {
486 cmd.env_clear();
487 }
488 cmd.args([
489 "--output-format", "stream-json",
490 "--verbose",
491 "--input-format", "stream-json",
492 "--await-initialize",
493 "--replay-user-messages",
496 ]);
497 if opts.include_partial {
498 cmd.arg("--include-partial-messages");
499 }
500 if let Some(ref m) = opts.model {
501 cmd.args(["--model", m]);
502 }
503 cmd.args(cli_args(&opts));
504 let allowed: Vec<String> = opts.allowed_tools.iter().cloned()
505 .chain(opts.mcp_servers.iter().flat_map(SdkMcpServer::qualified_tool_names))
506 .collect();
507 if !allowed.is_empty() {
508 cmd.args(["--allowedTools", &allowed.join(",")]);
509 }
510 if !opts.disallowed_tools.is_empty() {
511 cmd.args(["--disallowedTools", &opts.disallowed_tools.join(",")]);
512 }
513 let settings = match (&opts.settings, opts.code_mode) {
514 (Some(serde_json::Value::String(path)), true) => {
516 Some(read_settings_file(path, opts.cwd.as_deref()).await?)
517 }
518 (settings, _) => settings.clone(),
519 };
520 match settings_arg(settings, opts.code_mode)? {
521 Some(serde_json::Value::String(path)) => {
523 cmd.args(["--settings", &path]);
524 }
525 Some(settings) => {
526 cmd.args(["--settings", &settings.to_string()]);
527 }
528 None => {}
529 }
530 cmd.args(&opts.extra_args);
531 if let Some(ref cwd) = opts.cwd {
532 cmd.current_dir(cwd);
533 }
534 cmd.env("CLAUDE_CODE_ENTRYPOINT", "sdk-cli");
538 if opts.code_mode {
539 cmd.env("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE", "1");
540 }
541 if opts.tool_search {
542 cmd.env("ENABLE_TOOL_SEARCH", "1");
543 }
544 for (k, v) in &opts.env {
545 cmd.env(k, v);
546 }
547 cmd.stdin(Stdio::piped())
548 .stdout(Stdio::piped())
549 .stderr(Stdio::piped())
550 .kill_on_drop(false); #[cfg(unix)]
554 cmd.process_group(0);
555
556 let record = open_record(&opts).await?;
558 let mut child = cmd.spawn()?;
559 let pgid = child.id().and_then(|id| i32::try_from(id).ok());
560 let (Some(stdin), Some(stdout), Some(stderr)) =
561 (child.stdin.take(), child.stdout.take(), child.stderr.take())
562 else {
563 return Err(SessionError::Io(std::io::Error::other("subprocess pipes missing")));
564 };
565 let on_stderr = opts.on_stderr.clone();
566 let exit = Box::pin(async move {
567 let mut tail = VecDeque::with_capacity(STDERR_TAIL_LINES);
568 let mut lines = BufReader::new(stderr).lines();
569 while let Ok(Some(line)) = lines.next_line().await {
570 if let Some(cb) = &on_stderr {
571 (cb.0)(&line);
572 }
573 if tail.len() == STDERR_TAIL_LINES {
574 tail.pop_front();
575 }
576 tail.push_back(line);
577 }
578 let code = child.wait().await.ok().and_then(|s| s.code());
579 ExitInfo { code, stderr: Vec::from(tail).join("\n") }
580 });
581 let transport = Transport { stdin: Box::new(stdin), stdout: Box::new(stdout), exit, pgid };
582 Self::connect(transport, opts, init, record).await
583 }
584
585 pub(crate) async fn connect(
588 transport: Transport,
589 opts: SessionOptions,
590 mut init: Initialize,
591 record: Option<tokio::fs::File>,
592 ) -> Result<Self> {
593 let Transport { stdin, stdout, exit: exit_fut, pgid } = transport;
594 let (stdin_tx, mut stdin_rx) = mpsc::channel::<Vec<u8>>(256);
595 let fanout = Arc::new(std::sync::Mutex::new(Fanout::default()));
596 let session_id = Arc::new(RwLock::new(None));
597 let pending: Arc<Pending> = Arc::new(DashMap::new());
598 let state = Arc::new(AtomicU8::new(STATE_RUNNING));
599 let (exit_tx, exit_rx) = watch::channel(None);
600 let (reader_done_tx, reader_done) = watch::channel(false);
601 let turns_in_flight = Arc::new(AtomicUsize::new(0));
602
603 let writer = tokio::spawn(async move {
604 let mut w = BufWriter::new(stdin);
605 while let Some(bytes) = stdin_rx.recv().await {
606 if w.write_all(&bytes).await.is_err()
607 || w.write_all(b"\n").await.is_err()
608 || w.flush().await.is_err()
609 {
610 break;
611 }
612 }
613 let _ = w.shutdown().await;
614 });
615
616 let state2 = state.clone();
617 let watchdog = tokio::spawn(async move {
618 let info = exit_fut.await;
619 state2.store(STATE_DEAD, Ordering::SeqCst);
620 let _ = exit_tx.send(Some(info));
621 });
622
623 let responder = Arc::new(Responder {
624 stdin_tx: stdin_tx.downgrade(),
625 hooks: opts.hooks.clone(),
626 can_use_tool: opts.can_use_tool.clone(),
627 on_elicitation: opts.on_elicitation.clone(),
628 on_user_dialog: opts.on_user_dialog.clone(),
629 mcp_servers: opts.mcp_servers.clone(),
630 dynamic_mcp_servers: RwLock::new(vec![]),
631 in_flight: DashMap::new(),
632 });
633 let reader = tokio::spawn(read_loop(stdout, Reader {
634 record,
635 fanout: fanout.clone(),
636 session_id: session_id.clone(),
637 pending: pending.clone(),
638 turns_in_flight: turns_in_flight.clone(),
639 responder: responder.clone(),
640 done: reader_done_tx,
641 }));
642
643 let session = Session(Arc::new(SessionInner {
644 session_id,
645 stdin_tx: Mutex::new(Some(stdin_tx)),
646 fanout,
647 pending,
648 next_request_id: AtomicU64::new(0),
649 state,
650 exit: exit_rx,
651 pgid,
652 include_partial: opts.include_partial,
653 initialize_response: OnceLock::new(),
654 cli_version: OnceLock::new(),
655 control_timeout: opts.control_timeout,
656 responder,
657 turns_in_flight,
658 reader_done,
659 _tasks: [reader, writer, watchdog],
660 }));
661
662 init.hooks = opts.hooks.initialize_config();
663 let body = serde_json::to_value(&init)?;
664 let body = with_subtype(body, "initialize");
665 let response = session.request_with_timeout(&body, INITIALIZE_TIMEOUT).await?;
666 let _ = session.0.initialize_response.set(response);
667 session.check_cli_version().await?;
668 Ok(session)
669 }
670
671 async fn check_cli_version(&self) -> Result<()> {
674 let reply = self.control(&serde_json::json!({ "subtype": "get_binary_version" })).await;
675 let version = match reply {
676 Ok(v) => v.get("version").and_then(|v| v.as_str()).map(str::to_owned),
677 Err(e) => {
678 tracing::warn!(error = %e, "could not read the Claude Code version");
679 None
680 }
681 };
682 let Some(version) = version else { return Ok(()) };
683 if version_lt(&version, MIN_CLI_VERSION) {
684 self.close().await;
685 return Err(SessionError::UnsupportedCliVersion { found: version, min: MIN_CLI_VERSION });
686 }
687 let _ = self.0.cli_version.set(version);
688 Ok(())
689 }
690
691 pub async fn reconnect(previous_id: &str, mut opts: SessionOptions, init: Initialize) -> Result<Self> {
693 opts.resume = Some(previous_id.to_string());
694 Self::spawn(opts, init).await
695 }
696
697 pub async fn send<T: serde::Serialize>(&self, msg: &T) -> Result<()> {
699 if self.0.state.load(Ordering::Acquire) != STATE_RUNNING {
700 return Err(self.dead_error().await);
701 }
702 let bytes = serde_json::to_vec(msg)?;
703 let tx = self.0.stdin_tx.lock().await.clone().ok_or(SessionError::Closed)?;
704 tx.send(bytes).await.map_err(|_| SessionError::Closed)
705 }
706
707 pub async fn control<B: serde::Serialize>(&self, body: &B) -> Result<serde_json::Value> {
710 self.request_with_timeout(body, self.0.control_timeout).await
711 }
712
713 pub async fn interrupt(&self) -> Result<()> {
717 self.control(&serde_json::json!({ "subtype": "interrupt" })).await.map(|_| ())
718 }
719
720 pub async fn interrupt_all(&self) -> Result<()> {
723 let reply = self.control(&serde_json::json!({ "subtype": "interrupt", "cancel_queued": true })).await?;
724 let cancelled = reply.get("cancelled").and_then(|c| c.as_array()).map_or(0, Vec::len);
726 for _ in 0..cancelled {
727 decrement(&self.0.turns_in_flight);
728 }
729 Ok(())
730 }
731
732 pub async fn set_model(&self, model: Option<&str>) -> Result<()> {
736 self.control(&serde_json::json!({ "subtype": "set_model", "model": model })).await.map(|_| ())
737 }
738
739 pub async fn set_model_and_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
744 self.control(&serde_json::json!({
745 "subtype": "set_model", "model": model, "system_prompt": system_prompt,
746 }))
747 .await
748 .map(|_| ())
749 }
750
751 pub async fn set_system_prompt(&self, model: &str, system_prompt: &str) -> Result<()> {
759 self.control(&serde_json::json!({
760 "subtype": "set_model", "model": model, "system_prompt": system_prompt,
761 "only_if_model_is_current": true,
762 }))
763 .await
764 .map(|_| ())
765 }
766
767 pub async fn set_max_thinking_tokens(&self, tokens: Option<u32>, display: Option<ThinkingDisplay>) -> Result<()> {
771 let mut body = serde_json::json!({ "subtype": "set_max_thinking_tokens", "max_thinking_tokens": tokens });
772 if let Some(d) = display {
773 body["thinking_display"] = d.as_str().into();
774 }
775 self.control(&body).await.map(|_| ())
776 }
777
778 pub async fn set_effort(&self, effort: Option<Effort>) -> Result<()> {
783 let settings = serde_json::json!({ "effortLevel": effort });
784 self.control(&serde_json::json!({ "subtype": "apply_flag_settings", "settings": settings }))
785 .await
786 .map(|_| ())
787 }
788
789 pub async fn set_permission_mode(&self, mode: PermissionMode) -> Result<()> {
791 self.control(&serde_json::json!({ "subtype": "set_permission_mode", "mode": mode })).await.map(|_| ())
792 }
793
794 pub async fn stop_task(&self, task_id: &str) -> Result<()> {
797 self.control(&serde_json::json!({ "subtype": "stop_task", "task_id": task_id })).await.map(|_| ())
798 }
799
800 pub async fn context_usage(&self, exact: bool) -> Result<serde_json::Value> {
805 let detail = if exact { "full" } else { "summary" };
806 self.control(&serde_json::json!({ "subtype": "get_context_usage", "detail": detail })).await
807 }
808
809 pub async fn cancel_prompt(&self, uuid: &str) -> Result<()> {
814 let dropped = self
815 .control(&serde_json::json!({ "subtype": "cancel_async_message", "message_uuid": uuid }))
816 .await?;
817 if dropped.get("cancelled").and_then(|v| v.as_bool()) == Some(true) {
818 decrement(&self.0.turns_in_flight);
820 return Ok(());
821 }
822 self.control(&serde_json::json!({ "subtype": "interrupt", "for_user_message_uuids": [uuid] }))
823 .await
824 .map(|_| ())
825 }
826
827 pub async fn rename_session(&self, title: &str) -> Result<()> {
829 self.control(&serde_json::json!({ "subtype": "rename_session", "title": title })).await.map(|_| ())
830 }
831
832 pub async fn rewind_files(&self, user_message_id: &str, dry_run: bool) -> Result<serde_json::Value> {
836 self.control(&serde_json::json!({
837 "subtype": "rewind_files", "user_message_id": user_message_id, "dry_run": dry_run,
838 }))
839 .await
840 }
841
842 pub async fn mcp_status(&self) -> Result<serde_json::Value> {
844 self.control(&serde_json::json!({ "subtype": "mcp_status" })).await
845 }
846
847 pub async fn mcp_toggle(&self, server: &str, enabled: bool) -> Result<()> {
849 self.control(&serde_json::json!({ "subtype": "mcp_toggle", "serverName": server, "enabled": enabled }))
850 .await
851 .map(|_| ())
852 }
853
854 pub async fn mcp_reconnect(&self, server: &str) -> Result<()> {
856 self.control(&serde_json::json!({ "subtype": "mcp_reconnect", "serverName": server })).await.map(|_| ())
857 }
858
859 pub async fn set_mcp_servers(
865 &self,
866 sdk: Vec<SdkMcpServer>,
867 external: serde_json::Map<String, serde_json::Value>,
868 ) -> Result<serde_json::Value> {
869 let servers = server_map(&sdk, Some(&external));
870 *self.0.responder.dynamic_mcp_servers.write().unwrap_or_else(std::sync::PoisonError::into_inner) = sdk;
871 self.control(&serde_json::json!({ "subtype": "mcp_set_servers", "servers": servers })).await
872 }
873
874 pub async fn list_models(&self) -> Result<serde_json::Value> {
876 self.control(&serde_json::json!({ "subtype": "list_models" })).await
877 }
878
879 pub async fn get_settings(&self) -> Result<serde_json::Value> {
882 self.control(&serde_json::json!({ "subtype": "get_settings" })).await
883 }
884
885 pub async fn update_settings(&self, local: bool, settings: serde_json::Value) -> Result<serde_json::Value> {
889 let source = if local { "localSettings" } else { "userSettings" };
890 self.control(&serde_json::json!({ "subtype": "update_settings", "source": source, "settings": settings }))
891 .await
892 }
893
894 pub async fn get_usage(&self, skip_behaviors: bool) -> Result<serde_json::Value> {
899 self.control(&serde_json::json!({ "subtype": "get_usage", "skip_behaviors": skip_behaviors })).await
900 }
901
902 pub async fn reload_skills(&self) -> Result<serde_json::Value> {
904 self.control(&serde_json::json!({ "subtype": "reload_skills" })).await
905 }
906
907 pub async fn reload_plugins(&self, opts: ReloadPlugins) -> Result<serde_json::Value> {
909 let mut body = serde_json::json!({
910 "subtype": "reload_plugins",
911 "hold_on_cache_impact": opts.hold_on_cache_impact,
912 "refuse_if_busy": opts.refuse_if_busy,
913 });
914 if !opts.add_plugins.is_empty() {
915 body["add_plugins"] = serde_json::json!(opts.add_plugins);
916 }
917 self.control(&body).await
918 }
919
920 pub async fn task_output(&self, task_id: &str) -> Result<serde_json::Value> {
923 self.control(&serde_json::json!({ "subtype": "get_task_output", "task_id": task_id })).await
924 }
925
926 pub async fn register_repo_root(&self, directory: &str) -> Result<serde_json::Value> {
930 self.control(&serde_json::json!({
931 "subtype": "register_repo_root", "directory": directory,
932 "reload_claude_md": true, "reload_plugins": true, "reload_skills": true,
933 }))
934 .await
935 }
936
937 pub async fn mcp_call(&self, tool: &str, arguments: serde_json::Value, opts: McpCall) -> Result<serde_json::Value> {
942 let mut body = serde_json::json!({ "subtype": "mcp_call", "tool": tool, "arguments": arguments });
943 if let Some(t) = opts.timeout {
944 body["timeout_ms"] = serde_json::json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
945 }
946 if opts.result_not_for_model {
947 body["result_not_for_model"] = true.into();
948 }
949 if opts.check_permissions {
950 body["check_permissions"] = true.into();
951 }
952 self.control(&body).await
953 }
954
955 pub async fn mcp_read_resource(&self, server: &str, uri: &str) -> Result<serde_json::Value> {
958 self.control(&serde_json::json!({ "subtype": "mcp_read_resource", "serverName": server, "uri": uri }))
959 .await
960 }
961
962 pub async fn read_file(&self, path: &str, max_bytes: Option<u64>, base64: bool) -> Result<serde_json::Value> {
966 let mut body = serde_json::json!({
967 "subtype": "read_file", "path": path,
968 "encoding": if base64 { "base64" } else { "utf-8" },
969 });
970 if let Some(n) = max_bytes {
971 body["max_bytes"] = n.into();
972 }
973 self.control(&body).await
974 }
975
976 pub async fn file_suggestions(&self, query: &str) -> Result<serde_json::Value> {
979 self.control(&serde_json::json!({ "subtype": "file_suggestions", "query": query })).await
980 }
981
982 pub async fn hooks_listing(&self) -> Result<serde_json::Value> {
985 self.control(&serde_json::json!({ "subtype": "get_hooks_listing" })).await
986 }
987
988 pub async fn permission_rules(&self) -> Result<serde_json::Value> {
991 self.control(&serde_json::json!({ "subtype": "list_permission_rules" })).await
992 }
993
994 pub async fn session_cost(&self) -> Result<serde_json::Value> {
997 self.control(&serde_json::json!({ "subtype": "get_session_cost" })).await
998 }
999
1000 pub async fn reload_output_styles(&self) -> Result<serde_json::Value> {
1002 self.control(&serde_json::json!({ "subtype": "reload_output_styles" })).await
1003 }
1004
1005 pub async fn seed_read_state(&self, path: &str, mtime_ms: u64) -> Result<()> {
1008 self.control(&serde_json::json!({ "subtype": "seed_read_state", "path": path, "mtime": mtime_ms }))
1009 .await
1010 .map(|_| ())
1011 }
1012
1013 pub fn pid(&self) -> Option<u32> {
1015 self.0.pgid.and_then(|p| u32::try_from(p).ok())
1016 }
1017
1018 pub fn cli_version(&self) -> Option<&str> {
1020 self.0.cli_version.get().map(String::as_str)
1021 }
1022
1023 pub fn subscribe(&self) -> EventRx {
1026 let (tx, rx) = mpsc::unbounded_channel();
1027 let mut fanout = lock(&self.0.fanout);
1028 if !fanout.ended {
1029 fanout.subs.push(tx);
1030 }
1031 rx
1032 }
1033
1034 pub fn session_id(&self) -> Option<String> {
1037 self.0.session_id.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
1038 }
1039
1040 pub fn initialize_response(&self) -> Option<&serde_json::Value> {
1042 self.0.initialize_response.get()
1043 }
1044
1045 pub fn include_partial(&self) -> bool {
1046 self.0.include_partial
1047 }
1048
1049 pub fn is_busy(&self) -> bool {
1051 self.0.turns_in_flight.load(Ordering::Acquire) > 0
1052 }
1053
1054 pub(crate) async fn send_prompt(&self, message: &crate::protocol::UserMessage) -> Result<()> {
1057 self.0.turns_in_flight.fetch_add(1, Ordering::AcqRel);
1058 let sent = self.send(message).await;
1059 if sent.is_err() {
1060 decrement(&self.0.turns_in_flight);
1061 }
1062 sent
1063 }
1064
1065 pub fn is_alive(&self) -> bool {
1067 self.0.state.load(Ordering::Acquire) == STATE_RUNNING
1068 }
1069
1070 pub async fn close(&self) -> Option<i32> {
1075 let _ = self.0.state.compare_exchange(STATE_RUNNING, STATE_CLOSING, Ordering::SeqCst, Ordering::SeqCst);
1076 self.0.stdin_tx.lock().await.take();
1077 let mut exit = self.wait_exit(CLOSE_GRACE).await;
1078 #[cfg(unix)]
1079 for signal in [nix::sys::signal::Signal::SIGTERM, nix::sys::signal::Signal::SIGKILL] {
1080 if exit.is_some() {
1081 break;
1082 }
1083 self.signal_group(signal);
1084 exit = self.wait_exit(CLOSE_GRACE).await;
1085 }
1086 #[cfg(unix)]
1088 self.signal_group(nix::sys::signal::Signal::SIGTERM);
1089 #[cfg(not(unix))]
1090 if exit.is_none() {
1091 kill_tree(self.0.pgid);
1092 exit = self.wait_exit(CLOSE_GRACE).await;
1093 }
1094 let mut done = self.0.reader_done.clone();
1096 let _ = tokio::time::timeout(CLOSE_GRACE, done.wait_for(|d| *d)).await;
1097 exit.and_then(|e| e.code)
1098 }
1099
1100 async fn wait_exit(&self, timeout: Duration) -> Option<ExitInfo> {
1101 let mut rx = self.0.exit.clone();
1102 let waited = tokio::time::timeout(timeout, async {
1103 rx.wait_for(Option::is_some).await.ok().and_then(|info| info.clone())
1104 })
1105 .await;
1106 waited.ok().flatten()
1107 }
1108
1109 #[cfg(unix)]
1110 fn signal_group(&self, signal: nix::sys::signal::Signal) {
1111 if let Some(pgid) = self.0.pgid {
1112 let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), signal);
1113 }
1114 }
1115
1116 async fn request_with_timeout<B: serde::Serialize>(
1119 &self,
1120 body: &B,
1121 timeout: Duration,
1122 ) -> Result<serde_json::Value> {
1123 let n = self.0.next_request_id.fetch_add(1, Ordering::Relaxed);
1124 let request_id = format!("req_{n}_{}", std::process::id());
1125 let subtype = serde_json::to_value(body)?
1126 .get("subtype")
1127 .and_then(|s| s.as_str())
1128 .unwrap_or("?")
1129 .to_string();
1130
1131 let (tx, rx) = oneshot::channel();
1133 self.0.pending.insert(request_id.clone(), tx);
1134 if lock(&self.0.fanout).ended {
1137 self.0.pending.remove(&request_id);
1138 return Err(self.dead_error().await);
1139 }
1140 let envelope = OutboundControlRequest { kind: "control_request", request_id: &request_id, request: body };
1141 if let Err(e) = self.send(&envelope).await {
1142 self.0.pending.remove(&request_id);
1143 return Err(e);
1144 }
1145
1146 let reply = match tokio::time::timeout(timeout, rx).await {
1147 Ok(Ok(reply)) => reply,
1148 Ok(Err(_)) => return Err(self.dead_error().await),
1150 Err(_) => {
1151 self.0.pending.remove(&request_id);
1152 return Err(SessionError::ControlTimeout(subtype));
1153 }
1154 };
1155 match reply.subtype.as_str() {
1156 "success" => Ok(reply.response.unwrap_or(serde_json::Value::Null)),
1157 _ => Err(SessionError::ControlError {
1158 subtype,
1159 error: reply.error.unwrap_or_else(|| "unknown error".into()),
1160 }),
1161 }
1162 }
1163
1164 async fn dead_error(&self) -> SessionError {
1166 if self.0.state.load(Ordering::Acquire) == STATE_CLOSING {
1167 return SessionError::Closed;
1168 }
1169 match self.wait_exit(Duration::from_secs(1)).await {
1171 Some(ExitInfo { code, stderr }) => SessionError::ProcessExited { code, stderr },
1172 None => SessionError::Closed,
1173 }
1174 }
1175}
1176
1177impl Drop for SessionInner {
1178 fn drop(&mut self) {
1180 #[cfg(unix)]
1181 if let Some(pgid) = self.pgid
1182 && self.state.load(Ordering::Acquire) != STATE_DEAD {
1183 let _ = nix::sys::signal::killpg(nix::unistd::Pid::from_raw(pgid), nix::sys::signal::Signal::SIGTERM);
1184 }
1185 #[cfg(not(unix))]
1186 if self.state.load(Ordering::Acquire) != STATE_DEAD {
1187 kill_tree(self.pgid);
1188 }
1189 }
1190}
1191
1192#[cfg(not(unix))]
1194fn kill_tree(pid: Option<i32>) {
1195 if let Some(pid) = pid {
1196 let _ = std::process::Command::new("taskkill")
1197 .args(["/PID", &pid.to_string(), "/T", "/F"])
1198 .stdout(Stdio::null())
1199 .stderr(Stdio::null())
1200 .status();
1201 }
1202}
1203
1204fn cli_args(opts: &SessionOptions) -> Vec<String> {
1206 let mut args: Vec<String> = vec![];
1207 let mut flag = |name: &str, value: Option<String>| {
1208 if let Some(v) = value {
1209 args.push(name.into());
1210 args.push(v);
1211 }
1212 };
1213 flag("--model", opts.model.clone());
1214 flag("--effort", opts.effort.map(|e| e.as_str().into()));
1215 flag("--permission-mode", opts.permission_mode.map(|m| m.as_str().into()));
1216 flag("--fallback-model", opts.fallback_model.clone());
1217 flag("--thinking", opts.thinking.map(|t| t.as_str().into()));
1218 flag("--thinking-display", opts.thinking_display.map(|d| d.as_str().into()));
1219 flag("--max-thinking-tokens", opts.max_thinking_tokens.map(|n| n.to_string()));
1220 flag("--max-turns", opts.max_turns.map(|n| n.to_string()));
1221 flag("--max-budget-usd", opts.max_budget_usd.map(|n| n.to_string()));
1222 flag("--task-budget", opts.task_budget.map(|n| n.to_string()));
1223 flag("--resume", opts.resume.clone());
1224 flag("--resume-session-at", opts.resume_session_at.clone());
1225 flag("--session-id", opts.session_id.clone());
1226 flag("--name", opts.name.clone());
1227 flag("--tools", opts.tools.as_ref().map(|t| t.join(",")));
1228 flag("--agent", opts.agent.clone());
1229 flag("--append-subagent-system-prompt", opts.append_subagent_system_prompt.clone());
1230 flag("--betas", (!opts.betas.is_empty()).then(|| opts.betas.join(",")));
1231 flag("--debug-file", opts.debug_file.as_ref().map(|p| p.display().to_string()));
1232 flag("--setting-sources", opts.setting_sources.as_ref().map(|s| s.join(",")));
1233 flag("--permission-prompt-tool", opts.can_use_tool.as_ref().map(|_| "stdio".into()));
1234 flag(
1235 "--mcp-config",
1236 (!opts.mcp_servers.is_empty())
1237 .then(|| serde_json::json!({ "mcpServers": server_map(&opts.mcp_servers, None) }).to_string()),
1238 );
1239 for dir in &opts.add_dirs {
1240 flag("--add-dir", Some(dir.display().to_string()));
1241 }
1242 for dir in &opts.plugin_dirs {
1243 flag("--plugin-dir", Some(dir.display().to_string()));
1244 }
1245 for url in &opts.plugin_urls {
1246 flag("--plugin-url", Some(url.clone()));
1247 }
1248 for spec in &opts.files {
1249 flag("--file", Some(spec.clone()));
1250 }
1251 flag("--autocompact", opts.autocompact.map(|a| a.to_arg()));
1252 flag("--permission-prompts", opts.permission_prompts.map(|p| p.as_str().into()));
1253 if let Some(Some(name)) = &opts.worktree {
1254 flag("--worktree", Some(name.clone()));
1255 }
1256 if let Some(None) = opts.worktree {
1257 args.push("--worktree".into());
1258 }
1259 for (on, name) in [
1260 (opts.bare, "--bare"),
1261 (opts.safe_mode, "--safe-mode"),
1262 (opts.restricted, "--restricted"),
1263 (opts.disable_slash_commands, "--disable-slash-commands"),
1264 (opts.brief, "--brief"),
1265 (opts.include_hook_events, "--include-hook-events"),
1266 ] {
1267 if on {
1268 args.push(name.into());
1269 }
1270 }
1271 if opts.continue_conversation {
1272 args.push("--continue".into());
1273 }
1274 if opts.fork_session {
1275 args.push("--fork-session".into());
1276 }
1277 if !opts.persist_session {
1278 args.push("--no-session-persistence".into());
1279 }
1280 if opts.strict_mcp_config {
1281 args.push("--strict-mcp-config".into());
1282 }
1283 args
1284}
1285
1286fn version_lt(a: &str, b: &str) -> bool {
1288 let parse = |v: &str| -> Vec<u64> {
1289 v.split(['.', '-', ' '])
1290 .map_while(|part| part.parse().ok())
1291 .collect()
1292 };
1293 parse(a) < parse(b)
1294}
1295
1296fn decrement(n: &AtomicUsize) {
1298 let mut current = n.load(Ordering::Acquire);
1299 while current > 0 {
1300 match n.compare_exchange_weak(current, current - 1, Ordering::AcqRel, Ordering::Acquire) {
1301 Ok(_) => break,
1302 Err(actual) => current = actual,
1303 }
1304 }
1305}
1306
1307pub(crate) async fn open_record(opts: &SessionOptions) -> Result<Option<tokio::fs::File>> {
1309 match &opts.record {
1310 Some(path) => Ok(Some(tokio::fs::File::create(path).await?)),
1311 None => Ok(None),
1312 }
1313}
1314
1315async fn read_settings_file(path: &str, cwd: Option<&std::path::Path>) -> Result<serde_json::Value> {
1318 let path = match cwd {
1319 Some(dir) => dir.join(path),
1320 None => PathBuf::from(path),
1321 };
1322 Ok(serde_json::from_slice(&tokio::fs::read(path).await?)?)
1323}
1324
1325fn settings_arg(settings: Option<serde_json::Value>, code_mode: bool) -> Result<Option<serde_json::Value>> {
1328 if !code_mode {
1329 return Ok(settings);
1330 }
1331 let mut settings = settings.unwrap_or_else(|| serde_json::json!({}));
1332 let env = settings
1333 .as_object_mut()
1334 .map(|obj| obj.entry("env").or_insert_with(|| serde_json::json!({})))
1335 .and_then(serde_json::Value::as_object_mut)
1336 .ok_or(crate::code_mode::CodeModeError::Settings)?;
1337 env.insert("CLAUDE_CODE_EXPERIMENTAL_CODE_MODE".into(), "1".into());
1338 Ok(Some(settings))
1339}
1340
1341fn with_subtype(mut body: serde_json::Value, subtype: &str) -> serde_json::Value {
1342 if let Some(obj) = body.as_object_mut() {
1343 obj.insert("subtype".into(), subtype.into());
1344 }
1345 body
1346}
1347
1348struct Reader {
1350 record: Option<tokio::fs::File>,
1351 fanout: Arc<std::sync::Mutex<Fanout>>,
1352 session_id: Arc<RwLock<Option<String>>>,
1353 pending: Arc<Pending>,
1354 turns_in_flight: Arc<AtomicUsize>,
1355 responder: Arc<Responder>,
1356 done: watch::Sender<bool>,
1357}
1358
1359async fn read_loop(stdout: Box<dyn AsyncRead + Unpin + Send>, reader: Reader) {
1360 let Reader { mut record, fanout, session_id, pending, turns_in_flight, responder, done: reader_done } = reader;
1361 let mut lines = BufReader::new(stdout).lines();
1362 while let Ok(Some(line)) = lines.next_line().await {
1363 if line.trim().is_empty() {
1364 continue;
1365 }
1366 if let Some(file) = record.as_mut()
1367 && (file.write_all(line.as_bytes()).await.is_err()
1368 || file.write_all(b"\n").await.is_err()
1369 || file.flush().await.is_err())
1370 {
1371 tracing::warn!("recording failed; continuing without it");
1372 record = None;
1373 }
1374 let msg = parse_frame(&line);
1375 match msg {
1376 InboundMessage::ControlResponse(r) => {
1377 if let Some((_, tx)) = pending.remove(&r.response.request_id) {
1378 let _ = tx.send(r.response);
1379 }
1380 }
1381 InboundMessage::ControlRequest(req) => {
1382 let request_id = req.request_id.clone();
1388 let handler = responder.clone();
1389 let task = tokio::spawn(async move { handler.respond(req).await });
1390 responder.in_flight.insert(request_id.clone(), task.abort_handle());
1391 let responder = responder.clone();
1392 tokio::spawn(async move {
1393 let outcome = task.await;
1394 responder.in_flight.remove(&request_id);
1395 let response = match outcome {
1396 Ok(response) => response,
1397 Err(e) if e.is_cancelled() => return,
1399 Err(e) => ControlResponse::error(&request_id, format!("handler failed: {e}")),
1400 };
1401 responder.write(&response).await;
1402 });
1403 }
1404 InboundMessage::ControlCancelRequest(cancel) => {
1405 if let Some((_, task)) = responder.in_flight.remove(&cancel.request_id) {
1406 task.abort();
1407 }
1408 }
1409 other => {
1410 if let InboundMessage::Result(ref r) = other
1411 && r.origin.is_none()
1412 {
1413 decrement(&turns_in_flight);
1414 }
1415 if let InboundMessage::System(ref s) = other {
1416 let mut id = session_id.write().unwrap_or_else(std::sync::PoisonError::into_inner);
1417 if id.as_deref() != Some(s.session_id.as_str()) {
1418 *id = Some(s.session_id.clone());
1419 }
1420 }
1421 let msg = Arc::new(other);
1422 lock(&fanout).subs.retain(|tx| tx.send(msg.clone()).is_ok());
1423 }
1424 }
1425 }
1426 {
1429 let mut f = lock(&fanout);
1430 f.ended = true;
1431 f.subs.clear();
1432 }
1433 pending.clear();
1434 turns_in_flight.store(0, Ordering::Release);
1435 drop(record);
1436 let _ = reader_done.send(true);
1437}
1438
1439fn parse_frame(line: &str) -> InboundMessage {
1442 match serde_json::from_str(line) {
1443 Ok(InboundMessage::Unknown) => match serde_json::from_str(line) {
1445 Ok(value) => InboundMessage::Other(value),
1446 Err(_) => InboundMessage::Unknown,
1447 },
1448 Ok(m) => m,
1449 Err(e) => {
1450 let value: Option<serde_json::Value> = serde_json::from_str(line).ok();
1451 let field = |k: &str| value.as_ref().and_then(|v| v.get(k)).and_then(|v| v.as_str()).map(str::to_owned);
1452 if field("type").as_deref() == Some("result") {
1453 tracing::warn!(error = %e, "undecodable result frame; ending the turn with it");
1454 InboundMessage::Result(ResultMessage {
1455 subtype: field("subtype").unwrap_or_else(|| "error_unparsed_result".into()),
1456 is_error: value.as_ref().and_then(|v| v.get("is_error")).and_then(|v| v.as_bool()).unwrap_or(false),
1457 result: field("result"),
1458 session_id: field("session_id"),
1459 origin: value.as_ref().and_then(|v| v.get("origin")).cloned(),
1460 ..ResultMessage::default()
1461 })
1462 } else if let (Some("control_request"), Some(request_id)) = (field("type").as_deref(), value.as_ref().and_then(|v| v.get("request_id")).and_then(|v| v.as_str())) {
1463 tracing::warn!(error = %e, "undecodable control_request; answering with an error");
1465 InboundMessage::ControlRequest(ControlRequest {
1466 request_id: request_id.to_owned(),
1467 request: ControlRequestBody::Unsupported,
1468 })
1469 } else {
1470 tracing::debug!(error = %e, line = %line, "unparsed stdout line");
1471 InboundMessage::Unknown
1472 }
1473 }
1474 }
1475}
1476
1477impl Responder {
1478 async fn respond(&self, req: ControlRequest) -> ControlResponse {
1479 match req.request {
1480 ControlRequestBody::HookCallback(hcb) => {
1481 let span = tracing::info_span!(
1482 "claude.hook",
1483 callback_id = %hcb.callback_id,
1484 event = ?hcb.input.hook_event_name,
1485 tool = hcb.input.tool_name.as_deref().unwrap_or(""),
1486 blocked = tracing::field::Empty,
1487 );
1488 let output = self.hooks.dispatch(&hcb.callback_id, hcb.input).instrument(span.clone()).await;
1489 if let Some(ref o) = output {
1490 span.record("blocked", o.is_block());
1491 }
1492 match output {
1493 Some(output) => match serde_json::to_value(output) {
1494 Ok(v) => ControlResponse::success(&req.request_id, v),
1495 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1496 },
1497 None => ControlResponse::error(
1498 &req.request_id,
1499 format!("no hook callback registered for id {}", hcb.callback_id),
1500 ),
1501 }
1502 }
1503 ControlRequestBody::CanUseTool(cut) => match &self.can_use_tool {
1504 Some(handler) => {
1505 let original = cut.input.clone();
1506 let decision = match (handler.0)(cut).await {
1507 ToolDecision::Allow { updated_input, updated_permissions } => ToolDecision::Allow {
1509 updated_input: Some(updated_input.unwrap_or(original)),
1510 updated_permissions,
1511 },
1512 deny => deny,
1513 };
1514 match serde_json::to_value(decision) {
1515 Ok(v) => ControlResponse::success(&req.request_id, v),
1516 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1517 }
1518 }
1519 None => ControlResponse::error(&req.request_id, "no can_use_tool handler"),
1520 },
1521 ControlRequestBody::McpMessage(m) => {
1522 let span = tracing::info_span!(
1523 "claude.tool",
1524 server = %m.server_name,
1525 method = m.message.get("method").and_then(|v| v.as_str()).unwrap_or(""),
1526 tool = m.message.pointer("/params/name").and_then(|v| v.as_str()).unwrap_or(""),
1527 );
1528 let server = self.mcp_servers.iter().find(|s| s.name == m.server_name).cloned().or_else(|| {
1529 let dynamic = self.dynamic_mcp_servers.read().unwrap_or_else(std::sync::PoisonError::into_inner);
1530 dynamic.iter().find(|s| s.name == m.server_name).cloned()
1531 });
1532 let reply = match server {
1533 Some(server) => server.handle(&m.message).instrument(span).await,
1534 None => serde_json::json!({
1535 "jsonrpc": "2.0",
1536 "id": m.message.get("id"),
1537 "error": { "code": -32601, "message": format!("Server '{}' not found", m.server_name) },
1538 }),
1539 };
1540 ControlResponse::success(&req.request_id, serde_json::json!({ "mcp_response": reply }))
1541 }
1542 ControlRequestBody::Elicitation(e) => match &self.on_elicitation {
1543 Some(handler) => match serde_json::to_value((handler.0)(e).await) {
1544 Ok(v) => ControlResponse::success(&req.request_id, v),
1545 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1546 },
1547 None => ControlResponse::error(&req.request_id, "no on_elicitation handler"),
1548 },
1549 ControlRequestBody::RequestUserDialog(d) => match &self.on_user_dialog {
1550 Some(handler) => match serde_json::to_value((handler.0)(d).await) {
1551 Ok(v) => ControlResponse::success(&req.request_id, v),
1552 Err(e) => ControlResponse::error(&req.request_id, e.to_string()),
1553 },
1554 None => ControlResponse::error(&req.request_id, "no on_user_dialog handler"),
1555 },
1556 ControlRequestBody::Unsupported => {
1557 ControlResponse::error(&req.request_id, "unsupported control request subtype")
1558 }
1559 }
1560 }
1561
1562 async fn write(&self, response: &ControlResponse) {
1563 match serde_json::to_vec(response) {
1564 Ok(bytes) => match self.stdin_tx.upgrade() {
1565 Some(tx) => {
1566 let _ = tx.send(bytes).await;
1567 }
1568 None => tracing::debug!("session closed; dropping control response"),
1569 },
1570 Err(e) => tracing::warn!(error = %e, "failed to serialize control response"),
1571 }
1572 }
1573}