1use std::fmt;
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::atomic::{AtomicU64, Ordering};
16use std::sync::Arc;
17use std::time::Duration;
18
19use dashmap::DashMap;
20use serde_json::{json, Value};
21use tokio::sync::oneshot;
22
23use crate::protocol::ToolDef;
24
25type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
26type ToolFn = Arc<dyn Fn(Value, ToolContext) -> BoxFuture<ToolResult> + Send + Sync>;
27
28const PROTOCOL_VERSION: &str = "2024-11-05";
29const REQUEST_CANCELLED: i64 = -32800;
31
32#[derive(Debug, Clone, PartialEq, serde::Serialize)]
34#[serde(tag = "type", rename_all = "snake_case")]
35pub enum ToolContent {
36 Text {
38 text: String,
40 },
41 Image {
43 data: String,
45 #[serde(rename = "mimeType")]
47 mime_type: String,
48 },
49 Resource {
51 resource: Value,
53 },
54 ResourceLink(serde_json::Map<String, Value>),
56}
57
58#[derive(Debug, Clone, PartialEq)]
60pub struct ToolResult {
61 pub content: Vec<ToolContent>,
63 pub structured: Option<Value>,
65 pub is_error: bool,
67}
68
69impl ToolResult {
70 pub fn text(text: impl Into<String>) -> Self {
72 Self::content(vec![ToolContent::Text { text: text.into() }])
73 }
74
75 pub fn error(text: impl Into<String>) -> Self {
77 Self { is_error: true, ..Self::text(text) }
78 }
79
80 pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
82 Self::content(vec![ToolContent::Image { data: data.into(), mime_type: mime_type.into() }])
83 }
84
85 #[must_use]
87 pub fn content(content: Vec<ToolContent>) -> Self {
88 Self { content, structured: None, is_error: false }
89 }
90
91 #[must_use]
93 pub fn from_value(value: Value) -> Self {
94 match value {
95 Value::String(s) => Self::text(s),
96 other => Self::text(other.to_string()),
97 }
98 }
99
100 #[must_use]
103 pub fn with_structured(mut self, value: Value) -> Self {
104 self.structured = Some(value);
105 self
106 }
107
108 fn into_wire(self) -> Value {
109 let content = if self.content.is_empty() {
110 let text = self.structured.as_ref().map(Value::to_string).unwrap_or_default();
111 vec![ToolContent::Text { text }]
112 } else {
113 self.content
114 };
115 let mut body = json!({ "content": content });
116 if let Some(s) = self.structured {
117 body["structuredContent"] = s;
118 }
119 if self.is_error {
120 body["isError"] = Value::Bool(true);
121 }
122 body
123 }
124}
125
126#[derive(Debug, Clone, Default)]
128pub struct ToolContext {
129 pub tool_use_id: Option<String>,
131 pub session_id: Option<String>,
136 pub meta: Value,
138}
139
140impl ToolContext {
141 fn from_params(params: Option<&Value>, session_id: Option<String>) -> Self {
142 let meta = params.and_then(|p| p.get("_meta")).cloned().unwrap_or(Value::Null);
143 let field = |k: &str| meta.get(k).and_then(Value::as_str).map(str::to_owned);
144 Self {
145 tool_use_id: field("claudecode/toolUseId"),
146 session_id: field("claudecode/sessionId").or(session_id),
147 meta,
148 }
149 }
150}
151
152#[derive(Clone)]
159pub struct SdkTool {
160 pub def: ToolDef,
162 handler: ToolFn,
163}
164
165impl fmt::Debug for SdkTool {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.debug_struct("SdkTool").field("name", &self.def.name).finish_non_exhaustive()
168 }
169}
170
171impl SdkTool {
172 pub fn new<F, Fut>(def: ToolDef, handler: F) -> Self
174 where
175 F: Fn(Value) -> Fut + Send + Sync + 'static,
176 Fut: Future<Output = ToolResult> + Send + 'static,
177 {
178 Self { def, handler: Arc::new(move |args, _ctx| Box::pin(handler(args))) }
179 }
180
181 pub fn with_context<F, Fut>(def: ToolDef, handler: F) -> Self
183 where
184 F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
185 Fut: Future<Output = ToolResult> + Send + 'static,
186 {
187 Self { def, handler: Arc::new(move |args, ctx| Box::pin(handler(args, ctx))) }
188 }
189}
190
191#[derive(Debug, Clone)]
193pub struct SdkMcpServer {
194 pub name: String,
196 pub version: String,
198 pub timeout: Option<Duration>,
201 tools: Vec<SdkTool>,
202 in_flight: Arc<InFlight>,
206}
207
208type InFlight = DashMap<String, (u64, oneshot::Sender<()>)>;
212
213static NEXT_CALL: AtomicU64 = AtomicU64::new(0);
215
216pub(crate) struct CallRegistration {
219 in_flight: Arc<InFlight>,
220 key: String,
221 tag: u64,
222 cancelled: oneshot::Receiver<()>,
223}
224
225impl Drop for CallRegistration {
226 fn drop(&mut self) {
227 self.in_flight.remove_if(&self.key, |_, (tag, _)| *tag == self.tag);
228 }
229}
230
231impl SdkMcpServer {
232 pub fn new(name: impl Into<String>) -> Self {
234 Self {
235 name: name.into(),
236 version: "1.0.0".into(),
237 timeout: None,
238 tools: vec![],
239 in_flight: Arc::new(InFlight::new()),
240 }
241 }
242
243 #[must_use]
245 pub fn tool(mut self, tool: SdkTool) -> Self {
246 self.tools.push(tool);
247 self
248 }
249
250 #[must_use]
252 pub fn timeout(mut self, timeout: Duration) -> Self {
253 self.timeout = Some(timeout);
254 self
255 }
256
257 #[must_use]
259 pub fn qualified_tool_names(&self) -> Vec<String> {
260 self.tools.iter().map(|t| format!("mcp__{}__{}", self.name, t.def.name)).collect()
261 }
262
263 pub(crate) fn for_session(&self) -> Self {
266 Self { in_flight: Arc::new(InFlight::new()), ..self.clone() }
267 }
268
269 pub(crate) fn taking_over(&self, running: &Self) -> Self {
272 Self { in_flight: running.in_flight.clone(), ..self.clone() }
273 }
274
275 pub(crate) fn register_call(&self, message: &Value) -> Option<CallRegistration> {
279 (message.get("method").and_then(Value::as_str) == Some("tools/call"))
280 .then(|| self.register(message.get("id").unwrap_or(&Value::Null).to_string()))
281 }
282
283 fn register(&self, key: String) -> CallRegistration {
284 let tag = NEXT_CALL.fetch_add(1, Ordering::Relaxed);
285 let (cancel, cancelled) = oneshot::channel();
286 self.in_flight.insert(key.clone(), (tag, cancel));
287 CallRegistration { in_flight: self.in_flight.clone(), key, tag, cancelled }
288 }
289
290 pub(crate) fn config(&self) -> Value {
292 let mut config = json!({ "type": "sdk", "name": self.name });
293 if let Some(t) = self.timeout {
294 config["timeout"] = json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
295 }
296 config
297 }
298
299 pub async fn handle(&self, message: &Value) -> Value {
302 let registration = self.register_call(message);
303 self.handle_in_session(message, None, registration).await
304 }
305
306 pub(crate) async fn handle_in_session(
309 &self,
310 message: &Value,
311 session_id: Option<String>,
312 registration: Option<CallRegistration>,
313 ) -> Value {
314 let id = message.get("id").cloned().unwrap_or(Value::Null);
315 let method = message.get("method").and_then(Value::as_str).unwrap_or("");
316 let params = message.get("params");
317 match method {
318 "initialize" => rpc_result(id, json!({
319 "protocolVersion": PROTOCOL_VERSION,
320 "capabilities": { "tools": {} },
321 "serverInfo": { "name": self.name, "version": self.version },
322 })),
323 "ping" => rpc_result(id, json!({})),
324 "notifications/cancelled" => {
325 let request_id = params.and_then(|p| p.get("requestId")).map(Value::to_string);
326 if let Some((_, (_, cancel))) = request_id.and_then(|rid| self.in_flight.remove(&rid)) {
327 let _ = cancel.send(());
328 }
329 json!({ "jsonrpc": "2.0", "result": {} })
330 }
331 m if m.starts_with("notifications/") => json!({ "jsonrpc": "2.0", "result": {} }),
332 "tools/list" => {
333 let tools: Vec<Value> = self.tools.iter().map(|t| tool_listing(&t.def)).collect();
334 rpc_result(id, json!({ "tools": tools }))
335 }
336 "tools/call" => {
337 let registration = registration.unwrap_or_else(|| self.register(id.to_string()));
338 self.call_tool(id, params, session_id, registration).await
339 }
340 other => rpc_error(id, -32601, &format!("Method '{other}' not found")),
341 }
342 }
343
344 async fn call_tool(
347 &self,
348 id: Value,
349 params: Option<&Value>,
350 session_id: Option<String>,
351 mut registration: CallRegistration,
352 ) -> Value {
353 let name = params.and_then(|p| p.get("name")).and_then(Value::as_str).unwrap_or("");
354 let args = params.and_then(|p| p.get("arguments")).cloned().unwrap_or_else(|| json!({}));
355 let Some(tool) = self.tools.iter().find(|t| t.def.name == name) else {
356 return rpc_error(id, -32602, &format!("Tool '{name}' not found"));
357 };
358 let run = (tool.handler)(args, ToolContext::from_params(params, session_id));
359 let outcome = tokio::select! {
360 result = run => Some(result),
361 Ok(()) = &mut registration.cancelled => None,
362 };
363 match outcome {
364 Some(result) => rpc_result(id, result.into_wire()),
365 None => rpc_error(id, REQUEST_CANCELLED, "Request cancelled"),
366 }
367 }
368}
369
370fn tool_listing(def: &ToolDef) -> Value {
371 let mut tool = json!({
372 "name": def.name,
373 "description": def.description,
374 "inputSchema": def.input_schema.clone()
375 .unwrap_or_else(|| json!({ "type": "object", "properties": {} })),
376 });
377 if let Some(title) = &def.title {
378 tool["title"] = json!(title);
379 }
380 if let Some(schema) = &def.output_schema {
381 tool["outputSchema"] = schema.clone();
382 }
383 if let Some(annotations) = &def.annotations {
384 tool["annotations"] = json!(annotations);
385 }
386 tool
387}
388
389pub(crate) fn server_map(servers: &[SdkMcpServer], external: Option<&serde_json::Map<String, Value>>) -> Value {
391 let mut map: serde_json::Map<String, Value> =
392 servers.iter().map(|s| (s.name.clone(), s.config())).collect();
393 if let Some(external) = external {
394 map.extend(external.iter().map(|(k, v)| (k.clone(), v.clone())));
395 }
396 Value::Object(map)
397}
398
399fn rpc_result(id: Value, result: Value) -> Value {
402 rpc_reply(id, "result", result)
403}
404
405fn rpc_error(id: Value, code: i64, message: &str) -> Value {
406 rpc_reply(id, "error", json!({ "code": code, "message": message }))
407}
408
409fn rpc_reply(id: Value, key: &str, payload: Value) -> Value {
410 let mut reply = serde_json::Map::with_capacity(3);
411 reply.insert("jsonrpc".into(), "2.0".into());
412 reply.insert("id".into(), id);
413 reply.insert(key.into(), payload);
414 Value::Object(reply)
415}