Skip to main content

agent_client_protocol/mcp_server/
context.rs

1use crate::{ConnectionTo, role::Role};
2
3#[cfg(feature = "unstable_mcp_over_acp")]
4use crate::v1::schema::{McpRequestId, McpServerAcpId, SessionId, ToolCallId};
5#[cfg(feature = "unstable_mcp_over_acp")]
6use futures::channel::oneshot;
7#[cfg(feature = "unstable_mcp_over_acp")]
8use std::sync::{Arc, Mutex};
9
10/// Describes how an MCP server connection was established.
11#[derive(Clone, Debug, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum McpConnectionContext {
14    /// The MCP server was connected directly, without an ACP transport.
15    Standalone,
16
17    /// The MCP server was attached to an ACP session.
18    #[cfg(feature = "unstable_mcp_over_acp")]
19    #[non_exhaustive]
20    Acp {
21        /// The identifier advertised in the session's `McpServer::Acp` declaration.
22        server_id: McpServerAcpId,
23
24        /// The logical identifier of this independent MCP request.
25        request_id: McpRequestId,
26
27        /// The session the Agent says this request was sent for, if it
28        /// supplied one. The SDK does not check it.
29        session_id: Option<SessionId>,
30
31        /// The tool call in that session that the Agent says this request
32        /// is part of, if it supplied one.
33        tool_call_id: Option<ToolCallId>,
34    },
35}
36
37impl McpConnectionContext {
38    /// Whether this MCP connection was established without an ACP transport.
39    #[must_use]
40    pub fn is_standalone(&self) -> bool {
41        matches!(self, Self::Standalone)
42    }
43
44    /// The identifier advertised in the session's `McpServer::Acp` declaration.
45    ///
46    /// Returns `None` for a standalone MCP connection.
47    #[cfg(feature = "unstable_mcp_over_acp")]
48    #[must_use]
49    pub fn server_id(&self) -> Option<&McpServerAcpId> {
50        match self {
51            Self::Standalone => None,
52            Self::Acp { server_id, .. } => Some(server_id),
53        }
54    }
55
56    /// The logical identifier of the active MCP request.
57    ///
58    /// Returns `None` for a standalone MCP connection.
59    #[cfg(feature = "unstable_mcp_over_acp")]
60    #[must_use]
61    pub fn request_id(&self) -> Option<&McpRequestId> {
62        match self {
63            Self::Standalone => None,
64            Self::Acp { request_id, .. } => Some(request_id),
65        }
66    }
67
68    /// The session the Agent says this request was sent for.
69    ///
70    /// Returns `None` for a standalone MCP connection, and when the Agent
71    /// supplied no session. For a child session's work this is the child's ID.
72    ///
73    /// The SDK does not check the value. Before you use it to choose what a
74    /// request acts on, check that the session is active on the connection, or
75    /// is a child that the Agent announced for an active session, and that this
76    /// server was declared to it or to one of its ancestors.
77    #[cfg(feature = "unstable_mcp_over_acp")]
78    #[must_use]
79    pub fn session_id(&self) -> Option<&SessionId> {
80        match self {
81            Self::Standalone => None,
82            Self::Acp { session_id, .. } => session_id.as_ref(),
83        }
84    }
85
86    /// The tool call, in the session returned by `session_id`, that the Agent
87    /// says this request is part of.
88    ///
89    /// Returns `None` for a standalone MCP connection, and when the Agent
90    /// supplied no tool call. The Agent can report the tool call after it
91    /// sends the request, so the ID might not be known yet.
92    #[cfg(feature = "unstable_mcp_over_acp")]
93    #[must_use]
94    pub fn tool_call_id(&self) -> Option<&ToolCallId> {
95        match self {
96            Self::Standalone => None,
97            Self::Acp { tool_call_id, .. } => tool_call_id.as_ref(),
98        }
99    }
100}
101
102/// Connection information available to an MCP server.
103#[derive(Clone, Debug)]
104pub struct McpConnectionTo<Counterpart: Role> {
105    pub(super) context: McpConnectionContext,
106    pub(super) connection: ConnectionTo<Counterpart>,
107    #[cfg(feature = "unstable_mcp_over_acp")]
108    pub(super) cleanup: Option<Arc<Mutex<Vec<oneshot::Receiver<()>>>>>,
109}
110
111impl<Counterpart: Role> McpConnectionTo<Counterpart> {
112    #[cfg(all(feature = "unstable_mcp_over_acp", feature = "schemars"))]
113    pub(crate) fn register_cleanup(&self, done: oneshot::Receiver<()>) {
114        if let Some(cleanup) = &self.cleanup {
115            cleanup.lock().expect("MCP cleanup poisoned").push(done);
116        }
117    }
118
119    #[cfg(feature = "unstable_mcp_over_acp")]
120    pub(crate) async fn wait_cleanup(&self) {
121        if let Some(cleanup) = &self.cleanup {
122            let pending = std::mem::take(&mut *cleanup.lock().expect("MCP cleanup poisoned"));
123            for done in pending {
124                let _finished = done.await;
125            }
126        }
127    }
128
129    /// Describes whether this is a standalone or ACP-attached MCP connection.
130    #[must_use]
131    pub fn context(&self) -> &McpConnectionContext {
132        &self.context
133    }
134
135    /// The identifier advertised in the session's `McpServer::Acp` declaration.
136    ///
137    /// Returns `None` for a standalone MCP connection.
138    #[cfg(feature = "unstable_mcp_over_acp")]
139    #[must_use]
140    pub fn server_id(&self) -> Option<&McpServerAcpId> {
141        self.context.server_id()
142    }
143
144    /// The logical identifier of the active MCP request.
145    ///
146    /// Returns `None` for a standalone MCP connection.
147    #[cfg(feature = "unstable_mcp_over_acp")]
148    #[must_use]
149    pub fn request_id(&self) -> Option<&McpRequestId> {
150        self.context.request_id()
151    }
152
153    /// The session the Agent says this request was sent for.
154    ///
155    /// Returns `None` for a standalone MCP connection, and when the Agent
156    /// supplied no session. For a child session's work this is the child's ID.
157    ///
158    /// The SDK does not check the value. Before you use it to choose what a
159    /// request acts on, check that the session is active on the connection, or
160    /// is a child that the Agent announced for an active session, and that this
161    /// server was declared to it or to one of its ancestors.
162    #[cfg(feature = "unstable_mcp_over_acp")]
163    #[must_use]
164    pub fn session_id(&self) -> Option<&SessionId> {
165        self.context.session_id()
166    }
167
168    /// The tool call, in the session returned by `session_id`, that the Agent
169    /// says this request is part of.
170    ///
171    /// Returns `None` for a standalone MCP connection, and when the Agent
172    /// supplied no tool call. The Agent can report the tool call after it
173    /// sends the request, so the ID might not be known yet.
174    #[cfg(feature = "unstable_mcp_over_acp")]
175    #[must_use]
176    pub fn tool_call_id(&self) -> Option<&ToolCallId> {
177        self.context.tool_call_id()
178    }
179
180    /// Borrow the host protocol connection.
181    ///
182    /// For an ACP-attached server, this is its host ACP connection. For a
183    /// standalone server, this is the direct MCP client connection.
184    #[must_use]
185    pub fn connection(&self) -> &ConnectionTo<Counterpart> {
186        &self.connection
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::McpConnectionContext;
193
194    #[test]
195    fn standalone_context_is_explicit() {
196        let context = McpConnectionContext::Standalone;
197
198        assert!(context.is_standalone());
199
200        #[cfg(feature = "unstable_mcp_over_acp")]
201        {
202            assert_eq!(context.server_id(), None);
203            assert_eq!(context.request_id(), None);
204            assert_eq!(context.session_id(), None);
205            assert_eq!(context.tool_call_id(), None);
206        }
207    }
208
209    #[cfg(feature = "unstable_mcp_over_acp")]
210    #[test]
211    fn acp_context_exposes_server_and_request_ids() {
212        use crate::v1::schema::{McpRequestId, McpServerAcpId, SessionId, ToolCallId};
213
214        let server_id = McpServerAcpId::new("server-id");
215        let request_id = McpRequestId::new("request-id");
216        let session_id = SessionId::new("session-id");
217        let tool_call_id = ToolCallId::new("tool-call-id");
218        let context = McpConnectionContext::Acp {
219            server_id: server_id.clone(),
220            request_id: request_id.clone(),
221            session_id: Some(session_id.clone()),
222            tool_call_id: Some(tool_call_id.clone()),
223        };
224
225        assert!(!context.is_standalone());
226        assert_eq!(context.server_id(), Some(&server_id));
227        assert_eq!(context.request_id(), Some(&request_id));
228        assert_eq!(context.session_id(), Some(&session_id));
229        assert_eq!(context.tool_call_id(), Some(&tool_call_id));
230    }
231}