MCP: a server's text is cleaned and redacted; names that collide; the menu's manners

One function (mcp/clean.ts) takes control characters out of everything a
server supplies, where it enters and where a name is shown. /mcp's text
shows an address without credentials or query, a local server by its
program's name, an error by its first line with secrets out, never stderr;
as a markdown reply, names are code and descriptions escaped. A prompt is
listed and inserted under its registered name. Both of two colliding tool
names get a hash; a library server's tools other than the one it is there
for are ordinary MCP tools. In the menu: sign-out asks once, a failure is
said once, a failed save is said, a server the user's own config switches
off is switched on for the session only (and says why).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-12 19:02:08 +00:00
1 parent 9d6c316794
commit db7e7f05ff
6 files changed
+347 -60

No files matched your search

+65
View File
@@ -0,0 +1,65 @@
// What a server says is somebody else's text. Before any of it is drawn on a terminal or printed —
// a tool's or a prompt's name and description, an error, what a local server wrote to stderr —
// it goes through here: control characters out (an escape sequence in a description must not
// move the cursor, set the title or the clipboard), and, where it leaves this machine or is
// printed into a reply, what looks like a secret out too.
/** Text with every control character gone: escape sequences (CSI, OSC, the rest), the other C0
* and C1 characters, DEL. `lines`: newlines are kept (a description, an error in full); else the
* text becomes one line. A tab is a space. */
export function clean(text: unknown, lines = false): string {
const s = typeof text === "string" ? text : text === undefined || text === null ? "" : String(text)
const out = s
.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g, "") // OSC … BEL | ST
.replace(/\x1b[P^_X][^\x1b]*(?:\x1b\\)?/g, "") // DCS, PM, APC, SOS … ST
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "") // CSI
.replace(/\x1b[\s\S]?/g, "") // any other escape
.replace(/\u009b[0-?]*[ -/]*[@-~]/g, "") // 8-bit CSI
.replace(/\r\n?/g, "\n")
.replace(/\t/g, " ")
// eslint-disable-next-line no-control-regex
.replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "")
return lines ? out : out.replace(/\s*\n\s*/g, " ").trim()
}
/** An address without what may be secret in it: no user or password, no query, no fragment. Not
* an address: the text, cleaned. */
export function redactUrl(url: string): string {
try {
const u = new URL(url)
return `${u.protocol}//${u.host}${u.pathname}${u.search ? "?…" : ""}`
} catch {
return clean(url)
}
}
/** Text with what looks like a secret taken out: credentials and queries in addresses, a value
* after `token`, `key`, `secret`, `password`, `authorization` or `bearer`, and long runs of
* letters and digits that have both (keys, hashes). */
export function redactSecrets(text: string): string {
return text
.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, "$1")
.replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^\s?#"')]+)\?[^\s"')]*/gi, "$1?…")
.replace(/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [redacted]")
.replace(/\b((?:api[_-]?)?(?:token|key|secret|password|passwd|authorization|auth|cookie)\b["']?\s*[=:]\s*["']?)[^\s"',;&]+/gi, "$1[redacted]")
.replace(/\b(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{32,}\b/g, "[redacted]")
}
/** Text with the credentials and queries of the addresses in it taken out — what is shown of an
* error on this machine, where the rest of it is the person's own to read. */
export function redactUrls(text: string): string {
return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, "$1").replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^\s?#"')]+)\?[^\s"')]*/gi, "$1?…")
}
/** An error as it may leave this machine or be printed into a reply: its first line, cleaned,
* secrets out, not longer than a line should be. */
export function errorLine(error: string | undefined, max = 200): string {
const line = redactSecrets(clean((error ?? "").split("\n")[0]))
return line.length > max ? `${line.slice(0, max - 1)}…` : line
}
/** Text for a markdown reply, so that nothing in it is markup: a server's description cannot put
* a link or an image into the chat. */
export function mdEscape(text: string): string {
return text.replace(/[\\`*_{}[\]()<>#+!|~]/g, "\\$&").replace(/^(\s*)([-+]|\d+[.)])(\s)/gm, "$1\\$2$3")
}
+41 -12
View File
@@ -17,6 +17,7 @@ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"
import { ToolListChangedNotificationSchema, PromptListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"
import { clean } from "./clean.ts"
import type { McpServer } from "../config/schema.ts"
import { expandHome } from "../config/paths.ts"
import { scanThreats } from "../memory/threats.ts"
@@ -79,6 +80,12 @@ const sanitize = (s: string) => s.replace(/[^A-Za-z0-9_-]/g, "_")
* `memory` tool keeps its name and stands in for this machine's; notes, knowledge and skills stay
* this machine's (spec 3.0.0). */
export const LIBRARY_SERVER = "lembas-library"
/** A server's prompt as the command it is registered as: `<server>:<prompt>`, both spelled with
* letters, digits, `_` and `-` only. */
export function promptCommand(server: string, prompt: string): string {
return `${sanitize(server)}:${sanitize(prompt)}`
}
/** mcp__<server>__<tool>, at most 64 characters (the providers' limit); longer ones keep a hash. */
export function toolName(server: string, tool: string): string {
const full = `mcp__${sanitize(server)}__${sanitize(tool)}`
@@ -149,13 +156,14 @@ export class McpManager {
/** The name a server's tool goes by among this program's tools — its permission key too. */
nameOf(server: string, tool: string): string {
return this.names.get(`${server}\u0000${tool}`) ?? (server === LIBRARY_SERVER ? sanitize(tool) : toolName(server, tool))
return this.names.get(`${server}\u0000${tool}`) ?? toolName(server, tool)
}
private listeners: (() => void)[] = []
/** Called whenever a server's status, tools or prompts change. */
onChange(f: () => void) {
onChange(f: () => void): () => void {
this.listeners.push(f)
return () => void (this.listeners = this.listeners.filter((x) => x !== f))
}
private changed() {
@@ -202,7 +210,8 @@ export class McpManager {
await close()
}
t.stderr?.on("data", (chunk: Buffer) => {
s.stderr.push(...chunk.toString().split("\n").filter(Boolean))
// Somebody else's text from here on (mcp/clean.ts): no control characters are kept.
s.stderr.push(...chunk.toString().split("\n").map((l) => clean(l)).filter(Boolean))
if (s.stderr.length > 20) s.stderr.splice(0, s.stderr.length - 20)
})
return t
@@ -294,7 +303,7 @@ export class McpManager {
private fail(s: ServerState, why: string): ServerState {
s.status = "failed"
s.error = why
s.error = clean(why, true)
this.changed()
return s
}
@@ -342,10 +351,15 @@ export class McpManager {
const r = await c.listPrompts(cursor ? { cursor } : undefined)
return { items: r.prompts as RemotePrompt[], next: r.nextCursor }
}) : []
s.tools = tools.filter((t) => toolAllowed(t.name, s.cfg.tools))
s.prompts = prompts
// Where a server's words enter: descriptions are text to be shown, so control characters go
// (clean.ts). Names stay as the server spells them — they are what it is called by — and are
// cleaned where they are shown.
s.tools = tools
.filter((t) => toolAllowed(t.name, s.cfg.tools))
.map((t) => ({ ...t, ...(t.description === undefined ? {} : { description: clean(t.description, true) }), ...(t.annotations?.title === undefined ? {} : { annotations: { ...t.annotations, title: clean(t.annotations.title) } }) }))
s.prompts = prompts.map((p) => ({ ...p, ...(p.description === undefined ? {} : { description: clean(p.description, true) }), ...(p.arguments ? { arguments: p.arguments.map((a) => ({ ...a, ...(a.description === undefined ? {} : { description: clean(a.description) }) })) } : {}) }))
s.resources = !!caps.resources && s.cfg.resources !== false
const ins = s.cfg.instructions === false ? undefined : c.getInstructions()?.trim()
const ins = s.cfg.instructions === false ? undefined : clean(c.getInstructions() ?? "", true).trim() || undefined
s.instructions = undefined
if (ins) {
// The server wrote this, not the user: anything aimed at the agent is left out.
@@ -391,19 +405,34 @@ export class McpManager {
/** Every connected server's tools as LLeMbas CLI tools, and list/read tools for resources. */
tools(): Tool[] {
const out: Tool[] = []
// Different names can come out the same (get.user and get_user; server a.b and a_b): the
// second gets a hash of what it really is, so every tool stays reachable and names stay unique.
// Different names can come out the same (get.user and get_user; server a.b and a_b). Every
// one of such a set gets a hash of what it really is — not only the second to arrive — so a
// server that lists its tools in another order cannot move a name, and with it an "always
// allow", from one tool onto another.
const bare = (s: ServerState, tool: string) => s.name === LIBRARY_SERVER && (s.cfg.tools?.include ?? []).includes(tool)
const counts = new Map<string, number>()
for (const s of this.servers.values()) {
if (s.status !== "connected") continue
for (const t of s.tools) {
const n = bare(s, t.name) ? sanitize(t.name) : toolName(s.name, t.name)
counts.set(n, (counts.get(n) ?? 0) + 1)
}
}
const used = new Set<string>()
const unique = (server: string, tool: string) => {
let n = toolName(server, tool)
if (used.has(n)) n = `${n.slice(0, 55)}_${createHash("sha256").update(`${server}\u0000${tool}`).digest("hex").slice(0, 8)}`
if ((counts.get(n) ?? 0) > 1 || used.has(n)) n = `${n.slice(0, 55)}_${createHash("sha256").update(`${server}\u0000${tool}`).digest("hex").slice(0, 8)}`
used.add(n)
return n
}
for (const s of this.servers.values()) {
if (s.status !== "connected") continue
for (const t of s.tools) {
const library = s.name === LIBRARY_SERVER
// The LLeMbas server's library stands in for this machine's memory tool, so that one tool
// (what its config includes) goes by the bare name and under the memory tool's rules;
// anything else such a server offered is an MCP tool like any other, with a name and a
// permission of its own — never a bare name a built-in tool already has.
const library = bare(s, t.name)
const name = library ? sanitize(t.name) : unique(s.name, t.name)
if (library) used.add(name)
this.names.set(`${s.name}\u0000${t.name}`, name)
@@ -478,7 +507,7 @@ export class McpManager {
prompts(): McpPromptCommand[] {
return [...this.servers.values()]
.filter((s) => s.status === "connected")
.flatMap((s) => s.prompts.map((p) => ({ name: `${sanitize(s.name)}:${sanitize(p.name)}`, description: p.description ?? `prompt from ${s.name}`, args: (p.arguments ?? []).map((a) => a.name), server: s.name, prompt: p.name })))
.flatMap((s) => s.prompts.map((p) => ({ name: promptCommand(s.name, p.name), description: p.description ?? `prompt from ${s.name}`, args: (p.arguments ?? []).map((a) => a.name), server: s.name, prompt: p.name })))
}
/** A prompt's text with the typed words as its arguments, in order (the last takes the rest). */
+38 -16
View File
@@ -3,8 +3,10 @@
// the web UI shows it as a reply). Lines of a list begin with "- ": they read as they are in a
// terminal and stay one to a line where the reply is drawn as markdown (indented lines would run
// together there). The TUI's menu (tui/mcpmenu.ts) reads the same words.
import { basename } from "node:path"
import type { McpManager, ServerState } from "./index.ts"
import { LIBRARY_SERVER } from "./index.ts"
import { LIBRARY_SERVER, promptCommand } from "./index.ts"
import { clean, errorLine, mdEscape, redactUrl } from "./clean.ts"
export const STATE_WORDS: Record<ServerState["status"], string> = {
connected: "connected",
@@ -28,43 +30,63 @@ export function offers(s: Pick<ServerState, "tools" | "prompts" | "resources">):
return [n(s.tools.length, "tool"), ...(s.prompts.length ? [n(s.prompts.length, "prompt")] : []), ...(s.resources ? ["resources"] : [])].join(", ")
}
/** One server's state in a line: `connected — 3 tools`, `failed: <why, one line>`. */
/** One server's state in a line: `connected — 3 tools`, `failed: <why, one line>`. The reason is
* somebody else's text and may carry what the config resolved to: one line, cleaned, with what
* looks like a secret taken out (clean.ts). */
export function stateLine(s: ServerState): string {
if (s.status === "connected") return `${STATE_WORDS.connected} — ${offers(s)}`
if (s.status === "failed") return `${STATE_WORDS.failed}: ${(s.error ?? "no reason given").split("\n")[0]}`
if (s.status === "needs_auth") return `${STATE_WORDS.needs_auth} — /mcp auth ${s.name}`
if (s.status === "failed") return `${STATE_WORDS.failed}: ${errorLine(s.error) || "no reason given"}`
if (s.status === "needs_auth") return `${STATE_WORDS.needs_auth} — /mcp auth ${clean(s.name)}`
return STATE_WORDS[s.status]
}
/** Where a server is reached: its address, or `local` and the program it runs. */
/** Where a server is reached, without what the config may hold that is secret: an address with
* no user, password or query; for a local server the program's name alone — its arguments and
* environment are where tokens are put. */
export function whereOf(s: Pick<ServerState, "cfg">): string {
return s.cfg.command !== undefined ? `local: ${(Array.isArray(s.cfg.command) ? s.cfg.command : [s.cfg.command]).join(" ")}` : (s.cfg.url ?? "")
if (s.cfg.command === undefined) return redactUrl(s.cfg.url ?? "")
const program = Array.isArray(s.cfg.command) ? s.cfg.command[0]! : s.cfg.command.trim().split(/\s+/)[0]!
return `local: ${clean(basename(program))}`
}
/** The servers as a plain table, or one server with its tools and prompts (`name` given). `rule`:
* what the permission rules say of a tool by its name here (allow, ask, deny), where they speak. */
export function mcpText(mcp: McpManager, name = "", rule: (tool: string) => string | undefined = () => undefined): string {
/** The servers as a plain list, or one server with its tools and prompts (`name` given) — what
* `/mcp` says where there is no menu. It may leave this machine (a reply in the web UI), so an
* error is its first line only, and never what a local server wrote to stderr. `rule`: what the
* permission rules say of a tool by its name here. `markdown`: the text will be drawn as
* markdown, so names are code and a server's descriptions are escaped — a description cannot
* put a link or an image into the chat. */
export function mcpText(mcp: McpManager, name = "", rule: (tool: string) => string | undefined = () => undefined, o: { markdown?: boolean } = {}): string {
const said = (text: string) => (o.markdown ? mdEscape(text) : text)
const code = (text: string) => (o.markdown ? `\`${text.replace(/`/g, "'")}\`` : text)
const servers = [...mcp.servers.values()]
if (!servers.length) return "No MCP servers are configured. Add one under mcp: in ~/.config/lembas/config.yaml (or this project's .agent/config.yaml)."
if (name) {
const s = mcp.servers.get(name)
if (!s) return `No MCP server "${name}" — the servers: ${servers.map((x) => x.name).join(", ")}.`
const lines = [`${s.name} — ${stateLine(s)}`, "", `From ${SOURCE_WORDS[sourceOf(s)]} · ${whereOf(s)}`]
if (s.error && s.error.includes("\n")) lines.push("", "The error in full:", "", ...s.error.split("\n").map((l) => ` ${l}`))
if (!s) return `No MCP server "${clean(name)}" — the servers: ${servers.map((x) => clean(x.name)).join(", ")}.`
const lines = [`${said(clean(s.name))} — ${said(stateLine(s))}`, "", `From ${SOURCE_WORDS[sourceOf(s)]} · ${said(whereOf(s))}`]
if (s.status === "connected") {
if (s.tools.length) lines.push("", "Tools:")
for (const t of s.tools) {
const called = mcp.nameOf(s.name, t.name)
const said = { allow: "always allowed", deny: "denied", ask: "asks" }[rule(called) ?? "ask"] ?? "asks"
lines.push(`- ${called} — ${said}${t.annotations?.readOnlyHint ? ", read-only" : ""}${t.description ? ` — ${t.description.trim().split("\n")[0]}` : ""}`)
const does = { allow: "always allowed", deny: "denied", ask: "asks" }[rule(called) ?? "ask"] ?? "asks"
const about = clean((t.description ?? "").split("\n")[0])
lines.push(`- ${code(clean(called))} — ${does}${t.annotations?.readOnlyHint ? ", read-only" : ""}${about ? ` — ${said(about)}` : ""}`)
}
if (s.prompts.length) lines.push("", "Prompts:", ...s.prompts.map((p) => `- /${s.name}:${p.name}${p.description ? ` — ${p.description.split("\n")[0]}` : ""}`))
if (s.prompts.length)
lines.push(
"",
"Prompts:",
...s.prompts.map((p) => {
const about = clean((p.description ?? "").split("\n")[0])
return `- ${code(`/${promptCommand(s.name, p.name)}`)}${about ? ` — ${said(about)}` : ""}`
}),
)
}
return lines.join("\n")
}
return [
"MCP servers:",
...servers.map((s) => `- ${s.name} — ${stateLine(s)} (${SOURCE_WORDS[sourceOf(s)]})`),
...servers.map((s) => `- ${said(clean(s.name))} — ${said(stateLine(s))} (${SOURCE_WORDS[sourceOf(s)]})`),
"",
"/mcp <name> lists one server's tools. A tool asks before it runs unless a permission rule allows it.",
].join("\n")
+12
View File
@@ -126,6 +126,18 @@ export function persistProjectMcpEnabled(project: Project, name: string, on: boo
writeFileSync(file, doc.toString())
}
/** What the project's own config.yaml says of a server's `enabled`, if anything. */
export function projectMcpEnabled(project: Project, name: string): boolean | undefined {
const file = join(project.dir, "config.yaml")
if (!existsSync(file)) return undefined
try {
const v = parseDocument(readFileSync(file, "utf8")).getIn(["mcp", name, "enabled"])
return typeof v === "boolean" ? v : undefined
} catch {
return undefined
}
}
/** Take a rule out of the project's config.yaml again (one a menu saved there); whether it was
* there. A permission left with no pattern goes too. */
export function forgetProjectRule(project: Project, rule: Pick<Rule, "permission" | "pattern">): boolean {
+70 -32
View File
@@ -7,7 +7,9 @@ import type { Option } from "./components/dialog.tsx"
import type { Mark } from "./notices.ts"
import { applyRule } from "./menus.ts"
import type { ServerState } from "../mcp/index.ts"
import { persistProjectMcpEnabled } from "../project/root.ts"
import { persistProjectMcpEnabled, projectMcpEnabled } from "../project/root.ts"
import { promptCommand } from "../mcp/index.ts"
import { clean, errorLine, redactUrls } from "../mcp/clean.ts"
import { offers, sourceOf, SOURCE_WORDS, STATE_WORDS, whereOf } from "../mcp/text.ts"
const MARK_OF: Record<ServerState["status"], Mark> = { connected: "on", connecting: "busy", failed: "failed", needs_auth: "attention", disabled: "off" }
@@ -20,8 +22,13 @@ const SECTION = { library: "From the LLeMbas server", project: "This project (.a
/** Where switching a server on or off holds: the session, and — in a trusted project, for a
* server that is not the login's own — the project's config, so it starts that way next time. */
const persists = (c: CommandCtx, s: ServerState) => c.app.trusted && sourceOf(s) !== "library"
const persists = (c: CommandCtx, s: ServerState) => c.app.trusted && sourceOf(s) !== "library" && !offByUser(c, s)
const scope = (c: CommandCtx, s: ServerState) => (persists(c, s) ? "for this project" : "for this session")
/** Why "on" is the session's only for a server the person's own config switches off. */
const OFF_BY_USER = "Your own config switches this server off (mcp: enabled: false). A project cannot switch it on, so this holds for the session; change your config to keep it on."
/** Switched off in the person's own config (not by this project): a project's `enabled: true`
* would be ignored at the next start, so switching it on is the session's only. */
const offByUser = (c: CommandCtx, s: ServerState) => s.cfg.enabled === false && s.cfg.source === "global" && projectMcpEnabled(c.app.project, s.name) === undefined
/** A sign-in waiting for the person to paste the address the browser ended on (/mcp code). */
export const pendingCodes = new Map<string, (text: string) => void>()
@@ -29,7 +36,7 @@ export const pendingCodes = new Map<string, (text: string) => void>()
/** What one server's row says after its name. */
function rowWords(s: ServerState): string {
if (s.status === "connected") return offers(s)
if (s.status === "failed") return `${STATE_WORDS.failed}: ${(s.error ?? "no reason given").split("\n")[0]}`
if (s.status === "failed") return `${STATE_WORDS.failed}: ${errorLine(s.error) || "no reason given"}`
return STATE_WORDS[s.status]
}
@@ -38,7 +45,7 @@ export function openMcpMenu(c: CommandCtx, select?: string) {
const mcp = c.app.mcp
const order = { library: 0, project: 1, user: 2 }
const servers = [...mcp.servers.values()].sort((a, b) => order[sourceOf(a)] - order[sourceOf(b)] || a.name.localeCompare(b.name))
const options: Option[] = servers.map((s) => ({ label: s.name, value: s.name, mark: MARK_OF[s.status], description: rowWords(s), section: SECTION[sourceOf(s)], detail: whereOf(s) }))
const options: Option[] = servers.map((s) => ({ label: clean(s.name), value: s.name, mark: MARK_OF[s.status], description: rowWords(s), section: SECTION[sourceOf(s)], detail: whereOf(s) }))
c.openDialog({
title: `MCP servers${servers.length ? ` — ${servers.filter((s) => s.status === "connected").length} of ${servers.length} connected` : ""}`,
options,
@@ -63,35 +70,36 @@ export function openMcpServer(c: CommandCtx, name: string, select?: string) {
const act = (id: string, label: string, description: string): Option => ({ label, value: `${ACTION}${id}`, description, section: "Actions" })
const actions: Option[] = [
...(s.status === "disabled"
? [act("on", "Switch on", `connect it — ${scope(c, s)}`)]
? [{ ...act("on", "Switch on", `connect it — ${scope(c, s)}`), ...(offByUser(c, s) && c.app.trusted ? { detail: OFF_BY_USER } : {}) }]
: [act("reconnect", s.status === "connected" ? "Reconnect" : "Connect again", "close the connection and make it anew"), act("off", "Switch off", `its tools are withdrawn — ${scope(c, s)}`)]),
...(signIn ? [act("auth", s.status === "needs_auth" ? "Sign in" : "Sign in again", "opens the server's sign-in page in your browser")] : []),
...(signIn ? [act("logout", "Sign out", "forget the stored sign-in for this server")] : []),
...(s.error ? [act("error", "Read the last error in full", s.error.split("\n")[0]!)] : []),
...(signIn ? [act("logout", "Sign out", "forget the stored sign-in for this server (asks first)")] : []),
...(s.error ? [act("error", "Read the last error in full", errorLine(s.error))] : []),
]
const tools: Option[] =
s.status === "connected"
? s.tools.map((t) => {
const called = mcp.nameOf(s.name, t.name)
const rule = c.app.engine.ruleFor(called) ?? "ask"
const first = (t.description ?? "").trim().split("\n")[0] ?? ""
const first = clean((t.description ?? "").trim().split("\n")[0])
return {
label: t.name,
label: clean(t.name),
value: `${TOOL}${t.name}`,
mark: RULE_MARK[rule],
description: `${RULE_WORDS[rule]}${t.annotations?.readOnlyHint ? " · read-only" : ""}${first ? ` · ${first}` : ""}`,
section: `Tools (${s.tools.length}) — enter changes what a tool may do`,
detail: `${called}\n${(t.description ?? "No description.").trim()}`,
detail: `${clean(called)}\n${clean(t.description ?? "No description.", true).trim()}`,
}
})
: []
const prompts: Option[] =
s.status === "connected"
? s.prompts.map((p) => ({ label: `/${s.name}:${p.name}`, value: `${PROMPT}${p.name}`, description: (p.description ?? "").split("\n")[0], section: `Prompts (${s.prompts.length}) — enter puts one in the box`, detail: p.description ?? "" }))
? // By the name the command is registered under (mcp/index.ts promptCommand), which is what the box understands.
s.prompts.map((p) => ({ label: `/${promptCommand(s.name, p.name)}`, value: `${PROMPT}${p.name}`, description: clean((p.description ?? "").split("\n")[0]), section: `Prompts (${s.prompts.length}) — enter puts one in the box`, detail: clean(p.description ?? "", true) }))
: []
c.openDialog({
title: `MCP · ${s.name}`,
body: [`${STATE_WORDS[s.status]}${s.status === "connected" ? ` — ${offers(s)}` : ""} · from ${SOURCE_WORDS[sourceOf(s)]}`, whereOf(s), ...(s.status === "failed" && s.error ? [`failed: ${s.error.split("\n")[0]}`] : [])],
title: `MCP · ${clean(s.name)}`,
body: [`${STATE_WORDS[s.status]}${s.status === "connected" ? ` — ${offers(s)}` : ""} · from ${SOURCE_WORDS[sourceOf(s)]}`, whereOf(s), ...(s.status === "failed" && s.error ? [`failed: ${errorLine(s.error)}`] : [])],
options: [...actions, ...tools, ...prompts],
// Searchable as soon as there is more than a handful of tools.
filter: tools.length + prompts.length > 6,
@@ -100,7 +108,7 @@ export function openMcpServer(c: CommandCtx, name: string, select?: string) {
onBack: () => openMcpMenu(c, s.name),
onSelect: (v) => {
if (v.startsWith(TOOL)) return openToolRule(c, s.name, v.slice(TOOL.length))
if (v.startsWith(PROMPT)) return c.setInput(`/${s.name}:${v.slice(PROMPT.length)} `)
if (v.startsWith(PROMPT)) return c.setInput(`/${promptCommand(s.name, v.slice(PROMPT.length))} `)
void runAction(c, s.name, v.slice(ACTION.length))
},
})
@@ -114,8 +122,8 @@ function openToolRule(c: CommandCtx, server: string, tool: string) {
const remote = mcp.servers.get(server)?.tools.find((t) => t.name === tool)
const where = c.app.trusted ? "this session, and saved to this project's .agent/config.yaml" : "this session (the project is not trusted, so nothing is saved)"
c.openDialog({
title: `${server} · ${tool}`,
body: [called, ...(remote?.description ? [remote.description.trim().split("\n")[0]!] : []), `Applies to ${where}.`],
title: `${clean(server)} · ${clean(tool)}`,
body: [clean(called), ...(remote?.description ? [clean(remote.description.trim().split("\n")[0])] : []), `Applies to ${where}. A narrower, stricter rule — and your own config — keeps winning.`],
options: [
{ label: "Ask each time", value: "ask", current: now === "ask", description: "a card before every call" },
{ label: "Always allow", value: "allow", current: now === "allow", description: "runs without asking" },
@@ -124,7 +132,7 @@ function openToolRule(c: CommandCtx, server: string, tool: string) {
filter: false,
onBack: () => openMcpServer(c, server, `${TOOL}${tool}`),
onSelect: (action) => {
applyRule(c, { permission: called, pattern: "*", action: action as "ask" | "allow" | "deny" }, tool)
applyRule(c, { permission: called, pattern: "*", action: action as "ask" | "allow" | "deny" }, clean(tool))
openMcpServer(c, server, `${TOOL}${tool}`)
},
})
@@ -134,33 +142,49 @@ function openToolRule(c: CommandCtx, server: string, tool: string) {
function openError(c: CommandCtx, server: string) {
const s = c.app.mcp.servers.get(server)
const width = Math.max(20, Math.min(72, c.renderer.width - 4) - 6)
const lines = [...(s?.error ?? "no error").split("\n"), ...(s?.stderr.length ? ["", "What the program wrote before it stopped:", ...s.stderr] : [])].flatMap((l) => (l.length <= width ? [l] : Array.from({ length: Math.ceil(l.length / width) }, (_, i) => l.slice(i * width, (i + 1) * width))))
// In full, here on the person's own screen — cleaned, and without the credentials an address may carry.
const lines = [...redactUrls(clean(s?.error ?? "no error", true)).split("\n"), ...(s?.stderr.length ? ["", "What the program wrote before it stopped:", ...s.stderr.map((l) => redactUrls(clean(l)))] : [])].flatMap((l) => (l.length <= width ? [l] : Array.from({ length: Math.ceil(l.length / width) }, (_, i) => l.slice(i * width, (i + 1) * width))))
c.openDialog({
title: `MCP · ${server} · the last error`,
options: lines.map((l, i) => ({ label: l || " ", value: String(i) })),
options: lines.map((l, i) => ({ label: l || " ", value: String(i), inert: true })),
filter: false,
hint: "↑↓ pgup/pgdn scroll · esc back",
onBack: () => openMcpServer(c, server, `${ACTION}error`),
onSelect: () => openMcpServer(c, server, `${ACTION}error`),
onSelect: () => {},
})
}
/** Do one thing to a server, say how it went in a line, and show the server again. */
export async function runAction(c: CommandCtx, name: string, action: string, o: { menu?: boolean; code?: string } = { menu: true }): Promise<void> {
export async function runAction(c: CommandCtx, name: string, action: string, o: { menu?: boolean; code?: string; confirmed?: boolean } = { menu: true }): Promise<void> {
const mcp = c.app.mcp
const back = () => (o.menu ? openMcpServer(c, name) : undefined)
if (action === "error") return openError(c, name)
/** Whether the transcript got a line about this server since `mark` — a server that fails or
* needs a sign-in is announced once, by whoever watches the servers (app.ts); it is not said twice. */
const mark = c.view.state.items.length
const announced = () => c.view.state.items.slice(mark).some((i) => i.kind === "notice" && i.text.startsWith(`MCP ${clean(name)} `))
/** Keep a switch for the project, where that holds; what to say when it could not be written. */
const keep = (s: ServerState, on: boolean): string => {
if (!persists(c, s)) return offByUser(c, s) && c.app.trusted ? "for this session — your own config switches it off, and a project cannot switch it on" : scope(c, s)
try {
persistProjectMcpEnabled(c.app.project, name, on)
return "for this project"
} catch (e) {
return `for this session only — it could not be saved to the project: ${(e as Error).message.split("\n")[0]}`
}
}
try {
if (action === "reconnect" || action === "on") {
c.flash(`MCP ${name}: connecting…`)
c.flash(`MCP ${clean(name)}: connecting…`)
// Read before it is switched on: what the configs said of it decides where "on" can be kept.
const where = action === "on" ? keep(mcp.servers.get(name)!, true) : ""
const s = action === "on" ? await mcp.setEnabled(name, true) : await mcp.connect(name)
if (action === "on" && persists(c, s)) persistProjectMcpEnabled(c.app.project, name, true)
if (s.status === "connected") c.view.info(`MCP ${name}: connected — ${offers(s)}`, "success")
else c.view.info(`MCP ${name} did not connect: ${(s.error ?? s.status).split("\n")[0]}`, "warn")
if (s.status === "connected") c.view.info(`MCP ${clean(name)}: connected — ${offers(s)}${where ? ` · switched on ${where}` : ""}`, "success")
else if (!announced()) c.view.info(`MCP ${clean(name)} did not connect: ${errorLine(s.error) || STATE_WORDS[s.status]}`, "warn")
} else if (action === "off") {
const s = await mcp.setEnabled(name, false)
if (persists(c, s)) persistProjectMcpEnabled(c.app.project, name, false)
c.view.info(`MCP ${name}: switched off ${scope(c, s)} — /mcp ${name} switches it on again`)
const where = keep(mcp.servers.get(name)!, false)
await mcp.setEnabled(name, false)
c.view.info(`MCP ${clean(name)}: switched off ${where} — /mcp ${clean(name)} switches it on again`, where.includes("could not") ? "warn" : "info")
} else if (action === "auth") {
const pasted = new Promise<string>((resolve) => pendingCodes.set(name, resolve))
const s = await mcp.auth(
@@ -169,8 +193,8 @@ export async function runAction(c: CommandCtx, name: string, action: string, o:
pasted,
)
pendingCodes.delete(name)
if (s.status === "connected") c.view.info(`MCP ${name}: signed in — ${offers(s)}`, "success")
else c.view.info(`MCP ${name}: ${(s.error ?? s.status).split("\n")[0]}`, "warn")
if (s.status === "connected") c.view.info(`MCP ${clean(name)}: signed in — ${offers(s)}`, "success")
else if (!announced()) c.view.info(`MCP ${clean(name)}: ${errorLine(s.error) || STATE_WORDS[s.status]}`, "warn")
// The sign-in page was read meanwhile: the menu is not put back over it.
return c.refresh()
} else if (action === "code") {
@@ -178,12 +202,26 @@ export async function runAction(c: CommandCtx, name: string, action: string, o:
if (!give) return c.view.info(`no sign-in to ${name} is waiting — /mcp auth ${name} starts one`, "warn")
return give(o.code ?? "")
} else if (action === "logout") {
// Asked once in the menu: signing in again means the browser and the server's page.
if (o.menu && !o.confirmed)
return c.openDialog({
title: `Sign out of ${clean(name)}?`,
body: ["The stored sign-in for this server is forgotten; using it again means signing in in the browser."],
options: [
{ label: "Sign out", value: "yes" },
{ label: "Keep the sign-in", value: "no", current: true },
],
select: "no",
filter: false,
onBack: () => openMcpServer(c, name, `${ACTION}logout`),
onSelect: (v) => (v === "yes" ? void runAction(c, name, "logout", { ...o, confirmed: true }) : openMcpServer(c, name, `${ACTION}logout`)),
})
mcp.logout(name)
c.view.info(`MCP ${name}: the stored sign-in is removed`)
c.view.info(`MCP ${clean(name)}: the stored sign-in is removed`)
} else return c.view.info(`unknown: /mcp ${action} — reconnect, on, off, auth, code or logout`, "warn")
} catch (e) {
pendingCodes.delete(name)
c.view.info(`MCP ${name}: ${(e as Error).message.split("\n")[0]}`, "warn")
if (!announced()) c.view.info(`MCP ${clean(name)}: ${errorLine((e as Error).message)}`, "warn")
}
c.refresh()
back()
+121
View File
@@ -0,0 +1,121 @@
// What an MCP server says is somebody else's text: control characters never reach a terminal,
// what the config resolved to (credentials in an address, a local server's arguments) never
// leaves in `/mcp`'s text, and a description cannot put markup into a reply.
import { expect, test } from "bun:test"
import { clean, errorLine, mdEscape, redactSecrets, redactUrl, redactUrls } from "../src/mcp/clean.ts"
import { McpManager, promptCommand, type ServerState } from "../src/mcp/index.ts"
import { mcpText, whereOf } from "../src/mcp/text.ts"
import { noteNeedsAttention } from "../src/session/engine.ts"
const ESC = "\x1b"
test("control characters are taken out: escape sequences whole, the rest one by one", () => {
expect(clean(`red ${ESC}[31mtext${ESC}[0m`)).toBe("red text")
expect(clean(`title ${ESC}]0;owned${"\x07"} here`)).toBe("title here")
expect(clean(`clip ${ESC}]52;c;aGk=${ESC}\\ x`)).toBe("clip x")
expect(clean(`a\rb\x00c\x08d\x7fe\u009b31mf`)).toBe("a bcdef")
expect(clean("two\nlines\tand a tab")).toBe("two lines and a tab")
expect(clean("two\nlines", true)).toBe("two\nlines")
expect(clean(`cursor ${ESC}[2J${ESC}[H home`, true)).toBe("cursor home")
// Text direction overrides and the like are invisible ways to say something else.
expect(clean("safe‮gnp.exe")).toBe("safegnp.exe")
expect(clean(undefined)).toBe("")
expect(clean(42)).toBe("42")
})
test("addresses and errors without what may be secret in them", () => {
expect(redactUrl("https://user:hunter2@example.org:8443/mcp?token=abc123&x=1#frag")).toBe("https://example.org:8443/mcp?…")
expect(redactUrl("https://example.org/mcp")).toBe("https://example.org/mcp")
expect(redactUrls("fetch https://bob:pw@example.org/a?key=zzz failed")).toBe("fetch https://example.org/a?… failed")
expect(redactSecrets("401 for Authorization: Bearer abcdef0123456789xyz")).not.toContain("abcdef0123456789xyz")
expect(redactSecrets("api_key=sk-test-1234567890 was refused")).toBe("api_key=[redacted] was refused")
expect(redactSecrets('token: "t0psecretvalue"')).not.toContain("t0psecretvalue")
expect(redactSecrets("id 0123456789abcdef0123456789abcdef0123 not found")).toBe("id [redacted] not found")
expect(redactSecrets("connect ECONNREFUSED 127.0.0.1:9")).toBe("connect ECONNREFUSED 127.0.0.1:9")
expect(errorLine(`first ${ESC}[31mline\nsecond line with password=hunter2`)).toBe("first line")
expect(errorLine("x".repeat(400)).length).toBeLessThanOrEqual(200)
expect(mdEscape("see [here](https://example.org) ![x](y) <b> `c` *e*")).toBe("see \\[here\\]\\(https://example.org\\) \\!\\[x\\]\\(y\\) \\<b\\> \\`c\\` \\*e\\*")
})
function server(name: string, o: Partial<ServerState> = {}): ServerState {
return { name, cfg: { url: `https://example.org/${name}`, source: "global" } as never, status: "connected", tools: [], prompts: [], resources: false, stderr: [], gen: 0, ...o }
}
function manager(...servers: ServerState[]): McpManager {
const m = new McpManager({}, { root: "/tmp", version: "0" } as never)
for (const s of servers) m.servers.set(s.name, s)
m.tools()
return m
}
test("/mcp's text does not leak what the config resolved to, nor a server's stderr, nor more than one line of an error", () => {
const m = manager(
server("remote", { cfg: { url: "https://alice:s3cret@example.org/mcp?api_key=abcdef", source: "global" } as never, status: "failed", error: `could not reach https://alice:s3cret@example.org/mcp?api_key=abcdef\nstack line two\nBearer zzzzzzzzzzzzzzzz`, stderr: ["TOKEN=verysecretvalue loaded"] }),
server("local", { cfg: { command: ["/opt/tools/bin/files-server", "--token", "tok_live_123456", "/home/someone/private"], source: "project" } as never }),
)
const list = mcpText(m)
const remote = mcpText(m, "remote")
const local = mcpText(m, "local")
for (const text of [list, remote, local]) {
for (const secret of ["s3cret", "alice", "abcdef", "tok_live_123456", "/home/someone/private", "--token", "verysecretvalue", "stack line two", "zzzzzzzzzzzzzzzz"]) expect(text).not.toContain(secret)
}
expect(remote).toContain("https://example.org/mcp?…")
expect(remote).toContain("failed: could not reach https://example.org/mcp?…")
expect(local).toContain("local: files-server")
expect(whereOf(m.servers.get("local")!)).toBe("local: files-server")
})
test("a server's own strings are cleaned before they are printed, and escaped where the text is markdown", () => {
const hostile = server("evil", {
tools: [{ name: `wipe${ESC}[2J`, description: `Helpful ${ESC}]0;pwned${"\x07"}tool. [click](https://example.org/x) ![img](https://example.org/p.png)\nsecond line`, inputSchema: {} }],
prompts: [{ name: "do it", description: `run ${ESC}[31mnow <script>` }],
})
const m = manager(hostile)
const plain = mcpText(m, "evil")
const md = mcpText(m, "evil", () => undefined, { markdown: true })
for (const text of [plain, md]) {
expect(text).not.toContain(ESC)
expect(text).not.toContain("\x07")
expect(text).not.toContain("pwned")
expect(text).not.toContain("second line")
}
// Markdown: a name is code, a description has no live markup.
expect(md).toContain("- `mcp__evil__wipe__2J` — asks — Helpful tool. \\[click\\]\\(https://example.org/x\\) \\!\\[img\\]\\(https://example.org/p.png\\)")
expect(md).not.toMatch(/(^|[^\\])\[click\]\(/)
expect(md).toContain("\\<script\\>")
// Plain: as it reads.
expect(plain).toContain("- mcp__evil__wipe__2J — asks — Helpful tool. [click](https://example.org/x)")
// A prompt is listed by the name the command is registered under.
expect(promptCommand("evil", "do it")).toBe("evil:do_it")
expect(plain).toContain("- /evil:do_it — run now <script>")
expect(m.prompts().map((p) => p.name)).toEqual(["evil:do_it"])
})
test("tools whose names come out the same both get a hash, whatever order the server lists them in; a library server's other tools are not bare", () => {
const a = { name: "get.user", description: "one", inputSchema: {} }
const b = { name: "get_user", description: "two", inputSchema: {} }
const one = manager(server("s", { tools: [a, b] }))
const two = manager(server("s", { tools: [b, a] }))
const names = (m: McpManager) => [m.nameOf("s", "get.user"), m.nameOf("s", "get_user")]
expect(names(one)).toEqual(names(two))
expect(names(one)[0]).not.toBe(names(one)[1])
// Neither keeps the plain name the other could later inherit.
expect(names(one)).not.toContain("mcp__s__get_user")
expect(names(one).every((n) => /^mcp__s__get_user_[0-9a-f]{8}$/.test(n))).toBe(true)
// A tool with nobody to collide with keeps its plain name.
expect(manager(server("s", { tools: [a] })).nameOf("s", "get.user")).toBe("mcp__s__get_user")
// The LLeMbas server's library: the tool it is there for goes by the bare name; anything else
// it offered is an MCP tool with a name of its own — never a built-in tool's.
const lib = manager(server("lembas-library", { cfg: { url: "https://example.org/mcp", source: "global", tools: { include: ["memory"] } } as never, tools: [{ name: "memory", inputSchema: {} }, { name: "bash", inputSchema: {} }] }))
expect(lib.nameOf("lembas-library", "memory")).toBe("memory")
expect(lib.nameOf("lembas-library", "bash")).toBe("mcp__lembas-library__bash")
expect(lib.tools().map((t) => t.name).sort()).toEqual(["mcp__lembas-library__bash", "memory"])
})
test("a finished job's line keeps the warning sign only when it did not end well", () => {
expect(noteNeedsAttention("job1 (make test) exited with 0 after 12s.")).toBe(false)
expect(noteNeedsAttention("job1 (make test) exited with 2 after 12s.")).toBe(true)
expect(noteNeedsAttention("job2 (sleep 90) stopped (SIGTERM) after 3s.")).toBe(true)
expect(noteNeedsAttention("job3 (explore: find the callers) finished after 40s.")).toBe(false)
expect(noteNeedsAttention("job4 (explore) failed: the model did not answer")).toBe(true)
expect(noteNeedsAttention("job5 was lost when the program restarted")).toBe(true)
})