claude.rs

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