1use std::path::PathBuf;
2
3use acp_thread::AcpThread;
4use agent_client_protocol as acp;
5use anyhow::{Context, Result};
6use collections::HashMap;
7use context_server::types::{
8 CallToolParams, CallToolResponse, Implementation, InitializeParams, InitializeResponse,
9 ListToolsResponse, ProtocolVersion, ServerCapabilities, Tool, ToolAnnotations,
10 ToolResponseContent, ToolsCapabilities, requests,
11};
12use gpui::{App, AsyncApp, Entity, Task, WeakEntity};
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15
16use crate::claude::tools::{ClaudeTool, EditToolParams, ReadToolParams};
17
18pub struct ClaudeZedMcpServer {
19 server: context_server::listener::McpServer,
20}
21
22pub const SERVER_NAME: &str = "zed";
23pub const READ_TOOL: &str = "Read";
24pub const EDIT_TOOL: &str = "Edit";
25pub const PERMISSION_TOOL: &str = "Confirmation";
26
27#[derive(Deserialize, JsonSchema, Debug)]
28struct PermissionToolParams {
29 tool_name: String,
30 input: serde_json::Value,
31 tool_use_id: Option<String>,
32}
33
34#[derive(Serialize)]
35#[serde(rename_all = "camelCase")]
36struct PermissionToolResponse {
37 behavior: PermissionToolBehavior,
38 updated_input: serde_json::Value,
39}
40
41#[derive(Serialize)]
42#[serde(rename_all = "snake_case")]
43enum PermissionToolBehavior {
44 Allow,
45 Deny,
46}
47
48impl ClaudeZedMcpServer {
49 pub async fn new(
50 thread_rx: watch::Receiver<WeakEntity<AcpThread>>,
51 cx: &AsyncApp,
52 ) -> Result<Self> {
53 let mut mcp_server = context_server::listener::McpServer::new(cx).await?;
54 mcp_server.handle_request::<requests::Initialize>(Self::handle_initialize);
55 mcp_server.handle_request::<requests::ListTools>(Self::handle_list_tools);
56 mcp_server.handle_request::<requests::CallTool>(move |request, cx| {
57 Self::handle_call_tool(request, thread_rx.clone(), cx)
58 });
59
60 Ok(Self { server: mcp_server })
61 }
62
63 pub fn server_config(&self) -> Result<McpServerConfig> {
64 let zed_path = std::env::current_exe()
65 .context("finding current executable path for use in mcp_server")?;
66
67 Ok(McpServerConfig {
68 command: zed_path,
69 args: vec![
70 "--nc".into(),
71 self.server.socket_path().display().to_string(),
72 ],
73 env: None,
74 })
75 }
76
77 fn handle_initialize(_: InitializeParams, cx: &App) -> Task<Result<InitializeResponse>> {
78 cx.foreground_executor().spawn(async move {
79 Ok(InitializeResponse {
80 protocol_version: ProtocolVersion("2025-06-18".into()),
81 capabilities: ServerCapabilities {
82 experimental: None,
83 logging: None,
84 completions: None,
85 prompts: None,
86 resources: None,
87 tools: Some(ToolsCapabilities {
88 list_changed: Some(false),
89 }),
90 },
91 server_info: Implementation {
92 name: SERVER_NAME.into(),
93 version: "0.1.0".into(),
94 },
95 meta: None,
96 })
97 })
98 }
99
100 fn handle_list_tools(_: (), cx: &App) -> Task<Result<ListToolsResponse>> {
101 cx.foreground_executor().spawn(async move {
102 Ok(ListToolsResponse {
103 tools: vec![
104 Tool {
105 name: PERMISSION_TOOL.into(),
106 input_schema: schemars::schema_for!(PermissionToolParams).into(),
107 description: None,
108 annotations: None,
109 },
110 Tool {
111 name: READ_TOOL.into(),
112 input_schema: schemars::schema_for!(ReadToolParams).into(),
113 description: Some("Read the contents of a file. In sessions with mcp__zed__Read always use it instead of Read as it contains the most up-to-date contents.".to_string()),
114 annotations: Some(ToolAnnotations {
115 title: Some("Read file".to_string()),
116 read_only_hint: Some(true),
117 destructive_hint: Some(false),
118 open_world_hint: Some(false),
119 // if time passes the contents might change, but it's not going to do anything different
120 // true or false seem too strong, let's try a none.
121 idempotent_hint: None,
122 }),
123 },
124 Tool {
125 name: EDIT_TOOL.into(),
126 input_schema: schemars::schema_for!(EditToolParams).into(),
127 description: Some("Edits a file. In sessions with mcp__zed__Edit always use it instead of Edit as it will show the diff to the user better.".to_string()),
128 annotations: Some(ToolAnnotations {
129 title: Some("Edit file".to_string()),
130 read_only_hint: Some(false),
131 destructive_hint: Some(false),
132 open_world_hint: Some(false),
133 idempotent_hint: Some(false),
134 }),
135 },
136 ],
137 next_cursor: None,
138 meta: None,
139 })
140 })
141 }
142
143 fn handle_call_tool(
144 request: CallToolParams,
145 mut thread_rx: watch::Receiver<WeakEntity<AcpThread>>,
146 cx: &App,
147 ) -> Task<Result<CallToolResponse>> {
148 cx.spawn(async move |cx| {
149 let Some(thread) = thread_rx.recv().await?.upgrade() else {
150 anyhow::bail!("Thread closed");
151 };
152
153 if request.name.as_str() == PERMISSION_TOOL {
154 let input =
155 serde_json::from_value(request.arguments.context("Arguments required")?)?;
156
157 let result = Self::handle_permissions_tool_call(input, thread, cx).await?;
158 Ok(CallToolResponse {
159 content: vec![ToolResponseContent::Text {
160 text: serde_json::to_string(&result)?,
161 }],
162 is_error: None,
163 meta: None,
164 })
165 } else if request.name.as_str() == READ_TOOL {
166 let input =
167 serde_json::from_value(request.arguments.context("Arguments required")?)?;
168
169 let content = Self::handle_read_tool_call(input, thread, cx).await?;
170 Ok(CallToolResponse {
171 content,
172 is_error: None,
173 meta: None,
174 })
175 } else if request.name.as_str() == EDIT_TOOL {
176 let input =
177 serde_json::from_value(request.arguments.context("Arguments required")?)?;
178
179 Self::handle_edit_tool_call(input, thread, cx).await?;
180 Ok(CallToolResponse {
181 content: vec![],
182 is_error: None,
183 meta: None,
184 })
185 } else {
186 anyhow::bail!("Unsupported tool");
187 }
188 })
189 }
190
191 fn handle_read_tool_call(
192 ReadToolParams {
193 abs_path,
194 offset,
195 limit,
196 }: ReadToolParams,
197 thread: Entity<AcpThread>,
198 cx: &AsyncApp,
199 ) -> Task<Result<Vec<ToolResponseContent>>> {
200 cx.spawn(async move |cx| {
201 let content = thread
202 .update(cx, |thread, cx| {
203 thread.read_text_file(abs_path, offset, limit, false, cx)
204 })?
205 .await?;
206
207 Ok(vec![ToolResponseContent::Text { text: content }])
208 })
209 }
210
211 fn handle_edit_tool_call(
212 params: EditToolParams,
213 thread: Entity<AcpThread>,
214 cx: &AsyncApp,
215 ) -> Task<Result<()>> {
216 cx.spawn(async move |cx| {
217 let content = thread
218 .update(cx, |threads, cx| {
219 threads.read_text_file(params.abs_path.clone(), None, None, true, cx)
220 })?
221 .await?;
222
223 let new_content = content.replace(¶ms.old_text, ¶ms.new_text);
224 if new_content == content {
225 return Err(anyhow::anyhow!("The old_text was not found in the content"));
226 }
227
228 thread
229 .update(cx, |threads, cx| {
230 threads.write_text_file(params.abs_path, new_content, cx)
231 })?
232 .await?;
233
234 Ok(())
235 })
236 }
237
238 fn handle_permissions_tool_call(
239 params: PermissionToolParams,
240 thread: Entity<AcpThread>,
241 cx: &AsyncApp,
242 ) -> Task<Result<PermissionToolResponse>> {
243 cx.spawn(async move |cx| {
244 let claude_tool = ClaudeTool::infer(¶ms.tool_name, params.input.clone());
245
246 let tool_call_id =
247 acp::ToolCallId(params.tool_use_id.context("Tool ID required")?.into());
248
249 let allow_option_id = acp::PermissionOptionId("allow".into());
250 let reject_option_id = acp::PermissionOptionId("reject".into());
251
252 let chosen_option = thread
253 .update(cx, |thread, cx| {
254 thread.request_tool_call_permission(
255 claude_tool.as_acp(tool_call_id),
256 vec![
257 acp::PermissionOption {
258 id: allow_option_id.clone(),
259 label: "Allow".into(),
260 kind: acp::PermissionOptionKind::AllowOnce,
261 },
262 acp::PermissionOption {
263 id: reject_option_id,
264 label: "Reject".into(),
265 kind: acp::PermissionOptionKind::RejectOnce,
266 },
267 ],
268 cx,
269 )
270 })?
271 .await?;
272
273 if chosen_option == allow_option_id {
274 Ok(PermissionToolResponse {
275 behavior: PermissionToolBehavior::Allow,
276 updated_input: params.input,
277 })
278 } else {
279 Ok(PermissionToolResponse {
280 behavior: PermissionToolBehavior::Deny,
281 updated_input: params.input,
282 })
283 }
284 })
285 }
286}
287
288#[derive(Serialize)]
289#[serde(rename_all = "camelCase")]
290pub struct McpConfig {
291 pub mcp_servers: HashMap<String, McpServerConfig>,
292}
293
294#[derive(Serialize, Clone)]
295#[serde(rename_all = "camelCase")]
296pub struct McpServerConfig {
297 pub command: PathBuf,
298 pub args: Vec<String>,
299 #[serde(skip_serializing_if = "Option::is_none")]
300 pub env: Option<HashMap<String, String>>,
301}