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