@mcpbox/mcpbox-claude 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart hook: query the mcpbox tracker and print a compact summary of
3
+ // open tasks so Claude sees them at the top of every fresh session.
4
+ //
5
+ // Output goes to stdout — Claude Code injects it as a <system-reminder>.
6
+ // Exit 0 always so an mcpbox outage never blocks the session from opening.
7
+ //
8
+ // Fetch path: spawns the local `daruma` binary in stdio MCP mode (same tracker
9
+ // tools the mcpbox server exposes). Cloud-only setups without the local binary
10
+ // silently no-op (exit 0) — the /mcpbox:tasks command still works on demand.
11
+ // ponytail: stdio-only fetch; add an HTTP+token path for cloud-only if the
12
+ // silent no-op proves too quiet in practice.
13
+ //
14
+ // Environment variables:
15
+ // MCPBOX_MCP_CMD — command to start the stdio MCP server (default: "daruma")
16
+ // MCPBOX_MCP_ARGS — space-separated extra args (default: "mcp serve")
17
+ // MCPBOX_SCOPE — optional project_scope path filter
18
+
19
+ import { MCPClient } from "../lib/mcp-client.mjs";
20
+
21
+ const TIMEOUT_MS = 12_000;
22
+ const MAX_TASKS = 15;
23
+
24
+ const STATUS_EMOJI = {
25
+ inbox: "📥",
26
+ todo: "⬜",
27
+ in_progress: "🟢",
28
+ in_review: "🔍",
29
+ done: "✅",
30
+ cancelled: "🚫",
31
+ };
32
+
33
+ function emoji(status) {
34
+ return STATUS_EMOJI[status] ?? "❓";
35
+ }
36
+
37
+ function truncate(str, len) {
38
+ if (!str) return "";
39
+ return str.length > len ? str.slice(0, len - 1) + "…" : str;
40
+ }
41
+
42
+ function formatTask(t) {
43
+ const e = emoji(t.status ?? "");
44
+ const pri = t.priority ? `p${t.priority}` : " ";
45
+ const title = truncate(t.title ?? t.subject ?? "(no title)", 60);
46
+ return ` ${e} [${pri}] ${title}`;
47
+ }
48
+
49
+ async function fetchSummary() {
50
+ const cmd = process.env.MCPBOX_MCP_CMD ?? "daruma";
51
+ const extraArgs = process.env.MCPBOX_MCP_ARGS ?? "mcp serve";
52
+ const args = extraArgs.trim() ? extraArgs.trim().split(/\s+/) : ["mcp", "serve"];
53
+ const scope = process.env.MCPBOX_SCOPE;
54
+
55
+ const client = new MCPClient();
56
+ const timer = setTimeout(() => {
57
+ client.stop().catch(() => {});
58
+ }, TIMEOUT_MS);
59
+
60
+ try {
61
+ await client.start(cmd, args, { stderrLog: null });
62
+ await client.initialize();
63
+
64
+ let projectId = null;
65
+ let projectTitle = null;
66
+ try {
67
+ const wsResult = await client.callTool("daruma_workspace_info", {});
68
+ const ws = wsResult.parsed ?? {};
69
+ projectId = ws.default_project ?? ws.defaultProject ?? null;
70
+ projectTitle = ws.project_title ?? ws.title ?? null;
71
+ } catch { /* no workspace info — continue without project filter */ }
72
+
73
+ const listArgs = {
74
+ status: ["inbox", "todo", "in_progress", "in_review"],
75
+ limit: MAX_TASKS + 1,
76
+ };
77
+ if (projectId) listArgs.project_id = projectId;
78
+ if (!projectId && scope) listArgs.project_scope = scope;
79
+
80
+ const listResult = await client.callTool("daruma_list", listArgs);
81
+ const raw = listResult.parsed ?? listResult.text;
82
+ const tasks = Array.isArray(raw)
83
+ ? raw
84
+ : Array.isArray(raw?.tasks)
85
+ ? raw.tasks
86
+ : Array.isArray(raw?.items)
87
+ ? raw.items
88
+ : [];
89
+
90
+ await client.stop();
91
+ clearTimeout(timer);
92
+ return { tasks, projectTitle, projectId };
93
+ } catch (err) {
94
+ clearTimeout(timer);
95
+ try { await client.stop(); } catch { /* ignore */ }
96
+ throw err;
97
+ }
98
+ }
99
+
100
+ async function main() {
101
+ let data;
102
+ try {
103
+ data = await fetchSummary();
104
+ } catch (err) {
105
+ if (process.env.MCPBOX_DEBUG) {
106
+ process.stderr.write(`[mcpbox-claude/session-start] error: ${err?.message ?? err}\n`);
107
+ }
108
+ process.exit(0);
109
+ }
110
+
111
+ const { tasks, projectTitle } = data;
112
+
113
+ if (!tasks || tasks.length === 0) {
114
+ process.stdout.write(
115
+ "[mcpbox] No open tasks — run /mcpbox:tasks to verify, or /mcpbox:pipeline-run \"<idea>\" to open a maturity run.\n"
116
+ );
117
+ process.exit(0);
118
+ }
119
+
120
+ const shown = tasks.slice(0, MAX_TASKS);
121
+ const extra = tasks.length > MAX_TASKS ? tasks.length - MAX_TASKS : 0;
122
+ const count = tasks.length > MAX_TASKS ? MAX_TASKS + "+" : tasks.length;
123
+ const plural = tasks.length !== 1 ? "s" : "";
124
+ const header = projectTitle
125
+ ? `[mcpbox] ${count} open task${plural} in "${projectTitle}":`
126
+ : `[mcpbox] ${count} open task${plural}:`;
127
+
128
+ const lines = [header, ...shown.map(formatTask)];
129
+ if (extra > 0) lines.push(` …and ${extra} more — /mcpbox:tasks for full list`);
130
+ lines.push("→ /mcpbox:next to claim the next task | /mcpbox:status for server + pipeline health");
131
+
132
+ process.stdout.write(lines.join("\n") + "\n");
133
+ process.exit(0);
134
+ }
135
+
136
+ main();
package/hooks/stop.mjs ADDED
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ // Stop hook: auto-record nudge. Prints a <system-reminder>-style hint so Claude
3
+ // considers capturing a reusable lesson via daruma_comment at session end.
4
+ //
5
+ // Prints nothing when there is no active tracked task (MCPBOX_ACTIVE_TASK env
6
+ // absent), so it only fires when the agent was working on a tracked task.
7
+ //
8
+ // asyncRewake: true in hooks.json re-wakes Claude with the rewakeMessage only
9
+ // when this script exits 0 AND prints non-empty output.
10
+
11
+ import { pathToFileURL } from "node:url";
12
+
13
+ export function stopHookMessage(activeTask = "") {
14
+ if (!activeTask) return "";
15
+ return (
16
+ `[mcpbox/auto-record] Active task: ${activeTask}\n` +
17
+ `If this session produced a concrete reusable lesson (command, invariant, bug pattern, file path), ` +
18
+ `capture it now via /mcpbox:capture or call daruma_comment directly:\n` +
19
+ ` daruma_comment task_id="${activeTask}" body="lesson: <short durable lesson>"\n` +
20
+ `Skip if there is nothing durable to record.\n`
21
+ );
22
+ }
23
+
24
+ function main() {
25
+ const message = stopHookMessage(process.env.MCPBOX_ACTIVE_TASK ?? "");
26
+ if (message) process.stdout.write(message);
27
+ }
28
+
29
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
30
+ main();
31
+ }
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ // UserPromptSubmit hook: detect capture / sync / status / close / pipeline
3
+ // intent in the user's prompt and prepend a short routing hint so Claude routes
4
+ // to the right slash command rather than improvising.
5
+ //
6
+ // Output goes to stdout — Claude Code injects it as a <system-reminder>.
7
+ // Exit 0 always; this hook must never block a prompt from being submitted.
8
+ //
9
+ // Reads the prompt text from CLAUDE_USER_PROMPT env var (set by Claude Code).
10
+
11
+ import { pathToFileURL } from "node:url";
12
+
13
+ // Intent patterns. Order matters — first match wins. ASCII keywords use \b;
14
+ // Cyrillic uses whitespace/edge guards since \b is ASCII-only.
15
+ const PATTERNS = [
16
+ {
17
+ re: /\b(pipeline|maturity|handoff|action\s*packet)\b|(?<![а-яёА-ЯЁ])(пайплайн|конвейер|зрелость|хендофф)(?![а-яёА-ЯЁ])/,
18
+ hint: "[mcpbox] Detected pipeline intent → /mcpbox:pipeline-run or mcpbox_pipeline_run (raw input matures torii→…→fujin→handoff, never daruma_create directly).",
19
+ },
20
+ {
21
+ re: /\b(capture|record|lesson)\b|(?<![а-яёА-ЯЁ])(сохрани|запомни|урок)(?![а-яёА-ЯЁ])/,
22
+ hint: "[mcpbox] Detected lesson-capture intent → /mcpbox:capture",
23
+ },
24
+ {
25
+ re: /\b(sync|refresh\s+tasks)\b|(?<![а-яёА-ЯЁ])(синх|обнови\s+задачи)(?![а-яёА-ЯЁ])/,
26
+ hint: "[mcpbox] Detected sync intent → /mcpbox:sync",
27
+ },
28
+ {
29
+ re: /\b(status|progress|what.?s\s+(open|next|left))\b|(?<![а-яёА-ЯЁ])(статус|прогресс|что\s+(открыто|осталось|дальше))(?![а-яёА-ЯЁ])/,
30
+ hint: "[mcpbox] Detected status query → /mcpbox:status",
31
+ },
32
+ {
33
+ re: /\b(close|complete|mark\s+.*done)\b|(?<![а-яёА-ЯЁ])(закрой|закрыть|завершить|пометь\s+.*выполненной)(?![а-яёА-ЯЁ])/,
34
+ hint: "[mcpbox] Detected close intent → /mcpbox:close",
35
+ },
36
+ ];
37
+
38
+ export function promptSubmitHint(promptText = "") {
39
+ const prompt = promptText.toLowerCase().trim();
40
+ for (const { re, hint } of PATTERNS) {
41
+ if (re.test(prompt)) return hint;
42
+ }
43
+ return "";
44
+ }
45
+
46
+ function main() {
47
+ const hint = promptSubmitHint(process.env.CLAUDE_USER_PROMPT ?? "");
48
+ if (hint) process.stdout.write(hint + "\n");
49
+ }
50
+
51
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
52
+ main();
53
+ }
package/lib/codex.mjs ADDED
@@ -0,0 +1,70 @@
1
+ // Codex surface for the mcpbox harness — parity with the Claude CLAUDE.md
2
+ // plugin. Two idempotent writes:
3
+ // 1. AGENTS.md policy block (Codex reads it every session in the workspace).
4
+ // 2. `~/.codex/config.toml` [mcp_servers.mcpbox] pointing at the single
5
+ // canonical HTTP endpoint. Codex's config is global-only, so the entry
6
+ // is fenced with comment markers and replaced in place — surrounding
7
+ // hand-written TOML is preserved.
8
+ //
9
+ // The policy body is BLOCK_BODY from lib/policy.mjs — one source of truth
10
+ // shared across CLAUDE.md / AGENTS.md / .cursor/rules. Slash-command and
11
+ // tool-surface phrasing stays Claude-flavoured; that's a deliberate
12
+ // non-issue, not per-surface forks to maintain.
13
+
14
+ import { homedir } from "node:os";
15
+ import { join, resolve } from "node:path";
16
+ import {
17
+ BLOCK_BODY,
18
+ MCP_URL,
19
+ installManagedBlock,
20
+ removeManagedBlock,
21
+ } from "./policy.mjs";
22
+
23
+ const BEGIN = "<!-- mcpbox:policy:begin -->";
24
+ const END = "<!-- mcpbox:policy:end -->";
25
+
26
+ const TOML_BEGIN = "# mcpbox:mcp:begin";
27
+ const TOML_END = "# mcpbox:mcp:end";
28
+ const TOML_BLOCK = `[mcp_servers.mcpbox]
29
+ url = "${MCP_URL}"
30
+ `;
31
+
32
+ function codexConfigPath(configPath) {
33
+ return configPath ? resolve(configPath) : join(homedir(), ".codex", "config.toml");
34
+ }
35
+
36
+ // AGENTS.md policy block in the project directory.
37
+ export function installCodexPolicy({ projectDir } = {}) {
38
+ const dir = projectDir ? resolve(projectDir) : process.cwd();
39
+ return installManagedBlock({ target: join(dir, "AGENTS.md"), begin: BEGIN, end: END, block: BLOCK_BODY });
40
+ }
41
+
42
+ export function removeCodexPolicy({ projectDir } = {}) {
43
+ const dir = projectDir ? resolve(projectDir) : process.cwd();
44
+ return removeManagedBlock({ target: join(dir, "AGENTS.md"), begin: BEGIN, end: END });
45
+ }
46
+
47
+ // [mcp_servers.mcpbox] entry in the global ~/.codex/config.toml.
48
+ // `configPath` overrides the target (used by tests).
49
+ export function installCodexMcp({ configPath } = {}) {
50
+ return installManagedBlock({ target: codexConfigPath(configPath), begin: TOML_BEGIN, end: TOML_END, block: TOML_BLOCK });
51
+ }
52
+
53
+ export function removeCodexMcp({ configPath } = {}) {
54
+ return removeManagedBlock({ target: codexConfigPath(configPath), begin: TOML_BEGIN, end: TOML_END });
55
+ }
56
+
57
+ // Both surfaces at once (what `mcpbox-claude codex-init` calls).
58
+ export async function installCodex({ projectDir } = {}) {
59
+ const policy = await installCodexPolicy({ projectDir });
60
+ const mcp = await installCodexMcp();
61
+ return { policy, mcp };
62
+ }
63
+
64
+ export async function removeCodex({ projectDir } = {}) {
65
+ const policy = await removeCodexPolicy({ projectDir });
66
+ const mcp = await removeCodexMcp();
67
+ return { policy, mcp };
68
+ }
69
+
70
+ export { BEGIN, END, TOML_BEGIN, TOML_END, codexConfigPath };
package/lib/cursor.mjs ADDED
@@ -0,0 +1,121 @@
1
+ // Cursor surface for the mcpbox harness — parity with the Claude CLAUDE.md
2
+ // plugin. Two idempotent writes:
3
+ // 1. `.cursor/rules/mcpbox-policy.mdc` — an always-applied rule. We own the
4
+ // whole file, so it's written wholesale (no in-file markers needed).
5
+ // 2. `.cursor/mcp.json` — upsert the `mcpbox` HTTP server entry, leaving any
6
+ // other servers the user configured untouched.
7
+ //
8
+ // Rule body is BLOCK_BODY from lib/policy.mjs — the shared source of truth.
9
+
10
+ import { promises as fs } from "node:fs";
11
+ import { dirname, join, resolve } from "node:path";
12
+ import { BLOCK_BODY, MCP_URL } from "./policy.mjs";
13
+
14
+ const RULE_FRONTMATTER = `---
15
+ description: Workspace policy — mcpbox is the default tracker AND maturity pipeline (torii→…→fujin→daruma). Triggered by mentions of "трекер", "tracker", "task tracker", "backlog", "pipeline", "план", "задача". Overrides ad-hoc trackers and OMC plan files.
16
+ globs: ["**/*"]
17
+ alwaysApply: true
18
+ ---
19
+
20
+ `;
21
+
22
+ function ruleContent() {
23
+ return RULE_FRONTMATTER + BLOCK_BODY;
24
+ }
25
+
26
+ function rulePath(projectDir) {
27
+ const dir = projectDir ? resolve(projectDir) : process.cwd();
28
+ return join(dir, ".cursor", "rules", "mcpbox-policy.mdc");
29
+ }
30
+
31
+ function mcpPath(projectDir) {
32
+ const dir = projectDir ? resolve(projectDir) : process.cwd();
33
+ return join(dir, ".cursor", "mcp.json");
34
+ }
35
+
36
+ const MCP_ENTRY = { type: "http", url: MCP_URL };
37
+
38
+ // `.cursor/rules/mcpbox-policy.mdc` — whole-file managed rule.
39
+ export async function installCursorRule({ projectDir } = {}) {
40
+ const target = rulePath(projectDir);
41
+ const content = ruleContent();
42
+ await fs.mkdir(dirname(target), { recursive: true });
43
+ let existing = null;
44
+ try {
45
+ existing = await fs.readFile(target, "utf8");
46
+ } catch (err) {
47
+ if (err.code !== "ENOENT") throw err;
48
+ }
49
+ if (existing === content) return { action: "unchanged", path: target };
50
+ await fs.writeFile(target, content);
51
+ return { action: existing === null ? "installed" : "updated", path: target };
52
+ }
53
+
54
+ export async function removeCursorRule({ projectDir } = {}) {
55
+ const target = rulePath(projectDir);
56
+ try {
57
+ await fs.unlink(target);
58
+ return { action: "removed-file", path: target };
59
+ } catch (err) {
60
+ if (err.code === "ENOENT") return { action: "missing", path: target };
61
+ throw err;
62
+ }
63
+ }
64
+
65
+ // `.cursor/mcp.json` — upsert only the `mcpbox` entry, preserve the rest.
66
+ async function readMcp(target) {
67
+ try {
68
+ const doc = JSON.parse(await fs.readFile(target, "utf8"));
69
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
70
+ throw new Error(`${target} is not a JSON object`);
71
+ }
72
+ if (!doc.mcpServers || typeof doc.mcpServers !== "object") doc.mcpServers = {};
73
+ return doc;
74
+ } catch (err) {
75
+ if (err.code === "ENOENT") return { mcpServers: {} };
76
+ throw err;
77
+ }
78
+ }
79
+
80
+ export async function installCursorMcp({ projectDir } = {}) {
81
+ const target = mcpPath(projectDir);
82
+ const doc = await readMcp(target);
83
+ const before = doc.mcpServers.mcpbox;
84
+ if (before && JSON.stringify(before) === JSON.stringify(MCP_ENTRY)) {
85
+ return { action: "unchanged", path: target };
86
+ }
87
+ doc.mcpServers.mcpbox = MCP_ENTRY;
88
+ await fs.mkdir(dirname(target), { recursive: true });
89
+ await fs.writeFile(target, JSON.stringify(doc, null, 2) + "\n");
90
+ return { action: before ? "updated" : "installed", path: target };
91
+ }
92
+
93
+ export async function removeCursorMcp({ projectDir } = {}) {
94
+ const target = mcpPath(projectDir);
95
+ let doc;
96
+ try {
97
+ doc = await readMcp(target);
98
+ } catch (err) {
99
+ if (err.code === "ENOENT") return { action: "missing", path: target };
100
+ throw err;
101
+ }
102
+ if (!doc.mcpServers.mcpbox) return { action: "missing", path: target };
103
+ delete doc.mcpServers.mcpbox;
104
+ await fs.writeFile(target, JSON.stringify(doc, null, 2) + "\n");
105
+ return { action: "removed-block", path: target };
106
+ }
107
+
108
+ // Both surfaces at once (what `mcpbox-claude cursor-init` calls).
109
+ export async function installCursor({ projectDir } = {}) {
110
+ const rule = await installCursorRule({ projectDir });
111
+ const mcp = await installCursorMcp({ projectDir });
112
+ return { rule, mcp };
113
+ }
114
+
115
+ export async function removeCursor({ projectDir } = {}) {
116
+ const rule = await removeCursorRule({ projectDir });
117
+ const mcp = await removeCursorMcp({ projectDir });
118
+ return { rule, mcp };
119
+ }
120
+
121
+ export { rulePath, mcpPath };
@@ -0,0 +1,178 @@
1
+ // Minimal MCP (Model Context Protocol) client over stdio JSON-RPC for ouroboros.
2
+ // Speaks line-delimited JSON (one message per newline) — confirmed via probe
3
+ // against `ouroboros mcp serve` (mcp@1.27.0). Does not pull the @modelcontextprotocol
4
+ // SDK to keep omo dependency-free.
5
+ //
6
+ // Lifecycle:
7
+ // const client = new MCPClient();
8
+ // await client.start("ouroboros", ["mcp", "serve"], { cwd, stderrLog });
9
+ // await client.initialize();
10
+ // const result = await client.callTool("ouroboros_interview", { initial_context });
11
+ // await client.stop();
12
+ //
13
+ // `result` is the parsed `result.content[]` from MCP tool/call response — the
14
+ // caller deals with whatever shape ouroboros puts in there (usually a single
15
+ // TextContent whose `text` is JSON we then parse).
16
+
17
+ import { spawn } from "node:child_process";
18
+ import { createWriteStream } from "node:fs";
19
+
20
+ const REQUEST_TIMEOUT_MS = 120_000;
21
+
22
+ export class MCPClient {
23
+ constructor() {
24
+ this._proc = null;
25
+ this._buf = "";
26
+ this._nextId = 1;
27
+ this._pending = new Map();
28
+ this._initialized = false;
29
+ this._serverInfo = null;
30
+ this._stderrStream = null;
31
+ }
32
+
33
+ async start(cmd, args = [], { cwd = process.cwd(), stderrLog = null, env = process.env } = {}) {
34
+ if (this._proc) throw new Error("MCPClient already started");
35
+ this._proc = spawn(cmd, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] });
36
+
37
+ if (stderrLog) {
38
+ this._stderrStream = createWriteStream(stderrLog, { flags: "a" });
39
+ this._proc.stderr.pipe(this._stderrStream);
40
+ } else {
41
+ this._proc.stderr.on("data", () => {}); // drain to avoid backpressure
42
+ }
43
+
44
+ this._proc.stdout.setEncoding("utf8");
45
+ this._proc.stdout.on("data", (chunk) => this._onData(chunk));
46
+ this._proc.on("exit", (code, signal) => this._onExit(code, signal));
47
+ this._proc.on("error", (err) => this._failAll(err));
48
+ }
49
+
50
+ async initialize() {
51
+ const result = await this._call("initialize", {
52
+ protocolVersion: "2024-11-05",
53
+ capabilities: {},
54
+ clientInfo: { name: "omo", version: "0.0.4" },
55
+ });
56
+ this._serverInfo = result.serverInfo ?? null;
57
+ this._initialized = true;
58
+ // Per spec, follow up with a one-way "initialized" notification.
59
+ this._send({ jsonrpc: "2.0", method: "notifications/initialized" });
60
+ return result;
61
+ }
62
+
63
+ async callTool(name, args = {}) {
64
+ if (!this._initialized) throw new Error("MCPClient: call initialize() first");
65
+ const result = await this._call("tools/call", { name, arguments: args });
66
+ return this._unwrapToolResult(result);
67
+ }
68
+
69
+ async listTools() {
70
+ if (!this._initialized) throw new Error("MCPClient: call initialize() first");
71
+ const result = await this._call("tools/list", {});
72
+ return result.tools ?? [];
73
+ }
74
+
75
+ async stop() {
76
+ if (!this._proc) return;
77
+ const proc = this._proc;
78
+ this._proc = null;
79
+ try {
80
+ proc.stdin.end();
81
+ } catch { /* already closed */ }
82
+ // Give server up to 2s for graceful shutdown, then SIGTERM.
83
+ await new Promise((resolve) => {
84
+ const timer = setTimeout(() => {
85
+ try { proc.kill("SIGTERM"); } catch { /* gone */ }
86
+ resolve();
87
+ }, 2000);
88
+ proc.once("exit", () => { clearTimeout(timer); resolve(); });
89
+ });
90
+ if (this._stderrStream) this._stderrStream.end();
91
+ this._failAll(new Error("MCPClient stopped"));
92
+ }
93
+
94
+ // --- internals -----------------------------------------------------------
95
+
96
+ _call(method, params) {
97
+ const id = this._nextId++;
98
+ return new Promise((resolve, reject) => {
99
+ const timer = setTimeout(() => {
100
+ this._pending.delete(id);
101
+ reject(new Error(`MCP ${method} timeout after ${REQUEST_TIMEOUT_MS}ms`));
102
+ }, REQUEST_TIMEOUT_MS);
103
+ this._pending.set(id, {
104
+ resolve: (v) => { clearTimeout(timer); resolve(v); },
105
+ reject: (e) => { clearTimeout(timer); reject(e); },
106
+ });
107
+ this._send({ jsonrpc: "2.0", id, method, params });
108
+ });
109
+ }
110
+
111
+ _send(msg) {
112
+ if (!this._proc) throw new Error("MCPClient: server not running");
113
+ this._proc.stdin.write(JSON.stringify(msg) + "\n");
114
+ }
115
+
116
+ _onData(chunk) {
117
+ this._buf += chunk;
118
+ let nl;
119
+ while ((nl = this._buf.indexOf("\n")) !== -1) {
120
+ const line = this._buf.slice(0, nl).trim();
121
+ this._buf = this._buf.slice(nl + 1);
122
+ if (!line) continue;
123
+ let msg;
124
+ try {
125
+ msg = JSON.parse(line);
126
+ } catch {
127
+ // Server printed non-JSON noise on stdout (rare with ouroboros, but
128
+ // possible). Skip silently — the server's stderr captures structured
129
+ // diagnostics already.
130
+ continue;
131
+ }
132
+ this._dispatch(msg);
133
+ }
134
+ }
135
+
136
+ _dispatch(msg) {
137
+ if (msg.id != null && this._pending.has(msg.id)) {
138
+ const { resolve, reject } = this._pending.get(msg.id);
139
+ this._pending.delete(msg.id);
140
+ if (msg.error) {
141
+ const err = new Error(`MCP error ${msg.error.code}: ${msg.error.message}`);
142
+ err.data = msg.error.data;
143
+ reject(err);
144
+ } else {
145
+ resolve(msg.result);
146
+ }
147
+ }
148
+ // Otherwise: notification or unmatched response — drop it.
149
+ }
150
+
151
+ _onExit(code, signal) {
152
+ this._failAll(new Error(`MCP server exited (code=${code}, signal=${signal})`));
153
+ }
154
+
155
+ _failAll(err) {
156
+ for (const [, { reject }] of this._pending) reject(err);
157
+ this._pending.clear();
158
+ }
159
+
160
+ // MCP tool/call results come as `{ content: [{type, text}, ...], isError? }`.
161
+ // Most ouroboros tools return one TextContent whose `text` is JSON.
162
+ // Returns: { isError, content (raw array), text (joined text), parsed (best-effort JSON) }.
163
+ _unwrapToolResult(result) {
164
+ const content = Array.isArray(result?.content) ? result.content : [];
165
+ const text = content.map((c) => c?.text ?? "").join("");
166
+ let parsed = null;
167
+ if (text) {
168
+ try { parsed = JSON.parse(text); }
169
+ catch { /* leave as text */ }
170
+ }
171
+ return {
172
+ isError: Boolean(result?.isError),
173
+ content,
174
+ text,
175
+ parsed,
176
+ };
177
+ }
178
+ }