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