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