claude.rs

  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                                let content = content.to_string();
285                                delegate
286                                    .update_tool_call(UpdateToolCallParams {
287                                        tool_call_id: id,
288                                        status: acp::ToolCallStatus::Finished,
289                                        // Don't unset existing content
290                                        content: (!content.is_empty()).then_some(
291                                            ToolCallContent::Markdown {
292                                                // For now we only include text content
293                                                markdown: content,
294                                            },
295                                        ),
296                                    })
297                                    .await
298                                    .log_err();
299                            }
300                        }
301                        ContentChunk::Image
302                        | ContentChunk::Document
303                        | ContentChunk::Thinking
304                        | ContentChunk::RedactedThinking
305                        | ContentChunk::WebSearchToolResult => {
306                            delegate
307                                .stream_assistant_message_chunk(StreamAssistantMessageChunkParams {
308                                    chunk: acp::AssistantMessageChunk::Text {
309                                        text: format!("Unsupported content: {:?}", chunk),
310                                    },
311                                })
312                                .await
313                                .log_err();
314                        }
315                    }
316                }
317            }
318            SdkMessage::Result {
319                is_error, subtype, ..
320            } => {
321                if let Some(end_turn_tx) = end_turn_tx.borrow_mut().take() {
322                    if is_error {
323                        end_turn_tx.send(Err(anyhow!("Error: {subtype}"))).ok();
324                    } else {
325                        end_turn_tx.send(Ok(())).ok();
326                    }
327                }
328            }
329            SdkMessage::System { .. } => {}
330        }
331    }
332
333    async fn handle_io(
334        mut outgoing_rx: UnboundedReceiver<SdkMessage>,
335        incoming_tx: UnboundedSender<SdkMessage>,
336        mut outgoing_bytes: impl Unpin + AsyncWrite,
337        incoming_bytes: impl Unpin + AsyncRead,
338    ) -> Result<()> {
339        let mut output_reader = BufReader::new(incoming_bytes);
340        let mut outgoing_line = Vec::new();
341        let mut incoming_line = String::new();
342        loop {
343            select_biased! {
344                message = outgoing_rx.next() => {
345                    if let Some(message) = message {
346                        outgoing_line.clear();
347                        serde_json::to_writer(&mut outgoing_line, &message)?;
348                        log::trace!("send: {}", String::from_utf8_lossy(&outgoing_line));
349                        outgoing_line.push(b'\n');
350                        outgoing_bytes.write_all(&outgoing_line).await.ok();
351                    } else {
352                        break;
353                    }
354                }
355                bytes_read = output_reader.read_line(&mut incoming_line).fuse() => {
356                    if bytes_read? == 0 {
357                        break
358                    }
359                    log::trace!("recv: {}", &incoming_line);
360                    match serde_json::from_str::<SdkMessage>(&incoming_line) {
361                        Ok(message) => {
362                            incoming_tx.unbounded_send(message).log_err();
363                        }
364                        Err(error) => {
365                            log::error!("failed to parse incoming message: {error}. Raw: {incoming_line}");
366                        }
367                    }
368                    incoming_line.clear();
369                }
370            }
371        }
372        Ok(())
373    }
374}
375
376#[derive(Debug, Clone, Serialize, Deserialize)]
377struct Message {
378    role: Role,
379    content: Content,
380    #[serde(skip_serializing_if = "Option::is_none")]
381    id: Option<String>,
382    #[serde(skip_serializing_if = "Option::is_none")]
383    model: Option<String>,
384    #[serde(skip_serializing_if = "Option::is_none")]
385    stop_reason: Option<String>,
386    #[serde(skip_serializing_if = "Option::is_none")]
387    stop_sequence: Option<String>,
388    #[serde(skip_serializing_if = "Option::is_none")]
389    usage: Option<Usage>,
390}
391
392#[derive(Debug, Clone, Serialize, Deserialize)]
393#[serde(untagged)]
394enum Content {
395    UntaggedText(String),
396    Chunks(Vec<ContentChunk>),
397}
398
399impl Content {
400    pub fn chunks(self) -> impl Iterator<Item = ContentChunk> {
401        match self {
402            Self::Chunks(chunks) => chunks.into_iter(),
403            Self::UntaggedText(text) => vec![ContentChunk::Text { text: text.clone() }].into_iter(),
404        }
405    }
406}
407
408impl Display for Content {
409    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
410        match self {
411            Content::UntaggedText(txt) => write!(f, "{}", txt),
412            Content::Chunks(chunks) => {
413                for chunk in chunks {
414                    write!(f, "{}", chunk)?;
415                }
416                Ok(())
417            }
418        }
419    }
420}
421
422#[derive(Debug, Clone, Serialize, Deserialize)]
423#[serde(tag = "type", rename_all = "snake_case")]
424enum ContentChunk {
425    Text {
426        text: String,
427    },
428    ToolUse {
429        id: String,
430        name: String,
431        input: serde_json::Value,
432    },
433    ToolResult {
434        content: Content,
435        tool_use_id: String,
436    },
437    // TODO
438    Image,
439    Document,
440    Thinking,
441    RedactedThinking,
442    WebSearchToolResult,
443    #[serde(untagged)]
444    UntaggedText(String),
445}
446
447impl Display for ContentChunk {
448    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449        match self {
450            ContentChunk::Text { text } => write!(f, "{}", text),
451            ContentChunk::UntaggedText(text) => write!(f, "{}", text),
452            ContentChunk::ToolResult { content, .. } => write!(f, "{}", content),
453            ContentChunk::Image
454            | ContentChunk::Document
455            | ContentChunk::Thinking
456            | ContentChunk::RedactedThinking
457            | ContentChunk::ToolUse { .. }
458            | ContentChunk::WebSearchToolResult => {
459                write!(f, "\n{:?}\n", &self)
460            }
461        }
462    }
463}
464
465#[derive(Debug, Clone, Serialize, Deserialize)]
466struct Usage {
467    input_tokens: u32,
468    cache_creation_input_tokens: u32,
469    cache_read_input_tokens: u32,
470    output_tokens: u32,
471    service_tier: String,
472}
473
474#[derive(Debug, Clone, Serialize, Deserialize)]
475#[serde(rename_all = "snake_case")]
476enum Role {
477    System,
478    Assistant,
479    User,
480}
481
482#[derive(Debug, Clone, Serialize, Deserialize)]
483struct MessageParam {
484    role: Role,
485    content: String,
486}
487
488#[derive(Debug, Clone, Serialize, Deserialize)]
489#[serde(tag = "type", rename_all = "snake_case")]
490enum SdkMessage {
491    // An assistant message
492    Assistant {
493        message: Message, // from Anthropic SDK
494        #[serde(skip_serializing_if = "Option::is_none")]
495        session_id: Option<String>,
496    },
497
498    // A user message
499    User {
500        message: Message, // from Anthropic SDK
501        #[serde(skip_serializing_if = "Option::is_none")]
502        session_id: Option<String>,
503    },
504
505    // Emitted as the last message in a conversation
506    Result {
507        subtype: ResultErrorType,
508        duration_ms: f64,
509        duration_api_ms: f64,
510        is_error: bool,
511        num_turns: i32,
512        #[serde(skip_serializing_if = "Option::is_none")]
513        result: Option<String>,
514        session_id: String,
515        total_cost_usd: f64,
516    },
517    // Emitted as the first message at the start of a conversation
518    System {
519        cwd: String,
520        session_id: String,
521        tools: Vec<String>,
522        model: String,
523        mcp_servers: Vec<McpServer>,
524        #[serde(rename = "apiKeySource")]
525        api_key_source: String,
526        #[serde(rename = "permissionMode")]
527        permission_mode: PermissionMode,
528    },
529}
530
531#[derive(Debug, Clone, Serialize, Deserialize)]
532#[serde(rename_all = "snake_case")]
533enum ResultErrorType {
534    Success,
535    ErrorMaxTurns,
536    ErrorDuringExecution,
537}
538
539impl Display for ResultErrorType {
540    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
541        match self {
542            ResultErrorType::Success => write!(f, "success"),
543            ResultErrorType::ErrorMaxTurns => write!(f, "error_max_turns"),
544            ResultErrorType::ErrorDuringExecution => write!(f, "error_during_execution"),
545        }
546    }
547}
548
549#[derive(Debug, Clone, Serialize, Deserialize)]
550struct McpServer {
551    name: String,
552    status: String,
553}
554
555#[derive(Debug, Clone, Serialize, Deserialize)]
556#[serde(rename_all = "camelCase")]
557enum PermissionMode {
558    Default,
559    AcceptEdits,
560    BypassPermissions,
561    Plan,
562}
563
564#[derive(Serialize)]
565#[serde(rename_all = "camelCase")]
566struct McpConfig {
567    mcp_servers: HashMap<String, McpServerConfig>,
568}
569
570#[derive(Serialize)]
571#[serde(rename_all = "camelCase")]
572struct McpServerConfig {
573    command: String,
574    args: Vec<String>,
575    #[serde(skip_serializing_if = "Option::is_none")]
576    env: Option<HashMap<String, String>>,
577}
578
579#[cfg(test)]
580pub(crate) mod tests {
581    use super::*;
582    use serde_json::json;
583
584    crate::common_e2e_tests!(ClaudeCode);
585
586    pub fn local_command() -> AgentServerCommand {
587        AgentServerCommand {
588            path: "claude".into(),
589            args: vec![],
590            env: None,
591        }
592    }
593
594    #[test]
595    fn test_deserialize_content_untagged_text() {
596        let json = json!("Hello, world!");
597        let content: Content = serde_json::from_value(json).unwrap();
598        match content {
599            Content::UntaggedText(text) => assert_eq!(text, "Hello, world!"),
600            _ => panic!("Expected UntaggedText variant"),
601        }
602    }
603
604    #[test]
605    fn test_deserialize_content_chunks() {
606        let json = json!([
607            {
608                "type": "text",
609                "text": "Hello"
610            },
611            {
612                "type": "tool_use",
613                "id": "tool_123",
614                "name": "calculator",
615                "input": {"operation": "add", "a": 1, "b": 2}
616            }
617        ]);
618        let content: Content = serde_json::from_value(json).unwrap();
619        match content {
620            Content::Chunks(chunks) => {
621                assert_eq!(chunks.len(), 2);
622                match &chunks[0] {
623                    ContentChunk::Text { text } => assert_eq!(text, "Hello"),
624                    _ => panic!("Expected Text chunk"),
625                }
626                match &chunks[1] {
627                    ContentChunk::ToolUse { id, name, input } => {
628                        assert_eq!(id, "tool_123");
629                        assert_eq!(name, "calculator");
630                        assert_eq!(input["operation"], "add");
631                        assert_eq!(input["a"], 1);
632                        assert_eq!(input["b"], 2);
633                    }
634                    _ => panic!("Expected ToolUse chunk"),
635                }
636            }
637            _ => panic!("Expected Chunks variant"),
638        }
639    }
640
641    #[test]
642    fn test_deserialize_tool_result_untagged_text() {
643        let json = json!({
644            "type": "tool_result",
645            "content": "Result content",
646            "tool_use_id": "tool_456"
647        });
648        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
649        match chunk {
650            ContentChunk::ToolResult {
651                content,
652                tool_use_id,
653            } => {
654                match content {
655                    Content::UntaggedText(text) => assert_eq!(text, "Result content"),
656                    _ => panic!("Expected UntaggedText content"),
657                }
658                assert_eq!(tool_use_id, "tool_456");
659            }
660            _ => panic!("Expected ToolResult variant"),
661        }
662    }
663
664    #[test]
665    fn test_deserialize_tool_result_chunks() {
666        let json = json!({
667            "type": "tool_result",
668            "content": [
669                {
670                    "type": "text",
671                    "text": "Processing complete"
672                },
673                {
674                    "type": "text",
675                    "text": "Result: 42"
676                }
677            ],
678            "tool_use_id": "tool_789"
679        });
680        let chunk: ContentChunk = serde_json::from_value(json).unwrap();
681        match chunk {
682            ContentChunk::ToolResult {
683                content,
684                tool_use_id,
685            } => {
686                match content {
687                    Content::Chunks(chunks) => {
688                        assert_eq!(chunks.len(), 2);
689                        match &chunks[0] {
690                            ContentChunk::Text { text } => assert_eq!(text, "Processing complete"),
691                            _ => panic!("Expected Text chunk"),
692                        }
693                        match &chunks[1] {
694                            ContentChunk::Text { text } => assert_eq!(text, "Result: 42"),
695                            _ => panic!("Expected Text chunk"),
696                        }
697                    }
698                    _ => panic!("Expected Chunks content"),
699                }
700                assert_eq!(tool_use_id, "tool_789");
701            }
702            _ => panic!("Expected ToolResult variant"),
703        }
704    }
705}