claude.rs

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