surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! skills.sh search (M53): `GET https://skills.sh/api/search?q=<query>`,
//! the unauthenticated endpoint the open-source `skills` CLI uses (the
//! documented v1 API needs a Vercel OIDC token). The endpoint is not part
//! of that documented API, so its answer is read defensively: items that
//! do not parse are skipped, a body of another shape is
//! `catalog_unreachable`. There is no unauthenticated detail endpoint:
//! entries are read back from cached search pages.

use serde_json::Value;

use super::http::{Http, host_of, unreachable};
use super::{Catalog, CatalogEntry, EntryKind, Publisher};
use crate::error::CoreError;

/// The shortest search skills.sh answers.
pub const MIN_QUERY: usize = 2;
/// What a refresh searches to learn whether skills.sh answers.
pub(crate) const PING_QUERY: &str = "skills";
/// The longest catalog text kept (names, sources).
const MAX_TEXT: usize = 200;
/// Why a skills.sh entry from a website is not installed.
pub(crate) const WEBSITE_PROBLEM: &str = "this skill comes from a website, not a GitHub \
     repository; Surjection installs skills.sh entries from GitHub repositories only";

/// `text` without control characters, trimmed, at most [`MAX_TEXT`]
/// characters; `None` when nothing is left.
fn clean(text: &str) -> Option<String> {
    let text: String = text
        .chars()
        .filter(|c| !c.is_control())
        .take(MAX_TEXT)
        .collect();
    let text = text.trim();
    (!text.is_empty()).then(|| text.to_owned())
}

/// One part of a skills.sh path: ASCII letters, digits, `.`, `_`, `-`.
fn valid_part(part: &str) -> bool {
    !part.is_empty()
        && part != "."
        && part != ".."
        && part
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}

/// The GitHub `owner/repo` of a skills.sh id `owner/repo/skill`; `None`
/// for a website ("well-known") source such as `mintlify.com/skill`
/// (GitHub owners never hold a `.`).
pub(crate) fn github_source(id: &str) -> Option<(&str, &str, &str)> {
    let mut parts = id.split('/');
    let (owner, repo, skill) = (parts.next()?, parts.next()?, parts.next()?);
    (parts.next().is_none()
        && [owner, repo, skill].iter().all(|p| valid_part(p))
        && !owner.contains('.'))
    .then_some((owner, repo, skill))
}

/// The skills.sh page of `id`.
pub(crate) fn page_url(catalog: &Catalog, id: &str) -> String {
    format!("{}/{id}", catalog.url.trim_end_matches('/'))
}

/// The entry for the skills.sh id `id` (`installs` when known). `None`
/// for an id that is not `<source>/<skill>` in safe characters.
pub(crate) fn entry_for(
    catalog: &Catalog,
    id: &str,
    name: Option<String>,
    source: Option<String>,
    installs: Option<u64>,
) -> Option<CatalogEntry> {
    if id.len() > MAX_TEXT || id.split('/').count() < 2 || !id.split('/').all(valid_part) {
        return None;
    }
    let github = github_source(id);
    let source = source
        .or_else(|| id.rsplit_once('/').map(|(source, _)| source.to_owned()))
        .unwrap_or_default();
    let skill = id.rsplit('/').next().unwrap_or(id).to_owned();
    Some(CatalogEntry {
        catalog: catalog.id.clone(),
        id: id.to_owned(),
        kind: EntryKind::Skill,
        name: name.unwrap_or_else(|| skill.clone()),
        description: None,
        version: None,
        updated_at: None,
        deprecated: false,
        status_message: None,
        publisher: Some(Publisher {
            name: source,
            checked: None,
        }),
        official: false,
        warning: None,
        repository: github.map(|(owner, repo, _)| format!("https://github.com/{owner}/{repo}")),
        website: Some(page_url(catalog, id)),
        license: None,
        transports: Vec::new(),
        packages: Vec::new(),
        remotes: Vec::new(),
        required_secrets: Vec::new(),
        pinned: false,
        git_ref: None,
        commit: None,
        path: None,
        skills: vec![skill],
        servers: Vec::new(),
        not_imported: Vec::new(),
        source: None,
        install_mcp: false,
        install_skill: github.is_some(),
        problem: github.is_none().then(|| WEBSITE_PROBLEM.to_owned()),
        server_json: None,
        mcp_servers: None,
        installs,
    })
}

/// One item of the answer; `None` when it does not parse. `id` and
/// `source` are checked as given (length and characters), never shortened
/// or cleaned into another valid id; only `name` is cleaned.
fn parse_item(catalog: &Catalog, item: &Value) -> Option<CatalogEntry> {
    let text = |key: &str| item.get(key).and_then(Value::as_str);
    let id = text("id")?;
    let source = text("source")?;
    let name = clean(text("name")?)?;
    if source.len() > MAX_TEXT
        || !source.split('/').all(valid_part)
        || !id.starts_with(&format!("{source}/"))
    {
        return None;
    }
    let installs = item.get("installs").and_then(Value::as_u64);
    entry_for(catalog, id, Some(name), Some(source.to_owned()), installs)
}

/// The skills matching `query` ([`MIN_QUERY`] characters or more, checked
/// by the caller).
pub(crate) fn search(
    http: &dyn Http,
    catalog: &Catalog,
    query: &str,
) -> Result<Vec<CatalogEntry>, CoreError> {
    let base = catalog.url.trim_end_matches('/');
    let mut url = url::Url::parse(&format!("{base}/api/search"))
        .map_err(|_| unreachable(&catalog.url, "its address is not valid"))?;
    url.query_pairs_mut().append_pair("q", query.trim());
    let url = String::from(url);
    let response = http.get(&url)?;
    let site = |url: &str| host_of(url).trim_start_matches("www.").to_owned();
    if let Some(answered) = &response.url
        && site(answered) != site(&url)
    {
        return Err(unreachable(&url, "it redirected to another site"));
    }
    match response.status {
        200..=299 => {}
        429 | 403 => {
            return Err(unreachable(
                &url,
                "it is limiting requests from this network; try again later",
            ));
        }
        status => return Err(unreachable(&url, format!("it answered HTTP {status}"))),
    }
    let unexpected = || {
        CoreError::new(
            crate::error::ErrorCode::CatalogUnreachable,
            "skills.sh answered in an unexpected format",
        )
    };
    let json: Value = serde_json::from_slice(&response.body).map_err(|_| unexpected())?;
    let items = json
        .get("skills")
        .and_then(Value::as_array)
        .ok_or_else(unexpected)?;
    let mut entries: Vec<CatalogEntry> = Vec::new();
    for entry in items.iter().filter_map(|item| parse_item(catalog, item)) {
        if !entries.iter().any(|known| known.id == entry.id) {
            entries.push(entry);
        }
    }
    Ok(entries)
}