1mod mcp_server;
2pub mod tools;
3
4use collections::HashMap;
5use project::Project;
6use settings::SettingsStore;
7use smol::process::Child;
8use std::cell::RefCell;
9use std::fmt::Display;
10use std::path::Path;
11use std::pin::pin;
12use std::rc::Rc;
13use uuid::Uuid;
14
15use agent_client_protocol as acp;
16use anyhow::{Result, anyhow};
17use futures::channel::oneshot;
18use futures::{AsyncBufReadExt, AsyncWriteExt};
19use futures::{
20 AsyncRead, AsyncWrite, FutureExt, StreamExt,
21 channel::mpsc::{self, UnboundedReceiver, UnboundedSender},
22 io::BufReader,
23 select_biased,
24};
25use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity};
26use serde::{Deserialize, Serialize};
27use util::ResultExt;
28
29use crate::claude::mcp_server::{ClaudeZedMcpServer, McpConfig};
30use crate::claude::tools::ClaudeTool;
31use crate::{AgentServer, AgentServerCommand, AllAgentServersSettings};
32use acp_thread::{AcpThread, AgentConnection};
33
34#[derive(Clone)]
35pub struct ClaudeCode;
36
37impl AgentServer for ClaudeCode {
38 fn name(&self) -> &'static str {
39 "Claude Code"
40 }
41
42 fn empty_state_headline(&self) -> &'static str {
43 self.name()
44 }
45
46 fn empty_state_message(&self) -> &'static str {
47 ""
48 }
49
50 fn logo(&self) -> ui::IconName {
51 ui::IconName::AiClaude
52 }
53
54 fn connect(
55 &self,
56 _root_dir: &Path,
57 _project: &Entity<Project>,
58 _cx: &mut App,
59 ) -> Task<Result<Rc<dyn AgentConnection>>> {
60 let connection = ClaudeAgentConnection {
61 sessions: Default::default(),
62 };
63
64 Task::ready(Ok(Rc::new(connection) as _))
65 }
66}
67
68#[cfg(unix)]
69fn send_interrupt(pid: libc::pid_t) -> anyhow::Result<()> {
70 let pid = nix::unistd::Pid::from_raw(pid);
71
72 nix::sys::signal::kill(pid, nix::sys::signal::SIGINT)
73 .map_err(|e| anyhow!("Failed to interrupt process: {}", e))
74}
75
76#[cfg(windows)]
77fn send_interrupt(_pid: i32) -> anyhow::Result<()> {
78 panic!("Cancel not implemented on Windows")
79}
80
81struct ClaudeAgentConnection {
82 sessions: Rc<RefCell<HashMap<acp::SessionId, ClaudeAgentSession>>>,
83}
84
85impl AgentConnection for ClaudeAgentConnection {
86 fn name(&self) -> &'static str {
87 ClaudeCode.name()
88 }
89
90 fn new_thread(
91 self: Rc<Self>,
92 project: Entity<Project>,
93 cwd: &Path,
94 cx: &mut AsyncApp,
95 ) -> Task<Result<Entity<AcpThread>>> {
96 let cwd = cwd.to_owned();
97 cx.spawn(async move |cx| {
98 let (mut thread_tx, thread_rx) = watch::channel(WeakEntity::new_invalid());
99 let permission_mcp_server = ClaudeZedMcpServer::new(thread_rx.clone(), cx).await?;
100
101 let mut mcp_servers = HashMap::default();
102 mcp_servers.insert(
103 mcp_server::SERVER_NAME.to_string(),
104 permission_mcp_server.server_config()?,
105 );
106 let mcp_config = McpConfig { mcp_servers };
107
108 let mcp_config_file = tempfile::NamedTempFile::new()?;
109 let (mcp_config_file, mcp_config_path) = mcp_config_file.into_parts();
110
111 let mut mcp_config_file = smol::fs::File::from(mcp_config_file);
112 mcp_config_file
113 .write_all(serde_json::to_string(&mcp_config)?.as_bytes())
114 .await?;
115 mcp_config_file.flush().await?;
116
117 let settings = cx.read_global(|settings: &SettingsStore, _| {
118 settings.get::<AllAgentServersSettings>(None).claude.clone()
119 })?;
120
121 let Some(command) =
122 AgentServerCommand::resolve("claude", &[], settings, &project, cx).await
123 else {
124 anyhow::bail!("Failed to find claude binary");
125 };
126
127 let (incoming_message_tx, mut incoming_message_rx) = mpsc::unbounded();
128 let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
129 let (cancel_tx, mut cancel_rx) = mpsc::unbounded::<oneshot::Sender<Result<()>>>();
130
131 let session_id = acp::SessionId(Uuid::new_v4().to_string().into());
132
133 log::trace!("Starting session with id: {}", session_id);
134
135 cx.background_spawn({
136 let session_id = session_id.clone();
137 async move {
138 let mut outgoing_rx = Some(outgoing_rx);
139 let mut mode = ClaudeSessionMode::Start;
140
141 loop {
142 let mut child = spawn_claude(
143 &command,
144 mode,
145 session_id.clone(),
146 &mcp_config_path,
147 &cwd,
148 )
149 .await?;
150 mode = ClaudeSessionMode::Resume;
151
152 let pid = child.id();
153 log::trace!("Spawned (pid: {})", pid);
154
155 let mut io_fut = pin!(
156 ClaudeAgentSession::handle_io(
157 outgoing_rx.take().unwrap(),
158 incoming_message_tx.clone(),
159 child.stdin.take().unwrap(),
160 child.stdout.take().unwrap(),
161 )
162 .fuse()
163 );
164
165 select_biased! {
166 done_tx = cancel_rx.next() => {
167 if let Some(done_tx) = done_tx {
168 log::trace!("Interrupted (pid: {})", pid);
169 let result = send_interrupt(pid as i32);
170 outgoing_rx.replace(io_fut.await?);
171 done_tx.send(result).log_err();
172 continue;
173 }
174 }
175 result = io_fut => {
176 result?;
177 }
178 }
179
180 log::trace!("Stopped (pid: {})", pid);
181 break;
182 }
183
184 drop(mcp_config_path);
185 anyhow::Ok(())
186 }
187 })
188 .detach();
189
190 let end_turn_tx = Rc::new(RefCell::new(None));
191 let handler_task = cx.spawn({
192 let end_turn_tx = end_turn_tx.clone();
193 let thread_rx = thread_rx.clone();
194 async move |cx| {
195 while let Some(message) = incoming_message_rx.next().await {
196 ClaudeAgentSession::handle_message(
197 thread_rx.clone(),
198 message,
199 end_turn_tx.clone(),
200 cx,
201 )
202 .await
203 }
204 }
205 });
206
207 let thread =
208 cx.new(|cx| AcpThread::new(self.clone(), project, session_id.clone(), cx))?;
209
210 thread_tx.send(thread.downgrade())?;
211
212 let session = ClaudeAgentSession {
213 outgoing_tx,
214 end_turn_tx,
215 cancel_tx,
216 _handler_task: handler_task,
217 _mcp_server: Some(permission_mcp_server),
218 };
219
220 self.sessions.borrow_mut().insert(session_id, session);
221
222 Ok(thread)
223 })
224 }
225
226 fn authenticate(&self, _cx: &mut App) -> Task<Result<()>> {
227 Task::ready(Err(anyhow!("Authentication not supported")))
228 }
229
230 fn prompt(&self, params: acp::PromptToolArguments, cx: &mut App) -> Task<Result<()>> {
231 let sessions = self.sessions.borrow();
232 let Some(session) = sessions.get(¶ms.session_id) else {
233 return Task::ready(Err(anyhow!(
234 "Attempted to send message to nonexistent session {}",
235 params.session_id
236 )));
237 };
238
239 let (tx, rx) = oneshot::channel();
240 session.end_turn_tx.borrow_mut().replace(tx);
241
242 let mut content = String::new();
243 for chunk in params.prompt {
244 match chunk {
245 acp::ContentBlock::Text(text_content) => {
246 content.push_str(&text_content.text);
247 }
248 acp::ContentBlock::ResourceLink(resource_link) => {
249 content.push_str(&format!("@{}", resource_link.uri));
250 }
251 acp::ContentBlock::Audio(_)
252 | acp::ContentBlock::Image(_)
253 | acp::ContentBlock::Resource(_) => {
254 // TODO
255 }
256 }
257 }
258
259 if let Err(err) = session.outgoing_tx.unbounded_send(SdkMessage::User {
260 message: Message {
261 role: Role::User,
262 content: Content::UntaggedText(content),
263 id: None,
264 model: None,
265 stop_reason: None,
266 stop_sequence: None,
267 usage: None,
268 },
269 session_id: Some(params.session_id.to_string()),
270 }) {
271 return Task::ready(Err(anyhow!(err)));
272 }
273
274 cx.foreground_executor().spawn(async move {
275 rx.await??;
276 Ok(())
277 })
278 }
279
280 fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
281 let sessions = self.sessions.borrow();
282 let Some(session) = sessions.get(&session_id) else {
283 log::warn!("Attempted to cancel nonexistent session {}", session_id);
284 return;
285 };
286
287 let (done_tx, done_rx) = oneshot::channel();
288 if session
289 .cancel_tx
290 .unbounded_send(done_tx)
291 .log_err()
292 .is_some()
293 {
294 let end_turn_tx = session.end_turn_tx.clone();
295 cx.foreground_executor()
296 .spawn(async move {
297 done_rx.await??;
298 if let Some(end_turn_tx) = end_turn_tx.take() {
299 end_turn_tx.send(Ok(())).ok();
300 }
301 anyhow::Ok(())
302 })
303 .detach_and_log_err(cx);
304 }
305 }
306}
307
308#[derive(Clone, Copy)]
309enum ClaudeSessionMode {
310 Start,
311 Resume,
312}
313
314async fn spawn_claude(
315 command: &AgentServerCommand,
316 mode: ClaudeSessionMode,
317 session_id: acp::SessionId,
318 mcp_config_path: &Path,
319 root_dir: &Path,
320) -> Result<Child> {
321 let child = util::command::new_smol_command(&command.path)
322 .args([
323 "--input-format",
324 "stream-json",
325 "--output-format",
326 "stream-json",
327 "--print",
328 "--verbose",
329 "--mcp-config",
330 mcp_config_path.to_string_lossy().as_ref(),
331 "--permission-prompt-tool",
332 &format!(
333 "mcp__{}__{}",
334 mcp_server::SERVER_NAME,
335 mcp_server::PERMISSION_TOOL
336 ),
337 "--allowedTools",
338 "mcp__zed__Read,mcp__zed__Edit",
339 "--disallowedTools",
340 "Read,Edit",
341 ])
342 .args(match mode {
343 ClaudeSessionMode::Start => ["--session-id".to_string(), session_id.to_string()],
344 ClaudeSessionMode::Resume => ["--resume".to_string(), session_id.to_string()],
345 })
346 .args(command.args.iter().map(|arg| arg.as_str()))
347 .current_dir(root_dir)
348 .stdin(std::process::Stdio::piped())
349 .stdout(std::process::Stdio::piped())
350 .stderr(std::process::Stdio::inherit())
351 .kill_on_drop(true)
352 .spawn()?;
353
354 Ok(child)
355}
356
357struct ClaudeAgentSession {
358 outgoing_tx: UnboundedSender<SdkMessage>,
359 end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<()>>>>>,
360 cancel_tx: UnboundedSender<oneshot::Sender<Result<()>>>,
361 _mcp_server: Option<ClaudeZedMcpServer>,
362 _handler_task: Task<()>,
363}
364
365impl ClaudeAgentSession {
366 async fn handle_message(
367 mut thread_rx: watch::Receiver<WeakEntity<AcpThread>>,
368 message: SdkMessage,
369 end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<()>>>>>,
370 cx: &mut AsyncApp,
371 ) {
372 match message {
373 SdkMessage::Assistant {
374 message,
375 session_id: _,
376 }
377 | SdkMessage::User {
378 message,
379 session_id: _,
380 } => {
381 let Some(thread) = thread_rx
382 .recv()
383 .await
384 .log_err()
385 .and_then(|entity| entity.upgrade())
386 else {
387 log::error!("Received an SDK message but thread is gone");
388 return;
389 };
390
391 for chunk in message.content.chunks() {
392 match chunk {
393 ContentChunk::Text { text } | ContentChunk::UntaggedText(text) => {
394 thread
395 .update(cx, |thread, cx| {
396 thread.push_assistant_chunk(text.into(), false, cx)
397 })
398 .log_err();
399 }
400 ContentChunk::ToolUse { id, name, input } => {
401 let claude_tool = ClaudeTool::infer(&name, input);
402
403 thread
404 .update(cx, |thread, cx| {
405 if let ClaudeTool::TodoWrite(Some(params)) = claude_tool {
406 thread.update_plan(
407 acp::Plan {
408 entries: params
409 .todos
410 .into_iter()
411 .map(Into::into)
412 .collect(),
413 },
414 cx,
415 )
416 } else {
417 thread.upsert_tool_call(
418 claude_tool.as_acp(acp::ToolCallId(id.into())),
419 cx,
420 );
421 }
422 })
423 .log_err();
424 }
425 ContentChunk::ToolResult {
426 content,
427 tool_use_id,
428 } => {
429 let content = content.to_string();
430 thread
431 .update(cx, |thread, cx| {
432 thread.update_tool_call(
433 acp::ToolCallId(tool_use_id.into()),
434 acp::ToolCallStatus::Completed,
435 (!content.is_empty()).then(|| vec![content.into()]),
436 cx,
437 )
438 })
439 .log_err();
440 }
441 ContentChunk::Image
442 | ContentChunk::Document
443 | ContentChunk::Thinking
444 | ContentChunk::RedactedThinking
445 | ContentChunk::WebSearchToolResult => {
446 thread
447 .update(cx, |thread, cx| {
448 thread.push_assistant_chunk(
449 format!("Unsupported content: {:?}", chunk).into(),
450 false,
451 cx,
452 )
453 })
454 .log_err();
455 }
456 }
457 }
458 }
459 SdkMessage::Result {
460 is_error, subtype, ..
461 } => {
462 if let Some(end_turn_tx) = end_turn_tx.borrow_mut().take() {
463 if is_error {
464 end_turn_tx.send(Err(anyhow!("Error: {subtype}"))).ok();
465 } else {
466 end_turn_tx.send(Ok(())).ok();
467 }
468 }
469 }
470 SdkMessage::System { .. } => {}
471 }
472 }
473
474 async fn handle_io(
475 mut outgoing_rx: UnboundedReceiver<SdkMessage>,
476 incoming_tx: UnboundedSender<SdkMessage>,
477 mut outgoing_bytes: impl Unpin + AsyncWrite,
478 incoming_bytes: impl Unpin + AsyncRead,
479 ) -> Result<UnboundedReceiver<SdkMessage>> {
480 let mut output_reader = BufReader::new(incoming_bytes);
481 let mut outgoing_line = Vec::new();
482 let mut incoming_line = String::new();
483 loop {
484 select_biased! {
485 message = outgoing_rx.next() => {
486 if let Some(message) = message {
487 outgoing_line.clear();
488 serde_json::to_writer(&mut outgoing_line, &message)?;
489 log::trace!("send: {}", String::from_utf8_lossy(&outgoing_line));
490 outgoing_line.push(b'\n');
491 outgoing_bytes.write_all(&outgoing_line).await.ok();
492 } else {
493 break;
494 }
495 }
496 bytes_read = output_reader.read_line(&mut incoming_line).fuse() => {
497 if bytes_read? == 0 {
498 break
499 }
500 log::trace!("recv: {}", &incoming_line);
501 match serde_json::from_str::<SdkMessage>(&incoming_line) {
502 Ok(message) => {
503 incoming_tx.unbounded_send(message).log_err();
504 }
505 Err(error) => {
506 log::error!("failed to parse incoming message: {error}. Raw: {incoming_line}");
507 }
508 }
509 incoming_line.clear();
510 }
511 }
512 }
513
514 Ok(outgoing_rx)
515 }
516}
517
518#[derive(Debug, Clone, Serialize, Deserialize)]
519struct Message {
520 role: Role,
521 content: Content,
522 #[serde(skip_serializing_if = "Option::is_none")]
523 id: Option<String>,
524 #[serde(skip_serializing_if = "Option::is_none")]
525 model: Option<String>,
526 #[serde(skip_serializing_if = "Option::is_none")]
527 stop_reason: Option<String>,
528 #[serde(skip_serializing_if = "Option::is_none")]
529 stop_sequence: Option<String>,
530 #[serde(skip_serializing_if = "Option::is_none")]
531 usage: Option<Usage>,
532}
533
534#[derive(Debug, Clone, Serialize, Deserialize)]
535#[serde(untagged)]
536enum Content {
537 UntaggedText(String),
538 Chunks(Vec<ContentChunk>),
539}
540
541impl Content {
542 pub fn chunks(self) -> impl Iterator<Item = ContentChunk> {
543 match self {
544 Self::Chunks(chunks) => chunks.into_iter(),
545 Self::UntaggedText(text) => vec![ContentChunk::Text { text: text.clone() }].into_iter(),
546 }
547 }
548}
549
550impl Display for Content {
551 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
552 match self {
553 Content::UntaggedText(txt) => write!(f, "{}", txt),
554 Content::Chunks(chunks) => {
555 for chunk in chunks {
556 write!(f, "{}", chunk)?;
557 }
558 Ok(())
559 }
560 }
561 }
562}
563
564#[derive(Debug, Clone, Serialize, Deserialize)]
565#[serde(tag = "type", rename_all = "snake_case")]
566enum ContentChunk {
567 Text {
568 text: String,
569 },
570 ToolUse {
571 id: String,
572 name: String,
573 input: serde_json::Value,
574 },
575 ToolResult {
576 content: Content,
577 tool_use_id: String,
578 },
579 // TODO
580 Image,
581 Document,
582 Thinking,
583 RedactedThinking,
584 WebSearchToolResult,
585 #[serde(untagged)]
586 UntaggedText(String),
587}
588
589impl Display for ContentChunk {
590 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
591 match self {
592 ContentChunk::Text { text } => write!(f, "{}", text),
593 ContentChunk::UntaggedText(text) => write!(f, "{}", text),
594 ContentChunk::ToolResult { content, .. } => write!(f, "{}", content),
595 ContentChunk::Image
596 | ContentChunk::Document
597 | ContentChunk::Thinking
598 | ContentChunk::RedactedThinking
599 | ContentChunk::ToolUse { .. }
600 | ContentChunk::WebSearchToolResult => {
601 write!(f, "\n{:?}\n", &self)
602 }
603 }
604 }
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize)]
608struct Usage {
609 input_tokens: u32,
610 cache_creation_input_tokens: u32,
611 cache_read_input_tokens: u32,
612 output_tokens: u32,
613 service_tier: String,
614}
615
616#[derive(Debug, Clone, Serialize, Deserialize)]
617#[serde(rename_all = "snake_case")]
618enum Role {
619 System,
620 Assistant,
621 User,
622}
623
624#[derive(Debug, Clone, Serialize, Deserialize)]
625struct MessageParam {
626 role: Role,
627 content: String,
628}
629
630#[derive(Debug, Clone, Serialize, Deserialize)]
631#[serde(tag = "type", rename_all = "snake_case")]
632enum SdkMessage {
633 // An assistant message
634 Assistant {
635 message: Message, // from Anthropic SDK
636 #[serde(skip_serializing_if = "Option::is_none")]
637 session_id: Option<String>,
638 },
639
640 // A user message
641 User {
642 message: Message, // from Anthropic SDK
643 #[serde(skip_serializing_if = "Option::is_none")]
644 session_id: Option<String>,
645 },
646
647 // Emitted as the last message in a conversation
648 Result {
649 subtype: ResultErrorType,
650 duration_ms: f64,
651 duration_api_ms: f64,
652 is_error: bool,
653 num_turns: i32,
654 #[serde(skip_serializing_if = "Option::is_none")]
655 result: Option<String>,
656 session_id: String,
657 total_cost_usd: f64,
658 },
659 // Emitted as the first message at the start of a conversation
660 System {
661 cwd: String,
662 session_id: String,
663 tools: Vec<String>,
664 model: String,
665 mcp_servers: Vec<McpServer>,
666 #[serde(rename = "apiKeySource")]
667 api_key_source: String,
668 #[serde(rename = "permissionMode")]
669 permission_mode: PermissionMode,
670 },
671}
672
673#[derive(Debug, Clone, Serialize, Deserialize)]
674#[serde(rename_all = "snake_case")]
675enum ResultErrorType {
676 Success,
677 ErrorMaxTurns,
678 ErrorDuringExecution,
679}
680
681impl Display for ResultErrorType {
682 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683 match self {
684 ResultErrorType::Success => write!(f, "success"),
685 ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
686 ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
687 }
688 }
689}
690
691#[derive(Debug, Clone, Serialize, Deserialize)]
692struct McpServer {
693 name: String,
694 status: String,
695}
696
697#[derive(Debug, Clone, Serialize, Deserialize)]
698#[serde(rename_all = "camelCase")]
699enum PermissionMode {
700 Default,
701 AcceptEdits,
702 BypassPermissions,
703 Plan,
704}
705
706#[cfg(test)]
707pub(crate) mod tests {
708 use super::*;
709 use serde_json::json;
710
711 crate::common_e2e_tests!(ClaudeCode);
712
713 pub fn local_command() -> AgentServerCommand {
714 AgentServerCommand {
715 path: "claude".into(),
716 args: vec![],
717 env: None,
718 }
719 }
720
721 #[test]
722 fn test_deserialize_content_untagged_text() {
723 let json = json!("Hello, world!");
724 let content: Content = serde_json::from_value(json).unwrap();
725 match content {
726 Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
727 _ => panic!("Expected UntaggedText variant"),
728 }
729 }
730
731 #[test]
732 fn test_deserialize_content_chunks() {
733 let json = json!([
734 {
735 "type": "text",
736 "text": "Hello"
737 },
738 {
739 "type": "tool_use",
740 "id": "tool_123",
741 "name": "calculator",
742 "input": {"operation": "add", "a": 1, "b": 2}
743 }
744 ]);
745 let content: Content = serde_json::from_value(json).unwrap();
746 match content {
747 Content::Chunks(chunks) => {
748 assert_eq!(chunks.len(), 2);
749 match &chunks[0] {
750 ContentChunk::Text { text } => assert_eq!(text, "Hello"),
751 _ => panic!("Expected Text chunk"),
752 }
753 match &chunks[1] {
754 ContentChunk::ToolUse { id, name, input } => {
755 assert_eq!(id, "tool_123");
756 assert_eq!(name, "calculator");
757 assert_eq!(input["operation"], "add");
758 assert_eq!(input["a"], 1);
759 assert_eq!(input["b"], 2);
760 }
761 _ => panic!("Expected ToolUse chunk"),
762 }
763 }
764 _ => panic!("Expected Chunks variant"),
765 }
766 }
767
768 #[test]
769 fn test_deserialize_tool_result_untagged_text() {
770 let json = json!({
771 "type": "tool_result",
772 "content": "Result content",
773 "tool_use_id": "tool_456"
774 });
775 let chunk: ContentChunk = serde_json::from_value(json).unwrap();
776 match chunk {
777 ContentChunk::ToolResult {
778 content,
779 tool_use_id,
780 } => {
781 match content {
782 Content::UntaggedText(text) => assert_eq!(text, "Result content"),
783 _ => panic!("Expected UntaggedText content"),
784 }
785 assert_eq!(tool_use_id, "tool_456");
786 }
787 _ => panic!("Expected ToolResult variant"),
788 }
789 }
790
791 #[test]
792 fn test_deserialize_tool_result_chunks() {
793 let json = json!({
794 "type": "tool_result",
795 "content": [
796 {
797 "type": "text",
798 "text": "Processing complete"
799 },
800 {
801 "type": "text",
802 "text": "Result: 42"
803 }
804 ],
805 "tool_use_id": "tool_789"
806 });
807 let chunk: ContentChunk = serde_json::from_value(json).unwrap();
808 match chunk {
809 ContentChunk::ToolResult {
810 content,
811 tool_use_id,
812 } => {
813 match content {
814 Content::Chunks(chunks) => {
815 assert_eq!(chunks.len(), 2);
816 match &chunks[0] {
817 ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
818 _ => panic!("Expected Text chunk"),
819 }
820 match &chunks[1] {
821 ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
822 _ => panic!("Expected Text chunk"),
823 }
824 }
825 _ => panic!("Expected Chunks content"),
826 }
827 assert_eq!(tool_use_id, "tool_789");
828 }
829 _ => panic!("Expected ToolResult variant"),
830 }
831 }
832}