1use std::collections::BTreeMap;
4use std::time::Duration;
5
6use serde_json::{json, Value};
7
8use crate::mcp::config::{ConfiguredServer, EnvLookup, ServerTransport};
9use crate::mcp::http::StreamableHttpTransport;
10use crate::mcp::protocol::{
11 ImplementationInfo, InitializeResult, McpError, Tool, ToolCallResult, ToolsListResult,
12 MCP_PROTOCOL_VERSION,
13};
14use crate::mcp::stdio::StdioTransport;
15
16pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
18
19const MAX_TOOLS_PAGES: usize = 100;
20
21pub trait McpTransport: Send {
23 fn send_request(
24 &mut self,
25 request_id: u64,
26 method: &str,
27 params: Option<Value>,
28 timeout: Duration,
29 ) -> Result<Value, McpError>;
30
31 fn send_notification(
32 &mut self,
33 method: &str,
34 params: Option<Value>,
35 timeout: Duration,
36 ) -> Result<(), McpError>;
37}
38
39pub struct McpClient {
41 transport: Box<dyn McpTransport>,
42 next_id: u64,
43 timeout: Duration,
44 initialized: Option<InitializeResult>,
45}
46
47impl McpClient {
48 pub fn new(transport: impl McpTransport + 'static) -> Self {
50 Self {
51 transport: Box::new(transport),
52 next_id: 1,
53 timeout: DEFAULT_TIMEOUT,
54 initialized: None,
55 }
56 }
57
58 pub fn with_timeout(mut self, timeout: Duration) -> Self {
60 self.timeout = timeout;
61 self
62 }
63
64 pub fn set_timeout(&mut self, timeout: Duration) {
66 self.timeout = timeout;
67 }
68
69 pub fn open_stdio(
71 command: &str,
72 args: &[String],
73 env: &BTreeMap<String, String>,
74 timeout: Duration,
75 ) -> Result<Self, McpError> {
76 let transport = StdioTransport::spawn(command, args, env)?;
77 Ok(Self::new(transport).with_timeout(timeout))
78 }
79
80 pub fn open_http(
82 url: impl Into<String>,
83 headers: BTreeMap<String, String>,
84 bearer_token: Option<String>,
85 timeout: Duration,
86 ) -> Self {
87 let transport = StreamableHttpTransport::new(url, headers, bearer_token);
88 Self::new(transport).with_timeout(timeout)
89 }
90
91 pub fn open_server(
94 server: &ConfiguredServer,
95 env_lookup: &EnvLookup,
96 bearer_token: Option<String>,
97 timeout: Duration,
98 ) -> Result<Self, McpError> {
99 if !server.trusted {
100 return Err(McpError::UntrustedProjectServer {
101 name: server.name.clone(),
102 path: server.source_path.clone(),
103 });
104 }
105 match server.resolve_transport(env_lookup)? {
106 ServerTransport::Stdio { command, args, env } => {
107 Self::open_stdio(&command, &args, &env, timeout)
108 }
109 ServerTransport::Http { url, headers } => {
110 Ok(Self::open_http(url, headers, bearer_token, timeout))
111 }
112 }
113 }
114
115 pub fn connect_server(
117 server: &ConfiguredServer,
118 env_lookup: &EnvLookup,
119 bearer_token: Option<String>,
120 timeout: Duration,
121 ) -> Result<(Self, InitializeResult), McpError> {
122 let mut client = Self::open_server(server, env_lookup, bearer_token, timeout)?;
123 let init = client.initialize()?;
124 Ok((client, init))
125 }
126
127 pub fn server_info(&self) -> Option<&InitializeResult> {
129 self.initialized.as_ref()
130 }
131
132 pub fn initialize(&mut self) -> Result<InitializeResult, McpError> {
134 let params = json!({
135 "protocolVersion": MCP_PROTOCOL_VERSION,
136 "capabilities": {},
137 "clientInfo": ImplementationInfo::blyte(),
138 });
139 let raw = self.request("initialize", Some(params))?;
140 let result: InitializeResult = serde_json::from_value(raw)
141 .map_err(|e| McpError::Protocol(format!("invalid 'initialize' result payload: {e}")))?;
142 self.notify("notifications/initialized", None)?;
143 self.initialized = Some(result.clone());
144 Ok(result)
145 }
146
147 pub fn list_tools_page(&mut self, cursor: Option<&str>) -> Result<ToolsListResult, McpError> {
149 let params = match cursor {
150 Some(c) => Some(json!({ "cursor": c })),
151 None => Some(json!({})),
152 };
153 let raw = self.request("tools/list", params)?;
154 serde_json::from_value(raw)
155 .map_err(|e| McpError::Protocol(format!("invalid 'tools/list' result payload: {e}")))
156 }
157
158 pub fn list_tools(&mut self) -> Result<Vec<Tool>, McpError> {
160 let mut tools = Vec::new();
161 let mut cursor: Option<String> = None;
162 for _ in 0..MAX_TOOLS_PAGES {
163 let page = self.list_tools_page(cursor.as_deref())?;
164 tools.extend(page.tools);
165 match page.next_cursor {
166 Some(next) if !next.is_empty() => cursor = Some(next),
167 _ => return Ok(tools),
168 }
169 }
170 Err(McpError::Protocol(format!(
171 "'tools/list' exceeded maximum pagination depth ({MAX_TOOLS_PAGES} pages)"
172 )))
173 }
174
175 pub fn call_tool(&mut self, name: &str, arguments: Value) -> Result<ToolCallResult, McpError> {
177 let params = json!({
178 "name": name,
179 "arguments": arguments,
180 });
181 let raw = self.request("tools/call", Some(params))?;
182 serde_json::from_value(raw)
183 .map_err(|e| McpError::Protocol(format!("invalid 'tools/call' result payload: {e}")))
184 }
185
186 pub fn request(&mut self, method: &str, params: Option<Value>) -> Result<Value, McpError> {
188 let id = self.next_id;
189 self.next_id += 1;
190 self.transport
191 .send_request(id, method, params, self.timeout)
192 }
193
194 pub fn notify(&mut self, method: &str, params: Option<Value>) -> Result<(), McpError> {
196 self.transport
197 .send_notification(method, params, self.timeout)
198 }
199}