Skip to main content

rigspark_runtime/
mcp.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use sha2::{Digest, Sha256};
4use std::{
5    collections::{BTreeMap, HashSet},
6    path::{Path, PathBuf},
7    time::Duration,
8};
9use tokio_util::sync::CancellationToken;
10#[derive(Debug, thiserror::Error)]
11pub enum McpError {
12    #[error("invalid MCP connector or response")]
13    Invalid,
14    #[error("MCP connector unavailable")]
15    Unavailable,
16    #[error("MCP request failed")]
17    Transport,
18    #[error("MCP request cancelled")]
19    Cancelled,
20    #[error("MCP resource limit exceeded")]
21    Limit,
22    #[error("MCP approval missing, stale, or mismatched")]
23    Approval,
24    #[error("MCP persistence failed")]
25    Storage,
26}
27#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(tag = "transport", rename_all = "lowercase", deny_unknown_fields)]
29pub enum Connector {
30    Stdio {
31        id: String,
32        name: String,
33        command: String,
34        #[serde(default)]
35        args: Vec<String>,
36        #[serde(skip_serializing_if = "Option::is_none")]
37        env: Option<BTreeMap<String, String>>,
38    },
39    Http {
40        id: String,
41        name: String,
42        url: String,
43    },
44}
45impl std::fmt::Debug for Connector {
46    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        formatter
48            .debug_struct("Connector")
49            .field("id", &self.id())
50            .finish_non_exhaustive()
51    }
52}
53pub fn loopback_url(raw: &str) -> Result<url::Url, McpError> {
54    let url = url::Url::parse(raw).map_err(|_| McpError::Invalid)?;
55    let local = match url.host() {
56        Some(url::Host::Ipv4(address)) => address.is_loopback(),
57        Some(url::Host::Ipv6(address)) => address.is_loopback(),
58        Some(url::Host::Domain(domain)) => domain == "localhost",
59        None => false,
60    };
61    if !local
62        || !["http", "https"].contains(&url.scheme())
63        || !url.username().is_empty()
64        || url.password().is_some()
65        || raw.len() > 2048
66        || raw.chars().any(char::is_control)
67    {
68        return Err(McpError::Invalid);
69    }
70    Ok(url)
71}
72impl Connector {
73    pub fn id(&self) -> &str {
74        match self {
75            Self::Stdio { id, .. } | Self::Http { id, .. } => id,
76        }
77    }
78    pub fn name(&self) -> &str {
79        match self {
80            Self::Stdio { name, .. } | Self::Http { name, .. } => name,
81        }
82    }
83    pub fn validate(&self) -> Result<(), McpError> {
84        let id = self.id();
85        if id.is_empty()
86            || id.len() > 64
87            || !id.as_bytes()[0].is_ascii_alphanumeric()
88            || !id
89                .bytes()
90                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
91            || self.name().trim().is_empty()
92            || self.name().len() > 120
93        {
94            return Err(McpError::Invalid);
95        }
96        match self {
97            Self::Http { url, .. } => {
98                loopback_url(url)?;
99            }
100            Self::Stdio {
101                command, args, env, ..
102            } => {
103                if command.trim().is_empty()
104                    || command.len() > 512
105                    || command.contains('\0')
106                    || args.len() > 64
107                    || args.iter().any(|arg| arg.len() > 512 || arg.contains('\0'))
108                    || env.as_ref().is_some_and(|env| {
109                        env.len() > 64
110                            || env.iter().any(|(key, value)| {
111                                key.is_empty()
112                                    || key.len() > 256
113                                    || key.contains(['\0', '='])
114                                    || value.len() > 4096
115                                    || value.contains('\0')
116                            })
117                    })
118                {
119                    return Err(McpError::Invalid);
120                }
121            }
122        }
123        Ok(())
124    }
125}
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(rename_all = "camelCase", deny_unknown_fields)]
128pub struct ConnectorFile {
129    pub schema_version: u8,
130    pub connectors: Vec<Connector>,
131}
132impl Default for ConnectorFile {
133    fn default() -> Self {
134        Self {
135            schema_version: 1,
136            connectors: Vec::new(),
137        }
138    }
139}
140impl ConnectorFile {
141    pub fn parse(raw: &str) -> Result<Self, McpError> {
142        if raw.len() > 65536 {
143            return Err(McpError::Limit);
144        }
145        if raw.trim().is_empty() {
146            return Ok(Self::default());
147        }
148        let file: Self = serde_json::from_str(raw).map_err(|_| McpError::Invalid)?;
149        file.validate()?;
150        Ok(file)
151    }
152    pub fn validate(&self) -> Result<(), McpError> {
153        if self.schema_version != 1 || self.connectors.len() > 32 {
154            return Err(McpError::Invalid);
155        }
156        let mut ids = HashSet::new();
157        for connector in &self.connectors {
158            connector.validate()?;
159            if !ids.insert(connector.id()) {
160                return Err(McpError::Invalid);
161            }
162        }
163        Ok(())
164    }
165}
166pub struct ConnectorStore {
167    home: PathBuf,
168}
169impl ConnectorStore {
170    pub fn new(home: &Path) -> Self {
171        Self { home: home.into() }
172    }
173    pub fn load(&self) -> Result<ConnectorFile, McpError> {
174        match crate::state::secure_read(&self.home.join("connectors.json"), 65536, false) {
175            Ok(raw) => ConnectorFile::parse(&raw),
176            Err(error) if error.kind == "absent" => Ok(ConnectorFile::default()),
177            Err(_) => Err(McpError::Storage),
178        }
179    }
180    pub fn save(&self, file: &ConnectorFile) -> Result<(), McpError> {
181        file.validate()?;
182        let bytes = format!(
183            "{}\n",
184            serde_json::to_string_pretty(file).map_err(|_| McpError::Invalid)?
185        );
186        if bytes.len() > 65536 {
187            return Err(McpError::Limit);
188        }
189        crate::memory::owned_directory(&self.home).map_err(|_| McpError::Storage)?;
190        let store = crate::state::StateStore::new(
191            crate::state::Config::from_home(&self.home).map_err(|_| McpError::Storage)?,
192        );
193        let guard = store
194            .lock(Duration::from_secs(10))
195            .map_err(|_| McpError::Storage)?;
196        crate::memory::atomic_file(&self.home.join("connectors.json"), bytes.as_bytes())
197            .map_err(|_| McpError::Storage)?;
198        guard.release().map_err(|_| McpError::Storage)
199    }
200}
201#[derive(Debug, Clone, Serialize, Deserialize)]
202#[serde(rename_all = "camelCase", deny_unknown_fields)]
203pub struct Tool {
204    pub name: String,
205    pub description: String,
206    pub input_schema: Value,
207}
208#[derive(Debug, Clone, Serialize, Deserialize)]
209#[serde(rename_all = "camelCase", deny_unknown_fields)]
210pub struct ToolResult {
211    pub content: String,
212    pub is_error: bool,
213}
214#[async_trait::async_trait]
215pub trait Connection: Send + Sync {
216    async fn tools(&mut self, cancel: &CancellationToken) -> Result<Vec<Tool>, McpError>;
217    async fn call(
218        &mut self,
219        name: &str,
220        args: Value,
221        cancel: &CancellationToken,
222    ) -> Result<ToolResult, McpError>;
223    async fn close(&mut self) -> Result<(), McpError>;
224}
225#[async_trait::async_trait]
226pub trait ClientFactory: Send + Sync {
227    async fn connect(
228        &self,
229        connector: &Connector,
230        cancel: &CancellationToken,
231    ) -> Result<Box<dyn Connection>, McpError>;
232}
233struct Entry {
234    connection: Box<dyn Connection>,
235    tools: Vec<Tool>,
236    generation: String,
237}
238#[derive(Serialize)]
239#[serde(rename_all = "camelCase")]
240pub struct ReviewedCall {
241    pub connector_id: String,
242    pub tool: String,
243    #[serde(serialize_with = "crate::tool_policy::serialize_arguments")]
244    pub arguments: Value,
245    pub risk: crate::tool_policy::ToolRisk,
246    #[serde(skip)]
247    tool_identity: String,
248    #[serde(skip)]
249    fingerprint: String,
250    #[serde(skip)]
251    generation: String,
252}
253pub struct Approval {
254    reviewed: ReviewedCall,
255    manager: String,
256}
257pub struct Manager {
258    definitions: ConnectorFile,
259    entries: BTreeMap<String, Entry>,
260    identity: String,
261    failures: BTreeMap<String, String>,
262}
263#[derive(Serialize)]
264pub struct ConnectorView {
265    pub id: String,
266    pub name: String,
267    pub transport: &'static str,
268    pub target: String,
269    pub status: &'static str,
270    pub tools: Vec<Tool>,
271    #[serde(skip_serializing_if = "Option::is_none")]
272    pub error: Option<String>,
273}
274fn fingerprint(value: &impl Serialize) -> Result<String, McpError> {
275    let value = serde_json::to_value(value).map_err(|_| McpError::Invalid)?;
276    let bytes = serde_json::to_vec(&value).map_err(|_| McpError::Invalid)?;
277    if bytes.len() > 1048576 {
278        return Err(McpError::Limit);
279    }
280    Ok(format!("{:x}", Sha256::digest(bytes)))
281}
282impl Manager {
283    pub fn new(definitions: ConnectorFile) -> Result<Self, McpError> {
284        definitions.validate()?;
285        Ok(Self {
286            definitions,
287            entries: BTreeMap::new(),
288            identity: uuid::Uuid::new_v4().to_string(),
289            failures: BTreeMap::new(),
290        })
291    }
292    pub fn snapshot(&self) -> ConnectorFile {
293        self.definitions.clone()
294    }
295    pub fn list(&self) -> Vec<ConnectorView> {
296        self.definitions
297            .connectors
298            .iter()
299            .map(|connector| {
300                let entry = self.entries.get(connector.id());
301                let error = self.failures.get(connector.id()).cloned();
302                let (transport, target) = match connector {
303                    Connector::Stdio { command, .. } => ("stdio", command.clone()),
304                    Connector::Http { url, .. } => ("http", url.clone()),
305                };
306                ConnectorView {
307                    id: connector.id().into(),
308                    name: connector.name().into(),
309                    transport,
310                    target,
311                    status: if entry.is_some() {
312                        "connected"
313                    } else if error.is_some() {
314                        "error"
315                    } else {
316                        "disconnected"
317                    },
318                    tools: entry.map(|entry| entry.tools.clone()).unwrap_or_default(),
319                    error,
320                }
321            })
322            .collect()
323    }
324    pub async fn add(
325        &mut self,
326        connector: Connector,
327        store: &ConnectorStore,
328    ) -> Result<(), McpError> {
329        connector.validate()?;
330        if self
331            .definitions
332            .connectors
333            .iter()
334            .any(|entry| entry.id() == connector.id())
335        {
336            return Err(McpError::Invalid);
337        }
338        let mut file = self.snapshot();
339        file.connectors.push(connector);
340        self.replace(file, store).await
341    }
342    pub async fn remove(&mut self, id: &str, store: &ConnectorStore) -> Result<(), McpError> {
343        if !self
344            .definitions
345            .connectors
346            .iter()
347            .any(|entry| entry.id() == id)
348        {
349            return Err(McpError::Invalid);
350        }
351        let mut file = self.snapshot();
352        file.connectors.retain(|entry| entry.id() != id);
353        self.replace(file, store).await
354    }
355    pub fn tools(&self) -> Vec<(String, Tool)> {
356        self.definitions
357            .connectors
358            .iter()
359            .filter_map(|connector| {
360                self.entries
361                    .get(connector.id())
362                    .map(|entry| (connector.id(), entry))
363            })
364            .flat_map(|(id, entry)| {
365                entry
366                    .tools
367                    .iter()
368                    .map(move |tool| (id.to_owned(), tool.clone()))
369            })
370            .collect()
371    }
372    pub async fn connect(
373        &mut self,
374        id: &str,
375        factory: &dyn ClientFactory,
376        cancel: &CancellationToken,
377    ) -> Result<(), McpError> {
378        let connector = self
379            .definitions
380            .connectors
381            .iter()
382            .find(|connector| connector.id() == id)
383            .ok_or(McpError::Invalid)?;
384        let connection = tokio::select! {biased;_=cancel.cancelled()=>Err(McpError::Cancelled),result=tokio::time::timeout(Duration::from_secs(15),factory.connect(connector,cancel))=>result.map_err(|_|McpError::Transport).and_then(|result|result)};
385        let result = match connection {
386            Ok(connection) => self.attach(id, connection, cancel).await,
387            Err(error) => Err(error),
388        };
389        if let Err(error) = &result {
390            self.failures.insert(id.into(), error.to_string());
391        }
392        result
393    }
394    pub async fn attach(
395        &mut self,
396        id: &str,
397        mut connection: Box<dyn Connection>,
398        cancel: &CancellationToken,
399    ) -> Result<(), McpError> {
400        if !self
401            .definitions
402            .connectors
403            .iter()
404            .any(|connector| connector.id() == id)
405        {
406            let _ = tokio::time::timeout(Duration::from_secs(5), connection.close()).await;
407            return Err(McpError::Invalid);
408        }
409        let tools = tokio::select! {biased;_=cancel.cancelled()=>Err(McpError::Cancelled),result=tokio::time::timeout(Duration::from_secs(15),connection.tools(cancel))=>result.map_err(|_|McpError::Transport).and_then(|result|result)};
410        let tools = match tools {
411            Ok(tools) => tools,
412            Err(error) => {
413                let _ = tokio::time::timeout(Duration::from_secs(5), connection.close()).await;
414                return Err(error);
415            }
416        };
417        let mut names = HashSet::new();
418        if tools.len() > 1024
419            || tools.iter().any(|tool| {
420                tool.name.is_empty()
421                    || tool.name.len() > 256
422                    || tool.description.len() > 65536
423                    || !tool.input_schema.is_object()
424                    || !names.insert(&tool.name)
425            })
426            || serde_json::to_vec(&tools)
427                .map_err(|_| McpError::Invalid)?
428                .len()
429                > 1048576
430        {
431            let _ = tokio::time::timeout(Duration::from_secs(5), connection.close()).await;
432            return Err(McpError::Limit);
433        }
434        if let Err(error) = self.disconnect(id).await {
435            let _ = tokio::time::timeout(Duration::from_secs(5), connection.close()).await;
436            return Err(error);
437        }
438        self.entries.insert(
439            id.into(),
440            Entry {
441                connection,
442                tools,
443                generation: uuid::Uuid::new_v4().to_string(),
444            },
445        );
446        self.failures.remove(id);
447        Ok(())
448    }
449    pub fn review(&self, id: &str, name: &str, arguments: Value) -> Result<ReviewedCall, McpError> {
450        if !arguments.is_object() {
451            return Err(McpError::Invalid);
452        }
453        let connector = self
454            .definitions
455            .connectors
456            .iter()
457            .find(|connector| connector.id() == id)
458            .ok_or(McpError::Invalid)?;
459        let entry = self.entries.get(id).ok_or(McpError::Unavailable)?;
460        let tool = entry
461            .tools
462            .iter()
463            .find(|tool| tool.name == name)
464            .ok_or(McpError::Invalid)?;
465        Ok(ReviewedCall {
466            connector_id: id.into(),
467            tool: name.into(),
468            risk: crate::tool_policy::classify(&tool.name, &tool.description),
469            tool_identity: fingerprint(&(1, &self.identity, &entry.generation, connector, tool))?,
470            fingerprint: fingerprint(&(connector, tool, &arguments))?,
471            arguments,
472            generation: entry.generation.clone(),
473        })
474    }
475    pub fn approve(&self, reviewed: ReviewedCall) -> Result<Approval, McpError> {
476        let current = self.review(
477            &reviewed.connector_id,
478            &reviewed.tool,
479            reviewed.arguments.clone(),
480        )?;
481        if current.fingerprint != reviewed.fingerprint || current.generation != reviewed.generation
482        {
483            return Err(McpError::Approval);
484        }
485        Ok(Approval {
486            reviewed,
487            manager: self.identity.clone(),
488        })
489    }
490    pub fn approve_session(
491        &self,
492        reviewed: ReviewedCall,
493        grants: &mut crate::tool_policy::SessionGrants,
494    ) -> Result<Approval, McpError> {
495        let approval = self.approve(reviewed)?;
496        if !grants.grant(approval.reviewed.tool_identity.clone()) {
497            return Err(McpError::Approval);
498        }
499        Ok(approval)
500    }
501    pub fn session_approval(
502        &self,
503        reviewed: ReviewedCall,
504        grants: &crate::tool_policy::SessionGrants,
505    ) -> Result<Approval, McpError> {
506        let approval = self.approve(reviewed)?;
507        if !grants.allows(&approval.reviewed.tool_identity) {
508            return Err(McpError::Approval);
509        }
510        Ok(approval)
511    }
512    pub async fn call(
513        &mut self,
514        id: &str,
515        name: &str,
516        arguments: Value,
517        approval: Option<Approval>,
518        cancel: &CancellationToken,
519    ) -> Result<ToolResult, McpError> {
520        let approval = approval.ok_or(McpError::Approval)?;
521        let current = self.review(id, name, arguments.clone())?;
522        if approval.manager != self.identity
523            || approval.reviewed.fingerprint != current.fingerprint
524            || approval.reviewed.generation != current.generation
525        {
526            return Err(McpError::Approval);
527        }
528        let entry = self.entries.get_mut(id).ok_or(McpError::Unavailable)?;
529        let result = tokio::select! {biased;_=cancel.cancelled()=>Err(McpError::Cancelled),result=tokio::time::timeout(Duration::from_secs(60),entry.connection.call(name,arguments,cancel))=>result.map_err(|_|McpError::Transport).and_then(|result|result)};
530        let result = result.and_then(|result| {
531            if result.content.len() > 1048576 {
532                Err(McpError::Limit)
533            } else {
534                Ok(result)
535            }
536        });
537        if result.is_err() {
538            let _ = self.disconnect(id).await;
539        }
540        result
541    }
542    pub async fn disconnect(&mut self, id: &str) -> Result<(), McpError> {
543        self.failures.remove(id);
544        if let Some(mut entry) = self.entries.remove(id) {
545            tokio::time::timeout(Duration::from_secs(5), entry.connection.close())
546                .await
547                .map_err(|_| McpError::Transport)??;
548        }
549        Ok(())
550    }
551    pub async fn replace(
552        &mut self,
553        file: ConnectorFile,
554        store: &ConnectorStore,
555    ) -> Result<(), McpError> {
556        file.validate()?;
557        store.save(&file)?;
558        let removed: Vec<_> = self
559            .definitions
560            .connectors
561            .iter()
562            .filter(|old| !file.connectors.contains(old))
563            .map(|old| old.id().to_owned())
564            .collect();
565        self.definitions = file;
566        let mut failed = false;
567        for id in removed {
568            failed |= self.disconnect(&id).await.is_err();
569        }
570        if failed {
571            Err(McpError::Transport)
572        } else {
573            Ok(())
574        }
575    }
576    pub async fn shutdown(&mut self) -> Result<(), McpError> {
577        let ids: Vec<_> = self.entries.keys().cloned().collect();
578        let mut failure = false;
579        for id in ids {
580            failure |= self.disconnect(&id).await.is_err();
581        }
582        if failure {
583            Err(McpError::Transport)
584        } else {
585            Ok(())
586        }
587    }
588}