Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Find a tool: local copy of the MCP Registry, search and one-step install (#555)

Oleksandr Ivanchenkoffb9b36bf66b
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index 1a85a41d..6e706762 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -190,6 +190,82 @@ fixed_headers` (names only), `inputs[{name, kind: "env"|"header", description, r
status (pending|installing|installed|dismissed), server_id, last_error`. Changes arrive as SSE `mcp_suggestion_updated
{suggestion}` and the message meta is updated in place.
+## Public directory (Find a tool)
+
+The person searches the official [MCP Registry](https://registry.modelcontextprotocol.io) and adds
+an entry in one step. kwnt keeps its own copy of the registry (latest versions only, in memory):
+the first sync pages through the whole registry after start (`/v0.1/servers?version=latest`,
+100 a page, 150 ms apart), then every 6 hours only what changed (`updated_since`, from 10 minutes
+before the last sync started). A failed sync keeps the old copy and tries again after 2 minutes,
+doubling up to an hour. Until the first sync has finished, a search goes to the registry's own
+search instead. Both routes refuse agents' tokens (`403`); agents use `mcp_search`/`mcp_suggest`.
+Only entries kwnt can add in one step are kept (the same rules as suggestions: a remote, or an
+npm/PyPI/OCI package run with `npx`/`uvx`/`docker`; no shells, no placeholder addresses).
+
+### `GET /api/mcp/registry/search?q=&space=`
+Up to 12 entries for `q` (cut to 60 characters; fewer than 2 letters answer no entries).
+`200` →
+
+```json
+{
+ "entries": [{
+ "registry_name": "com.stripe/mcp",
+ "version": "0.2.4",
+ "title": "Stripe",
+ "description": "MCP server integrating with Stripe - tools for customers, products, payments, and more.",
+ "publisher": {"label": "stripe.com", "kind": "domain"},
+ "kind": "remote",
+ "url": "https://mcp.stripe.com",
+ "transport": "http",
+ "command": null,
+ "inputs": [],
+ "already_added": false
+ }],
+ "unavailable": false,
+ "source": "copy"
+}
+```
+
+| Field | Notes |
+|---|---|
+| `title` | The entry's title; else the last part of its name, or the publisher's name when that part is generic (`mcp`, `server`, `mcp-server`, `remote`, `official`, `api`), in title case. |
+| `publisher` | From the name's namespace: `com.stripe` → `{"label": "stripe.com", "kind": "domain"}`, `io.github.alice` → `{"label": "github.com/alice", "kind": "github"}`. The registry checked the namespace (a DNS or GitHub proof); kwnt checks nothing more. |
+| `kind` | `"remote"` (an http address, `url` and `transport: "http"`) or `"stdio"` (`command` is the command line that would run, e.g. `npx -y @scope/[email protected]`, shown, never run by search). |
+| `url` | A bare host keeps no trailing `/` (`https://mcp.stripe.com`). |
+| `inputs` | What the person types: header names for remotes, env names for packages. `secret` ones belong in password fields. |
+| `already_added` | A server from this entry exists in the space: installed from it before, or one with the same address (remote) or the same command and arguments (stdio). |
+| `unavailable` | `true` (with no entries) only when there's no copy yet and the registry can't be reached. |
+| `source` | `"copy"` or `"live"` (before the first sync). |
+
+Ranking, best first: entries whose publisher is what was typed (`stripe` → `com.stripe/*`,
+`github` → `io.github.github/*`; a publisher's name is a two-label domain's first label or the GitHub
+user, so `io.ddx.pg` isn't `pg`); then how the name or title matches (starts with it, a word starts
+with it, a known alias such as `pg` → postgres, a name part, contains it, one or two typos); within
+each of those, a publisher one or two typos from what was typed (`strpie` → stripe.com); an exact
+name or title (for typo matches, a whole name or title a typo away: `gmial` → Gmail); remotes before packages; then registry order. Typos are only looked for when closer
+matches leave fewer than 12 rows. `ai.smithery/*` mirrors and entries whose address is a
+`{placeholder}` always come last. Case and accents don't matter. The answer carries
+`Server-Timing: directory;dur=<ms>`.
+
+### `POST /api/mcp/registry/install?space=` `{registry_name, env?: {NAME: value}, headers?: {Name: value}}`
+Fetches the entry's latest version from the registry again and plans it from the registry's data
+only (never from the request). `env` and `headers` fill its `inputs` by name (a `Bearer {token}`
+template gets the bare value). The server is added like one the person typed in: for every bot,
+named after the entry (`com.stripe/mcp` → `stripe`, `-2` if taken). It's tested; it's kept when the
+test passes or the server only needs sign-in.
+
+- `200` → `{registry_name, version, server: Server, test, oauth_required}`. With
+ `oauth_required: true`, start the sign-in (`POST /api/mcp/servers/:id/oauth/start`).
+- `400` bad `registry_name`, a missing required input, an unknown name, a value that isn't one line,
+ more than 50 values, or a body that isn't JSON with text values.
+- `404` the registry doesn't know it (any more). `409` the space is archived.
+- `422` it can't be added in one step, or it didn't start (`{error, test}`; nothing is kept).
+- `502` `{error, unavailable: true}`: the registry can't be reached.
+- `403` an agent's token.
+
+The values sent are never in the answer (every value of 6+ characters is replaced with `********`
+anywhere in it, error text included) and never logged; a malformed body gets a fixed message.
+
## Fallbacks before "not possible"
Two of kwnt's own tools exist so a bot tries the obvious way round, or offers the fix, instead of
diff --git a/src/mcp/directory.rs b/src/mcp/directory.rs
new file mode 100644
index 00000000..0c18a641
--- /dev/null
+++ b/src/mcp/directory.rs
@@ -0,0 +1,758 @@
+//! The public MCP directory as people search it ("Find a tool", mcp-finder): a local copy of the
+//! official MCP Registry's latest versions, synced in the background, and the matching and
+//! ranking that turn a few typed letters into up to 12 rows in well under 50 ms.
+//!
+//! The first sync pages through the whole registry; after that kwnt asks only for what changed
+//! (`updated_since`) every 6 hours. Until the first sync has finished, a search goes to the
+//! registry's own (name-only) search instead. Only entries kwnt can set up in one click are kept.
+//!
+//! Ranking: entries from Smithery's proxy or with a `{placeholder}` address go last; then a
+//! publisher whose proven name is the query (`stripe` → stripe.com, `github` → github.com/github);
+//! then how well the name matches (starts with > a word starts with > alias > a part of the
+//! registry name > contains > typo); then a publisher a typo away (`strpie` → stripe.com), which
+//! only orders entries within one of those tiers; then an exact name or title; then remote before
+//! stdio; then registry order. Typos are only looked for when closer matches leave room.
+
+use super::registry::{publisher_name, McpRegistry, RegistryEntry, GENERIC_SERVER_PARTS};
+use serde::Serialize;
+use std::collections::BTreeMap;
+use std::sync::{Arc, RwLock};
+use std::time::{Duration, SystemTime};
+use tokio_util::sync::CancellationToken;
+use unicode_normalization::UnicodeNormalization;
+
+/// Most entries one search answers.
+pub const MAX_RESULTS: usize = 12;
+/// Shorter queries answer nothing (the UI asks from 2 letters).
+pub const MIN_QUERY_CHARS: usize = 2;
+const SYNC_EVERY: Duration = Duration::from_secs(6 * 3600);
+/// After a failed sync: first retry, doubling up to [`RETRY_MAX`].
+const RETRY_FIRST: Duration = Duration::from_secs(120);
+const RETRY_MAX: Duration = Duration::from_secs(3600);
+/// A pause between pages, to be gentle with a free service.
+const PAGE_PAUSE: Duration = Duration::from_millis(150);
+/// Safety stops for a registry that never ends.
+const MAX_PAGES: usize = 1000;
+const MAX_ENTRIES: usize = 60_000;
+/// `updated_since` starts this much before the last sync began, so nothing falls in a gap.
+const OVERLAP: Duration = Duration::from_secs(600);
+
+/// The publisher line: what the registry's namespace check proves about who published it.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Publisher {
+ /// "stripe.com" or "github.com/alice".
+ pub label: String,
+ /// "domain" or "github".
+ pub kind: &'static str,
+}
+
+/// `com.stripe/mcp` → stripe.com; `io.github.alice/x` → github.com/alice.
+pub fn publisher_of(registry_name: &str) -> Publisher {
+ let ns = registry_name.split('/').next().unwrap_or(registry_name).to_ascii_lowercase();
+ match ns.strip_prefix("io.github.") {
+ Some(user) => Publisher { label: format!("github.com/{user}"), kind: "github" },
+ None => Publisher { label: ns.rsplit('.').collect::<Vec<_>>().join("."), kind: "domain" },
+ }
+}
+
+/// Lower case, no accents, letters and digits only: "Google Sheets" = "google-sheets" = "googlesheets".
+pub fn normalize(text: &str) -> String {
+ text.nfd().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()
+}
+
+fn words(text: &str) -> Vec<String> {
+ text.split(|c: char| !c.is_alphanumeric()).map(normalize).filter(|w| !w.is_empty()).collect()
+}
+
+/// Other names people type (autocomplete.md §4); the value is matched like a typed query.
+const ALIASES: [(&str, &str); 13] = [
+ ("googlemail", "gmail"),
+ ("gcal", "google calendar"),
+ ("calendar", "google calendar"),
+ ("sheets", "google sheets"),
+ ("docs", "google docs"),
+ ("drive", "google drive"),
+ ("11labs", "elevenlabs"),
+ ("eleven", "elevenlabs"),
+ ("teams", "microsoft teams"),
+ ("twitter", "x"),
+ ("postgres", "postgresql"),
+ ("pg", "postgresql"),
+ ("gdrive", "google drive"),
+];
+
+/// How well a name matches; lower is better.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub enum Match {
+ Prefix,
+ WordPrefix,
+ Alias,
+ NamePart,
+ Contains,
+ /// A whole word, the title or the name is a typo away.
+ Typo,
+ /// Only the start of a word is a typo away.
+ TypoStart,
+}
+
+/// One entry of the copy, with what matching needs worked out once.
+#[derive(Debug, Clone)]
+pub struct DirEntry {
+ pub entry: RegistryEntry,
+ pub publisher: Publisher,
+ /// The registry's title, else a name made from its registry name.
+ pub title: String,
+ title_norm: String,
+ slug_norm: String,
+ name_norm: String,
+ words: Vec<String>,
+ /// Dot and slash separated parts of the registry name.
+ parts: Vec<String>,
+ /// The publisher's own name: `stripe` for stripe.com (two-label domains only, so a subdomain
+ /// such as pg.ddx.io or stripecheckup.vercel.app isn't taken for its owner), `getsentry` for
+ /// github.com/getsentry.
+ publisher_key: Option<String>,
+ /// The publisher label normalised (`stripecom`).
+ publisher_norm: String,
+ /// `title_norm` NUL `name_norm`: every closer match is a piece of it, so one search of it
+ /// rules most entries out.
+ hay: String,
+ demoted: bool,
+}
+
+/// The title to show: the registry's own, else the part after the slash, else for a generic
+/// part (`com.stripe/mcp`) the publisher's name, capitalised ("Stripe").
+fn display_title(e: &RegistryEntry) -> String {
+ if e.title != e.name && !e.title.trim().is_empty() {
+ return e.title.clone();
+ }
+ let part = e.name.rsplit('/').next().unwrap_or(&e.name);
+ if !GENERIC_SERVER_PARTS.contains(&part.to_ascii_lowercase().as_str()) {
+ return part.to_string();
+ }
+ let p = publisher_name(&e.name);
+ let mut c = p.chars();
+ c.next().map(|f| f.to_uppercase().chain(c).collect()).unwrap_or_else(|| e.name.clone())
+}
+
+impl DirEntry {
+ /// `None` for an entry kwnt can't set up in one click: the directory doesn't show those.
+ pub fn new(entry: RegistryEntry) -> Option<Self> {
+ entry.plan.as_ref().ok()?;
+ let publisher = publisher_of(&entry.name);
+ let title = display_title(&entry);
+ let slug = entry.name.rsplit('/').next().unwrap_or(&entry.name);
+ let mut ws = words(&title);
+ for w in words(slug) {
+ if !ws.contains(&w) {
+ ws.push(w);
+ }
+ }
+ let publisher_key = publisher_key(&publisher);
+ let (title_norm, name_norm) = (normalize(&title), normalize(&entry.name));
+ Some(Self {
+ hay: format!("{title_norm}\0{name_norm}"),
+ title_norm,
+ slug_norm: normalize(slug),
+ name_norm,
+ words: ws,
+ parts: entry.name.split(['.', '/']).map(normalize).filter(|p| !p.is_empty()).collect(),
+ demoted: entry.name.to_ascii_lowercase().starts_with("ai.smithery/") || entry.placeholder_url,
+ publisher_key,
+ publisher_norm: normalize(&publisher.label),
+ publisher,
+ title,
+ entry,
+ })
+ }
+
+ fn is_remote(&self) -> bool {
+ self.entry.plan.as_ref().is_ok_and(|p| p.transport == "http")
+ }
+
+ /// The publisher is the query itself (`stripe` → stripe.com).
+ fn publisher_is(&self, q: &str) -> bool {
+ self.publisher_key.as_deref() == Some(q) || self.publisher_norm == q
+ }
+
+ fn direct_match(&self, q: &str) -> Option<Match> {
+ if self.title_norm.starts_with(q) || self.slug_norm.starts_with(q) || self.publisher_is(q) {
+ Some(Match::Prefix)
+ } else if self.words.iter().any(|w| w.starts_with(q)) {
+ Some(Match::WordPrefix)
+ } else {
+ None
+ }
+ }
+
+ /// Every match but a typo.
+ fn close_match(&self, q: &Query) -> Option<Match> {
+ // The title, its words, the registry name, its parts and the publisher's name are all
+ // pieces of `hay`; only the publisher label (`stripecom`) isn't.
+ let may = |t: &str| self.hay.contains(t) || self.publisher_norm == t;
+ if !may(&q.text) && !q.alias.as_deref().is_some_and(may) {
+ return None;
+ }
+ if let Some(m) = self.direct_match(&q.text) {
+ return Some(m);
+ }
+ if q.alias.as_deref().is_some_and(|a| self.direct_match(a).is_some()) {
+ return Some(Match::Alias);
+ }
+ if self.parts.iter().any(|p| p.starts_with(q.text.as_str())) {
+ return Some(Match::NamePart);
+ }
+ if self.title_norm.contains(q.text.as_str()) || self.name_norm.contains(q.text.as_str()) {
+ return Some(Match::Contains);
+ }
+ None
+ }
+
+ fn typo_match(&self, q: &Query) -> Option<Match> {
+ if q.budget == 0 {
+ return None;
+ }
+ let all = || self.words.iter().chain([&self.title_norm, &self.slug_norm]).map(String::as_str);
+ let whole = |w: &str| within(&q.text, q.chars, w, q.budget);
+ if all().any(whole) {
+ return Some(Match::Typo);
+ }
+ let start = |w: &str| match w.char_indices().nth(q.chars) {
+ Some((end, _)) if q.budget == 1 => one_edit_same_length(&q.text, &w[..end]),
+ Some((end, _)) => osa_within(&q.text, &w[..end], q.budget),
+ None => false,
+ };
+ all().any(start).then_some(Match::TypoStart)
+ }
+
+ /// How `q` matches this entry, if at all.
+ pub fn matches(&self, q: &str) -> Option<Match> {
+ let q = Query::new(q)?;
+ self.close_match(&q).or_else(|| self.typo_match(&q))
+ }
+
+ fn exact(&self, q: &str) -> bool {
+ self.title_norm == q || self.slug_norm == q
+ }
+
+ /// The sort key; lower comes first.
+ fn key(&self, q: &Query, m: Match, order: usize) -> SortKey {
+ let publisher = self.publisher_is(&q.text);
+ let publisher_typo = !publisher && q.budget > 0 && self.publisher_key.as_deref().is_some_and(|k| within(&q.text, q.chars, k, q.budget));
+ // Among typo matches, the name or title itself a typo away (`gmial` → gmail) first
+ let exact = self.exact(&q.text) || (m == Match::Typo && [&self.title_norm, &self.slug_norm].iter().any(|t| within(&q.text, q.chars, t, q.budget)));
+ (self.demoted, !publisher, m, !publisher_typo, !exact, !self.is_remote(), order)
+ }
+}
+
+/// `stripe` for stripe.com, `getsentry` for github.com/getsentry; none for a longer domain.
+fn publisher_key(p: &Publisher) -> Option<String> {
+ let key = match p.kind {
+ "github" => normalize(p.label.strip_prefix("github.com/")?),
+ _ => match p.label.split('.').collect::<Vec<_>>()[..] {
+ [name, _tld] => normalize(name),
+ _ => return None,
+ },
+ };
+ (!key.is_empty()).then_some(key)
+}
+
+/// Demoted, not the publisher, match, no publisher a typo away, not exact, not remote, order.
+type SortKey = (bool, bool, Match, bool, bool, bool, usize);
+
+/// A typed query, worked out once per search.
+struct Query {
+ /// Normalised.
+ text: String,
+ chars: usize,
+ /// What an alias stands for, normalised (`pg` → `postgresql`).
+ alias: Option<String>,
+ budget: usize,
+}
+
+impl Query {
+ /// `None` below [`MIN_QUERY_CHARS`].
+ fn new(typed: &str) -> Option<Self> {
+ let text = normalize(typed);
+ let chars = text.chars().count();
+ if chars < MIN_QUERY_CHARS {
+ return None;
+ }
+ let alias = ALIASES.iter().find(|(a, _)| *a == text).map(|(_, canonical)| normalize(canonical));
+ Some(Self { budget: typo_budget(chars), text, chars, alias })
+ }
+}
+
+/// 1 edit from 4 letters, 2 from 8 (autocomplete.md §4); none past [`OSA_MAX`] letters.
+fn typo_budget(chars: usize) -> usize {
+ match chars {
+ 0..=3 => 0,
+ 4..=7 => 1,
+ 8..=OSA_MAX => 2,
+ _ => 0,
+ }
+}
+
+fn char_count(s: &str) -> usize {
+ if s.is_ascii() {
+ s.len()
+ } else {
+ s.chars().count()
+ }
+}
+
+/// Two strings of the same length one substitution or one swap of neighbours apart (or equal):
+/// [`osa_bounded`] ≤ 1 for them, without the table.
+fn one_edit_same_length(a: &str, b: &str) -> bool {
+ let (mut a, mut b) = (a.chars(), b.chars());
+ loop {
+ match (a.next(), b.next()) {
+ (None, None) => return true,
+ (Some(x), Some(y)) if x == y => {}
+ (Some(x), Some(y)) => {
+ if a.clone().eq(b.clone()) {
+ return true;
+ }
+ return matches!((a.next(), b.next()), (Some(x2), Some(y2)) if x2 == y && y2 == x) && a.eq(b);
+ }
+ _ => return false,
+ }
+ }
+}
+
+/// `w` at most `max` edits from `q` (`q_chars` characters long). One edit, the common case, is
+/// checked without the table.
+fn within(q: &str, q_chars: usize, w: &str, max: usize) -> bool {
+ let w_chars = char_count(w);
+ if w_chars.abs_diff(q_chars) > max {
+ return false;
+ }
+ match (max, w_chars.cmp(&q_chars)) {
+ (0, _) => q == w,
+ (1, std::cmp::Ordering::Equal) => one_edit_same_length(q, w),
+ (1, std::cmp::Ordering::Less) => one_insert(w, q),
+ (1, std::cmp::Ordering::Greater) => one_insert(q, w),
+ _ => osa_within(q, w, max),
+ }
+}
+
+/// `long` is `short` with one character added.
+fn one_insert(short: &str, long: &str) -> bool {
+ let (mut s, mut l) = (short.chars(), long.chars());
+ loop {
+ match (s.clone().next(), l.next()) {
+ (Some(x), Some(y)) if x == y => {
+ s.next();
+ }
+ (_, Some(_)) => return s.eq(l),
+ (_, None) => return false,
+ }
+ }
+}
+
+/// The longest strings [`osa_bounded`] compares.
+const OSA_MAX: usize = 40;
+
+fn osa_within(a: &str, b: &str, max: usize) -> bool {
+ osa_bounded(a, b, max) <= max
+}
+
+/// Edits (insert, delete, substitute, swap two neighbours) between two short strings, without
+/// allocating; anything over `max`, or a string longer than [`OSA_MAX`], answers `max + 1`.
+fn osa_bounded(a: &str, b: &str, max: usize) -> usize {
+ fn fill(s: &str, buf: &mut [char; OSA_MAX]) -> Option<usize> {
+ let mut n = 0;
+ for c in s.chars() {
+ *buf.get_mut(n)? = c;
+ n += 1;
+ }
+ Some(n)
+ }
+ let (mut ab, mut bb) = (['\0'; OSA_MAX], ['\0'; OSA_MAX]);
+ let (Some(n), Some(m)) = (fill(a, &mut ab), fill(b, &mut bb)) else { return max + 1 };
+ if n.abs_diff(m) > max {
+ return max + 1;
+ }
+ let (a, b) = (&ab[..n], &bb[..m]);
+ let (mut before, mut prev, mut cur) = ([0usize; OSA_MAX + 1], [0usize; OSA_MAX + 1], [0usize; OSA_MAX + 1]);
+ for (j, cell) in prev.iter_mut().enumerate().take(m + 1) {
+ *cell = j;
+ }
+ for i in 1..=n {
+ cur[0] = i;
+ let mut row_min = i;
+ for j in 1..=m {
+ let cost = usize::from(a[i - 1] != b[j - 1]);
+ let mut d = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
+ if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
+ d = d.min(before[j - 2] + 1);
+ }
+ cur[j] = d;
+ row_min = row_min.min(d);
+ }
+ // A row's minimum never drops by more than one per row, so this can't come back under.
+ if row_min > max {
+ return max + 1;
+ }
+ std::mem::swap(&mut before, &mut prev);
+ std::mem::swap(&mut prev, &mut cur);
+ }
+ prev[m].min(max + 1)
+}
+
+/// The best `limit` entries for `query`, in order. `entries` is in registry order.
+pub fn rank<'a>(query: &str, entries: impl IntoIterator<Item = &'a DirEntry>, limit: usize) -> Vec<&'a DirEntry> {
+ let Some(q) = Query::new(query) else { return Vec::new() };
+ let mut hits = Vec::new();
+ let mut rest = Vec::new();
+ let mut shown = 0usize;
+ for (order, e) in entries.into_iter().enumerate() {
+ match e.close_match(&q) {
+ Some(m) => {
+ shown += usize::from(!e.demoted);
+ hits.push((e.key(&q, m, order), e));
+ }
+ None if q.budget > 0 => rest.push((order, e)),
+ None => {}
+ }
+ }
+ // A typo match ranks below every closer match that isn't demoted, so typos are only
+ // looked for when those leave room.
+ if shown < limit {
+ hits.extend(rest.into_iter().filter_map(|(order, e)| e.typo_match(&q).map(|m| (e.key(&q, m, order), e))));
+ }
+ hits.sort_unstable_by_key(|h| h.0);
+ hits.into_iter().take(limit).map(|(_, e)| e).collect()
+}
+
+/// The copy itself: every one-click entry's latest version, by registry name.
+#[derive(Debug, Default)]
+pub struct Copy {
+ pub entries: BTreeMap<String, DirEntry>,
+ /// When the sync that made this copy started (the next `updated_since`).
+ pub synced_from: Option<SystemTime>,
+}
+
+/// The directory: the copy, once the first sync finished. The registry it syncs from is passed
+/// in (`AppState::mcp_registry`, which `KWNT_MCP_REGISTRY_URL` and tests point elsewhere).
+#[derive(Default)]
+pub struct Directory {
+ copy: RwLock<Option<Arc<Copy>>>,
+}
+
+/// Where a search answer came from.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Source {
+ Copy,
+ Live,
+}
+
+pub struct SearchAnswer {
+ pub entries: Vec<DirEntry>,
+ pub source: Source,
+ /// Neither a copy nor the registry could answer.
+ pub unavailable: bool,
+}
+
+impl Directory {
+ /// The current copy, if the first sync has finished.
+ pub fn copy(&self) -> Option<Arc<Copy>> {
+ self.copy.read().ok().and_then(|c| c.clone())
+ }
+
+ fn set(&self, copy: Copy) {
+ if let Ok(mut c) = self.copy.write() {
+ *c = Some(Arc::new(copy));
+ }
+ }
+
+ /// Answers from the copy; before the first sync, from the registry's own search.
+ pub async fn search(&self, registry: &McpRegistry, query: &str) -> SearchAnswer {
+ if let Some(copy) = self.copy() {
+ let entries = rank(query, copy.entries.values(), MAX_RESULTS).into_iter().cloned().collect();
+ return SearchAnswer { entries, source: Source::Copy, unavailable: false };
+ }
+ if normalize(query).chars().count() < MIN_QUERY_CHARS {
+ return SearchAnswer { entries: Vec::new(), source: Source::Live, unavailable: false };
+ }
+ match registry.search(query).await {
+ Ok(hits) => {
+ let all: Vec<DirEntry> = hits.into_iter().filter_map(DirEntry::new).collect();
+ let entries = rank(query, all.iter(), MAX_RESULTS).into_iter().cloned().collect();
+ SearchAnswer { entries, source: Source::Live, unavailable: false }
+ }
+ Err(e) => {
+ tracing::info!(error = %e, "MCP directory: no copy yet and the registry search failed");
+ SearchAnswer { entries: Vec::new(), source: Source::Live, unavailable: true }
+ }
+ }
+ }
+
+ /// One sync: the whole registry when there's no copy yet, else what changed since the last
+ /// one. The copy is replaced only when every page arrived.
+ pub async fn sync_once(&self, registry: &McpRegistry) -> Result<usize, String> {
+ let started = SystemTime::now();
+ let previous = self.copy();
+ let since = previous.as_ref().and_then(|c| c.synced_from).map(|t| {
+ let t = t.checked_sub(OVERLAP).unwrap_or(t);
+ chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
+ });
+ let mut entries = match (&previous, &since) {
+ (Some(c), Some(_)) => c.entries.clone(),
+ _ => BTreeMap::new(),
+ };
+ let mut cursor: Option<String> = None;
+ let mut seen = 0usize;
+ for page_no in 0..MAX_PAGES {
+ if page_no > 0 {
+ tokio::time::sleep(PAGE_PAUSE).await;
+ }
+ let page = registry.page(cursor.as_deref(), since.as_deref()).await?;
+ seen += page.items.len();
+ for (name, entry) in page.items {
+ match entry.and_then(DirEntry::new) {
+ Some(e) if entries.len() < MAX_ENTRIES || entries.contains_key(&name) => {
+ entries.insert(name, e);
+ }
+ Some(_) => {}
+ None => {
+ entries.remove(&name);
+ }
+ }
+ }
+ match page.next_cursor {
+ Some(next) if Some(&next) != cursor.as_ref() => cursor = Some(next),
+ _ => break,
+ }
+ }
+ let kept = entries.len();
+ self.set(Copy { entries, synced_from: Some(started) });
+ tracing::info!(listed = seen, kept, full = since.is_none(), "MCP directory synced");
+ Ok(kept)
+ }
+
+ /// Syncs now and then every 6 hours, retrying failures with a growing pause, until shutdown.
+ pub fn spawn(self: Arc<Self>, registry: Arc<McpRegistry>, shutdown: CancellationToken) -> tokio::task::JoinHandle<()> {
+ tokio::spawn(async move {
+ let mut retry = RETRY_FIRST;
+ loop {
+ let wait = match self.sync_once(&registry).await {
+ Ok(_) => {
+ retry = RETRY_FIRST;
+ SYNC_EVERY
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "MCP directory sync failed; trying again later");
+ let w = retry;
+ retry = (retry * 2).min(RETRY_MAX);
+ w
+ }
+ };
+ tokio::select! {
+ _ = shutdown.cancelled() => return,
+ _ = tokio::time::sleep(wait) => {}
+ }
+ }
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::mcp::registry::parse_list;
+
+ const STRIPE: &str = include_str!("../../tests/fixtures/mcp_registry/stripe.json");
+ const NOTION: &str = include_str!("../../tests/fixtures/mcp_registry/notion.json");
+
+ fn fixture(body: &str) -> Vec<DirEntry> {
+ parse_list(body.as_bytes()).unwrap().into_iter().filter_map(DirEntry::new).collect()
+ }
+
+ fn names(query: &str, list: &[DirEntry]) -> Vec<String> {
+ rank(query, list.iter(), 50).into_iter().map(|e| e.entry.name.clone()).collect()
+ }
+
+ #[test]
+ fn stripe_ranks_stripe_first_and_drops_refused_plans() {
+ let list = fixture(STRIPE);
+ let ranked = names("stripe", &list);
+ assert_eq!(ranked[0], "com.stripe/mcp", "{ranked:?}");
+ let top = &rank("stripe", list.iter(), 1)[0];
+ assert_eq!(top.publisher, Publisher { label: "stripe.com".into(), kind: "domain" });
+ assert_eq!(top.title, "Stripe");
+ // eu.nordicmcp/stripe's only address is https://nordicmcp.eu/mcp/stripe/{token}: not one-click
+ assert!(!ranked.iter().any(|n| n == "eu.nordicmcp/stripe"), "{ranked:?}");
+ // mcpb packages aren't installable either
+ assert!(!ranked.iter().any(|n| n == "io.github.theluckystrike/stripe-billing"));
+ // Look-alikes come after, and an exact name ("stripe") before the rest
+ assert_eq!(ranked[1], "com.insightfulpipe/stripe", "{ranked:?}");
+ assert!(ranked.len() >= 8, "{ranked:?}");
+ // Upper case, spaces and typos
+ assert_eq!(names("STRIPE ", &list)[0], "com.stripe/mcp");
+ assert_eq!(names("strpie", &list)[0], "com.stripe/mcp");
+ }
+
+ #[test]
+ fn notion_ranks_notion_first_and_smithery_last() {
+ let list = fixture(NOTION);
+ let ranked = names("notion", &list);
+ assert_eq!(ranked[0], "com.notion/mcp", "{ranked:?}");
+ assert_eq!(ranked.last().map(String::as_str), Some("ai.smithery/smithery-notion"), "{ranked:?}");
+ assert_eq!(names("notoin", &list)[0], "com.notion/mcp");
+ // Remote before stdio among equal matches
+ let remote_at = ranked.iter().position(|n| n == "com.insightfulpipe/notion").unwrap();
+ let stdio_at = ranked.iter().position(|n| n == "com.foreverworks/notion").unwrap();
+ assert!(remote_at < stdio_at, "{ranked:?}");
+ }
+
+ #[test]
+ fn placeholder_addresses_go_last_even_with_a_package() {
+ let body = serde_json::json!({"servers": [
+ {"server": {"name": "io.github.a/weather-tenant", "title": "Weather", "description": "d", "version": "1",
+ "remotes": [{"type": "streamable-http", "url": "https://{tenant}.weather.example/mcp"}],
+ "packages": [{"registryType": "npm", "identifier": "weather-mcp", "version": "1.0.0", "transport": {"type": "stdio"}}]}},
+ {"server": {"name": "io.github.b/weather-x", "description": "d", "version": "1",
+ "packages": [{"registryType": "npm", "identifier": "weather-x", "version": "1.0.0", "transport": {"type": "stdio"}}]}},
+ ]});
+ let list = fixture(&body.to_string());
+ assert_eq!(names("weather", &list), ["io.github.b/weather-x", "io.github.a/weather-tenant"]);
+ }
+
+ #[test]
+ fn short_queries_aliases_and_publishers() {
+ let list = fixture(STRIPE);
+ assert!(names("s", &list).is_empty());
+ assert!(names("--", &list).is_empty());
+ assert_eq!(publisher_of("io.github.Alice/x"), Publisher { label: "github.com/alice".into(), kind: "github" });
+ assert_eq!(publisher_of("app.vercel.stripecheckup/x").label, "stripecheckup.vercel.app");
+ assert_eq!(normalize("Google-Sheets É"), "googlesheetse");
+ assert_eq!(osa_bounded("notoin", "notion", 2), 1);
+ assert_eq!(osa_bounded("gmial", "gmail", 2), 1);
+ assert_eq!(osa_bounded("kitten", "sitting", 5), 3);
+ assert_eq!(osa_bounded("ab", "ba", 2), 1);
+ assert_eq!(osa_bounded("abc", "abcdefgh", 2), 3);
+ assert_eq!(osa_bounded("abcdef", "uvwxyz", 1), 2, "stops early, past the limit");
+ assert_eq!(osa_bounded("café", "cafe", 2), 1);
+ assert_eq!(osa_bounded(&"a".repeat(41), &"a".repeat(41), 2), 3, "too long to compare");
+ assert_eq!((typo_budget(3), typo_budget(4), typo_budget(8), typo_budget(41)), (0, 1, 2, 0));
+ for (a, b) in [("abcd", "abcd"), ("abcd", "abxd"), ("abcd", "bacd"), ("abcd", "abdc"), ("strpie", "stripe"), ("cafe", "café"), ("abcd", "abcde"), ("abcd", "xbcy"), ("abcd", "badc"), ("abcd", "acdb"), ("abcd", "dbca")] {
+ assert_eq!(one_edit_same_length(a, b), osa_bounded(a, b, 1) <= 1 && char_count(a) == char_count(b), "{a} {b}");
+ }
+ assert_eq!((char_count("café"), char_count("cafe")), (4, 4));
+ for (a, b) in [("gmail", "gmial"), ("gmail", "gmai"), ("gmail", "gmaill"), ("gmail", "xgmail"), ("gmail", "gmal"), ("gmail", "gmali"), ("gmail", "mail"), ("gmail", "gmailxx"), ("gmail", "gamil"), ("gmail", "gnail"), ("abcd", "acbd"), ("abcd", "abc"), ("abc", "ab")] {
+ for (x, y) in [(a, b), (b, a)] {
+ assert_eq!(within(x, char_count(x), y, 1), osa_bounded(x, y, 1) <= 1, "{x} {y}");
+ assert_eq!(within(x, char_count(x), y, 2), osa_bounded(x, y, 2) <= 2, "{x} {y}");
+ }
+ }
+ assert!(within("abc", 3, "abc", 0) && !within("abc", 3, "abd", 0));
+ let pg = fixture(
+ &serde_json::json!({"servers": [{"server": {"name": "io.github.x/postgresql-tools", "description": "d", "version": "1",
+ "remotes": [{"type": "streamable-http", "url": "https://pg.example/mcp"}]}}]})
+ .to_string(),
+ );
+ assert_eq!(rank("pg", pg.iter(), 5).len(), 1);
+ assert_eq!(rank("pg", pg.iter(), 5)[0].matches("pg"), Some(Match::Alias));
+ }
+
+ /// Remote entries named like the real registry's: `(registry name, title)`.
+ fn remotes(list: &[(&str, &str)]) -> Vec<DirEntry> {
+ let servers: Vec<_> = list
+ .iter()
+ .enumerate()
+ .map(|(i, (name, title))| {
+ serde_json::json!({"server": {"name": name, "title": title, "description": "d", "version": "1",
+ "remotes": [{"type": "streamable-http", "url": format!("https://mcp{i}.example.com/mcp")}]}})
+ })
+ .collect();
+ fixture(&serde_json::json!({ "servers": servers }).to_string())
+ }
+
+ #[test]
+ fn a_publisher_a_typo_away_never_beats_a_closer_match() {
+ // From the real registry (Nov 13): stride.info and scripe.io are one letter from stripe
+ let list = remotes(&[
+ ("info.stride/stride", "Stride"),
+ ("io.scripe/mcp", "Scripe"),
+ ("com.insightfulpipe/stripe", "Stripe"),
+ ("com.stripe/mcp", "Stripe"),
+ ("io.github.someone/stripe-billing", "Stripe billing"),
+ ]);
+ let ranked = names("stripe", &list);
+ assert_eq!(&ranked[..3], ["com.stripe/mcp", "com.insightfulpipe/stripe", "io.github.someone/stripe-billing"], "{ranked:?}");
+ // A typo in the query: the publisher a typo away goes first among the typo matches
+ assert_eq!(names("strpie", &list)[0], "com.stripe/mcp");
+
+ let list = remotes(&[
+ ("fr.gentry/logement", "Gentry logement"),
+ ("fyi.entry/entry", "Entry"),
+ ("io.github.getsentry/sentry-mcp", "Sentry"),
+ ]);
+ assert_eq!(names("sentry", &list)[0], "io.github.getsentry/sentry-mcp");
+
+ // Among typo matches, the name itself a typo away comes before a word in a longer title
+ let list = remotes(&[("ai.fgac/fgac", "Fgac for gmail and drive"), ("ai.waystation/gmail", "Gmail")]);
+ assert_eq!(names("gmial", &list), ["ai.waystation/gmail", "ai.fgac/fgac"]);
+ }
+
+ #[test]
+ fn github_publishers_and_subdomains() {
+ let list = remotes(&[
+ ("com.robinsonaisystems/github", "GitHub"),
+ ("io.github.github/github-mcp-server", "GitHub"),
+ ("io.ddx.pg/archive", "Archive"),
+ ("io.github.x/postgresql-tools", "Postgres tools"),
+ ("app.vercel.stripecheckup/x", "Checkup"),
+ ]);
+ assert_eq!(names("github", &list)[0], "io.github.github/github-mcp-server");
+ assert_eq!(names("getsentry", &remotes(&[("io.github.getsentry/sentry-mcp", "Sentry")])).len(), 1);
+ // pg.ddx.io's owner is ddx.io, not "pg": the alias for PostgreSQL comes first
+ assert_eq!(names("pg", &list), ["io.github.x/postgresql-tools", "io.ddx.pg/archive"]);
+ // stripecheckup.vercel.app isn't Vercel's own
+ assert_eq!(list[4].publisher_key, None);
+ assert_eq!(list[1].publisher_key.as_deref(), Some("github"));
+ assert_eq!(list[0].publisher_key.as_deref(), Some("robinsonaisystems"));
+ }
+
+ #[test]
+ fn typos_are_skipped_when_closer_matches_fill_the_list() {
+ let mut named: Vec<(String, String)> = (0..20).map(|i| (format!("com.acme{i}/stripe-tools"), format!("Stripe tools {i}"))).collect();
+ named.push(("info.stride/stride".into(), "Stride".into()));
+ let list = remotes(&named.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect::<Vec<_>>());
+ let top = rank("stripe", list.iter(), MAX_RESULTS);
+ assert_eq!(top.len(), MAX_RESULTS);
+ assert!(top.iter().all(|e| e.entry.name.starts_with("com.acme")));
+ let ranked = names("stripe", &list);
+ assert_eq!((ranked.len(), ranked.last().map(String::as_str)), (21, Some("info.stride/stride")), "{ranked:?}");
+ // With room left, the typo match is there, last
+ assert_eq!(names("stride", &list)[0], "info.stride/stride");
+ assert_eq!(rank("stripe", list[15..].iter(), MAX_RESULTS).last().map(|e| e.entry.name.as_str()), Some("info.stride/stride"));
+ }
+
+ #[test]
+ fn ten_thousand_entries_answer_fast() {
+ // Varied names, like the real copy (about 6,000 one-click entries on Nov 13)
+ let mut seed = 7u64;
+ let mut word = |len: usize| -> String {
+ (0..len)
+ .map(|_| {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ char::from(b'a' + ((seed >> 33) % 26) as u8)
+ })
+ .collect()
+ };
+ let named: Vec<(String, String)> =
+ (0..12_000).map(|i| (format!("io.github.{}/{}-mcp", word(8), word(3 + i % 9)), format!("{} {} tools", word(6), word(7)))).collect();
+ let list = remotes(&named.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect::<Vec<_>>());
+ assert_eq!(list.len(), 12_000);
+ let started = std::time::Instant::now();
+ for q in ["st", "stripe", "strpie", "zqxw", "zzzzzzzz", "billing tools", "pg"] {
+ rank(q, list.iter(), MAX_RESULTS);
+ }
+ // Seven searches; a release build takes a few ms each. Debug builds are many times slower,
+ // so this only guards against something going badly wrong.
+ assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
+ }
+}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index c39cc73d..bc1525a9 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -11,6 +11,7 @@ pub mod oauth;
pub mod payment_floor;
pub mod prod_floor;
pub mod oauth_mock;
+pub mod directory;
pub mod registry;
pub mod session;
pub mod shell_risk;
@@ -112,6 +113,11 @@ pub struct McpServerInput {
pub timeout_secs: Option<i64>,
}
+/// A name `build_server` accepts: the shape below and not one of kwnt's own names.
+pub fn usable_server_name(name: &str) -> bool {
+ valid_server_name(name) && !name.eq_ignore_ascii_case(RESERVED_SERVER_NAME) && !name.eq_ignore_ascii_case(SELF_SERVER_NAME)
+}
+
fn valid_server_name(name: &str) -> bool {
let first_ok = name.chars().next().is_some_and(|c| c.is_ascii_alphanumeric());
first_ok
diff --git a/src/mcp/registry.rs b/src/mcp/registry.rs
index 2afdfd1d..5032fd66 100644
--- a/src/mcp/registry.rs
+++ b/src/mcp/registry.rs
@@ -75,6 +75,10 @@ pub struct RegistryEntry {
pub website_url: Option<String>,
/// The plan, or why the entry can't be set up in one click.
pub plan: Result<InstallPlan, String>,
+ /// One of its remote addresses has a `{placeholder}` (a per-person address): ranked last in
+ /// the directory even when a package makes it installable.
+ #[serde(skip)]
+ pub placeholder_url: bool,
}
// Raw registry JSON (only the fields kwnt uses)
@@ -83,6 +87,15 @@ pub struct RegistryEntry {
struct RawList {
#[serde(default)]
servers: Option<Vec<RawResponse>>,
+ #[serde(default)]
+ metadata: Option<RawMetadata>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct RawMetadata {
+ #[serde(default)]
+ next_cursor: Option<String>,
}
#[derive(Debug, Deserialize)]
@@ -457,6 +470,7 @@ fn entry(r: RawResponse) -> Option<RegistryEntry> {
}
let s = r.server;
let plan = plan_for(&s);
+ let placeholder_url = s.remotes.as_deref().unwrap_or(&[]).iter().any(|r| r.url.as_deref().is_some_and(templated));
Some(RegistryEntry {
title: clip(s.title.as_deref().filter(|t| !t.trim().is_empty()).unwrap_or(&s.name), 100),
description: clip(&s.description, 300),
@@ -465,6 +479,7 @@ fn entry(r: RawResponse) -> Option<RegistryEntry> {
website_url: s.website_url.filter(|u| u.starts_with("https://")).map(|u| clip(&u, 300)),
name: s.name,
plan,
+ placeholder_url,
})
}
@@ -474,6 +489,27 @@ pub fn parse_list(body: &[u8]) -> Result<Vec<RegistryEntry>, String> {
Ok(list.servers.unwrap_or_default().into_iter().filter_map(entry).collect())
}
+/// One page of a `GET /v0.1/servers` walk: every listed name with its entry, `None` for an entry
+/// that is no longer active (deleted or deprecated), so a copy can drop it; and the next cursor.
+pub struct Page {
+ pub items: Vec<(String, Option<RegistryEntry>)>,
+ pub next_cursor: Option<String>,
+}
+
+pub fn parse_page(body: &[u8]) -> Result<Page, String> {
+ let list: RawList = serde_json::from_slice(body).map_err(|_| "the registry sent an answer kwnt can't read".to_string())?;
+ let items = list
+ .servers
+ .unwrap_or_default()
+ .into_iter()
+ // An older version that changed says nothing about the latest one.
+ .filter(|r| r.meta["io.modelcontextprotocol.registry/official"]["isLatest"].as_bool() != Some(false))
+ .map(|r| (r.server.name.clone(), entry(r)))
+ .collect();
+ let next_cursor = list.metadata.and_then(|m| m.next_cursor).filter(|c| !c.is_empty() && c.len() <= 400);
+ Ok(Page { items, next_cursor })
+}
+
/// Parses a `GET /v0.1/servers/{name}/versions/latest` answer.
pub fn parse_one(body: &[u8]) -> Result<Option<RegistryEntry>, String> {
let one: RawResponse = serde_json::from_slice(body).map_err(|_| "the registry sent an answer kwnt can't read".to_string())?;
@@ -492,9 +528,20 @@ pub fn valid_registry_name(name: &str) -> bool {
&& server.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c))
}
-/// A kwnt server name for a registry entry: its part after the slash, cleaned up.
+/// Server parts that say nothing about whose server it is (`com.stripe/mcp`).
+pub const GENERIC_SERVER_PARTS: [&str; 6] = ["mcp", "server", "mcp-server", "remote", "official", "api"];
+
+/// The name a publisher's namespace proves: `com.stripe` → `stripe`, `io.github.alice` → `alice`.
+pub fn publisher_name(registry_name: &str) -> &str {
+ let ns = registry_name.split('/').next().unwrap_or(registry_name);
+ ns.strip_prefix("io.github.").unwrap_or_else(|| ns.rsplit('.').next().unwrap_or(ns))
+}
+
+/// A kwnt server name for a registry entry: its part after the slash, cleaned up; for a generic
+/// part (`com.stripe/mcp`), the publisher's name (`stripe`).
pub fn server_name_for(registry_name: &str) -> String {
let base = registry_name.rsplit('/').next().unwrap_or(registry_name);
+ let base = if GENERIC_SERVER_PARTS.contains(&base.to_ascii_lowercase().as_str()) { publisher_name(registry_name) } else { base };
let mut name = String::new();
for c in base.chars() {
let c = if c.is_ascii_alphanumeric() || c == '-' { c } else { '-' };
@@ -669,6 +716,26 @@ impl McpRegistry {
Ok(hits)
}
+ /// One page of every server's latest version (100 per page), for the directory copy. With
+ /// `updated_since` (RFC 3339), only servers changed since then.
+ pub async fn page(&self, cursor: Option<&str>, updated_since: Option<&str>) -> Result<Page, String> {
+ let mut url = self.url(&["v0.1", "servers"])?;
+ {
+ let mut q = url.query_pairs_mut();
+ q.append_pair("version", "latest").append_pair("limit", "100");
+ if let Some(c) = cursor {
+ q.append_pair("cursor", c);
+ }
+ if let Some(t) = updated_since {
+ q.append_pair("updated_since", t);
+ }
+ }
+ match self.get(url).await? {
+ Some(body) => parse_page(&body),
+ None => Ok(Page { items: Vec::new(), next_cursor: None }),
+ }
+ }
+
/// The latest version of one entry; `None` when the registry doesn't know it.
pub async fn get_latest(&self, name: &str) -> Result<Option<RegistryEntry>, String> {
if !valid_registry_name(name) {
@@ -805,6 +872,9 @@ mod tests {
assert_eq!(list.len(), 1);
assert_eq!(server_name_for("io.github.Foo/Echo.Server_v2"), "echo-server-v2");
assert_eq!(server_name_for("a.b/kwnt"), "mcp-server");
+ assert_eq!(server_name_for("com.stripe/mcp"), "stripe");
+ assert_eq!(server_name_for("io.github.alice/MCP"), "alice");
+ assert_eq!(server_name_for("com.notion/notion-mcp"), "notion-mcp");
assert!(valid_registry_name("io.github.x/echo"));
assert!(!valid_registry_name("../etc/passwd"));
assert!(!valid_registry_name("noslash"));
diff --git a/src/server/mcp_directory.rs b/src/server/mcp_directory.rs
new file mode 100644
index 00000000..2b1b0ebb
--- /dev/null
+++ b/src/server/mcp_directory.rs
@@ -0,0 +1,240 @@
+//! The public MCP directory for people ("Find a tool", mcp-finder): search kwnt's local copy of
+//! the MCP Registry and add an entry in one step. Agents have their own `mcp_search` and
+//! `mcp_suggest`; both routes here refuse agents' tokens.
+//! Contract: docs/mcp-api.md ("Public directory").
+
+use super::mcp_routes::view;
+use super::mcp_suggest::{create_and_test, refuse_agent_tokens, InstallFailed, Installed};
+use super::spaces::{ensure_active, Scope};
+use super::AppState;
+use crate::db::models::McpServer;
+use crate::mcp::directory::{DirEntry, Source};
+use crate::mcp::registry::{valid_registry_name, MAX_QUERY_CHARS};
+use crate::mcp::SECRET_MASK;
+use axum::{
+ extract::{rejection::JsonRejection, Query, State},
+ http::{header::HeaderName, HeaderMap, HeaderValue, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+use std::time::Instant;
+
+const REFUSAL: &str = "only the person can search the directory and add tools from it";
+/// Most env values plus headers one install takes.
+const MAX_VALUES: usize = 50;
+
+fn error(status: StatusCode, message: impl Into<String>) -> Response {
+ (status, Json(json!({ "error": message.into() }))).into_response()
+}
+
+#[derive(Deserialize)]
+pub struct SearchQuery {
+ #[serde(default)]
+ pub q: String,
+}
+
+/// An address for comparing: lower case, no trailing slash.
+fn same_address(url: &str) -> String {
+ url.trim().trim_end_matches('/').to_ascii_lowercase()
+}
+
+/// `https://mcp.stripe.com/` → `https://mcp.stripe.com`: the address as people write it.
+fn shown_url(url: &str) -> String {
+ match reqwest::Url::parse(url) {
+ Ok(u) if u.path() == "/" && u.query().is_none() && u.fragment().is_none() => url.trim_end_matches('/').to_string(),
+ _ => url.to_string(),
+ }
+}
+
+/// `npx -y @scope/[email protected]`: the command line installing it would run (a preview only).
+fn command_line(command: &str, args: &[String]) -> String {
+ std::iter::once(command.to_string())
+ .chain(args.iter().map(|a| if a.is_empty() || a.chars().any(char::is_whitespace) { format!("'{}'", a.replace('\'', "'\\''")) } else { a.clone() }))
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+/// Whether a server from this entry already exists in the space: one installed from it through
+/// a suggestion, or one with the same address (remote) or the same command line (stdio).
+fn already_added(e: &DirEntry, servers: &[McpServer], suggested: &[String]) -> bool {
+ if suggested.iter().any(|n| n == &e.entry.name) {
+ return true;
+ }
+ let Ok(plan) = &e.entry.plan else { return false };
+ servers.iter().any(|s| match (&plan.url, &s.url) {
+ (Some(a), Some(b)) if plan.transport == "http" => same_address(a) == same_address(b),
+ _ => plan.transport == "stdio" && s.transport == "stdio" && plan.command == s.command && plan.args == s.args,
+ })
+}
+
+/// One row as Find a tool reads it (`DirectoryEntry` in frontend/src/connections.ts).
+fn entry_json(e: &DirEntry, added: bool) -> Value {
+ let Ok(plan) = &e.entry.plan else { return Value::Null };
+ let remote = plan.transport == "http";
+ json!({
+ "registry_name": e.entry.name,
+ "version": e.entry.version,
+ "title": e.title,
+ "description": e.entry.description,
+ "publisher": e.publisher,
+ "kind": if remote { "remote" } else { "stdio" },
+ "url": if remote { plan.url.as_deref().map(shown_url) } else { None },
+ "transport": if remote { Some("http") } else { None },
+ "command": if remote { None } else { plan.command.as_deref().map(|c| command_line(c, &plan.args)) },
+ "inputs": plan.inputs.iter().map(|i| json!({
+ "name": i.name,
+ "description": i.description,
+ "required": i.required,
+ "secret": i.secret,
+ })).collect::<Vec<_>>(),
+ "already_added": added,
+ })
+}
+
+/// `GET /api/mcp/registry/search?q=&space=`: up to 12 one-click entries for what the person typed,
+/// from kwnt's copy of the registry (from the registry's own search until the first sync is done).
+/// 200 `{entries, unavailable, source}`; `unavailable: true` (and no entries) when there's no copy
+/// yet and the registry can't be reached. Fewer than 2 letters answer no entries.
+pub async fn search(State(state): State<AppState>, headers: HeaderMap, Scope(space): Scope, Query(q): Query<SearchQuery>) -> Response {
+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {
+ return r;
+ }
+ let started = Instant::now();
+ let query: String = q.q.chars().filter(|c| !c.is_control()).take(MAX_QUERY_CHARS).collect();
+ let answer = state.mcp_directory.search(&state.mcp_registry, &query).await;
+ let (servers, suggested) = if answer.entries.is_empty() {
+ (Vec::new(), Vec::new())
+ } else {
+ let servers = state.db.list_mcp_servers(&space).await.unwrap_or_default();
+ let suggested = state.db.installed_mcp_suggestions(&space).await.unwrap_or_default().into_iter().map(|(n, _)| n).collect();
+ (servers, suggested)
+ };
+ let entries: Vec<Value> = answer.entries.iter().map(|e| entry_json(e, already_added(e, &servers, &suggested))).collect();
+ let source = match answer.source {
+ Source::Copy => "copy",
+ Source::Live => "live",
+ };
+ let body = json!({ "entries": entries, "unavailable": answer.unavailable, "source": source });
+ let timing = format!("directory;dur={:.1}", started.elapsed().as_secs_f64() * 1000.0);
+ let mut resp = Json(body).into_response();
+ if let Ok(v) = HeaderValue::from_str(&timing) {
+ resp.headers_mut().insert(HeaderName::from_static("server-timing"), v);
+ }
+ resp
+}
+
+#[derive(Deserialize)]
+pub struct InstallBody {
+ pub registry_name: String,
+ /// The Name on the form; used when it is a valid server name (else the entry's own name).
+ #[serde(default)]
+ pub name: Option<String>,
+ #[serde(default)]
+ pub env: BTreeMap<String, String>,
+ #[serde(default)]
+ pub headers: BTreeMap<String, String>,
+}
+
+/// Every string in `v` with each secret replaced by the mask.
+fn scrub(v: Value, secrets: &[String]) -> Value {
+ match v {
+ Value::String(s) => Value::String(secrets.iter().fold(s, |s, secret| s.replace(secret.as_str(), SECRET_MASK))),
+ Value::Array(a) => Value::Array(a.into_iter().map(|x| scrub(x, secrets)).collect()),
+ Value::Object(o) => Value::Object(o.into_iter().map(|(k, x)| (k, scrub(x, secrets))).collect()),
+ other => other,
+ }
+}
+
+/// `POST /api/mcp/registry/install?space= {registry_name, name?, env?, headers?}`: the person adds an
+/// entry from the directory. Its latest version is fetched again and planned from the registry's
+/// data only; `env` and `headers` fill its named inputs. The server is added like one the person
+/// typed in (for every bot), tested, and kept if it starts or only needs sign-in
+/// (`oauth_required: true`). It is named `name` when that is a valid server name, else after the
+/// entry, with a suffix on a clash. The values typed are never echoed back or logged.
+pub async fn install(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Scope(space): Scope,
+ body: Result<Json<InstallBody>, JsonRejection>,
+) -> Response {
+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {
+ return r;
+ }
+ // A JSON error can quote what was sent, so it isn't passed on.
+ let Ok(Json(body)) = body else {
+ return error(StatusCode::BAD_REQUEST, "send {registry_name, name, env, headers} as JSON, with text values");
+ };
+ let secrets: Vec<String> = body.env.values().chain(body.headers.values()).map(|v| v.trim().to_string()).filter(|v| v.len() >= 6).collect();
+ let resp = install_inner(&state, &space, body).await;
+ let (status, value) = resp;
+ (status, Json(scrub(value, &secrets))).into_response()
+}
+
+async fn install_inner(state: &AppState, space: &crate::db::spaces::SpaceId, body: InstallBody) -> (StatusCode, Value) {
+ let err = |status: StatusCode, msg: &str| (status, json!({ "error": msg }));
+ if let Err(r) = ensure_active(state, space).await {
+ return (r.status(), json!({ "error": "this space can't be changed" }));
+ }
+ let name = body.registry_name.trim();
+ if !valid_registry_name(name) {
+ return err(StatusCode::BAD_REQUEST, "registry_name must be a registry name like com.example/server");
+ }
+ if body.env.len() + body.headers.len() > MAX_VALUES {
+ return err(StatusCode::BAD_REQUEST, "too many values");
+ }
+ let entry = match state.mcp_registry.get_latest(name).await {
+ Ok(Some(e)) => e,
+ Ok(None) => return err(StatusCode::NOT_FOUND, "This server isn't in the MCP Registry any more."),
+ Err(e) => return (StatusCode::BAD_GATEWAY, json!({ "error": e, "unavailable": true })),
+ };
+ let plan = match &entry.plan {
+ Ok(p) => p,
+ Err(why) => return err(StatusCode::UNPROCESSABLE_ENTITY, &format!("This server can't be added in one step: {why}.")),
+ };
+ let (env, header_values) = match plan.resolve(&body.env, &body.headers) {
+ Ok(v) => v,
+ Err(e) => return err(StatusCode::BAD_REQUEST, &e),
+ };
+ match create_and_test(state, space, name, body.name.as_deref(), plan, env, header_values, None).await {
+ Ok(Installed { server, test, oauth_required }) => {
+ tracing::info!(registry_name = %name, server_id = %server.id, oauth_required, "MCP server added from the directory");
+ (
+ StatusCode::OK,
+ json!({
+ "registry_name": name,
+ "version": entry.version,
+ "server": view(state, &server).await,
+ "test": test,
+ "oauth_required": oauth_required,
+ }),
+ )
+ }
+ Err(InstallFailed { status, error, test }) => {
+ tracing::info!(registry_name = %name, status = status.as_u16(), "adding an MCP server from the directory failed");
+ let mut v = json!({ "error": error });
+ if let Some(t) = test {
+ v["test"] = t;
+ }
+ (status, v)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn addresses_command_lines_and_scrubbing() {
+ assert_eq!(shown_url("https://mcp.stripe.com/"), "https://mcp.stripe.com");
+ assert_eq!(shown_url("https://mcp.notion.com/mcp"), "https://mcp.notion.com/mcp");
+ assert_eq!(shown_url("https://x.example/?a=1"), "https://x.example/?a=1");
+ assert_eq!(same_address("https://MCP.stripe.com/"), same_address("https://mcp.stripe.com"));
+ assert_eq!(command_line("npx", &["-y".into(), "a b".into(), "x".into()]), "npx -y 'a b' x");
+ let v = scrub(json!({"error": "bad key sk_live_123", "n": [1, "Bearer sk_live_123"]}), &["sk_live_123".into()]);
+ assert_eq!(v, json!({"error": format!("bad key {SECRET_MASK}"), "n": [1, format!("Bearer {SECRET_MASK}")]}));
+ }
+}
diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rs
index 06d8f956..80eee6b6 100644
--- a/src/server/mcp_routes.rs
+++ b/src/server/mcp_routes.rs
@@ -40,7 +40,7 @@ async fn opt_outs(state: &AppState, space: &SpaceId) -> std::collections::HashMa
}
/// The API view of `server`, with its sign-in status.
-async fn view(state: &AppState, server: &McpServer) -> McpServerView {
+pub(super) async fn view(state: &AppState, server: &McpServer) -> McpServerView {
let mut view = McpServerView::from(server);
view.oauth = mcp_oauth::statuses(state).await.remove(&server.id).unwrap_or_default();
let space = state.db.space_of_mcp_server(&server.id).await.ok().flatten().unwrap_or_else(SpaceId::default_space);
diff --git a/src/server/mcp_suggest.rs b/src/server/mcp_suggest.rs
index ec9872b9..9461e6a9 100644
--- a/src/server/mcp_suggest.rs
+++ b/src/server/mcp_suggest.rs
@@ -445,6 +445,83 @@ fn free_name(base: &str, taken: &[String]) -> String {
}
}
+/// The server name for an install: the person's `preferred` name when it is one the custom form
+/// accepts (letters, numbers, `-` or `_`, trimmed), else the entry's own name; either way kept
+/// free in the space (`name-2`, …). A preferred name that has no room left for a suffix falls
+/// back to the entry's name too.
+fn install_name(preferred: Option<&str>, registry_name: &str, taken: &[String]) -> String {
+ if let Some(p) = preferred.map(str::trim).filter(|p| mcp::usable_server_name(p)) {
+ let name = free_name(p, taken);
+ if mcp::usable_server_name(&name) {
+ return name;
+ }
+ }
+ free_name(&server_name_for(registry_name), taken)
+}
+
+/// A registry entry set up in a space: the server, its first test, and whether it needs sign-in.
+pub(super) struct Installed {
+ pub server: McpServer,
+ pub test: Value,
+ pub oauth_required: bool,
+}
+
+/// Why setting one up failed; `test` when it was created but didn't start (and was removed).
+pub(super) struct InstallFailed {
+ pub status: StatusCode,
+ pub error: String,
+ pub test: Option<Value>,
+}
+
+/// The shared core of installing a registry entry (a suggestion, or the person's pick from the
+/// directory): create the server from `plan` and the resolved values under a free name, test
+/// it, and keep it if it starts or only needs sign-in. A server that doesn't start is removed.
+/// `for_kwant` switches it on for that bot only; `None` adds it like any server the person adds.
+/// `preferred_name` is the Name the person saw on the form (see `install_name`).
+/// Values are never logged.
+#[allow(clippy::too_many_arguments)]
+pub(super) async fn create_and_test(
+ state: &AppState,
+ space: &SpaceId,
+ registry_name: &str,
+ preferred_name: Option<&str>,
+ plan: &InstallPlan,
+ env: BTreeMap<String, String>,
+ headers: BTreeMap<String, String>,
+ for_kwant: Option<&str>,
+) -> Result<Installed, InstallFailed> {
+ let failed = |status, error: String, test| InstallFailed { status, error, test };
+ let taken: Vec<String> = state.db.list_mcp_servers(space).await.unwrap_or_default().into_iter().map(|s| s.name).collect();
+ let input = McpServerInput {
+ name: install_name(preferred_name, registry_name, &taken),
+ transport: plan.transport.clone(),
+ command: plan.command.clone(),
+ args: Some(plan.args.clone()),
+ url: plan.url.clone(),
+ env: Some(env),
+ headers: Some(headers),
+ enabled: Some(true),
+ timeout_secs: None,
+ };
+ let server = mcp::build_server(input, None).map_err(|e| failed(StatusCode::BAD_REQUEST, e, None))?;
+ let created = match for_kwant {
+ Some(kwant) => state.db.create_mcp_server_for_kwant(space, &server, kwant).await,
+ None => state.db.create_mcp_server(space, &server).await,
+ };
+ let created = created.map_err(|e| {
+ let (status, Json(body)) = db_err(e);
+ failed(status, body["error"].as_str().unwrap_or("database error").to_string(), None)
+ })?;
+ let test = run_test(state, &created).await;
+ let oauth_required = test["auth_required"] == json!(true);
+ if test["ok"] != json!(true) && !oauth_required {
+ let _ = state.db.delete_mcp_server(&created.id).await;
+ let msg = format!("The server didn't start: {}", test["error"].as_str().unwrap_or("unknown error"));
+ return Err(failed(StatusCode::UNPROCESSABLE_ENTITY, msg, Some(test)));
+ }
+ Ok(Installed { server: created, test, oauth_required })
+}
+
/// `POST /api/mcp/suggestions/:id/install {env?, headers?}`: the person installs a suggestion.
/// The server is created from the stored plan only, switched on for the suggesting agent only,
/// and tested. A failed test removes it again and the suggestion stays pending with the error;
@@ -510,39 +587,16 @@ pub async fn install(
}
};
- let taken: Vec<String> = state.db.list_mcp_servers(&space).await.unwrap_or_default().into_iter().map(|s| s.name).collect();
- let input = McpServerInput {
- name: free_name(&server_name_for(&s.registry_name), &taken),
- transport: plan.transport.clone(),
- command: plan.command.clone(),
- args: Some(plan.args.clone()),
- url: plan.url.clone(),
- env: Some(env),
- headers: Some(header_values),
- enabled: Some(true),
- timeout_secs: None,
- };
- let server = match mcp::build_server(input, None) {
- Ok(s) => s,
- Err(e) => return fail(StatusCode::BAD_REQUEST, e, None).await,
- };
- let created = match state.db.create_mcp_server_for_kwant(&space, &server, &s.kwant_id).await {
- Ok(c) => c,
- Err(e) => {
- let (status, Json(body)) = db_err(e);
- let msg = body["error"].as_str().unwrap_or("database error").to_string();
- return fail(status, msg, None).await;
+ let done = match create_and_test(&state, &space, &s.registry_name, None, &plan, env, header_values, Some(&s.kwant_id)).await {
+ Ok(done) => done,
+ Err(InstallFailed { status, error, test }) => {
+ if test.is_some() {
+ tracing::info!(suggestion_id = %id, "suggested MCP server failed its test; removed");
+ }
+ return fail(status, error, test).await;
}
};
-
- let test = run_test(&state, &created).await;
- let oauth_required = test["auth_required"] == json!(true);
- if test["ok"] != json!(true) && !oauth_required {
- let _ = state.db.delete_mcp_server(&created.id).await;
- let msg = format!("The server didn't start: {}", test["error"].as_str().unwrap_or("unknown error"));
- tracing::info!(suggestion_id = %id, "suggested MCP server failed its test; removed");
- return fail(StatusCode::UNPROCESSABLE_ENTITY, msg, Some(test)).await;
- }
+ let Installed { server: created, test, oauth_required } = done;
if state.db.mark_mcp_suggestion_installed(&id, &created.id).await.is_err() {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
@@ -634,4 +688,26 @@ mod tests {
assert!(same_server(&oci, &server("docker", &["run", "ghcr.io/a/c:latest"])));
assert_eq!(free_name("echo", &["echo".into(), "Echo-2".into()]), "echo-3");
}
+
+ #[test]
+ fn install_name_honours_the_forms_name() {
+ let none: Vec<String> = Vec::new();
+ // Honoured, trimmed, case kept
+ assert_eq!(install_name(Some("Stripe"), "com.stripe/mcp", &none), "Stripe");
+ assert_eq!(install_name(Some(" my_tool-2 "), "com.stripe/mcp", &none), "my_tool-2");
+ // Missing or not the form's rule: the entry's own name, as before
+ assert_eq!(install_name(None, "com.stripe/mcp", &none), "stripe");
+ for bad in ["", " ", "Stripe API", "stripé", "a/b", "-x", "a__b", "kwnt", "KWNT_tools", &"x".repeat(49)] {
+ assert_eq!(install_name(Some(bad), "com.stripe/mcp", &none), "stripe", "{bad:?}");
+ }
+ // A clash gets a suffix, case-insensitively
+ let taken: Vec<String> = vec!["stripe".into(), "Stripe-2".into()];
+ assert_eq!(install_name(Some("STRIPE"), "com.stripe/mcp", &taken), "STRIPE-3");
+ assert_eq!(install_name(None, "com.stripe/mcp", &taken), "stripe-3");
+ assert_eq!(install_name(Some("bad name"), "com.stripe/mcp", &taken), "stripe-3");
+ // No room for a suffix: the entry's name instead of a name build_server would refuse
+ let long = "a".repeat(48);
+ assert_eq!(install_name(Some(&long), "com.stripe/mcp", &none), long);
+ assert_eq!(install_name(Some(&long), "com.stripe/mcp", std::slice::from_ref(&long)), "stripe");
+ }
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index af315555..505de12b 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -40,6 +40,7 @@ pub mod spaces;
pub mod asks;
pub mod away;
pub mod computer;
+pub mod mcp_directory;
pub mod mcp_suggest;
pub mod page_source;
pub mod tool_failures;
@@ -140,6 +141,8 @@ pub struct AppState {
pub grok_login: Arc<engine_login::EngineLogin>,
/// The MCP Registry agents search and suggest servers from (`KWNT_MCP_REGISTRY_URL`).
pub mcp_registry: Arc<crate::mcp::registry::McpRegistry>,
+ /// The local copy of the MCP Registry people search (mcp-finder), synced in the background.
+ pub mcp_directory: Arc<crate::mcp::directory::Directory>,
/// Composio's app catalogue (`KWNT_COMPOSIO_API_URL`), called only once Composio is added.
pub composio_api: Arc<crate::mcp::composio::ComposioApi>,
/// Saved website passwords, outside every bot's folder (see `sandbox::credentials`).
@@ -206,6 +209,7 @@ impl AppState {
codex_login: Arc::new(engine_login::EngineLogin::system(crate::profiles::Engine::Codex)),
grok_login: Arc::new(engine_login::EngineLogin::system(crate::profiles::Engine::Grok)),
mcp_registry: Arc::new(crate::mcp::registry::McpRegistry::from_env()),
+ mcp_directory: Arc::default(),
composio_api: Arc::new(crate::mcp::composio::ComposioApi::from_env()),
credentials: Arc::new(crate::sandbox::vault::PasswordVault::open(&config_data_dir)),
zombie: Default::default(),
@@ -436,6 +440,8 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/agent-connections", get(agents_connect::list_connections).post(agents_connect::create_connection))
.route("/api/agent-connections/:id", delete(agents_connect::revoke_connection))
.route("/api/agent-connections/:id/activity", get(agents_connect::connection_activity))
+ .route("/api/mcp/registry/search", get(mcp_directory::search))
+ .route("/api/mcp/registry/install", post(mcp_directory::install))
.route("/api/mcp/suggestions", get(mcp_suggest::list))
.route("/api/mcp/suggestions/:id/install", post(mcp_suggest::install))
.route("/api/mcp/suggestions/:id/dismiss", post(mcp_suggest::dismiss))
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 6a3607f8..88979dd2 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -896,6 +896,7 @@ pub fn spawn_background(state: AppState, shutdown: CancellationToken) {
super::dev::worktrees::spawn(state.clone(), shutdown.clone());
super::dev::tickets::pickup::spawn(state.clone(), shutdown.clone());
super::telegram::spawn(state.clone(), shutdown.clone());
+ state.mcp_directory.clone().spawn(state.mcp_registry.clone(), shutdown.clone());
spawn(state, shutdown);
}
diff --git a/tests/fixtures/mcp_registry/notion.json b/tests/fixtures/mcp_registry/notion.json
new file mode 100644
index 00000000..536fae49
--- /dev/null
+++ b/tests/fixtures/mcp_registry/notion.json
@@ -0,0 +1 @@
+{"servers":[{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-09-29/server.schema.json","name":"ai.smithery/smithery-notion","description":"A Notion workspace is a collaborative environment where teams can organize work, manage projects,…","repository":{"url":"https://github.com/smithery-ai/mcp-servers","source":"github","subfolder":"notion"},"version":"1.0.0","remotes":[{"type":"streamable-http","url":"https://server.smithery.ai/@smithery/notion/mcp","headers":[{"description":"Bearer token for Smithery authentication","isRequired":true,"value":"Bearer {smithery_api_key}","isSecret":true,"name":"Authorization"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2025-09-10T18:26:59.341637Z","publishedAt":"2025-09-10T18:26:59.341637Z","updatedAt":"2025-09-10T18:26:59.341637Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"com.foreverworks/notion","description":"Search, read and write your Notion workspaces, with pages as Markdown and typed database queries.","title":"Notion","repository":{"url":"https://github.com/foreverworks/mcps","source":"github","subfolder":"servers/notion"},"version":"0.1.1","websiteUrl":"https://foreverworks.github.io/mcps/servers/notion/","icons":[{"src":"https://raw.githubusercontent.com/foreverworks/mcps/main/servers/notion/icons/icon.svg","mimeType":"image/svg+xml","sizes":["any"]},{"src":"https://raw.githubusercontent.com/foreverworks/mcps/main/servers/notion/icons/icon-512.png","mimeType":"image/png","sizes":["512x512"]}],"packages":[{"registryType":"npm","registryBaseUrl":"https://registry.npmjs.org","identifier":"@foreverworks/mcp-notion","version":"0.1.1","runtimeHint":"npx","transport":{"type":"stdio"},"environmentVariables":[{"description":"A folder holding one file per workspace, notion-\u003clabel\u003e, each with that workspace's integration token or personal access token.","isRequired":true,"format":"filepath","name":"NOTION_TOKENS_DIR"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-31T13:01:02.722509Z","publishedAt":"2026-10-31T13:01:02.722509Z","updatedAt":"2026-10-31T13:01:02.722509Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"com.insightfulpipe/notion","description":"Hosted Notion MCP server for Claude, ChatGPT and Cursor, with each action switched per account.","title":"Notion MCP by InsightfulPipe","repository":{"url":"https://github.com/Insightful-Pipe/notion-mcp-server","source":"github"},"version":"1.0.0","websiteUrl":"https://insightfulpipe.com/mcp-servers/notion","remotes":[{"type":"streamable-http","url":"https://notion.insightfulmcp.com/"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-21T01:17:43.993497Z","publishedAt":"2026-10-21T01:17:43.993497Z","updatedAt":"2026-10-21T01:17:43.993497Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"com.mcparmory/notion","description":"Create, update, and manage pages, databases, and workspace users","repository":{"url":"https://github.com/mcparmory/registry","source":"github"},"version":"1.0.2","packages":[{"registryType":"pypi","identifier":"mcparmory-notion","version":"1.0.2","runtimeHint":"uvx","transport":{"type":"stdio"}},{"registryType":"oci","identifier":"ghcr.io/mcparmory/notion:1.0.2","runtimeHint":"docker","transport":{"type":"stdio"}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-05-11T20:01:04.251555Z","publishedAt":"2026-05-11T20:01:04.251555Z","updatedAt":"2026-05-11T20:01:04.251555Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-09-29/server.schema.json","name":"com.notion/mcp","description":"Official Notion MCP server","repository":{},"version":"1.0.1","remotes":[{"type":"streamable-http","url":"https://mcp.notion.com/mcp"},{"type":"sse","url":"https://mcp.notion.com/sse"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2025-09-11T22:25:50.737872Z","publishedAt":"2025-09-11T22:25:50.737872Z","updatedAt":"2025-09-11T22:25:50.737872Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.ai-aviate/better-notion","description":"Operate Notion with a single Markdown document — read, create, and update pages in one call.","repository":{"url":"https://github.com/ai-aviate/better-mcp-notion","source":"github"},"version":"0.3.2","packages":[{"registryType":"npm","identifier":"better-mcp-notion","version":"0.3.2","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion API key (starts with ntn_)","isRequired":true,"format":"string","isSecret":true,"name":"NOTION_API_KEY"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-02-19T11:56:28.809509Z","publishedAt":"2026-02-19T11:56:28.809509Z","updatedAt":"2026-02-19T11:56:28.809509Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.awkoy/notion-mcp-server","description":"Token-auth Notion MCP: pages, databases, blocks, comments, files. Runs headless in CI and agents.","repository":{"url":"https://github.com/awkoy/notion-mcp-server","source":"github"},"version":"3.4.0","packages":[{"registryType":"npm","identifier":"notion-mcp-server","version":"3.4.0","runtimeHint":"npx","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion Personal Access Token (ntn_...) or Internal Integration Secret. Create at https://app.notion.com/developers/tokens","isRequired":true,"isSecret":true,"name":"NOTION_TOKEN"},{"description":"Optional default parent page ID used by create_page / create_database when no parent is passed.","name":"NOTION_PAGE_ID"}]},{"registryType":"oci","identifier":"ghcr.io/awkoy/notion-mcp-server:3.4.0","runtimeHint":"docker","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion Personal Access Token (ntn_...) or Internal Integration Secret. Create at https://app.notion.com/developers/tokens","isRequired":true,"isSecret":true,"name":"NOTION_TOKEN"},{"description":"Optional default parent page ID used by create_page / create_database when no parent is passed.","name":"NOTION_PAGE_ID"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-11-09T21:17:36.860321Z","publishedAt":"2026-11-09T21:17:36.860321Z","updatedAt":"2026-11-09T21:17:36.860321Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.cphoskins/notion-full-mcp","description":"Notion MCP server: deep reads, block editing, safe snapshot/restore, file uploads, page move/copy","repository":{"url":"https://github.com/cphoskins/notion-full-mcp","source":"github"},"version":"0.5.1","packages":[{"registryType":"pypi","identifier":"notion-full-mcp","version":"0.5.1","transport":{"type":"stdio"},"environmentVariables":[{"description":"Your Notion integration API token (starts with ntn_)","isRequired":true,"isSecret":true,"name":"NOTION_API_TOKEN"},{"description":"Optional directory that uploads, downloads and snapshots are confined to","name":"NOTION_MCP_FILE_ROOT"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-11-11T02:36:46.175332Z","publishedAt":"2026-11-11T02:36:46.175332Z","updatedAt":"2026-11-11T02:36:46.175332Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.imgul/notion-arena","description":"MCP server for Notion Arena — 143 Notion components: 132 widgets + 11 recipes","repository":{"url":"https://github.com/SynergyFlowLabs/notion-arena","source":"github"},"version":"0.2.2","packages":[{"registryType":"npm","identifier":"notion-arena-mcp","version":"0.2.2","transport":{"type":"stdio"}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-11T21:30:11.031107Z","publishedAt":"2026-10-11T21:30:11.031107Z","updatedAt":"2026-10-11T21:30:11.031107Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.infoinlet-marketplace/mcp-notion","description":"Notion for AI agents — search, read pages/blocks, query databases, create pages.","repository":{"url":"https://github.com/infoinlet-marketplace/marketplace","source":"github","subfolder":"services/mcp-notion"},"version":"0.1.1","packages":[{"registryType":"npm","identifier":"@infoinlet/mcp-notion","version":"0.1.1","transport":{"type":"stdio"}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-05-29T13:29:44.032935Z","publishedAt":"2026-05-29T13:29:44.032935Z","updatedAt":"2026-05-29T13:29:44.032935Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.misterwigglesworth/easy-notion","description":"Markdown-first Notion MCP server. ~6-7x fewer response tokens vs official Notion MCP. 43 tools.","repository":{"url":"https://github.com/Grey-Iris/easy-notion-mcp","source":"github"},"version":"1.1.0","packages":[{"registryType":"npm","identifier":"easy-notion-mcp","version":"1.1.0","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion integration token","isRequired":true,"format":"string","isSecret":true,"name":"NOTION_TOKEN"},{"description":"Default parent page ID for create_page (optional — falls back to workspace root in OAuth mode)","format":"string","name":"NOTION_ROOT_PAGE_ID"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-08-28T01:39:59.043383Z","publishedAt":"2026-08-28T01:39:59.043383Z","updatedAt":"2026-08-28T01:39:59.043383Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.n24q02m/better-notion-mcp","description":"Markdown-first Notion for AI agents -- pages, databases, blocks, and comments in one call.","repository":{"url":"https://github.com/n24q02m/notion.git","source":"github"},"version":"2.42.0","packages":[{"registryType":"npm","identifier":"@n24q02m/notion","version":"2.42.0","runtimeHint":"npx","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion integration token. Create at https://www.notion.so/my-integrations","isRequired":true,"isSecret":true,"name":"NOTION_TOKEN"}]},{"registryType":"oci","identifier":"docker.io/n24q02m/notion:latest","runtimeHint":"docker","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion integration token. Create at https://www.notion.so/my-integrations","isRequired":true,"isSecret":true,"name":"NOTION_TOKEN"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-27T14:11:36.374093Z","publishedAt":"2026-10-27T14:11:36.374093Z","updatedAt":"2026-10-27T14:11:36.374093Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.n24q02m/notion","description":"Markdown-first Notion for AI agents -- pages, databases, blocks, and comments in one call.","repository":{"url":"https://github.com/n24q02m/notion.git","source":"github"},"version":"2.43.0","packages":[{"registryType":"npm","identifier":"@n24q02m/notion","version":"2.43.0","runtimeHint":"npx","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion integration token. Create at https://www.notion.so/my-integrations","isRequired":true,"isSecret":true,"name":"NOTION_TOKEN"}]},{"registryType":"oci","identifier":"docker.io/n24q02m/notion:latest","runtimeHint":"docker","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion integration token. Create at https://www.notion.so/my-integrations","isRequired":true,"isSecret":true,"name":"NOTION_TOKEN"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-11-12T16:58:46.034765Z","publishedAt":"2026-11-12T16:58:46.034765Z","updatedAt":"2026-11-12T16:58:46.034765Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.pipeworx-io/notion_connect","description":"Notion MCP Pack","title":"Notion_connect","repository":{"url":"https://github.com/pipeworx-io/mcp-notion_connect","source":"github"},"version":"0.2.1","websiteUrl":"https://pipeworx.io/packs/notion_connect","packages":[{"registryType":"npm","identifier":"@pipeworx/mcp-notion_connect","version":"0.2.1","transport":{"type":"stdio"},"environmentVariables":[{"description":"Optional Pipeworx API key. Without it calls are anonymous and capped daily; a free key raises the cap.","isSecret":true,"name":"PIPEWORX_API_KEY"}]}],"remotes":[{"type":"streamable-http","url":"https://gateway.pipeworx.io/notion_connect/mcp"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-11-03T21:06:14.912749Z","publishedAt":"2026-11-03T21:06:14.912749Z","updatedAt":"2026-11-03T21:06:14.912749Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.quietnotion/barevalue","description":"AI podcast editing. Sign up in one call, send audio by link or from disk, get an edited episode.","title":"Barevalue","repository":{"url":"https://github.com/barevalue-ai/barevalue-mcp","source":"github"},"version":"1.5.0","packages":[{"registryType":"npm","identifier":"barevalue-mcp","version":"1.5.0","transport":{"type":"stdio"},"environmentVariables":[{"description":"Optional Barevalue API key. Without one, barevalue_register gives a new email address a key.","format":"string","isSecret":true,"name":"BAREVALUE_API_KEY"}]}],"remotes":[{"type":"streamable-http","url":"https://barevalue.com/mcp"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-14T08:59:43.846787Z","publishedAt":"2026-10-14T08:59:43.846787Z","updatedAt":"2026-10-14T08:59:43.846787Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.sadri-dridi/notion-url-shape","description":"Check a Notion URL shape. Path discarded.","title":"Notion URL Shape","repository":{"url":"https://github.com/sadri-dridi/named-mcp-utilities","source":"github"},"version":"1.0.0","remotes":[{"type":"streamable-http","url":"https://agent-observatory-sensor.nolimit-observatory.workers.dev/s/notion-url-shape/mcp"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-09-08T22:53:53.016903Z","publishedAt":"2026-09-08T22:53:53.016903Z","updatedAt":"2026-09-08T22:53:53.016903Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.shck-dev/notion-mcp","description":"Notion MCP server — search, export, and import pages as markdown","repository":{"url":"https://github.com/shck-dev/notion-mcp","source":"github"},"version":"0.5.2","packages":[{"registryType":"npm","identifier":"@shck-dev/notion-mcp","version":"0.5.2","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion token_v2 cookie value from browser DevTools","isRequired":true,"isSecret":true,"name":"NOTION_TOKEN"},{"description":"Notion user ID from x-notion-active-user-header","isRequired":true,"name":"NOTION_USER_ID"},{"description":"Notion workspace ID from API request body","isRequired":true,"name":"NOTION_SPACE_ID"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-06-23T16:14:39.768548Z","publishedAt":"2026-06-23T16:14:39.768548Z","updatedAt":"2026-06-23T16:14:39.768548Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.shoubhiksaha/notion-large-file-upload","description":"Upload local files up to 5 GB to Notion and attach them to pages, read from disk, not the chat.","title":"Notion Large File Upload","repository":{"url":"https://github.com/shoubhiksaha/notion-multipart-uploader","source":"github","subfolder":"mcp-server"},"version":"1.0.0","websiteUrl":"https://github.com/shoubhiksaha/notion-multipart-uploader/tree/main/mcp-server#readme","packages":[{"registryType":"npm","identifier":"notion-large-file-upload-mcp","version":"1.0.0","transport":{"type":"stdio"},"environmentVariables":[{"description":"Notion integration token. The integration needs access to the pages you attach files to.","isRequired":true,"format":"string","isSecret":true,"name":"NOTION_KEY"},{"description":"Folders the server may upload files from, separated by : (; on Windows). Uploads are refused until this is set.","isRequired":true,"format":"string","name":"NOTION_UPLOAD_ALLOWED_DIRS"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-28T21:20:05.9213Z","publishedAt":"2026-10-28T21:20:05.9213Z","updatedAt":"2026-10-28T21:20:05.9213Z","isLatest":true}}}],"metadata":{"count":18}}
diff --git a/tests/fixtures/mcp_registry/stripe.json b/tests/fixtures/mcp_registry/stripe.json
new file mode 100644
index 00000000..40a62d55
--- /dev/null
+++ b/tests/fixtures/mcp_registry/stripe.json
@@ -0,0 +1 @@
+{"servers":[{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-09-29/server.schema.json","name":"app.vercel.stripecheckup/stripecheckup","description":"Scan pasted Stripe webhook/checkout code for common integration bugs.","version":"1.0.0","websiteUrl":"https://stripecheckup.vercel.app","remotes":[{"type":"streamable-http","url":"https://stripecheckup.vercel.app/api/mcp"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-09-13T04:31:29.710593Z","publishedAt":"2026-09-13T04:31:29.710593Z","updatedAt":"2026-09-13T04:31:29.710593Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"com.insightfulpipe/stripe","description":"Hosted Stripe MCP server for Claude, ChatGPT and Cursor, with each action switched per account.","title":"Stripe MCP by InsightfulPipe","repository":{"url":"https://github.com/Insightful-Pipe/stripe-mcp-server","source":"github"},"version":"1.0.0","websiteUrl":"https://insightfulpipe.com/mcp-servers/stripe","remotes":[{"type":"streamable-http","url":"https://stripe.insightfulmcp.com/"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-21T01:18:16.929141Z","publishedAt":"2026-10-21T01:18:16.929141Z","updatedAt":"2026-10-21T01:18:16.929141Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-10-17/server.schema.json","name":"com.stripe/mcp","description":"MCP server integrating with Stripe - tools for customers, products, payments, and more.","repository":{"url":"https://github.com/stripe/agent-toolkit","source":"github"},"version":"0.2.4","remotes":[{"type":"streamable-http","url":"https://mcp.stripe.com"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2025-10-28T22:06:18.495159Z","publishedAt":"2025-10-28T22:06:18.495159Z","updatedAt":"2025-10-28T22:06:18.495159Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"eu.nordicmcp/stripe","description":"Hosted Stripe MCP server: 18 tools for payments, subscriptions, invoicing, customers, and reporting.","title":"NordicMCP — Stripe","repository":{"url":"https://github.com/pefman/nordicmcp.eu","source":"github"},"version":"1.0.0","websiteUrl":"https://nordicmcp.eu/docs/integrations/stripe","remotes":[{"type":"streamable-http","url":"https://nordicmcp.eu/mcp/stripe/{token}","variables":{"token":{"description":"Your NordicMCP API token (36-char UUID) for the Stripe integration — create one at https://nordicmcp.eu after adding your Stripe key","isRequired":true,"isSecret":true}}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-08-16T20:07:08.826426Z","publishedAt":"2026-08-16T20:07:08.826426Z","updatedAt":"2026-08-16T20:07:08.826426Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.CSOAI-ORG/meok-stripe-acp-checkout-mcp","description":"MEOK Stripe ACP Checkout MCP — ChatGPT shopping bridge. Issues + verifies + signs Stripe Agentic","repository":{"url":"https://github.com/CSOAI-ORG/meok-stripe-acp-checkout-mcp","source":"github"},"version":"1.0.6","packages":[{"registryType":"pypi","identifier":"meok-stripe-acp-checkout-mcp","version":"1.0.6","runtimeHint":"python","transport":{"type":"stdio"}}],"remotes":[{"type":"streamable-http","url":"https://api.meok.ai/v1/a2a/stripe-acp-checkout"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"deprecated","statusChangedAt":"2026-09-29T15:57:54.820711Z","statusMessage":"Remote endpoint https://api.meok.ai/v1/a2a/stripe-acp-checkout is not live: api.meok.ai has no public DNS answer (checked via 1.1.1.1, 2026-09-29). Deprecated by the publisher until a live endpoint exists. The PyPI package meok-stripe-acp-checkout-mcp still installs and runs locally over stdio.","publishedAt":"2026-08-19T15:21:32.235791Z","updatedAt":"2026-09-29T15:57:54.820711Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.CSOAI-ORG/stripe-billing-mcp","description":"Stripe Billing MCP Server by MEOK AI Labs","repository":{"url":"https://github.com/CSOAI-ORG/stripe-billing-mcp","source":"github"},"version":"1.0.6","packages":[{"registryType":"pypi","identifier":"stripe-billing-mcp","version":"1.0.7","runtimeHint":"python","transport":{"type":"stdio"}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-08-19T15:22:33.751443Z","publishedAt":"2026-08-19T15:22:33.751443Z","updatedAt":"2026-08-19T15:22:33.751443Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.codespar/mcp-stripe","description":"MCP server for Stripe — global payments API (PaymentIntents, Checkout, Billing, Refunds)","repository":{"url":"https://github.com/codespar/mcp-dev-latam","source":"github","subfolder":"packages/payments/stripe"},"version":"0.2.2","packages":[{"registryType":"npm","identifier":"@codespar/mcp-stripe","version":"0.2.2","transport":{"type":"stdio"},"environmentVariables":[{"description":"Stripe secret key (sk_test_... for test mode, sk_live_... for live mode). The key prefix selects the environment — no separate base URL.","isRequired":true,"format":"string","isSecret":true,"name":"STRIPE_SECRET_KEY"},{"description":"Optional Stripe API version to pin via the Stripe-Version header (e.g. '2024-06-20'). When omitted, Stripe uses the account's default version.","format":"string","name":"STRIPE_API_VERSION"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-06-22T18:52:33.068289Z","publishedAt":"2026-06-22T18:52:33.068289Z","updatedAt":"2026-06-22T18:52:33.068289Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.codespar/mcp-stripe-acp","description":"Stripe ACP — AI agent checkout, payment delegation, products, invoices","repository":{"url":"https://github.com/codespar/mcp-dev-latam","source":"github","subfolder":"packages/payments/stripe-acp"},"version":"0.1.4","packages":[{"registryType":"npm","identifier":"@codespar/mcp-stripe-acp","version":"0.1.4","transport":{"type":"stdio"},"environmentVariables":[{"description":"API key for stripe-acp","isRequired":true,"format":"string","isSecret":true,"name":"STRIPE_API_KEY"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-06-22T18:52:35.305082Z","publishedAt":"2026-06-22T18:52:35.305082Z","updatedAt":"2026-06-22T18:52:35.305082Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.friendlygeorge/stripe-mcp-server","description":"MCP server for Stripe API — customers, charges, payments, subscriptions, products, and invoices","repository":{"url":"https://github.com/friendlygeorge/stripe-mcp-server","source":"github"},"version":"1.0.0","packages":[{"registryType":"npm","identifier":"stripe-mcp-server","version":"1.0.0","transport":{"type":"stdio"}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-06-06T14:46:21.741051Z","publishedAt":"2026-06-06T14:46:21.741051Z","updatedAt":"2026-06-06T14:46:21.741051Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.infoinlet-marketplace/mcp-stripe","description":"Read-only Stripe for AI agents — customers, charges, subscriptions, invoices, balance.","repository":{"url":"https://github.com/infoinlet-marketplace/marketplace","source":"github","subfolder":"services/mcp-stripe"},"version":"0.1.1","packages":[{"registryType":"npm","identifier":"@infoinlet/mcp-stripe","version":"0.1.1","transport":{"type":"stdio"}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-05-31T00:55:08.565667Z","publishedAt":"2026-05-31T00:55:08.565667Z","updatedAt":"2026-05-31T00:55:08.565667Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.lordbasilaiassistant-sudo/stripe-analytics","description":"Stripe analytics — revenue, customers, subscriptions, refunds, churn from Claude.","repository":{"url":"https://github.com/lordbasilaiassistant-sudo/mcp-stripe-analytics","source":"github"},"version":"1.0.1","packages":[{"registryType":"npm","identifier":"mcp-stripe-analytics","version":"1.0.1","transport":{"type":"stdio"},"environmentVariables":[{"description":"Your Stripe secret API key","isRequired":true,"format":"string","isSecret":true,"name":"STRIPE_SECRET_KEY"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-03-07T14:57:10.761149Z","publishedAt":"2026-03-07T14:57:10.761149Z","updatedAt":"2026-03-07T14:57:10.761149Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.mcp-dir/stripe-mcp","description":"Payments and billing on Stripe with the full official REST API (api.stripe.com), covers the entire d","title":"Stripe","repository":{"url":"https://github.com/mcp-dir/stripe-mcp","source":"github"},"version":"0.1.0","remotes":[{"type":"streamable-http","url":"https://api.mcp.ai/p_stripe"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-08-21T13:34:29.620542Z","publishedAt":"2026-08-21T13:34:29.620542Z","updatedAt":"2026-08-21T13:34:29.620542Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.mrfentmen/stripe-mcp","description":"Query the Stripe API (test-mode key; set STRIPE_SECRET_KEY, Basic): charges, customers, balance.","repository":{"url":"https://github.com/mrfentmen/premium-mcps","source":"github"},"version":"1.1.0","packages":[{"registryType":"npm","identifier":"@mrfentmen/stripe-mcp","version":"1.1.0","transport":{"type":"stdio"}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-17T06:58:56.506158Z","publishedAt":"2026-10-17T06:58:56.506158Z","updatedAt":"2026-10-17T06:58:56.506158Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.pipeworx-io/stripe_connect","description":"Stripe MCP Pack — read-only access to Stripe data via API key.","title":"Stripe_connect","repository":{"url":"https://github.com/pipeworx-io/mcp-stripe_connect","source":"github"},"version":"0.2.1","websiteUrl":"https://pipeworx.io/packs/stripe_connect","packages":[{"registryType":"npm","identifier":"@pipeworx/mcp-stripe_connect","version":"0.2.1","transport":{"type":"stdio"},"environmentVariables":[{"description":"Optional Pipeworx API key. Without it calls are anonymous and capped daily; a free key raises the cap.","isSecret":true,"name":"PIPEWORX_API_KEY"}]}],"remotes":[{"type":"streamable-http","url":"https://gateway.pipeworx.io/stripe_connect/mcp"}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-11-05T20:54:27.414773Z","publishedAt":"2026-11-05T20:54:27.414773Z","updatedAt":"2026-11-05T20:54:27.414773Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.rafaelcg/stripekit","description":"Reconcile a declarative Stripe catalog and inspect your account — plan, push, pull, check.","repository":{"url":"https://github.com/rafaelcg/stripekit","source":"github"},"version":"0.2.2","packages":[{"registryType":"npm","identifier":"stripekit","version":"0.2.2","runtimeHint":"npx","transport":{"type":"stdio"},"packageArguments":[{"type":"positional","value":"mcp"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-08-07T21:51:15.856516Z","publishedAt":"2026-08-07T21:51:15.856516Z","updatedAt":"2026-08-07T21:51:15.856516Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.robinafaruqia/stripe-mcp","description":"Read-only MCP server for querying Stripe customers, payments, and invoices.","title":"Stripe MCP","repository":{"url":"https://github.com/robinafaruqia/stripe-mcp","source":"github"},"version":"0.1.2","websiteUrl":"https://www.npmjs.com/package/@devtechtricks/stripe-mcp","packages":[{"registryType":"npm","identifier":"@devtechtricks/stripe-mcp","version":"0.1.2","transport":{"type":"stdio"},"environmentVariables":[{"description":"Stripe test-mode secret or restricted key (sk_test_ or rk_test_)","isRequired":true,"format":"string","isSecret":true,"placeholder":"sk_test_...","name":"STRIPE_SECRET_KEY"}]}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-09-04T12:00:37.01482Z","publishedAt":"2026-09-04T12:00:37.01482Z","updatedAt":"2026-09-04T12:00:37.01482Z","isLatest":true}}},{"server":{"$schema":"https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name":"io.github.theluckystrike/stripe-billing","description":"Read your Stripe billing data from AI chat: balances, invoices, subscriptions. Read-only.","repository":{"url":"https://github.com/theluckystrike/mcp-servers","source":"github","subfolder":"servers/stripe-billing"},"version":"1.0.1","packages":[{"registryType":"mcpb","identifier":"https://github.com/theluckystrike/mcp-servers/releases/download/v0.22.0/stripe-billing.mcpb","version":"1.0.1","fileSha256":"f371cbf173a881fd462da68578ea12d8f6804dd365e049397bade2805f0960af","transport":{"type":"stdio"}}]},"_meta":{"io.modelcontextprotocol.registry/official":{"status":"active","statusChangedAt":"2026-10-09T11:40:17.501007Z","publishedAt":"2026-10-09T11:40:17.501007Z","updatedAt":"2026-10-09T11:40:17.501007Z","isLatest":true}}}],"metadata":{"count":17}}
diff --git a/tests/mcp_suggest_test.rs b/tests/mcp_suggest_test.rs
index a3f665a3..0918a444 100644
--- a/tests/mcp_suggest_test.rs
+++ b/tests/mcp_suggest_test.rs
@@ -25,7 +25,7 @@ use kwnt::{
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use tempfile::{tempdir, TempDir};
use tower::ServiceExt;
@@ -67,20 +67,39 @@ async fn fake_signin_mcp() -> String {
}
struct Registry {
- entries: Vec<Value>,
+ entries: Mutex<Vec<Value>>,
hits: AtomicUsize,
+ /// Every `updated_since` a listing was asked with.
+ since: Mutex<Vec<String>>,
}
+/// Listing pages: a search answers in one page; a listing without one (the directory's sync)
+/// comes 2 entries a page with `nextCursor`, and `updated_since` keeps only entries changed after it.
async fn list(State(r): State<Arc<Registry>>, Query(q): Query<HashMap<String, String>>) -> Json<Value> {
r.hits.fetch_add(1, Ordering::SeqCst);
- let search = q.get("search").cloned().unwrap_or_default();
- let servers: Vec<Value> = r.entries.iter().filter(|e| e["server"]["name"].as_str().unwrap().contains(&search)).cloned().collect();
- Json(json!({"servers": servers, "metadata": {"count": servers.len()}}))
+ let entries = r.entries.lock().unwrap().clone();
+ if let Some(search) = q.get("search") {
+ let servers: Vec<Value> = entries.iter().filter(|e| e["server"]["name"].as_str().unwrap().contains(search.as_str())).cloned().collect();
+ return Json(json!({"servers": servers, "metadata": {"count": servers.len()}}));
+ }
+ assert_eq!(q.get("version").map(String::as_str), Some("latest"));
+ let mut entries = entries;
+ if let Some(since) = q.get("updated_since") {
+ r.since.lock().unwrap().push(since.clone());
+ entries.retain(|e| e["_meta"]["io.modelcontextprotocol.registry/official"]["updatedAt"].as_str().unwrap_or("") > since.as_str());
+ }
+ let start: usize = q.get("cursor").map(|c| c.parse().unwrap()).unwrap_or(0);
+ let servers: Vec<Value> = entries.iter().skip(start).take(2).cloned().collect();
+ let mut metadata = json!({"count": servers.len()});
+ if start + 2 < entries.len() {
+ metadata["nextCursor"] = json!((start + 2).to_string());
+ }
+ Json(json!({"servers": servers, "metadata": metadata}))
}
async fn one(State(r): State<Arc<Registry>>, Path((name, version)): Path<(String, String)>) -> Response {
assert_eq!(version, "latest");
- match r.entries.iter().find(|e| e["server"]["name"] == name.as_str()) {
+ match r.entries.lock().unwrap().iter().find(|e| e["server"]["name"] == name.as_str()) {
Some(e) => Json(e.clone()).into_response(),
None => StatusCode::NOT_FOUND.into_response(),
}
@@ -92,7 +111,8 @@ fn entry(name: &str, server: Value, status: &str) -> Value {
for (k, v) in server.as_object().unwrap() {
s[k] = v.clone();
}
- json!({"server": s, "_meta": {"io.modelcontextprotocol.registry/official": {"status": status, "isLatest": true}}})
+ json!({"server": s, "_meta": {"io.modelcontextprotocol.registry/official": {"status": status, "isLatest": true,
+ "updatedAt": "2026-01-01T00:00:00Z"}}})
}
async fn fake_registry(echo_url: &str, signin_url: &str) -> (String, Arc<Registry>) {
@@ -113,7 +133,7 @@ async fn fake_registry(echo_url: &str, signin_url: &str) -> (String, Arc<Registr
entry("io.github.kwnt-test/echo-shell", json!({"description": "Wants a shell.",
"packages": [{"registryType": "npm", "identifier": "x", "version": "1.0.0", "runtimeHint": "bash", "transport": {"type": "stdio"}}]}), "active"),
];
- let reg = Arc::new(Registry { entries, hits: AtomicUsize::new(0) });
+ let reg = Arc::new(Registry { entries: Mutex::new(entries), hits: AtomicUsize::new(0), since: Mutex::new(Vec::new()) });
let app = Router::new()
.route("/v0.1/servers", get(list))
.route("/v0.1/servers/:name/versions/:version", get(one))
@@ -460,6 +480,221 @@ async fn server_that_needs_sign_in_is_kept_and_says_so() {
assert!(e.state.db.get_mcp_server(server_id).await.unwrap().is_some());
}
+// ---- The public directory (Find a tool): GET /api/mcp/registry/search, POST /api/mcp/registry/install ----
+
+async fn dir_search(e: &Env, q: &str) -> Value {
+ let (status, v) = call(&e.app, "GET", &format!("/api/mcp/registry/search?q={q}"), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ v
+}
+
+fn row<'a>(v: &'a Value, name: &str) -> Option<&'a Value> {
+ v["entries"].as_array().unwrap().iter().find(|r| r["registry_name"] == name)
+}
+
+fn now_rfc3339() -> String {
+ chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
+}
+
+#[tokio::test]
+async fn directory_searches_live_until_the_copy_is_synced_then_keeps_it_current() {
+ let e = setup().await;
+
+ // No copy yet: the registry's own search answers
+ let v = dir_search(&e, "echo").await;
+ assert_eq!(v["source"], "live");
+ assert_eq!(v["unavailable"], false);
+ let echo = row(&v, "io.github.kwnt-test/echo").expect("echo").clone();
+ assert_eq!(echo["title"], "Echo");
+ assert_eq!(echo["kind"], "remote");
+ assert_eq!(echo["transport"], "http");
+ assert_eq!(echo["url"], e.echo_url.as_str());
+ assert_eq!(echo["command"], Value::Null);
+ assert_eq!(echo["publisher"], json!({"label": "github.com/kwnt-test", "kind": "github"}));
+ assert_eq!(echo["inputs"][0], json!({"name": "Authorization", "description": "Your Echo API key", "required": true, "secret": true}));
+ assert_eq!(echo["already_added"], false);
+ let local = row(&v, "io.github.kwnt-test/echo-local").expect("local");
+ assert_eq!(local["kind"], "stdio");
+ assert_eq!(local["url"], Value::Null);
+ assert_eq!(local["command"], "npx -y @kwnt-test/[email protected]");
+ assert!(row(&v, "io.github.kwnt-test/echo-shell").is_none(), "not one click");
+ assert!(row(&v, "io.github.kwnt-test/echo-old").is_none(), "deleted");
+ // An exact name comes first
+ assert_eq!(v["entries"][0]["registry_name"], "io.github.kwnt-test/echo");
+
+ // Too short to search, and an agent's token is refused
+ let v = dir_search(&e, "e").await;
+ assert_eq!(v["entries"], json!([]));
+ let token = turn(&e, "t-dir").await;
+ let (status, _) = call(&e.app, "GET", "/api/mcp/registry/search?q=echo", Some(&token), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+
+ // The first sync pages through everything (6 entries, 2 a page)
+ let hits = e.reg.hits.load(Ordering::SeqCst);
+ let kept = e.state.mcp_directory.sync_once(&e.state.mcp_registry).await.unwrap();
+ assert_eq!(kept, 4, "echo, echo-local, echo-broken, echo-signin");
+ assert_eq!(e.reg.hits.load(Ordering::SeqCst) - hits, 3);
+ assert!(e.reg.since.lock().unwrap().is_empty(), "the first sync is a full one");
+
+ // Now the copy answers, without asking the registry
+ let hits = e.reg.hits.load(Ordering::SeqCst);
+ let v = dir_search(&e, "echo").await;
+ assert_eq!(v["source"], "copy");
+ assert_eq!(v["entries"][0]["registry_name"], "io.github.kwnt-test/echo");
+ assert_eq!(v["entries"].as_array().unwrap().len(), 4);
+ let v = dir_search(&e, "ehco").await;
+ assert_eq!(v["entries"][0]["registry_name"], "io.github.kwnt-test/echo", "one typo still finds it: {v}");
+ assert_eq!(e.reg.hits.load(Ordering::SeqCst), hits);
+
+ // The next sync asks only for what changed: a new entry arrives and a deleted one goes
+ {
+ let mut entries = e.reg.entries.lock().unwrap();
+ let mut fresh = entry("io.github.kwnt-test/echo-new", json!({"description": "Brand new.",
+ "remotes": [{"type": "streamable-http", "url": "https://new.example/mcp"}]}), "active");
+ fresh["_meta"]["io.modelcontextprotocol.registry/official"]["updatedAt"] = json!(now_rfc3339());
+ entries.push(fresh);
+ let broken = entries.iter_mut().find(|x| x["server"]["name"] == "io.github.kwnt-test/echo-broken").unwrap();
+ broken["_meta"]["io.modelcontextprotocol.registry/official"]["status"] = json!("deleted");
+ broken["_meta"]["io.modelcontextprotocol.registry/official"]["updatedAt"] = json!(now_rfc3339());
+ }
+ let kept = e.state.mcp_directory.sync_once(&e.state.mcp_registry).await.unwrap();
+ assert_eq!(kept, 4);
+ assert_eq!(e.reg.since.lock().unwrap().len(), 1, "one page of changes");
+ let v = dir_search(&e, "echo").await;
+ assert!(row(&v, "io.github.kwnt-test/echo-new").is_some(), "{v}");
+ assert!(row(&v, "io.github.kwnt-test/echo-broken").is_none(), "{v}");
+ assert!(row(&v, "io.github.kwnt-test/echo").is_some(), "unchanged entries stay");
+
+ // Registry down after a sync: the copy still answers
+ let mut e = e;
+ e.state.mcp_registry = Arc::new(McpRegistry::new("http://127.0.0.1:9"));
+ e.app = create_router(e.state.clone());
+ assert!(e.state.mcp_directory.sync_once(&e.state.mcp_registry).await.is_err());
+ let v = dir_search(&e, "echo").await;
+ assert_eq!(v["source"], "copy");
+ assert_eq!(v["unavailable"], false);
+ assert_eq!(v["entries"].as_array().unwrap().len(), 4);
+}
+
+#[tokio::test]
+async fn directory_without_copy_or_registry_says_unavailable() {
+ let mut e = setup().await;
+ e.state.mcp_registry = Arc::new(McpRegistry::new("http://127.0.0.1:9"));
+ e.app = create_router(e.state.clone());
+ let v = dir_search(&e, "stripe").await;
+ assert_eq!(v["entries"], json!([]));
+ assert_eq!(v["unavailable"], true);
+ let (status, v) = call(&e.app, "POST", "/api/mcp/registry/install", None, Some(json!({"registry_name": "com.stripe/mcp"}))).await;
+ assert_eq!(status, StatusCode::BAD_GATEWAY);
+ assert_eq!(v["unavailable"], true);
+}
+
+#[tokio::test]
+async fn directory_install_adds_tests_and_never_echoes_secrets() {
+ let e = setup().await;
+ let install = |body: Value| {
+ let app = e.app.clone();
+ async move { call(&app, "POST", "/api/mcp/registry/install", None, Some(body)).await }
+ };
+
+ // Agents can't add from the directory
+ let token = turn(&e, "t-dir-install").await;
+ let (status, _) = call(&e.app, "POST", "/api/mcp/registry/install", Some(&token),
+ Some(json!({"registry_name": "io.github.kwnt-test/echo", "headers": {"Authorization": SECRET}}))).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert!(servers(&e).await.is_empty());
+
+ // Refusals, none of which quote a value
+ let (status, v) = install(json!({"registry_name": "../etc/passwd"})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");
+ let (status, v) = install(json!({"registry_name": "io.github.kwnt-test/nope"})).await;
+ assert_eq!(status, StatusCode::NOT_FOUND, "{v}");
+ let (status, v) = install(json!({"registry_name": "io.github.kwnt-test/echo-shell"})).await;
+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{v}");
+ assert!(v["error"].as_str().unwrap().contains("one step"), "{v}");
+ let (status, v) = install(json!({"registry_name": "io.github.kwnt-test/echo"})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");
+ assert!(v["error"].as_str().unwrap().contains("Authorization is required"), "{v}");
+ let (status, v) = install(json!({"registry_name": "io.github.kwnt-test/echo", "headers": {"X-Other": SECRET}})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");
+ assert!(!v.to_string().contains(SECRET), "{v}");
+ let (status, v) = install(json!({"registry_name": 5, "headers": {"Authorization": SECRET}})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");
+ assert!(!v.to_string().contains(SECRET), "{v}");
+ let (status, v) = install(json!({"registry_name": "io.github.kwnt-test/echo", "headers": {"Authorization": "line\nbreak-123"}})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{v}");
+ assert!(!v.to_string().contains("break-123"), "{v}");
+
+ // A wrong key: the server doesn't start, isn't kept, and the key isn't echoed
+ let (status, v) = install(json!({"registry_name": "io.github.kwnt-test/echo", "headers": {"Authorization": "wrong-key-999"}})).await;
+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{v}");
+ assert!(!v.to_string().contains("wrong-key-999"), "{v}");
+ assert!(servers(&e).await.is_empty());
+
+ // The right key: added for every bot, tested, masked
+ let (status, v) = install(json!({"registry_name": "io.github.kwnt-test/echo", "headers": {"Authorization": SECRET}})).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert!(!v.to_string().contains(SECRET), "{v}");
+ assert_eq!(v["registry_name"], "io.github.kwnt-test/echo");
+ assert_eq!(v["version"], "1.0.0");
+ assert_eq!(v["oauth_required"], false);
+ assert_eq!(v["test"]["ok"], true, "{v}");
+ assert_eq!(v["server"]["name"], "echo");
+ assert_eq!(v["server"]["headers"]["Authorization"], SECRET_MASK);
+ assert_eq!(v["server"]["disabled_for_kwants"], json!([]));
+ let id = v["server"]["id"].as_str().unwrap().to_string();
+ let stored = e.state.db.get_mcp_server(&id).await.unwrap().unwrap();
+ assert_eq!(stored.headers.get("Authorization").map(String::as_str), Some(format!("Bearer {SECRET}").as_str()));
+
+ // The search now says it's there
+ let v = dir_search(&e, "echo").await;
+ assert_eq!(row(&v, "io.github.kwnt-test/echo").unwrap()["already_added"], true);
+ assert_eq!(row(&v, "io.github.kwnt-test/echo-signin").unwrap()["already_added"], false);
+
+ // One that needs sign-in is kept and says so
+ let (status, v) = install(json!({"registry_name": "io.github.kwnt-test/echo-signin"})).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(v["oauth_required"], true);
+ assert_eq!(v["test"]["auth_required"], true);
+ assert_eq!(servers(&e).await.len(), 2);
+}
+
+#[tokio::test]
+async fn directory_install_uses_the_forms_name() {
+ let e = setup().await;
+ let install = |body: Value| {
+ let app = e.app.clone();
+ async move { call(&app, "POST", "/api/mcp/registry/install", None, Some(body)).await }
+ };
+ let added = |v: &Value| v["server"]["name"].as_str().unwrap_or_default().to_string();
+ let signin = "io.github.kwnt-test/echo-signin";
+
+ // Name honoured (trimmed, case kept)
+ let (status, v) = install(json!({"registry_name": signin, "name": " Echo_Login "})).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(added(&v), "Echo_Login");
+ // A clash with it gets a suffix
+ let (status, v) = install(json!({"registry_name": signin, "name": "echo_login"})).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(added(&v), "echo_login-2");
+ // Missing name: today's behaviour, the entry's own name
+ let (status, v) = install(json!({"registry_name": signin})).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(added(&v), "echo-signin");
+ // Not the form's rule (or kwnt's own name): the entry's name, kept free
+ for (bad, want) in [("Echo Login!", "echo-signin-2"), (" ", "echo-signin-3"), ("kwnt", "echo-signin-4"), ("a__b", "echo-signin-5")] {
+ let (status, v) = install(json!({"registry_name": signin, "name": bad})).await;
+ assert_eq!(status, StatusCode::OK, "{bad:?}: {v}");
+ assert_eq!(added(&v), want, "{bad:?}");
+ }
+ // A name that isn't text is refused like any bad body, and nothing is added
+ let (status, _) = install(json!({"registry_name": signin, "name": 5})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ let mut names: Vec<String> = servers(&e).await.into_iter().map(|s| s.name).collect();
+ names.sort();
+ assert_eq!(names, ["Echo_Login", "echo-signin", "echo-signin-2", "echo-signin-3", "echo-signin-4", "echo-signin-5", "echo_login-2"]);
+}
+
/// The real registry, by hand only: `cargo test --test mcp_suggest_test -- --ignored`.
#[tokio::test]
#[ignore = "talks to registry.modelcontextprotocol.io"]