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