argsbarg 1.3.0 → 1.4.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.
package/src/invoke.ts ADDED
@@ -0,0 +1,192 @@
1
+ /*
2
+ This module invokes leaf CLI handlers without exiting the process.
3
+ It parses argv against the user schema, captures stdout/stderr, and patches
4
+ process.exit so MCP tool calls can run handlers repeatedly.
5
+ */
6
+
7
+ import { CliContext } from "./context.ts";
8
+ import { parse, postParseValidate, ParseKind } from "./parse.ts";
9
+ import { CliCommand } from "./types.ts";
10
+ import { format } from "node:util";
11
+
12
+ /** Outcome of a non-exiting CLI invocation. */
13
+ export type CliInvokeKind = "ok" | "help" | "schema" | "error";
14
+
15
+ /** Result of cliInvoke: captured output and exit metadata without process.exit. */
16
+ export interface CliInvokeResult {
17
+ /** Invocation outcome. */
18
+ kind: CliInvokeKind;
19
+ /** Simulated exit code. */
20
+ exitCode: number;
21
+ /** Captured stdout during handler execution. */
22
+ stdout: string;
23
+ /** Captured stderr during handler execution. */
24
+ stderr: string;
25
+ /** Set when kind === "error" (parse/validation message). */
26
+ errorMsg?: string;
27
+ }
28
+
29
+ /** Thrown internally when a patched process.exit fires during handler execution. */
30
+ class CliInvokeExit extends Error {
31
+ /** Exit code passed to process.exit. */
32
+ readonly code: number;
33
+
34
+ /** Creates an exit signal with the given status code. */
35
+ constructor(code: number) {
36
+ super(`process.exit(${code})`);
37
+ this.name = "CliInvokeExit";
38
+ this.code = code;
39
+ }
40
+ }
41
+
42
+ /** Looks up a subcommand or routing node by `key`. */
43
+ function findChild(cmds: CliCommand[], name: string): CliCommand | undefined {
44
+ return cmds.find((c) => c.key === name);
45
+ }
46
+
47
+ /**
48
+ * Parses argv against the user root, runs the leaf handler, and returns captured output.
49
+ * Never calls process.exit.
50
+ */
51
+ export async function cliInvoke(root: CliCommand, argv: string[]): Promise<CliInvokeResult> {
52
+ let pr = parse(root, argv);
53
+ pr = postParseValidate(root, pr);
54
+
55
+ if (pr.kind === ParseKind.Help) {
56
+ return {
57
+ kind: "help",
58
+ exitCode: 1,
59
+ stdout: "",
60
+ stderr: "",
61
+ errorMsg: "Help is not available via MCP tool calls.",
62
+ };
63
+ }
64
+
65
+ if (pr.kind === ParseKind.Schema) {
66
+ return {
67
+ kind: "schema",
68
+ exitCode: 1,
69
+ stdout: "",
70
+ stderr: "",
71
+ errorMsg: "Schema export is not available via MCP tool calls.",
72
+ };
73
+ }
74
+
75
+ if (pr.kind === ParseKind.Error) {
76
+ return {
77
+ kind: "error",
78
+ exitCode: 1,
79
+ stdout: "",
80
+ stderr: pr.errorMsg,
81
+ errorMsg: pr.errorMsg,
82
+ };
83
+ }
84
+
85
+ let current: CliCommand = root;
86
+ for (const seg of pr.path) {
87
+ const ch = findChild(current.commands ?? [], seg);
88
+ if (!ch) {
89
+ return {
90
+ kind: "error",
91
+ exitCode: 1,
92
+ stdout: "",
93
+ stderr: "Internal error: missing handler for path.",
94
+ errorMsg: "Internal error: missing handler for path.",
95
+ };
96
+ }
97
+ current = ch;
98
+ }
99
+
100
+ if (!("handler" in current) || !current.handler) {
101
+ return {
102
+ kind: "error",
103
+ exitCode: 1,
104
+ stdout: "",
105
+ stderr: "Internal error: missing handler for path.",
106
+ errorMsg: "Internal error: missing handler for path.",
107
+ };
108
+ }
109
+
110
+ const handler = current.handler;
111
+ const ctx = new CliContext(root.key, pr.path, pr.args, pr.opts, root);
112
+
113
+ let stdout = "";
114
+ let stderr = "";
115
+ const origExit = process.exit;
116
+ const origStdoutWrite = process.stdout.write.bind(process.stdout);
117
+ const origStderrWrite = process.stderr.write.bind(process.stderr);
118
+ const origConsoleLog = console.log;
119
+ const origConsoleError = console.error;
120
+ const origConsoleInfo = console.info;
121
+ const origConsoleWarn = console.warn;
122
+
123
+ process.exit = ((code?: number) => {
124
+ throw new CliInvokeExit(code ?? 0);
125
+ }) as typeof process.exit;
126
+
127
+ process.stdout.write = ((chunk: string | Uint8Array, ...args: unknown[]) => {
128
+ stdout += typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);
129
+ if (typeof args[0] === "function") {
130
+ (args[0] as () => void)();
131
+ }
132
+ return true;
133
+ }) as typeof process.stdout.write;
134
+
135
+ process.stderr.write = ((chunk: string | Uint8Array, ...args: unknown[]) => {
136
+ stderr += typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk);
137
+ if (typeof args[0] === "function") {
138
+ (args[0] as () => void)();
139
+ }
140
+ return true;
141
+ }) as typeof process.stderr.write;
142
+
143
+ console.log = (...args: unknown[]) => {
144
+ stdout += format(...args) + "\n";
145
+ };
146
+ console.info = (...args: unknown[]) => {
147
+ stdout += format(...args) + "\n";
148
+ };
149
+ console.warn = (...args: unknown[]) => {
150
+ stderr += format(...args) + "\n";
151
+ };
152
+ console.error = (...args: unknown[]) => {
153
+ stderr += format(...args) + "\n";
154
+ };
155
+
156
+ try {
157
+ await Promise.resolve(handler(ctx));
158
+ return { kind: "ok", exitCode: 0, stdout, stderr };
159
+ } catch (err) {
160
+ if (err instanceof CliInvokeExit) {
161
+ if (err.code === 0) {
162
+ return { kind: "ok", exitCode: 0, stdout, stderr };
163
+ }
164
+ const msg = stderr.trim() || `Exit code ${err.code}`;
165
+ return { kind: "error", exitCode: err.code, stdout, stderr, errorMsg: msg };
166
+ }
167
+ if (err instanceof Error) {
168
+ return {
169
+ kind: "error",
170
+ exitCode: 1,
171
+ stdout,
172
+ stderr: err.message + "\n",
173
+ errorMsg: err.message,
174
+ };
175
+ }
176
+ return {
177
+ kind: "error",
178
+ exitCode: 1,
179
+ stdout,
180
+ stderr: "Unknown error\n",
181
+ errorMsg: "Unknown error",
182
+ };
183
+ } finally {
184
+ process.exit = origExit;
185
+ process.stdout.write = origStdoutWrite;
186
+ process.stderr.write = origStderrWrite;
187
+ console.log = origConsoleLog;
188
+ console.error = origConsoleError;
189
+ console.info = origConsoleInfo;
190
+ console.warn = origConsoleWarn;
191
+ }
192
+ }
@@ -0,0 +1,57 @@
1
+ /*
2
+ This module builds MCP tools/call success results from captured handler output.
3
+ */
4
+
5
+ /** Text content block in an MCP tool result. */
6
+ export interface McpTextContent {
7
+ type: "text";
8
+ text: string;
9
+ }
10
+
11
+ /** Successful MCP tools/call result payload. */
12
+ export interface McpToolCallSuccess {
13
+ content: McpTextContent[];
14
+ structuredContent?: unknown;
15
+ isError: false;
16
+ }
17
+
18
+ /** Parses stdout as JSON when the full trimmed string is valid JSON. */
19
+ function parseStructuredStdout(stdout: string): unknown | undefined {
20
+ const trimmed = stdout.trim();
21
+ if (trimmed.length === 0) {
22
+ return undefined;
23
+ }
24
+ try {
25
+ return JSON.parse(trimmed) as unknown;
26
+ } catch {
27
+ return undefined;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Builds a successful tools/call result from captured handler stdout/stderr.
33
+ * stderr is a second content block when non-empty; structuredContent is set when stdout is JSON.
34
+ */
35
+ export function buildToolCallSuccess(stdout: string, stderr: string): McpToolCallSuccess {
36
+ const content: McpTextContent[] = [];
37
+ if (stdout.length > 0) {
38
+ content.push({ type: "text", text: stdout });
39
+ }
40
+ const errText = stderr.trim();
41
+ if (errText.length > 0) {
42
+ if (content.length === 0) {
43
+ content.push({ type: "text", text: "" });
44
+ }
45
+ content.push({ type: "text", text: errText });
46
+ }
47
+ if (content.length === 0) {
48
+ content.push({ type: "text", text: "" });
49
+ }
50
+
51
+ const structuredContent = parseStructuredStdout(stdout);
52
+ const result: McpToolCallSuccess = { content, isError: false };
53
+ if (structuredContent !== undefined) {
54
+ result.structuredContent = structuredContent;
55
+ }
56
+ return result;
57
+ }
@@ -0,0 +1,226 @@
1
+ /*
2
+ This module implements the MCP JSON-RPC server over stdio: initialize, tools,
3
+ resources, and ping. Responses are newline-delimited JSON on stdout only.
4
+ */
5
+
6
+ import { cliInvoke } from "../invoke.ts";
7
+ import { cliSchemaJson } from "../schema.ts";
8
+ import { CliCommand } from "../types.ts";
9
+ import { buildToolCallSuccess } from "./result.ts";
10
+ import {
11
+ collectMcpTools,
12
+ mcpToolCallToArgv,
13
+ resolveMcpSchemaUri,
14
+ resolveMcpServerInfo,
15
+ } from "./tools.ts";
16
+
17
+ const MCP_PROTOCOL_VERSION = "2024-11-05";
18
+
19
+ /** JSON-RPC request shape from stdin. */
20
+ interface JsonRpcRequest {
21
+ jsonrpc?: string;
22
+ id?: string | number | null;
23
+ method?: string;
24
+ params?: unknown;
25
+ }
26
+
27
+ /** Writes a JSON-RPC response line to stdout. */
28
+ function writeResponse(msg: Record<string, unknown>): void {
29
+ process.stdout.write(JSON.stringify(msg) + "\n");
30
+ }
31
+
32
+ /** Writes a JSON-RPC error response. */
33
+ function writeError(id: string | number | null | undefined, code: number, message: string): void {
34
+ if (id === undefined) {
35
+ return;
36
+ }
37
+ writeResponse({
38
+ jsonrpc: "2.0",
39
+ id,
40
+ error: { code, message },
41
+ });
42
+ }
43
+
44
+ /** Handles one NDJSON request line. */
45
+ async function handleRequestLine(root: CliCommand, line: string): Promise<void> {
46
+ let req: JsonRpcRequest;
47
+ try {
48
+ req = JSON.parse(line) as JsonRpcRequest;
49
+ } catch {
50
+ return;
51
+ }
52
+
53
+ const id = req.id;
54
+ const hasId = id !== undefined;
55
+
56
+ if (req.jsonrpc !== "2.0") {
57
+ if (hasId) {
58
+ writeError(id, -32600, "Invalid Request");
59
+ }
60
+ return;
61
+ }
62
+
63
+ const method = req.method ?? "";
64
+ const params = (req.params ?? {}) as Record<string, unknown>;
65
+
66
+ if (method === "notifications/initialized") {
67
+ return;
68
+ }
69
+
70
+ if (!hasId) {
71
+ return;
72
+ }
73
+
74
+ try {
75
+ if (method === "initialize") {
76
+ const info = resolveMcpServerInfo(root);
77
+ writeResponse({
78
+ jsonrpc: "2.0",
79
+ id,
80
+ result: {
81
+ protocolVersion: MCP_PROTOCOL_VERSION,
82
+ capabilities: { tools: {}, resources: {} },
83
+ serverInfo: { name: info.name, version: info.version },
84
+ },
85
+ });
86
+ return;
87
+ }
88
+
89
+ if (method === "ping") {
90
+ writeResponse({ jsonrpc: "2.0", id, result: {} });
91
+ return;
92
+ }
93
+
94
+ if (method === "tools/list") {
95
+ const tools = collectMcpTools(root).map((t) => ({
96
+ name: t.name,
97
+ description: t.description,
98
+ inputSchema: t.inputSchema,
99
+ }));
100
+ writeResponse({ jsonrpc: "2.0", id, result: { tools } });
101
+ return;
102
+ }
103
+
104
+ if (method === "tools/call") {
105
+ const name = params.name;
106
+ if (typeof name !== "string") {
107
+ writeError(id, -32602, "Invalid params: name required");
108
+ return;
109
+ }
110
+ const rawArgs = params.arguments;
111
+ if (rawArgs !== undefined && (typeof rawArgs !== "object" || rawArgs === null || Array.isArray(rawArgs))) {
112
+ writeError(id, -32602, "Invalid params: arguments must be an object");
113
+ return;
114
+ }
115
+ const toolList = collectMcpTools(root);
116
+ const tool = toolList.find((t) => t.name === name);
117
+ if (!tool) {
118
+ writeError(id, -32602, `Unknown tool: ${name}`);
119
+ return;
120
+ }
121
+ const argvResult = mcpToolCallToArgv(root, tool, (rawArgs ?? {}) as Record<string, unknown>);
122
+ if ("error" in argvResult) {
123
+ writeResponse({
124
+ jsonrpc: "2.0",
125
+ id,
126
+ result: {
127
+ content: [{ type: "text", text: argvResult.error }],
128
+ isError: true,
129
+ },
130
+ });
131
+ return;
132
+ }
133
+ const invokeResult = await cliInvoke(root, argvResult);
134
+ if (invokeResult.kind === "ok" && invokeResult.exitCode === 0) {
135
+ writeResponse({
136
+ jsonrpc: "2.0",
137
+ id,
138
+ result: buildToolCallSuccess(invokeResult.stdout, invokeResult.stderr),
139
+ });
140
+ return;
141
+ }
142
+ const errText = invokeResult.stderr.trim() || invokeResult.errorMsg || `Exit code ${invokeResult.exitCode}`;
143
+ writeResponse({
144
+ jsonrpc: "2.0",
145
+ id,
146
+ result: {
147
+ content: [{ type: "text", text: errText }],
148
+ isError: true,
149
+ },
150
+ });
151
+ return;
152
+ }
153
+
154
+ if (method === "resources/list") {
155
+ const uri = resolveMcpSchemaUri(root);
156
+ writeResponse({
157
+ jsonrpc: "2.0",
158
+ id,
159
+ result: {
160
+ resources: [
161
+ {
162
+ uri,
163
+ name: "cli-schema",
164
+ description: "Full CLI command tree (same as --schema).",
165
+ mimeType: "application/json",
166
+ },
167
+ ],
168
+ },
169
+ });
170
+ return;
171
+ }
172
+
173
+ if (method === "resources/read") {
174
+ const uri = params.uri;
175
+ if (typeof uri !== "string") {
176
+ writeError(id, -32602, "Invalid params: uri required");
177
+ return;
178
+ }
179
+ const expected = resolveMcpSchemaUri(root);
180
+ if (uri !== expected) {
181
+ writeError(id, -32602, `Unknown resource: ${uri}`);
182
+ return;
183
+ }
184
+ writeResponse({
185
+ jsonrpc: "2.0",
186
+ id,
187
+ result: {
188
+ contents: [
189
+ {
190
+ uri: expected,
191
+ mimeType: "application/json",
192
+ text: cliSchemaJson(root).trimEnd(),
193
+ },
194
+ ],
195
+ },
196
+ });
197
+ return;
198
+ }
199
+
200
+ writeError(id, -32601, "Method not found");
201
+ } catch (err) {
202
+ const message = err instanceof Error ? err.message : "Internal error";
203
+ writeError(id, -32603, message);
204
+ }
205
+ }
206
+
207
+ /** Runs the MCP NDJSON read loop on stdin until EOF. */
208
+ export async function mcpServeStdioLoop(root: CliCommand): Promise<void> {
209
+ let buffer = "";
210
+ for await (const chunk of Bun.stdin.stream()) {
211
+ buffer += new TextDecoder().decode(chunk);
212
+ let nl: number;
213
+ while ((nl = buffer.indexOf("\n")) !== -1) {
214
+ const line = buffer.slice(0, nl).trim();
215
+ buffer = buffer.slice(nl + 1);
216
+ if (line.length === 0) {
217
+ continue;
218
+ }
219
+ await handleRequestLine(root, line);
220
+ }
221
+ }
222
+ const trailing = buffer.trim();
223
+ if (trailing.length > 0) {
224
+ await handleRequestLine(root, trailing);
225
+ }
226
+ }
@@ -0,0 +1,209 @@
1
+ /*
2
+ This module maps CliCommand leaf nodes to MCP tool definitions and converts
3
+ flat JSON tool arguments into argv for cliInvoke.
4
+ */
5
+
6
+ import { readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { collectOptionDefs } from "../parse.ts";
9
+ import { CliCommand, CliOption, CliOptionKind, CliPositional } from "../types.ts";
10
+
11
+ /** Default URI for the CLI schema MCP resource. */
12
+ export const MCP_SCHEMA_URI_DEFAULT = "argsbarg://schema";
13
+
14
+ /** One MCP tool derived from a leaf CLI command. */
15
+ export interface McpToolDef {
16
+ /** MCP tool name (underscore-separated path). */
17
+ name: string;
18
+ /** Tool description from the leaf command. */
19
+ description: string;
20
+ /** Command path segments from the program root. */
21
+ path: string[];
22
+ /** Leaf command node. */
23
+ leaf: CliCommand;
24
+ /** JSON Schema for tools/call arguments. */
25
+ inputSchema: Record<string, unknown>;
26
+ }
27
+
28
+ /** Builds MCP tool description: "{cli path} — {description}". */
29
+ export function mcpToolDescription(path: string[], rootKey: string, description: string): string {
30
+ const prefix = path.length > 0 ? path.join(" ") : rootKey;
31
+ return `${prefix} — ${description}`;
32
+ }
33
+
34
+ /** Sanitizes a command key segment for MCP tool names. */
35
+ export function sanitizeToolSegment(key: string): string {
36
+ return key.replace(/[^a-zA-Z0-9]/g, "_");
37
+ }
38
+
39
+ /** Builds the MCP tool name for a leaf at the given path. */
40
+ export function mcpToolName(root: CliCommand, path: string[]): string {
41
+ if (path.length === 0) {
42
+ return sanitizeToolSegment(root.key);
43
+ }
44
+ return path.map(sanitizeToolSegment).join("_");
45
+ }
46
+
47
+ /** JSON Schema property for one option. */
48
+ function optionProperty(opt: CliOption): Record<string, unknown> {
49
+ const base = { description: opt.description };
50
+ switch (opt.kind) {
51
+ case CliOptionKind.Presence:
52
+ return { type: "boolean", ...base };
53
+ case CliOptionKind.String:
54
+ return { type: "string", ...base };
55
+ case CliOptionKind.Number:
56
+ return { type: "number", ...base };
57
+ }
58
+ }
59
+
60
+ /** JSON Schema property for one positional slot. */
61
+ function positionalProperty(p: CliPositional): Record<string, unknown> {
62
+ const base = { description: p.description };
63
+ const { argMax = 1 } = p;
64
+ if (argMax === 0) {
65
+ return { type: "array", items: { type: "string" }, ...base };
66
+ }
67
+ return { type: "string", ...base };
68
+ }
69
+
70
+ /** Builds inputSchema for a leaf command. */
71
+ function buildInputSchema(root: CliCommand, path: string[], leaf: CliCommand): Record<string, unknown> {
72
+ const properties: Record<string, unknown> = {};
73
+ const required: string[] = [];
74
+
75
+ for (const opt of collectOptionDefs(root, path)) {
76
+ properties[opt.name] = optionProperty(opt);
77
+ if (opt.required) {
78
+ required.push(opt.name);
79
+ }
80
+ }
81
+
82
+ for (const p of leaf.positionals ?? []) {
83
+ properties[p.name] = positionalProperty(p);
84
+ const { argMin = 1, argMax = 1 } = p;
85
+ if (argMax === 1 && argMin >= 1) {
86
+ required.push(p.name);
87
+ }
88
+ }
89
+
90
+ const schema: Record<string, unknown> = {
91
+ type: "object",
92
+ properties,
93
+ additionalProperties: false,
94
+ };
95
+ if (required.length > 0) {
96
+ schema.required = required;
97
+ }
98
+ return schema;
99
+ }
100
+
101
+ /** Recursively collects MCP tool definitions from user leaf commands. */
102
+ export function collectMcpTools(root: CliCommand): McpToolDef[] {
103
+ const out: McpToolDef[] = [];
104
+
105
+ /** Walks the command tree and appends leaf tools. */
106
+ function walk(cmd: CliCommand, path: string[]): void {
107
+ if ("handler" in cmd && cmd.handler) {
108
+ if (cmd.key === "completion" || cmd.key === "mcp") {
109
+ return;
110
+ }
111
+ if (cmd.mcpTool?.enabled === false) {
112
+ return;
113
+ }
114
+ out.push({
115
+ name: mcpToolName(root, path),
116
+ description: mcpToolDescription(path, root.key, cmd.description),
117
+ path,
118
+ leaf: cmd,
119
+ inputSchema: buildInputSchema(root, path, cmd),
120
+ });
121
+ return;
122
+ }
123
+ for (const ch of cmd.commands ?? []) {
124
+ walk(ch, [...path, ch.key]);
125
+ }
126
+ }
127
+
128
+ if ("handler" in root && root.handler) {
129
+ walk(root, []);
130
+ } else {
131
+ for (const ch of root.commands ?? []) {
132
+ walk(ch, [ch.key]);
133
+ }
134
+ }
135
+
136
+ return out;
137
+ }
138
+
139
+ /** Reads package.json version from cwd synchronously. */
140
+ function resolveMcpVersionFromPackageJson(): string | undefined {
141
+ try {
142
+ const text = readFileSync(join(process.cwd(), "package.json"), "utf8");
143
+ const version = (JSON.parse(text) as { version?: string }).version;
144
+ return typeof version === "string" ? version : undefined;
145
+ } catch {
146
+ return undefined;
147
+ }
148
+ }
149
+
150
+ /** Resolves MCP server name and version for initialize. */
151
+ export function resolveMcpServerInfo(root: CliCommand): { name: string; version: string } {
152
+ return {
153
+ name: root.mcpServer?.name ?? root.key,
154
+ version: root.mcpServer?.version ?? resolveMcpVersionFromPackageJson() ?? "0.0.0",
155
+ };
156
+ }
157
+
158
+ /** Resolves the schema resource URI for this app. */
159
+ export function resolveMcpSchemaUri(root: CliCommand): string {
160
+ return root.mcpServer?.schemaResourceUri ?? MCP_SCHEMA_URI_DEFAULT;
161
+ }
162
+
163
+ /** Converts flat MCP tool arguments to argv for cliInvoke. */
164
+ export function mcpToolCallToArgv(
165
+ root: CliCommand,
166
+ tool: McpToolDef,
167
+ args: Record<string, unknown>,
168
+ ): string[] | { error: string } {
169
+ const argv = [...tool.path];
170
+
171
+ for (const opt of collectOptionDefs(root, tool.path)) {
172
+ const val = args[opt.name];
173
+ if (val === undefined) {
174
+ continue;
175
+ }
176
+ if (opt.kind === CliOptionKind.Presence) {
177
+ if (val === true) {
178
+ argv.push(`--${opt.name}`);
179
+ }
180
+ continue;
181
+ }
182
+ argv.push(`--${opt.name}`, String(val));
183
+ }
184
+
185
+ for (const p of tool.leaf.positionals ?? []) {
186
+ const val = args[p.name];
187
+ const { argMin = 1, argMax = 1 } = p;
188
+
189
+ if (argMax === 0) {
190
+ if (!Array.isArray(val)) {
191
+ return { error: `Missing argument: ${p.name}` };
192
+ }
193
+ for (const item of val) {
194
+ argv.push(String(item));
195
+ }
196
+ continue;
197
+ }
198
+
199
+ if (val === undefined) {
200
+ if (argMin >= 1) {
201
+ return { error: `Missing argument: ${p.name}` };
202
+ }
203
+ continue;
204
+ }
205
+ argv.push(String(val));
206
+ }
207
+
208
+ return argv;
209
+ }
package/src/mcp.ts ADDED
@@ -0,0 +1,24 @@
1
+ /*
2
+ This module starts the ArgsBarg MCP stdio server for opt-in program roots.
3
+ */
4
+
5
+ import { mcpServeStdioLoop } from "./mcp/server.ts";
6
+ import { CliCommand } from "./types.ts";
7
+
8
+ /**
9
+ * Runs the MCP JSON-RPC server on stdin/stdout until stdin closes, then exits.
10
+ * Caller must ensure `root.mcpServer` is set.
11
+ */
12
+ export async function cliMcpServeStdio(root: CliCommand): Promise<never> {
13
+ try {
14
+ await mcpServeStdioLoop(root);
15
+ process.exit(0);
16
+ } catch (err) {
17
+ if (err instanceof Error) {
18
+ process.stderr.write(err.message + "\n");
19
+ } else {
20
+ process.stderr.write("MCP server error.\n");
21
+ }
22
+ process.exit(1);
23
+ }
24
+ }