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