@goke/mcp 0.0.4

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/README.md ADDED
@@ -0,0 +1,217 @@
1
+ # @goke/mcp
2
+
3
+ Turn any [MCP](https://modelcontextprotocol.io) server into a CLI. Connects to the server, discovers tools, and generates CLI commands with typed arguments — automatically.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @goke/mcp goke
9
+ ```
10
+
11
+ `goke` is a peer dependency (the CLI framework that commands are registered on).
12
+
13
+ ## How it works
14
+
15
+ ```
16
+ MCP server Your CLI
17
+ ┌──────────────────┐ ┌──────────────────────────┐
18
+ │ tools/list │──discover──▸ │ mycli notion-search │
19
+ │ - notion-search │ │ mycli notion-get-page │
20
+ │ - notion-get-… │ │ mycli notion-create-… │
21
+ │ (JSON Schema) │──coerce───▸ │ --query <string> │
22
+ │ │ │ --pageId <string> │
23
+ └──────────────────┘ └──────────────────────────┘
24
+ ```
25
+
26
+ 1. **Discover** — calls `tools/list` on the MCP server to get every tool + its JSON Schema
27
+ 2. **Register** — creates a CLI command per tool with `--options` derived from the schema
28
+ 3. **Cache** — tools and session ID are cached for 1 hour (no network on subsequent runs)
29
+ 4. **Execute** — on invocation, connects to the server and calls the tool with coerced arguments
30
+ 5. **OAuth** — if the server returns 401, automatically opens the browser for OAuth, then retries
31
+
32
+ ## Quick start
33
+
34
+ ```ts
35
+ import { goke } from 'goke'
36
+ import { addMcpCommands } from '@goke/mcp'
37
+ import type { McpOAuthState, CachedMcpTools } from '@goke/mcp'
38
+
39
+ const cli = goke('notion-mcp-cli')
40
+
41
+ await addMcpCommands({
42
+ cli,
43
+ getMcpUrl: () => 'https://mcp.notion.com/mcp',
44
+ oauth: {
45
+ clientName: 'Notion CLI',
46
+ load: () => loadConfig().oauthState,
47
+ save: (state) => saveConfig({ oauthState: state }),
48
+ },
49
+ loadCache: () => loadConfig().cache,
50
+ saveCache: (cache) => saveConfig({ cache }),
51
+ })
52
+
53
+ cli.help()
54
+ cli.parse()
55
+ ```
56
+
57
+ That's it. Every tool the MCP server exposes becomes a CLI command:
58
+
59
+ ```bash
60
+ notion-mcp-cli notion-search --query "meeting notes"
61
+ notion-mcp-cli notion-retrieve-page --page_id "abc123"
62
+ notion-mcp-cli notion-list-users
63
+ ```
64
+
65
+ ## Full example (with config persistence)
66
+
67
+ This is the pattern used by [notion-mcp-cli](../notion-mcp-cli):
68
+
69
+ ```ts
70
+ import { goke } from 'goke'
71
+ import { addMcpCommands } from '@goke/mcp'
72
+ import type { McpOAuthState, CachedMcpTools } from '@goke/mcp'
73
+ import fs from 'node:fs'
74
+ import path from 'node:path'
75
+ import os from 'node:os'
76
+
77
+ // --- Config persistence (JSON file in ~/.myapp/) ---
78
+
79
+ const CONFIG_DIR = path.join(os.homedir(), '.myapp')
80
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json')
81
+
82
+ interface AppConfig {
83
+ mcpUrl: string
84
+ oauthState?: McpOAuthState
85
+ cache?: CachedMcpTools
86
+ }
87
+
88
+ function loadConfig(): AppConfig {
89
+ try {
90
+ return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'))
91
+ } catch {
92
+ return { mcpUrl: 'https://mcp.notion.com/mcp' }
93
+ }
94
+ }
95
+
96
+ function saveConfig(partial: Partial<AppConfig>): void {
97
+ const merged = { ...loadConfig(), ...partial }
98
+ fs.mkdirSync(CONFIG_DIR, { recursive: true })
99
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2))
100
+ }
101
+
102
+ // --- CLI setup ---
103
+
104
+ const cli = goke('myapp')
105
+
106
+ await addMcpCommands({
107
+ cli,
108
+ clientName: 'myapp',
109
+ getMcpUrl: () => loadConfig().mcpUrl,
110
+ oauth: {
111
+ clientName: 'My App',
112
+ load: () => loadConfig().oauthState,
113
+ save: (state) => saveConfig({ oauthState: state }),
114
+ },
115
+ loadCache: () => loadConfig().cache,
116
+ saveCache: (cache) => saveConfig({ cache }),
117
+ })
118
+
119
+ // Custom commands alongside auto-generated MCP commands
120
+ cli
121
+ .command('login', 'Save MCP URL')
122
+ .option('--url <url>', 'MCP server URL')
123
+ .action((options) => {
124
+ saveConfig({ mcpUrl: options.url })
125
+ console.log(`Saved: ${options.url}`)
126
+ })
127
+
128
+ cli.command('logout', 'Clear tokens').action(() => {
129
+ saveConfig({ oauthState: undefined, cache: undefined })
130
+ console.log('Logged out')
131
+ })
132
+
133
+ cli.help()
134
+ cli.parse()
135
+ ```
136
+
137
+ ## API
138
+
139
+ ### `addMcpCommands(options)`
140
+
141
+ Registers MCP tool commands on a goke CLI instance.
142
+
143
+ | Option | Type | Default | Description |
144
+ |--------|------|---------|-------------|
145
+ | `cli` | `Goke` | **required** | The goke CLI instance to add commands to |
146
+ | `getMcpUrl` | `() => string \| undefined` | — | Returns the MCP server URL |
147
+ | `commandPrefix` | `string` | `''` | Prefix for commands (e.g. `'mcp'` makes `mcp notion-search`) |
148
+ | `clientName` | `string` | `'mcp-cli-client'` | Name sent to the MCP server during connection |
149
+ | `oauth` | `McpOAuthConfig` | — | OAuth config for servers that require authentication |
150
+ | `loadCache` | `() => CachedMcpTools \| undefined` | **required** | Load cached tools from storage |
151
+ | `saveCache` | `(cache) => void` | **required** | Save cached tools to storage |
152
+
153
+ ### `McpOAuthConfig`
154
+
155
+ | Field | Type | Description |
156
+ |-------|------|-------------|
157
+ | `clientName` | `string` | Name shown on the OAuth consent screen |
158
+ | `load` | `() => McpOAuthState \| undefined` | Load persisted OAuth state |
159
+ | `save` | `(state) => void` | Save OAuth state after auth or token refresh |
160
+ | `onAuthUrl` | `(url: string) => void` | Custom handler for auth URL (default: opens browser) |
161
+ | `onAuthSuccess` | `() => void` | Called after successful authentication |
162
+ | `onAuthError` | `(error: string) => void` | Called on authentication failure |
163
+
164
+ ### Exports
165
+
166
+ ```ts
167
+ // Main function
168
+ export { addMcpCommands } from '@goke/mcp'
169
+
170
+ // Types
171
+ export type { AddMcpCommandsOptions } from '@goke/mcp'
172
+ export type { CachedMcpTools } from '@goke/mcp'
173
+ export type { McpOAuthConfig, McpOAuthState } from '@goke/mcp'
174
+ ```
175
+
176
+ ## OAuth flow
177
+
178
+ OAuth is **lazy** — no auth check happens on startup. The flow is:
179
+
180
+ ```
181
+ User runs command
182
+
183
+
184
+ Call MCP tool ───── success ──▸ Print result
185
+
186
+ 401 error
187
+
188
+
189
+ Start local server (random port)
190
+
191
+
192
+ Open browser ──▸ User authorizes
193
+
194
+
195
+ Receive callback with auth code
196
+
197
+
198
+ Exchange code for tokens
199
+
200
+
201
+ Save tokens via oauth.save()
202
+
203
+
204
+ Retry the original tool call
205
+ ```
206
+
207
+ Tokens are persisted via the `oauth.save()` callback you provide, so subsequent runs skip auth entirely.
208
+
209
+ ## Caching
210
+
211
+ Tools and the MCP session ID are cached for **1 hour** to avoid connecting on every invocation. The cache is managed through the `loadCache`/`saveCache` callbacks — you control where it's stored (file, database, env, etc.).
212
+
213
+ When the cache expires or a tool call fails, the cache is cleared and tools are re-fetched on the next run.
214
+
215
+ ## License
216
+
217
+ MIT
package/dist/auth.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import type { OAuthFlowResult, StartOAuthFlowOptions } from "./types.js";
2
+ /**
3
+ * Start the OAuth flow for an MCP server.
4
+ * This is an internal function - consumers should not call this directly.
5
+ * It is automatically triggered by addMcpCommands when a 401 error occurs.
6
+ *
7
+ * This function:
8
+ * 1. Starts a local callback server on a random port
9
+ * 2. Initiates OAuth with the MCP server
10
+ * 3. Opens the browser for user authorization
11
+ * 4. Waits for the callback with the authorization code
12
+ * 5. Exchanges the code for tokens
13
+ * 6. Returns the OAuth state for persistence
14
+ */
15
+ export declare function startOAuthFlow(options: StartOAuthFlowOptions): Promise<OAuthFlowResult>;
16
+ /**
17
+ * Check if an error indicates authentication is required.
18
+ * Internal function used by addMcpCommands.
19
+ */
20
+ export declare function isAuthRequiredError(err: unknown): boolean;
21
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAiB,eAAe,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AA0BxF;;;;;;;;;;;;GAYG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,eAAe,CAAC,CA4E7F;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAazD"}
package/dist/auth.js ADDED
@@ -0,0 +1,122 @@
1
+ import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
2
+ import { FileOAuthProvider } from "./oauth-provider.js";
3
+ import { startCallbackServer } from "./local-callback-server.js";
4
+ /**
5
+ * Open a URL in the default browser.
6
+ * Uses platform-specific commands.
7
+ */
8
+ async function openBrowser(url) {
9
+ const { exec } = await import("node:child_process");
10
+ const { promisify } = await import("node:util");
11
+ const execAsync = promisify(exec);
12
+ const platform = process.platform;
13
+ const command = (() => {
14
+ if (platform === "darwin") {
15
+ return `open "${url}"`;
16
+ }
17
+ if (platform === "win32") {
18
+ return `start "" "${url}"`;
19
+ }
20
+ // Linux and others
21
+ return `xdg-open "${url}"`;
22
+ })();
23
+ await execAsync(command);
24
+ }
25
+ /**
26
+ * Start the OAuth flow for an MCP server.
27
+ * This is an internal function - consumers should not call this directly.
28
+ * It is automatically triggered by addMcpCommands when a 401 error occurs.
29
+ *
30
+ * This function:
31
+ * 1. Starts a local callback server on a random port
32
+ * 2. Initiates OAuth with the MCP server
33
+ * 3. Opens the browser for user authorization
34
+ * 4. Waits for the callback with the authorization code
35
+ * 5. Exchanges the code for tokens
36
+ * 6. Returns the OAuth state for persistence
37
+ */
38
+ export async function startOAuthFlow(options) {
39
+ const { serverUrl, clientName, existingState, onAuthUrl, timeout } = options;
40
+ // Start local callback server on random port
41
+ const callbackServer = await startCallbackServer({ timeout });
42
+ const { redirectUri, waitForCallback, close } = callbackServer;
43
+ try {
44
+ // Create OAuth provider with the dynamic redirect URI
45
+ const oauthProvider = new FileOAuthProvider({
46
+ serverUrl,
47
+ redirectUri,
48
+ clientName,
49
+ tokens: existingState?.tokens,
50
+ clientInformation: existingState?.clientInformation,
51
+ codeVerifier: existingState?.codeVerifier,
52
+ });
53
+ // Start the OAuth flow - this will trigger dynamic client registration
54
+ // and set the authorization URL on the provider
55
+ const authResult = await auth(oauthProvider, { serverUrl });
56
+ if (authResult !== "REDIRECT") {
57
+ // Auth succeeded without redirect (had valid tokens)
58
+ close();
59
+ return {
60
+ success: true,
61
+ state: oauthProvider.getState(),
62
+ };
63
+ }
64
+ // Get the authorization URL
65
+ const authUrl = oauthProvider.redirectStartAuthUrl;
66
+ if (!authUrl) {
67
+ close();
68
+ return {
69
+ success: false,
70
+ error: "No authorization URL returned from OAuth flow",
71
+ };
72
+ }
73
+ // Open browser or call custom handler
74
+ const authUrlString = authUrl.toString();
75
+ if (onAuthUrl) {
76
+ onAuthUrl(authUrlString);
77
+ }
78
+ else {
79
+ await openBrowser(authUrlString);
80
+ }
81
+ // Wait for the callback
82
+ const callback = await waitForCallback();
83
+ // Complete the OAuth flow by exchanging the code for tokens
84
+ const finalResult = await auth(oauthProvider, {
85
+ serverUrl,
86
+ authorizationCode: callback.code,
87
+ });
88
+ if (finalResult === "REDIRECT") {
89
+ return {
90
+ success: false,
91
+ error: "Unexpected redirect after code exchange",
92
+ };
93
+ }
94
+ return {
95
+ success: true,
96
+ state: oauthProvider.getState(),
97
+ };
98
+ }
99
+ catch (err) {
100
+ close();
101
+ return {
102
+ success: false,
103
+ error: err instanceof Error ? err.message : String(err),
104
+ };
105
+ }
106
+ }
107
+ /**
108
+ * Check if an error indicates authentication is required.
109
+ * Internal function used by addMcpCommands.
110
+ */
111
+ export function isAuthRequiredError(err) {
112
+ if (!(err instanceof Error)) {
113
+ return false;
114
+ }
115
+ const message = err.message.toLowerCase();
116
+ return (message.includes("401") ||
117
+ message.includes("unauthorized") ||
118
+ message.includes("authentication required") ||
119
+ message.includes("not authenticated") ||
120
+ message.includes("invalid_token") ||
121
+ message.includes("missing or invalid access token"));
122
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * # MCP to CLI
3
+ *
4
+ * Dynamically generates CLI commands from MCP (Model Context Protocol) server tools.
5
+ * This module connects to any MCP server, discovers available tools, and creates
6
+ * corresponding CLI commands with proper argument parsing and validation.
7
+ *
8
+ * ## Features
9
+ *
10
+ * - **Auto-discovery**: Fetches all tools from the MCP server and creates CLI commands
11
+ * - **Caching**: Tools are cached for 1 hour to avoid reconnecting on every invocation
12
+ * - **Session reuse**: MCP session IDs are cached to skip initialization handshake
13
+ * - **Type-aware parsing**: Handles string, number, boolean, object, and array arguments
14
+ * - **JSON schema support**: Generates CLI options from tool input schemas
15
+ * - **OAuth support**: Automatic OAuth authentication on 401 errors (lazy auth)
16
+ *
17
+ * ## Example Usage
18
+ *
19
+ * ```ts
20
+ * import { goke } from 'goke'
21
+ * import { addMcpCommands } from '@goke/mcp'
22
+ *
23
+ * const cli = goke('mycli')
24
+ *
25
+ * await addMcpCommands({
26
+ * cli,
27
+ * getMcpUrl: () => 'https://your-mcp-server.com/mcp',
28
+ * oauth: {
29
+ * clientName: 'My CLI',
30
+ * load: () => loadConfig().oauthState,
31
+ * save: (state) => saveConfig({ oauthState: state }),
32
+ * },
33
+ * loadCache: () => loadConfig().cache,
34
+ * saveCache: (cache) => saveConfig({ cache }),
35
+ * })
36
+ *
37
+ * cli.parse()
38
+ * ```
39
+ *
40
+ * @module @goke/mcp
41
+ */
42
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
43
+ import type { Goke } from "goke";
44
+ import type { McpOAuthConfig } from "./types.js";
45
+ export type { Transport };
46
+ export type { McpOAuthConfig, McpOAuthState } from "./types.js";
47
+ export interface CachedMcpTools {
48
+ tools: Array<{
49
+ name: string;
50
+ description?: string;
51
+ inputSchema?: unknown;
52
+ }>;
53
+ timestamp: number;
54
+ sessionId?: string;
55
+ }
56
+ export interface AddMcpCommandsOptions {
57
+ cli: Goke;
58
+ /**
59
+ * Prefix for all MCP tool commands.
60
+ * Set to empty string '' for no prefix (e.g., 'notion-search' instead of 'mcp notion-search').
61
+ * @default ''
62
+ */
63
+ commandPrefix?: string;
64
+ /**
65
+ * Name used when connecting to the MCP server.
66
+ * @default 'mcp-cli-client'
67
+ */
68
+ clientName?: string;
69
+ /**
70
+ * Returns the MCP server URL, or undefined if not configured.
71
+ * Required when using the oauth option.
72
+ */
73
+ getMcpUrl?: () => string | undefined;
74
+ /**
75
+ * Returns a transport to connect to the MCP server, or null if not configured.
76
+ * If null is returned, no MCP tool commands will be registered.
77
+ * @param sessionId - Optional session ID from cache to reuse existing session
78
+ *
79
+ * @deprecated Use getMcpUrl + oauth instead for simpler setup
80
+ */
81
+ getMcpTransport?: (sessionId?: string) => Transport | null | Promise<Transport | null>;
82
+ /**
83
+ * OAuth configuration. When provided, enables automatic OAuth authentication.
84
+ *
85
+ * OAuth is lazy - no auth check happens on startup. Authentication is only
86
+ * triggered when a tool call returns 401. After successful auth, the tool
87
+ * call is automatically retried.
88
+ *
89
+ * The library handles everything internally:
90
+ * - Detecting 401 errors
91
+ * - Starting local callback server on random port
92
+ * - Opening browser for authorization
93
+ * - Exchanging code for tokens
94
+ * - Persisting tokens via save()
95
+ * - Retrying the failed tool call
96
+ */
97
+ oauth?: McpOAuthConfig;
98
+ /**
99
+ * Load cached MCP tools. Return undefined if no cache exists.
100
+ */
101
+ loadCache: () => CachedMcpTools | undefined;
102
+ /**
103
+ * Save cached MCP tools. Pass undefined to clear the cache.
104
+ */
105
+ saveCache: (cache: CachedMcpTools | undefined) => void;
106
+ }
107
+ /**
108
+ * Adds MCP tool commands to a goke CLI instance.
109
+ *
110
+ * Tools are cached for 1 hour to avoid connecting on every CLI invocation.
111
+ * Session ID is also cached to skip MCP initialization handshake.
112
+ *
113
+ * OAuth is lazy - authentication only happens when a 401 error occurs.
114
+ * After successful auth, the operation is automatically retried.
115
+ */
116
+ export declare function addMcpCommands(options: AddMcpCommandsOptions): Promise<void>;
117
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAIH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAKjC,OAAO,KAAK,EAAE,cAAc,EAAiB,MAAM,YAAY,CAAC;AAGhE,YAAY,EAAE,SAAS,EAAE,CAAC;AAC1B,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhE,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,KAAK,CAAC;QACX,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,WAAW,CAAC,EAAE,OAAO,CAAC;KACvB,CAAC,CAAC;IACH,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAID,MAAM,WAAW,qBAAqB;IACpC,GAAG,EAAE,IAAI,CAAC;IACV;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,MAAM,GAAG,SAAS,CAAC;IAErC;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,CAAC,SAAS,CAAC,EAAE,MAAM,KAAK,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;IAEvF;;;;;;;;;;;;;;OAcG;IACH,KAAK,CAAC,EAAE,cAAc,CAAC;IAEvB;;OAEG;IACH,SAAS,EAAE,MAAM,cAAc,GAAG,SAAS,CAAC;IAE5C;;OAEG;IACH,SAAS,EAAE,CAAC,KAAK,EAAE,cAAc,GAAG,SAAS,KAAK,IAAI,CAAC;CACxD;AAmID;;;;;;;;GAQG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAyMlF"}