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        "How can I help you today?"
 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 new_thread(
 74        self: Rc<Self>,
 75        project: Entity<Project>,
 76        cwd: &Path,
 77        cx: &mut AsyncApp,
 78    ) -> Task<Result<Entity<AcpThread>>> {
 79        let cwd = cwd.to_owned();
 80        cx.spawn(async move |cx| {
 81            let (mut thread_tx, thread_rx) = watch::channel(WeakEntity::new_invalid());
 82            let permission_mcp_server = ClaudeZedMcpServer::new(thread_rx.clone(), cx).await?;
 83
 84            let mut mcp_servers = HashMap::default();
 85            mcp_servers.insert(
 86                mcp_server::SERVER_NAME.to_string(),
 87                permission_mcp_server.server_config()?,
 88            );
 89            let mcp_config = McpConfig { mcp_servers };
 90
 91            let mcp_config_file = tempfile::NamedTempFile::new()?;
 92            let (mcp_config_file, mcp_config_path) = mcp_config_file.into_parts();
 93
 94            let mut mcp_config_file = smol::fs::File::from(mcp_config_file);
 95            mcp_config_file
 96                .write_all(serde_json::to_string(&mcp_config)?.as_bytes())
 97                .await?;
 98            mcp_config_file.flush().await?;
 99
100            let settings = cx.read_global(|settings: &SettingsStore, _| {
101                settings.get::<AllAgentServersSettings>(None).claude.clone()
102            })?;
103
104            let Some(command) =
105                AgentServerCommand::resolve("claude", &[], settings, &project, cx).await
106            else {
107                anyhow::bail!("Failed to find claude binary");
108            };
109
110            let (incoming_message_tx, mut incoming_message_rx) = mpsc::unbounded();
111            let (outgoing_tx, outgoing_rx) = mpsc::unbounded();
112
113            let session_id = acp::SessionId(Uuid::new_v4().to_string().into());
114
115            log::trace!("Starting session with id: {}", session_id);
116
117            cx.background_spawn({
118                let session_id = session_id.clone();
119                async move {
120                    let mut outgoing_rx = Some(outgoing_rx);
121
122                    let mut child = spawn_claude(
123                        &command,
124                        ClaudeSessionMode::Start,
125                        session_id.clone(),
126                        &mcp_config_path,
127                        &cwd,
128                    )?;
129
130                    let pid = child.id();
131                    log::trace!("Spawned (pid: {})", pid);
132
133                    ClaudeAgentSession::handle_io(
134                        outgoing_rx.take().unwrap(),
135                        incoming_message_tx.clone(),
136                        child.stdin.take().unwrap(),
137                        child.stdout.take().unwrap(),
138                    )
139                    .await?;
140
141                    log::trace!("Stopped (pid: {})", pid);
142
143                    drop(mcp_config_path);
144                    anyhow::Ok(())
145                }
146            })
147            .detach();
148
149            let end_turn_tx = Rc::new(RefCell::new(None));
150            let handler_task = cx.spawn({
151                let end_turn_tx = end_turn_tx.clone();
152                let thread_rx = thread_rx.clone();
153                async move |cx| {
154                    while let Some(message) = incoming_message_rx.next().await {
155                        ClaudeAgentSession::handle_message(
156                            thread_rx.clone(),
157                            message,
158                            end_turn_tx.clone(),
159                            cx,
160                        )
161                        .await
162                    }
163                }
164            });
165
166            let thread = cx.new(|cx| {
167                AcpThread::new("Claude Code", self.clone(), project, session_id.clone(), cx)
168            })?;
169
170            thread_tx.send(thread.downgrade())?;
171
172            let session = ClaudeAgentSession {
173                outgoing_tx,
174                end_turn_tx,
175                _handler_task: handler_task,
176                _mcp_server: Some(permission_mcp_server),
177            };
178
179            self.sessions.borrow_mut().insert(session_id, session);
180
181            Ok(thread)
182        })
183    }
184
185    fn auth_methods(&self) -> &[acp::AuthMethod] {
186        &[]
187    }
188
189    fn authenticate(&self, _: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
190        Task::ready(Err(anyhow!("Authentication not supported")))
191    }
192
193    fn prompt(&self, params: acp::PromptRequest, 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
264fn 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_content_block(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::ToolCallUpdate {
391                                            id: acp::ToolCallId(tool_use_id.into()),
392                                            fields: acp::ToolCallUpdateFields {
393                                                status: Some(acp::ToolCallStatus::Completed),
394                                                content: (!content.is_empty())
395                                                    .then(|| vec![content.into()]),
396                                                ..Default::default()
397                                            },
398                                        },
399                                        cx,
400                                    )
401                                })
402                                .log_err();
403                        }
404                        ContentChunk::Image
405                        | ContentChunk::Document
406                        | ContentChunk::Thinking
407                        | ContentChunk::RedactedThinking
408                        | ContentChunk::WebSearchToolResult => {
409                            thread
410                                .update(cx, |thread, cx| {
411                                    thread.push_assistant_content_block(
412                                        format!("Unsupported content: {:?}", chunk).into(),
413                                        false,
414                                        cx,
415                                    )
416                                })
417                                .log_err();
418                        }
419                    }
420                }
421            }
422            SdkMessage::Result {
423                is_error,
424                subtype,
425                result,
426                ..
427            } => {
428                if let Some(end_turn_tx) = end_turn_tx.borrow_mut().take() {
429                    if is_error {
430                        end_turn_tx
431                            .send(Err(anyhow!(
432                                "Error: {}",
433                                result.unwrap_or_else(|| subtype.to_string())
434                            )))
435                            .ok();
436                    } else {
437                        end_turn_tx.send(Ok(())).ok();
438                    }
439                }
440            }
441            SdkMessage::System { .. } | SdkMessage::ControlResponse { .. } => {}
442        }
443    }
444
445    async fn handle_io(
446        mut outgoing_rx: UnboundedReceiver<SdkMessage>,
447        incoming_tx: UnboundedSender<SdkMessage>,
448        mut outgoing_bytes: impl Unpin + AsyncWrite,
449        incoming_bytes: impl Unpin + AsyncRead,
450    ) -> Result<UnboundedReceiver<SdkMessage>> {
451        let mut output_reader = BufReader::new(incoming_bytes);
452        let mut outgoing_line = Vec::new();
453        let mut incoming_line = String::new();
454        loop {
455            select_biased! {
456                message = outgoing_rx.next() => {
457                    if let Some(message) = message {
458                        outgoing_line.clear();
459                        serde_json::to_writer(&mut outgoing_line, &message)?;
460                        log::trace!("send: {}", String::from_utf8_lossy(&outgoing_line));
461                        outgoing_line.push(b'\n');
462                        outgoing_bytes.write_all(&outgoing_line).await.ok();
463                    } else {
464                        break;
465                    }
466                }
467                bytes_read = output_reader.read_line(&mut incoming_line).fuse() => {
468                    if bytes_read? == 0 {
469                        break
470                    }
471                    log::trace!("recv: {}", &incoming_line);
472                    match serde_json::from_str::<SdkMessage>(&incoming_line) {
473                        Ok(message) => {
474                            incoming_tx.unbounded_send(message).log_err();
475                        }
476                        Err(error) => {
477                            log::error!("failed to parse incoming message: {error}. Raw: {incoming_line}");
478                        }
479                    }
480                    incoming_line.clear();
481                }
482            }
483        }
484
485        Ok(outgoing_rx)
486    }
487}
488
489#[derive(Debug, Clone, Serialize, Deserialize)]
490struct Message {
491    role: Role,
492    content: Content,
493    #[serde(skip_serializing_if = "Option::is_none")]
494    id: Option<String>,
495    #[serde(skip_serializing_if = "Option::is_none")]
496    model: Option<String>,
497    #[serde(skip_serializing_if = "Option::is_none")]
498    stop_reason: Option<String>,
499    #[serde(skip_serializing_if = "Option::is_none")]
500    stop_sequence: Option<String>,
501    #[serde(skip_serializing_if = "Option::is_none")]
502    usage: Option<Usage>,
503}
504
505#[derive(Debug, Clone, Serialize, Deserialize)]
506#[serde(untagged)]
507enum Content {
508    UntaggedText(String),
509    Chunks(Vec<ContentChunk>),
510}
511
512impl Content {
513    pub fn chunks(self) -> impl Iterator<Item = ContentChunk> {
514        match self {
515            Self::Chunks(chunks) => chunks.into_iter(),
516            Self::UntaggedText(text) => vec![ContentChunk::Text { text: text.clone() }].into_iter(),
517        }
518    }
519}
520
521impl Display for Content {
522    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
523        match self {
524            Content::UntaggedText(txt) => write!(f, "{}", txt),
525            Content::Chunks(chunks) => {
526                for chunk in chunks {
527                    write!(f, "{}", chunk)?;
528                }
529                Ok(())
530            }
531        }
532    }
533}
534
535#[derive(Debug, Clone, Serialize, Deserialize)]
536#[serde(tag = "type", rename_all = "snake_case")]
537enum ContentChunk {
538    Text {
539        text: String,
540    },
541    ToolUse {
542        id: String,
543        name: String,
544        input: serde_json::Value,
545    },
546    ToolResult {
547        content: Content,
548        tool_use_id: String,
549    },
550    // TODO
551    Image,
552    Document,
553    Thinking,
554    RedactedThinking,
555    WebSearchToolResult,
556    #[serde(untagged)]
557    UntaggedText(String),
558}
559
560impl Display for ContentChunk {
561    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
562        match self {
563            ContentChunk::Text { text } => write!(f, "{}", text),
564            ContentChunk::UntaggedText(text) => write!(f, "{}", text),
565            ContentChunk::ToolResult { content, .. } => write!(f, "{}", content),
566            ContentChunk::Image
567            | ContentChunk::Document
568            | ContentChunk::Thinking
569            | ContentChunk::RedactedThinking
570            | ContentChunk::ToolUse { .. }
571            | ContentChunk::WebSearchToolResult => {
572                write!(f, "\n{:?}\n", &self)
573            }
574        }
575    }
576}
577
578#[derive(Debug, Clone, Serialize, Deserialize)]
579struct Usage {
580    input_tokens: u32,
581    cache_creation_input_tokens: u32,
582    cache_read_input_tokens: u32,
583    output_tokens: u32,
584    service_tier: String,
585}
586
587#[derive(Debug, Clone, Serialize, Deserialize)]
588#[serde(rename_all = "snake_case")]
589enum Role {
590    System,
591    Assistant,
592    User,
593}
594
595#[derive(Debug, Clone, Serialize, Deserialize)]
596struct MessageParam {
597    role: Role,
598    content: String,
599}
600
601#[derive(Debug, Clone, Serialize, Deserialize)]
602#[serde(tag = "type", rename_all = "snake_case")]
603enum SdkMessage {
604    // An assistant message
605    Assistant {
606        message: Message, // from Anthropic SDK
607        #[serde(skip_serializing_if = "Option::is_none")]
608        session_id: Option<String>,
609    },
610    // A user message
611    User {
612        message: Message, // from Anthropic SDK
613        #[serde(skip_serializing_if = "Option::is_none")]
614        session_id: Option<String>,
615    },
616    // Emitted as the last message in a conversation
617    Result {
618        subtype: ResultErrorType,
619        duration_ms: f64,
620        duration_api_ms: f64,
621        is_error: bool,
622        num_turns: i32,
623        #[serde(skip_serializing_if = "Option::is_none")]
624        result: Option<String>,
625        session_id: String,
626        total_cost_usd: f64,
627    },
628    // Emitted as the first message at the start of a conversation
629    System {
630        cwd: String,
631        session_id: String,
632        tools: Vec<String>,
633        model: String,
634        mcp_servers: Vec<McpServer>,
635        #[serde(rename = "apiKeySource")]
636        api_key_source: String,
637        #[serde(rename = "permissionMode")]
638        permission_mode: PermissionMode,
639    },
640    /// Messages used to control the conversation, outside of chat messages to the model
641    ControlRequest {
642        request_id: String,
643        request: ControlRequest,
644    },
645    /// Response to a control request
646    ControlResponse { response: ControlResponse },
647}
648
649#[derive(Debug, Clone, Serialize, Deserialize)]
650#[serde(tag = "subtype", rename_all = "snake_case")]
651enum ControlRequest {
652    /// Cancel the current conversation
653    Interrupt,
654}
655
656#[derive(Debug, Clone, Serialize, Deserialize)]
657struct ControlResponse {
658    request_id: String,
659    subtype: ResultErrorType,
660}
661
662#[derive(Debug, Clone, Serialize, Deserialize)]
663#[serde(rename_all = "snake_case")]
664enum ResultErrorType {
665    Success,
666    ErrorMaxTurns,
667    ErrorDuringExecution,
668}
669
670impl Display for ResultErrorType {
671    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
672        match self {
673            ResultErrorType::Success => write!(f, "success"),
674            ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
675            ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
676        }
677    }
678}
679
680impl SdkMessage {
681    fn new_interrupt_message() -> Self {
682        use rand::Rng;
683        // In the Claude Code TS SDK they just generate a random 12 character string,
684        // `Math.random().toString(36).substring(2, 15)`
685        let request_id = rand::thread_rng()
686            .sample_iter(&rand::distributions::Alphanumeric)
687            .take(12)
688            .map(char::from)
689            .collect();
690
691        Self::ControlRequest {
692            request_id,
693            request: ControlRequest::Interrupt,
694        }
695    }
696}
697
698#[derive(Debug, Clone, Serialize, Deserialize)]
699struct McpServer {
700    name: String,
701    status: String,
702}
703
704#[derive(Debug, Clone, Serialize, Deserialize)]
705#[serde(rename_all = "camelCase")]
706enum PermissionMode {
707    Default,
708    AcceptEdits,
709    BypassPermissions,
710    Plan,
711}
712
713#[cfg(test)]
714pub(crate) mod tests {
715    use super::*;
716    use serde_json::json;
717
718    crate::common_e2e_tests!(ClaudeCode, allow_option_id = "allow");
719
720    pub fn local_command() -> AgentServerCommand {
721        AgentServerCommand {
722            path: "claude".into(),
723            args: vec![],
724            env: None,
725        }
726    }
727
728    #[test]
729    fn test_deserialize_content_untagged_text() {
730        let json = json!("Hello, world!");
731        let content: Content = serde_json::from_value(json).unwrap();
732        match content {
733            Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
734            _ => panic!("Expected UntaggedText variant"),
735        }
736    }
737
738    #[test]
739    fn test_deserialize_content_chunks() {
740        let json = json!([
741            {
742                "type": "text",
743                "text": "Hello"
744            },
745            {
746                "type": "tool_use",
747                "id": "tool_123",
748                "name": "calculator",
749                "input": {"operation": "add", "a": 1, "b": 2}
750            }
751        ]);
752        let content: Content = serde_json::from_value(json).unwrap();
753        match content {
754            Content::Chunks(chunks) => {
755                assert_eq!(chunks.len(), 2);
756                match &chunks[0] {
757                    ContentChunk::Text { text } => assert_eq!(text, "Hello"),
758                    _ => panic!("Expected Text chunk"),
759                }
760                match &chunks[1] {
761                    ContentChunk::ToolUse { id, name, input } => {
762                        assert_eq!(id, "tool_123");
763                        assert_eq!(name, "calculator");
764                        assert_eq!(input["operation"], "add");
765                        assert_eq!(input["a"], 1);
766                        assert_eq!(input["b"], 2);
767                    }
768                    _ => panic!("Expected ToolUse chunk"),
769                }
770            }
771            _ => panic!("Expected Chunks variant"),
772        }
773    }
774
775    #[test]
776    fn test_deserialize_tool_result_untagged_text() {
777        let json = json!({
778            "type": "tool_result",
779            "content": "Result content",
780            "tool_use_id": "tool_456"
781        });
782        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
783        match chunk {
784            ContentChunk::ToolResult {
785                content,
786                tool_use_id,
787            } => {
788                match content {
789                    Content::UntaggedText(text) => assert_eq!(text, "Result content"),
790                    _ => panic!("Expected UntaggedText content"),
791                }
792                assert_eq!(tool_use_id, "tool_456");
793            }
794            _ => panic!("Expected ToolResult variant"),
795        }
796    }
797
798    #[test]
799    fn test_deserialize_tool_result_chunks() {
800        let json = json!({
801            "type": "tool_result",
802            "content": [
803                {
804                    "type": "text",
805                    "text": "Processing complete"
806                },
807                {
808                    "type": "text",
809                    "text": "Result: 42"
810                }
811            ],
812            "tool_use_id": "tool_789"
813        });
814        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
815        match chunk {
816            ContentChunk::ToolResult {
817                content,
818                tool_use_id,
819            } => {
820                match content {
821                    Content::Chunks(chunks) => {
822                        assert_eq!(chunks.len(), 2);
823                        match &chunks[0] {
824                            ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
825                            _ => panic!("Expected Text chunk"),
826                        }
827                        match &chunks[1] {
828                            ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
829                            _ => panic!("Expected Text chunk"),
830                        }
831                    }
832                    _ => panic!("Expected Chunks content"),
833                }
834                assert_eq!(tool_use_id, "tool_789");
835            }
836            _ => panic!("Expected ToolResult variant"),
837        }
838    }
839}