use std::collections::BTreeMap;
use std::time::Duration;
use serde_json::{json, Value};
use crate::mcp::config::{ConfiguredServer, EnvLookup, ServerTransport};
use crate::mcp::http::StreamableHttpTransport;
use crate::mcp::protocol::{
ImplementationInfo, InitializeResult, McpError, Tool, ToolCallResult, ToolsListResult,
MCP_PROTOCOL_VERSION,
};
use crate::mcp::stdio::StdioTransport;
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_TOOLS_PAGES: usize = 100;
pub trait McpTransport: Send {
fn send_request(
&mut self,
request_id: u64,
method: &str,
params: Option<Value>,
timeout: Duration,
) -> Result<Value, McpError>;
fn send_notification(
&mut self,
method: &str,
params: Option<Value>,
timeout: Duration,
) -> Result<(), McpError>;
}
pub struct McpClient {
transport: Box<dyn McpTransport>,
next_id: u64,
timeout: Duration,
initialized: Option<InitializeResult>,
}
impl McpClient {
pub fn new(transport: impl McpTransport + 'static) -> Self {
Self {
transport: Box::new(transport),
next_id: 1,
timeout: DEFAULT_TIMEOUT,
initialized: None,
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn set_timeout(&mut self, timeout: Duration) {
self.timeout = timeout;
}
pub fn open_stdio(
command: &str,
args: &[String],
env: &BTreeMap<String, String>,
timeout: Duration,
) -> Result<Self, McpError> {
let transport = StdioTransport::spawn(command, args, env)?;
Ok(Self::new(transport).with_timeout(timeout))
}
pub fn open_http(
url: impl Into<String>,
headers: BTreeMap<String, String>,
bearer_token: Option<String>,
timeout: Duration,
) -> Self {
let transport = StreamableHttpTransport::new(url, headers, bearer_token);
Self::new(transport).with_timeout(timeout)
}
pub fn open_server(
server: &ConfiguredServer,
env_lookup: &EnvLookup,
bearer_token: Option<String>,
timeout: Duration,
) -> Result<Self, McpError> {
if !server.trusted {
return Err(McpError::UntrustedProjectServer {
name: server.name.clone(),
path: server.source_path.clone(),
});
}
match server.resolve_transport(env_lookup)? {
ServerTransport::Stdio { command, args, env } => {
Self::open_stdio(&command, &args, &env, timeout)
}
ServerTransport::Http { url, headers } => {
Ok(Self::open_http(url, headers, bearer_token, timeout))
}
}
}
pub fn connect_server(
server: &ConfiguredServer,
env_lookup: &EnvLookup,
bearer_token: Option<String>,
timeout: Duration,
) -> Result<(Self, InitializeResult), McpError> {
let mut client = Self::open_server(server, env_lookup, bearer_token, timeout)?;
let init = client.initialize()?;
Ok((client, init))
}
pub fn server_info(&self) -> Option<&InitializeResult> {
self.initialized.as_ref()
}
pub fn initialize(&mut self) -> Result<InitializeResult, McpError> {
let params = json!({
"protocolVersion": MCP_PROTOCOL_VERSION,
"capabilities": {},
"clientInfo": ImplementationInfo::blyte(),
});
let raw = self.request("initialize", Some(params))?;
let result: InitializeResult = serde_json::from_value(raw)
.map_err(|e| McpError::Protocol(format!("invalid 'initialize' result payload: {e}")))?;
self.notify("notifications/initialized", None)?;
self.initialized = Some(result.clone());
Ok(result)
}
pub fn list_tools_page(&mut self, cursor: Option<&str>) -> Result<ToolsListResult, McpError> {
let params = match cursor {
Some(c) => Some(json!({ "cursor": c })),
None => Some(json!({})),
};
let raw = self.request("tools/list", params)?;
serde_json::from_value(raw)
.map_err(|e| McpError::Protocol(format!("invalid 'tools/list' result payload: {e}")))
}
pub fn list_tools(&mut self) -> Result<Vec<Tool>, McpError> {
let mut tools = Vec::new();
let mut cursor: Option<String> = None;
for _ in 0..MAX_TOOLS_PAGES {
let page = self.list_tools_page(cursor.as_deref())?;
tools.extend(page.tools);
match page.next_cursor {
Some(next) if !next.is_empty() => cursor = Some(next),
_ => return Ok(tools),
}
}
Err(McpError::Protocol(format!(
"'tools/list' exceeded maximum pagination depth ({MAX_TOOLS_PAGES} pages)"
)))
}
pub fn call_tool(&mut self, name: &str, arguments: Value) -> Result<ToolCallResult, McpError> {
let params = json!({
"name": name,
"arguments": arguments,
});
let raw = self.request("tools/call", Some(params))?;
serde_json::from_value(raw)
.map_err(|e| McpError::Protocol(format!("invalid 'tools/call' result payload: {e}")))
}
pub fn request(&mut self, method: &str, params: Option<Value>) -> Result<Value, McpError> {
let id = self.next_id;
self.next_id += 1;
self.transport
.send_request(id, method, params, self.timeout)
}
pub fn notify(&mut self, method: &str, params: Option<Value>) -> Result<(), McpError> {
self.transport
.send_notification(method, params, self.timeout)
}
}