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