agent_client_protocol/mcp_server/
admission.rs1use 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#[derive(Clone)]
37pub struct McpAdmission {
38 parts: Arc<Parts>,
40}
41
42#[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
53impl 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 #[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 #[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 #[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 #[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 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 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 #[must_use]
140 pub fn server_id(&self) -> &McpServerAcpId {
141 &self.parts.server_id
142 }
143
144 #[must_use]
146 pub fn request_id(&self) -> &McpRequestId {
147 &self.parts.request_id
148 }
149
150 #[must_use]
152 pub fn method(&self) -> &str {
153 &self.parts.method
154 }
155
156 #[must_use]
158 pub fn params(&self) -> Option<&Map<String, Value>> {
159 self.parts.params.as_ref()
160 }
161
162 #[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 #[must_use]
180 pub fn session_id(&self) -> Option<&SessionId> {
181 self.parts.session_id.as_ref()
182 }
183
184 #[must_use]
191 pub fn tool_call_id(&self) -> Option<&ToolCallId> {
192 self.parts.tool_call_id.as_ref()
193 }
194
195 pub fn require_session_id(&self) -> Result<&SessionId, McpRejection> {
206 self.session_id().ok_or_else(McpRejection::session_required)
207 }
208}
209
210#[derive(Clone, Debug, PartialEq, Eq)]
216pub struct McpRejection {
217 reason: String,
218}
219
220impl McpRejection {
221 #[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 #[must_use]
239 pub fn session_rejected(reason: impl fmt::Display) -> Self {
240 Self {
241 reason: format!("sessionId rejected: {reason}"),
242 }
243 }
244
245 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
259trait Check: Send + Sync {
261 fn admit(&self, request: McpAdmission) -> BoxFuture<'_, Result<(), McpRejection>>;
262}
263
264struct 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#[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 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}