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 async move {
157 while let Some(message) = incoming_message_rx.next().await {
158 ClaudeAgentConnection::handle_message(
159 delegate.clone(),
160 message,
161 end_turn_tx.clone(),
162 tool_id_map.clone(),
163 )
164 .await
165 }
166 }
167 });
168
169 let mut connection = ClaudeAgentConnection {
170 outgoing_tx,
171 end_turn_tx,
172 _handler_task: handler_task,
173 _mcp_server: None,
174 };
175
176 connection._mcp_server = Some(permission_mcp_server);
177 acp_thread::AcpThread::new(connection, title, None, project.clone(), cx)
178 })
179 })
180 }
181}
182
183impl AgentConnection for ClaudeAgentConnection {
184 /// Send a request to the agent and wait for a response.
185 fn request_any(
186 &self,
187 params: AnyAgentRequest,
188 ) -> LocalBoxFuture<'static, Result<acp::AnyAgentResult>> {
189 let end_turn_tx = self.end_turn_tx.clone();
190 let outgoing_tx = self.outgoing_tx.clone();
191 async move {
192 match params {
193 // todo: consider sending an empty request so we get the init response?
194 AnyAgentRequest::InitializeParams(_) => Ok(AnyAgentResult::InitializeResponse(
195 acp::InitializeResponse {
196 is_authenticated: true,
197 protocol_version: ProtocolVersion::latest(),
198 },
199 )),
200 AnyAgentRequest::AuthenticateParams(_) => {
201 Err(anyhow!("Authentication not supported"))
202 }
203 AnyAgentRequest::SendUserMessageParams(message) => {
204 let (tx, rx) = oneshot::channel();
205 end_turn_tx.borrow_mut().replace(tx);
206 let mut content = String::new();
207 for chunk in message.chunks {
208 match chunk {
209 agentic_coding_protocol::UserMessageChunk::Text { text } => {
210 content.push_str(&text)
211 }
212 agentic_coding_protocol::UserMessageChunk::Path { path } => {
213 content.push_str(&format!("@{path:?}"))
214 }
215 }
216 }
217 outgoing_tx.unbounded_send(SdkMessage::User {
218 message: Message {
219 role: Role::User,
220 content: Content::UntaggedText(content),
221 id: None,
222 model: None,
223 stop_reason: None,
224 stop_sequence: None,
225 usage: None,
226 },
227 session_id: None,
228 })?;
229 rx.await??;
230 Ok(AnyAgentResult::SendUserMessageResponse(
231 acp::SendUserMessageResponse,
232 ))
233 }
234 AnyAgentRequest::CancelSendMessageParams(_) => Ok(
235 AnyAgentResult::CancelSendMessageResponse(acp::CancelSendMessageResponse),
236 ),
237 }
238 }
239 .boxed_local()
240 }
241}
242
243struct ClaudeAgentConnection {
244 outgoing_tx: UnboundedSender<SdkMessage>,
245 end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<()>>>>>,
246 _mcp_server: Option<ClaudeMcpServer>,
247 _handler_task: Task<()>,
248}
249
250impl ClaudeAgentConnection {
251 async fn handle_message(
252 delegate: AcpClientDelegate,
253 message: SdkMessage,
254 end_turn_tx: Rc<RefCell<Option<oneshot::Sender<Result<()>>>>>,
255 tool_id_map: Rc<RefCell<HashMap<String, acp::ToolCallId>>>,
256 ) {
257 match message {
258 SdkMessage::Assistant { message, .. } | SdkMessage::User { message, .. } => {
259 for chunk in message.content.chunks() {
260 match chunk {
261 ContentChunk::Text { text } | ContentChunk::UntaggedText(text) => {
262 delegate
263 .stream_assistant_message_chunk(StreamAssistantMessageChunkParams {
264 chunk: acp::AssistantMessageChunk::Text { text },
265 })
266 .await
267 .log_err();
268 }
269 ContentChunk::ToolUse { id, name, input } => {
270 if let Some(resp) = delegate
271 .push_tool_call(ClaudeTool::infer(&name, input).as_acp())
272 .await
273 .log_err()
274 {
275 tool_id_map.borrow_mut().insert(id, resp.id);
276 }
277 }
278 ContentChunk::ToolResult {
279 content,
280 tool_use_id,
281 } => {
282 let id = tool_id_map.borrow_mut().remove(&tool_use_id);
283 if let Some(id) = id {
284 delegate
285 .update_tool_call(UpdateToolCallParams {
286 tool_call_id: id,
287 status: acp::ToolCallStatus::Finished,
288 content: Some(ToolCallContent::Markdown {
289 // For now we only include text content
290 markdown: content.to_string(),
291 }),
292 })
293 .await
294 .log_err();
295 }
296 }
297 ContentChunk::Image
298 | ContentChunk::Document
299 | ContentChunk::Thinking
300 | ContentChunk::RedactedThinking
301 | ContentChunk::WebSearchToolResult => {
302 delegate
303 .stream_assistant_message_chunk(StreamAssistantMessageChunkParams {
304 chunk: acp::AssistantMessageChunk::Text {
305 text: format!("Unsupported content: {:?}", chunk),
306 },
307 })
308 .await
309 .log_err();
310 }
311 }
312 }
313 }
314 SdkMessage::Result {
315 is_error, subtype, ..
316 } => {
317 if let Some(end_turn_tx) = end_turn_tx.borrow_mut().take() {
318 if is_error {
319 end_turn_tx.send(Err(anyhow!("Error: {subtype}"))).ok();
320 } else {
321 end_turn_tx.send(Ok(())).ok();
322 }
323 }
324 }
325 SdkMessage::System { .. } => {}
326 }
327 }
328
329 async fn handle_io(
330 mut outgoing_rx: UnboundedReceiver<SdkMessage>,
331 incoming_tx: UnboundedSender<SdkMessage>,
332 mut outgoing_bytes: impl Unpin + AsyncWrite,
333 incoming_bytes: impl Unpin + AsyncRead,
334 ) -> Result<()> {
335 let mut output_reader = BufReader::new(incoming_bytes);
336 let mut outgoing_line = Vec::new();
337 let mut incoming_line = String::new();
338 loop {
339 select_biased! {
340 message = outgoing_rx.next() => {
341 if let Some(message) = message {
342 outgoing_line.clear();
343 serde_json::to_writer(&mut outgoing_line, &message)?;
344 log::trace!("send: {}", String::from_utf8_lossy(&outgoing_line));
345 outgoing_line.push(b'\n');
346 outgoing_bytes.write_all(&outgoing_line).await.ok();
347 } else {
348 break;
349 }
350 }
351 bytes_read = output_reader.read_line(&mut incoming_line).fuse() => {
352 if bytes_read? == 0 {
353 break
354 }
355 log::trace!("recv: {}", &incoming_line);
356 match serde_json::from_str::<SdkMessage>(&incoming_line) {
357 Ok(message) => {
358 incoming_tx.unbounded_send(message).log_err();
359 }
360 Err(error) => {
361 log::error!("failed to parse incoming message: {error}. Raw: {incoming_line}");
362 }
363 }
364 incoming_line.clear();
365 }
366 }
367 }
368 Ok(())
369 }
370}
371
372#[derive(Debug, Clone, Serialize, Deserialize)]
373struct Message {
374 role: Role,
375 content: Content,
376 #[serde(skip_serializing_if = "Option::is_none")]
377 id: Option<String>,
378 #[serde(skip_serializing_if = "Option::is_none")]
379 model: Option<String>,
380 #[serde(skip_serializing_if = "Option::is_none")]
381 stop_reason: Option<String>,
382 #[serde(skip_serializing_if = "Option::is_none")]
383 stop_sequence: Option<String>,
384 #[serde(skip_serializing_if = "Option::is_none")]
385 usage: Option<Usage>,
386}
387
388#[derive(Debug, Clone, Serialize, Deserialize)]
389#[serde(untagged)]
390enum Content {
391 UntaggedText(String),
392 Chunks(Vec<ContentChunk>),
393}
394
395impl Content {
396 pub fn chunks(self) -> impl Iterator<Item = ContentChunk> {
397 match self {
398 Self::Chunks(chunks) => chunks.into_iter(),
399 Self::UntaggedText(text) => vec![ContentChunk::Text { text: text.clone() }].into_iter(),
400 }
401 }
402}
403
404impl Display for Content {
405 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
406 match self {
407 Content::UntaggedText(txt) => write!(f, "{}", txt),
408 Content::Chunks(chunks) => {
409 for chunk in chunks {
410 write!(f, "{}", chunk)?;
411 }
412 Ok(())
413 }
414 }
415 }
416}
417
418#[derive(Debug, Clone, Serialize, Deserialize)]
419#[serde(tag = "type", rename_all = "snake_case")]
420enum ContentChunk {
421 Text {
422 text: String,
423 },
424 ToolUse {
425 id: String,
426 name: String,
427 input: serde_json::Value,
428 },
429 ToolResult {
430 content: Content,
431 tool_use_id: String,
432 },
433 // TODO
434 Image,
435 Document,
436 Thinking,
437 RedactedThinking,
438 WebSearchToolResult,
439 #[serde(untagged)]
440 UntaggedText(String),
441}
442
443impl Display for ContentChunk {
444 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
445 match self {
446 ContentChunk::Text { text } => write!(f, "{}", text),
447 ContentChunk::UntaggedText(text) => write!(f, "{}", text),
448 ContentChunk::ToolResult { content, .. } => write!(f, "{}", content),
449 ContentChunk::Image
450 | ContentChunk::Document
451 | ContentChunk::Thinking
452 | ContentChunk::RedactedThinking
453 | ContentChunk::ToolUse { .. }
454 | ContentChunk::WebSearchToolResult => {
455 write!(f, "\n{:?}\n", &self)
456 }
457 }
458 }
459}
460
461#[derive(Debug, Clone, Serialize, Deserialize)]
462struct Usage {
463 input_tokens: u32,
464 cache_creation_input_tokens: u32,
465 cache_read_input_tokens: u32,
466 output_tokens: u32,
467 service_tier: String,
468}
469
470#[derive(Debug, Clone, Serialize, Deserialize)]
471#[serde(rename_all = "snake_case")]
472enum Role {
473 System,
474 Assistant,
475 User,
476}
477
478#[derive(Debug, Clone, Serialize, Deserialize)]
479struct MessageParam {
480 role: Role,
481 content: String,
482}
483
484#[derive(Debug, Clone, Serialize, Deserialize)]
485#[serde(tag = "type", rename_all = "snake_case")]
486enum SdkMessage {
487 // An assistant message
488 Assistant {
489 message: Message, // from Anthropic SDK
490 #[serde(skip_serializing_if = "Option::is_none")]
491 session_id: Option<String>,
492 },
493
494 // A user message
495 User {
496 message: Message, // from Anthropic SDK
497 #[serde(skip_serializing_if = "Option::is_none")]
498 session_id: Option<String>,
499 },
500
501 // Emitted as the last message in a conversation
502 Result {
503 subtype: ResultErrorType,
504 duration_ms: f64,
505 duration_api_ms: f64,
506 is_error: bool,
507 num_turns: i32,
508 #[serde(skip_serializing_if = "Option::is_none")]
509 result: Option<String>,
510 session_id: String,
511 total_cost_usd: f64,
512 },
513 // Emitted as the first message at the start of a conversation
514 System {
515 cwd: String,
516 session_id: String,
517 tools: Vec<String>,
518 model: String,
519 mcp_servers: Vec<McpServer>,
520 #[serde(rename = "apiKeySource")]
521 api_key_source: String,
522 #[serde(rename = "permissionMode")]
523 permission_mode: PermissionMode,
524 },
525}
526
527#[derive(Debug, Clone, Serialize, Deserialize)]
528#[serde(rename_all = "snake_case")]
529enum ResultErrorType {
530 Success,
531 ErrorMaxTurns,
532 ErrorDuringExecution,
533}
534
535impl Display for ResultErrorType {
536 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537 match self {
538 ResultErrorType::Success => write!(f, "success"),
539 ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
540 ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
541 }
542 }
543}
544
545#[derive(Debug, Clone, Serialize, Deserialize)]
546struct McpServer {
547 name: String,
548 status: String,
549}
550
551#[derive(Debug, Clone, Serialize, Deserialize)]
552#[serde(rename_all = "camelCase")]
553enum PermissionMode {
554 Default,
555 AcceptEdits,
556 BypassPermissions,
557 Plan,
558}
559
560#[derive(Serialize)]
561#[serde(rename_all = "camelCase")]
562struct McpConfig {
563 mcp_servers: HashMap<String, McpServerConfig>,
564}
565
566#[derive(Serialize)]
567#[serde(rename_all = "camelCase")]
568struct McpServerConfig {
569 command: String,
570 args: Vec<String>,
571 #[serde(skip_serializing_if = "Option::is_none")]
572 env: Option<HashMap<String, String>>,
573}
574
575#[cfg(test)]
576pub(crate) mod tests {
577 use super::*;
578 use serde_json::json;
579
580 // crate::common_e2e_tests!(ClaudeCode);
581
582 pub fn local_command() -> AgentServerCommand {
583 AgentServerCommand {
584 path: "claude".into(),
585 args: vec![],
586 env: None,
587 }
588 }
589
590 #[test]
591 fn test_deserialize_content_untagged_text() {
592 let json = json!("Hello, world!");
593 let content: Content = serde_json::from_value(json).unwrap();
594 match content {
595 Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
596 _ => panic!("Expected UntaggedText variant"),
597 }
598 }
599
600 #[test]
601 fn test_deserialize_content_chunks() {
602 let json = json!([
603 {
604 "type": "text",
605 "text": "Hello"
606 },
607 {
608 "type": "tool_use",
609 "id": "tool_123",
610 "name": "calculator",
611 "input": {"operation": "add", "a": 1, "b": 2}
612 }
613 ]);
614 let content: Content = serde_json::from_value(json).unwrap();
615 match content {
616 Content::Chunks(chunks) => {
617 assert_eq!(chunks.len(), 2);
618 match &chunks[0] {
619 ContentChunk::Text { text } => assert_eq!(text, "Hello"),
620 _ => panic!("Expected Text chunk"),
621 }
622 match &chunks[1] {
623 ContentChunk::ToolUse { id, name, input } => {
624 assert_eq!(id, "tool_123");
625 assert_eq!(name, "calculator");
626 assert_eq!(input["operation"], "add");
627 assert_eq!(input["a"], 1);
628 assert_eq!(input["b"], 2);
629 }
630 _ => panic!("Expected ToolUse chunk"),
631 }
632 }
633 _ => panic!("Expected Chunks variant"),
634 }
635 }
636
637 #[test]
638 fn test_deserialize_tool_result_untagged_text() {
639 let json = json!({
640 "type": "tool_result",
641 "content": "Result content",
642 "tool_use_id": "tool_456"
643 });
644 let chunk: ContentChunk = serde_json::from_value(json).unwrap();
645 match chunk {
646 ContentChunk::ToolResult {
647 content,
648 tool_use_id,
649 } => {
650 match content {
651 Content::UntaggedText(text) => assert_eq!(text, "Result content"),
652 _ => panic!("Expected UntaggedText content"),
653 }
654 assert_eq!(tool_use_id, "tool_456");
655 }
656 _ => panic!("Expected ToolResult variant"),
657 }
658 }
659
660 #[test]
661 fn test_deserialize_tool_result_chunks() {
662 let json = json!({
663 "type": "tool_result",
664 "content": [
665 {
666 "type": "text",
667 "text": "Processing complete"
668 },
669 {
670 "type": "text",
671 "text": "Result: 42"
672 }
673 ],
674 "tool_use_id": "tool_789"
675 });
676 let chunk: ContentChunk = serde_json::from_value(json).unwrap();
677 match chunk {
678 ContentChunk::ToolResult {
679 content,
680 tool_use_id,
681 } => {
682 match content {
683 Content::Chunks(chunks) => {
684 assert_eq!(chunks.len(), 2);
685 match &chunks[0] {
686 ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
687 _ => panic!("Expected Text chunk"),
688 }
689 match &chunks[1] {
690 ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
691 _ => panic!("Expected Text chunk"),
692 }
693 }
694 _ => panic!("Expected Chunks content"),
695 }
696 assert_eq!(tool_use_id, "tool_789");
697 }
698 _ => panic!("Expected ToolResult variant"),
699 }
700 }
701}