claude.rs

  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::{McpConfig, ZedMcpServer};
 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 project = project.clone();
 61        let root_dir = root_dir.to_path_buf();
 62        cx.spawn(async move |cx| {
 63            let threads_map = Rc::new(RefCell::new(HashMap::default()));
 64            let permission_mcp_server = ZedMcpServer::new(threads_map.clone(), cx).await?;
 65
 66            let mut mcp_servers = HashMap::default();
 67            mcp_servers.insert(
 68                mcp_server::SERVER_NAME.to_string(),
 69                permission_mcp_server.server_config()?,
 70            );
 71            let mcp_config = McpConfig { mcp_servers };
 72
 73            let mcp_config_file = tempfile::NamedTempFile::new()?;
 74            let (mcp_config_file, mcp_config_path) = mcp_config_file.into_parts();
 75
 76            let mut mcp_config_file = smol::fs::File::from(mcp_config_file);
 77            mcp_config_file
 78                .write_all(serde_json::to_string(&mcp_config)?.as_bytes())
 79                .await?;
 80            mcp_config_file.flush().await?;
 81
 82            let settings = cx.read_global(|settings: &SettingsStore, _| {
 83                settings.get::<AllAgentServersSettings>(None).claude.clone()
 84            })?;
 85
 86            let Some(command) =
 87                AgentServerCommand::resolve("claude", &[], settings, &project, cx).await
 88            else {
 89                anyhow::bail!("Failed to find claude binary");
 90            };
 91
 92            let (incoming_message_tx, mut incoming_message_rx) = mpsc::unbounded();
 93            let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
 94            let (cancel_tx, mut cancel_rx) = mpsc::unbounded::<oneshot::Sender<Result<()>>>();
 95
 96            let session_id = acp::SessionId(Uuid::new_v4().to_string().into());
 97
 98            log::trace!("Starting session with id: {}", session_id);
 99
100            cx.background_spawn({
101                let session_id = session_id.clone();
102                async move {
103                    let mut outgoing_rx = Some(outgoing_rx);
104                    let mut mode = ClaudeSessionMode::Start;
105
106                    loop {
107                        let mut child = spawn_claude(
108                            &command,
109                            mode,
110                            session_id.clone(),
111                            &mcp_config_path,
112                            &root_dir,
113                        )
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            })
153            .detach();
154
155            let end_turn_tx = Rc::new(RefCell::new(None));
156            let handler_task = cx.spawn({
157                let end_turn_tx = end_turn_tx.clone();
158                let threads_map = threads_map.clone();
159                async move |cx| {
160                    while let Some(message) = incoming_message_rx.next().await {
161                        ClaudeAgentConnection::handle_message(
162                            threads_map.clone(),
163                            message,
164                            end_turn_tx.clone(),
165                            cx,
166                        )
167                        .await
168                    }
169                }
170            });
171
172            let connection = ClaudeAgentConnection {
173                threads_map,
174                outgoing_tx,
175                end_turn_tx,
176                cancel_tx,
177                session_id,
178                _handler_task: handler_task,
179                _mcp_server: Some(permission_mcp_server),
180            };
181
182            Ok(Rc::new(connection) as _)
183        })
184    }
185}
186
187#[cfg(unix)]
188fn send_interrupt(pid: libc::pid_t) -> anyhow::Result<()> {
189    let pid = nix::unistd::Pid::from_raw(pid);
190
191    nix::sys::signal::kill(pid, nix::sys::signal::SIGINT)
192        .map_err(|e| anyhow!("Failed to interrupt process: {}", e))
193}
194
195#[cfg(windows)]
196fn send_interrupt(_pid: i32) -> anyhow::Result<()> {
197    panic!("Cancel not implemented on Windows")
198}
199
200impl AgentConnection for ClaudeAgentConnection {
201    fn name(&self) -> &'static str {
202        ClaudeCode.name()
203    }
204
205    fn new_thread(
206        self: Rc<Self>,
207        project: Entity<Project>,
208        _cwd: &Path,
209        cx: &mut AsyncApp,
210    ) -> Task<Result<Entity<AcpThread>>> {
211        let session_id = self.session_id.clone();
212        let thread_result =
213            cx.new(|cx| AcpThread::new(self.clone(), project, session_id.clone(), cx));
214
215        if let Ok(thread) = &thread_result {
216            self.threads_map
217                .borrow_mut()
218                .insert(session_id, thread.downgrade());
219        }
220
221        Task::ready(thread_result)
222    }
223
224    fn authenticate(&self, _cx: &mut App) -> Task<Result<()>> {
225        Task::ready(Err(anyhow!("Authentication not supported")))
226    }
227
228    fn prompt(&self, params: acp::PromptToolArguments, cx: &mut App) -> Task<Result<()>> {
229        let (tx, rx) = oneshot::channel();
230        self.end_turn_tx.borrow_mut().replace(tx);
231
232        let mut content = String::new();
233        for chunk in params.prompt {
234            match chunk {
235                acp::ContentBlock::Text(text_content) => {
236                    content.push_str(&text_content.text);
237                }
238                acp::ContentBlock::ResourceLink(resource_link) => {
239                    content.push_str(&format!("@{}", resource_link.uri));
240                }
241                acp::ContentBlock::Audio(_)
242                | acp::ContentBlock::Image(_)
243                | acp::ContentBlock::Resource(_) => {
244                    // TODO
245                }
246            }
247        }
248
249        if let Err(err) = self.outgoing_tx.unbounded_send(SdkMessage::User {
250            message: Message {
251                role: Role::User,
252                content: Content::UntaggedText(content),
253                id: None,
254                model: None,
255                stop_reason: None,
256                stop_sequence: None,
257                usage: None,
258            },
259            session_id: Some(params.session_id.to_string()),
260        }) {
261            return Task::ready(Err(anyhow!(err)));
262        }
263
264        cx.foreground_executor().spawn(async move {
265            rx.await??;
266            Ok(())
267        })
268    }
269
270    fn cancel(&self, cx: &mut App) {
271        let (done_tx, done_rx) = oneshot::channel();
272        if self.cancel_tx.unbounded_send(done_tx).log_err().is_some() {
273            cx.foreground_executor()
274                .spawn(async move { done_rx.await? })
275                .detach_and_log_err(cx);
276        }
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}