|
| 1 | +import type { McpManager, McpPromptRef } from "../mcp/manager.js"; |
| 2 | +import type { McpContentBlock } from "../mcp/protocol.js"; |
| 3 | +import type { CommandRegistry } from "./registry.js"; |
| 4 | +import type { Command } from "./types.js"; |
| 5 | + |
| 6 | +/** MCP prompt → slash command name: `mcp__<server>__<prompt>`, mirroring tool naming. */ |
| 7 | +export function mcpPromptCommandName(server: string, prompt: string): string { |
| 8 | + return `mcp__${server}__${prompt}`; |
| 9 | +} |
| 10 | + |
| 11 | +const VALID = /^[a-z0-9][a-z0-9_-]*$/i; |
| 12 | + |
| 13 | +/** |
| 14 | + * Bridge connected MCP prompts into slash commands. `/mcp__<server>__<name> |
| 15 | + * [args]` calls prompts/get on the server, flattens the returned messages |
| 16 | + * into a single prompt, and submits it to the agent. Arguments are parsed |
| 17 | + * positionally against the prompt's declared `arguments`, or as |
| 18 | + * `key=value` pairs. Names that collide with a built-in or are unsafe for |
| 19 | + * a command are skipped. |
| 20 | + */ |
| 21 | +export function buildMcpPromptCommands( |
| 22 | + prompts: readonly McpPromptRef[], |
| 23 | + mcp: McpManager, |
| 24 | + registry: CommandRegistry, |
| 25 | +): Command[] { |
| 26 | + const out: Command[] = []; |
| 27 | + for (const { server, descriptor } of prompts) { |
| 28 | + const name = mcpPromptCommandName(server, descriptor.name); |
| 29 | + if (!VALID.test(name) || registry.get(name)) continue; |
| 30 | + out.push({ |
| 31 | + name, |
| 32 | + description: descriptor.description |
| 33 | + ? `${descriptor.description} (MCP prompt)` |
| 34 | + : `MCP prompt ${descriptor.name}.`, |
| 35 | + handler: (args, ctx) => { |
| 36 | + if (ctx.state.status !== "idle" && ctx.state.status !== "error" && ctx.state.status !== "aborted") { |
| 37 | + ctx.emit(`agent is busy — run /${name} after this turn settles.`); |
| 38 | + return { handled: true }; |
| 39 | + } |
| 40 | + const parsed = parseArgs(args, descriptor.arguments); |
| 41 | + void mcp |
| 42 | + .getPrompt(server, descriptor.name, parsed) |
| 43 | + .then((result) => { |
| 44 | + const text = flattenPromptMessages(result.messages); |
| 45 | + if (!text.trim()) { |
| 46 | + ctx.emit(`MCP prompt "${descriptor.name}" returned nothing.`); |
| 47 | + return; |
| 48 | + } |
| 49 | + return ctx.bundle.submitUserPrompt(text).then((r) => { |
| 50 | + if (!r.submitted) ctx.emit(`prompt blocked: ${r.reason ?? "refused by hook"}`); |
| 51 | + else if (r.error) ctx.emit(`agent error: ${r.error}`); |
| 52 | + }); |
| 53 | + }) |
| 54 | + .catch((err) => ctx.emit(`MCP prompt failed: ${err instanceof Error ? err.message : String(err)}`)); |
| 55 | + return { handled: true }; |
| 56 | + }, |
| 57 | + }); |
| 58 | + } |
| 59 | + return out; |
| 60 | +} |
| 61 | + |
| 62 | +/** Map user args to the prompt's declared arguments — `key=value` pairs first, else positional. */ |
| 63 | +export function parseArgs(raw: string, declared: McpPromptRef["descriptor"]["arguments"]): Record<string, string> { |
| 64 | + const trimmed = raw.trim(); |
| 65 | + if (!trimmed) return {}; |
| 66 | + const tokens = trimmed.split(/\s+/); |
| 67 | + const names = (declared ?? []).map((a) => a.name); |
| 68 | + |
| 69 | + // All tokens look like key=value → keyed. |
| 70 | + if (tokens.every((t) => /^[^=\s]+=/.test(t))) { |
| 71 | + const out: Record<string, string> = {}; |
| 72 | + for (const t of tokens) { |
| 73 | + const eq = t.indexOf("="); |
| 74 | + out[t.slice(0, eq)] = t.slice(eq + 1); |
| 75 | + } |
| 76 | + return out; |
| 77 | + } |
| 78 | + |
| 79 | + // Positional against declared names; a single undeclared arg → first slot. |
| 80 | + if (names.length === 0) return { input: trimmed }; |
| 81 | + const out: Record<string, string> = {}; |
| 82 | + names.forEach((n, i) => { |
| 83 | + if (i < names.length - 1) { |
| 84 | + if (tokens[i] !== undefined) out[n] = tokens[i]; |
| 85 | + } else { |
| 86 | + // Last declared arg soaks up the remaining tokens. |
| 87 | + const rest = tokens.slice(i).join(" "); |
| 88 | + if (rest) out[n] = rest; |
| 89 | + } |
| 90 | + }); |
| 91 | + return out; |
| 92 | +} |
| 93 | + |
| 94 | +/** Flatten prompt messages into a single text prompt; non-user roles are labeled. */ |
| 95 | +export function flattenPromptMessages( |
| 96 | + messages: Array<{ role: string; content: string | McpContentBlock | McpContentBlock[] }> | undefined, |
| 97 | +): string { |
| 98 | + if (!Array.isArray(messages)) return ""; |
| 99 | + const parts: string[] = []; |
| 100 | + for (const m of messages) { |
| 101 | + const text = contentToText(m.content); |
| 102 | + if (!text) continue; |
| 103 | + parts.push(m.role === "user" ? text : `[${m.role}]\n${text}`); |
| 104 | + } |
| 105 | + return parts.join("\n\n"); |
| 106 | +} |
| 107 | + |
| 108 | +function contentToText(content: string | McpContentBlock | McpContentBlock[]): string { |
| 109 | + if (typeof content === "string") return content; |
| 110 | + const blocks = Array.isArray(content) ? content : [content]; |
| 111 | + return blocks |
| 112 | + .map((b) => (b.type === "text" && typeof b.text === "string" ? b.text : `[${b.type} content]`)) |
| 113 | + .join("\n"); |
| 114 | +} |
0 commit comments