The dialog every picker uses gains sections, state marks, a body, a line about the highlighted row, esc-goes-back, paging and a position in long lists. /mcp is a menu on it: the servers by where they come from, with state and what they offer; a server's actions (reconnect, off/on — kept for a trusted project —, sign in/out, the last error in full), its tools with their permission rule, changeable there (engine.setRule: the session, and the project when trusted; never under the user's own stricter rule), and its prompts. /mcp <name> opens one. Where there is no menu — over the link, lembas run — /mcp is a plain table (mcp/text.ts). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
13 files changed
+665
-57
No files matched your search
@@ -6,6 +6,20 @@ All notable changes to LLeMbas CLI. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **A `/mcp` menu.** The servers with their state (connected, connecting, failed and why, needs
|
||||
sign-in, switched off), where each comes from (the LLeMbas server's library, this project, your
|
||||
config) and what it offers. Enter opens a server: reconnect, switch it off or on (kept for a
|
||||
trusted project), sign in or out, read its last error in full; its tools, searchable as you
|
||||
type, each with what the permission rules say of it — asks, always allowed, denied — which
|
||||
Enter changes (for the session, and saved to a trusted project; your own config's stricter rule
|
||||
is never loosened from here); its prompts. `/mcp <name>` opens one server directly. Keyboard
|
||||
only; Esc goes back. Over the link and in `lembas run`, `/mcp` and `/mcp <name>` print a plain
|
||||
table instead.
|
||||
- **Menus have sections, state marks, a line about the highlighted row, Esc-goes-back, PgUp/PgDn
|
||||
and Home/End, and say where the cursor is in a long list** — every picker is the one component.
|
||||
|
||||
### Changed
|
||||
|
||||
- **An MCP server that connects no longer says so with a warning sign at every start.** Nothing is
|
||||
|
||||
@@ -3,6 +3,7 @@ import { existsSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
import { parseArgs } from "node:util"
|
||||
import { createApp } from "./app.ts"
|
||||
import { expandSlash } from "./session/commands.ts"
|
||||
import { attachmentsFor } from "./project/attach.ts"
|
||||
import { ConfigError, loadConfig } from "./config/load.ts"
|
||||
import { asMode, EFFORTS, MODES, type Mode } from "./config/schema.ts"
|
||||
@@ -344,6 +345,14 @@ async function main() {
|
||||
// One prompt, so the MCP servers' tools must be there before it (each server has its own
|
||||
// connect timeout; a failure is a notice, not a stop).
|
||||
await app.mcpReady
|
||||
// A command that only says something (/mcp, /agents, /team — what the TUI shows as a menu):
|
||||
// its text, and no model is asked.
|
||||
const said = expandSlash(app, prompt)
|
||||
if (said?.kind === "message") {
|
||||
console.log(said.text)
|
||||
app.discardIfEmpty()
|
||||
process.exit(0)
|
||||
}
|
||||
const atts = attachmentsFor(prompt, app.engine.o.toolCtx, app.engine.model.spec.vision === true)
|
||||
// Through the turns, like every front end: a job's note wakes the session the same way.
|
||||
const reason = await app.turns.prompt(prompt, atts.flatMap((a) => (a.image ? [a.text, a.image] : [a.text])))
|
||||
|
||||
@@ -144,6 +144,13 @@ let exitHook = false
|
||||
|
||||
export class McpManager {
|
||||
readonly servers = new Map<string, ServerState>()
|
||||
/** What each server's tool is called here, as `tools()` last named it. */
|
||||
private names = new Map<string, string>()
|
||||
|
||||
/** 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))
|
||||
}
|
||||
private listeners: (() => void)[] = []
|
||||
|
||||
/** Called whenever a server's status, tools or prompts change. */
|
||||
@@ -399,6 +406,7 @@ export class McpManager {
|
||||
const library = s.name === LIBRARY_SERVER
|
||||
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)
|
||||
const readOnly = t.annotations?.readOnlyHint === true
|
||||
out.push({
|
||||
name,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// What is said about the MCP servers in words: the states, where a server comes from, and the
|
||||
// plain table `/mcp` prints where there is no menu (`lembas run`, a prompt sent over the link —
|
||||
// the web UI shows it as a reply). The TUI's menu (tui/mcpmenu.ts) reads the same words.
|
||||
import type { McpManager, ServerState } from "./index.ts"
|
||||
import { LIBRARY_SERVER } from "./index.ts"
|
||||
|
||||
export const STATE_WORDS: Record<ServerState["status"], string> = {
|
||||
connected: "connected",
|
||||
connecting: "connecting",
|
||||
failed: "failed",
|
||||
needs_auth: "needs sign-in",
|
||||
disabled: "switched off",
|
||||
}
|
||||
|
||||
/** Where a server is configured: the LLeMbas server's own library (it comes with the login), the
|
||||
* project's .agent/config.yaml, or the person's own config. */
|
||||
export function sourceOf(s: Pick<ServerState, "name" | "cfg">): "library" | "project" | "user" {
|
||||
return s.name === LIBRARY_SERVER ? "library" : s.cfg.source === "project" ? "project" : "user"
|
||||
}
|
||||
|
||||
export const SOURCE_WORDS = { library: "the LLeMbas server's library", project: "this project", user: "your config" } as const
|
||||
|
||||
/** `3 tools, 1 prompt, resources` — what a connected server offers. */
|
||||
export function offers(s: Pick<ServerState, "tools" | "prompts" | "resources">): string {
|
||||
const n = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`
|
||||
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>`. */
|
||||
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}`
|
||||
return STATE_WORDS[s.status]
|
||||
}
|
||||
|
||||
/** Where a server is reached: its address, or `local` and the program it runs. */
|
||||
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 ?? "")
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
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("", ...s.error.split("\n").map((l) => ` ${l}`))
|
||||
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]}` : ""}`)
|
||||
}
|
||||
if (s.prompts.length) lines.push("", "Prompts:", ...s.prompts.map((p) => ` /${s.name}:${p.name}${p.description ? ` — ${p.description.split("\n")[0]}` : ""}`))
|
||||
}
|
||||
return lines.join("\n")
|
||||
}
|
||||
const width = Math.max(...servers.map((s) => s.name.length))
|
||||
return [
|
||||
"MCP servers:",
|
||||
...servers.map((s) => ` ${s.name.padEnd(width)} ${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")
|
||||
}
|
||||
@@ -63,6 +63,19 @@ export function toRules(config: PermissionConfig, source?: Rule["source"]): Rule
|
||||
return rules
|
||||
}
|
||||
|
||||
/** What the rules say of a permission and pattern, before any mode: undefined where none speaks
|
||||
* (the call is then asked or allowed by its class and the mode). */
|
||||
export function ruleAction(permission: string, pattern: string, rules: Rule[]): Action | undefined {
|
||||
return lookupRule(permission, pattern, rules)?.action
|
||||
}
|
||||
|
||||
/** The user's own global rule that is stricter than `action` for this permission and pattern —
|
||||
* the floor a rule made anywhere else cannot go under — or undefined. */
|
||||
export function stricterGlobal(permission: string, pattern: string, action: Action, rules: Rule[]): Rule | undefined {
|
||||
const own = rules.findLast((r) => r.source === "global" && !r.learned && match(permission, r.permission) && match(pattern, r.pattern))
|
||||
return own && RANK[own.action] > RANK[action] ? own : undefined
|
||||
}
|
||||
|
||||
function lookupRule(permission: string, pattern: string, rules: Rule[]): Rule | undefined {
|
||||
const hit = rules.findLast((r) => match(permission, r.permission) && match(pattern, r.pattern))
|
||||
// A project's rule (or an "always" answer) that is looser than what the user's global config says
|
||||
|
||||
@@ -113,6 +113,19 @@ export function setTrust(root: string, level: TrustLevel) {
|
||||
writeFileSync(trustFile(), JSON.stringify(t, null, 2))
|
||||
}
|
||||
|
||||
/** A server switched off or on for this project: `mcp.<name>.enabled` in the project's
|
||||
* config.yaml, keeping its comments (for a server of the user's own config this is the one thing
|
||||
* a project may say about it). */
|
||||
export function persistProjectMcpEnabled(project: Project, name: string, on: boolean) {
|
||||
const file = join(project.dir, "config.yaml")
|
||||
mkdirSync(project.dir, { recursive: true })
|
||||
assertProjectFile(file, project.root)
|
||||
const doc = parseDocument(existsSync(file) ? readFileSync(file, "utf8") : "")
|
||||
if (!doc.contents) doc.contents = doc.createNode({}) as never
|
||||
doc.setIn(["mcp", name, "enabled"], on)
|
||||
writeFileSync(file, doc.toString())
|
||||
}
|
||||
|
||||
/** "Always allow (project)": add the rule to the project's config.yaml, keeping its comments. */
|
||||
export function persistProjectRule(project: Project, rule: Rule) {
|
||||
const file = join(project.dir, "config.yaml")
|
||||
|
||||
@@ -20,6 +20,7 @@ import { TEAM, Team } from "../team/team.ts"
|
||||
import { SUBAGENTS } from "../team/subagents.ts"
|
||||
import { progressLine } from "./progress.ts"
|
||||
import { fillPrompt } from "../prompt/fill.ts"
|
||||
import { mcpText } from "../mcp/text.ts"
|
||||
|
||||
export type CommandKind = "custom" | "skill" | "builtin"
|
||||
|
||||
@@ -50,6 +51,7 @@ export const SHARED_BUILTINS: { name: string; description: string; hint?: string
|
||||
{ name: "changelog", description: "update CHANGELOG.md's Unreleased section from the commits since the last tag", hint: "since" },
|
||||
{ name: "init", description: "make or update the project's AGENTS.md from what the repository says", hint: "what to focus on" },
|
||||
{ name: "continue", description: "carry on — after esc stopped it, or when it should keep going (ctrl+g)" },
|
||||
{ name: "mcp", description: "MCP servers: a menu of them — state, tools and what each may do, sign in, switch one on or off", hint: "server" },
|
||||
{ name: "agents", description: "subagents: list them, make one, or hand one a task", hint: "name" },
|
||||
{ name: "team", description: "subagents: the tree and the room; how many; stop one; their findings", hint: "size <min> <max> | stop <name> | findings <name>" },
|
||||
]
|
||||
@@ -264,6 +266,11 @@ export function expandSlash(app: App, text: string): Expanded | undefined {
|
||||
return { kind: "message", name, text: agentsText(app, arg) }
|
||||
case "team":
|
||||
return { kind: "message", name, text: teamText(app, arg) }
|
||||
case "mcp":
|
||||
// No menu here: the servers as a table, or one server's tools. What changes a server (sign
|
||||
// in, switch off) is the terminal's to do.
|
||||
if (/^(reconnect|on|off|auth|code|logout)\b/.test(arg.trim())) return { kind: "message", name, text: "/mcp here shows the servers and their tools; connecting, switching one off and signing in are done at the terminal." }
|
||||
return { kind: "message", name, text: mcpText(app.mcp, arg.trim().split(/\s+/)[0] ?? "", (tool) => app.engine.ruleFor(tool)) }
|
||||
case "init":
|
||||
// The prompt is ours; only what was typed after the name may attach files.
|
||||
return { kind: "prompt", name, prompt: initPrompt(app, arg), shown: t, attachFrom: arg }
|
||||
|
||||
+37
-1
@@ -8,7 +8,7 @@ import { isAbsolute } from "node:path"
|
||||
import type { Asker, AttachmentInfo, Bus } from "../bus/index.ts"
|
||||
import type { Mode } from "../config/schema.ts"
|
||||
import type { Level } from "../provider/effort.ts"
|
||||
import { evaluate, shadowsDeny, type Context as PermContext, type PermissionRequest, type Rule } from "../permission/evaluate.ts"
|
||||
import { evaluate, ruleAction, shadowsDeny, stricterGlobal, type Context as PermContext, type PermissionRequest, type Rule } from "../permission/evaluate.ts"
|
||||
import { ProviderError, type Client, type ImagePart, type Message, type ResolvedModel, type ToolCallPart, type Usage } from "../provider/types.ts"
|
||||
import type { Plan } from "../plan/plan.ts"
|
||||
import { LOOP } from "../harness.ts"
|
||||
@@ -394,6 +394,42 @@ export class Engine {
|
||||
return { args, ...(title ? { title } : {}) }
|
||||
}
|
||||
|
||||
/** Every rule in force: the configured ones, then this session's. */
|
||||
get rules(): Rule[] {
|
||||
return [...this.o.perm.rules, ...this.sessionRules]
|
||||
}
|
||||
|
||||
/** What the rules say of a permission (and pattern) now, before the mode; undefined: none speaks. */
|
||||
ruleFor(permission: string, pattern = "*"): Rule["action"] | undefined {
|
||||
return ruleAction(permission, pattern, this.rules)
|
||||
}
|
||||
|
||||
/** A rule the person set themselves (a menu, not an answer to a card): in force at once for
|
||||
* this session, and written to the project's config where the project is trusted. Refused,
|
||||
* with the rule that stands in the way, where the person's own global config is stricter —
|
||||
* that is changed there, not written over from a project. */
|
||||
setRule(rule: Pick<Rule, "permission" | "pattern" | "action">): { saved: "project" | "session" } | { refused: Rule } {
|
||||
const floor = stricterGlobal(rule.permission, rule.pattern, rule.action, this.o.perm.rules)
|
||||
if (floor) return { refused: floor }
|
||||
this.sessionRules = this.sessionRules.filter((r) => !(r.permission === rule.permission && r.pattern === rule.pattern))
|
||||
this.sessionRules.push({ ...rule })
|
||||
if (!this.o.persistRule) return { saved: "session" }
|
||||
this.o.persistRule({ ...rule })
|
||||
return { saved: "project" }
|
||||
}
|
||||
|
||||
/** Take a rule of this session away again (one made by an "always" answer, or set here). */
|
||||
dropSessionRule(permission: string, pattern: string): boolean {
|
||||
const before = this.sessionRules.length
|
||||
this.sessionRules = this.sessionRules.filter((r) => !(r.permission === permission && r.pattern === pattern))
|
||||
return this.sessionRules.length < before
|
||||
}
|
||||
|
||||
/** This session's own rules ("always" answers and what was set in a menu). */
|
||||
get ownRules(): readonly Rule[] {
|
||||
return this.sessionRules
|
||||
}
|
||||
|
||||
/** How this session's last turn ended, when it did not finish — from the store. */
|
||||
storedEnd(): { reason: string; error?: string } | undefined {
|
||||
if (!this.o.store || !this.sessionId) return undefined
|
||||
|
||||
+8
-41
@@ -30,6 +30,7 @@ import { listPrototypes } from "../prototype/store.ts"
|
||||
import { keyMatcher } from "../voice/index.ts"
|
||||
import { PLAYER_NAMES, playerFor, recorderFor } from "../voice/audio.ts"
|
||||
import { duration } from "../duration.ts"
|
||||
import { openMcpMenu, openMcpServer, runAction } from "./mcpmenu.ts"
|
||||
import type { Job, JobInfo } from "../jobs/registry.ts"
|
||||
|
||||
export interface CommandCtx extends Ctx {
|
||||
@@ -82,8 +83,6 @@ const HELP_KEYS = [
|
||||
"pgup/pgdn scroll half a screen · ctrl+↑/↓ three lines · the mouse wheel · ↑ in an empty box takes back a message waiting to go in",
|
||||
]
|
||||
|
||||
/** A sign-in waiting for the user to paste the redirect address (/mcp code). */
|
||||
const pendingCodes = new Map<string, (text: string) => void>()
|
||||
|
||||
const AGENT_TEMPLATE = (name: string) => `---
|
||||
description: what ${name} is for — the model reads this when it picks a subagent
|
||||
@@ -996,49 +995,17 @@ export const COMMANDS: Command[] = [
|
||||
},
|
||||
{
|
||||
name: "mcp",
|
||||
args: "[reconnect|on|off|auth|code|logout <server>]",
|
||||
description: "MCP servers: status and tools; sign in; switch one on or off",
|
||||
args: "[<server> | reconnect|on|off|auth|code|logout <server>]",
|
||||
description: "MCP servers: a menu of them — state, tools and what each may do, sign in, switch one on or off",
|
||||
async run(c, arg) {
|
||||
const mcp = c.app.mcp
|
||||
const [sub = "", name = "", ...rest] = arg.trim().split(/\s+/)
|
||||
if (!sub) {
|
||||
if (!mcp.servers.size) return c.view.info("no MCP servers — add them under mcp: in ~/.config/lembas/config.yaml")
|
||||
const mark = { connected: "●", connecting: "…", disabled: "○", failed: "✗", needs_auth: c.theme().icons.locked } as const
|
||||
const lines = [...mcp.servers.values()].map((s) => {
|
||||
const head = `${mark[s.status]} ${s.name} ${s.cfg.command !== undefined ? "local" : s.cfg.url}${s.cfg.source === "project" ? " · project" : ""} — ${s.status}${s.error ? `: ${s.error}` : ""}`
|
||||
const tools = s.status === "connected" ? s.tools.map((t) => ` ${t.name}${t.annotations?.readOnlyHint ? " (read-only)" : ""}`) : []
|
||||
const prompts = s.status === "connected" ? s.prompts.map((pr) => ` /${s.name}:${pr.name}`) : []
|
||||
return [head, ...tools, ...prompts].join("\n")
|
||||
})
|
||||
return c.view.info(`${lines.join("\n\n")}\n\nTools are named mcp__<server>__<tool> and ask before they run unless a permission rule allows them.`)
|
||||
}
|
||||
// No word: the menu. A server's name: that server.
|
||||
if (!sub) return openMcpMenu(c)
|
||||
if (mcp.servers.has(sub) && !name) return openMcpServer(c, sub)
|
||||
if (!["reconnect", "on", "off", "auth", "code", "logout"].includes(sub)) return c.view.info(`no MCP server "${sub}" — ${[...mcp.servers.keys()].join(", ") || "none are configured"}`, "warn")
|
||||
if (!name || !mcp.servers.has(name)) return c.view.info(`usage: /mcp ${sub} <server> — servers: ${[...mcp.servers.keys()].join(", ") || "(none)"}`, "warn")
|
||||
try {
|
||||
if (sub === "reconnect" || sub === "on") {
|
||||
c.view.info(`MCP ${name}: connecting…`)
|
||||
const s = sub === "on" ? await mcp.setEnabled(name, true) : await mcp.connect(name)
|
||||
if (s.status !== "connected") c.view.info(`MCP ${name}: ${s.error ?? s.status}`, "warn")
|
||||
} else if (sub === "off") {
|
||||
await mcp.setEnabled(name, false)
|
||||
c.view.info(`MCP ${name}: off for this session`)
|
||||
} else if (sub === "auth") {
|
||||
const pasted = new Promise<string>((resolve) => pendingCodes.set(name, resolve))
|
||||
const s = await mcp.auth(name, (url) => c.view.info(`Sign in to ${name} at:\n${url}\n\nThe browser is sent back to this machine (127.0.0.1). If it cannot get here, copy the address it ends on and type: /mcp code ${name} <that address>`), pasted)
|
||||
pendingCodes.delete(name)
|
||||
c.view.info(s.status === "connected" ? `MCP ${name}: signed in` : `MCP ${name}: ${s.error ?? s.status}`, s.status === "connected" ? undefined : "warn")
|
||||
} else if (sub === "code") {
|
||||
const give = pendingCodes.get(name)
|
||||
if (!give) return c.view.info(`no sign-in to ${name} is waiting — /mcp auth ${name} starts one`, "warn")
|
||||
give(rest.join(" "))
|
||||
} else if (sub === "logout") {
|
||||
mcp.logout(name)
|
||||
c.view.info(`MCP ${name}: stored sign-in removed`)
|
||||
} else c.view.info(`unknown: /mcp ${sub} — reconnect, on, off, auth, code or logout`, "warn")
|
||||
} catch (e) {
|
||||
pendingCodes.delete(name)
|
||||
c.view.info(`MCP ${name}: ${(e as Error).message}`, "warn")
|
||||
}
|
||||
c.refresh()
|
||||
await runAction(c, name, sub, { menu: false, code: rest.join(" ") })
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
+108
-14
@@ -2,12 +2,21 @@ import { RGBA, TextAttributes } from "@opentui/core"
|
||||
import { useKeyboard } from "@opentui/solid"
|
||||
import { createEffect, createMemo, createSignal, For, onCleanup, Show } from "solid-js"
|
||||
import { useTui } from "../context.ts"
|
||||
import { MARKS, type Mark } from "../notices.ts"
|
||||
|
||||
export interface Option {
|
||||
label: string
|
||||
value: string
|
||||
description?: string
|
||||
current?: boolean
|
||||
/** The heading this row stands under: drawn once, above the first row of each run of it. */
|
||||
section?: string
|
||||
/** The row's state, as a coloured mark before its label (tui/notices.ts MARKS) — a server
|
||||
* connected, a rule that denies. Takes the place of the `current` dot. */
|
||||
mark?: Mark
|
||||
/** More about the highlighted row than its line holds — a tool's whole description — shown
|
||||
* under the list, wrapped, while the row is highlighted. */
|
||||
detail?: string
|
||||
/** A two-handle range on this row (the Subagents setting, harness team.md §2: one range from 1
|
||||
* to the cap, Min and Max). While the row is highlighted ←→ move the handle in focus and tab
|
||||
* moves the focus; Min never passes Max. Enter calls `onSubmit` with both, not `onSelect`. */
|
||||
@@ -45,10 +54,18 @@ export interface DialogSpec {
|
||||
custom?: { label: string; onSubmit: (text: string) => void }
|
||||
/** More keys on the highlighted row — the Resume picker's ctrl+d deletes the session
|
||||
* under it. The dialog closes first, as for enter; `when(key)` says whether a key is this one. */
|
||||
keys?: { when: (key: { name: string; ctrl?: boolean; meta?: boolean; shift?: boolean }) => boolean; run: (value: string) => void }[]
|
||||
keys?: { when: (key: { name: string; ctrl?: boolean; meta?: boolean; shift?: boolean }) => boolean; run: (value: string) => void; /** The menu stays open (the caller redraws it). */ keep?: boolean }[]
|
||||
/** The footer in place of `↑↓ move · enter choose · esc close`, to name those keys: a
|
||||
* binding nobody is told about is one nobody finds, which is how delete went unseen in /sessions. */
|
||||
hint?: string
|
||||
/** Lines above the list: what the menu is about (a server's address and state). Wrapped. */
|
||||
body?: string[]
|
||||
/** What an empty list says, in place of "nothing matches" (which is for a filter). */
|
||||
empty?: string
|
||||
/** Esc goes back here (a menu opened from another) rather than closing; the footer says so. */
|
||||
onBack?: () => void
|
||||
/** The row to start on, by value (else the `current` one, else the first). */
|
||||
select?: string
|
||||
/** Columns the box may take (72 by default; the terminal less four is the ceiling either way):
|
||||
* a list whose rows are columns of their own (/jobs) asks for more. */
|
||||
width?: number
|
||||
@@ -58,6 +75,29 @@ export interface DialogSpec {
|
||||
}
|
||||
|
||||
const CUSTOM = "\u0000custom"
|
||||
/** The most rows a menu's body and the highlighted row's detail may take. */
|
||||
const BODY_ROWS = 6
|
||||
const DETAIL_ROWS = 3
|
||||
|
||||
/** A sentence as rows of at most `width` columns, broken at spaces (a word longer than a row is
|
||||
* cut). */
|
||||
export function wrapWords(text: string, width: number): string[] {
|
||||
const out: string[] = []
|
||||
let line = ""
|
||||
for (const word of text.split(/\s+/).filter(Boolean)) {
|
||||
if (line && line.length + 1 + word.length > width) {
|
||||
out.push(line)
|
||||
line = ""
|
||||
}
|
||||
line = line ? `${line} ${word}` : word
|
||||
while (line.length > width) {
|
||||
out.push(line.slice(0, width))
|
||||
line = line.slice(width)
|
||||
}
|
||||
}
|
||||
if (line || !out.length) out.push(line)
|
||||
return out
|
||||
}
|
||||
|
||||
/** A modal list: type to filter, ↑↓ to move, enter to choose, esc to close. */
|
||||
export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
@@ -80,7 +120,7 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
const next: [number, number] = focus() === 0 ? [Math.min(hi, Math.max(r.from, lo + by)), hi] : [lo, Math.min(r.to, Math.max(lo, hi + by))]
|
||||
setRanges((m) => ({ ...m, [o.value]: next }))
|
||||
}
|
||||
const start = Math.max(0, p.spec.options.findIndex((o) => o.current))
|
||||
const start = Math.max(0, p.spec.options.findIndex((o) => (p.spec.select !== undefined ? o.value === p.spec.select : o.current)))
|
||||
const [sel, setSel] = createSignal(start)
|
||||
// The spec is live: a list that redraws itself with fewer rows keeps the cursor on a row.
|
||||
createEffect(() => {
|
||||
@@ -90,8 +130,41 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
// Taken once: the spec that opened the dialog says what to do when it goes.
|
||||
const onClose = p.spec.onClose
|
||||
onCleanup(() => onClose?.())
|
||||
const visible = () => Math.max(3, Math.min(14, dims().height - 10))
|
||||
const offset = () => Math.max(0, Math.min(sel() - Math.floor(visible() / 2), shown().length - visible()))
|
||||
const width = () => Math.min(p.spec.width ?? 72, dims().width - 4)
|
||||
const body = createMemo(() => (p.spec.body ?? []).flatMap((l) => (l ? wrapWords(l, Math.max(10, width() - 4)) : [""])))
|
||||
const detail = createMemo(() => {
|
||||
const d = shown()[sel()]?.detail
|
||||
return d ? d.split("\n").flatMap((l) => wrapWords(l, Math.max(10, width() - 6))).slice(0, DETAIL_ROWS) : []
|
||||
})
|
||||
// The list's rows: every option, and a heading above the first row of each section.
|
||||
type Row = { head: string } | { option: Option; index: number }
|
||||
const rows = createMemo(() => {
|
||||
const out: Row[] = []
|
||||
let section: string | undefined
|
||||
shown().forEach((option, index) => {
|
||||
if (option.section !== undefined && option.section !== section) out.push({ head: option.section })
|
||||
section = option.section
|
||||
out.push({ option, index })
|
||||
})
|
||||
return out
|
||||
})
|
||||
// What the screen leaves for the list: less the body above it and the detail below.
|
||||
const visible = () => Math.max(3, Math.min(16, dims().height - 10 - Math.min(body().length, BODY_ROWS) - (detail().length ? DETAIL_ROWS + 1 : 0)))
|
||||
const offset = () => {
|
||||
const at = rows().findIndex((r) => "option" in r && r.index === sel())
|
||||
const first = Math.max(0, Math.min(at - Math.floor(visible() / 2), rows().length - visible()))
|
||||
// A heading just above the window's first row is shown with it.
|
||||
return first > 0 && at - first < visible() - 1 && "head" in (rows()[first - 1] ?? {}) ? first - 1 : first
|
||||
}
|
||||
|
||||
/** The key hints: the menu's own, or the usual ones — with "esc back" in a menu that has
|
||||
* somewhere to go back to, and where the cursor is in a list longer than the window. */
|
||||
const footer = () => {
|
||||
const esc = p.spec.onBack ? "esc back" : "esc close"
|
||||
const base = p.spec.hint ?? `↑↓ move · enter choose · ${esc}`
|
||||
const n = shown().length
|
||||
return n > visible() ? `${base} · ${sel() + 1}/${n}` : base
|
||||
}
|
||||
|
||||
useKeyboard((key) => {
|
||||
const n = shown().length
|
||||
@@ -101,10 +174,15 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
if (o && o.value !== CUSTOM) {
|
||||
// Taken before closing, as for enter: closing clears the spec.
|
||||
const run = bound.run
|
||||
p.close()
|
||||
if (!bound.keep) p.close()
|
||||
run(o.value)
|
||||
}
|
||||
} else if (key.name === "escape") p.close()
|
||||
} else if (key.name === "escape") {
|
||||
const back = p.spec.onBack
|
||||
p.close()
|
||||
back?.()
|
||||
} else if (key.name === "pageup" || key.name === "pagedown") setSel((i) => Math.max(0, Math.min(n - 1, i + (key.name === "pageup" ? -1 : 1) * Math.max(1, visible() - 1))))
|
||||
else if (key.name === "home" || key.name === "end") setSel(key.name === "home" ? 0 : Math.max(0, n - 1))
|
||||
else if (shown()[sel()]?.range && (key.name === "left" || key.name === "right")) move(shown()[sel()]!, key.name === "left" ? -1 : 1)
|
||||
else if (shown()[sel()]?.range && key.name === "tab") setFocus((f) => (f === 0 ? 1 : 0))
|
||||
else if (key.name === "up" || (key.ctrl && key.name === "p")) setSel((i) => (i + n - 1) % Math.max(n, 1))
|
||||
@@ -133,16 +211,23 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
key.stopPropagation()
|
||||
})
|
||||
|
||||
const width = () => Math.min(p.spec.width ?? 72, dims().width - 4)
|
||||
return (
|
||||
<box position="absolute" zIndex={100} left={0} top={0} width={dims().width} height={dims().height} alignItems="center" paddingTop={Math.max(1, Math.floor(dims().height / 6))} backgroundColor={RGBA.fromInts(0, 0, 0, 140)}>
|
||||
<box width={width()} border borderStyle="rounded" borderColor={c().border} backgroundColor={c().menu} flexDirection="column" paddingLeft={1} paddingRight={1} title={` ${p.spec.title} `} titleColor={c().title}>
|
||||
<Show when={filterable()}>
|
||||
<text fg={query() ? c().text : c().dim}>{query() ? `› ${query()}` : "› type to filter"}</text>
|
||||
</Show>
|
||||
<For each={shown().slice(offset(), offset() + visible())}>
|
||||
{(o, i) => {
|
||||
const active = () => i() + offset() === sel()
|
||||
<For each={body().slice(0, BODY_ROWS)}>{(l) => <text fg={c().muted} wrapMode="none" truncate>{l || " "}</text>}</For>
|
||||
<For each={rows().slice(offset(), offset() + visible())}>
|
||||
{(row) => {
|
||||
if ("head" in row)
|
||||
return (
|
||||
<text wrapMode="none" truncate fg={c().label}>
|
||||
{row.head}
|
||||
</text>
|
||||
)
|
||||
const o = row.option
|
||||
const active = () => row.index === sel()
|
||||
if (o.range) {
|
||||
const values = () => valuesOf(o)
|
||||
const track = () => rangeTrack(o.range!, values()[0], values()[1])
|
||||
@@ -170,7 +255,9 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
return (
|
||||
<box flexDirection="row" backgroundColor={active() ? c().menuCurrent : undefined}>
|
||||
<text wrapMode="none" truncate fg={active() ? c().title : c().text} attributes={active() ? TextAttributes.BOLD : 0}>
|
||||
{o.current ? "● " : " "}
|
||||
<Show when={o.mark} fallback={o.current ? "● " : " "}>
|
||||
<span style={{ fg: c()[MARKS[o.mark!].color] }}>{MARKS[o.mark!].glyph} </span>
|
||||
</Show>
|
||||
{o.label}
|
||||
<span style={{ fg: c().muted }}>{o.description ? ` ${o.description}` : ""}</span>
|
||||
</text>
|
||||
@@ -179,12 +266,19 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
}}
|
||||
</For>
|
||||
<Show when={shown().length === 0}>
|
||||
<text fg={c().muted}>nothing matches</text>
|
||||
<text fg={c().muted} wrapMode="word">
|
||||
{query() ? "nothing matches" : (p.spec.empty ?? "nothing here")}
|
||||
</text>
|
||||
</Show>
|
||||
<text fg={c().dim}>
|
||||
<Show when={detail().length}>
|
||||
<box flexDirection="column" height={DETAIL_ROWS + 1} border={["top"]} borderColor={c().border}>
|
||||
<For each={detail()}>{(l) => <text fg={c().muted} wrapMode="none" truncate>{l || " "}</text>}</For>
|
||||
</box>
|
||||
</Show>
|
||||
<text fg={c().dim} wrapMode="none" truncate>
|
||||
{shown()[sel()]?.range
|
||||
? `←→ move ${shown()[sel()]!.range!.names[focus()]} · tab ${shown()[sel()]!.range!.names[focus() === 0 ? 1 : 0]} · enter set · esc close`
|
||||
: (p.spec.hint ?? "↑↓ move · enter choose · esc close")}
|
||||
: footer()}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
// The /mcp menu: the servers with their state and where each comes from; one server's tools with
|
||||
// what the permission rules say of each (changeable here), its prompts, and what can be done with
|
||||
// it — reconnect, switch off or on, sign in or out, read the last error in full. Built on the
|
||||
// shared menu (components/dialog.tsx), so it looks and answers to keys as every other one does.
|
||||
import type { CommandCtx } from "./commands.ts"
|
||||
import type { Option } from "./components/dialog.tsx"
|
||||
import type { Mark } from "./notices.ts"
|
||||
import type { ServerState } from "../mcp/index.ts"
|
||||
import { persistProjectMcpEnabled } from "../project/root.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" }
|
||||
/** What the rules say of a tool, as the menu words it. */
|
||||
const RULE_WORDS = { ask: "asks", allow: "always allowed", deny: "denied" } as const
|
||||
const RULE_MARK: Record<keyof typeof RULE_WORDS, Mark> = { ask: "off", allow: "on", deny: "failed" }
|
||||
|
||||
const ADD_HINT = "No MCP servers are configured. Add one under mcp: in ~/.config/lembas/config.yaml (or this project's .agent/config.yaml), then /reload."
|
||||
const SECTION = { library: "From the LLeMbas server", project: "This project (.agent/config.yaml)", user: "Your config" } as const
|
||||
|
||||
/** 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 scope = (c: CommandCtx, s: ServerState) => (persists(c, s) ? "for this project" : "for this session")
|
||||
|
||||
/** 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>()
|
||||
|
||||
/** 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]}`
|
||||
return STATE_WORDS[s.status]
|
||||
}
|
||||
|
||||
/** The list of servers. Enter opens one. */
|
||||
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) }))
|
||||
c.openDialog({
|
||||
title: `MCP servers${servers.length ? ` — ${servers.filter((s) => s.status === "connected").length} of ${servers.length} connected` : ""}`,
|
||||
options,
|
||||
empty: ADD_HINT,
|
||||
...(select ? { select } : {}),
|
||||
hint: "↑↓ move · enter open · esc close",
|
||||
onSelect: (name) => openMcpServer(c, name),
|
||||
})
|
||||
}
|
||||
|
||||
const ACTION = "\u0000action:"
|
||||
const TOOL = "\u0000tool:"
|
||||
const PROMPT = "\u0000prompt:"
|
||||
|
||||
/** One server: what can be done with it, its tools (type to search), its prompts. */
|
||||
export function openMcpServer(c: CommandCtx, name: string, select?: string) {
|
||||
const mcp = c.app.mcp
|
||||
const s = mcp.servers.get(name)
|
||||
if (!s) return openMcpMenu(c)
|
||||
const remote = s.cfg.url !== undefined
|
||||
const signIn = remote && s.cfg.oauth !== false && sourceOf(s) !== "library"
|
||||
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("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]!)] : []),
|
||||
]
|
||||
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] ?? ""
|
||||
return {
|
||||
label: 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()}`,
|
||||
}
|
||||
})
|
||||
: []
|
||||
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 ?? "" }))
|
||||
: []
|
||||
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]}`] : [])],
|
||||
options: [...actions, ...tools, ...prompts],
|
||||
// Searchable as soon as there is more than a handful of tools.
|
||||
filter: tools.length + prompts.length > 6,
|
||||
...(select ? { select } : {}),
|
||||
hint: "↑↓ move · enter choose · esc back",
|
||||
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)} `)
|
||||
void runAction(c, s.name, v.slice(ACTION.length))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** What a tool may do: ask each time, always allowed, denied — the permission rule for it. */
|
||||
function openToolRule(c: CommandCtx, server: string, tool: string) {
|
||||
const mcp = c.app.mcp
|
||||
const called = mcp.nameOf(server, tool)
|
||||
const now = c.app.engine.ruleFor(called) ?? "ask"
|
||||
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}.`],
|
||||
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" },
|
||||
{ label: "Deny", value: "deny", current: now === "deny", description: "never runs; the model is told" },
|
||||
],
|
||||
filter: false,
|
||||
onBack: () => openMcpServer(c, server, `${TOOL}${tool}`),
|
||||
onSelect: (action) => {
|
||||
const r = c.app.engine.setRule({ permission: called, pattern: "*", action: action as "ask" | "allow" | "deny" })
|
||||
if ("refused" in r) c.view.info(`${tool}: your own config says ${r.refused.action} for ${r.refused.permission} — change it there (~/.config/lembas/config.yaml, permission:); a rule made here cannot loosen it`, "warn")
|
||||
else c.flash(`${tool}: ${RULE_WORDS[action as keyof typeof RULE_WORDS]}${r.saved === "project" ? " — saved to the project" : " for this session"}`)
|
||||
openMcpServer(c, server, `${TOOL}${tool}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/** A server's last error, every line of it, as a list to scroll. */
|
||||
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))))
|
||||
c.openDialog({
|
||||
title: `MCP · ${server} · the last error`,
|
||||
options: lines.map((l, i) => ({ label: l || " ", value: String(i) })),
|
||||
filter: false,
|
||||
hint: "↑↓ pgup/pgdn scroll · esc back",
|
||||
onBack: () => openMcpServer(c, server, `${ACTION}error`),
|
||||
onSelect: () => openMcpServer(c, server, `${ACTION}error`),
|
||||
})
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
const mcp = c.app.mcp
|
||||
const back = () => (o.menu ? openMcpServer(c, name) : undefined)
|
||||
if (action === "error") return openError(c, name)
|
||||
try {
|
||||
if (action === "reconnect" || action === "on") {
|
||||
c.flash(`MCP ${name}: connecting…`)
|
||||
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")
|
||||
} 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`)
|
||||
} else if (action === "auth") {
|
||||
const pasted = new Promise<string>((resolve) => pendingCodes.set(name, resolve))
|
||||
const s = await mcp.auth(
|
||||
name,
|
||||
(url) => c.view.info(`Sign in to ${name} at:\n${url}\n\nThe browser is sent back to this machine (127.0.0.1). If it cannot get here, copy the address it ends on and type: /mcp code ${name} <that address>`),
|
||||
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")
|
||||
// The sign-in page was read meanwhile: the menu is not put back over it.
|
||||
return c.refresh()
|
||||
} else if (action === "code") {
|
||||
const give = pendingCodes.get(name)
|
||||
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") {
|
||||
mcp.logout(name)
|
||||
c.view.info(`MCP ${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")
|
||||
}
|
||||
c.refresh()
|
||||
back()
|
||||
}
|
||||
@@ -540,7 +540,8 @@ test("MCP: a server's prompt is a /server:prompt command; /mcp lists the server;
|
||||
for (const line of t.frame().split("\n")) expect(Bun.stringWidth(line)).toBeLessThanOrEqual(80)
|
||||
await t.input.typeText("/mcp")
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("● fix local")).toBe(true)
|
||||
expect(await t.until("MCP servers — 1 of 1 connected")).toBe(true)
|
||||
expect(t.frame()).toContain("● fix ")
|
||||
}, 20_000)
|
||||
|
||||
test("MCP: a server's prompt cannot attach a file by naming it with @", async () => {
|
||||
|
||||
@@ -61,3 +61,188 @@ test("a notice with a level is drawn by the table: only a warning carries the wa
|
||||
expect(f).toContain("✗ it broke")
|
||||
expect(f).toContain("⚠ no level given")
|
||||
})
|
||||
|
||||
// ---- the /mcp menu ----
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs"
|
||||
import { expandSlash } from "../../src/session/commands.ts"
|
||||
import { mcpText } from "../../src/mcp/text.ts"
|
||||
import type { ServerState } from "../../src/mcp/index.ts"
|
||||
|
||||
/** A server put into the manager as if it had connected (no process): `tools` of them. */
|
||||
function fake(name: string, o: Partial<ServerState> & { toolCount?: number; source?: "global" | "project" } = {}): ServerState {
|
||||
const { toolCount = 2, source = "global", ...rest } = o
|
||||
return {
|
||||
name,
|
||||
cfg: { url: `https://example.org/${name}/mcp`, source } as never,
|
||||
status: "connected",
|
||||
tools: Array.from({ length: toolCount }, (_, i) => ({ name: `tool_${i}`, description: `Does thing ${i}.\nA second line about thing ${i}.`, inputSchema: {} })),
|
||||
prompts: [],
|
||||
resources: false,
|
||||
stderr: [],
|
||||
gen: 0,
|
||||
...rest,
|
||||
}
|
||||
}
|
||||
const put = (...servers: ServerState[]) => {
|
||||
for (const s of servers) t!.app.mcp.servers.set(s.name, s)
|
||||
}
|
||||
const widest = () => Math.max(...t!.frame().split("\n").map((l) => l.trimEnd().length))
|
||||
|
||||
test("/mcp with no servers says how to add one, in the menu — not a dump", async () => {
|
||||
t = await tui([])
|
||||
await t.input.typeText("/mcp")
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("MCP servers")).toBe(true)
|
||||
expect(t.frame()).toContain("No MCP servers are configured.")
|
||||
expect(t.frame()).toContain("esc close")
|
||||
t.input.pressEscape()
|
||||
await t.settle()
|
||||
expect(t.frame()).not.toContain("No MCP servers are configured.")
|
||||
})
|
||||
|
||||
test("/mcp: the servers with state and where they come from; enter opens one; a tool's rule is changed there; esc goes back", async () => {
|
||||
t = await tui([], { width: 100, height: 32 }, `mcp:\n${local("fix")}${broken("gone")}`)
|
||||
await t.app.mcpReady
|
||||
await t.settle(200)
|
||||
await t.input.typeText("/mcp")
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("MCP servers — 1 of 2 connected")).toBe(true)
|
||||
let f = t.frame()
|
||||
expect(f).toContain("Your config")
|
||||
expect(f).toMatch(/● fix {2}\d+ tools, \d+ prompts?/)
|
||||
expect(f).toMatch(/✗ gone {2}failed: /)
|
||||
t.input.pressEnter() // fix is first
|
||||
expect(await t.until("MCP · fix")).toBe(true)
|
||||
f = t.frame()
|
||||
expect(f).toContain("connected — ")
|
||||
expect(f).toContain("from your config")
|
||||
expect(f).toContain("Actions")
|
||||
expect(f).toContain("Reconnect")
|
||||
expect(f).toContain("Switch off")
|
||||
expect(f).not.toContain("Sign in") // a local server has no sign-in
|
||||
expect(f).toMatch(/Tools \(\d+\)/)
|
||||
expect(f).toContain("esc back")
|
||||
// Type to search the tools, then open the one found.
|
||||
await t.input.typeText("echo")
|
||||
await t.settle()
|
||||
expect(t.frame()).toMatch(/○ echo {2}asks · read-only · Repeat the text/)
|
||||
expect(t.frame()).toContain("mcp__fix__echo") // the highlighted tool's own name and description
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("fix · echo")).toBe(true)
|
||||
expect(t.frame()).toContain("● Ask each time")
|
||||
t.input.pressArrow("down")
|
||||
t.input.pressEnter() // Always allow
|
||||
expect(await t.until("MCP · fix")).toBe(true)
|
||||
expect(t.app.engine.ruleFor("mcp__fix__echo")).toBe("allow")
|
||||
await t.input.typeText("echo")
|
||||
await t.settle()
|
||||
expect(t.frame()).toMatch(/● echo {2}always allowed/)
|
||||
// Esc: back to the list, on the server that was open; esc again closes.
|
||||
t.input.pressEscape()
|
||||
expect(await t.until("MCP servers — 1 of 2 connected")).toBe(true)
|
||||
t.input.pressEscape()
|
||||
await t.settle()
|
||||
expect(t.frame()).not.toContain("MCP servers —")
|
||||
})
|
||||
|
||||
test("/mcp <name> opens that server; a failed one offers its last error in full; an unknown name is said", async () => {
|
||||
t = await tui([], { width: 100, height: 32 }, `mcp:\n${broken("gone")}`)
|
||||
await t.app.mcpReady
|
||||
await t.settle(200)
|
||||
await t.input.typeText("/mcp gone")
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("MCP · gone")).toBe(true)
|
||||
expect(t.frame()).toContain("failed: ")
|
||||
expect(t.frame()).toContain("Connect again")
|
||||
expect(t.frame()).toContain("Read the last error in full")
|
||||
for (let i = 0; i < 2; i++) t.input.pressArrow("down")
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("MCP · gone · the last error")).toBe(true)
|
||||
t.input.pressEscape()
|
||||
expect(await t.until("Connect again")).toBe(true)
|
||||
t.input.pressEscape()
|
||||
expect(await t.until("MCP servers — 0 of 1 connected")).toBe(true)
|
||||
t.input.pressEscape()
|
||||
await t.settle()
|
||||
await t.input.typeText("/mcp nosuch")
|
||||
t.input.pressEnter()
|
||||
expect(await t.until('no MCP server "nosuch" — gone')).toBe(true)
|
||||
})
|
||||
|
||||
test("/mcp at 60 columns, with 30 servers and a server of 200 tools: nothing wider than the screen, the list scrolls, search finds", async () => {
|
||||
t = await tui([], { width: 60, height: 24 })
|
||||
put(...Array.from({ length: 29 }, (_, i) => fake(`server-${String(i).padStart(2, "0")}`, i % 7 === 3 ? { status: "failed", error: "connection refused by the far side, which is a long reason to give", tools: [] } : i % 5 === 0 ? { status: "needs_auth", tools: [] } : {})), fake("big", { toolCount: 200, source: "project" }))
|
||||
t.app.mcp.tools()
|
||||
await t.input.typeText("/mcp")
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("MCP servers — ")).toBe(true)
|
||||
expect(widest()).toBeLessThanOrEqual(60)
|
||||
expect(t.frame()).toContain("This project")
|
||||
expect(t.frame()).toMatch(/· 1\/30/) // where the cursor is, of how many
|
||||
expect(t.frame()).toContain("type to filter")
|
||||
await t.input.typeText("big")
|
||||
await t.settle()
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("MCP · big")).toBe(true)
|
||||
expect(widest()).toBeLessThanOrEqual(60)
|
||||
expect(t.frame()).toContain("Tools (200)")
|
||||
// The end of a long list is a keypress away, and the footer says where that is.
|
||||
t.input.pressKey("END")
|
||||
await t.settle()
|
||||
expect(t.frame()).toContain("tool_199")
|
||||
expect(t.frame()).toMatch(/20\d\/20\d/)
|
||||
expect(widest()).toBeLessThanOrEqual(60)
|
||||
for (const ch of "tool_137") t.input.pressKey(ch)
|
||||
await t.settle()
|
||||
expect(t.frame()).toContain("tool_137")
|
||||
expect(t.frame()).toContain("Does thing 137.")
|
||||
expect(t.frame()).not.toContain("tool_138")
|
||||
expect(widest()).toBeLessThanOrEqual(60)
|
||||
})
|
||||
|
||||
test("a rule the person's own config makes stricter is not loosened from the menu; a remote server offers sign-in", async () => {
|
||||
t = await tui([], { width: 100, height: 30 }, "permission:\n mcp__web__tool_0: deny\n")
|
||||
put(fake("web", { status: "needs_auth", tools: [] }))
|
||||
await t.input.typeText("/mcp web")
|
||||
t.input.pressEnter()
|
||||
expect(await t.until("MCP · web")).toBe(true)
|
||||
expect(t.frame()).toContain("needs sign-in")
|
||||
expect(t.frame()).toContain("Sign in")
|
||||
expect(t.frame()).toContain("Sign out")
|
||||
expect(t.frame()).toContain("https://example.org/web/mcp")
|
||||
t.input.pressEscape()
|
||||
await t.settle()
|
||||
t.input.pressEscape()
|
||||
await t.settle()
|
||||
expect(t.app.engine.setRule({ permission: "mcp__web__tool_0", pattern: "*", action: "allow" })).toMatchObject({ refused: { action: "deny", source: "global" } })
|
||||
expect(t.app.engine.ruleFor("mcp__web__tool_0")).toBe("deny")
|
||||
// Stricter is always possible, and for an untrusted project it stays in the session.
|
||||
expect(t.app.engine.setRule({ permission: "mcp__web__tool_1", pattern: "*", action: "deny" })).toEqual({ saved: "session" })
|
||||
expect(existsSync(join(t.cwd, ".agent", "config.yaml"))).toBe(false)
|
||||
})
|
||||
|
||||
test("without a menu — over the link, in lembas run — /mcp is a plain table, and /mcp <name> one server's tools", async () => {
|
||||
t = await tui([], { width: 100, height: 30 }, "permission:\n mcp__alpha__tool_1: allow\n")
|
||||
put(fake("alpha"), fake("beta", { status: "failed", error: "connect ECONNREFUSED\nat the second line", tools: [] }), fake("lembas-library", { toolCount: 1 }))
|
||||
t.app.mcp.tools()
|
||||
const all = expandSlash(t.app, "/mcp")
|
||||
expect(all).toMatchObject({ kind: "message", name: "mcp" })
|
||||
const text = (all as { text: string }).text
|
||||
expect(text.split("\n")).toEqual([
|
||||
"MCP servers:",
|
||||
" alpha connected — 2 tools (your config)",
|
||||
" beta failed: connect ECONNREFUSED (your config)",
|
||||
" lembas-library connected — 1 tool (the LLeMbas server's library)",
|
||||
"",
|
||||
"/mcp <name> lists one server's tools. A tool asks before it runs unless a permission rule allows it.",
|
||||
])
|
||||
const one = (expandSlash(t.app, "/mcp alpha") as { text: string }).text
|
||||
expect(one).toContain("alpha — connected — 2 tools")
|
||||
expect(one).toContain(" mcp__alpha__tool_0 — asks — Does thing 0.")
|
||||
expect(one).toContain(" mcp__alpha__tool_1 — always allowed — Does thing 1.")
|
||||
expect((expandSlash(t.app, "/mcp beta") as { text: string }).text).toContain("at the second line")
|
||||
expect((expandSlash(t.app, "/mcp off alpha") as { text: string }).text).toContain("done at the terminal")
|
||||
expect(mcpText(t.app.mcp, "nosuch")).toContain('No MCP server "nosuch"')
|
||||
expect(readFileSync(join(import.meta.dir, "..", "..", "src", "mcp", "text.ts"), "utf8")).not.toMatch(/\.lan\b/)
|
||||
})
|
||||
Reference in new issue
Block a user