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