1use 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";
28const REQUEST_CANCELLED: i64 = -32800;
30
31#[derive(Debug, Clone, PartialEq, serde::Serialize)]
33#[serde(tag = "type", rename_all = "snake_case")]
34pub enum ToolContent {
35 Text {
37 text: String,
39 },
40 Image {
42 data: String,
44 #[serde(rename = "mimeType")]
46 mime_type: String,
47 },
48 Resource {
50 resource: Value,
52 },
53 ResourceLink(serde_json::Map<String, Value>),
55}
56
57#[derive(Debug, Clone, PartialEq)]
59pub struct ToolResult {
60 pub content: Vec<ToolContent>,
62 pub structured: Option<Value>,
64 pub is_error: bool,
66}
67
68impl ToolResult {
69 pub fn text(text: impl Into<String>) -> Self {
71 Self::content(vec![ToolContent::Text { text: text.into() }])
72 }
73
74 pub fn error(text: impl Into<String>) -> Self {
76 Self { is_error: true, ..Self::text(text) }
77 }
78
79 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 #[must_use]
86 pub fn content(content: Vec<ToolContent>) -> Self {
87 Self { content, structured: None, is_error: false }
88 }
89
90 #[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 #[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#[derive(Debug, Clone, Default)]
127pub struct ToolContext {
128 pub tool_use_id: Option<String>,
130 pub session_id: Option<String>,
135 pub meta: Value,
137}
138
139impl ToolContext {
140 fn from_params(params: Option<&Value>, session_id: Option<String>) -> Self {
141 let meta = params.and_then(|p| p.get("_meta")).cloned().unwrap_or(Value::Null);
142 let field = |k: &str| meta.get(k).and_then(Value::as_str).map(str::to_owned);
143 Self {
144 tool_use_id: field("claudecode/toolUseId"),
145 session_id: field("claudecode/sessionId").or(session_id),
146 meta,
147 }
148 }
149}
150
151#[derive(Clone)]
158pub struct SdkTool {
159 pub def: ToolDef,
161 handler: ToolFn,
162}
163
164impl fmt::Debug for SdkTool {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 f.debug_struct("SdkTool").field("name", &self.def.name).finish_non_exhaustive()
167 }
168}
169
170impl SdkTool {
171 pub fn new<F, Fut>(def: ToolDef, handler: F) -> Self
173 where
174 F: Fn(Value) -> Fut + Send + Sync + 'static,
175 Fut: Future<Output = ToolResult> + Send + 'static,
176 {
177 Self { def, handler: Arc::new(move |args, _ctx| Box::pin(handler(args))) }
178 }
179
180 pub fn with_context<F, Fut>(def: ToolDef, handler: F) -> Self
182 where
183 F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
184 Fut: Future<Output = ToolResult> + Send + 'static,
185 {
186 Self { def, handler: Arc::new(move |args, ctx| Box::pin(handler(args, ctx))) }
187 }
188}
189
190#[derive(Debug, Clone)]
192pub struct SdkMcpServer {
193 pub name: String,
195 pub version: String,
197 pub timeout: Option<Duration>,
200 tools: Vec<SdkTool>,
201 in_flight: Arc<DashMap<String, oneshot::Sender<()>>>,
205}
206
207impl SdkMcpServer {
208 pub fn new(name: impl Into<String>) -> Self {
210 Self {
211 name: name.into(),
212 version: "1.0.0".into(),
213 timeout: None,
214 tools: vec![],
215 in_flight: Arc::new(DashMap::new()),
216 }
217 }
218
219 #[must_use]
221 pub fn tool(mut self, tool: SdkTool) -> Self {
222 self.tools.push(tool);
223 self
224 }
225
226 #[must_use]
228 pub fn timeout(mut self, timeout: Duration) -> Self {
229 self.timeout = Some(timeout);
230 self
231 }
232
233 #[must_use]
235 pub fn qualified_tool_names(&self) -> Vec<String> {
236 self.tools.iter().map(|t| format!("mcp__{}__{}", self.name, t.def.name)).collect()
237 }
238
239 pub(crate) fn for_session(&self) -> Self {
242 Self { in_flight: Arc::new(DashMap::new()), ..self.clone() }
243 }
244
245 pub(crate) fn config(&self) -> Value {
247 let mut config = json!({ "type": "sdk", "name": self.name });
248 if let Some(t) = self.timeout {
249 config["timeout"] = json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
250 }
251 config
252 }
253
254 pub async fn handle(&self, message: &Value) -> Value {
257 self.handle_in_session(message, None).await
258 }
259
260 pub(crate) async fn handle_in_session(&self, message: &Value, session_id: Option<String>) -> Value {
262 let id = message.get("id").cloned().unwrap_or(Value::Null);
263 let method = message.get("method").and_then(Value::as_str).unwrap_or("");
264 let params = message.get("params");
265 match method {
266 "initialize" => rpc_result(id, json!({
267 "protocolVersion": PROTOCOL_VERSION,
268 "capabilities": { "tools": {} },
269 "serverInfo": { "name": self.name, "version": self.version },
270 })),
271 "ping" => rpc_result(id, json!({})),
272 "notifications/cancelled" => {
273 let request_id = params.and_then(|p| p.get("requestId")).map(Value::to_string);
274 if let Some((_, cancel)) = request_id.and_then(|rid| self.in_flight.remove(&rid)) {
275 let _ = cancel.send(());
276 }
277 json!({ "jsonrpc": "2.0", "result": {} })
278 }
279 m if m.starts_with("notifications/") => json!({ "jsonrpc": "2.0", "result": {} }),
280 "tools/list" => {
281 let tools: Vec<Value> = self.tools.iter().map(|t| tool_listing(&t.def)).collect();
282 rpc_result(id, json!({ "tools": tools }))
283 }
284 "tools/call" => self.call_tool(id, params, session_id).await,
285 other => rpc_error(id, -32601, &format!("Method '{other}' not found")),
286 }
287 }
288
289 async fn call_tool(&self, id: Value, params: Option<&Value>, session_id: Option<String>) -> Value {
290 let name = params.and_then(|p| p.get("name")).and_then(Value::as_str).unwrap_or("");
291 let args = params.and_then(|p| p.get("arguments")).cloned().unwrap_or_else(|| json!({}));
292 let Some(tool) = self.tools.iter().find(|t| t.def.name == name) else {
293 return rpc_error(id, -32602, &format!("Tool '{name}' not found"));
294 };
295 let key = id.to_string();
296 let (cancel_tx, cancel_rx) = oneshot::channel();
297 self.in_flight.insert(key.clone(), cancel_tx);
298 let _registered = InFlightGuard { in_flight: &self.in_flight, key: &key };
300 let run = (tool.handler)(args, ToolContext::from_params(params, session_id));
301 let outcome = tokio::select! {
302 result = run => Some(result),
303 Ok(()) = cancel_rx => None,
304 };
305 match outcome {
306 Some(result) => rpc_result(id, result.into_wire()),
307 None => rpc_error(id, REQUEST_CANCELLED, "Request cancelled"),
308 }
309 }
310}
311
312struct InFlightGuard<'a> {
314 in_flight: &'a DashMap<String, oneshot::Sender<()>>,
315 key: &'a str,
316}
317
318impl Drop for InFlightGuard<'_> {
319 fn drop(&mut self) {
320 self.in_flight.remove(self.key);
321 }
322}
323
324fn tool_listing(def: &ToolDef) -> Value {
325 let mut tool = json!({
326 "name": def.name,
327 "description": def.description,
328 "inputSchema": def.input_schema.clone()
329 .unwrap_or_else(|| json!({ "type": "object", "properties": {} })),
330 });
331 if let Some(title) = &def.title {
332 tool["title"] = json!(title);
333 }
334 if let Some(schema) = &def.output_schema {
335 tool["outputSchema"] = schema.clone();
336 }
337 if let Some(annotations) = &def.annotations {
338 tool["annotations"] = json!(annotations);
339 }
340 tool
341}
342
343pub(crate) fn server_map(servers: &[SdkMcpServer], external: Option<&serde_json::Map<String, Value>>) -> Value {
345 let mut map: serde_json::Map<String, Value> =
346 servers.iter().map(|s| (s.name.clone(), s.config())).collect();
347 if let Some(external) = external {
348 map.extend(external.iter().map(|(k, v)| (k.clone(), v.clone())));
349 }
350 Value::Object(map)
351}
352
353fn rpc_result(id: Value, result: Value) -> Value {
356 rpc_reply(id, "result", result)
357}
358
359fn rpc_error(id: Value, code: i64, message: &str) -> Value {
360 rpc_reply(id, "error", json!({ "code": code, "message": message }))
361}
362
363fn rpc_reply(id: Value, key: &str, payload: Value) -> Value {
364 let mut reply = serde_json::Map::with_capacity(3);
365 reply.insert("jsonrpc".into(), "2.0".into());
366 reply.insert("id".into(), id);
367 reply.insert(key.into(), payload);
368 Value::Object(reply)
369}