rig-mcp-server 0.47.6

Serve Rig agents and tools over the Model Context Protocol (MCP): agents as tools with sessions, streamed progress and cancellation; typed agents with structured output; stdio and Streamable HTTP.
Documentation
//! The static resources, resource templates and prompts a server offers next to
//! its tools.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use futures::future::BoxFuture;
use percent_encoding::percent_decode_str;
use rmcp::model::{Prompt, PromptMessage, Resource, ResourceContents, ResourceTemplate};

use crate::completion::BoxError;

/// A prompt's rendering: the arguments a client passed, in, and its messages out.
pub(crate) type Render = Arc<dyn Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Send + Sync>;

/// A resource template's read: the variables a URI matched, in, and its text out.
pub(crate) type TemplateRead =
    Arc<dyn Fn(TemplateVars) -> BoxFuture<'static, Result<String, BoxError>> + Send + Sync>;

/// A resource with its fixed contents, returned by `resources/read`.
pub(crate) struct StaticResource {
    pub(crate) resource: Resource,
    pub(crate) contents: ResourceContents,
}

/// A resource template, listed by `resources/templates/list` and read for any URI
/// its pattern matches.
pub(crate) struct StaticTemplate {
    pub(crate) template: ResourceTemplate,
    pub(crate) read: TemplateRead,
}

/// A prompt, listed with its arguments and rendered by `prompts/get`.
pub(crate) struct StaticPrompt {
    pub(crate) prompt: Prompt,
    pub(crate) render: Render,
}

/// The values of a resource template's variables, taken from a read URI.
///
/// A variable is written `{name}` in the template. It matches one or more
/// characters of the URI that are not a literal `/`, so an encoded `%2F` stays
/// inside one segment. The value is percent-decoded. A URI whose value does not
/// decode to UTF-8 does not match.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TemplateVars(HashMap<String, String>);

impl TemplateVars {
    /// The value of the variable `name`, if the template has one by that name.
    pub fn get(&self, name: &str) -> Option<&str> {
        self.0.get(name).map(String::as_str)
    }
}

/// One part of a parsed template: fixed text, or a variable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Piece {
    Literal(String),
    Var(String),
}

/// Parse a template such as `memo://{id}/notes`. `None` when it has an unclosed
/// or empty `{}`, a variable name that is not letters, digits or `_`, a stray
/// `}`, or the same variable twice.
pub(crate) fn parse(template: &str) -> Option<Vec<Piece>> {
    let mut pieces = Vec::new();
    let mut seen = HashSet::new();
    let mut literal = String::new();
    let mut chars = template.chars();
    while let Some(c) = chars.next() {
        match c {
            '}' => return None,
            '{' => {
                let mut name = String::new();
                loop {
                    match chars.next()? {
                        '}' => break,
                        n if n.is_ascii_alphanumeric() || n == '_' => name.push(n),
                        _ => return None,
                    }
                }
                if name.is_empty() || !seen.insert(name.clone()) {
                    return None;
                }
                if !literal.is_empty() {
                    pieces.push(Piece::Literal(std::mem::take(&mut literal)));
                }
                pieces.push(Piece::Var(name));
            }
            c => literal.push(c),
        }
    }
    if !literal.is_empty() {
        pieces.push(Piece::Literal(literal));
    }
    Some(pieces)
}

/// The variables of `pieces` when `uri` matches it, or `None`. Matching runs on
/// the URI as sent; the values are decoded only once it has matched.
pub(crate) fn matches(pieces: &[Piece], uri: &str) -> Option<TemplateVars> {
    let mut raw = HashMap::new();
    if !match_from(pieces, uri, &mut raw) {
        return None;
    }
    let mut vars = HashMap::with_capacity(raw.len());
    for (name, value) in raw {
        if !escapes_are_well_formed(&value) {
            return None;
        }
        let decoded = percent_decode_str(&value).decode_utf8().ok()?;
        vars.insert(name, decoded.into_owned());
    }
    Some(TemplateVars(vars))
}

/// Every `%` is followed by two hex digits. `percent_decode_str` would pass a bad
/// escape through as written, so it is checked first.
fn escapes_are_well_formed(value: &str) -> bool {
    value.split('%').skip(1).all(|part| {
        part.as_bytes()
            .get(..2)
            .is_some_and(|hex| hex.iter().all(u8::is_ascii_hexdigit))
    })
}

// ponytail: each variable tries every length it could take, so a match is O(n^2)
// in the URI length in the worst case. Bounded by the request size limit. Upgrade
// to a single-pass matcher if templates ever get many variables.
fn match_from(pieces: &[Piece], text: &str, vars: &mut HashMap<String, String>) -> bool {
    let Some((first, rest)) = pieces.split_first() else {
        return text.is_empty();
    };
    match first {
        Piece::Literal(literal) => text
            .strip_prefix(literal.as_str())
            .is_some_and(|tail| match_from(rest, tail, vars)),
        Piece::Var(name) => {
            let limit = text.find('/').unwrap_or(text.len());
            // Longest value first; every end is a char boundary.
            let ends: Vec<usize> = text
                .char_indices()
                .map(|(index, c)| index + c.len_utf8())
                .take_while(|&end| end <= limit)
                .collect();
            ends.into_iter().rev().any(|end| {
                let (value, tail) = text.split_at(end);
                vars.insert(name.clone(), value.to_owned());
                match_from(rest, tail, vars)
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_variable_takes_one_segment() {
        let pieces = parse("geo://{lat}/{lon}").expect("valid");
        let vars = matches(&pieces, "geo://1.5/-2").expect("matches");
        assert_eq!(vars.get("lat"), Some("1.5"));
        assert_eq!(vars.get("lon"), Some("-2"));
        assert!(matches(&pieces, "geo://1/2/3").is_none());
        assert!(matches(&pieces, "geo:///2").is_none());
    }
}