Skip to main content

claude_code_agent/
mcp.rs

1//! In-process (SDK) MCP servers — Rust functions exposed to Claude as tools.
2//!
3//! The CLI is told about each server with
4//! `--mcp-config {"mcpServers":{"<name>":{"type":"sdk","name":"<name>"}}}`
5//! (or later with `Session::set_mcp_servers`) and then forwards every
6//! JSON-RPC message for it as an `mcp_message` control request; the session
7//! answers with `{"mcp_response": <JSON-RPC response>}`.
8//! Claude sees the tools as `mcp__<server>__<tool>`.
9//!
10//! Source: `claude_agent_sdk` 0.1.48 `transport/subprocess_cli.py:240–260`,
11//!         _internal/query.py:305–320, :394–500; binary sdk MCP config schema
12use std::fmt;
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::Arc;
16use std::time::Duration;
17
18use dashmap::DashMap;
19use serde_json::{json, Value};
20use tokio::sync::oneshot;
21
22use crate::protocol::ToolDef;
23
24type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
25type ToolFn = Arc<dyn Fn(Value, ToolContext) -> BoxFuture<ToolResult> + Send + Sync>;
26
27const PROTOCOL_VERSION: &str = "2024-11-05";
28/// JSON-RPC error code for a request the client cancelled.
29const REQUEST_CANCELLED: i64 = -32800;
30
31/// One content item of a tool result. Source: MCP `CallToolResult.content`
32#[derive(Debug, Clone, PartialEq, serde::Serialize)]
33#[serde(tag = "type", rename_all = "snake_case")]
34pub enum ToolContent {
35    /// Plain text.
36    Text {
37        /// The text.
38        text: String,
39    },
40    /// Base64 image data, e.g. `mime_type` "image/png".
41    Image {
42        /// Base64-encoded image bytes.
43        data: String,
44        /// Image MIME type (`mimeType`).
45        #[serde(rename = "mimeType")]
46        mime_type: String,
47    },
48    /// An embedded resource: `{"uri", "mimeType", "text" | "blob"}`.
49    Resource {
50        /// The resource object.
51        resource: Value,
52    },
53    /// A link to a resource: `{"uri", "name", …}` fields.
54    ResourceLink(serde_json::Map<String, Value>),
55}
56
57/// Result of a tool call, returned to the model.
58#[derive(Debug, Clone, PartialEq)]
59pub struct ToolResult {
60    /// Content returned to the model.
61    pub content: Vec<ToolContent>,
62    /// Machine-readable output matching `ToolDef::output_schema`.
63    pub structured: Option<Value>,
64    /// The call failed (`isError`).
65    pub is_error: bool,
66}
67
68impl ToolResult {
69    /// A single text item.
70    pub fn text(text: impl Into<String>) -> Self {
71        Self::content(vec![ToolContent::Text { text: text.into() }])
72    }
73
74    /// A text item marked as an error.
75    pub fn error(text: impl Into<String>) -> Self {
76        Self { is_error: true, ..Self::text(text) }
77    }
78
79    /// A base64 image.
80    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
81        Self::content(vec![ToolContent::Image { data: data.into(), mime_type: mime_type.into() }])
82    }
83
84    /// A successful result with these items.
85    #[must_use]
86    pub fn content(content: Vec<ToolContent>) -> Self {
87        Self { content, structured: None, is_error: false }
88    }
89
90    /// Strings are passed through verbatim, anything else as JSON text.
91    #[must_use]
92    pub fn from_value(value: Value) -> Self {
93        match value {
94            Value::String(s) => Self::text(s),
95            other => Self::text(other.to_string()),
96        }
97    }
98
99    /// Attach structured output (also sent to the model as JSON text when
100    /// the result has no content).
101    #[must_use]
102    pub fn with_structured(mut self, value: Value) -> Self {
103        self.structured = Some(value);
104        self
105    }
106
107    fn into_wire(self) -> Value {
108        let content = if self.content.is_empty() {
109            let text = self.structured.as_ref().map(Value::to_string).unwrap_or_default();
110            vec![ToolContent::Text { text }]
111        } else {
112            self.content
113        };
114        let mut body = json!({ "content": content });
115        if let Some(s) = self.structured {
116            body["structuredContent"] = s;
117        }
118        if self.is_error {
119            body["isError"] = Value::Bool(true);
120        }
121        body
122    }
123}
124
125/// What a tool handler knows about its call besides the arguments.
126#[derive(Debug, Clone, Default)]
127pub struct ToolContext {
128    /// The model's `tool_use` id for this call.
129    pub tool_use_id: Option<String>,
130    /// The session id (`claudecode/sessionId` in `_meta`).
131    pub session_id: Option<String>,
132    /// The request's raw `_meta` object.
133    pub meta: Value,
134}
135
136impl ToolContext {
137    fn from_params(params: Option<&Value>) -> Self {
138        let meta = params.and_then(|p| p.get("_meta")).cloned().unwrap_or(Value::Null);
139        let field = |k: &str| meta.get(k).and_then(Value::as_str).map(str::to_owned);
140        Self { tool_use_id: field("claudecode/toolUseId"), session_id: field("claudecode/sessionId"), meta }
141    }
142}
143
144/// A tool definition plus the async function that runs it.
145/// `#[claude_tool]` generates `<fn>_tool() -> SdkTool`.
146///
147/// A call the CLI cancels (`notifications/cancelled`, e.g. after an
148/// interrupt) drops the handler's future, so `.await` points are where a
149/// handler stops.
150#[derive(Clone)]
151pub struct SdkTool {
152    /// Name, description and schemas sent to the CLI.
153    pub def: ToolDef,
154    handler: ToolFn,
155}
156
157impl fmt::Debug for SdkTool {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.debug_struct("SdkTool").field("name", &self.def.name).finish_non_exhaustive()
160    }
161}
162
163impl SdkTool {
164    /// `handler` receives the raw `arguments` object of the tool call.
165    pub fn new<F, Fut>(def: ToolDef, handler: F) -> Self
166    where
167        F: Fn(Value) -> Fut + Send + Sync + 'static,
168        Fut: Future<Output = ToolResult> + Send + 'static,
169    {
170        Self { def, handler: Arc::new(move |args, _ctx| Box::pin(handler(args))) }
171    }
172
173    /// Like `new`, with the call's `ToolContext` (`tool_use` id, session id).
174    pub fn with_context<F, Fut>(def: ToolDef, handler: F) -> Self
175    where
176        F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
177        Fut: Future<Output = ToolResult> + Send + 'static,
178    {
179        Self { def, handler: Arc::new(move |args, ctx| Box::pin(handler(args, ctx))) }
180    }
181}
182
183/// A named group of SDK tools, served in-process.
184#[derive(Debug, Clone)]
185pub struct SdkMcpServer {
186    /// Server name; tools are exposed as `mcp__<name>__<tool>`.
187    pub name: String,
188    /// `serverInfo.version` reported to the CLI. Default "1.0.0".
189    pub version: String,
190    /// Per-call timeout the CLI applies to this server's tools (≥ 1 s);
191    /// `None` = the CLI's `MCP_TOOL_TIMEOUT` or its default.
192    pub timeout: Option<Duration>,
193    tools: Vec<SdkTool>,
194    /// Running `tools/call`s by JSON-RPC id; firing one cancels the call.
195    in_flight: Arc<DashMap<String, oneshot::Sender<()>>>,
196}
197
198impl SdkMcpServer {
199    /// An empty server named `name`.
200    pub fn new(name: impl Into<String>) -> Self {
201        Self {
202            name: name.into(),
203            version: "1.0.0".into(),
204            timeout: None,
205            tools: vec![],
206            in_flight: Arc::new(DashMap::new()),
207        }
208    }
209
210    /// Add a tool.
211    #[must_use]
212    pub fn tool(mut self, tool: SdkTool) -> Self {
213        self.tools.push(tool);
214        self
215    }
216
217    /// Set the per-call timeout (`SdkMcpServer::timeout`).
218    #[must_use]
219    pub fn timeout(mut self, timeout: Duration) -> Self {
220        self.timeout = Some(timeout);
221        self
222    }
223
224    /// Fully qualified tool names as Claude sees them: `mcp__<server>__<tool>`.
225    #[must_use]
226    pub fn qualified_tool_names(&self) -> Vec<String> {
227        self.tools.iter().map(|t| format!("mcp__{}__{}", self.name, t.def.name)).collect()
228    }
229
230    /// This server's entry in an MCP server map (`--mcp-config`, `mcp_set_servers`).
231    pub(crate) fn config(&self) -> Value {
232        let mut config = json!({ "type": "sdk", "name": self.name });
233        if let Some(t) = self.timeout {
234            config["timeout"] = json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
235        }
236        config
237    }
238
239    /// Answer one JSON-RPC message from the CLI. Notifications get an empty
240    /// result: the control channel answers every `mcp_message`.
241    pub async fn handle(&self, message: &Value) -> Value {
242        let id = message.get("id").cloned().unwrap_or(Value::Null);
243        let method = message.get("method").and_then(Value::as_str).unwrap_or("");
244        let params = message.get("params");
245        match method {
246            "initialize" => rpc_result(id, json!({
247                "protocolVersion": PROTOCOL_VERSION,
248                "capabilities": { "tools": {} },
249                "serverInfo": { "name": self.name, "version": self.version },
250            })),
251            "ping" => rpc_result(id, json!({})),
252            "notifications/cancelled" => {
253                let request_id = params.and_then(|p| p.get("requestId")).map(Value::to_string);
254                if let Some((_, cancel)) = request_id.and_then(|rid| self.in_flight.remove(&rid)) {
255                    let _ = cancel.send(());
256                }
257                json!({ "jsonrpc": "2.0", "result": {} })
258            }
259            m if m.starts_with("notifications/") => json!({ "jsonrpc": "2.0", "result": {} }),
260            "tools/list" => {
261                let tools: Vec<Value> = self.tools.iter().map(|t| tool_listing(&t.def)).collect();
262                rpc_result(id, json!({ "tools": tools }))
263            }
264            "tools/call" => self.call_tool(id, params).await,
265            other => rpc_error(id, -32601, &format!("Method '{other}' not found")),
266        }
267    }
268
269    async fn call_tool(&self, id: Value, params: Option<&Value>) -> Value {
270        let name = params.and_then(|p| p.get("name")).and_then(Value::as_str).unwrap_or("");
271        let args = params.and_then(|p| p.get("arguments")).cloned().unwrap_or_else(|| json!({}));
272        let Some(tool) = self.tools.iter().find(|t| t.def.name == name) else {
273            return rpc_error(id, -32602, &format!("Tool '{name}' not found"));
274        };
275        let key = id.to_string();
276        let (cancel_tx, cancel_rx) = oneshot::channel();
277        self.in_flight.insert(key.clone(), cancel_tx);
278        // Unregisters also when this future is dropped mid-call.
279        let _registered = InFlightGuard { in_flight: &self.in_flight, key: &key };
280        let run = (tool.handler)(args, ToolContext::from_params(params));
281        let outcome = tokio::select! {
282            result = run => Some(result),
283            Ok(()) = cancel_rx => None,
284        };
285        match outcome {
286            Some(result) => rpc_result(id, result.into_wire()),
287            None => rpc_error(id, REQUEST_CANCELLED, "Request cancelled"),
288        }
289    }
290}
291
292/// Removes a tool call's cancel registration when dropped.
293struct InFlightGuard<'a> {
294    in_flight: &'a DashMap<String, oneshot::Sender<()>>,
295    key: &'a str,
296}
297
298impl Drop for InFlightGuard<'_> {
299    fn drop(&mut self) {
300        self.in_flight.remove(self.key);
301    }
302}
303
304fn tool_listing(def: &ToolDef) -> Value {
305    let mut tool = json!({
306        "name": def.name,
307        "description": def.description,
308        "inputSchema": def.input_schema.clone()
309            .unwrap_or_else(|| json!({ "type": "object", "properties": {} })),
310    });
311    if let Some(title) = &def.title {
312        tool["title"] = json!(title);
313    }
314    if let Some(schema) = &def.output_schema {
315        tool["outputSchema"] = schema.clone();
316    }
317    if let Some(annotations) = &def.annotations {
318        tool["annotations"] = json!(annotations);
319    }
320    tool
321}
322
323/// An MCP server map with `servers` as SDK entries plus `external` as given.
324pub(crate) fn server_map(servers: &[SdkMcpServer], external: Option<&serde_json::Map<String, Value>>) -> Value {
325    let mut map: serde_json::Map<String, Value> =
326        servers.iter().map(|s| (s.name.clone(), s.config())).collect();
327    if let Some(external) = external {
328        map.extend(external.iter().map(|(k, v)| (k.clone(), v.clone())));
329    }
330    Value::Object(map)
331}
332
333/// A JSON-RPC reply; `id` and `result` are moved in, not copied (`json!`
334/// would deep-copy a possibly large tool result).
335fn rpc_result(id: Value, result: Value) -> Value {
336    rpc_reply(id, "result", result)
337}
338
339fn rpc_error(id: Value, code: i64, message: &str) -> Value {
340    rpc_reply(id, "error", json!({ "code": code, "message": message }))
341}
342
343fn rpc_reply(id: Value, key: &str, payload: Value) -> Value {
344    let mut reply = serde_json::Map::with_capacity(3);
345    reply.insert("jsonrpc".into(), "2.0".into());
346    reply.insert("id".into(), id);
347    reply.insert(key.into(), payload);
348    Value::Object(reply)
349}