@goke/mcp 0.0.7 → 0.0.9

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,353 @@
1
+ /**
2
+ * Tests for createMcpAction — turning a CLI into a stdio MCP server.
3
+ *
4
+ * Uses InMemoryTransport (via createTransport option) to avoid actual stdio.
5
+ * Simulates the goke runtime by setting matchedCommandName before calling the action.
6
+ */
7
+
8
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
9
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
10
+ import { goke, wrapJsonSchema } from "goke";
11
+ import { z } from "zod";
12
+ import { describe, expect, it } from "vitest";
13
+ import { createMcpAction } from "../cli-to-mcp.js";
14
+
15
+ function firstTextContent(result: Awaited<ReturnType<Client["callTool"]>>): string {
16
+ const content = "content" in result ? (result as { content: Array<{ type: string; text?: string }> }).content : [];
17
+ return content.find((entry) => entry.type === "text")?.text ?? "";
18
+ }
19
+
20
+ describe("createMcpAction", () => {
21
+ it("returns an action function", () => {
22
+ const cli = goke("test");
23
+ const action = createMcpAction({ cli });
24
+ expect(typeof action).toBe("function");
25
+ });
26
+
27
+ it("starts an MCP server exposing CLI commands, excluding the mcp command", async () => {
28
+ const cli = goke("test");
29
+
30
+ cli
31
+ .command("greet", "Say hello")
32
+ .option("--name <name>", z.string().describe("Person to greet"))
33
+ .action((options: { name: string }) => `Hello ${options.name}!`);
34
+
35
+ cli
36
+ .command("add", "Add numbers")
37
+ .option("--a <a>", z.number().describe("First"))
38
+ .option("--b <b>", z.number().describe("Second"))
39
+ .action((options: { a: number; b: number }) => ({ sum: options.a + options.b }));
40
+
41
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
42
+
43
+ cli.command("mcp", "Start MCP server").action(
44
+ createMcpAction({
45
+ cli,
46
+ createTransport: () => serverTransport,
47
+ }),
48
+ );
49
+
50
+ // Simulate goke matching the "mcp" command (normally set by cli.parse())
51
+ cli.matchedCommandName = "mcp";
52
+
53
+ // Fire the action — starts the MCP server on the in-memory transport
54
+ const mcpCommand = cli.commands.find((c) => c.name === "mcp")!;
55
+ await mcpCommand.commandAction!({});
56
+
57
+ const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} });
58
+ await client.connect(clientTransport);
59
+
60
+ try {
61
+ const tools = await client.listTools();
62
+ const toolNames = tools.tools.map((t) => t.name).sort();
63
+ expect(toolNames).toEqual(["add", "greet"]);
64
+
65
+ const greetResult = await client.callTool({
66
+ name: "greet",
67
+ arguments: { name: "World" },
68
+ });
69
+ expect(firstTextContent(greetResult)).toBe("Hello World!");
70
+
71
+ const addResult = await client.callTool({
72
+ name: "add",
73
+ arguments: { a: 3, b: 7 },
74
+ });
75
+ expect(firstTextContent(addResult)).toBe('{\n "sum": 10\n}');
76
+ } finally {
77
+ await client.close();
78
+ }
79
+ });
80
+
81
+ it("composes user commandFilter with auto-exclusion", async () => {
82
+ const cli = goke("test");
83
+
84
+ cli.command("public-cmd", "Public command").action(() => "public");
85
+ cli.command("secret-cmd", "Secret command").action(() => "secret");
86
+
87
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
88
+
89
+ cli.command("mcp", "Start MCP server").action(
90
+ createMcpAction({
91
+ cli,
92
+ commandFilter: (name) => name !== "secret-cmd",
93
+ createTransport: () => serverTransport,
94
+ }),
95
+ );
96
+
97
+ cli.matchedCommandName = "mcp";
98
+
99
+ const mcpCommand = cli.commands.find((c) => c.name === "mcp")!;
100
+ await mcpCommand.commandAction!({});
101
+
102
+ const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} });
103
+ await client.connect(clientTransport);
104
+
105
+ try {
106
+ const tools = await client.listTools();
107
+ const toolNames = tools.tools.map((t) => t.name).sort();
108
+ // Both "mcp" (auto-excluded) and "secret-cmd" (user filter) excluded
109
+ expect(toolNames).toEqual(["public-cmd"]);
110
+ } finally {
111
+ await client.close();
112
+ }
113
+ });
114
+
115
+ it("works with multi-word command names", async () => {
116
+ const cli = goke("test");
117
+
118
+ cli
119
+ .command("db migrate", "Run migrations")
120
+ .action(() => "migrated");
121
+
122
+ cli
123
+ .command("db seed", "Seed database")
124
+ .action(() => "seeded");
125
+
126
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
127
+
128
+ cli.command("serve mcp", "Start MCP server").action(
129
+ createMcpAction({
130
+ cli,
131
+ createTransport: () => serverTransport,
132
+ }),
133
+ );
134
+
135
+ cli.matchedCommandName = "serve mcp";
136
+
137
+ const mcpCommand = cli.commands.find((c) => c.name === "serve mcp")!;
138
+ await mcpCommand.commandAction!({});
139
+
140
+ const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} });
141
+ await client.connect(clientTransport);
142
+
143
+ try {
144
+ const tools = await client.listTools();
145
+ const toolNames = tools.tools.map((t) => t.name).sort();
146
+ expect(toolNames).toEqual(["db_migrate", "db_seed"]);
147
+
148
+ const migrateResult = await client.callTool({
149
+ name: "db_migrate",
150
+ arguments: {},
151
+ });
152
+ expect(firstTextContent(migrateResult)).toBe("migrated");
153
+ } finally {
154
+ await client.close();
155
+ }
156
+ });
157
+
158
+ it("end-to-end: MCP client connects, discovers tools with schemas, calls tools, handles errors", async () => {
159
+ const cli = goke("my-app");
160
+
161
+ // String option command
162
+ cli
163
+ .command("search", "Search for items")
164
+ .option("--query <query>", z.string().describe("Search query"))
165
+ .option("--limit [limit]", z.number().default(10).describe("Max results"))
166
+ .action((options: { query: string; limit: number }) => {
167
+ return { results: [`result for "${options.query}"`], limit: options.limit };
168
+ });
169
+
170
+ // Boolean flag + positional arg command
171
+ cli
172
+ .command("deploy <env>", "Deploy to environment")
173
+ .option("--dry-run", z.boolean().default(false).describe("Simulate deployment"))
174
+ .action((env: string, options: { dryRun: boolean }) => {
175
+ return options.dryRun ? `dry-run deploy to ${env}` : `deployed to ${env}`;
176
+ });
177
+
178
+ // Command that returns a CallToolResult directly
179
+ cli
180
+ .command("status", "Get system status")
181
+ .action(() => ({
182
+ content: [{ type: "text", text: "all systems operational" }],
183
+ }));
184
+
185
+ // Command that throws an error (should be caught and returned as isError)
186
+ cli
187
+ .command("fail", "Always fails")
188
+ .action(() => {
189
+ throw new Error("something went wrong");
190
+ });
191
+
192
+ // Wrapped JSON schema command
193
+ cli
194
+ .command("config set", "Set a config value")
195
+ .option("--key <key>", wrapJsonSchema({ type: "string", description: "Config key" }))
196
+ .option("--value <value>", wrapJsonSchema({ type: "string", description: "Config value" }))
197
+ .action((options: { key: string; value: string }) => {
198
+ return `set ${options.key} = ${options.value}`;
199
+ });
200
+
201
+ // Commands without actions (should NOT appear as tools)
202
+ cli.command("no-action", "This has no action handler");
203
+
204
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
205
+
206
+ cli.command("mcp", "Start MCP server").action(
207
+ createMcpAction({
208
+ cli,
209
+ serverName: "my-app-mcp",
210
+ serverVersion: "2.5.0",
211
+ createTransport: () => serverTransport,
212
+ }),
213
+ );
214
+
215
+ cli.matchedCommandName = "mcp";
216
+
217
+ const mcpCommand = cli.commands.find((c) => c.name === "mcp")!;
218
+ await mcpCommand.commandAction!({});
219
+
220
+ const client = new Client({ name: "e2e-test-client", version: "1.0.0" }, { capabilities: {} });
221
+ await client.connect(clientTransport);
222
+
223
+ try {
224
+ // ── Server info ──
225
+ const serverInfo = client.getServerVersion();
226
+ expect(serverInfo).toMatchObject({ name: "my-app-mcp", version: "2.5.0" });
227
+
228
+ // ── Tool discovery ──
229
+ const tools = await client.listTools();
230
+ const toolNames = tools.tools.map((t) => t.name).sort();
231
+ // "mcp" auto-excluded, "no-action" has no handler → not mounted
232
+ expect(toolNames).toEqual(["config_set", "deploy", "fail", "search", "status"]);
233
+
234
+ // ── Verify schemas are propagated ──
235
+ const searchTool = tools.tools.find((t) => t.name === "search")!;
236
+ expect(searchTool.description).toBe("Search for items");
237
+ expect(searchTool.inputSchema.properties).toHaveProperty("query");
238
+ expect(searchTool.inputSchema.properties).toHaveProperty("limit");
239
+ expect(searchTool.inputSchema.required).toEqual(["query"]);
240
+
241
+ const deployTool = tools.tools.find((t) => t.name === "deploy")!;
242
+ expect(deployTool.inputSchema.properties).toHaveProperty("env");
243
+ expect(deployTool.inputSchema.properties).toHaveProperty("dryRun");
244
+ expect(deployTool.inputSchema.required).toEqual(["env"]);
245
+
246
+ // ── Call tool with schema-based options ──
247
+ const searchResult = await client.callTool({
248
+ name: "search",
249
+ arguments: { query: "hello", limit: 5 },
250
+ });
251
+ expect(firstTextContent(searchResult)).toBe(
252
+ '{\n "results": [\n "result for \\"hello\\""\n ],\n "limit": 5\n}',
253
+ );
254
+
255
+ // ── Call tool with positional args ──
256
+ const deployResult = await client.callTool({
257
+ name: "deploy",
258
+ arguments: { env: "production", dryRun: true },
259
+ });
260
+ expect(firstTextContent(deployResult)).toBe("dry-run deploy to production");
261
+
262
+ // ── Call tool that returns a raw CallToolResult ──
263
+ const statusResult = await client.callTool({
264
+ name: "status",
265
+ arguments: {},
266
+ });
267
+ expect(firstTextContent(statusResult)).toBe("all systems operational");
268
+
269
+ // ── Call tool that throws → error is caught and returned as isError ──
270
+ const failResult = await client.callTool({
271
+ name: "fail",
272
+ arguments: {},
273
+ });
274
+ expect(failResult.isError).toBe(true);
275
+ expect(firstTextContent(failResult)).toBe("something went wrong");
276
+
277
+ // ── Call tool with multi-word command name ──
278
+ const configResult = await client.callTool({
279
+ name: "config_set",
280
+ arguments: { key: "theme", value: "dark" },
281
+ });
282
+ expect(firstTextContent(configResult)).toBe("set theme = dark");
283
+
284
+ // ── Call nonexistent tool → MCP error ──
285
+ await expect(
286
+ client.callTool({ name: "nonexistent", arguments: {} }),
287
+ ).rejects.toThrow(/not found/i);
288
+ } finally {
289
+ await client.close();
290
+ }
291
+ });
292
+
293
+ it("returns empty tool list when only the mcp command exists", async () => {
294
+ const cli = goke("empty-app");
295
+
296
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
297
+
298
+ cli.command("mcp", "Start MCP server").action(
299
+ createMcpAction({
300
+ cli,
301
+ createTransport: () => serverTransport,
302
+ }),
303
+ );
304
+
305
+ cli.matchedCommandName = "mcp";
306
+
307
+ const mcpCommand = cli.commands.find((c) => c.name === "mcp")!;
308
+ await mcpCommand.commandAction!({});
309
+
310
+ const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} });
311
+ await client.connect(clientTransport);
312
+
313
+ try {
314
+ const tools = await client.listTools();
315
+ expect(tools.tools).toEqual([]);
316
+ } finally {
317
+ await client.close();
318
+ }
319
+ });
320
+
321
+ it("exposes all commands when matchedCommandName is not set", async () => {
322
+ const cli = goke("test");
323
+
324
+ cli.command("ping", "Ping").action(() => "pong");
325
+
326
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
327
+
328
+ cli.command("mcp", "Start MCP server").action(
329
+ createMcpAction({
330
+ cli,
331
+ createTransport: () => serverTransport,
332
+ }),
333
+ );
334
+
335
+ // Do NOT set matchedCommandName — simulates programmatic invocation
336
+ // without cli.parse(). All commands including "mcp" should be exposed.
337
+
338
+ const mcpCommand = cli.commands.find((c) => c.name === "mcp")!;
339
+ await mcpCommand.commandAction!({});
340
+
341
+ const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} });
342
+ await client.connect(clientTransport);
343
+
344
+ try {
345
+ const tools = await client.listTools();
346
+ const toolNames = tools.tools.map((t) => t.name).sort();
347
+ // Without matchedCommandName, auto-exclusion can't kick in
348
+ expect(toolNames).toEqual(["mcp", "ping"]);
349
+ } finally {
350
+ await client.close();
351
+ }
352
+ });
353
+ });
package/src/cli-to-mcp.ts CHANGED
@@ -7,6 +7,7 @@
7
7
 
