Skip to main content

agent_client_protocol/mcp_server/
admission.rs

1//! The check that decides whether an `mcp/message` request runs.
2
3use std::{fmt, sync::Arc};
4
5use futures::future::BoxFuture;
6use serde_json::{Map, Value};
7
8use crate::v1::schema::{McpRequestId, McpServerAcpId, SessionId, ToolCallId};
9
10/// One `mcp/message` request, before it runs.
11///
12/// An admission check receives it and decides whether the request is
13/// admitted. Register a check for a server with
14/// [`McpServer::with_admission`](super::McpServer::with_admission).
15///
16/// The SDK builds the value for each request. Build one yourself to test a
17/// check without a connection:
18///
19/// ```
20/// use agent_client_protocol::mcp_server::{McpAdmission, McpRejection};
21///
22/// async fn needs_session(request: McpAdmission) -> Result<(), McpRejection> {
23///     request.require_session_id()?;
24///     Ok(())
25/// }
26///
27/// # futures::executor::block_on(async {
28/// let request = McpAdmission::new("server-1", "request-1", "tools/call");
29/// assert_eq!(
30///     needs_session(request.clone()).await,
31///     Err(McpRejection::session_required())
32/// );
33/// assert_eq!(needs_session(request.with_session_id("sess_1")).await, Ok(()));
34/// # });
35/// ```
36#[derive(Clone)]
37pub struct McpAdmission {
38    // Shared, so that handing the request to each check copies no params.
39    parts: Arc<Parts>,
40}
41
42/// The parts of a request that a check reads.
43#[derive(Clone)]
44struct Parts {
45    server_id: McpServerAcpId,
46    request_id: McpRequestId,
47    method: String,
48    params: Option<Map<String, Value>>,
49    session_id: Option<SessionId>,
50    tool_call_id: Option<ToolCallId>,
51}
52
53// The inner params can hold tool arguments, so `Debug` leaves them out.
54impl fmt::Debug for McpAdmission {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.debug_struct("McpAdmission")
57            .field("server_id", &self.parts.server_id)
58            .field("request_id", &self.parts.request_id)
59            .field("method", &self.parts.method)
60            .field("session_id", &self.parts.session_id)
61            .field("tool_call_id", &self.parts.tool_call_id)
62            .finish_non_exhaustive()
63    }
64}
65
66impl McpAdmission {
67    /// Builds a request to `method` of the server `server_id`, with no inner
68    /// params, no session, and no tool call.
69    #[must_use]
70    pub fn new(
71        server_id: impl Into<McpServerAcpId>,
72        request_id: impl Into<McpRequestId>,
73        method: impl Into<String>,
74    ) -> Self {
75        Self {
76            parts: Arc::new(Parts {
77                server_id: server_id.into(),
78                request_id: request_id.into(),
79                method: method.into(),
80                params: None,
81                session_id: None,
82                tool_call_id: None,
83            }),
84        }
85    }
86
87    /// Sets the inner MCP params.
88    #[must_use]
89    pub fn with_params(mut self, params: Map<String, Value>) -> Self {
90        Arc::make_mut(&mut self.parts).params = Some(params);
91        self
92    }
93
94    /// Sets the session the request was sent for.
95    #[must_use]
96    pub fn with_session_id(mut self, session_id: impl Into<SessionId>) -> Self {
97        Arc::make_mut(&mut self.parts).session_id = Some(session_id.into());
98        self
99    }
100
101    /// Sets the tool call the request is part of.
102    #[must_use]
103    pub fn with_tool_call_id(mut self, tool_call_id: impl Into<ToolCallId>) -> Self {
104        Arc::make_mut(&mut self.parts).tool_call_id = Some(tool_call_id.into());
105        self
106    }
107
108    /// The request a server runs once it is admitted.
109    pub(super) fn from_request(
110        server_id: McpServerAcpId,
111        request_id: McpRequestId,
112        method: String,
113        params: Option<Map<String, Value>>,
114        session_id: Option<SessionId>,
115        tool_call_id: Option<ToolCallId>,
116    ) -> Self {
117        Self {
118            parts: Arc::new(Parts {
119                server_id,
120                request_id,
121                method,
122                params,
123                session_id,
124                tool_call_id,
125            }),
126        }
127    }
128
129    /// Gives the inner method and params back to the server that runs them.
130    /// Copies them only if a check kept the request.
131    pub(super) fn into_method_and_params(self) -> (String, Option<Map<String, Value>>) {
132        match Arc::try_unwrap(self.parts) {
133            Ok(parts) => (parts.method, parts.params),
134            Err(shared) => (shared.method.clone(), shared.params.clone()),
135        }
136    }
137
138    /// The declared server the request is addressed to.
139    #[must_use]
140    pub fn server_id(&self) -> &McpServerAcpId {
141        &self.parts.server_id
142    }
143
144    /// The logical identifier of the request.
145    #[must_use]
146    pub fn request_id(&self) -> &McpRequestId {
147        &self.parts.request_id
148    }
149
150    /// The inner MCP method, such as `tools/call`.
151    #[must_use]
152    pub fn method(&self) -> &str {
153        &self.parts.method
154    }
155
156    /// The inner MCP params, including the request's `_meta`.
157    #[must_use]
158    pub fn params(&self) -> Option<&Map<String, Value>> {
159        self.parts.params.as_ref()
160    }
161
162    /// The name of the tool a `tools/call` request calls.
163    ///
164    /// Returns `None` for every other method, and for a `tools/call` request
165    /// whose params have no `name` string.
166    #[must_use]
167    pub fn tool_name(&self) -> Option<&str> {
168        if self.method() != "tools/call" {
169            return None;
170        }
171        self.params()?.get("name")?.as_str()
172    }
173
174    /// The session the Agent says this request was sent for.
175    ///
176    /// Returns `None` when the Agent supplied no session. For a child
177    /// session's work this is the child's ID. The SDK does not check the
178    /// value.
179    #[must_use]
180    pub fn session_id(&self) -> Option<&SessionId> {
181        self.parts.session_id.as_ref()
182    }
183
184    /// The tool call, in the session returned by `session_id`, that the Agent
185    /// says this request is part of.
186    ///
187    /// Returns `None` when the Agent supplied no tool call. The Agent can
188    /// report the tool call after it sends the request, so the ID might not be
189    /// known yet.
190    #[must_use]
191    pub fn tool_call_id(&self) -> Option<&ToolCallId> {
192        self.parts.tool_call_id.as_ref()
193    }
194
195    /// Returns the session the Agent says this request was sent for, for a
196    /// check that needs one.
197    ///
198    /// This only reads the request. The request is rejected when the check
199    /// returns the error.
200    ///
201    /// # Errors
202    ///
203    /// Returns [`McpRejection::session_required`] when the Agent supplied no
204    /// session.
205    pub fn require_session_id(&self) -> Result<&SessionId, McpRejection> {
206        self.session_id().ok_or_else(McpRejection::session_required)
207    }
208}
209
210/// Why an `mcp/message` request is not admitted.
211///
212/// An admission check returns it. The SDK then answers the request with the
213/// outer ACP error Invalid params (`-32602`), with this reason as the `data`
214/// string, and runs nothing else for the request.
215#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct McpRejection {
217    reason: String,
218}
219
220impl McpRejection {
221    /// The server needs the session of a request, and the Agent supplied none.
222    ///
223    /// The `data` string is
224    /// `this MCP server requires sessionId on mcp/message`.
225    #[must_use]
226    pub fn session_required() -> Self {
227        Self {
228            reason: "this MCP server requires sessionId on mcp/message".to_owned(),
229        }
230    }
231
232    /// The server's own check of the request's session failed.
233    ///
234    /// Use it for a session that is not active on the connection and is not a
235    /// child the Agent announced for an active session, or that this server
236    /// was not declared to. The `data` string is
237    /// `sessionId rejected: {reason}`. `reason` is sent to the Agent.
238    #[must_use]
239    pub fn session_rejected(reason: impl fmt::Display) -> Self {
240        Self {
241            reason: format!("sessionId rejected: {reason}"),
242        }
243    }
244
245    /// The outer ACP error that answers the rejected request.
246    pub(super) fn into_error(self) -> crate::Error {
247        crate::Error::invalid_params().data(self.reason)
248    }
249}
250
251impl fmt::Display for McpRejection {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        f.write_str(&self.reason)
254    }
255}
256
257impl std::error::Error for McpRejection {}
258
259/// One admission check, stored without the type of its closure.
260trait Check: Send + Sync {
261    fn admit(&self, request: McpAdmission) -> BoxFuture<'_, Result<(), McpRejection>>;
262}
263
264/// A check with the function that boxes its future. The future can borrow
265/// what the check captured.
266struct AsyncCheck<F, ToFut> {
267    admit: F,
268    to_future_hack: ToFut,
269}
270
271impl<F, ToFut> Check for AsyncCheck<F, ToFut>
272where
273    F: Send + Sync,
274    ToFut: for<'a> Fn(&'a F, McpAdmission) -> BoxFuture<'a, Result<(), McpRejection>> + Send + Sync,
275{
276    fn admit(&self, request: McpAdmission) -> BoxFuture<'_, Result<(), McpRejection>> {
277        (self.to_future_hack)(&self.admit, request)
278    }
279}
280
281/// Admission checks, in the order they were added.
282#[derive(Clone, Default)]
283pub(super) struct AdmissionChecks(Vec<Arc<dyn Check>>);
284
285impl AdmissionChecks {
286    pub(super) fn push<F>(
287        &mut self,
288        admit: F,
289        to_future_hack: impl for<'a> Fn(&'a F, McpAdmission) -> BoxFuture<'a, Result<(), McpRejection>>
290        + Send
291        + Sync
292        + 'static,
293    ) where
294        F: AsyncFn(McpAdmission) -> Result<(), McpRejection> + Send + Sync + 'static,
295    {
296        self.0.push(Arc::new(AsyncCheck {
297            admit,
298            to_future_hack,
299        }));
300    }
301
302    /// Runs the checks one after the other and returns the first rejection.
303    /// The checks after it do not run.
304    pub(super) async fn admit(&self, request: &McpAdmission) -> Result<(), McpRejection> {
305        for check in &self.0 {
306            check.admit(request.clone()).await?;
307        }
308        Ok(())
309    }
310}
311
312impl fmt::Debug for AdmissionChecks {
313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314        f.debug_struct("AdmissionChecks")
315            .field("checks", &self.0.len())
316            .finish()
317    }
318}