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