8
8
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
9
9
  import type { Server } from "@modelcontextprotocol/sdk/server/index.js";
10
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
10
11
  import {
11
12
  CallToolRequestSchema,
12
13
  ErrorCode,
@@ -456,6 +457,73 @@ function getOrInstallState(server: Server): CliToMcpState {
456
457
  return state;
457
458
  }
458
459
 
460
+ export interface CreateMcpActionOptions {
461
+ /** The CLI instance whose commands will be exposed as MCP tools */
462
+ cli: Goke;
463
+ /** Additional filter for which commands to expose. The MCP command itself is always excluded. */
464
+ commandFilter?: (commandName: string) => boolean;
465
+ /** Custom tool name sanitizer */
466
+ sanitizeToolName?: (commandName: string) => string;
467
+ /** MCP server name. Defaults to the CLI name or 'cli-mcp-server' */
468
+ serverName?: string;
469
+ /** MCP server version. Defaults to '1.0.0' */
470
+ serverVersion?: string;
471
+ /** Custom transport factory. Defaults to StdioServerTransport (stdin/stdout). */
472
+ createTransport?: () => Transport | Promise<Transport>;
473
+ }
474
+
475
+ /**
476
+ * Create a goke action callback that starts an MCP server over stdio.
477
+ *
478
+ * Exposes all CLI commands as MCP tools, automatically excluding the
479
+ * command this action is attached to.
480
+ *
481
+ * @example
482
+ * ```ts
483
+ * cli.command('mcp', 'Start MCP server over stdio')
484
+ * .action(createMcpAction({ cli }))
485
+ * ```
486
+ */
487
+ export function createMcpAction(options: CreateMcpActionOptions): (...args: any[]) => Promise<void> {
488
+ const { cli, commandFilter: userFilter, sanitizeToolName, serverName, serverVersion, createTransport } = options;
489
+
490
+ return async () => {
491
+ // At call time, goke has already matched the command and set matchedCommandName.
492
+ // We use it to auto-exclude the MCP command itself from the tool list.
493
+ const mcpCommandName = cli.matchedCommandName;
494
+
495
+ const { Server: ServerClass } = await import("@modelcontextprotocol/sdk/server/index.js");
496
+
497
+ const server = new ServerClass(
498
+ {
499
+ name: serverName || cli.name || "cli-mcp-server",
500
+ version: serverVersion || "1.0.0",
501
+ },
502
+ { capabilities: {} },
503
+ );
504
+
505
+ addCliToolsToMcp({
506
+ cli,
507
+ server,
508
+ commandFilter: (name) => {
509
+ if (mcpCommandName && name === mcpCommandName) return false;
510
+ return userFilter ? userFilter(name) : true;
511
+ },
512
+ sanitizeToolName,
513
+ });
514
+
515
+ let transport: Transport;
516
+ if (createTransport) {
517
+ transport = await createTransport();
518
+ } else {
519
+ const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
520
+ transport = new StdioServerTransport();
521
+ }
522
+
523
+ await server.connect(transport);
524
+ };
525
+ }
526
+
459
527
  export function addCliToolsToMcp(options: AddCliToolsToMcpOptions): void {
460
528
  const { cli, commandFilter, sanitizeToolName = defaultSanitizeToolName } = options;
461
529
  const server = resolveServer(options.server);
package/src/index.ts CHANGED
@@ -49,8 +49,8 @@ import yaml from "js-yaml";
49
49
  import { FileOAuthProvider } from "./oauth-provider.js";
50
50
  import { startOAuthFlow, isAuthRequiredError } from "./auth.js";
51
51
  import type { McpOAuthConfig, McpOAuthState } from "./types.js";
52
- export { addCliToolsToMcp } from "./cli-to-mcp.js";
53
- export type { AddCliToolsToMcpOptions } from "./cli-to-mcp.js";
52
+ export { addCliToolsToMcp, createMcpAction } from "./cli-to-mcp.js";
53
+ export type { AddCliToolsToMcpOptions, CreateMcpActionOptions } from "./cli-to-mcp.js";
54
54
 
55
55
  // Public exports - only types that consumers need
56
56
  export type { Transport };