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