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