use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use dashmap::DashMap;
use serde_json::{json, Value};
use tokio::sync::oneshot;
use crate::protocol::ToolDef;
type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
type ToolFn = Arc<dyn Fn(Value, ToolContext) -> BoxFuture<ToolResult> + Send + Sync>;
const PROTOCOL_VERSION: &str = "2024-11-05";
const REQUEST_CANCELLED: i64 = -32800;
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ToolContent {
Text { text: String },
Image {
data: String,
#[serde(rename = "mimeType")]
mime_type: String,
},
Resource { resource: Value },
ResourceLink(serde_json::Map<String, Value>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolResult {
pub content: Vec<ToolContent>,
pub structured: Option<Value>,
pub is_error: bool,
}
impl ToolResult {
pub fn text(text: impl Into<String>) -> Self {
Self::content(vec![ToolContent::Text { text: text.into() }])
}
pub fn error(text: impl Into<String>) -> Self {
Self { is_error: true, ..Self::text(text) }
}
pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
Self::content(vec![ToolContent::Image { data: data.into(), mime_type: mime_type.into() }])
}
pub fn content(content: Vec<ToolContent>) -> Self {
Self { content, structured: None, is_error: false }
}
pub fn from_value(value: Value) -> Self {
match value {
Value::String(s) => Self::text(s),
other => Self::text(other.to_string()),
}
}
pub fn with_structured(mut self, value: Value) -> Self {
self.structured = Some(value);
self
}
fn to_wire(&self) -> Value {
let content = if self.content.is_empty() {
let text = self.structured.as_ref().map(Value::to_string).unwrap_or_default();
vec![ToolContent::Text { text }]
} else {
self.content.clone()
};
let mut body = json!({ "content": content });
if let Some(s) = &self.structured {
body["structuredContent"] = s.clone();
}
if self.is_error {
body["isError"] = Value::Bool(true);
}
body
}
}
#[derive(Debug, Clone, Default)]
pub struct ToolContext {
pub tool_use_id: Option<String>,
pub session_id: Option<String>,
pub meta: Value,
}
impl ToolContext {
fn from_params(params: Option<&Value>) -> Self {
let meta = params.and_then(|p| p.get("_meta")).cloned().unwrap_or(Value::Null);
let field = |k: &str| meta.get(k).and_then(Value::as_str).map(str::to_owned);
Self {
tool_use_id: field("claudecode/toolUseId"),
session_id: field("claudecode/sessionId"),
meta: meta.clone(),
}
}
}
#[derive(Clone)]
pub struct SdkTool {
pub def: ToolDef,
handler: ToolFn,
}
impl fmt::Debug for SdkTool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SdkTool").field("name", &self.def.name).finish()
}
}
impl SdkTool {
pub fn new<F, Fut>(def: ToolDef, handler: F) -> Self
where
F: Fn(Value) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ToolResult> + Send + 'static,
{
Self { def, handler: Arc::new(move |args, _ctx| Box::pin(handler(args))) }
}
pub fn with_context<F, Fut>(def: ToolDef, handler: F) -> Self
where
F: Fn(Value, ToolContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ToolResult> + Send + 'static,
{
Self { def, handler: Arc::new(move |args, ctx| Box::pin(handler(args, ctx))) }
}
}
#[derive(Debug, Clone)]
pub struct SdkMcpServer {
pub name: String,
pub version: String,
pub timeout: Option<Duration>,
tools: Vec<SdkTool>,
in_flight: Arc<DashMap<String, oneshot::Sender<()>>>,
}
impl SdkMcpServer {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
version: "1.0.0".into(),
timeout: None,
tools: vec![],
in_flight: Arc::new(DashMap::new()),
}
}
pub fn tool(mut self, tool: SdkTool) -> Self {
self.tools.push(tool);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn qualified_tool_names(&self) -> Vec<String> {
self.tools.iter().map(|t| format!("mcp__{}__{}", self.name, t.def.name)).collect()
}
pub(crate) fn config(&self) -> Value {
let mut config = json!({ "type": "sdk", "name": self.name });
if let Some(t) = self.timeout {
config["timeout"] = json!(u64::try_from(t.as_millis()).unwrap_or(u64::MAX));
}
config
}
pub async fn handle(&self, message: &Value) -> Value {
let id = message.get("id").cloned().unwrap_or(Value::Null);
let method = message.get("method").and_then(Value::as_str).unwrap_or("");
let params = message.get("params");
match method {
"initialize" => rpc_result(id, json!({
"protocolVersion": PROTOCOL_VERSION,
"capabilities": { "tools": {} },
"serverInfo": { "name": self.name, "version": self.version },
})),
"ping" => rpc_result(id, json!({})),
"notifications/cancelled" => {
let request_id = params.and_then(|p| p.get("requestId")).map(Value::to_string);
if let Some((_, cancel)) = request_id.and_then(|rid| self.in_flight.remove(&rid)) {
let _ = cancel.send(());
}
json!({ "jsonrpc": "2.0", "result": {} })
}
m if m.starts_with("notifications/") => json!({ "jsonrpc": "2.0", "result": {} }),
"tools/list" => {
let tools: Vec<Value> = self.tools.iter().map(|t| tool_listing(&t.def)).collect();
rpc_result(id, json!({ "tools": tools }))
}
"tools/call" => self.call_tool(id, params).await,
other => rpc_error(id, -32601, format!("Method '{other}' not found")),
}
}
async fn call_tool(&self, id: Value, params: Option<&Value>) -> Value {
let name = params.and_then(|p| p.get("name")).and_then(Value::as_str).unwrap_or("");
let args = params.and_then(|p| p.get("arguments")).cloned().unwrap_or_else(|| json!({}));
let Some(tool) = self.tools.iter().find(|t| t.def.name == name) else {
return rpc_error(id, -32602, format!("Tool '{name}' not found"));
};
let key = id.to_string();
let (cancel_tx, cancel_rx) = oneshot::channel();
self.in_flight.insert(key.clone(), cancel_tx);
let run = (tool.handler)(args, ToolContext::from_params(params));
let outcome = tokio::select! {
result = run => Some(result),
Ok(()) = cancel_rx => None,
};
self.in_flight.remove(&key);
match outcome {
Some(result) => rpc_result(id, result.to_wire()),
None => rpc_error(id, REQUEST_CANCELLED, "Request cancelled".into()),
}
}
}
fn tool_listing(def: &ToolDef) -> Value {
let mut tool = json!({
"name": def.name,
"description": def.description,
"inputSchema": def.input_schema.clone()
.unwrap_or_else(|| json!({ "type": "object", "properties": {} })),
});
if let Some(title) = &def.title {
tool["title"] = json!(title);
}
if let Some(schema) = &def.output_schema {
tool["outputSchema"] = schema.clone();
}
if let Some(annotations) = &def.annotations {
tool["annotations"] = json!(annotations);
}
tool
}
pub(crate) fn server_map(servers: &[SdkMcpServer], external: Option<&serde_json::Map<String, Value>>) -> Value {
let mut map: serde_json::Map<String, Value> =
servers.iter().map(|s| (s.name.clone(), s.config())).collect();
if let Some(external) = external {
map.extend(external.iter().map(|(k, v)| (k.clone(), v.clone())));
}
Value::Object(map)
}
fn rpc_result(id: Value, result: Value) -> Value {
json!({ "jsonrpc": "2.0", "id": id, "result": result })
}
fn rpc_error(id: Value, code: i64, message: String) -> Value {
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
}