Skip to main content

agent_client_protocol/mcp_server/
registry.rs

1//! Runtime-neutral MCP tool registration and dispatch.
2
3use std::{collections::HashSet, sync::Arc};
4
5use futures::future::BoxFuture;
6use rustc_hash::FxHashMap;
7use schemars::{JsonSchema, generate::SchemaSettings};
8use serde_json::{Map, Value};
9
10use crate::{Error, Role};
11
12#[cfg(feature = "unstable_mcp_over_acp")]
13use super::{McpAdmission, McpRejection, admission::AdmissionChecks};
14use super::{McpConnectionTo, McpTool};
15
16/// JSON Schema object used to describe MCP tool inputs and outputs.
17pub type McpToolSchema = Map<String, Value>;
18
19/// Tracks which tools are enabled.
20///
21/// - `DenyList`: All tools enabled except those in the set (default)
22/// - `AllowList`: Only tools in the set are enabled
23#[derive(Clone, Debug)]
24enum EnabledTools {
25    /// All tools enabled except those in the deny set.
26    DenyList(HashSet<String>),
27    /// Only tools in the allow set are enabled.
28    AllowList(HashSet<String>),
29}
30
31impl Default for EnabledTools {
32    fn default() -> Self {
33        EnabledTools::DenyList(HashSet::new())
34    }
35}
36
37impl EnabledTools {
38    /// Check if a tool is enabled.
39    fn is_enabled(&self, name: &str) -> bool {
40        match self {
41            EnabledTools::DenyList(deny) => !deny.contains(name),
42            EnabledTools::AllowList(allow) => allow.contains(name),
43        }
44    }
45}
46
47/// [`McpToolRegistry::enable_tool`] or [`McpToolRegistry::disable_tool`] named
48/// a tool that is not registered.
49///
50/// This is a local configuration error, usually a typo, not a JSON-RPC error.
51/// Converting it into an [`Error`] with `?` produces an internal error
52/// (`-32603`) whose data names the tool.
53#[derive(Clone, Debug, PartialEq, Eq)]
54#[non_exhaustive]
55pub struct UnknownToolError {
56    name: String,
57}
58
59impl UnknownToolError {
60    fn new(name: &str) -> Self {
61        Self {
62            name: name.to_string(),
63        }
64    }
65
66    /// The tool name that is not registered.
67    #[must_use]
68    pub fn name(&self) -> &str {
69        &self.name
70    }
71}
72
73impl std::fmt::Display for UnknownToolError {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        write!(f, "unknown MCP tool `{}`", self.name)
76    }
77}
78
79impl std::error::Error for UnknownToolError {}
80
81impl From<UnknownToolError> for Error {
82    fn from(error: UnknownToolError) -> Self {
83        Error::internal_error().data(error.to_string())
84    }
85}
86
87/// Runtime-neutral metadata for an MCP tool.
88#[derive(Clone, Debug)]
89pub struct McpToolMetadata {
90    name: String,
91    title: Option<String>,
92    description: String,
93    input_schema: Arc<McpToolSchema>,
94    output_schema: Option<Arc<McpToolSchema>>,
95}
96
97impl McpToolMetadata {
98    fn from_tool<R: Role, M: McpTool<R>>(tool: &M) -> Self {
99        Self {
100            name: tool.name(),
101            title: tool.title(),
102            description: tool.description(),
103            input_schema: schema_for_type::<M::Input>(),
104            output_schema: schema_for_output::<M::Output>(),
105        }
106    }
107
108    /// The tool name.
109    #[must_use]
110    pub fn name(&self) -> &str {
111        &self.name
112    }
113
114    /// A human-readable title for the tool.
115    #[must_use]
116    pub fn title(&self) -> Option<&str> {
117        self.title.as_deref()
118    }
119
120    /// A description of what the tool does.
121    #[must_use]
122    pub fn description(&self) -> &str {
123        &self.description
124    }
125
126    /// JSON Schema object defining the expected parameters for the tool.
127    #[must_use]
128    pub fn input_schema(&self) -> &Arc<McpToolSchema> {
129        &self.input_schema
130    }
131
132    /// Optional JSON Schema object defining the structure of the tool's output.
133    #[must_use]
134    pub fn output_schema(&self) -> Option<&Arc<McpToolSchema>> {
135        self.output_schema.as_ref()
136    }
137}
138
139/// A registered MCP tool that can be dispatched with erased JSON values.
140pub struct RegisteredMcpTool<Counterpart: Role> {
141    metadata: McpToolMetadata,
142    tool: Arc<dyn ErasedMcpTool<Counterpart>>,
143    /// The checks from `McpToolRegistry::add_tool_admission`.
144    #[cfg(feature = "unstable_mcp_over_acp")]
145    admission: AdmissionChecks,
146}
147
148impl<Counterpart: Role + std::fmt::Debug> std::fmt::Debug for RegisteredMcpTool<Counterpart> {
149    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150        f.debug_struct("RegisteredMcpTool")
151            .field("metadata", &self.metadata)
152            .field("has_structured_output", &self.has_structured_output())
153            .finish_non_exhaustive()
154    }
155}
156
157impl<Counterpart: Role> RegisteredMcpTool<Counterpart> {
158    fn new(tool: impl McpTool<Counterpart> + 'static) -> Self {
159        let metadata = McpToolMetadata::from_tool(&tool);
160        Self {
161            metadata,
162            tool: make_erased_mcp_tool(tool),
163            #[cfg(feature = "unstable_mcp_over_acp")]
164            admission: AdmissionChecks::default(),
165        }
166    }
167
168    /// Tool metadata.
169    #[must_use]
170    pub fn metadata(&self) -> &McpToolMetadata {
171        &self.metadata
172    }
173
174    /// The tool name.
175    #[must_use]
176    pub fn name(&self) -> &str {
177        self.metadata.name()
178    }
179
180    /// Whether the tool returns structured output.
181    #[must_use]
182    pub fn has_structured_output(&self) -> bool {
183        self.metadata.output_schema().is_some()
184    }
185
186    /// Invoke the registered tool using JSON input and output values.
187    ///
188    /// # Errors
189    ///
190    /// Returns an invalid params error (`-32602`) if `input` does not
191    /// deserialize into the tool's input type, an internal error (`-32603`) if
192    /// the output does not serialize, and otherwise the tool's own error.
193    pub fn call_tool(
194        &self,
195        input: Value,
196        connection: McpConnectionTo<Counterpart>,
197    ) -> BoxFuture<'_, Result<Value, Error>> {
198        self.tool.call_tool(input, connection)
199    }
200
201    /// Decides whether a call of this tool over ACP is admitted.
202    ///
203    /// Awaits the tool's own [`McpTool::admit`], then the checks added for it
204    /// with [`McpToolRegistry::add_tool_admission`] in the order they were
205    /// added. The checks after a rejection do not run.
206    ///
207    /// # Errors
208    ///
209    /// The future returns the first [`McpRejection`].
210    #[cfg(feature = "unstable_mcp_over_acp")]
211    pub fn admit(&self, request: McpAdmission) -> BoxFuture<'_, Result<(), McpRejection>> {
212        Box::pin(async move {
213            self.tool.admit(request.clone()).await?;
214            self.admission.admit(&request).await
215        })
216    }
217}
218
219/// Runtime-neutral registry for MCP tools.
220#[derive(Debug)]
221pub struct McpToolRegistry<Counterpart: Role> {
222    instructions: Option<String>,
223    tool_indices: FxHashMap<String, usize>,
224    tools: Vec<RegisteredMcpTool<Counterpart>>,
225    enabled_tools: EnabledTools,
226}
227
228impl<Counterpart: Role> Default for McpToolRegistry<Counterpart> {
229    fn default() -> Self {
230        Self {
231            instructions: None,
232            tool_indices: FxHashMap::default(),
233            tools: Vec::new(),
234            enabled_tools: EnabledTools::default(),
235        }
236    }
237}
238
239impl<Counterpart: Role> McpToolRegistry<Counterpart> {
240    /// Set the server instructions that are provided to the client.
241    pub fn set_instructions(&mut self, instructions: impl ToString) {
242        self.instructions = Some(instructions.to_string());
243    }
244
245    /// Server instructions provided to the client.
246    #[must_use]
247    pub fn instructions(&self) -> Option<&str> {
248        self.instructions.as_deref()
249    }
250
251    /// Register a tool.
252    pub fn register_tool(&mut self, tool: impl McpTool<Counterpart> + 'static) {
253        let registered_tool = RegisteredMcpTool::new(tool);
254        let name = registered_tool.name().to_string();
255
256        if let Some(&index) = self.tool_indices.get(&name) {
257            self.tools[index] = registered_tool;
258        } else {
259            self.tool_indices.insert(name, self.tools.len());
260            self.tools.push(registered_tool);
261        }
262    }
263
264    /// Return all registered tools in registration order.
265    pub fn tools(&self) -> impl Iterator<Item = &RegisteredMcpTool<Counterpart>> {
266        self.tools.iter()
267    }
268
269    /// Return enabled registered tools in registration order.
270    pub fn enabled_tools(&self) -> impl Iterator<Item = &RegisteredMcpTool<Counterpart>> {
271        self.tools
272            .iter()
273            .filter(|tool| self.enabled_tools.is_enabled(tool.name()))
274    }
275
276    /// Return a registered tool by name, even if it is disabled.
277    #[must_use]
278    pub fn tool(&self, name: &str) -> Option<&RegisteredMcpTool<Counterpart>> {
279        self.tool_indices
280            .get(name)
281            .and_then(|&index| self.tools.get(index))
282    }
283
284    /// Return an enabled tool by name.
285    #[must_use]
286    pub fn enabled_tool(&self, name: &str) -> Option<&RegisteredMcpTool<Counterpart>> {
287        self.tool(name)
288            .filter(|tool| self.enabled_tools.is_enabled(tool.name()))
289    }
290
291    /// Check whether a tool is registered.
292    #[must_use]
293    pub fn contains_tool(&self, name: &str) -> bool {
294        self.tool_indices.contains_key(name)
295    }
296
297    /// Adds an admission check for one registered tool, for a tool that
298    /// cannot state its rule in [`McpTool::admit`], such as a function tool.
299    ///
300    /// The check is an async closure of the request. Pass
301    /// [`mcp_admission!`](crate::mcp_admission) as the last argument.
302    ///
303    /// The check runs after the tool's own [`McpTool::admit`] and after the
304    /// checks added for the tool before. Registering another tool under the
305    /// same name removes it.
306    ///
307    /// # Errors
308    ///
309    /// Returns [`UnknownToolError`] if no tool with this name is registered.
310    #[cfg(feature = "unstable_mcp_over_acp")]
311    pub fn add_tool_admission<F>(
312        &mut self,
313        name: &str,
314        admit: F,
315        to_future_hack: impl for<'a> Fn(&'a F, McpAdmission) -> BoxFuture<'a, Result<(), McpRejection>>
316        + Send
317        + Sync
318        + 'static,
319    ) -> Result<(), UnknownToolError>
320    where
321        F: AsyncFn(McpAdmission) -> Result<(), McpRejection> + Send + Sync + 'static,
322    {
323        let tool = self
324            .tool_indices
325            .get(name)
326            .and_then(|&index| self.tools.get_mut(index))
327            .ok_or_else(|| UnknownToolError::new(name))?;
328        tool.admission.push(admit, to_future_hack);
329        Ok(())
330    }
331
332    /// Decides whether a request to a server built from this registry is
333    /// admitted.
334    ///
335    /// For a `tools/call` request that names an enabled tool, this is that
336    /// tool's [`RegisteredMcpTool::admit`]. Every other request is admitted,
337    /// including a call of a tool that is unknown or disabled.
338    ///
339    /// # Errors
340    ///
341    /// The future returns the tool's [`McpRejection`].
342    #[cfg(feature = "unstable_mcp_over_acp")]
343    pub fn admit(&self, request: McpAdmission) -> BoxFuture<'_, Result<(), McpRejection>> {
344        match request.tool_name().and_then(|name| self.enabled_tool(name)) {
345            Some(tool) => tool.admit(request),
346            None => Box::pin(std::future::ready(Ok(()))),
347        }
348    }
349
350    /// Disable all tools. After calling this, only tools explicitly enabled
351    /// with [`enable_tool`](Self::enable_tool) will be available.
352    pub fn disable_all_tools(&mut self) {
353        self.enabled_tools = EnabledTools::AllowList(HashSet::new());
354    }
355
356    /// Enable all tools. After calling this, all tools will be available
357    /// except those explicitly disabled with [`disable_tool`](Self::disable_tool).
358    pub fn enable_all_tools(&mut self) {
359        self.enabled_tools = EnabledTools::DenyList(HashSet::new());
360    }
361
362    /// Disable a specific tool by name.
363    ///
364    /// # Errors
365    ///
366    /// Returns [`UnknownToolError`] if no tool with this name is registered.
367    pub fn disable_tool(&mut self, name: &str) -> Result<(), UnknownToolError> {
368        if !self.contains_tool(name) {
369            return Err(UnknownToolError::new(name));
370        }
371        match &mut self.enabled_tools {
372            EnabledTools::DenyList(deny) => {
373                deny.insert(name.to_string());
374            }
375            EnabledTools::AllowList(allow) => {
376                allow.remove(name);
377            }
378        }
379        Ok(())
380    }
381
382    /// Enable a specific tool by name.
383    ///
384    /// # Errors
385    ///
386    /// Returns [`UnknownToolError`] if no tool with this name is registered.
387    pub fn enable_tool(&mut self, name: &str) -> Result<(), UnknownToolError> {
388        if !self.contains_tool(name) {
389            return Err(UnknownToolError::new(name));
390        }
391        match &mut self.enabled_tools {
392            EnabledTools::DenyList(deny) => {
393                deny.remove(name);
394            }
395            EnabledTools::AllowList(allow) => {
396                allow.insert(name.to_string());
397            }
398        }
399        Ok(())
400    }
401}
402
403/// Erased version of the MCP tool trait that is dyn-compatible.
404trait ErasedMcpTool<Counterpart: Role>: Send + Sync {
405    fn call_tool(
406        &self,
407        input: Value,
408        connection: McpConnectionTo<Counterpart>,
409    ) -> BoxFuture<'_, Result<Value, Error>>;
410
411    #[cfg(feature = "unstable_mcp_over_acp")]
412    fn admit(&self, request: McpAdmission) -> BoxFuture<'_, Result<(), McpRejection>>;
413}
414
415fn make_erased_mcp_tool<R, M>(tool: M) -> Arc<dyn ErasedMcpTool<R>>
416where
417    R: Role,
418    M: McpTool<R> + 'static,
419{
420    struct ErasedMcpToolImpl<M> {
421        tool: M,
422    }
423
424    impl<R, M> ErasedMcpTool<R> for ErasedMcpToolImpl<M>
425    where
426        R: Role,
427        M: McpTool<R>,
428    {
429        fn call_tool(
430            &self,
431            input: Value,
432            context: McpConnectionTo<R>,
433        ) -> BoxFuture<'_, Result<Value, Error>> {
434            Box::pin(async move {
435                let input = serde_json::from_value(input)
436                    .map_err(|error| Error::invalid_params().data(error.to_string()))?;
437                serde_json::to_value(self.tool.call_tool(input, context).await?)
438                    .map_err(|error| Error::internal_error().data(error.to_string()))
439            })
440        }
441
442        #[cfg(feature = "unstable_mcp_over_acp")]
443        fn admit(&self, request: McpAdmission) -> BoxFuture<'_, Result<(), McpRejection>> {
444            Box::pin(self.tool.admit(request))
445        }
446    }
447
448    Arc::new(ErasedMcpToolImpl { tool })
449}
450
451fn schema_for_type<T: JsonSchema>() -> Arc<McpToolSchema> {
452    let settings = SchemaSettings::draft2020_12();
453    let generator = settings.into_generator();
454    let schema = generator.into_root_schema_for::<T>();
455    let object = serde_json::to_value(schema).expect("failed to serialize schema");
456    let Value::Object(object) = object else {
457        panic!("Schema serialization produced non-object value: expected JSON object");
458    };
459    Arc::new(object)
460}
461
462fn schema_for_output<T: JsonSchema>() -> Option<Arc<McpToolSchema>> {
463    let schema = schema_for_type::<T>();
464    match schema.get("type") {
465        Some(Value::String(t)) if t == "object" => Some(schema),
466        _ => None,
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use serde::Deserialize;
473
474    use super::*;
475    use crate::{Channel, mcp_server::McpConnectionContext, role::mcp};
476
477    #[derive(Deserialize, JsonSchema)]
478    struct EchoInput {
479        message: String,
480    }
481
482    struct Echo;
483
484    impl McpTool<mcp::Client> for Echo {
485        type Input = EchoInput;
486        type Output = String;
487
488        fn name(&self) -> String {
489            "echo".to_string()
490        }
491
492        fn description(&self) -> String {
493            "Echoes the message".to_string()
494        }
495
496        fn call_tool(
497            &self,
498            input: EchoInput,
499            _context: McpConnectionTo<mcp::Client>,
500        ) -> impl Future<Output = Result<String, Error>> + Send {
501            std::future::ready(Ok(input.message))
502        }
503    }
504
505    #[test]
506    fn call_tool_reports_bad_arguments_as_invalid_params() {
507        let (channel, _peer) = Channel::duplex();
508        futures::executor::block_on(mcp::Server.builder().connect_with(
509            channel,
510            async |connection| {
511                let context = McpConnectionTo {
512                    context: McpConnectionContext::Standalone,
513                    connection,
514                    #[cfg(feature = "unstable_mcp_over_acp")]
515                    cleanup: None,
516                };
517                let mut registry = McpToolRegistry::default();
518                registry.register_tool(Echo);
519                let tool = registry.tool("echo").expect("echo is registered");
520
521                let output = tool
522                    .call_tool(serde_json::json!({ "message": "hi" }), context.clone())
523                    .await?;
524                assert_eq!(output, Value::String("hi".to_string()));
525
526                let error = tool
527                    .call_tool(serde_json::json!({ "msg": "hi" }), context)
528                    .await
529                    .expect_err("mismatched arguments are rejected");
530                assert_eq!(error.code, Error::invalid_params().code);
531                Ok(())
532            },
533        ))
534        .unwrap();
535    }
536
537    #[cfg(feature = "unstable_mcp_over_acp")]
538    #[test]
539    fn registry_admits_by_the_rule_of_the_enabled_tool_a_call_names() {
540        fn admit(
541            registry: &McpToolRegistry<mcp::Client>,
542            method: &str,
543            tool: &str,
544        ) -> Result<(), McpRejection> {
545            let params = serde_json::json!({ "name": tool });
546            let request = McpAdmission::new("server", "request", method)
547                .with_params(params.as_object().unwrap().clone());
548            futures::executor::block_on(registry.admit(request))
549        }
550
551        let mut registry = McpToolRegistry::default();
552        registry.register_tool(Echo);
553        assert_eq!(
554            registry
555                .add_tool_admission("ech", async |_request| Ok(()), crate::mcp_admission!())
556                .unwrap_err()
557                .name(),
558            "ech"
559        );
560        assert_eq!(admit(&registry, "tools/call", "echo"), Ok(()));
561
562        registry
563            .add_tool_admission(
564                "echo",
565                async |request| {
566                    request.require_session_id()?;
567                    Ok(())
568                },
569                crate::mcp_admission!(),
570            )
571            .unwrap();
572        assert_eq!(
573            admit(&registry, "tools/call", "echo"),
574            Err(McpRejection::session_required())
575        );
576        // Only a call of the tool is its business.
577        assert_eq!(admit(&registry, "tools/list", "echo"), Ok(()));
578        assert_eq!(admit(&registry, "tools/call", "missing"), Ok(()));
579
580        registry.disable_tool("echo").unwrap();
581        assert_eq!(admit(&registry, "tools/call", "echo"), Ok(()));
582        registry.enable_tool("echo").unwrap();
583        assert_eq!(
584            admit(&registry, "tools/call", "echo"),
585            Err(McpRejection::session_required())
586        );
587
588        // Registering the tool again replaces it and the checks added for it.
589        registry.register_tool(Echo);
590        assert_eq!(admit(&registry, "tools/call", "echo"), Ok(()));
591    }
592}