連接器: a 公用市集 of remote servers from the official MCP Registry, on the computer and the phone

- 連接器市集 gets a search box over registry.modelcontextprotocol.io (public, with an API):
  servers reached by address only (a package would have to run on the brain, which may have no
  Node or uv); old SSE ones are marked as not yet supported, taken-down ones left out. A name
  that only says "mcp" (com.notion/mcp) reads as whose it is (notion).
- 加入 on the computer fills 新增連接器 and scrolls to it: a free name, the address, and the
  header with the registry's placeholder ("Authorization: Bearer {smithery_api_key}"), shown
  unmasked with what to put there (the key's description, an address variable's choices). 新增
  stays off while a 「{…}」 is left.
- The phone: 設定 › 整合 › 從公用市集加入. The brain searches (the phone's page may only talk to
  its own server; GET /api/mcp/registry, owner only, on the HTTP thread); a pick asks for the key
  or the address part and the brain adds it (the 「mcp」 action's new `add`).
- A server that answers 401 (or a 403 asking for a login) with no key given now says it signs
  people in with OAuth, which AnyBot can't do yet; with a key, that the key is wrong or old.
- mcpservers.org and the like are pages for people behind a browser check, with no list a program
  may read, so the market uses the registry.
- Checked live: 「notion」 finds 6; AWS Knowledge (no key) connects with 5 tools; Notion's own
  server (OAuth) gives the OAuth sentence. `cargo test -- --ignored registry_search_live`.
- Screenshot mode: ANYBOT_SHOT_MCP=<search> shows the 公用市集 after that search.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-11 17:12:12 +08:00
parent 41b6b7f465
commit 915fdcf589
7 changed files with 390 additions and 6 deletions

View File

@ -2004,6 +2004,13 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
- 工具數:files 14、memory 9、thinking 1、fetch 1、git 12、time 2、playwright 25。
- 用 time 實際查了台北時間。
- 測試是 `cargo test --release -- --ignored marketplace`。
- **公用市集**:連接器市集下面有搜尋框,搜官方 MCP Registry(registry.modelcontextprotocol.io,公開、有 API)裡用網址連的連接器。
- 只列用網址連的(Streamable HTTP);要在大腦上跑套件的(npm/PyPI)不列,伺服器上的大腦不一定有 Node.js 或 uv。舊式 SSE 的標「還不支援」;下架的不列。
- 電腦上按「加入」會把「新增連接器」表單填好、捲過去:名稱(重複就加「2」)、網址、標頭(例如「Authorization: Bearer {smithery_api_key}」)。還有「{…}」時標頭不遮起來、下面說要換成什麼(金鑰的說明、網址變數可以填的值),換好之前「新增」按不下去。
- 手機:設定 › 整合 ›「從公用市集加入」,打關鍵字,大腦去搜(手機頁面只能連自己的伺服器);點一個,要金鑰的問金鑰、網址有變數的問變數,再請大腦加上。只有擁有者能用。
- 要登入帳號(OAuth)的連接器 AnyBot 還不支援:連線時伺服器回 401(或要求登入的 403)、又沒填金鑰,狀態會說「這個連接器要先登入帳號(OAuth),AnyBot 還不支援」;有填金鑰的話說金鑰不對或過期了。
- mcpservers.org 這類網站是給人看的頁面,有瀏覽器檢查、沒有給程式讀的清單,所以用官方 Registry。
- 驗證過的:搜「notion」拿到 6 個;實際連上 AWS Knowledge(不用金鑰,5 個工具);Notion 官方(OAuth)顯示上面那句話。測試是 `cargo test -- --ignored registry_search_live`。
- github 要你的 Token,沒有測。
### 專屬號碼、打電話、X(設定 › 訊息管道)

View File

@ -1876,7 +1876,7 @@ function drawSettings(kind, quiet) {
if (kind === "integrations") {
const dot = (ok, on) => `<span style="width:8px;height:8px;border-radius:50%;flex:none;background:${!on ? "var(--text4)" : ok ? "var(--ok)" : "var(--warn)"}"></span>`;
h += group("訊息管道", (st.channels || []).map((c) => `<div class="item">${dot(c.ok, c.enabled)}<div class="mid"><div class="k">${esc(c.kind)} · ${esc(c.name)}</div><div class="v">由「${esc(c.bot)}」回覆${c.note ? " · " + esc(c.note) : ""}</div></div>${isOwner() ? `<label class="sw"><input type="checkbox" ${c.enabled ? "checked" : ""} data-ch="${c.id}"><i></i></label><button class="ib" data-chrm="${c.id}" title="移除">${ic("trash", 16)}</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有。Telegram、Slack、Discord… 要在電腦上的 AnyBot 新增(需要輸入 Token)。</div>`);
h += group("連接器(MCP)", (st.mcp || []).map((m) => `<div class="item">${dot(m.tools != null, m.enabled)}<div class="mid"><div class="k">${esc(m.name)}</div><div class="v">${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}</div></div>${isOwner() ? `<label class="sw"><input type="checkbox" ${m.enabled ? "checked" : ""} data-mcp="${esc(m.name)}"><i></i></label><button class="ib" data-mcprm="${esc(m.name)}" title="移除">${ic("trash", 16)}</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有連接器</div>`);
h += group("連接器(MCP)", ((st.mcp || []).map((m) => `<div class="item">${dot(m.tools != null, m.enabled)}<div class="mid"><div class="k">${esc(m.name)}</div><div class="v">${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}</div></div>${isOwner() ? `<label class="sw"><input type="checkbox" ${m.enabled ? "checked" : ""} data-mcp="${esc(m.name)}"><i></i></label><button class="ib" data-mcprm="${esc(m.name)}" title="移除">${ic("trash", 16)}</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有連接器</div>`) + (isOwner() ? item({icon: "plus", k: "從公用市集加入", v: "搜尋官方 MCP Registry 裡用網址連的連接器", tap: 1, data: 'data-mcpmarket="1"'}) : ""));
const skRows = (st.skills || []).map((k, i) => {
const tags = [...(k.resources && k.resources.length ? [`${k.resources.length} 檔`] : []), ...(k.steps ? [`可重播 ${k.steps} 步`] : [])].join(" · ");
return `<div class="item"><div class="mid" data-skill="${i}" style="cursor:pointer"><div class="k">${esc(k.name)}${tags ? ` <span class="pill" style="margin-left:4px">${esc(tags)}</span>` : ""}</div><div class="v">${esc(k.description)}</div></div>${isOwner() ? `<label class="sw"><input type="checkbox" ${k.enabled !== false ? "checked" : ""} data-sksw="${esc(k.name)}"><i></i></label>` : ""}</div>`;
@ -2012,6 +2012,38 @@ function wireSettings(kind, st) {
if (await confirmSheet(`登出「${d.name}」?`, "那支手機要重新輸入密碼才能再連。如果是你現在用的這支,也會被登出。", "登出") && await act("device_remove", {name: d.name, created: d.created}, "已登出那支手機")) again();
});
on("[data-sksw]", "onchange", async (x) => { if (!await act("skill", {name: x.dataset.sksw, enabled: x.checked})) x.checked = !x.checked; else again(); });
// 公用市集: the brain searches the official MCP Registry; a pick asks for what it needs (the
// key, an address part) and the brain adds it.
on("[data-mcpmarket]", "onclick", async () => {
const q = await ask("搜尋公用市集", "", "例如 notion、search、docs");
if (!q) return;
toast("搜尋中…");
let found;
try { found = (await api(base() + "api/mcp/registry?q=" + encodeURIComponent(q))).servers || []; } catch (e) { toast(e.message); return; }
if (!found.length) { toast("沒有找到,換個關鍵字試試(英文的比較多)"); return; }
const have = new Set((st.mcp || []).map((m) => m.what));
sheet(`公用市集:${q}`, found.map((e) => ({
icon: "plug",
label: e.title + (e.description ? " — " + e.description : ""),
x: e.note ? "還不支援" : have.has(e.url) ? "已加入" : e.header ? "要金鑰" : "",
on: async () => {
if (e.note) { toast(e.note); return; }
if (have.has(e.url)) { toast("已經加入過了"); return; }
let url = e.url, header = "";
for (const v of e.variables || []) {
const val = await ask(`網址裡的 ${v.name}`, (v.choices || [])[0] || "", v.description || "");
if (!val) return;
url = url.split("{" + v.name + "}").join(val);
}
if (e.header) {
const key = await ask(`${e.title} 的金鑰`, "", e.header.description || e.header.value);
if (!key) return;
header = `${e.header.name}: ${e.header.value.replace(/\{[^}]*\}/, key)}`;
}
if (await act("mcp", {add: {name: e.title, url, header}})) again();
},
})), `<div class="note" style="text-align:center">官方 MCP Registry 裡用網址連的連接器。要登入帳號(OAuth)的 AnyBot 還不支援,加入後連線時會說。</div>`);
});
on("[data-skillmarket]", "onclick", () => {
const installed = new Set((st.skills || []).map((s) => s.name));
const list = (st.skill_market || []).map((m) => ({

View File

@ -560,6 +560,10 @@ impl App {
Ok("channels") => {
app.show_settings = true;
app.settings_tab = SettingsTab::Channels;
// ANYBOT_SHOT_MCP=notion: the 公用市集 as that search leaves it.
if let Ok(q) = std::env::var("ANYBOT_SHOT_MCP") {
app.shot_registry(&q);
}
app.state.channels.push(crate::channels::Channel { id: 1, kind: crate::channels::Kind::Slack, name: "客服群".into(), bot_id: 2, token: "xoxb-demo".into(), target: "C0123ABCD".into(), enabled: true, client_id: String::new(), tenant: String::new() });
}
Ok("group") => {

View File

@ -31,6 +31,14 @@ pub struct ChannelUi {
pub(super) mcp_errors: Arc<Mutex<Vec<(String, String)>>>,
mcp_busy: Arc<AtomicBool>,
new_mcp: (String, String, String, String),
/// What the form needs from the person, for a server picked from the 公用市集.
new_mcp_hint: String,
/// The form was just filled from the market: scroll it into view.
focus_form: bool,
/// 公用市集 (the official MCP Registry): what is typed, a search on its way, what it found.
reg_q: String,
reg_busy: Arc<AtomicBool>,
reg_found: Arc<Mutex<Option<RegistryAnswer>>>,
/// 連接器市集 was asked for (scroll it into view once).
pub focus_market: bool,
skill_src: String,
@ -46,7 +54,7 @@ impl Default for ChannelUi {
fn default() -> Self {
let (tx, rx) = channel();
let (trig_tx, trig_rx) = channel();
ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), new_mcp: Default::default(), focus_market: false, skill_src: String::new(), skill_open: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false }
ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), new_mcp: Default::default(), focus_market: false, skill_src: String::new(), skill_open: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false, new_mcp_hint: String::new(), focus_form: false, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() }
}
}
@ -576,7 +584,7 @@ impl App {
if std::mem::take(&mut self.ch.focus_market) {
ui.scroll_to_cursor(Some(Align::TOP));
}
setting_title(ui, "連接器市集", "常用的連接器,按「加入」就能用。需要金鑰的會填好下面的表單,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。", p);
setting_title(ui, "連接器市集", "常用的連接器,按「加入」就能用。需要金鑰的會填好下面的表單,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。下面的「公用市集」搜尋官方 MCP Registry 裡用網址連的連接器。", p);
for (name, desc, cmd, needs) in crate::mcp::MARKET {
let added = self.state.mcp_servers.iter().any(|s| s.name == name);
listing_row(
@ -598,8 +606,12 @@ impl App {
},
);
}
self.registry_market(ui, ctx);
});
setting_card(ui, p, |ui| {
if std::mem::take(&mut self.ch.focus_form) {
ui.scroll_to_cursor(Some(Align::TOP));
}
setting_title(ui, "新增連接器", "", p);
let (name, cmd, env, headers) = &mut self.ch.new_mcp;
form_row(ui, "名稱", p, |ui| {
@ -612,9 +624,19 @@ impl App {
ui.add(egui::TextEdit::singleline(env).hint_text(t("GITHUB_TOKEN=…(多個用空白分開,本機伺服器用)")).password(true).desired_width(ui.available_width()));
});
form_row(ui, "標頭", p, |ui| {
ui.add(egui::TextEdit::singleline(headers).hint_text(t("Authorization: Bearer …(遠端伺服器用)")).password(true).desired_width(ui.available_width()));
// Shown as typed while a 「{…}」 is still to be replaced; hidden once it's a key.
let hide = !headers.contains('{');
ui.add(egui::TextEdit::singleline(headers).hint_text(t("Authorization: Bearer …(遠端伺服器用)")).password(hide).desired_width(ui.available_width()));
});
let ok = !name.trim().is_empty() && !cmd.trim().is_empty() && !self.state.mcp_servers.iter().any(|s| s.name == name.trim());
if !self.ch.new_mcp_hint.is_empty() {
ui.label(RichText::new(&self.ch.new_mcp_hint).size(FONT_XS).color(p.text2));
}
// A 「{…}」 left in the address or the header can only fail.
let unfilled = cmd.contains('{') || headers.contains('{');
if unfilled {
ui.label(RichText::new(t("還有「{…}」沒換成你的值")).size(FONT_XS).color(p.danger));
}
let ok = !unfilled && !name.trim().is_empty() && !cmd.trim().is_empty() && !self.state.mcp_servers.iter().any(|s| s.name == name.trim());
if ui.add_enabled(ok, primary_button("新增", p)).clicked() {
let c = cmd.trim().to_string();
let is_url = c.starts_with("http://") || c.starts_with("https://");
@ -632,6 +654,7 @@ impl App {
instructions: String::new(),
});
self.ch.new_mcp = Default::default();
self.ch.new_mcp_hint.clear();
}
});
let _ = ctx;
@ -642,6 +665,85 @@ impl App {
}
impl App {
/// 公用市集: search the official MCP Registry (in the background) and list what it has that
/// is reached by address; 加入 fills 新增連接器 with the address and the header to complete.
fn registry_market(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
let p = self.pal;
ui.add_space(8.0);
field_label(ui, "公用市集(官方 MCP Registry)", p);
let busy = self.ch.reg_busy.load(Ordering::SeqCst);
let mut go = false;
ui.horizontal(|ui| {
let w = (ui.available_width() - 72.0 - 8.0).max(120.0);
let resp = ui.add(egui::TextEdit::singleline(&mut self.ch.reg_q).hint_text(t("搜尋用網址連的連接器,例如 notion、search、docs")).desired_width(w));
let can = !busy && !self.ch.reg_q.trim().is_empty();
let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
go = ui.add_enabled(can, primary_button("搜尋", p)).clicked() || (can && enter);
});
if go {
self.ch.reg_busy.store(true, Ordering::SeqCst);
let (q, busy, found, ctx) = (self.ch.reg_q.clone(), self.ch.reg_busy.clone(), self.ch.reg_found.clone(), ctx.clone());
std::thread::spawn(move || {
*found.lock().unwrap() = Some(crate::mcp::registry_search(&q));
busy.store(false, Ordering::SeqCst);
ctx.request_repaint();
});
}
if busy {
ui.label(RichText::new(t("搜尋中…")).size(FONT_XS).color(p.text3));
return;
}
let found = self.ch.reg_found.lock().unwrap().clone();
let list = match found {
None => return,
Some(Err(e)) => {
ui.label(RichText::new(e).size(FONT_XS).color(p.danger));
return;
}
Some(Ok(list)) if list.is_empty() => {
ui.label(RichText::new(t("沒有找到。換個關鍵字試試(英文的比較多)。")).size(FONT_XS).color(p.text3));
return;
}
Some(Ok(list)) => list,
};
let mut pick = None;
for (i, e) in list.iter().enumerate() {
let (title, about, url, note) = (e["title"].as_str().unwrap_or(""), e["description"].as_str().unwrap_or(""), e["url"].as_str().unwrap_or(""), e["note"].as_str().unwrap_or(""));
let added = self.state.mcp_servers.iter().any(|s| s.url == url);
listing_row(
ui,
|ui| {
if !note.is_empty() {
ui.label(RichText::new(t(note)).size(11.5).color(p.text3));
} else if added {
ui.label(RichText::new(t("已加入")).size(12.0).color(p.text3));
} else if ui.add(secondary_button("加入")).clicked() {
pick = Some(i);
}
},
|ui| {
ui.label(RichText::new(title).strong().size(FONT_SM));
if e["header"].is_object() {
ui.label(RichText::new(t("要金鑰")).size(11.0).color(p.accent));
}
ui.add(egui::Label::new(RichText::new(about).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(format!("{about}\n{url}"));
},
);
}
if let Some(e) = pick.and_then(|i| list.get(i)) {
let (name, url, header, hint) = crate::mcp::registry_form(e, &self.state.mcp_servers);
self.ch.new_mcp = (name, url, String::new(), header);
self.ch.new_mcp_hint = hint;
self.ch.focus_form = true;
}
}
/// Screenshot mode: the 公用市集 with this search done.
pub(super) fn shot_registry(&mut self, q: &str) {
self.ch.reg_q = q.to_string();
*self.ch.reg_found.lock().unwrap() = Some(crate::mcp::registry_search(q));
}
/// Install a skill from an address or a folder. On a screen the brain does it — it fetches
/// an address itself, and a folder on this computer goes up whole — since the bots read skills
/// from the brain's disk. Otherwise it is fetched in the background and the list reloads.
@ -682,6 +784,9 @@ fn skill_status(ui: &mut egui::Ui, ch: &ChannelUi, busy: bool, p: Palette) {
}
}
/// What a 公用市集 search found (rows as `mcp::registry_entries` gives them), or why it failed.
type RegistryAnswer = Result<Vec<serde_json::Value>, String>;
/// One line of a list: its buttons on the right (`buttons` adds them rightmost first), and the
/// words on the left in the room that is left — a long description ends in … before the
/// buttons instead of running under them.

View File

@ -1259,6 +1259,21 @@ impl App {
if !owner {
return owner_only();
}
// From the phone's 公用市集: a server reached by address, with its key filled in.
if b["add"].is_object() {
let a = &b["add"];
let (url, header) = (a["url"].as_str().unwrap_or("").trim(), a["header"].as_str().unwrap_or("").trim());
if !(url.starts_with("https://") || url.starts_with("http://")) {
return fail("連接器要有網址");
}
if url.contains('{') || header.contains('{') {
return fail("還有「{…}」沒換成你的值");
}
let name = crate::mcp::free_name(a["name"].as_str().filter(|n| !n.trim().is_empty()).unwrap_or("連接器"), &self.state.mcp_servers);
self.state.mcp_servers.push(crate::mcp::remote_server(&name, url, header));
self.dirty = true;
return done(&format!("已加入連接器「{name}」"));
}
let name = s("name");
if !self.state.mcp_servers.iter().any(|m| m.name == name) {
return fail("找不到這個連接器");
@ -1593,6 +1608,24 @@ mod phone_act_tests {
assert!(app.phone_act(&ctx, "skill", &json!({"builtin": "pdf"}), "admin")["error"].is_string());
}
/// The phone's 公用市集 adds a server reached by address, with its key; never one with a
/// 「{…}」 left in it, never twice under one name, only the owner.
#[test]
fn the_phone_adds_a_connector_from_the_public_market() {
let (ctx, mut app) = demo();
let add = |name: &str, url: &str, header: &str| json!({"add": {"name": name, "url": url, "header": header}});
let r = app.phone_act(&ctx, "mcp", &add("Smithery", "https://server.smithery.ai/x/mcp", "Authorization: Bearer sk-1"), "owner");
assert_eq!(r["ok"], true, "{r}");
let m = app.state.mcp_servers.iter().find(|m| m.name == "Smithery").expect("added");
assert_eq!((m.url.as_str(), m.headers.get("Authorization").map(String::as_str), m.enabled), ("https://server.smithery.ai/x/mcp", Some("Bearer sk-1"), true));
assert_eq!(app.phone_act(&ctx, "mcp", &add("Smithery", "https://y.example/mcp", ""), "owner")["ok"], true);
assert!(app.state.mcp_servers.iter().any(|m| m.name == "Smithery 2"));
assert!(app.phone_act(&ctx, "mcp", &add("x", "https://y.example/mcp", "Authorization: Bearer {key}"), "owner")["error"].is_string());
assert!(app.phone_act(&ctx, "mcp", &add("x", "https://{host}/mcp", ""), "owner")["error"].is_string());
assert!(app.phone_act(&ctx, "mcp", &add("x", "npx -y evil", ""), "owner")["error"].is_string());
assert!(app.phone_act(&ctx, "mcp", &add("x", "https://y.example/mcp", ""), "admin")["error"].is_string());
}
#[test]
fn the_phone_never_gets_keys_or_secrets() {
let (ctx, mut app) = demo();

View File

@ -126,6 +126,20 @@ fn wait_id(rx: &Receiver<Value>, id: u64, secs: u64) -> Result<Value, String> {
}
}
/// What an HTTP server's refusal means to the person. A 401 (or a 403 that asks for a login)
/// with no key given is a server that signs people in with OAuth, which AnyBot can't do yet;
/// with a key, the key is wrong or old.
pub fn http_refusal(status: u16, asks_login: bool, has_key: bool, body: &str) -> String {
if status == 401 || (status == 403 && asks_login) {
return if has_key {
format!("金鑰不對或過期了(HTTP {status}):檢查「標頭」裡的金鑰")
} else {
"這個連接器要先登入帳號(OAuth),AnyBot 還不支援;它若也收 API 金鑰,填在「標頭」(例如 Authorization: Bearer …)".into()
};
}
format!("MCP 伺服器回 HTTP {status}:{}", body.chars().take(200).collect::<String>())
}
/// Answers from Streamable HTTP: plain JSON, or SSE with `data:` lines.
pub fn parse_http_answer(body: &str, id: u64) -> Result<Value, String> {
let candidates: Vec<Value> = if body.trim_start().starts_with('{') || body.trim_start().starts_with('[') {
@ -172,9 +186,10 @@ impl Live {
*session = Some(s.to_string());
}
let st = resp.status().as_u16();
let asks_login = resp.headers().contains_key("www-authenticate");
let body = resp.body_mut().read_to_string().unwrap_or_default();
if !(200..300).contains(&st) {
return Err(format!("MCP 伺服器回 HTTP {st}:{}", body.chars().take(200).collect::<String>()));
return Err(http_refusal(st, asks_login, !headers.is_empty(), &body));
}
parse_http_answer(&body, id)
}
@ -371,6 +386,113 @@ pub const MARKET: [(&str, &str, &str, &str); 8] = [
("github", "GitHub 的 Issue、PR、程式碼(官方遠端伺服器)", "https://api.githubcopilot.com/mcp/", "Authorization: Bearer 你的 GitHub Token"),
];
// ---------- 公用市集: the official MCP Registry ----------
/// The official MCP Registry: public and searchable, and for each server reached by address it
/// gives the address and the header (a key) it wants. (mcpservers.org and the like are pages
/// for people, behind a browser check, with no list a program may read.)
pub const REGISTRY: &str = "https://registry.modelcontextprotocol.io/v0.1/servers";
/// Results per search.
const REGISTRY_LIMIT: usize = 40;
/// Search the registry: servers reached by address, as [`registry_entries`] gives them.
pub fn registry_search(q: &str) -> Result<Vec<Value>, String> {
let url = format!("{REGISTRY}?version=latest&limit={REGISTRY_LIMIT}&search={}", crate::httpd::url_encode(q.trim()));
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(20))).http_status_as_error(false).build().into();
let mut resp = agent.get(&url).header("Accept", "application/json").call().map_err(|e| format!("連不到公用市集:{e}"))?;
let st = resp.status().as_u16();
let body = resp.body_mut().read_to_string().unwrap_or_default();
if !(200..300).contains(&st) {
return Err(format!("公用市集回 HTTP {st}"));
}
let v: Value = serde_json::from_str(&body).map_err(|_| "公用市集的回答看不懂".to_string())?;
Ok(registry_entries(&v))
}
/// The registry's answer as the market lists it: one row per server reached by address (a
/// package would have to run on the brain, which may have no Node or uv), none taken down. Each:
/// {id, title, description, url, header: {name, value, description} | null, variables:
/// [{name, description, choices}], note} — `note` says why it can't be added yet.
pub fn registry_entries(v: &Value) -> Vec<Value> {
let mut out: Vec<Value> = vec![];
for item in v["servers"].as_array().into_iter().flatten() {
let s = &item["server"];
if item["_meta"]["io.modelcontextprotocol.registry/official"]["status"].as_str().is_some_and(|st| st != "active") {
continue;
}
let remotes = s["remotes"].as_array().map(Vec::as_slice).unwrap_or_default();
let Some(r) = remotes.iter().find(|r| r["type"] == "streamable-http").or_else(|| remotes.first()) else { continue };
let id = s["name"].as_str().unwrap_or("");
let url = r["url"].as_str().unwrap_or("");
if id.is_empty() || url.is_empty() || out.iter().any(|o| o["id"] == id) {
continue;
}
let title = s["title"].as_str().map(str::trim).filter(|t| !t.is_empty()).map(String::from).unwrap_or_else(|| short_name(id));
// The key goes where the registry shows its placeholder ("Bearer {api_key}").
let header = r["headers"].as_array().and_then(|h| h.first()).map(|h| {
let value = h["value"].as_str().filter(|v| !v.trim().is_empty()).unwrap_or("{金鑰}");
json!({"name": h["name"].as_str().unwrap_or(""), "value": value, "description": h["description"].as_str().unwrap_or("")})
});
let variables: Vec<Value> = r["variables"].as_object().map(|o| o.iter().map(|(k, x)| json!({"name": k, "description": x["description"].as_str().unwrap_or(""), "choices": x["choices"].as_array().cloned().unwrap_or_default()})).collect()).unwrap_or_default();
let note = if r["type"] == "streamable-http" { "" } else { "舊式 SSE 連線,AnyBot 還不支援" };
out.push(json!({"id": id, "title": title, "description": s["description"].as_str().unwrap_or(""), "url": url, "header": header, "variables": variables, "note": note}));
}
out
}
/// A registry name ("ai.smithery/smithery-notion", "com.notion/mcp") as a person would call it:
/// its last part, or — when that only says "mcp" — whose it is.
fn short_name(id: &str) -> String {
let (owner, last) = id.rsplit_once('/').unwrap_or(("", id));
let plain = matches!(last.to_ascii_lowercase().as_str(), "mcp" | "server" | "mcp-server" | "remote" | "remote-mcp" | "api");
if plain && !owner.is_empty() {
return owner.rsplit('.').next().unwrap_or(owner).to_string();
}
last.to_string()
}
/// A name not taken yet: 「Notion」, then 「Notion 2」…
pub fn free_name(want: &str, servers: &[Server]) -> String {
let want = want.trim();
let taken = |n: &str| servers.iter().any(|s| s.name == n);
if !taken(want) {
return want.to_string();
}
(2..).map(|i| format!("{want} {i}")).find(|n| !taken(n)).unwrap_or_default()
}
/// A 公用市集 row as the 新增連接器 form: (name not taken yet, address, header line, what the
/// person still has to fill in).
pub fn registry_form(e: &Value, servers: &[Server]) -> (String, String, String, String) {
let name = free_name(e["title"].as_str().unwrap_or("連接器"), servers);
let url = e["url"].as_str().unwrap_or("").to_string();
let mut hint = vec![];
let header = match e["header"].as_object() {
Some(h) => {
let about = h.get("description").and_then(Value::as_str).unwrap_or("").trim();
hint.push(if about.is_empty() { "把標頭裡的「{…}」換成你的金鑰。".to_string() } else { format!("把標頭裡的「{{…}}」換成你的金鑰({about})。") });
format!("{}: {}", h.get("name").and_then(Value::as_str).unwrap_or(""), h.get("value").and_then(Value::as_str).unwrap_or(""))
}
None => String::new(),
};
for v in e["variables"].as_array().into_iter().flatten() {
let choices: Vec<&str> = v["choices"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let mut line = format!("把網址裡的「{{{}}}」換成{}", v["name"].as_str().unwrap_or(""), v["description"].as_str().map(|d| format!(":{d}")).unwrap_or_default());
if !choices.is_empty() {
line.push_str(&format!("(可填 {})", choices.join("、")));
}
hint.push(line);
}
hint.push("按「新增」就會連線;要登入帳號(OAuth)的連接器 AnyBot 還不支援,連線時會說。".into());
(name, url, header, hint.join(" "))
}
/// A server reached by address, with its one header ("Authorization: Bearer …") if any.
pub fn remote_server(name: &str, url: &str, header: &str) -> Server {
let headers = header.split_once(':').map(|(k, v)| (k.trim().to_string(), v.trim().to_string())).filter(|(k, _)| !k.is_empty()).into_iter().collect();
Server { name: name.trim().to_string(), command: String::new(), args: vec![], env: BTreeMap::new(), url: url.trim().to_string(), headers, enabled: true, instructions: String::new() }
}
/// A marketplace entry as a server (home folder spelled out).
pub fn market_server(name: &str, cmd: &str) -> Server {
let parts: Vec<String> = cmd.split_whitespace().map(|w| if w == "~/Documents" { crate::tools::expand_home(w).display().to_string() } else { w.to_string() }).collect();
@ -421,6 +543,76 @@ for line in sys.stdin:
let _ = std::fs::remove_dir_all(&dir);
}
/// The registry's answer as the 公用市集 lists it: servers reached by address (streamable
/// HTTP first), the key's placeholder kept, none taken down, packages left out, one row each.
#[test]
fn the_registry_lists_what_can_be_reached_by_address() {
let active = json!({"io.modelcontextprotocol.registry/official": {"status": "active"}});
let v = json!({"servers": [
{"server": {"name": "com.notion/mcp", "title": "Notion", "description": "Pages", "remotes": [{"type": "sse", "url": "https://mcp.notion.com/sse"}, {"type": "streamable-http", "url": "https://mcp.notion.com/mcp"}]}, "_meta": active},
{"server": {"name": "ai.smithery/smithery-notion", "description": "Via Smithery", "remotes": [{"type": "streamable-http", "url": "https://server.smithery.ai/@smithery/notion/mcp", "headers": [{"name": "Authorization", "value": "Bearer {smithery_api_key}", "description": "Smithery key", "isRequired": true}]}]}, "_meta": active},
{"server": {"name": "com.example/raw-key", "remotes": [{"type": "streamable-http", "url": "https://x.example/mcp", "headers": [{"name": "X-API-Key", "description": "Your key"}]}]}},
{"server": {"name": "ai.autorfp/mcp", "title": "AutoRFP", "remotes": [{"type": "streamable-http", "url": "https://{api_host}/mcp", "variables": {"api_host": {"description": "Region host", "choices": ["api.autorfp.ai", "api.eu.autorfp.ai"]}}}]}},
{"server": {"name": "io.old/sse-only", "remotes": [{"type": "sse", "url": "https://old.example/sse"}]}},
{"server": {"name": "com.gone/mcp", "remotes": [{"type": "streamable-http", "url": "https://gone.example/mcp"}]}, "_meta": {"io.modelcontextprotocol.registry/official": {"status": "deprecated"}}},
{"server": {"name": "com.pkg/only", "packages": [{"registryType": "npm", "identifier": "x"}]}},
{"server": {"name": "com.notion/mcp", "title": "Notion again", "remotes": [{"type": "streamable-http", "url": "https://mcp.notion.com/mcp"}]}},
]});
let e = registry_entries(&v);
let ids: Vec<&str> = e.iter().map(|x| x["id"].as_str().unwrap()).collect();
assert_eq!(ids, ["com.notion/mcp", "ai.smithery/smithery-notion", "com.example/raw-key", "ai.autorfp/mcp", "io.old/sse-only"]);
assert_eq!((e[0]["title"].as_str(), e[0]["url"].as_str(), e[0]["note"].as_str()), (Some("Notion"), Some("https://mcp.notion.com/mcp"), Some("")));
assert_eq!(e[1]["title"], "smithery-notion", "no title: the last part of its name");
assert_eq!((short_name("com.notion/mcp"), short_name("io.github.someone/remote-mcp"), short_name("x")), ("notion".into(), "someone".into(), "x".into()));
assert_eq!(e[1]["header"]["value"], "Bearer {smithery_api_key}");
assert_eq!(e[2]["header"]["value"], "{金鑰}", "a header with no shape still asks for the key");
assert!(!e[4]["note"].as_str().unwrap().is_empty(), "old SSE can't be added yet");
// 加入 fills the form: a free name, the header to complete, and what to do about it.
let have = vec![remote_server("Notion", "https://other.example/mcp", "")];
let (name, url, header, hint) = registry_form(&e[0], &have);
assert_eq!((name.as_str(), url.as_str(), header.as_str()), ("Notion 2", "https://mcp.notion.com/mcp", ""));
assert!(hint.contains("OAuth"));
let (_, _, header, hint) = registry_form(&e[1], &have);
assert_eq!(header, "Authorization: Bearer {smithery_api_key}");
assert!(hint.contains("Smithery key"));
let (_, url, _, hint) = registry_form(&e[3], &have);
assert_eq!(url, "https://{api_host}/mcp");
assert!(hint.contains("{api_host}") && hint.contains("api.eu.autorfp.ai"), "{hint}");
let s = remote_server("Smithery", "https://server.smithery.ai/x", "Authorization: Bearer sk-1");
assert_eq!(s.headers.get("Authorization").map(String::as_str), Some("Bearer sk-1"));
assert!(remote_server("x", "https://x", "").headers.is_empty());
}
/// A 401 says what to do: no key given means the server signs people in (OAuth, not yet
/// here); with a key, the key is wrong. Anything else reads as before.
#[test]
fn a_refusal_says_what_to_do() {
assert!(http_refusal(401, true, false, "").contains("OAuth"));
assert!(http_refusal(403, true, false, "").contains("OAuth"));
assert!(http_refusal(401, false, true, "").contains("金鑰不對"));
assert!(http_refusal(403, false, false, "forbidden").contains("HTTP 403:forbidden"));
assert!(http_refusal(500, true, false, "boom").contains("HTTP 500"));
}
/// Run by hand (it goes out to the internet): `cargo test registry_search_live -- --ignored`.
#[test]
#[ignore]
fn registry_search_live() {
let e = registry_search("notion").unwrap();
assert!(!e.is_empty());
assert!(e.iter().all(|x| x["url"].as_str().unwrap().starts_with("http")));
eprintln!("{} found; first: {} {}", e.len(), e[0]["title"], e[0]["url"]);
// An open server connects and lists its tools; one that signs people in says so.
let open = remote_server("aws-knowledge", "https://knowledge-mcp.global.api.aws", "");
let oauth = remote_server("notion", "https://mcp.notion.com/mcp", "");
let errs = sync(&[open, oauth]);
eprintln!("tools: {:?}\nerrors: {errs:?}", tools().iter().map(|t| format!("{}·{}", t.server, t.name)).collect::<Vec<_>>());
assert!(tools().iter().any(|t| t.server == "aws-knowledge"));
assert!(errs.iter().any(|(n, e)| n == "notion" && e.contains("OAuth")), "{errs:?}");
sync(&[]);
}
#[test]
fn http_answers_json_or_sse() {
assert_eq!(parse_http_answer(r#"{"jsonrpc":"2.0","id":3,"result":{"ok":1}}"#, 3).unwrap()["ok"], 1);

View File

@ -542,6 +542,17 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
Resp::json(&json!({"ok": true}))
}
// 語音: the phone's and the screens' recordings become text here, and answers sound.
// 公用市集 for the phone: the official MCP Registry, searched here (the phone's page may
// only talk to its own server). Answered on this thread, not the app's.
("GET", ["api", "mcp", "registry"]) => {
if role != "owner" {
return Resp::error(403, "連接器只有擁有者能加");
}
match crate::mcp::registry_search(req.query.get("q").map(String::as_str).unwrap_or("")) {
Ok(list) => Resp::json(&json!({"ok": true, "servers": list})),
Err(e) => Resp::error(502, &e),
}
}
("POST", ["api", "voice", "transcribe"] | ["api", "sync", "voice", "transcribe"]) => voice_transcribe(&req),
("POST", ["api", "voice", "speech"] | ["api", "sync", "voice", "speech"]) => voice_speech(&req),
("POST", ["api", "sync", "voice", "voices"]) => match hub().voice().speak.map(|e| crate::speech::voices(&e)) {