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 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::PromptArguments, 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_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 { .. } => {}
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}
646
647#[derive(Debug, Clone, Serialize, Deserialize)]
648#[serde(tag = "subtype", rename_all = "snake_case")]
649enum ControlRequest {
650    /// Cancel the current conversation
651    Interrupt,
652}
653
654#[derive(Debug, Clone, Serialize, Deserialize)]
655#[serde(rename_all = "snake_case")]
656enum ResultErrorType {
657    Success,
658    ErrorMaxTurns,
659    ErrorDuringExecution,
660}
661
662impl Display for ResultErrorType {
663    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
664        match self {
665            ResultErrorType::Success => write!(f, "success"),
666            ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
667            ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
668        }
669    }
670}
671
672impl SdkMessage {
673    fn new_interrupt_message() -> Self {
674        use rand::Rng;
675        // In the Claude Code TS SDK they just generate a random 12 character string,
676        // `Math.random().toString(36).substring(2, 15)`
677        let request_id = rand::thread_rng()
678            .sample_iter(&rand::distributions::Alphanumeric)
679            .take(12)
680            .map(char::from)
681            .collect();
682
683        Self::ControlRequest {
684            request_id,
685            request: ControlRequest::Interrupt,
686        }
687    }
688}
689
690#[derive(Debug, Clone, Serialize, Deserialize)]
691struct McpServer {
692    name: String,
693    status: String,
694}
695
696#[derive(Debug, Clone, Serialize, Deserialize)]
697#[serde(rename_all = "camelCase")]
698enum PermissionMode {
699    Default,
700    AcceptEdits,
701    BypassPermissions,
702    Plan,
703}
704
705#[cfg(test)]
706pub(crate) mod tests {
707    use super::*;
708    use serde_json::json;
709
710    crate::common_e2e_tests!(ClaudeCode);
711
712    pub fn local_command() -> AgentServerCommand {
713        AgentServerCommand {
714            path: "claude".into(),
715            args: vec![],
716            env: None,
717        }
718    }
719
720    #[test]
721    fn test_deserialize_content_untagged_text() {
722        let json = json!("Hello, world!");
723        let content: Content = serde_json::from_value(json).unwrap();
724        match content {
725            Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
726            _ => panic!("Expected UntaggedText variant"),
727        }
728    }
729
730    #[test]
731    fn test_deserialize_content_chunks() {
732        let json = json!([
733            {
734                "type": "text",
735                "text": "Hello"
736            },
737            {
738                "type": "tool_use",
739                "id": "tool_123",
740                "name": "calculator",
741                "input": {"operation": "add", "a": 1, "b": 2}
742            }
743        ]);
744        let content: Content = serde_json::from_value(json).unwrap();
745        match content {
746            Content::Chunks(chunks) => {
747                assert_eq!(chunks.len(), 2);
748                match &chunks[0] {
749                    ContentChunk::Text { text } => assert_eq!(text, "Hello"),
750                    _ => panic!("Expected Text chunk"),
751                }
752                match &chunks[1] {
753                    ContentChunk::ToolUse { id, name, input } => {
754                        assert_eq!(id, "tool_123");
755                        assert_eq!(name, "calculator");
756                        assert_eq!(input["operation"], "add");
757                        assert_eq!(input["a"], 1);
758                        assert_eq!(input["b"], 2);
759                    }
760                    _ => panic!("Expected ToolUse chunk"),
761                }
762            }
763            _ => panic!("Expected Chunks variant"),
764        }
765    }
766
767    #[test]
768    fn test_deserialize_tool_result_untagged_text() {
769        let json = json!({
770            "type": "tool_result",
771            "content": "Result content",
772            "tool_use_id": "tool_456"
773        });
774        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
775        match chunk {
776            ContentChunk::ToolResult {
777                content,
778                tool_use_id,
779            } => {
780                match content {
781                    Content::UntaggedText(text) => assert_eq!(text, "Result content"),
782                    _ => panic!("Expected UntaggedText content"),
783                }
784                assert_eq!(tool_use_id, "tool_456");
785            }
786            _ => panic!("Expected ToolResult variant"),
787        }
788    }
789
790    #[test]
791    fn test_deserialize_tool_result_chunks() {
792        let json = json!({
793            "type": "tool_result",
794            "content": [
795                {
796                    "type": "text",
797                    "text": "Processing complete"
798                },
799                {
800                    "type": "text",
801                    "text": "Result: 42"
802                }
803            ],
804            "tool_use_id": "tool_789"
805        });
806        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
807        match chunk {
808            ContentChunk::ToolResult {
809                content,
810                tool_use_id,
811            } => {
812                match content {
813                    Content::Chunks(chunks) => {
814                        assert_eq!(chunks.len(), 2);
815                        match &chunks[0] {
816                            ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
817                            _ => panic!("Expected Text chunk"),
818                        }
819                        match &chunks[1] {
820                            ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
821                            _ => panic!("Expected Text chunk"),
822                        }
823                    }
824                    _ => panic!("Expected Chunks content"),
825                }
826                assert_eq!(tool_use_id, "tool_789");
827            }
828            _ => panic!("Expected ToolResult variant"),
829        }
830    }
831}