Skip to main content

agent_client_protocol/mcp_server/
connect.rs

1use std::sync::Arc;
2
3use crate::{
4    DynConnectTo,
5    mcp_server::McpConnectionTo,
6    role::{self, Role},
7};
8
9/// Trait for types that can create MCP server connections.
10///
11/// Implement this trait to create custom MCP servers. Each call to [`connect`](Self::connect)
12/// should return a new [`ConnectTo`](crate::ConnectTo) that serves MCP requests for a single
13/// connection.
14///
15/// # Example
16///
17/// ```rust,ignore
18/// use agent_client_protocol::mcp_server::{McpServerConnect, McpConnectionTo};
19/// use agent_client_protocol::{DynConnectTo, role::Role};
20///
21/// struct MyMcpServer {
22///     name: String,
23/// }
24///
25/// impl<R: Role> McpServerConnect<R> for MyMcpServer {
26///     fn name(&self) -> String {
27///         self.name.clone()
28///     }
29///
30///     fn connect(&self, cx: McpConnectionTo<R>) -> DynConnectTo<role::mcp::Client> {
31///         // Create and return a component that handles MCP requests
32///         DynConnectTo::new(MyMcpComponent::new(cx))
33///     }
34/// }
35/// ```
36pub trait McpServerConnect<Counterpart: Role>: Send + Sync + 'static {
37    /// The name of the MCP server, used to identify it in session responses.
38    fn name(&self) -> String;
39
40    /// Create a component to service a new MCP connection.
41    ///
42    /// This is called each time an agent connects to this MCP server. The returned
43    /// component will handle MCP protocol messages for that connection.
44    ///
45    /// The [`McpConnectionTo`] provides access to the ACP connection context and the
46    /// server's ACP URL.
47    fn connect(&self, cx: McpConnectionTo<Counterpart>) -> DynConnectTo<role::mcp::Client>;
48}
49
50impl<Counterpart: Role, S: ?Sized + McpServerConnect<Counterpart>> McpServerConnect<Counterpart>
51    for Box<S>
52{
53    fn name(&self) -> String {
54        S::name(self)
55    }
56
57    fn connect(&self, cx: McpConnectionTo<Counterpart>) -> DynConnectTo<role::mcp::Client> {
58        S::connect(self, cx)
59    }
60}
61
62impl<Counterpart: Role, S: ?Sized + McpServerConnect<Counterpart>> McpServerConnect<Counterpart>
63    for Arc<S>
64{
65    fn name(&self) -> String {
66        S::name(self)
67    }
68
69    fn connect(&self, cx: McpConnectionTo<Counterpart>) -> DynConnectTo<role::mcp::Client> {
70        S::connect(self, cx)
71    }
72}