Skip to main content

graphrt_mcp/
lib.rs

1//! # graphrt-mcp
2//!
3//! Exposes the tools of [Model Context Protocol](https://modelcontextprotocol.io)
4//! servers to graphrt's `tool` and `agent` nodes.
5//!
6//! ```no_run
7//! # async fn demo() -> Result<(), graphrt_mcp::McpError> {
8//! use graphrt_mcp::{McpServers, connect_all};
9//!
10//! let servers: McpServers = serde_json::from_str(r#"{
11//!     "mcpServers": {
12//!         "fs": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"] },
13//!         "remote": { "url": "https://mcp.example.com/mcp", "bearer_token": "..." }
14//!     }
15//! }"#).unwrap_or_default();
16//! let tools = connect_all(&servers.into_configs()).await?;
17//! let services = graphrt_core::Services::new().with(tools);
18//! # let _ = services;
19//! # Ok(()) }
20//! ```
21//!
22//! Each server is registered in the [`ToolRegistry`] under both `<name>` and
23//! `mcp:<name>`, so a `tool` node can use `provider_id: mcp:fs`.
24//!
25//! Security defaults: stdio servers start with an empty environment except for
26//! a few launcher essentials ([`config::DEFAULT_PASS_ENV`]) plus explicitly
27//! listed variables; every request has a timeout; `allowed_tools` restricts
28//! which tools are exposed.
29
30pub mod config;
31pub mod content;
32pub mod runtime;
33
34use std::sync::Arc;
35
36use graphrt_core::tool::ToolRegistry;
37
38pub use config::{HttpConfig, McpServerConfig, McpServers, McpTransport, StdioConfig};
39pub use runtime::{McpError, McpToolRuntime};
40
41/// Prefix of the alias provider name for MCP servers.
42pub const PROVIDER_PREFIX: &str = "mcp:";
43
44/// Register a connected server under `<name>` and `mcp:<name>`, replacing any
45/// provider already registered under those names. Prefer [`try_register`], which
46/// refuses to shadow an existing provider.
47pub fn register(registry: &mut ToolRegistry, runtime: McpToolRuntime) {
48    let name = runtime.name().to_owned();
49    let runtime = Arc::new(runtime);
50    registry.add(format!("{PROVIDER_PREFIX}{name}"), runtime.clone());
51    registry.add(name, runtime);
52}
53
54/// Register a connected server under `<name>` and `mcp:<name>`. Fails if either name
55/// is already taken, so a server can never silently replace another provider
56/// (for example one named `builtin`).
57pub fn try_register(registry: &mut ToolRegistry, runtime: McpToolRuntime) -> Result<(), McpError> {
58    let name = runtime.name().to_owned();
59    validate_name(&name)?;
60    let alias = format!("{PROVIDER_PREFIX}{name}");
61    for provider in [&name, &alias] {
62        if registry.get(provider).is_some() {
63            return Err(McpError::DuplicateProvider(provider.clone()));
64        }
65    }
66    register(registry, runtime);
67    Ok(())
68}
69
70/// Check server names before connecting: non-empty, no `/` (tools are referenced as
71/// `provider/tool`), and unique.
72pub fn validate_configs(configs: &[McpServerConfig]) -> Result<(), McpError> {
73    let mut seen = std::collections::HashSet::new();
74    for config in configs {
75        validate_name(&config.name)?;
76        if !seen.insert(config.name.as_str()) {
77            return Err(McpError::Config(format!("duplicate MCP server name `{}`", config.name)));
78        }
79    }
80    Ok(())
81}
82
83fn validate_name(name: &str) -> Result<(), McpError> {
84    if name.trim().is_empty() {
85        return Err(McpError::Config("MCP server name must not be empty".to_owned()));
86    }
87    if name.contains('/') {
88        return Err(McpError::Config(format!("MCP server name `{name}` must not contain `/`")));
89    }
90    Ok(())
91}
92
93/// Connect to every server concurrently and build a [`ToolRegistry`].
94/// Names are validated first; fails on the first server that cannot be connected.
95pub async fn connect_all(configs: &[McpServerConfig]) -> Result<ToolRegistry, McpError> {
96    validate_configs(configs)?;
97    let connections = futures::future::join_all(configs.iter().map(McpToolRuntime::connect)).await;
98    let mut registry = ToolRegistry::new();
99    for connection in connections {
100        try_register(&mut registry, connection?)?;
101    }
102    Ok(registry)
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    fn cfg(name: &str) -> McpServerConfig {
110        serde_json::from_value(serde_json::json!({"name": name, "command": "srv"})).unwrap()
111    }
112
113    #[test]
114    fn config_names_are_validated() {
115        assert!(validate_configs(&[cfg("a"), cfg("b")]).is_ok());
116        assert!(matches!(validate_configs(&[cfg("a"), cfg("a")]), Err(McpError::Config(m)) if m.contains("duplicate")));
117        assert!(validate_configs(&[cfg("")]).is_err());
118        assert!(validate_configs(&[cfg("a/b")]).is_err());
119    }
120
121    #[tokio::test]
122    async fn connect_all_rejects_duplicates_before_spawning() {
123        // `srv` does not exist: a spawn would fail with a different error.
124        let err = connect_all(&[cfg("dup"), cfg("dup")]).await.unwrap_err();
125        assert!(matches!(err, McpError::Config(_)), "{err}");
126    }
127}