Skip to main content

agent_client_protocol_rmcp/
builder.rs

1//! MCP server builder for creating MCP servers.
2
3use 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/// Builder for creating MCP servers with tools.
25///
26/// Use [`crate::McpServerExt::builder`] to create a new builder, then chain methods to
27/// configure the server and call [`build`](Self::build) to create the server.
28///
29/// # Example
30///
31/// ```rust,ignore
32/// use agent_client_protocol::mcp_server::McpServer;
33/// use agent_client_protocol_rmcp::McpServerExt;
34///
35/// let server = McpServer::builder("my-server".to_string())
36///     .instructions("A helpful assistant")
37///     .tool(EchoTool)
38///     .tool_fn(
39///         "greet",
40///         "Greet someone by name",
41///         async |input: GreetInput, _cx| Ok(format!("Hello, {}!", input.name)),
42///         agent_client_protocol_rmcp::tool_fn!(),
43///     )
44///     .build();
45/// ```
46#[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    /// Set the server instructions that are provided to the client.
73    #[must_use]
74    pub fn instructions(mut self, instructions: impl ToString) -> Self {
75        self.data.set_instructions(instructions);
76        self
77    }
78
79    /// Add a tool to the server.
80    #[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    /// Disable all tools. After calling this, only tools explicitly enabled
87    /// with [`enable_tool`](Self::enable_tool) will be available.
88    #[must_use]
89    pub fn disable_all_tools(mut self) -> Self {
90        self.data.disable_all_tools();
91        self
92    }
93
94    /// Enable all tools. After calling this, all tools will be available
95    /// except those explicitly disabled with [`disable_tool`](Self::disable_tool).
96    #[must_use]
97    pub fn enable_all_tools(mut self) -> Self {
98        self.data.enable_all_tools();
99        self
100    }
101
102    /// Disable a specific tool by name.
103    ///
104    /// Returns an error if the tool is not registered.
105    pub fn disable_tool(mut self, name: &str) -> Result<Self, acp::Error> {
106        self.data.disable_tool(name)?;
107        Ok(self)
108    }
109
110    /// Enable a specific tool by name.
111    ///
112    /// Returns an error if the tool is not registered.
113    pub fn enable_tool(mut self, name: &str) -> Result<Self, acp::Error> {
114        self.data.enable_tool(name)?;
115        Ok(self)
116    }
117
118    /// Private fn: adds the tool but also adds a runner that will be
119    /// run while the MCP server is active.
120    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    /// Convenience wrapper for defining a "single-threaded" tool without having to create a struct.
135    /// By "single-threaded", we mean that only one invocation of the tool can be running at a time.
136    /// Typically agents invoke a tool once per session and then block waiting for the result,
137    /// so this is fine, but they could attempt to run multiple invocations concurrently, in which
138    /// case those invocations would be serialized.
139    ///
140    /// # Parameters
141    ///
142    /// * `name`: The name of the tool.
143    /// * `description`: The description of the tool.
144    /// * `func`: The function that implements the tool. Use an async closure like `async |args, cx| { .. }`.
145    ///
146    /// # Examples
147    ///
148    /// ```rust,ignore
149    /// McpServer::builder("my-server")
150    ///     .tool_fn_mut(
151    ///         "greet",
152    ///         "Greet someone by name",
153    ///         async |input: GreetInput, _cx| Ok(format!("Hello, {}!", input.name)),
154    ///     )
155    /// ```
156    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    /// Convenience wrapper for defining a stateless tool that can run concurrently.
180    /// Unlike [`tool_fn_mut`](Self::tool_fn_mut), multiple invocations of this tool can run
181    /// at the same time since the function is `Fn` rather than `FnMut`.
182    ///
183    /// # Parameters
184    ///
185    /// * `name`: The name of the tool.
186    /// * `description`: The description of the tool.
187    /// * `func`: The function that implements the tool. Use an async closure like `async |args, cx| { .. }`.
188    ///
189    /// # Examples
190    ///
191    /// ```rust,ignore
192    /// McpServer::builder("my-server")
193    ///     .tool_fn(
194    ///         "greet",
195    ///         "Greet someone by name",
196    ///         async |input: GreetInput, _cx| Ok(format!("Hello, {}!", input.name)),
197    ///     )
198    /// ```
199    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    /// Create an MCP server from this builder.
226    ///
227    /// This builder can be served directly. With the `unstable_mcp_over_acp`
228    /// feature, it can also be attached through
229    /// `SessionBuilder::with_mcp_server` or `Builder::with_mcp_server`.
230    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
262/// A connected MCP server instance.
263pub(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        // Create tokio byte streams that rmcp expects
271        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            // Run the rmcp server with the server side of the duplex stream
284            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            // Wait for the server to finish
289            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        // Lookup the tool definition, erroring if not found or disabled
308        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        // Convert input into JSON
316        let serde_value = serde_json::to_value(request.arguments).expect("valid json");
317
318        // Execute the user's tool, unless cancellation occurs
319        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            // If completed successfully
327            Either::Left((m, _)) => match m {
328                Ok(result) => {
329                    // Use structured output only if the tool declared an output_schema
330                    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            // If cancelled
342            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        // Return only enabled tools
354        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        // Basic server info
364        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
380/// Create an `rmcp` tool model from runtime-neutral MCP tool metadata.
381fn 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
400/// Convert an [`agent_client_protocol::Error`] into an [`rmcp::ErrorData`].
401fn 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}