Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(mcp): pullboard mcp coordinates, never as the person [A9,P6]
Corey Olson75df15eb5f29
diff --git a/docs/api.md b/docs/api.mdindex dbafe4db..2e642d64 100644--- a/docs/api.md+++ b/docs/api.md@@ -190,6 +190,25 @@ The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js`When `verify <id> accept` runs a frozen check and refuses with `CHECK_RED` or `CHECK_UNVERIFIED`, `error.message` includes its output digest, up to 40 sanitized tail lines, and `full output file: <path>`. The file is written with owner-only permissions. If diagnostic storage fails, the message says `full output file: (unavailable: CODE)` while retaining the bounded sanitized lines; the JSON error object remains `{ code, message, next }`. An item with no frozen check produces no check-output section.+## MCP server++`pullboard mcp` serves MCP tools over stdio for the agent of the checkout it starts in. The agent's own MCP client launches it from that agent's worktree, for example as a stdio server whose command is `pullboard mcp`. It speaks newline-delimited JSON-RPC 2.0 on stdin and stdout; stdout carries only protocol messages and diagnostics go to stderr. The server opens no network connection and needs no dependency. It exits when the client closes stdin. It takes no arguments, and `--json` is refused with `USAGE` because stdout belongs to the protocol.++It answers `initialize` with `protocolVersion` (the client's, when it is `2025-06-18`, `2025-03-26` or `2024-11-05`, otherwise `2025-06-18`), `capabilities: {tools: {}}`, `serverInfo: {name: "pullboard", version}` and `instructions` naming the seat's agent. It also answers `ping`, `tools/list` and `tools/call`; notifications such as `notifications/initialized` get no reply, and any other method gets JSON-RPC error `-32601`.++| Tool | Input schema | Mirrors | Result |+| --- | --- | --- | --- |+| `board_status` | `{}` | `pullboard status` and `pullboard list` | the `status` document plus `items` (open and active items) and `needsYou`: `decisions` (open decisions addressed to the person), `rows` (spec rows that are `pending` or `draft`) and `holds` (held lanes) |+| `show_item` | `{id: integer >= 1}` | `pullboard show <id>` | the `show` document |+| `shout` | `{to: string, text: string}` | `pullboard shout <to> <text>` | the `shout` document |+| `capture_idea` | `{text: string}` | `pullboard shout coordinator "idea: <text>"` | the `shout` document; until ideas become their own kind of item, an idea is a shout to the coordinator whose text starts `idea: ` |++Every input schema sets `additionalProperties: false`; an unknown or mistyped argument returns `BAD_REQUEST`. No argument names an author, a seat or a channel: the author of every move is the agent of the checkout the server runs in.++Each tool runs the CLI command it mirrors through the same engine as the terminal and the local API, with the API's move arguments, so a move records the same events and a refusal carries the CLI's own `code`, `message` and `next`. A result's `content` is one `text` part holding the versioned JSON document, which `structuredContent` repeats. A refusal is a result with `isError: true` and the versioned refusal document. A tool name the server does not offer gets JSON-RPC error `-32602` with an `UNKNOWN_TOOL` refusal in `data`.++A person's own moves never come through MCP (P6). A tool call that names one (approving or declining rows, answering a decision, signing off) returns `HUMAN_REQUIRED` before any argument is read, whatever the client claims in its arguments, `_meta`, `clientInfo` or environment, and from any seat, including the main checkout. Every engine call the server makes also carries the `mcp` channel, which the CLI's own person check refuses. The refusal's `next` says to ask the coordinator to bring the call to the person. Live notifications over MCP are not offered yet.+## Local HTTP API v1Run `pullboard serve --port 0` to print a private API address on `127.0.0.1`. Authenticate each call with the address's `k` query parameter, an `X-Pullboard-Key` header, or `Authorization: Bearer <key>`. The secret belongs to that server session. Board ids are random 128-bit values stored in each board; reopening or moving a repo preserves its id.diff --git a/src/cli.js b/src/cli.jsindex 9ccc8f9c..264f7b1a 100644--- a/src/cli.js+++ b/src/cli.js@@ -70,6 +70,7 @@ import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';import { exportView, serveView } from './serve.js';import { forgetView, rememberView, runningView } from './view-session.js';import { serveApi } from './api.js';+import { serveMcp } from './mcp.js';import { doctorProblems, doctrineProblems } from './doctor.js';import { staleFrozenItems, staleItemFinding } from './approved-rows.js';import { mainPolicy, policyAt, itemPolicy, submissionPaths, frozenCheck, checkAtCommit, dependencySnapshots, requireTrunkMerge, trunkRef } from './trusted-policy.js';@@ -1539,6 +1540,18 @@ async function launchBackgroundView(io, port, projectRoot) {}/** Serve API v1 until a shutdown signal, printing its address before waiting (A2). */+/**+ * Serve MCP over stdio as this checkout's agent (A9). Stdout carries only the protocol, so the command+ * takes no --json; each tool call runs its own CLI command, with its own relay sync, through main.+ * A person's move never comes through it (P6).+ */+async function mcpHere(io, { first, values }) {+ if (first) throw new Refused('USAGE', 'pullboard mcp takes no arguments; run pullboard mcp from the agent\'s worktree');+ if (values.json) throw new Refused('USAGE', 'pullboard mcp speaks MCP on stdout; run pullboard mcp without --json');+ context(io);+ return serveMcp({ cwd: io.cwd, input: io.stdin, output: io.stdout, log: io.stderr, runCommand: main });+}+async function serveHere(io, values) {traceServeStartup('serve-context-start');const ctx = context(io);@@ -3296,6 +3309,7 @@ async function runCommand(argv, io) {}if (command === 'view') return await viewHere(io, values);if (command === 'serve') return await serveHere(io, values);+ if (command === 'mcp') return await mcpHere(io, args);if (command === 'forget') {if (!first || second) throw new Refused('USAGE', 'pullboard forget <path>');const root = resolve(io.cwd, first);@@ -3464,7 +3478,7 @@ async function runMain(argv, streams) {positionals: parsed.positionals.slice(1),values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };sync = Boolean(command) && !parsed.values.help && !parsed.values.version- && !['help', 'version', 'hook', 'init', 'relay', 'tour'].includes(command)+ && !['help', 'version', 'hook', 'init', 'relay', 'tour', 'mcp'].includes(command)// A coordinator declaration on a linked clone must refuse before auto-link or relay sync.&& !(command === 'join' && parsed.positionals[1] === COORDINATOR);needsRepo = !(parsed.values.help || parsed.values.version || command === 'help' || command === 'version');diff --git a/src/help.js b/src/help.jsindex d2485849..445f7264 100644--- a/src/help.js+++ b/src/help.js@@ -28,6 +28,8 @@ Set uppullboard view --export <dir> a read-only snapshot with event replay, for any static hostpullboard serve [--port N] local API v1: boards, state, moves, requests and live events,behind the session secret in its printed address+ pullboard mcp MCP tools over stdio for this worktree's agent, started by its MCP client:+ board status, show, shout and capture an idea; a person's move is refusedpullboard relay [on|off|pair|join <code>] [--url <address>] link, inspect or unlink this board's sealed relayon signs in through GitHub; the address defaults to https://app.pullboard.devpair prints a one-use machine code; join stores it in another clone@@ -170,7 +172,7 @@ Reject reasons: TEST_FAILURE, BEHAVIOR_MISMATCH, INSUFFICIENT_EVIDENCE, STALE_HEconst HELP_NAMES = ['tour', 'init', 'worktree', 'join', 'takeover', 'whoami', 'lanes', 'status', 'resources', 'settings', 'view', 'view export',- 'serve', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'skills', 'show', 'next', 'land',+ 'serve', 'mcp', 'relay', 'relay recover', 'resume', 'hooks', 'add', 'edit', 'escalate', 'run', 'list', 'doctor', 'skills', 'show', 'next', 'land','check', 'claim', 'release', 'submit', 'done', 'verify', 'fact', 'shout', 'answer', 'pass', 'decisions', 'inbox', 'export', 'import','sweep', 'merged', 'withdraw', 'refreeze', 'reopen', 'hold', 'stats', 'ledger', 'log', 'spec', 'spec check', 'spec view','spec show', 'spec unmet', 'spec signoff', 'spec draft', 'spec signers', 'spec signers add', 'forget', 'prompt', 'gate', 'hook',@@ -193,7 +195,7 @@ const HELP_EXAMPLES = {fact: 'pullboard fact 12 measurement "The check passes in 8 seconds"',verify: 'pullboard verify 12 accept --note "removed the fix; the test failed"',answer: 'pullboard answer 12 "done"', pass: 'pullboard pass 12 "please decide"',- status: 'pullboard status', view: 'pullboard view', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',+ status: 'pullboard status', view: 'pullboard view', mcp: 'pullboard mcp', stats: 'pullboard stats --since 2026-10-08', log: 'pullboard log 12', ledger: 'pullboard ledger',roadmap: 'pullboard roadmap', milestone: 'pullboard milestone add "0.7.0" --items 12,13',edit: 'pullboard edit 12 --brief "Add the upload page"', release: 'pullboard release 12',land: 'pullboard land --max 4',diff --git a/src/mcp.js b/src/mcp.jsnew file mode 100644index 00000000..9088729a--- /dev/null+++ b/src/mcp.js@@ -0,0 +1,281 @@+/**+ * pullboard mcp: a local MCP server over stdio that lets an agent's own MCP client read the board and+ * coordinate on it as that agent (A9), and never make a person's move (P6). It is newline-delimited+ * JSON-RPC 2.0 on stdin and stdout, hand-written because Pullboard has no dependencies, and it opens+ * no network connection (P5). Every tool runs the CLI command it mirrors through the same `main` the+ * terminal and the local API use, with the API's move layer (moveArgs), so a refusal reaches the+ * client with the CLI's own code and next step.+ */+import { join } from 'node:path';+import * as store from './board.js';+import { COORDINATOR, loadConfig } from './config.js';+import { codeIsFromMain, repoInfo } from './git.js';+import { VERSION } from './help.js';+import { refusalDocument } from './json.js';+import { moveArgs } from './api-moves.js';+import { Refused } from './refused.js';++/** MCP revisions this server speaks; the first is offered when a client asks for one it does not know. */+export const MCP_PROTOCOL_VERSIONS = Object.freeze(['2025-06-18', '2025-03-26', '2024-11-05']);++/** The channel every engine call carries, so the CLI's own person check refuses too (B26, P6). */+export const MCP_CHANNEL = 'mcp';++/**+ * Tool names that read as a person's own move: approving or declining rows, answering a decision,+ * signing off. Matched anywhere in the normalized name, so a client cannot reach one by renaming it.+ */+const PERSON_MOVE = /approv|declin|answer|sign_?off|decide|decision/u;++/** The tools this server offers: name, what it does, and its exact input schema. */+export const MCP_TOOLS = Object.freeze([+ {+ name: 'board_status',+ description: 'The board at a glance for this seat\'s agent: who you are, the open and active items, the review queue, unread shouts, and Needs-you (the person\'s open decisions, spec rows waiting for the person, held lanes). Mirrors pullboard status and pullboard list.',+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },+ },+ {+ name: 'show_item',+ description: 'One item in full: its criterion, the check and criterion frozen at claim, its verdicts and its thread. Mirrors pullboard show <id>.',+ inputSchema: {+ type: 'object',+ properties: { id: { type: 'integer', minimum: 1, description: 'The item id, as on the board.' } },+ required: ['id'],+ additionalProperties: false,+ },+ },+ {+ name: 'shout',+ description: 'Shout to a lane, an agent or all, as this seat\'s agent. Mirrors pullboard shout <to> <text>.',+ inputSchema: {+ type: 'object',+ properties: {+ to: { type: 'string', minLength: 1, description: 'A lane, an agent id, or all.' },+ text: { type: 'string', minLength: 1, description: 'What to say.' },+ },+ required: ['to', 'text'],+ additionalProperties: false,+ },+ },+ {+ name: 'capture_idea',+ description: 'Capture an idea for the coordinator: it goes as a shout to the coordinator, marked as an idea. Mirrors pullboard shout coordinator "idea: <text>".',+ inputSchema: {+ type: 'object',+ properties: { text: { type: 'string', minLength: 1, description: 'The idea, in a sentence or two.' } },+ required: ['text'],+ additionalProperties: false,+ },+ },+]);++/** The prefix that marks a captured idea in its shout, until ideas become their own kind of item. */+export const IDEA_PREFIX = 'idea: ';++/**+ * Check a tool's arguments against its input schema, refusing anything else.+ * Unknown fields are refused rather than ignored, so no argument can select a channel, a person or another seat.+ */+function validateArguments(tool, args) {+ const schema = tool.inputSchema;+ if (args === undefined) args = {};+ if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Refused('BAD_REQUEST', `${tool.name} takes an object of arguments; use the tool's input schema`);+ for (const key of Object.keys(args)) {+ if (!Object.hasOwn(schema.properties, key)) throw new Refused('BAD_REQUEST', `${tool.name} does not take ${key}; use only the arguments in its input schema`);+ }+ for (const key of schema.required ?? []) {+ if (args[key] === undefined) throw new Refused('BAD_REQUEST', `${tool.name} needs ${key}; use the tool's input schema`);+ }+ for (const [key, rule] of Object.entries(schema.properties)) {+ const value = args[key];+ if (value === undefined) continue;+ if (rule.type === 'integer' && (!Number.isSafeInteger(value) || value < (rule.minimum ?? -Infinity))) {+ throw new Refused('BAD_REQUEST', `${tool.name} needs ${key} as a positive whole number; use the item id from the board`);+ }+ if (rule.type === 'string' && (typeof value !== 'string' || !value.trim())) {+ throw new Refused('BAD_REQUEST', `${tool.name} needs ${key} as nonempty text; use the tool's input schema`);+ }+ }+ return args;+}++/** Normalize a tool name so case, dashes, dots and spaces cannot hide a person's move. */+function normalizedToolName(name) {+ return String(name).replace(/([a-z0-9])([A-Z])/gu, '$1_$2').toLowerCase().replace(/[^a-z0-9]+/gu, '_').replace(/^_+|_+$/gu, '');+}++/**+ * Refuse a person's move outright, before any argument, header, environment or claimed identity is read.+ * P6: a person's own moves come only from the person, never through an agent interface such as MCP.+ */+export function refusePersonMove(name) {+ if (!PERSON_MOVE.test(normalizedToolName(name))) return;+ throw new Refused('HUMAN_REQUIRED', `${name} is a person's move; approving or declining rows, answering decisions and signing off come only from the person, never through MCP; ask your coordinator to bring it to the person, with the shout tool or pullboard shout coordinator --decision`);+}++/**+ * Run one CLI command in this seat's checkout through the CLI's own engine and return its one JSON document.+ * The channel is always mcp: the CLI's person check refuses any person move that could reach it.+ */+async function runCli(runCommand, cwd, argv) {+ let output = '';+ let diagnostics = '';+ const status = await runCommand(argv, {+ cwd,+ personChannel: MCP_CHANNEL,+ stdout: { isTTY: false, write: (text) => { output += text; } },+ stderr: { write: (text) => { diagnostics += text; } },+ });+ let document;+ try { document = JSON.parse(output); } catch {+ throw new Error(`pullboard ${argv[0]} printed no JSON document${diagnostics ? `: ${diagnostics.trim()}` : ''}`);+ }+ return { status, document };+}++/**+ * The person's calls on this board, as the view's Needs-you list counts them: decisions passed up to the+ * person and held lanes, with the spec file whose waiting rows join them. A read only; it opens the board as pullboard status does and changes nothing.+ */+function personCalls(cwd) {+ const info = repoInfo(cwd);+ const config = loadConfig(info.root);+ const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'), undefined, { isMain: codeIsFromMain() });+ try {+ return { spec: config.spec, decisions: store.openDecisions(board, store.PERSON), holds: store.laneHolds(board) };+ } finally { store.closeBoard(board); }+}++/** A tool result carrying one versioned document, flagged as an error when it is a refusal. */+function toolResult(document, isError) {+ return { content: [{ type: 'text', text: JSON.stringify(document, null, 2) }], structuredContent: document, isError };+}++/**+ * Run one tool through the CLI engine and return its MCP result.+ * Each read or move is the CLI command it mirrors; a nonzero status is that command's own refusal.+ */+async function callTool(runCommand, cwd, name, args) {+ refusePersonMove(name);+ const tool = MCP_TOOLS.find((entry) => entry.name === name);+ if (!tool) return null;+ const input = validateArguments(tool, args);+ if (name === 'board_status') {+ const status = await runCli(runCommand, cwd, ['status', '--json']);+ if (status.status) return toolResult(status.document, true);+ const list = await runCli(runCommand, cwd, ['list', '--json']);+ if (list.status) return toolResult(list.document, true);+ const spec = await runCli(runCommand, cwd, ['spec', '--json']);+ if (spec.status) return toolResult(spec.document, true);+ const calls = personCalls(cwd);+ const { version, ...summary } = status.document;+ return toolResult({+ version,+ ...summary,+ items: list.document.items,+ needsYou: {+ decisions: calls.decisions,+ rows: spec.document.rows.filter((row) => row.file === calls.spec && ['pending', 'draft'].includes(row.status)),+ holds: calls.holds,+ },+ }, false);+ }+ if (name === 'show_item') {+ const shown = await runCli(runCommand, cwd, ['show', String(input.id), '--json']);+ return toolResult(shown.document, Boolean(shown.status));+ }+ const argv = name === 'shout'+ ? moveArgs({ verb: 'shout', args: { to: input.to, text: input.text } })+ : moveArgs({ verb: 'shout', args: { to: COORDINATOR, text: `${IDEA_PREFIX}${input.text}` } });+ const moved = await runCli(runCommand, cwd, argv);+ return toolResult(moved.document, Boolean(moved.status));+}++/** A JSON-RPC 2.0 error reply. */+function rpcError(id, code, message, data) {+ return { jsonrpc: '2.0', id: id ?? null, error: { code, message, ...(data === undefined ? {} : { data }) } };+}++/**+ * Answer one JSON-RPC message, or return null for a notification, which never gets a reply.+ * Refusals from a tool are tool results with isError; protocol faults are JSON-RPC errors.+ */+async function handleMessage(message, { runCommand, cwd, seat }) {+ if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string') {+ return rpcError(message && typeof message === 'object' && !Array.isArray(message) ? message.id : null, -32600, 'invalid request: send one JSON-RPC 2.0 object with a method');+ }+ const isNotification = !Object.hasOwn(message, 'id');+ if (isNotification) return null;+ const { id, method } = message;+ const params = message.params ?? {};+ if (method === 'initialize') {+ const requested = typeof params.protocolVersion === 'string' ? params.protocolVersion : null;+ return { jsonrpc: '2.0', id, result: {+ protocolVersion: MCP_PROTOCOL_VERSIONS.includes(requested) ? requested : MCP_PROTOCOL_VERSIONS[0],+ capabilities: { tools: {} },+ serverInfo: { name: 'pullboard', version: VERSION },+ instructions: `Pullboard tools for ${seat}: read the board, show an item, shout, capture an idea. They run the CLI's own moves and refusals. A person's move (approving or declining rows, answering decisions, signing off) is refused HUMAN_REQUIRED here.`,+ } };+ }+ if (method === 'ping') return { jsonrpc: '2.0', id, result: {} };+ if (method === 'tools/list') return { jsonrpc: '2.0', id, result: { tools: MCP_TOOLS } };+ if (method === 'tools/call') {+ if (!params || typeof params !== 'object' || typeof params.name !== 'string') return rpcError(id, -32602, 'tools/call needs params.name and params.arguments');+ try {+ const result = await callTool(runCommand, cwd, params.name, params.arguments);+ if (!result) {+ return rpcError(id, -32602, `unknown tool ${params.name}`, refusalDocument(new Refused('UNKNOWN_TOOL', `no tool ${params.name}; use one from tools/list`)));+ }+ return { jsonrpc: '2.0', id, result };+ } catch (error) {+ if (error instanceof Refused) return { jsonrpc: '2.0', id, result: toolResult(refusalDocument(error), true) };+ return rpcError(id, -32603, `internal error: ${error.message}`);+ }+ }+ return rpcError(id, -32601, `method not found: ${method}`);+}++/**+ * Serve MCP on newline-delimited stdio until the client closes stdin. Messages are handled one at a+ * time, in order, because each tool runs one CLI command against the board. Only replies go to+ * output; anything diagnostic goes to log.+ *+ * @param {{ cwd: string, input: NodeJS.ReadableStream, output: { write(text: string): any }, log: { write(text: string): any }, runCommand: Function }} options+ * @returns {Promise<number>} the exit code+ */+export async function serveMcp({ cwd, input, output, log, runCommand }) {+ const me = await runCli(runCommand, cwd, ['whoami', '--json']);+ const seat = me.status ? 'this checkout' : `agent ${me.document.id} in the ${me.document.lane} lane`;+ if (me.status) log.write(`pullboard mcp: ${me.document.error?.message ?? 'this checkout has no agent'}\nnext: ${me.document.error?.next ?? 'run pullboard join <lane> --model "<model name>"'}\n`);+ let queue = Promise.resolve();+ let buffer = '';+ /** Parse one line and queue its reply behind earlier messages. */+ const accept = (line) => {+ if (!line.trim()) return;+ queue = queue.then(async () => {+ let message;+ try { message = JSON.parse(line); } catch {+ output.write(`${JSON.stringify(rpcError(null, -32700, 'parse error: each line must be one JSON-RPC message'))}\n`);+ return;+ }+ const reply = await handleMessage(message, { runCommand, cwd, seat });+ if (reply) output.write(`${JSON.stringify(reply)}\n`);+ }).catch((error) => { log.write(`pullboard mcp: ${error.stack ?? error.message}\n`); });+ };+ input.setEncoding?.('utf8');+ await new Promise((done, fail) => {+ input.on('data', (chunk) => {+ buffer += chunk;+ let newline;+ while ((newline = buffer.indexOf('\n')) >= 0) {+ accept(buffer.slice(0, newline));+ buffer = buffer.slice(newline + 1);+ }+ });+ input.once('end', done);+ input.once('error', fail);+ });+ accept(buffer);+ await queue;+ return 0;+}diff --git a/src/templates.js b/src/templates.jsindex 4ca3e3fe..0a0cf2bc 100644--- a/src/templates.js+++ b/src/templates.js@@ -129,7 +129,7 @@ The coordinator merges verified items into the main line; builders never merge.If your item needs code another lane owns and it is not there yet, shout that lane and take another item. Never copy their code into your lane, and never build another lane's item, even one that was rejected and blocks you: shout that lane and the coordinator. A claim refused as BLOCKED names the item it waits on.-**Talk.** \`pullboard shout <lane|agent|all> "<text>"\`. Read \`pullboard inbox\` before you start and after you submit.+**Talk.** \`pullboard shout <lane|agent|all> "<text>"\`. Read \`pullboard inbox\` before you start and after you submit. An MCP client can do the same as your agent: add \`pullboard mcp\`, run from your worktree, as a stdio server; it reads the board, shows an item, shouts and captures ideas for the coordinator, and never makes a person's move.**Never.** Bypass a hook with \`--no-verify\`, or get past a refusal with filler text: fix what it names. Edit the board's database. Verify your own work. Change an approved spec row without the person's OK. Delete or renumber a spec row. Act from the main checkout; it is the coordinator's. Count a yes relayed by another agent as the person's approval.${AGENTS_END}diff --git a/test/mcp.test.js b/test/mcp.test.jsnew file mode 100644index 00000000..9575338e--- /dev/null+++ b/test/mcp.test.js@@ -0,0 +1,341 @@+/** pullboard mcp, driven by a real stdio MCP client against real repos and a real board [A9,P6,P5]. */+import assert from 'node:assert/strict';+import { once } from 'node:events';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { test } from 'node:test';+import { pathToFileURL } from 'node:url';+import { fixtureChildMessage, runFixtureChild, runFixtureGit, startFixtureChild } from './fixture-child.js';+import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+const SPEC = `# MCP fixture++## G · Goals+- G1 [approved, must] The fixture keeps its board. | gate: true+- G2 [draft, aim] A draft row waits for the person.+`;++/** Network APIs the server must never touch; each attempt is logged and refused. */+const NETWORK_GUARD = `+import http from 'node:http';+import https from 'node:https';+import net from 'node:net';+import tls from 'node:tls';+import dgram from 'node:dgram';+import { appendFileSync } from 'node:fs';+const log = process.env.MCP_NETWORK_LOG;+appendFileSync(log, 'guard loaded\\n');+const blocked = (kind) => { appendFileSync(log, 'attempt ' + kind + '\\n'); throw new Error('unexpected outbound attempt: ' + kind); };+globalThis.fetch = async () => blocked('fetch');+http.request = () => blocked('http.request');+http.get = () => blocked('http.get');+https.request = () => blocked('https.request');+https.get = () => blocked('https.get');+net.connect = () => blocked('net.connect');+net.createConnection = () => blocked('net.createConnection');+net.Socket.prototype.connect = function () { return blocked('net.Socket.connect'); };+tls.connect = () => blocked('tls.connect');+dgram.createSocket = () => blocked('dgram.createSocket');+`;++/** Remove every agent and SSH marker, so the environment looks like the person's own terminal. */+function personTerminal(source) {+ const env = { ...source };+ for (const key of [...AGENT_SHELL_MARKERS, ...SSH_SHELL_MARKERS]) delete env[key];+ for (const key of Object.keys(env)) if (key.startsWith('GIT_') && !key.startsWith('GIT_CONFIG') && !key.startsWith('GIT_AUTHOR') && !key.startsWith('GIT_COMMITTER')) delete env[key];+ return env;+}++/** Quote a literal executable path for the fixture's pullboard shim, which the git hooks call. */+function shellWord(value) {+ return `'${value.replaceAll("'", "'\\''")}'`;+}++/** A real repo with one lane, a joined worktree bound to agent session A, and a network guard. */+function project(t) {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-mcp-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const bin = join(dir, 'bin');+ mkdirSync(bin);+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);+ chmodSync(join(bin, 'pullboard'), 0o755);+ const env = personTerminal({+ ...process.env,+ PATH: `${bin}:${process.env.PATH}`,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'MCP test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'MCP test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ PULLBOARD_HOME: join(dir, 'pullboard-home'),+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),+ MCP_NETWORK_LOG: join(dir, 'network.log'),+ });+ delete env.PULLBOARD_MODEL;+ const guard = join(dir, 'network-guard.mjs');+ writeFileSync(guard, NETWORK_GUARD);+ /** Run real Git under the fixture's isolated identity. */+ const git = (cwd, ...args) => runFixtureGit(args, { cwd, env });+ /** Run the real CLI in its own process; extra holds the environment of the shell it runs from. */+ const run = (cwd, args, extra = {}) => runFixtureChild(process.execPath, [BIN, ...args], { cwd, env: { ...env, ...extra }, encoding: 'utf8' });+ const repo = join(dir, 'repo');+ mkdirSync(repo);+ git(repo, 'init', '-q', '-b', 'main');+ const initialized = run(repo, ['init', '--model', 'coordinator-model']);+ assert.equal(initialized.status, 0, fixtureChildMessage(initialized));+ const configPath = join(repo, 'pullboard.json');+ const config = JSON.parse(readFileSync(configPath, 'utf8'));+ writeFileSync(configPath, `${JSON.stringify({ ...config, gate: 'true', spec: 'SPEC.md', lanes: { web: { owns: ['web/'], specs: ['G1'] } }, shared: [] }, null, 2)}\n`);+ writeFileSync(join(repo, 'SPEC.md'), SPEC);+ git(repo, 'add', '-A');+ git(repo, 'commit', '-q', '-m', 'chore: set up mcp fixture');+ const web = join(dir, 'web-1');+ git(repo, 'worktree', 'add', '-q', web, '-b', 'web/one');+ const sessionA = { CODEX_SESSION_ID: 'mcp-session-a' };+ const joined = run(web, ['join', 'web', '--model', 'fixture-model', '--json'], sessionA);+ assert.equal(joined.status, 0, fixtureChildMessage(joined));+ const agent = JSON.parse(joined.stdout).agent;+ return { dir, env, run, git, repo, web, agent, sessionA, guard, database: join(repo, '.git', 'pullboard', 'board.sqlite') };+}++/** Run one CLI command with --json and return its single document and status. */+function cli(box, cwd, args, extra = {}) {+ const result = box.run(cwd, [...args, '--json'], extra);+ let document;+ try { document = JSON.parse(result.stdout); } catch { assert.fail(`${args.join(' ')} printed no JSON\n${fixtureChildMessage(result)}`); }+ return { status: result.status, document };+}++/**+ * Start `pullboard mcp` and speak to it as a minimal MCP client: newline-delimited JSON-RPC 2.0+ * requests on its stdin, replies matched by id from its stdout, stderr kept apart for evidence.+ */+function mcpClient(t, box, cwd, extra = {}) {+ const child = startFixtureChild(process.execPath, ['--import', pathToFileURL(box.guard).href, BIN, 'mcp'], {+ cwd, env: { ...box.env, ...extra }, stdio: ['pipe', 'pipe', 'pipe'],+ });+ const lines = [];+ const waiting = new Map();+ let buffer = '';+ let stderr = '';+ let nextId = 1;+ child.stdout.setEncoding('utf8');+ child.stderr.setEncoding('utf8').on('data', (part) => { stderr += part; });+ child.stdout.on('data', (part) => {+ buffer += part;+ let newline;+ while ((newline = buffer.indexOf('\n')) >= 0) {+ const line = buffer.slice(0, newline);+ buffer = buffer.slice(newline + 1);+ lines.push(line);+ let message;+ try { message = JSON.parse(line); } catch { continue; }+ waiting.get(message.id)?.(message);+ }+ });+ const closed = once(child, 'close');+ t.after(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); });+ /** Send one request and wait for the reply with its id. */+ const request = (method, params) => new Promise((done, fail) => {+ const id = nextId++;+ const timer = setTimeout(() => fail(new Error(`no reply to ${method} within 30s\nstderr: ${stderr}`)), 30_000); // budget: hang ceiling for one MCP reply; no throughput claim.+ waiting.set(id, (message) => { clearTimeout(timer); waiting.delete(id); done(message); });+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) })}\n`);+ });+ return {+ request,+ /** Send a notification, which gets no reply. */+ notify: (method, params) => child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) })}\n`),+ /** Call one tool and return its MCP result. */+ call: async (name, args, extra = {}) => {+ const reply = await request('tools/call', { name, arguments: args, ...extra });+ assert.ok(reply.result, `tools/call ${name} returns a tool result: ${JSON.stringify(reply)}`);+ return reply.result;+ },+ /** Close stdin, wait for a clean exit, and return everything the server wrote. */+ close: async () => {+ child.stdin.end();+ const [code] = await closed;+ return { code, lines, stderr };+ },+ };+}++/** The handshake an MCP client makes before any tool call. */+async function initialize(client, clientInfo = { name: 'fixture-client', version: '1.0.0' }) {+ const reply = await client.request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo });+ client.notify('notifications/initialized');+ return reply;+}++/** Read the board's shout and event counts without opening it through pullboard. */+function counts(file) {+ const db = new DatabaseSync(file, { readOnly: true });+ try {+ return {+ shouts: db.prepare('SELECT COUNT(*) AS n FROM shout').get().n,+ events: db.prepare('SELECT COUNT(*) AS n FROM event').get().n,+ };+ } finally { db.close(); }+}++/** Read one shout row and the event that recorded it. */+function shoutRow(file, id) {+ const db = new DatabaseSync(file, { readOnly: true });+ try { return db.prepare('SELECT * FROM shout WHERE shout_id = ?').get(id); } finally { db.close(); }+}++/** Every line on stdout is one JSON-RPC 2.0 message; nothing else may reach it. */+function assertProtocolOnly(lines) {+ for (const line of lines) {+ const message = JSON.parse(line);+ assert.equal(message.jsonrpc, '2.0', `stdout carries only JSON-RPC: ${line}`);+ }+}++/** The person's decision fixture: the agent asks its coordinator, and the coordinator passes it up. */+function personDecision(box) {+ const asked = cli(box, box.web, ['shout', 'coordinator', 'Ship the MCP patch?', '--decision'], box.sessionA);+ assert.equal(asked.status, 0, JSON.stringify(asked.document));+ const passed = cli(box, box.repo, ['pass', String(asked.document.id), 'The person should decide.']);+ assert.equal(passed.status, 0, JSON.stringify(passed.document));+ return passed.document.id;+}++test('[A9,P5] an MCP client reads the board and shouts as its agent', async (t) => {+ const box = project(t);+ const added = cli(box, box.repo, ['add', 'web', 'MCP fixture item', '--criterion', 'an MCP client can read this item']);+ assert.equal(added.status, 0, JSON.stringify(added.document));+ const itemId = added.document.item.item_id;+ const decisionId = personDecision(box);++ const client = mcpClient(t, box, box.web, box.sessionA);+ const hello = await initialize(client);+ assert.equal(hello.result.protocolVersion, '2025-06-18');+ assert.deepEqual(hello.result.capabilities, { tools: {} });+ assert.equal(hello.result.serverInfo.name, 'pullboard');+ assert.match(hello.result.instructions, new RegExp(`agent ${box.agent} in the web lane`));++ const listed = await client.request('tools/list');+ assert.deepEqual(listed.result.tools.map((tool) => tool.name), ['board_status', 'show_item', 'shout', 'capture_idea']);+ for (const tool of listed.result.tools) {+ assert.equal(tool.inputSchema.type, 'object', tool.name);+ assert.equal(tool.inputSchema.additionalProperties, false, `${tool.name} refuses unknown arguments`);+ assert.ok(tool.description.trim(), tool.name);+ }++ const status = await client.call('board_status', {});+ assert.equal(status.isError, false, JSON.stringify(status));+ assert.equal(status.structuredContent.version, 1);+ assert.equal(status.structuredContent.me.id, box.agent, 'status reads as the seat\'s agent');+ assert.ok(status.structuredContent.items.some((item) => item.item_id === itemId && item.item_status === 'open'), 'status lists the open item');+ assert.deepEqual(status.structuredContent.needsYou.decisions.map((ask) => ask.shout_id), [decisionId], 'Needs-you carries the person\'s open decision');+ assert.deepEqual(status.structuredContent.needsYou.rows.map((row) => row.id), ['G2'], 'Needs-you carries the draft row');+ assert.deepEqual(JSON.parse(status.content[0].text), status.structuredContent, 'the text content is the same document');++ const shown = await client.call('show_item', { id: itemId });+ assert.equal(shown.isError, false, JSON.stringify(shown));+ const cliShown = cli(box, box.web, ['show', String(itemId)]);+ assert.deepEqual(shown.structuredContent, cliShown.document, 'show_item returns pullboard show --json');++ const before = counts(box.database);+ const shouted = await client.call('shout', { to: 'coordinator', text: 'hello from MCP' });+ assert.equal(shouted.isError, false, JSON.stringify(shouted));+ assert.deepEqual(Object.keys(shouted.structuredContent).sort(), ['decision', 'id', 'version']);+ const row = shoutRow(box.database, shouted.structuredContent.id);+ assert.equal(row.shout_from, box.agent, 'the shout\'s author is the seat\'s agent');+ assert.equal(row.shout_to, 'coordinator');+ assert.equal(row.shout_text, 'hello from MCP');+ const inbox = cli(box, box.repo, ['inbox']);+ assert.ok(inbox.document.shouts.some((shout) => shout.shout_id === row.shout_id && shout.shout_from === box.agent), 'the coordinator reads it from the agent');++ const toLane = await client.call('shout', { to: 'all', text: '-- a dash-led note stays text' });+ assert.equal(toLane.isError, false, JSON.stringify(toLane));+ assert.equal(shoutRow(box.database, toLane.structuredContent.id).shout_text, '-- a dash-led note stays text');++ const idea = await client.call('capture_idea', { text: 'ideas could become their own kind of item' });+ assert.equal(idea.isError, false, JSON.stringify(idea));+ const ideaRow = shoutRow(box.database, idea.structuredContent.id);+ assert.deepEqual([ideaRow.shout_from, ideaRow.shout_to, ideaRow.shout_text], [box.agent, 'coordinator', 'idea: ideas could become their own kind of item']);+ assert.equal(counts(box.database).shouts, before.shouts + 3);++ // The same engine: a refusal reaches the client with the CLI's own code, message and next step.+ const selfShout = await client.call('shout', { to: box.agent, text: 'talking to myself' });+ const cliSelf = cli(box, box.web, ['shout', box.agent, 'talking to myself'], box.sessionA);+ assert.equal(cliSelf.status, 1);+ assert.equal(selfShout.isError, true);+ assert.equal(selfShout.structuredContent.error.code, 'SELF_SHOUT');+ assert.deepEqual(selfShout.structuredContent, cliSelf.document);+ const missing = await client.call('show_item', { id: 999 });+ assert.equal(missing.isError, true);+ assert.deepEqual(missing.structuredContent, cli(box, box.web, ['show', '999']).document);++ // Arguments are exactly the schema's: no argument can name another author, seat or channel.+ const spoofed = await client.call('shout', { to: 'all', text: 'from someone else', from: 'person' });+ assert.equal(spoofed.isError, true);+ assert.equal(spoofed.structuredContent.error.code, 'BAD_REQUEST');+ assert.match(spoofed.structuredContent.error.next, /use only the arguments in its input schema/);+ const unknownTool = await client.request('tools/call', { name: 'land', arguments: {} });+ assert.equal(unknownTool.error.code, -32602);+ const unknownMethod = await client.request('resources/list');+ assert.equal(unknownMethod.error.code, -32601);+ assert.equal(counts(box.database).shouts, before.shouts + 3, 'refused calls write nothing');++ const done = await client.close();+ assert.equal(done.code, 0, done.stderr);+ assertProtocolOnly(done.lines);+ assert.equal(readFileSync(join(box.dir, 'network.log'), 'utf8'), 'guard loaded\n', 'the server opened no network connection');++ // Another agent session in the same checkout is refused exactly as the CLI refuses it there.+ const other = mcpClient(t, box, box.web, { CODEX_SESSION_ID: 'mcp-session-b' });+ await initialize(other);+ const intruder = await other.call('shout', { to: 'coordinator', text: 'not my checkout' });+ const cliIntruder = cli(box, box.web, ['shout', 'coordinator', 'not my checkout'], { CODEX_SESSION_ID: 'mcp-session-b' });+ assert.equal(cliIntruder.document.error.code, 'NOT_YOUR_CHECKOUT');+ assert.equal(intruder.isError, true);+ assert.deepEqual(intruder.structuredContent, cliIntruder.document);+ assert.equal((await other.close()).code, 0);+ assert.equal(counts(box.database).shouts, before.shouts + 3);+});++test('[P6,A9] a person\'s move through MCP is refused', async (t) => {+ const box = project(t);+ const decisionId = personDecision(box);+ const specBefore = readFileSync(join(box.repo, 'SPEC.md'));+ const before = counts(box.database);++ // The most privileged seat, a terminal with no agent markers, and every claim a client could make.+ const spoof = { PULLBOARD_PERSON: '1', PULLBOARD_CHANNEL: 'view', PULLBOARD_AS: 'person', PULLBOARD_AGENT: 'person', PULLBOARD_PERSON_CHANNEL: 'terminal' };+ const client = mcpClient(t, box, box.repo, spoof);+ await initialize(client, { name: 'person', version: '1.0.0', title: 'The person, in their own terminal' });+ const listed = await client.request('tools/list');+ assert.ok(listed.result.tools.every((tool) => !/approv|declin|answer|sign_?off/u.test(tool.name)), 'no person move is offered');++ const claims = { _meta: { person: true, channel: 'terminal', as: 'person' } };+ const approve = await client.call('spec_approve', { ids: 'G2', as: 'person', channel: 'terminal', by: 'person' }, claims);+ const answer = await client.call('answer', { id: decisionId, text: 'Ship it.', as: 'person' }, claims);+ for (const [name, result] of [['spec approve', approve], ['answer', answer]]) {+ assert.equal(result.isError, true, name);+ assert.equal(result.structuredContent.error.code, 'HUMAN_REQUIRED', `${name}: ${JSON.stringify(result.structuredContent)}`);+ assert.match(result.structuredContent.error.next, /^ask your coordinator to bring it to the person/u, name);+ }+ for (const name of ['spec_decline', 'spec_signoff', 'approveRows', 'Spec.Approve', 'answer-decision', 'sign off']) {+ const refused = await client.call(name, { ids: 'G2' });+ assert.equal(refused.structuredContent.error.code, 'HUMAN_REQUIRED', name);+ }+ const done = await client.close();+ assert.equal(done.code, 0, done.stderr);+ assertProtocolOnly(done.lines);++ assert.deepEqual(counts(box.database), before, 'no shout or event was written');+ assert.deepEqual(readFileSync(join(box.repo, 'SPEC.md')), specBefore, 'SPEC.md is unchanged');+ const open = cli(box, box.repo, ['decisions', '--as', 'person']);+ assert.ok(open.document.decisions.some((ask) => ask.shout_id === decisionId), 'the decision is still open');+ // The same moves are possible from the person's own terminal, so the refusal is MCP's, not the fixture's.+ const approved = cli(box, box.repo, ['spec', 'approve', 'G2']);+ assert.equal(approved.status, 0, JSON.stringify(approved.document));+});