diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1213d36d..d1d55d11 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -99,6 +99,21 @@ suite detects the missing binary, prints a clear skip message, and exits 0 logical units; a PR is a series of reviewed, individually sensible commits, not one giant diff. +## Release workflow + +- `package.json`'s `version` is the single source of truth for release + identity. `docker/Dockerfile` documents the image tag policy: images are + published to `ghcr.io/capsize-games/headlesscode`, tagged with the exact + `package.json` version plus a floating `latest` (versioned tag for + reproducibility, `latest` for local experimentation only). +- Cut a release by pushing a `v` tag whose version matches + `package.json` exactly — `.github/workflows/publish.yml` requires the + tag's `package.json` version to match the pushed `v*` tag. Do not retag or + move an existing tag. +- `npm run check-version` verifies every tracked in-repo image/tag reference + matches `package.json` (historical examples stay allow-listed with reasons + in `scripts/check-version-sync.mjs`). It must pass before tagging. + ## Code of conduct All contributors and maintainers are expected to follow our diff --git a/docs/mcp.md b/docs/mcp.md index c17a4ed4..deec7dba 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -31,19 +31,27 @@ other servers; failures are included in the system prompt and logger. Tool errors are returned as tool errors. Server clients are closed when the session ends, including setup-error paths. -Supported: tool calls (per-server function tools) and resources. +Supported: tool calls (per-server function tools), resources, and prompts. `mcp_list_resources` lists the resources one connected server advertises; `access_mcp_resource` reads a single resource URI through a named connected -server (at most 100 resources per server). Both are exposed to modes in the -`mcp` tool group, respecting `allowedMcpServers`, and are registered only for -unrestricted sessions (an explicit `tools` list never gains them). Safety -bounds: the URI is only ever resolved BY the named configured server — naming -an unconnected server fails instead of reaching any other server or host, and -bare paths or overlong URIs are rejected. Every read is truncated to 64K -characters with the cut named. Server clients (tools and resources alike) are -closed when the session ends, including setup-error paths. +server (at most 100 resources per server). `mcp_list_prompts` lists the +prompts one connected server advertises (name, description, arguments — +metadata only, never template text); `mcp_get_prompt` renders one prompt +through a named connected server with string arguments given as a JSON +object (at most 100 prompts per server). All four are exposed to modes in +the `mcp` tool group, respecting `allowedMcpServers`, and are registered +only for unrestricted sessions (an explicit `tools` list never gains them). +Prompt templates are a read-only discovery surface: the model sees metadata +first and fetches a full template only on explicit request — prompt text is +never spliced into the system prompt automatically. Safety +bounds: the server name is the allow-list everywhere — naming +an unconnected server fails instead of reaching any other server or host; prompt +argument values must be strings, and required arguments are validated +before any server call. Every resource read and every rendered prompt is truncated to 64K +characters with the cut named. Server clients (tools, resources, and +prompts alike) are closed when the session ends, including setup-error paths. -MCP prompts, OAuth setup, per-tool approval, and interactive controls for +MCP OAuth setup, per-tool approval, and interactive controls for enabling servers are not implemented. Configured server tools may read or change data according to that server's capabilities. HeadlessCode's own default command execution also runs with the diff --git a/package.json b/package.json index d2b75cf3..689c8d43 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "coverage": "node scripts/coverage.mjs", "check-standards": "node scripts/check-code-standards.mjs", "check-architecture": "tsx scripts/check-architecture.mjs", + "check-version": "node scripts/check-version-sync.mjs", "prepublishOnly": "npm ci && npm test" }, "dependencies": { diff --git a/scripts/check-version-sync.mjs b/scripts/check-version-sync.mjs new file mode 100644 index 00000000..a08d6cc4 --- /dev/null +++ b/scripts/check-version-sync.mjs @@ -0,0 +1,116 @@ +// Version-sync check (#190): the package.json version is the single source +// of truth for release identity. docker/Dockerfile documents tagging images +// with the exact package.json version plus a floating `latest`, but nothing +// enforced it, so pins drifted silently (1.9.16 vs npm 1.3.0 vs image +// 0.1.0). This script fails when any TRACKED in-repo image/tag reference +// names a version that does not match package.json, unless the reference is +// an explicit historical/example allow-list entry below. +// +// Usage: node scripts/check-version-sync.mjs [--root ] +// Exit 0 when in sync; exit 1 naming the offending file(s). No network: +// published npm/ghcr lag between releases is expected and not checked. +import { execFileSync } from "node:child_process" +import fs from "node:fs" +import path from "node:path" +import { fileURLToPath } from "node:url" + +const repoRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url))) + +function argValue(flag) { + const i = process.argv.indexOf(flag) + return i >= 0 ? process.argv[i + 1] : undefined +} + +const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/ + +const IMAGE_TAG = /(?:headlesscode|ghcr\.io\/capsize-games\/headlesscode):([A-Za-z0-9_][A-Za-z0-9_.-]*)/g +const TAG_VERSION_LIKE = /^v?\d+\.\d+\.\d+/ + +// Tracked references that intentionally name a different version, each with +// a reason. Tightly scoped (file + the exact pinned text found in that +// file), so a NEW stale pin elsewhere still fails. +const ALLOW_LIST = [ + { + file: "docker/Dockerfile", + match: "headlesscode:0.1.0", + reason: "illustrative build example + version-policy doc, not a pinned release tag", + }, + { + file: "scripts/docker-smoke.sh", + match: 'TAG="${1:-headlesscode:0.1.0}"', + reason: "smoke-script default local tag; caller may override via argv", + }, +] + +// The checker (and its self-test) carry allow-listed pin strings as data, +// so they are never scanned as candidate pins themselves. +const SELF_FILES = new Set(["scripts/check-version-sync.mjs", "scripts/check-version-sync.test.mjs"]) + +function isAllowed(file, fileText) { + return ALLOW_LIST.some((entry) => entry.file === file && fileText.includes(entry.match)) +} + +function listTrackedFiles(root) { + try { + const out = execFileSync("git", ["ls-files", "-z"], { cwd: root, encoding: "utf8" }) + return out.split("\0").filter(Boolean) + } catch { + return walkFiles(root) + } +} + +function walkFiles(root) { + const out = [] + const walk = (dir) => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.name === "node_modules" || entry.name === ".git") continue + const full = path.join(dir, entry.name) + if (entry.isDirectory()) walk(full) + else if (entry.isFile()) out.push(path.relative(root, full)) + } + } + walk(root) + return out +} + +function checkTree(root) { + const pkgRaw = fs.readFileSync(path.join(root, "package.json"), "utf8") + const pkg = JSON.parse(pkgRaw) + const version = pkg.version + if (typeof version !== "string" || !SEMVER.test(version)) { + return { ok: false, errors: [`package.json version ${JSON.stringify(version)} is not valid semver`] } + } + const errors = [] + for (const file of listTrackedFiles(root)) { + if (file.startsWith(".git/") || file.includes("node_modules")) continue + if (SELF_FILES.has(file)) continue + let text + try { + text = fs.readFileSync(path.join(root, file), "utf8") + } catch { + continue + } + if (text.includes("\0")) continue + for (const match of text.matchAll(IMAGE_TAG)) { + const tag = match[1] + if (!TAG_VERSION_LIKE.test(tag)) continue + const bare = tag.startsWith("v") ? tag.slice(1) : tag + if (bare === version) continue + if (isAllowed(file, text)) continue + errors.push(`${file}: image tag '${match[0]}' does not match package.json version ${version}`) + } + } + return { ok: errors.length === 0, errors, version } +} + +function main() { + const root = path.resolve(repoRoot, argValue("--root") ?? ".") + const { ok, errors, version } = checkTree(root) + if (!ok) { + for (const error of errors) process.stdout.write(`version-sync: ${error}\n`) + process.exit(1) + } + process.stdout.write(`version-sync: ok (package.json ${version})\n`) +} + +main() diff --git a/scripts/check-version-sync.test.mjs b/scripts/check-version-sync.test.mjs new file mode 100644 index 00000000..5ac69d3d --- /dev/null +++ b/scripts/check-version-sync.test.mjs @@ -0,0 +1,84 @@ +// Self-test for scripts/check-version-sync.mjs (#190): builds fixture trees +// with a copied package.json + scripts/check-version-sync.mjs layout, and +// asserts happy/sad/bad behavior. Exit 1 on mismatch. Pure node, no network. +import { execFileSync } from "node:child_process" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { fileURLToPath } from "node:url" + +const repoRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url))) + +function fail(message) { + console.error(`FAIL version-sync-selftest: ${message}`) + process.exit(1) +} + +function run(root, extraArgs = []) { + try { + const out = execFileSync("node", ["scripts/check-version-sync.mjs", "--root", root, ...extraArgs], { + cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], + }) + return { status: 0, out } + } catch (error) { + return { status: error.status ?? 1, out: `${error.stdout ?? ""}${error.stderr ?? ""}` } + } +} + +function fixtureTree(files) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "headlesscode-version-sync-")) + fs.mkdirSync(path.join(dir, "scripts"), { recursive: true }) + fs.copyFileSync( + path.join(repoRoot, "scripts", "check-version-sync.mjs"), + path.join(dir, "scripts", "check-version-sync.mjs"), + ) + for (const [name, content] of Object.entries(files)) { + const full = path.join(dir, name) + fs.mkdirSync(path.dirname(full), { recursive: true }) + fs.writeFileSync(full, content) + } + return dir +} + +// Happy: current tree passes. +const happy = run(repoRoot) +if (happy.status !== 0) fail(`current tree failed:\n${happy.out}`) + +// Sad: fixture with a mismatched pin and no allow-list entry fails naming the file. +const sadDir = fixtureTree({ + "package.json": JSON.stringify({ version: "9.9.9" }), + "deploy/compose.yml": "image: ghcr.io/capsize-games/headlesscode:1.2.3\n", + "docker/Dockerfile": "# -t headlesscode:0.1.0\n", +}) +try { + const sad = run(sadDir) + if (sad.status !== 1) fail(`mismatched-pin fixture exited ${sad.status}, want 1`) + if (!sad.out.includes("deploy/compose.yml")) fail(`mismatch did not name the file:\n${sad.out}`) +} finally { + fs.rmSync(sadDir, { recursive: true, force: true }) +} + +// Sad (bump simulation): the same fixture passes when the pin matches. +const bumpDir = fixtureTree({ + "package.json": JSON.stringify({ version: "1.2.3" }), + "deploy/compose.yml": "image: ghcr.io/capsize-games/headlesscode:1.2.3\n", +}) +try { + const bumped = run(bumpDir) + if (bumped.status !== 0) fail(`matching-pin fixture failed:\n${bumped.out}`) +} finally { + fs.rmSync(bumpDir, { recursive: true, force: true }) +} + +// Bad: malformed semver fails with a clear message, not a stack. +const badDir = fixtureTree({ "package.json": JSON.stringify({ version: "1.9" }) }) +try { + const bad = run(badDir) + if (bad.status !== 1) fail(`malformed-semver fixture exited ${bad.status}, want 1`) + if (!bad.out.includes("not valid semver")) fail(`malformed semver lacked a clear message:\n${bad.out}`) + if (bad.out.includes("at ") && bad.out.includes("node:internal")) fail(`malformed semver leaked a stack:\n${bad.out}`) +} finally { + fs.rmSync(badDir, { recursive: true, force: true }) +} + +console.log(" ok version-sync-selftest: current tree passes, mismatch fails naming the file, malformed semver is clean") diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index ca2a6045..2ba18b9c 100755 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -62,7 +62,7 @@ function removeOwnedTempRoot(root) { * remembered to invoke it separately — the only DIRECT check that the * vendored Zoo Code prompt builder still imports and runs headlessly. */ -const EXTRA_FILES = ["scripts/check-page-script.mjs", "scripts/check-tmpdir-project-store.mjs", "scripts/coverage.test.mjs", "scripts/check-code-standards.test.mjs", "scripts/check-architecture.test.mjs", "src/vendor/tests/smoke.ts"] +const EXTRA_FILES = ["scripts/check-page-script.mjs", "scripts/check-tmpdir-project-store.mjs", "scripts/coverage.test.mjs", "scripts/check-code-standards.test.mjs", "scripts/check-architecture.test.mjs", "scripts/check-version-sync.test.mjs", "src/vendor/tests/smoke.ts"] function findTestFiles(dir) { const found = [] diff --git a/src/engine/__tests__/mcp-prompts.test.ts b/src/engine/__tests__/mcp-prompts.test.ts new file mode 100644 index 00000000..4bfa2839 --- /dev/null +++ b/src/engine/__tests__/mcp-prompts.test.ts @@ -0,0 +1,277 @@ +/** + * Unit tests for src/engine/mcp-prompts.ts (MCP prompts, #193). + * + * Transport is stubbed: the hub surface is structural + * (McpPromptHub = Pick), so a plain object records calls + * and returns canned prompts/rendered messages. Live-server coverage of + * McpHub.listPrompts/getPrompt against a real stdio server exercises the + * pinned SDK's prompts/list + prompts/get round trip. + * + * Plain assert-based script (no framework, no network), run via + * `npm test` -> `tsx src/engine/__tests__/mcp-prompts.test.ts`. + */ +import assert from "node:assert/strict" + +import type { ModeConfig } from "../../vendor/zoo-code/types/index.js" +import type { McpPromptLike } from "../../vendor/zoo-code/src/services/mcp/McpHub.js" +import type { ChatTool, ToolContext } from "../types.js" +import { + MCP_GET_PROMPT_TOOL, + MCP_GET_PROMPT_TOOL_NAME, + MCP_LIST_PROMPTS_TOOL, + MCP_LIST_PROMPTS_TOOL_NAME, + MAX_MCP_PROMPT_TEXT_CHARS, + mcpPromptHandlers, + mcpPromptToolsForMode, + truncateMcpPromptText, + type McpPromptHub, +} from "../mcp-prompts.js" +import { runMain } from "../../test-runner.js" + +function testMode(groups: ModeConfig["groups"], allowedMcpServers?: string[]): ModeConfig { + return { + slug: "test-mode", + name: "Test Mode", + roleDefinition: "Test role.", + groups, + ...(allowedMcpServers === undefined ? {} : { allowedMcpServers }), + } +} + +interface StubCalls { + listed: string[] + got: Array<{ server: string; name: string }> +} + +function stubHub(options: { + servers?: Array<{ name: string; prompts?: McpPromptLike[] }> + listImpl?: (server: string) => McpPromptLike[] | Promise + getImpl?: (server: string, name: string, promptArgs: Record) => string | Promise +}): { hub: McpPromptHub; calls: StubCalls } { + const calls: StubCalls = { listed: [], got: [] } + const servers = options.servers ?? [ + { name: "docs", prompts: [{ name: "greet", description: "Greet someone", arguments: [{ name: "name", required: true }] }] }, + ] + const hub: McpPromptHub = { + getServers: () => servers.map((server) => ({ name: server.name, prompts: server.prompts })), + listPrompts: async (server: string) => { + calls.listed.push(server) + if (options.listImpl) return options.listImpl(server) + const found = servers.find((candidate) => candidate.name === server) + if (!found) throw new Error(`MCP prompt server is unavailable: ${server}`) + return found.prompts ?? [] + }, + getPrompt: async (server: string, name: string, promptArgs: Record) => { + calls.got.push({ server, name }) + if (options.getImpl) return options.getImpl(server, name, promptArgs) + const found = servers.find((candidate) => candidate.name === server) + if (!found) throw new Error(`MCP prompt server is unavailable: ${server}`) + return JSON.stringify([{ role: "user", content: { type: "text", text: `hello ${promptArgs["name"] ?? "?"}` } }]) + }, + } + return { hub, calls } +} + +function testContext(): ToolContext { + return { signal: undefined } as unknown as ToolContext +} + +function handlerByName(hub: McpPromptHub, name: string) { + const entry = mcpPromptHandlers(hub).find((candidate) => candidate.name === name) + assert.ok(entry, `expected a ${name} handler`) + return entry.handler +} + +async function testNoHubAdvertisesNothing(): Promise { + assert.deepEqual(mcpPromptToolsForMode(undefined, testMode(["mcp"])), []) +} + +async function testNonMcpModeAdvertisesNothing(): Promise { + const { hub } = stubHub({}) + assert.deepEqual(mcpPromptToolsForMode(hub, testMode(["read"])), []) +} + +async function testMcpModeAdvertisesBothTools(): Promise { + const { hub } = stubHub({}) + const tools = mcpPromptToolsForMode(hub, testMode(["mcp"])) + const names = tools.map((tool) => tool.function.name) + assert.deepEqual(names, [MCP_LIST_PROMPTS_TOOL_NAME, MCP_GET_PROMPT_TOOL_NAME]) +} + +async function testNoPromptServersAdvertisesNothing(): Promise { + const { hub } = stubHub({ servers: [{ name: "tools-only", prompts: [] }] }) + assert.deepEqual(mcpPromptToolsForMode(hub, testMode(["mcp"])), []) +} + +async function testAllowlistFiltersPromptServers(): Promise { + const { hub } = stubHub({}) + assert.deepEqual(mcpPromptToolsForMode(hub, testMode(["mcp"], ["other"])), []) + const tools = mcpPromptToolsForMode(hub, testMode(["mcp"], ["docs"])) + assert.equal(tools.length, 2) +} + +async function testAdvertisedSchemasAreStrictCompliant(): Promise { + const tools: ChatTool[] = [MCP_LIST_PROMPTS_TOOL, MCP_GET_PROMPT_TOOL] + for (const tool of tools) { + assert.equal(tool.type, "function") + if (!tool.function.strict) continue + const params = tool.function.parameters ?? {} + const properties = Object.keys((params.properties as Record | undefined) ?? {}) + const required = new Set((params.required as string[] | undefined) ?? []) + for (const property of properties) { + assert.ok(required.has(property), `${tool.function.name} is strict:true but '${property}' is not required`) + } + } +} + +async function testListReturnsMetadataOnly(): Promise { + const { hub } = stubHub({}) + const result = await handlerByName(hub, MCP_LIST_PROMPTS_TOOL_NAME)({ server_name: "docs" }, testContext()) + assert.equal(result.isError, false) + assert.deepEqual(JSON.parse(result.content), [ + { name: "greet", description: "Greet someone", arguments: [{ name: "name", required: true }] }, + ]) +} + +async function testListOfPromptlessServerIsEmpty(): Promise { + const { hub } = stubHub({ servers: [{ name: "bare", prompts: [] }] }) + const result = await handlerByName(hub, MCP_LIST_PROMPTS_TOOL_NAME)({ server_name: "bare" }, testContext()) + assert.equal(result.isError, false) + assert.deepEqual(JSON.parse(result.content), []) +} + +async function testListUnknownServerIsError(): Promise { + const { hub, calls } = stubHub({}) + const result = await handlerByName(hub, MCP_LIST_PROMPTS_TOOL_NAME)({ server_name: "ghost" }, testContext()) + assert.equal(result.isError, true) + assert.match(result.content, /MCP prompt server is unavailable: ghost/) + assert.deepEqual(calls.listed, ["ghost"]) +} + +async function testListMissingServerNameIsError(): Promise { + const { hub, calls } = stubHub({}) + const result = await handlerByName(hub, MCP_LIST_PROMPTS_TOOL_NAME)({}, testContext()) + assert.equal(result.isError, true) + assert.match(result.content, /server_name/) + assert.deepEqual(calls.listed, []) +} + +async function testGetHappyPath(): Promise { + const { hub, calls } = stubHub({}) + const result = await handlerByName(hub, MCP_GET_PROMPT_TOOL_NAME)( + { server_name: "docs", name: "greet", arguments: JSON.stringify({ name: "bob" }) }, + testContext(), + ) + assert.equal(result.isError, false) + assert.match(result.content, /hello bob/) + assert.deepEqual(calls.got, [{ server: "docs", name: "greet" }]) +} + +async function testGetMissingNameIsValidationError(): Promise { + const { hub, calls } = stubHub({}) + const result = await handlerByName(hub, MCP_GET_PROMPT_TOOL_NAME)( + { server_name: "docs", arguments: JSON.stringify({ name: "bob" }) }, + testContext(), + ) + assert.equal(result.isError, true) + assert.match(result.content, /'name' must be a non-empty string/) + // Validated locally — no server call was made. + assert.deepEqual(calls.got, []) +} + +async function testGetMalformedArgumentsIsValidationError(): Promise { + const { hub, calls } = stubHub({}) + for (const bad of ["not-json", "[1,2]", JSON.stringify({ name: 42 })]) { + const result = await handlerByName(hub, MCP_GET_PROMPT_TOOL_NAME)( + { server_name: "docs", name: "greet", arguments: bad }, + testContext(), + ) + assert.equal(result.isError, true, `expected '${bad}' to be rejected`) + assert.match(result.content, /[Aa]rgument/) + } + assert.deepEqual(calls.got, []) +} + +async function testGetUnknownServerNeverReachesAnotherServer(): Promise { + const { hub, calls } = stubHub({}) + const result = await handlerByName(hub, MCP_GET_PROMPT_TOOL_NAME)( + { server_name: "ghost", name: "greet", arguments: JSON.stringify({ name: "bob" }) }, + testContext(), + ) + assert.equal(result.isError, true) + assert.match(result.content, /MCP prompt server is unavailable: ghost/) + assert.deepEqual(calls.got, [{ server: "ghost", name: "greet" }]) +} + +async function testGetMapsServerErrorsVerbatim(): Promise { + const { hub } = stubHub({ + getImpl: () => { + throw new Error("Missing required argument: name") + }, + }) + const result = await handlerByName(hub, MCP_GET_PROMPT_TOOL_NAME)( + { server_name: "docs", name: "greet", arguments: JSON.stringify({ name: "bob" }) }, + testContext(), + ) + assert.equal(result.isError, true) + assert.equal(result.content, "[MCP error] Missing required argument: name") +} + +async function testGetTruncatesOversizedResult(): Promise { + const long = "x".repeat(MAX_MCP_PROMPT_TEXT_CHARS + 100) + const { hub } = stubHub({ getImpl: () => long }) + const result = await handlerByName(hub, MCP_GET_PROMPT_TOOL_NAME)( + { server_name: "docs", name: "greet", arguments: JSON.stringify({ name: "bob" }) }, + testContext(), + ) + assert.equal(result.isError, false) + assert.ok(result.content.length < long.length, "expected truncation") + assert.match(result.content, /truncated: showing/) + assert.match(result.content, new RegExp(`${MAX_MCP_PROMPT_TEXT_CHARS} of ${long.length} chars`)) +} + +async function testGetHandlesMalformedServerResponse(): Promise { + const { hub } = stubHub({ + // A server that returns garbage instead of throwing: the tool must + // surface a clean error and leave the session running, not crash. + getImpl: () => { + throw new SyntaxError("Unexpected token < in JSON") + }, + }) + const result = await handlerByName(hub, MCP_GET_PROMPT_TOOL_NAME)( + { server_name: "docs", name: "greet", arguments: JSON.stringify({ name: "bob" }) }, + testContext(), + ) + assert.equal(result.isError, true) + assert.equal(result.content, "[MCP error] Unexpected token < in JSON") +} + +async function testTruncateHelperKeepsShortText(): Promise { + assert.equal(truncateMcpPromptText("short"), "short") + assert.equal(truncateMcpPromptText("x".repeat(MAX_MCP_PROMPT_TEXT_CHARS)).length, MAX_MCP_PROMPT_TEXT_CHARS) + const truncated = truncateMcpPromptText("y".repeat(MAX_MCP_PROMPT_TEXT_CHARS + 1)) + assert.ok(truncated.endsWith(`…[truncated: showing ${MAX_MCP_PROMPT_TEXT_CHARS} of ${MAX_MCP_PROMPT_TEXT_CHARS + 1} chars]`)) +} + +const tests = [ + ["prompts: no hub advertises nothing", testNoHubAdvertisesNothing], + ["prompts: non-mcp mode advertises nothing", testNonMcpModeAdvertisesNothing], + ["prompts: mcp mode advertises list + get tools", testMcpModeAdvertisesBothTools], + ["prompts: no prompt servers advertises nothing", testNoPromptServersAdvertisesNothing], + ["prompts: server allowlist filters prompt servers", testAllowlistFiltersPromptServers], + ["prompts: advertised schemas are strict-compliant", testAdvertisedSchemasAreStrictCompliant], + ["prompts: list returns metadata only", testListReturnsMetadataOnly], + ["prompts: list of promptless server is empty", testListOfPromptlessServerIsEmpty], + ["prompts: list of unknown server is an error", testListUnknownServerIsError], + ["prompts: list without server_name is an error", testListMissingServerNameIsError], + ["prompts: get renders with string args", testGetHappyPath], + ["prompts: get without name is a validation error", testGetMissingNameIsValidationError], + ["prompts: get with malformed arguments is a validation error", testGetMalformedArgumentsIsValidationError], + ["prompts: get of unknown server never reaches another server", testGetUnknownServerNeverReachesAnotherServer], + ["prompts: get maps server errors verbatim", testGetMapsServerErrorsVerbatim], + ["prompts: get truncates oversized results", testGetTruncatesOversizedResult], + ["prompts: get handles malformed server response as tool error", testGetHandlesMalformedServerResponse], + ["prompts: truncate helper keeps short text intact", testTruncateHelperKeepsShortText], +] as const + +runMain("mcp-prompts", tests) diff --git a/src/engine/loop.ts b/src/engine/loop.ts index 99c4298a..361903c0 100644 --- a/src/engine/loop.ts +++ b/src/engine/loop.ts @@ -148,6 +148,7 @@ export { import { normalizeMcpToolName } from "../vendor/zoo-code/src/utils/mcp-name.js" import { getMcpServerTools } from "../vendor/zoo-code/src/core/prompts/tools/native-tools/mcp_server.js" import { mcpResourceHandlers, mcpResourceToolsForMode } from "./mcp-resources.js" +import { mcpPromptHandlers, mcpPromptToolsForMode } from "./mcp-prompts.js" import { appendBatchTool, appendBrowserActionTool, @@ -1810,6 +1811,12 @@ export class HeadlessSession { for (const { name, handler } of mcpResourceHandlers(mcpHub)) { this.executor.register(name, handler) } + // MCP prompts (#193): same session/hub lifecycle as the + // resource handlers above — discovery only, never spliced + // into the system prompt automatically. + for (const { name, handler } of mcpPromptHandlers(mcpHub)) { + this.executor.register(name, handler) + } } } const buildPrompt = isLeanSystemPromptEnabled() ? buildLeanSystemPrompt : buildSystemPrompt @@ -1836,7 +1843,7 @@ export class HeadlessSession { // sessions don't carry a describe_image schema they'd error on). let tools = this.config.tools ?? selectToolsForMode(mode, customModes) const modeConfig = getModeBySlug(mode, customModes) ?? modes.find((item) => item.slug === mode) ?? modes[0] - if (this.config.tools === undefined) tools = [...tools, ...mcpToolsForMode(this.mcpHub, modeConfig), ...mcpResourceToolsForMode(this.mcpHub, modeConfig)] + if (this.config.tools === undefined) tools = [...tools, ...mcpToolsForMode(this.mcpHub, modeConfig), ...mcpResourceToolsForMode(this.mcpHub, modeConfig), ...mcpPromptToolsForMode(this.mcpHub, modeConfig)] if (this.executor.has("browser_action")) { tools = appendBrowserActionTool(tools) } @@ -5902,7 +5909,7 @@ export class HeadlessSession { let newTools = this.config.tools ?? selectToolsForMode(modeSlug, this.customModes) const targetModeConfig = getModeBySlug(modeSlug, this.customModes) ?? modes.find((item) => item.slug === modeSlug) ?? modes[0] - if (this.config.tools === undefined) newTools = [...newTools, ...mcpToolsForMode(this.mcpHub, targetModeConfig), ...mcpResourceToolsForMode(this.mcpHub, targetModeConfig)] + if (this.config.tools === undefined) newTools = [...newTools, ...mcpToolsForMode(this.mcpHub, targetModeConfig), ...mcpResourceToolsForMode(this.mcpHub, targetModeConfig), ...mcpPromptToolsForMode(this.mcpHub, targetModeConfig)] // Same executor.gated non-vendored appends as run() — see the comment // there (T2/T3: a session never carries a schema its executor can't run). if (this.executor.has("browser_action")) { diff --git a/src/engine/mcp-prompts.ts b/src/engine/mcp-prompts.ts new file mode 100644 index 00000000..0ae6211d --- /dev/null +++ b/src/engine/mcp-prompts.ts @@ -0,0 +1,193 @@ +/** + * MCP prompt tools (#193): list + get access to prompts advertised by the + * session's connected MCP servers, exposed with the same idiom as the + * existing MCP resource tools (src/engine/mcp-resources.ts). + * + * - Exposure: `mcpPromptToolsForMode` mirrors `mcpResourceToolsForMode` + * (mcp-group gate + allowedMcpServers filter), and only advertises when + * at least one in-scope server actually exposes prompts. loop.ts + * registers the handlers on the executor at session start next to the + * per-server tool handlers and the resource handlers, and re-derives + * the advertised list on every mode switch. + * - `mcp_get_prompt` takes prompt arguments as STRINGS per the MCP spec; + * required args are validated locally before any server call, and the + * server's own error is returned verbatim (bounded) otherwise. + * - Discovery surface only: list returns metadata (name/description/args), + * the full template renders only on an explicit get — prompt text is + * never spliced into the system prompt. + * - Safety: the prompt is only ever resolved BY the named configured + * server (McpHub.getPrompt looks it up among connected servers and + * throws for unknown names). Every get is truncated to + * MAX_MCP_PROMPT_TEXT_CHARS with the cut named. + * - Lifecycle: reads ride the session hub's clients, so the existing + * session-end `mcpHub.dispose()` in loop.ts closes them; restricted + * sessions (explicit `config.tools`) never register these handlers. + */ +import { getGroupName } from "../vendor/zoo-code/src/shared/modes.js" +import type { ModeConfig } from "../vendor/zoo-code/types/index.js" +import type { McpHub, McpPromptLike } from "../vendor/zoo-code/src/services/mcp/McpHub.js" +import type { ChatTool, ToolContext, ToolHandler, ToolResult } from "./types.js" + +/** Structural hub surface this module needs — satisfied by McpHub; tests use a stub. */ +export type McpPromptHub = Pick + +/** Tool name for the headless-owned prompt-listing companion. */ +export const MCP_LIST_PROMPTS_TOOL_NAME = "mcp_list_prompts" as const + +/** Tool name for the headless-owned prompt-fetch companion. */ +export const MCP_GET_PROMPT_TOOL_NAME = "mcp_get_prompt" as const + +/** Model-facing bound for one rendered prompt (chars, not bytes). */ +export const MAX_MCP_PROMPT_TEXT_CHARS = 64 * 1024 + +/** Headless-owned discovery companion: metadata only, never template text. */ +export const MCP_LIST_PROMPTS_TOOL: ChatTool = { + type: "function", + function: { + name: MCP_LIST_PROMPTS_TOOL_NAME, + description: + "List the prompts advertised by one connected MCP server. Prompts are server-provided reusable templates (name, description, arguments). Pass a returned name to mcp_get_prompt to render it.", + strict: true, + parameters: { + type: "object", + properties: { + server_name: { + type: "string", + description: "The name of the connected MCP server whose prompts to list.", + }, + }, + required: ["server_name"], + additionalProperties: false, + }, + }, +} + +/** Headless-owned prompt-fetch companion: renders one prompt with string args. */ +export const MCP_GET_PROMPT_TOOL: ChatTool = { + type: "function", + function: { + name: MCP_GET_PROMPT_TOOL_NAME, + description: + "Render one MCP prompt from a connected server with the given string arguments. Returns the rendered messages as JSON. Prompt arguments are strings per the MCP spec; required arguments must all be present.", + strict: true, + parameters: { + type: "object", + properties: { + server_name: { + type: "string", + description: "The name of the connected MCP server providing the prompt.", + }, + name: { + type: "string", + description: "The name of the prompt to render, as listed by mcp_list_prompts.", + }, + arguments: { + type: "string", + description: + 'Prompt arguments as a JSON object of string values, e.g. {"topic": "caching"}. Omit entirely when the prompt takes no arguments.', + }, + }, + required: ["server_name", "name", "arguments"], + additionalProperties: false, + }, + }, +} + +/** Truncate a rendered prompt to the model-facing bound, naming the cut. */ +export function truncateMcpPromptText(text: string, maxChars: number = MAX_MCP_PROMPT_TEXT_CHARS): string { + if (text.length <= maxChars) return text + return `${text.slice(0, maxChars)}\n…[truncated: showing ${maxChars} of ${text.length} chars]` +} + +/** + * Prompt-tool schemas visible to a mode: the same mcp-group + + * allowedMcpServers gate as mcpResourceToolsForMode, plus at least one + * in-scope connected server must actually expose prompts (no dead tools). + */ +export function mcpPromptToolsForMode(hub: McpPromptHub | undefined, mode: ModeConfig): ChatTool[] { + if (!hub || !mode.groups.some((group) => getGroupName(group) === "mcp")) return [] + const allowed = mode.allowedMcpServers + const servers = hub.getServers().filter((server) => !allowed || allowed.includes(server.name)) + if (!servers.some((server) => (server.prompts?.length ?? 0) > 0)) return [] + return [MCP_LIST_PROMPTS_TOOL, MCP_GET_PROMPT_TOOL] +} + +function mcpError(message: string): ToolResult { + return { content: `[MCP error] ${message}`, isError: true } +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +function requiredString(args: Record, name: string): string { + const value = args[name] + if (typeof value !== "string" || value.length === 0) { + throw new Error(`'${name}' must be a non-empty string`) + } + return value +} + +async function listMcpPrompts(hub: McpPromptHub, args: Record, ctx: ToolContext): Promise { + let serverName: string + try { + serverName = requiredString(args, "server_name") + } catch (error) { + return mcpError(errorMessage(error)) + } + let prompts: McpPromptLike[] + try { + prompts = await hub.listPrompts(serverName, ctx.signal) + } catch (error) { + return mcpError(errorMessage(error)) + } + return { content: JSON.stringify(prompts, null, 2), isError: false } +} + +async function getMcpPrompt(hub: McpPromptHub, args: Record, ctx: ToolContext): Promise { + let serverName: string + let name: string + let rawArgs: string + try { + serverName = requiredString(args, "server_name") + name = requiredString(args, "name") + rawArgs = requiredString(args, "arguments") + } catch (error) { + return mcpError(errorMessage(error)) + } + let parsed: Record + try { + parsed = JSON.parse(rawArgs) as Record + } catch { + return mcpError("'arguments' must be a JSON object of string values") + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + return mcpError("'arguments' must be a JSON object of string values") + } + // Prompt arguments are strings per the MCP spec; anything else is a + // model-side encoding mistake, caught before any server call. + for (const [key, value] of Object.entries(parsed)) { + if (typeof value !== "string") { + return mcpError(`prompt argument '${key}' must be a string`) + } + } + let text: string + try { + text = await hub.getPrompt(serverName, name, parsed as Record, ctx.signal) + } catch (error) { + return mcpError(errorMessage(error)) + } + return { content: truncateMcpPromptText(text), isError: false } +} + +/** + * Executor handlers for the advertised prompt tools, in the same shape + * loop.ts registers the per-server MCP function tools + * (`(args, ctx) => ({ content, isError })` with `[MCP error]` mapping). + */ +export function mcpPromptHandlers(hub: McpPromptHub): Array<{ name: string; handler: ToolHandler }> { + return [ + { name: MCP_LIST_PROMPTS_TOOL_NAME, handler: (args, ctx) => listMcpPrompts(hub, args, ctx) }, + { name: MCP_GET_PROMPT_TOOL_NAME, handler: (args, ctx) => getMcpPrompt(hub, args, ctx) }, + ] +} diff --git a/src/vendor/tests/fixtures/mcp-stdio-server.mjs b/src/vendor/tests/fixtures/mcp-stdio-server.mjs index 43453686..5f67dd15 100644 --- a/src/vendor/tests/fixtures/mcp-stdio-server.mjs +++ b/src/vendor/tests/fixtures/mcp-stdio-server.mjs @@ -31,4 +31,14 @@ server.registerTool("delayed_write", { }) return { content: [{ type: "text", text: "finished" }] } }) +server.registerPrompt( + "greet", + { + description: "Greet someone by name", + argsSchema: { name: z.string().describe("who to greet"), style: z.string().optional().describe("greeting tone") }, + }, + async ({ name, style }) => ({ + messages: [{ role: "user", content: { type: "text", text: `hello ${name ?? "friend"} (${style ?? "plain"})` } }], + }), +) await server.connect(new StdioServerTransport()) diff --git a/src/vendor/zoo-code/src/services/mcp/McpHub.ts b/src/vendor/zoo-code/src/services/mcp/McpHub.ts index 65a95859..4b8496e3 100644 --- a/src/vendor/zoo-code/src/services/mcp/McpHub.ts +++ b/src/vendor/zoo-code/src/services/mcp/McpHub.ts @@ -20,6 +20,18 @@ export interface McpToolLike { enabledForPrompt?: boolean } +export interface McpPromptArgumentLike { + name: string + description?: string + required?: boolean +} + +export interface McpPromptLike { + name: string + description?: string + arguments?: McpPromptArgumentLike[] +} + export interface McpResourceLike { uri: string name: string @@ -31,6 +43,7 @@ export interface McpServerLike { name: string tools?: McpToolLike[] resources?: McpResourceLike[] + prompts?: McpPromptLike[] } interface StdioServerConfig { @@ -62,6 +75,7 @@ const DEFAULT_CONFIG = resolve(homedir(), ".config/capsize-agent/mcp.json") const MAX_SERVERS = 12 const MAX_TOOLS_PER_SERVER = 100 const MAX_RESOURCES_PER_SERVER = 100 +const MAX_PROMPTS_PER_SERVER = 100 function expandEnvironment(value: string): string { return value.replace(/\$\{([A-Z0-9_]+)\}/g, (_match, key: string) => process.env[key] ?? "") @@ -149,13 +163,34 @@ export class McpHub { if (listed.resources.length > MAX_RESOURCES_PER_SERVER) { throw new Error(`Server exposes more than ${MAX_RESOURCES_PER_SERVER} resources`) } - resources = listed.resources.map((resource) => ({ - uri: resource.uri, - name: resource.name, - description: resource.description, - mimeType: resource.mimeType, - })) + resources = listed.resources.map((resource) => ({ + uri: resource.uri, + name: resource.name, + description: resource.description, + mimeType: resource.mimeType, + })) + } + // Prompts are capability-gated like resources: a server that never + // advertises the prompts capability simply exposes none, and its + // tools keep working. A server that DOES advertise prompts but + // fails to list them is treated like the tools-listing failure + // above — the server is unavailable. + let prompts: McpPromptLike[] = [] + if (client.getServerCapabilities()?.prompts) { + const listed = await client.listPrompts() + if (listed.prompts.length > MAX_PROMPTS_PER_SERVER) { + throw new Error(`Server exposes more than ${MAX_PROMPTS_PER_SERVER} prompts`) } + prompts = listed.prompts.map((prompt) => ({ + name: prompt.name, + description: prompt.description, + arguments: prompt.arguments?.map((argument) => ({ + name: argument.name, + description: argument.description, + required: argument.required, + })), + })) + } this.servers.push({ name, client, @@ -166,6 +201,7 @@ export class McpHub { })), toolNames: new Set(result.tools.map((tool) => tool.name)), resources, + prompts, }) } catch (error) { this.errors.push(`${name}: ${error instanceof Error ? error.message : String(error)}`) @@ -299,6 +335,73 @@ export class McpHub { }).join("\n") } + /** + * Live prompt listing for one CONNECTED configured server. The server + * name is the allow-list: an unknown or failed server name throws + * instead of reaching any other server or the network. + */ + async listPrompts(serverName: string, signal?: AbortSignal): Promise { + const server = this.servers.find((candidate) => candidate.name === serverName) + if (!server) { + throw new Error(`MCP prompt server is unavailable: ${serverName}`) + } + if (this.closed) throw new Error("MCP connection is unavailable") + if (signal?.aborted) throw new Error("MCP prompt listing aborted") + let result + try { + if (!server.client.getServerCapabilities()?.prompts) return [] + result = await server.client.listPrompts(undefined, signal ? { signal } : undefined) + } finally { + // Same cancellation contract as callTool: let the SDK send + // notifications/cancelled while the transport is still open, + // then close owned clients to stop a server that ignores + // cancellation. + if (signal?.aborted) await this.dispose() + } + if (result.prompts.length > MAX_PROMPTS_PER_SERVER) { + throw new Error(`Server exposes more than ${MAX_PROMPTS_PER_SERVER} prompts`) + } + return result.prompts.map((prompt) => ({ + name: prompt.name, + description: prompt.description, + arguments: prompt.arguments?.map((argument) => ({ + name: argument.name, + description: argument.description, + required: argument.required, + })), + })) + } + + /** + * Render one prompt THROUGH the named connected server. Only the named + * configured server resolves it, so a prompt name cannot pull content + * from any other server or host. Arguments are strings per the MCP + * spec; the caller validates required args are present before calling. + * Returns the rendered messages as JSON; truncation to the + * model-facing bound happens in the headless prompt tools + * (src/engine/mcp-prompts.ts). + */ + async getPrompt( + serverName: string, + name: string, + promptArgs: Record, + signal?: AbortSignal, + ): Promise { + const server = this.servers.find((candidate) => candidate.name === serverName) + if (!server) { + throw new Error(`MCP prompt server is unavailable: ${serverName}`) + } + if (this.closed) throw new Error("MCP connection is unavailable") + if (signal?.aborted) throw new Error("MCP prompt get aborted") + let result + try { + result = await server.client.getPrompt({ name, arguments: promptArgs }, signal ? { signal } : undefined) + } finally { + if (signal?.aborted) await this.dispose() + } + return JSON.stringify(result.messages ?? [], null, 2) + } + async dispose(): Promise { if (this.closed) return this.closed = true