agent_client_protocol_rmcp/
builder.rs1use std::{marker::PhantomData, pin::pin, sync::Arc};
4
5use futures::future::{BoxFuture, Either};
6use futures_concurrency::future::TryJoin;
7use rmcp::{
8 ErrorData, ServerHandler,
9 model::{CallToolResult, ListToolsResult, Tool},
10};
11use schemars::JsonSchema;
12use serde::{Serialize, de::DeserializeOwned};
13use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
14
15use agent_client_protocol as acp;
16use agent_client_protocol::{
17 ByteStreams, ChainRun, ConnectTo, DynConnectTo, NullRun, RunWithConnectionTo,
18 mcp_server::{
19 McpConnectionTo, McpServer, McpServerConnect, McpTool, McpToolMetadata, McpToolRegistry,
20 },
21 role::{self, Role},
22};
23
24#[derive(Debug)]
47pub struct McpServerBuilder<Counterpart: Role, Runner>
48where
49 Runner: RunWithConnectionTo<Counterpart>,
50{
51 phantom: PhantomData<Counterpart>,
52 name: String,
53 data: McpToolRegistry<Counterpart>,
54 runner: Runner,
55}
56
57impl<Counterpart: Role> McpServerBuilder<Counterpart, NullRun> {
58 pub(super) fn new(name: String) -> Self {
59 Self {
60 name,
61 phantom: PhantomData,
62 data: McpToolRegistry::default(),
63 runner: NullRun,
64 }
65 }
66}
67
68impl<Counterpart: Role, Runner> McpServerBuilder<Counterpart, Runner>
69where
70 Runner: RunWithConnectionTo<Counterpart>,
71{
72 #[must_use]
74 pub fn instructions(mut self, instructions: impl ToString) -> Self {
75 self.data.set_instructions(instructions);
76 self
77 }
78
79 #[must_use]
81 pub fn tool(mut self, tool: impl McpTool<Counterpart> + 'static) -> Self {
82 self.data.register_tool(tool);
83 self
84 }
85
86 #[must_use]
89 pub fn disable_all_tools(mut self) -> Self {
90 self.data.disable_all_tools();
91 self
92 }
93
94 #[must_use]
97 pub fn enable_all_tools(mut self) -> Self {
98 self.data.enable_all_tools();
99 self
100 }
101
102 pub fn disable_tool(mut self, name: &str) -> Result<Self, acp::Error> {
106 self.data.disable_tool(name)?;
107 Ok(self)
108 }
109
110 pub fn enable_tool(mut self, name: &str) -> Result<Self, acp::Error> {
114 self.data.enable_tool(name)?;
115 Ok(self)
116 }
117
118 fn tool_with_runner(
121 self,
122 tool: impl McpTool<Counterpart> + 'static,
123 tool_runner: impl RunWithConnectionTo<Counterpart>,
124 ) -> McpServerBuilder<Counterpart, impl RunWithConnectionTo<Counterpart>> {
125 let this = self.tool(tool);
126 McpServerBuilder {
127 phantom: PhantomData,
128 name: this.name,
129 data: this.data,
130 runner: ChainRun::new(this.runner, tool_runner),
131 }
132 }
133
134 pub fn tool_fn_mut<P, Ret, F>(
157 self,
158 name: impl ToString,
159 description: impl ToString,
160 func: F,
161 tool_future_hack: impl for<'a> Fn(
162 &'a mut F,
163 P,
164 McpConnectionTo<Counterpart>,
165 ) -> BoxFuture<'a, Result<Ret, acp::Error>>
166 + Send
167 + 'static,
168 ) -> McpServerBuilder<Counterpart, impl RunWithConnectionTo<Counterpart>>
169 where
170 P: JsonSchema + DeserializeOwned + 'static + Send,
171 Ret: JsonSchema + Serialize + 'static + Send,
172 F: AsyncFnMut(P, McpConnectionTo<Counterpart>) -> Result<Ret, acp::Error> + Send,
173 {
174 let (tool, runner) =
175 acp::mcp_server::tool_fn_mut(name, description, func, tool_future_hack);
176 self.tool_with_runner(tool, runner)
177 }
178
179 pub fn tool_fn<P, Ret, F>(
200 self,
201 name: impl ToString,
202 description: impl ToString,
203 func: F,
204 tool_future_hack: impl for<'a> Fn(
205 &'a F,
206 P,
207 McpConnectionTo<Counterpart>,
208 ) -> BoxFuture<'a, Result<Ret, acp::Error>>
209 + Send
210 + Sync
211 + 'static,
212 ) -> McpServerBuilder<Counterpart, impl RunWithConnectionTo<Counterpart>>
213 where
214 P: JsonSchema + DeserializeOwned + 'static + Send,
215 Ret: JsonSchema + Serialize + 'static + Send,
216 F: AsyncFn(P, McpConnectionTo<Counterpart>) -> Result<Ret, acp::Error>
217 + Send
218 + Sync
219 + 'static,
220 {
221 let (tool, runner) = acp::mcp_server::tool_fn(name, description, func, tool_future_hack);
222 self.tool_with_runner(tool, runner)
223 }
224
225 pub fn build(self) -> McpServer<Counterpart, Runner> {
231 McpServer::new(
232 McpServerBuilt {
233 name: self.name,
234 data: Arc::new(self.data),
235 },
236 self.runner,
237 )
238 }
239}
240
241struct McpServerBuilt<Counterpart: Role> {
242 name: String,
243 data: Arc<McpToolRegistry<Counterpart>>,
244}
245
246impl<Counterpart: Role> McpServerConnect<Counterpart> for McpServerBuilt<Counterpart> {
247 fn name(&self) -> String {
248 self.name.clone()
249 }
250
251 fn connect(
252 &self,
253 mcp_connection: McpConnectionTo<Counterpart>,
254 ) -> DynConnectTo<role::mcp::Client> {
255 DynConnectTo::new(McpServerConnection {
256 data: self.data.clone(),
257 mcp_connection,
258 })
259 }
260}
261
262pub(crate) struct McpServerConnection<Counterpart: Role> {
264 data: Arc<McpToolRegistry<Counterpart>>,
265 mcp_connection: McpConnectionTo<Counterpart>,
266}
267
268impl<Counterpart: Role> ConnectTo<role::mcp::Client> for McpServerConnection<Counterpart> {
269 async fn connect_to(self, client: impl ConnectTo<role::mcp::Server>) -> Result<(), acp::Error> {
270 let (mcp_server_stream, mcp_client_stream) = tokio::io::duplex(8192);
272 let (mcp_server_read, mcp_server_write) = tokio::io::split(mcp_server_stream);
273 let (mcp_client_read, mcp_client_write) = tokio::io::split(mcp_client_stream);
274
275 let run_client = async {
276 let byte_streams =
277 ByteStreams::new(mcp_client_write.compat_write(), mcp_client_read.compat());
278 <ByteStreams<_, _> as ConnectTo<role::mcp::Client>>::connect_to(byte_streams, client)
279 .await
280 };
281
282 let run_server = async {
283 let running_server = rmcp::ServiceExt::serve(self, (mcp_server_read, mcp_server_write))
285 .await
286 .map_err(acp::Error::into_internal_error)?;
287
288 running_server
290 .waiting()
291 .await
292 .map(|_quit_reason| ())
293 .map_err(acp::Error::into_internal_error)
294 };
295
296 (run_client, run_server).try_join().await?;
297 Ok(())
298 }
299}
300
301impl<R: Role> ServerHandler for McpServerConnection<R> {
302 async fn call_tool(
303 &self,
304 request: rmcp::model::CallToolRequestParams,
305 context: rmcp::service::RequestContext<rmcp::RoleServer>,
306 ) -> Result<CallToolResult, ErrorData> {
307 let Some(registered) = self.data.enabled_tool(&request.name) else {
309 return Err(rmcp::model::ErrorData::invalid_params(
310 format!("tool `{}` not found", request.name),
311 None,
312 ));
313 };
314
315 let serde_value = serde_json::to_value(request.arguments).expect("valid json");
317
318 let has_structured_output = registered.has_structured_output();
320 match futures::future::select(
321 registered.call_tool(serde_value, self.mcp_connection.clone()),
322 pin!(context.ct.cancelled()),
323 )
324 .await
325 {
326 Either::Left((m, _)) => match m {
328 Ok(result) => {
329 if has_structured_output {
331 Ok(CallToolResult::structured(result))
332 } else {
333 Ok(CallToolResult::success(vec![
334 rmcp::model::ContentBlock::text(result.to_string()),
335 ]))
336 }
337 }
338 Err(error) => Err(to_rmcp_error(error)),
339 },
340
341 Either::Right(((), _)) => {
343 Err(rmcp::ErrorData::internal_error("operation cancelled", None))
344 }
345 }
346 }
347
348 async fn list_tools(
349 &self,
350 _request: Option<rmcp::model::PaginatedRequestParams>,
351 _context: rmcp::service::RequestContext<rmcp::RoleServer>,
352 ) -> Result<rmcp::model::ListToolsResult, ErrorData> {
353 let tools: Vec<_> = self
355 .data
356 .enabled_tools()
357 .map(|tool| make_tool_model(tool.metadata()))
358 .collect();
359 Ok(ListToolsResult::with_all_items(tools))
360 }
361
362 fn get_info(&self) -> rmcp::model::ServerInfo {
363 let base = rmcp::model::ServerInfo::new(
365 rmcp::model::ServerCapabilities::builder()
366 .enable_tools()
367 .build(),
368 )
369 .with_server_info(rmcp::model::Implementation::default())
370 .with_protocol_version(rmcp::model::ProtocolVersion::default());
371
372 if let Some(instructions) = self.data.instructions() {
373 base.with_instructions(instructions.to_string())
374 } else {
375 base
376 }
377 }
378}
379
380fn make_tool_model(metadata: &McpToolMetadata) -> Tool {
382 let mut tool = rmcp::model::Tool::new(
383 metadata.name().to_string(),
384 metadata.description().to_string(),
385 metadata.input_schema().clone(),
386 )
387 .with_execution(rmcp::model::ToolExecution::new());
388
389 if let Some(title) = metadata.title() {
390 tool = tool.with_title(title.to_string());
391 }
392
393 if let Some(schema) = metadata.output_schema() {
394 tool = tool.with_raw_output_schema(schema.clone());
395 }
396
397 tool
398}
399
400fn to_rmcp_error(error: acp::Error) -> rmcp::ErrorData {
402 rmcp::ErrorData {
403 code: rmcp::model::ErrorCode(error.code.into()),
404 message: error.message.into(),
405 data: error.data,
406 }
407}