Skip to main content

agent_client_protocol/mcp_server/
service.rs

1//! Reusable application services with request-scoped execution authority.
2
3use std::sync::{
4    Arc, Mutex,
5    atomic::{AtomicBool, Ordering},
6};
7
8use futures::{
9    channel::oneshot,
10    future::{BoxFuture, FutureExt, Shared},
11};
12use serde_json::{Map, Value};
13
14use super::{McpAdmission, McpConnectionTo, McpRejection};
15use crate::{
16    Error, RequestCancellation, Role,
17    v1::schema::{McpError, McpRequestId, McpServerAcpId, SessionId, ToolCallId},
18};
19
20/// One MCP invocation against a reusable service.
21#[derive(Debug)]
22pub struct McpRequest {
23    /// MCP method, without an implicit initialize or discovery exchange.
24    pub method: String,
25    /// Named parameters, including validated request metadata.
26    pub params: Option<Map<String, Value>>,
27}
28
29/// An MCP outcome, distinct from failure of the ACP binding.
30#[derive(Debug)]
31pub enum McpOutcome {
32    /// Opaque successful MCP result.
33    Result(Value),
34    /// Unmodified MCP error, including absent/null data and extension fields.
35    Error(McpError),
36}
37
38type Notify = dyn Fn(String, Option<Map<String, Value>>) -> BoxFuture<'static, Result<(), Error>>
39    + Send
40    + Sync;
41
42/// Cancellation from the caller, provider removal, or connection shutdown.
43#[derive(Clone)]
44pub struct McpOperationCancellation {
45    state: Arc<CancellationState>,
46}
47
48struct CancellationState {
49    cancelled: AtomicBool,
50    sender: Mutex<Option<oneshot::Sender<()>>>,
51    signal: Shared<BoxFuture<'static, ()>>,
52}
53
54impl std::fmt::Debug for McpOperationCancellation {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.debug_struct("McpOperationCancellation")
57            .field("cancelled", &self.is_cancelled())
58            .finish()
59    }
60}
61
62impl McpOperationCancellation {
63    pub(crate) fn new() -> Self {
64        let (sender, receiver) = oneshot::channel();
65        Self {
66            state: Arc::new(CancellationState {
67                cancelled: AtomicBool::new(false),
68                sender: Mutex::new(Some(sender)),
69                signal: receiver.map(|_| ()).boxed().shared(),
70            }),
71        }
72    }
73
74    pub(crate) fn cancel(&self) {
75        self.state.cancelled.store(true, Ordering::Release);
76        drop(
77            self.state
78                .sender
79                .lock()
80                .expect("MCP cancellation poisoned")
81                .take(),
82        );
83    }
84
85    /// Wait until the operation loses its output authority.
86    pub async fn cancelled(&self) {
87        self.state.signal.clone().await;
88    }
89
90    /// Whether cancellation has been requested.
91    #[must_use]
92    pub fn is_cancelled(&self) -> bool {
93        self.state.cancelled.load(Ordering::Acquire)
94    }
95}
96
97/// Authority for a single operation, not for the lifetime of its service.
98#[derive(Clone)]
99pub struct McpRequestContext<Counterpart: Role> {
100    server_id: McpServerAcpId,
101    request_id: McpRequestId,
102    connection: McpConnectionTo<Counterpart>,
103    metadata: Map<String, Value>,
104    cancellation: RequestCancellation,
105    operation_cancellation: McpOperationCancellation,
106    notify: Arc<Notify>,
107}
108
109impl<Counterpart: Role> std::fmt::Debug for McpRequestContext<Counterpart> {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.debug_struct("McpRequestContext")
112            .field("server_id", &self.server_id)
113            .field("request_id", &self.request_id)
114            .field("metadata", &self.metadata)
115            .field("operation_cancellation", &self.operation_cancellation)
116            .finish_non_exhaustive()
117    }
118}
119
120impl<Counterpart: Role> McpRequestContext<Counterpart> {
121    pub(crate) fn new(
122        server_id: McpServerAcpId,
123        request_id: McpRequestId,
124        connection: McpConnectionTo<Counterpart>,
125        metadata: Map<String, Value>,
126        cancellation: RequestCancellation,
127        operation_cancellation: McpOperationCancellation,
128        notify: Arc<Notify>,
129    ) -> Self {
130        Self {
131            server_id,
132            request_id,
133            connection,
134            metadata,
135            cancellation,
136            operation_cancellation,
137            notify,
138        }
139    }
140
141    /// Server identifier bound to this invocation.
142    pub fn server_id(&self) -> &McpServerAcpId {
143        &self.server_id
144    }
145    /// Logical request identifier, held until cleanup and terminal output finish.
146    pub fn request_id(&self) -> &McpRequestId {
147        &self.request_id
148    }
149    /// The session the Agent says this request was sent for.
150    ///
151    /// Returns `None` for a standalone MCP connection, and when the Agent
152    /// supplied no session. For a child session's work this is the child's ID.
153    ///
154    /// The SDK does not check the value. Before you use it to choose what a
155    /// request acts on, check that the session is active on the connection, or
156    /// is a child that the Agent announced for an active session, and that this
157    /// server was declared to it or to one of its ancestors.
158    pub fn session_id(&self) -> Option<&SessionId> {
159        self.connection.session_id()
160    }
161    /// The tool call, in the session returned by `session_id`, that the Agent
162    /// says this request is part of.
163    ///
164    /// Returns `None` for a standalone MCP connection, and when the Agent
165    /// supplied no tool call. The Agent can report the tool call after it
166    /// sends the request, so the ID might not be known yet.
167    pub fn tool_call_id(&self) -> Option<&ToolCallId> {
168        self.connection.tool_call_id()
169    }
170    /// Host connection for application tools.
171    pub fn connection(&self) -> &McpConnectionTo<Counterpart> {
172        &self.connection
173    }
174    /// Validated protocol version and client capability metadata.
175    pub fn metadata(&self) -> &Map<String, Value> {
176        &self.metadata
177    }
178    /// Cancellation of the outer ACP request.
179    pub fn cancellation(&self) -> &RequestCancellation {
180        &self.cancellation
181    }
182    /// Cancellation including provider removal and transport EOF.
183    pub fn operation_cancellation(&self) -> &McpOperationCancellation {
184        &self.operation_cancellation
185    }
186
187    /// Send an operation-scoped notification while this invocation is live.
188    ///
189    /// # Errors
190    ///
191    /// Returns Request cancelled (`-32800`) if the operation has finished
192    /// or was cancelled. Otherwise propagates any failure to send the notification.
193    pub async fn send_notification(
194        &self,
195        method: impl Into<String>,
196        params: Option<Map<String, Value>>,
197    ) -> Result<(), Error> {
198        if self.cancellation.is_cancelled() || self.operation_cancellation.is_cancelled() {
199            return Err(Error::request_cancelled());
200        }
201        (self.notify)(method.into(), params).await
202    }
203}
204
205/// Reusable MCP application state with owned invocation futures.
206pub trait McpService<Counterpart: Role>: Send + Sync + 'static {
207    /// Decides, before [`execute`](Self::execute) is called, whether a
208    /// request is admitted. The default admits every request.
209    ///
210    /// The SDK awaits it after the checks the server was given with
211    /// [`McpServer::with_admission`](super::McpServer::with_admission), and
212    /// answers a rejection the same way: with the outer ACP error Invalid
213    /// params (`-32602`), without calling `execute`. A service built from a
214    /// tool registry uses it to apply the rule of the tool a `tools/call`
215    /// request names.
216    ///
217    /// The SDK drops the returned future when the request is cancelled, its
218    /// server registration is removed, or the connection shuts down. It must
219    /// not own work that needs cleanup.
220    ///
221    /// # Errors
222    ///
223    /// The future returns the [`McpRejection`] that answers a request the
224    /// service does not admit.
225    fn admit(&self, request: McpAdmission) -> BoxFuture<'static, Result<(), McpRejection>> {
226        drop(request);
227        Box::pin(std::future::ready(Ok(())))
228    }
229
230    /// Execute one invocation, including backend teardown.
231    ///
232    /// On operation cancellation, stop user work and complete owned cleanup
233    /// before returning. The binding drives this future through cancellation;
234    /// dropping it is not used as a substitute for joining cleanup.
235    ///
236    /// # Errors
237    ///
238    /// An `Err` from an operation that ran to its end is reported to the
239    /// Agent as an MCP backend failure (`-33002`) with the error's text as
240    /// `data`, whatever the error's own code is. To answer Invalid params
241    /// (`-32602`) for a missing or refused session, reject the request before
242    /// it runs, in [`admit`](Self::admit) or with
243    /// [`McpServer::with_admission`](super::McpServer::with_admission).
244    fn execute(
245        &self,
246        request: McpRequest,
247        context: McpRequestContext<Counterpart>,
248    ) -> BoxFuture<'static, Result<McpOutcome, Error>>;
249}