conductor-node-mcp 14.23.8 → 14.24.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.
Files changed (65) hide show
  1. package/README.md +10 -7
  2. package/bridge.d.mts +11 -0
  3. package/bridge.d.mts.map +1 -0
  4. package/bridge.d.ts +11 -0
  5. package/bridge.d.ts.map +1 -0
  6. package/bridge.js +92 -0
  7. package/bridge.js.map +1 -0
  8. package/bridge.mjs +89 -0
  9. package/bridge.mjs.map +1 -0
  10. package/code-tool-paths.cjs +6 -0
  11. package/code-tool-paths.cjs.map +1 -1
  12. package/code-tool-paths.d.cts +1 -0
  13. package/code-tool-paths.d.cts.map +1 -1
  14. package/code-tool.d.mts.map +1 -1
  15. package/code-tool.d.ts.map +1 -1
  16. package/code-tool.js +4 -3
  17. package/code-tool.js.map +1 -1
  18. package/code-tool.mjs +3 -2
  19. package/code-tool.mjs.map +1 -1
  20. package/deno-bootstrap/index.ts +72 -0
  21. package/deno-http-worker/DenoHTTPWorker.d.mts +96 -0
  22. package/deno-http-worker/DenoHTTPWorker.d.mts.map +1 -0
  23. package/deno-http-worker/DenoHTTPWorker.d.ts +96 -0
  24. package/deno-http-worker/DenoHTTPWorker.d.ts.map +1 -0
  25. package/deno-http-worker/DenoHTTPWorker.js +310 -0
  26. package/deno-http-worker/DenoHTTPWorker.js.map +1 -0
  27. package/deno-http-worker/DenoHTTPWorker.mjs +302 -0
  28. package/deno-http-worker/DenoHTTPWorker.mjs.map +1 -0
  29. package/deno-http-worker/index.d.mts +2 -0
  30. package/deno-http-worker/index.d.mts.map +1 -0
  31. package/deno-http-worker/index.d.ts +2 -0
  32. package/deno-http-worker/index.d.ts.map +1 -0
  33. package/deno-http-worker/index.js +8 -0
  34. package/deno-http-worker/index.js.map +1 -0
  35. package/deno-http-worker/index.mjs +3 -0
  36. package/deno-http-worker/index.mjs.map +1 -0
  37. package/index.js +4 -3
  38. package/index.js.map +1 -1
  39. package/index.mjs +4 -3
  40. package/index.mjs.map +1 -1
  41. package/package.json +32 -3
  42. package/server.d.mts +1 -0
  43. package/server.d.mts.map +1 -1
  44. package/server.d.ts +1 -0
  45. package/server.d.ts.map +1 -1
  46. package/server.js +3 -2
  47. package/server.js.map +1 -1
  48. package/server.mjs +2 -1
  49. package/server.mjs.map +1 -1
  50. package/src/bridge.ts +113 -0
  51. package/src/code-tool-paths.cts +6 -0
  52. package/src/code-tool.ts +3 -2
  53. package/src/deno-http-worker/DenoHTTPWorker.ts +404 -0
  54. package/src/deno-http-worker/index.ts +8 -0
  55. package/src/index.ts +9 -8
  56. package/src/server.ts +3 -1
  57. package/src/stdio.ts +51 -12
  58. package/stdio.d.mts +3 -2
  59. package/stdio.d.mts.map +1 -1
  60. package/stdio.d.ts +3 -2
  61. package/stdio.d.ts.map +1 -1
  62. package/stdio.js +43 -11
  63. package/stdio.js.map +1 -1
  64. package/stdio.mjs +42 -10
  65. package/stdio.mjs.map +1 -1
package/src/bridge.ts ADDED
@@ -0,0 +1,113 @@
1
+ // Conductor stdio bridge. Over stdio this package runs no tools itself: it
2
+ // forwards every JSON-RPC message between the MCP client on stdin/stdout and
3
+ // the hosted Conductor MCP server over Streamable HTTP, authenticating with
4
+ // the user's secret key. The key is sent only as the Authorization header and
5
+ // is never logged.
6
+
7
+ import {
8
+ StreamableHTTPClientTransport,
9
+ StreamableHTTPError,
10
+ } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
11
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
12
+ import { isJSONRPCRequest, isJSONRPCResponse, type RequestId } from '@modelcontextprotocol/sdk/types.js';
13
+ import { getLogger } from './logger';
14
+ import { VERSION } from './server';
15
+
16
+ // Same shape the hosted server parses from x-stainless-mcp-client-permissions (see http.ts).
17
+ export type BridgePermissions = {
18
+ allow_http_gets?: boolean;
19
+ allowed_methods?: string[];
20
+ blocked_methods?: string[];
21
+ };
22
+
23
+ export async function runBridge({
24
+ upstreamUrl,
25
+ apiKey,
26
+ permissions,
27
+ }: {
28
+ upstreamUrl: string;
29
+ apiKey: string;
30
+ permissions: BridgePermissions;
31
+ }): Promise<void> {
32
+ const headers: Record<string, string> = {
33
+ Authorization: `Bearer ${apiKey}`,
34
+ 'User-Agent': `conductor-mcp-bridge/${VERSION}`,
35
+ };
36
+ if (Object.keys(permissions).length > 0) {
37
+ headers['x-stainless-mcp-client-permissions'] = JSON.stringify(permissions);
38
+ }
39
+ const upstream = new StreamableHTTPClientTransport(new URL(upstreamUrl), { requestInit: { headers } });
40
+ const client = new StdioServerTransport();
41
+ let initializeId: RequestId | undefined;
42
+
43
+ client.onmessage = (message) => {
44
+ if (isJSONRPCRequest(message) && message.method === 'initialize') {
45
+ initializeId = message.id;
46
+ }
47
+ upstream.send(message).catch((error: unknown) => {
48
+ if (isJSONRPCRequest(message)) {
49
+ void client.send({
50
+ jsonrpc: '2.0',
51
+ id: message.id,
52
+ error: describeUpstreamFailure(error, upstreamUrl),
53
+ });
54
+ }
55
+ });
56
+ };
57
+ upstream.onmessage = (message) => {
58
+ if (isJSONRPCResponse(message) && message.id === initializeId) {
59
+ const protocolVersion = message.result['protocolVersion'];
60
+ if (typeof protocolVersion === 'string') {
61
+ upstream.setProtocolVersion(protocolVersion);
62
+ }
63
+ }
64
+ void client.send(message);
65
+ };
66
+ // A failed upstream send is answered per request above; the SDK also reports it here.
67
+ upstream.onerror = (error) => getLogger().error({ error: error.message }, 'Upstream transport error');
68
+ client.onerror = (error) => console.error(`conductor-mcp-bridge: ${error.message}`);
69
+ process.stdout.on('error', () => process.exit(0));
70
+ process.stdin.once('end', () => {
71
+ void upstream.close().finally(() => process.exit(0));
72
+ });
73
+
74
+ await upstream.start();
75
+ await client.start();
76
+ }
77
+
78
+ function describeUpstreamFailure(
79
+ error: unknown,
80
+ upstreamUrl: string,
81
+ ): { code: number; message: string; data?: unknown } {
82
+ const host = new URL(upstreamUrl).host;
83
+ if (error instanceof StreamableHTTPError) {
84
+ const status = error.code ?? 0;
85
+ // The SDK uses non-HTTP codes (-1) for protocol-level failures such as an unexpected content type.
86
+ if (status <= 0) return { code: -32000, message: `Upstream error from ${host}: ${error.message}` };
87
+ const message =
88
+ status === 401 || status === 403 ?
89
+ `${host} rejected the secret key (HTTP ${status}). Check CONDUCTOR_SECRET_KEY.`
90
+ : status === 429 ? `${host} is rate limiting this key (HTTP 429). Retry shortly.`
91
+ : status >= 500 ? `${host} is unavailable right now (HTTP ${status}). Retry shortly.`
92
+ : `${host} rejected the request (HTTP ${status}).`;
93
+ const body = parseJsonBody(error.message);
94
+ return { code: -32000, message, ...(body !== undefined && { data: body }) };
95
+ }
96
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause.message : undefined;
97
+ const detail = cause ?? (error instanceof Error ? error.message : String(error));
98
+ return {
99
+ code: -32000,
100
+ message: `Could not reach ${host}: ${detail}. Check the network, proxy (NODE_USE_ENV_PROXY=1) and CA certificate (NODE_EXTRA_CA_CERTS) settings.`,
101
+ };
102
+ }
103
+
104
+ // The SDK folds the response body into its message; recover it when it is JSON.
105
+ function parseJsonBody(message: string): unknown {
106
+ const start = message.indexOf('{');
107
+ if (start < 0) return undefined;
108
+ try {
109
+ return JSON.parse(message.slice(start));
110
+ } catch {
111
+ return undefined;
112
+ }
113
+ }
@@ -3,3 +3,9 @@
3
3
  export function getWorkerPath(): string {
4
4
  return require.resolve('./code-tool-worker.mjs');
5
5
  }
6
+
7
+ // Shipped verbatim by `build` (cp -rp deno-bootstrap dist/); Deno receives its
8
+ // contents as a data: URL, so it is read, never imported.
9
+ export function getDenoBootstrapPath(): string {
10
+ return require.resolve('./deno-bootstrap/index.ts');
11
+ }
package/src/code-tool.ts CHANGED
@@ -8,6 +8,7 @@ import { getLogger } from './logger';
8
8
  import { SdkMethod } from './methods';
9
9
  import { McpCodeExecutionMode } from './options';
10
10
  import { ClientOptions } from 'conductor-node';
11
+ import { newDenoHTTPWorker } from './deno-http-worker';
11
12
 
12
13
  const prompt = `Runs JavaScript code to interact with the Conductor API.
13
14
 
@@ -189,8 +190,7 @@ const localDenoHandlerInner = async ({
189
190
  const fs = await import('node:fs');
190
191
  const path = await import('node:path');
191
192
  const url = await import('node:url');
192
- const { newDenoHTTPWorker } = await import('@valtown/deno-http-worker');
193
- const { getWorkerPath } = await import('./code-tool-paths.cjs');
193
+ const { getWorkerPath, getDenoBootstrapPath } = await import('./code-tool-paths.cjs');
194
194
  const workerPath = getWorkerPath();
195
195
 
196
196
  const client = reqContext.client;
@@ -243,6 +243,7 @@ const localDenoHandlerInner = async ({
243
243
 
244
244
  const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
245
245
  denoExecutable: denoPath,
246
+ denoBootstrapScriptPath: getDenoBootstrapPath(),
246
247
  runFlags: [
247
248
  `--node-modules-dir=manual`,
248
249
  `--allow-read=${allowRead}`,
@@ -0,0 +1,404 @@
1
+ // @ts-nocheck
2
+ // Vendored from the Conductor fork of @valtown/deno-http-worker, version
3
+ // 0.0.21-conductor.2 (github.com/conductor-is/deno-http-worker @ 6fab0714c57a,
4
+ // dist/DenoHTTPWorker.js). Upstream: github.com/val-town/deno-http-worker,
5
+ // copyright (c) Val Town, MIT License. Vendored so the package has no git
6
+ // dependency (npx on a machine without git failed with "spawn git ENOENT").
7
+ //
8
+ // Changes from the fork's dist file: the Deno bootstrap script path is passed
9
+ // by the caller (see code-tool-paths.cts and ../../deno-bootstrap/index.ts)
10
+ // instead of being resolved relative to import.meta.url, and the public
11
+ // types from dist/DenoHTTPWorker.d.ts are inlined. The runtime body is
12
+ // otherwise verbatim, including the fork's version-aware unix-socket grant
13
+ // under --allow-net for Deno >= 2.9.
14
+
15
+ import path from 'node:path';
16
+ import { spawn, execFile, type SpawnOptions } from 'node:child_process';
17
+ import readline from 'node:readline';
18
+ import http from 'node:http';
19
+ import fs from 'node:fs/promises';
20
+ import os from 'node:os';
21
+ import { fileURLToPath } from 'node:url';
22
+ import type { Readable } from 'node:stream';
23
+
24
+ type OnExitListener = (exitCode: number, signal: string) => void;
25
+
26
+ export interface MinimalChildProcess {
27
+ stdout: Readable | null;
28
+ stderr: Readable | null;
29
+ readonly pid?: number | undefined;
30
+ readonly exitCode: number | null;
31
+ kill(signal?: NodeJS.Signals | number): boolean;
32
+ on(event: string, listener: (...args: any[]) => void): this;
33
+ on(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
34
+ on(event: 'disconnect', listener: () => void): this;
35
+ on(event: 'error', listener: (err: Error) => void): this;
36
+ on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
37
+ on(event: 'spawn', listener: () => void): this;
38
+ }
39
+
40
+ export interface DenoWorkerOptions {
41
+ /**
42
+ * The path to the executable that should be use when spawning the subprocess.
43
+ * Defaults to "deno".
44
+ */
45
+ denoExecutable: string | string[];
46
+ /**
47
+ * The path to the script that bootstraps the worker environment in Deno.
48
+ * Required: this vendored copy ships no default (see deno-bootstrap/index.ts).
49
+ */
50
+ denoBootstrapScriptPath: string;
51
+ /**
52
+ * Flags that are passed to the Deno process. These flags follow the `deno
53
+ * run` command and can be used to enabled/disabled various permissions and
54
+ * features. These flags will be modified to ensure that the deno process can
55
+ * run the http server we'll be connecting to. Toggle the
56
+ * printCommandAndArguments if you need to understand what the final flag
57
+ * values are.
58
+ */
59
+ runFlags: string[];
60
+ /**
61
+ * Print stdout and stderr to the console with a "[deno]" prefix. This is
62
+ * useful for debugging.
63
+ */
64
+ printOutput: boolean;
65
+ /**
66
+ * Print out the command and arguments that are executed.
67
+ */
68
+ printCommandAndArguments: boolean;
69
+ /**
70
+ * Options used to spawn the Deno child process
71
+ */
72
+ spawnOptions: SpawnOptions;
73
+ /**
74
+ * Callback that is called when the process is spawned.
75
+ */
76
+ onSpawn?: (process: MinimalChildProcess) => void;
77
+ /**
78
+ * Provide an alternative spawn functions. Defaults to child_process.spawn.
79
+ */
80
+ spawnFunc: (command: string, args: string[], options: SpawnOptions) => MinimalChildProcess;
81
+ }
82
+
83
+ export interface DenoHTTPWorker {
84
+ /**
85
+ * Terminate the worker. This kills the process with SIGKILL if it is still
86
+ * running, closes the http connection, and deletes the socket file.
87
+ */
88
+ terminate(): void;
89
+ /**
90
+ * Gracefully shuts down the worker process and waits for any unresolved
91
+ * promises to exit.
92
+ */
93
+ shutdown(): void;
94
+ /**
95
+ * request calls http.request but patches the options to work with our
96
+ * connection pool and safely handle rewriting various headers.
97
+ */
98
+ request(
99
+ url: string | URL,
100
+ options: http.RequestOptions,
101
+ callback: (response: http.IncomingMessage) => void,
102
+ ): http.ClientRequest;
103
+ get stdout(): Readable;
104
+ get stderr(): Readable;
105
+ /**
106
+ * Adds the given listener for the "exit" event.
107
+ */
108
+ addEventListener(type: 'exit', listener: OnExitListener): void;
109
+ }
110
+
111
+ const unixNetGrantCache = new Map();
112
+ async function denoSupportsUnixNetPermission(denoExecutable) {
113
+ const argv = typeof denoExecutable === 'string' ? [denoExecutable] : denoExecutable;
114
+ const key = argv.join('\u0000');
115
+ if (unixNetGrantCache.has(key)) {
116
+ return unixNetGrantCache.get(key);
117
+ }
118
+ let supported = true;
119
+ try {
120
+ const stdout = await new Promise((resolve, reject) => {
121
+ execFile(argv[0], [...argv.slice(1), '--version'], { timeout: 5000 }, (err, out) =>
122
+ err ? reject(err) : resolve(String(out)),
123
+ );
124
+ });
125
+ const m = /deno (\d+)\.(\d+)\./.exec(stdout);
126
+ if (m) {
127
+ supported = Number(m[1]) > 2 || (Number(m[1]) === 2 && Number(m[2]) >= 9);
128
+ }
129
+ } catch {
130
+ // Unknown binary; default to the modern grant.
131
+ }
132
+ unixNetGrantCache.set(key, supported);
133
+ return supported;
134
+ }
135
+
136
+ export class EarlyExitDenoHTTPWorkerError extends Error {
137
+ message: string;
138
+ stderr: string;
139
+ stdout: string;
140
+ code: number;
141
+ signal: string;
142
+ constructor(message: string, stderr: string, stdout: string, code: number, signal: string) {
143
+ super(message);
144
+ this.message = message;
145
+ this.stderr = stderr;
146
+ this.stdout = stdout;
147
+ this.code = code;
148
+ this.signal = signal;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Create a new DenoHTTPWorker. This function will start a worker and being
154
+ */
155
+ export const newDenoHTTPWorker = async (
156
+ script: string | URL,
157
+ options: Partial<DenoWorkerOptions> = {},
158
+ ): Promise<DenoHTTPWorker> => {
159
+ const _options = {
160
+ denoExecutable: 'deno',
161
+ runFlags: [],
162
+ printCommandAndArguments: false,
163
+ spawnOptions: {},
164
+ printOutput: false,
165
+ spawnFunc: spawn,
166
+ ...options,
167
+ };
168
+ if (!_options.denoBootstrapScriptPath) {
169
+ throw new Error('denoBootstrapScriptPath is required');
170
+ }
171
+ let scriptArgs;
172
+ // Create the socket location that we'll use to communicate with Deno.
173
+ const socketFile = path.join(os.tmpdir(), `${crypto.randomUUID()}-deno-http.sock`);
174
+ // If we have a file import, make sure we allow read access to the file.
175
+ const allowReadFlagValue =
176
+ typeof script === 'string' ? socketFile : `${socketFile},${fileURLToPath(script)}`;
177
+ // Deno >= 2.9 moved unix-socket listening under the net permission, but
178
+ // older Deno rejects "unix:" entries in --allow-net at startup ("invalid
179
+ // port"). Probe the binary once per executable and grant the socket the
180
+ // way this Deno accepts; < 2.9 needs only the read/write grants below.
181
+ const grantUnixNet = await denoSupportsUnixNetPermission(_options.denoExecutable);
182
+ let allowReadFound = false;
183
+ let allowWriteFound = false;
184
+ let allowNetFound = false;
185
+ _options.runFlags = _options.runFlags.map((flag) => {
186
+ if (flag === '--allow-read' || flag === '--allow-all') {
187
+ allowReadFound = true;
188
+ }
189
+ if (flag === '--allow-write' || flag === '--allow-all') {
190
+ allowWriteFound = true;
191
+ }
192
+ if (flag === '--allow-net' || flag === '--allow-all') {
193
+ allowNetFound = true;
194
+ }
195
+ if (flag.startsWith('--allow-read=')) {
196
+ allowReadFound = true;
197
+ return (flag += `,${allowReadFlagValue}`);
198
+ }
199
+ if (flag.startsWith('--allow-write=')) {
200
+ allowWriteFound = true;
201
+ return (flag += `,${socketFile}`);
202
+ }
203
+ if (flag.startsWith('--allow-net=')) {
204
+ allowNetFound = true;
205
+ return grantUnixNet ? (flag += `,unix:${socketFile}`) : flag;
206
+ }
207
+ return flag;
208
+ });
209
+ if (!allowReadFound) {
210
+ _options.runFlags.push(`--allow-read=${allowReadFlagValue}`);
211
+ }
212
+ if (!allowWriteFound) {
213
+ _options.runFlags.push(`--allow-write=${socketFile}`);
214
+ }
215
+ if (!allowNetFound && grantUnixNet) {
216
+ _options.runFlags.push(`--allow-net=unix:${socketFile}`);
217
+ }
218
+ if (typeof script === 'string') {
219
+ scriptArgs = [socketFile, 'script', script];
220
+ } else {
221
+ scriptArgs = [socketFile, 'import', script.href];
222
+ }
223
+ if (Array.isArray(_options.denoExecutable) && _options.denoExecutable.length === 0) {
224
+ throw new Error('denoExecutable must not be an empty array');
225
+ }
226
+ const command =
227
+ typeof _options.denoExecutable === 'string' ? _options.denoExecutable : _options.denoExecutable[0];
228
+ const bootstrap = await fs.readFile(_options.denoBootstrapScriptPath, 'utf-8');
229
+ return new Promise((resolve, reject) => {
230
+ (async () => {
231
+ const args = [
232
+ ...(typeof _options.denoExecutable === 'string' ? [] : _options.denoExecutable.slice(1)),
233
+ 'run',
234
+ ..._options.runFlags,
235
+ 'data:text/typescript,' + encodeURIComponent(bootstrap),
236
+ ...scriptArgs,
237
+ ];
238
+ if (_options.printCommandAndArguments) {
239
+ console.log('Spawning deno process:', [command, ...args]);
240
+ }
241
+ const process = _options.spawnFunc(command, args, _options.spawnOptions);
242
+ let running = false;
243
+ let exited = false;
244
+ let worker = undefined;
245
+ process.on('exit', (code, signal) => {
246
+ exited = true;
247
+ if (!running) {
248
+ const stderr = process.stderr?.read()?.toString();
249
+ const stdout = process.stdout?.read()?.toString();
250
+ reject(
251
+ new EarlyExitDenoHTTPWorkerError('Deno exited before being ready', stderr, stdout, code, signal),
252
+ );
253
+ fs.rm(socketFile).catch(() => {});
254
+ } else {
255
+ worker._terminate(code, signal);
256
+ }
257
+ });
258
+ options.onSpawn && options.onSpawn(process);
259
+ const stdout = process.stdout;
260
+ const stderr = process.stderr;
261
+ if (_options.printOutput) {
262
+ readline.createInterface({ input: stdout }).on('line', (line) => {
263
+ console.log('[deno]', line);
264
+ });
265
+ readline.createInterface({ input: stderr }).on('line', (line) => {
266
+ console.error('[deno]', line);
267
+ });
268
+ }
269
+ // Wait for the socket file to be created by the Deno process.
270
+ for (;;) {
271
+ if (exited) {
272
+ break;
273
+ }
274
+ try {
275
+ await fs.stat(socketFile);
276
+ // File exists
277
+ break;
278
+ } catch (err) {
279
+ await new Promise((resolve) => setTimeout(resolve, 20));
280
+ }
281
+ }
282
+ worker = new denoHTTPWorker(socketFile, process, stdout, stderr);
283
+ running = true;
284
+ await worker.warmRequest();
285
+ return worker;
286
+ })()
287
+ .then(resolve)
288
+ .catch(reject);
289
+ });
290
+ };
291
+
292
+ class denoHTTPWorker {
293
+ #onexitListeners;
294
+ #process;
295
+ #socketFile;
296
+ #stderr;
297
+ #stdout;
298
+ #terminated = false;
299
+ #agent;
300
+ constructor(socketFile, process, stdout, stderr) {
301
+ this.#onexitListeners = [];
302
+ this.#process = process;
303
+ this.#socketFile = socketFile;
304
+ this.#stderr = stderr;
305
+ this.#stdout = stdout;
306
+ this.#agent = new http.Agent({ keepAlive: true });
307
+ }
308
+ _terminate(code, signal) {
309
+ if (this.#terminated) {
310
+ return;
311
+ }
312
+ this.#terminated = true;
313
+ if (this.#process && this.#process.exitCode === null) {
314
+ forceKill(this.#process.pid);
315
+ }
316
+ this.#agent.destroy();
317
+ fs.rm(this.#socketFile).catch(() => {});
318
+ for (const onexit of this.#onexitListeners) {
319
+ onexit(code ?? 1, signal ?? '');
320
+ }
321
+ }
322
+ terminate() {
323
+ this._terminate();
324
+ }
325
+ shutdown() {
326
+ this.#process.kill('SIGINT');
327
+ }
328
+ request(url, options, callback) {
329
+ options.headers = options.headers || {};
330
+ // TODO: ensure these are handled with the correct casing?
331
+ delete options.headers['x-deno-worker-host'];
332
+ delete options.headers['x-deno-worker-connection'];
333
+ // NodeJS will send both the host and the connection headers
334
+ // (https://nodejs.org/api/http.html#new-agentoptions). We don't want these
335
+ // to make it to Deno unless they are explicitly set by the user. So store
336
+ // them to reconstruct on the other size.
337
+ if (options.headers.host) {
338
+ options.headers['X-Deno-Worker-Host'] = options.headers.host;
339
+ }
340
+ if (options.headers.connection) {
341
+ options.headers['X-Deno-Worker-Connection'] = options.headers.connection;
342
+ }
343
+ options.headers = {
344
+ ...options.headers,
345
+ 'X-Deno-Worker-URL': typeof url === 'string' ? url : url.toString(),
346
+ };
347
+ url = 'http://deno';
348
+ options.agent = this.#agent;
349
+ options.socketPath = this.#socketFile;
350
+ return http.request(url, options, callback);
351
+ }
352
+ // We send this request to Deno so that we get a live connection in the
353
+ // http.Agent and subsequent requests are do not have to wait for a new
354
+ // connection.
355
+ async warmRequest() {
356
+ return new Promise((resolve, reject) => {
357
+ const req = http.request(
358
+ 'http://deno',
359
+ { agent: this.#agent, socketPath: this.#socketFile },
360
+ (resp) => {
361
+ resp.on('error', reject);
362
+ resp.on('data', () => {});
363
+ resp.on('close', () => {
364
+ resolve();
365
+ });
366
+ },
367
+ );
368
+ req.on('error', reject);
369
+ req.end();
370
+ });
371
+ }
372
+ get stdout() {
373
+ return this.#stdout;
374
+ }
375
+ get stderr() {
376
+ return this.#stderr;
377
+ }
378
+ addEventListener(type, listener) {
379
+ this.#onexitListeners.push(listener);
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Forcefully kills the process with the given ID.
385
+ * On Linux/Unix, this means sending the process the SIGKILL signal.
386
+ */
387
+ function forceKill(pid) {
388
+ return killUnix(pid);
389
+ }
390
+
391
+ function killUnix(pid) {
392
+ try {
393
+ const signal = 'SIGKILL';
394
+ process.kill(pid, signal);
395
+ } catch (e) {
396
+ // Allow this call to fail with
397
+ // ESRCH, which meant that the process
398
+ // to be killed was already dead.
399
+ // But re-throw on other codes.
400
+ if (e.code !== 'ESRCH') {
401
+ throw e;
402
+ }
403
+ }
404
+ }
@@ -0,0 +1,8 @@
1
+ // Vendored Conductor fork of @valtown/deno-http-worker; see DenoHTTPWorker.ts.
2
+ export {
3
+ newDenoHTTPWorker,
4
+ EarlyExitDenoHTTPWorkerError,
5
+ type DenoHTTPWorker,
6
+ type DenoWorkerOptions,
7
+ type MinimalChildProcess,
8
+ } from './DenoHTTPWorker';
package/src/index.ts CHANGED
@@ -14,23 +14,24 @@ async function main() {
14
14
  pretty: options.logFormat === 'pretty',
15
15
  });
16
16
 
17
- const selectedTools = await selectToolsOrError(options);
18
-
19
- getLogger().info(
20
- { tools: selectedTools.map((e) => e.tool.name) },
21
- `MCP Server starting with ${selectedTools.length} tools`,
22
- );
23
-
24
17
  switch (options.transport) {
25
18
  case 'stdio':
26
19
  await launchStdioServer(options);
27
20
  break;
28
- case 'http':
21
+ case 'http': {
22
+ const selectedTools = await selectToolsOrError(options);
23
+
24
+ getLogger().info(
25
+ { tools: selectedTools.map((e) => e.tool.name) },
26
+ `MCP Server starting with ${selectedTools.length} tools`,
27
+ );
28
+
29
29
  await launchStreamableHTTPServer({
30
30
  mcpOptions: options,
31
31
  port: options.socket ?? options.port,
32
32
  });
33
33
  break;
34
+ }
34
35
  }
35
36
  }
36
37
 
package/src/server.ts CHANGED
@@ -18,6 +18,8 @@ import { McpOptions } from './options';
18
18
  import { blockedMethodsForCodeTool } from './methods';
19
19
  import { HandlerFunction, McpRequestContext, ToolCallResult, McpTool } from './types';
20
20
 
21
+ export const VERSION = '14.24.0'; // x-release-please-version
22
+
21
23
  export const newMcpServer = async ({
22
24
  stainlessApiKey,
23
25
  customInstructionsPath,
@@ -28,7 +30,7 @@ export const newMcpServer = async ({
28
30
  new McpServer(
29
31
  {
30
32
  name: 'conductor_node_api',
31
- version: '14.23.8', // x-release-please-version
33
+ version: VERSION,
32
34
  },
33
35
  {
34
36
  instructions: await getInstructions({ stainlessApiKey, customInstructionsPath }),
package/src/stdio.ts CHANGED
@@ -1,17 +1,56 @@
1
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
2
- import { McpOptions } from './options';
3
- import { initMcpServer, newMcpServer } from './server';
1
+ import { runBridge, type BridgePermissions } from './bridge';
4
2
  import { getLogger } from './logger';
3
+ import { CLIOptions } from './options';
4
+ import { readEnv } from './util';
5
5
 
6
- export const launchStdioServer = async (mcpOptions: McpOptions) => {
7
- const server = await newMcpServer({
8
- stainlessApiKey: mcpOptions.stainlessApiKey,
9
- customInstructionsPath: mcpOptions.customInstructionsPath,
10
- });
6
+ export const DEFAULT_UPSTREAM_URL = 'https://mcp.conductor.is/';
11
7
 
12
- await initMcpServer({ server, mcpOptions, stainlessApiKey: mcpOptions.stainlessApiKey });
8
+ // The literal from the docs config blocks; pasted wholesale it is the most
9
+ // common setup mistake, so refuse it before the client sees a confusing error.
10
+ const PLACEHOLDER_KEY = 'sk_conductor_...';
13
11
 
14
- const transport = new StdioServerTransport();
15
- await server.connect(transport);
16
- getLogger().info('MCP Server running on stdio');
12
+ // Over stdio the package is a bridge to the hosted Conductor MCP server:
13
+ // nothing executes locally, and the only configuration is the secret key.
14
+ export const launchStdioServer = async (mcpOptions: CLIOptions) => {
15
+ rejectHttpOnlyOptionsOrExit(mcpOptions);
16
+ const apiKey = readSecretKeyOrExit();
17
+ const upstreamUrl = readEnv('CONDUCTOR_MCP_URL') ?? DEFAULT_UPSTREAM_URL;
18
+ const permissions: BridgePermissions = {
19
+ ...(mcpOptions.codeAllowHttpGets !== undefined && { allow_http_gets: mcpOptions.codeAllowHttpGets }),
20
+ ...(mcpOptions.codeAllowedMethods && { allowed_methods: mcpOptions.codeAllowedMethods }),
21
+ ...(mcpOptions.codeBlockedMethods && { blocked_methods: mcpOptions.codeBlockedMethods }),
22
+ };
23
+ getLogger().info({ upstreamUrl, permissions }, 'MCP bridge running on stdio');
24
+ await runBridge({ upstreamUrl, apiKey, permissions });
17
25
  };
26
+
27
+ // The hosted server chooses its own tools, docs and instructions; refuse the
28
+ // flags that would silently do nothing over stdio.
29
+ function rejectHttpOnlyOptionsOrExit(options: CLIOptions): void {
30
+ const flag =
31
+ options.includeCodeTool === false || options.includeDocsTools === false ? '--no-tools'
32
+ : options.includeCodeTool !== undefined || options.includeDocsTools !== undefined ? '--tools'
33
+ : options.docsDir !== undefined ? '--docs-dir'
34
+ : options.customInstructionsPath !== undefined ? '--custom-instructions-path'
35
+ : options.socket !== undefined ? '--socket'
36
+ : undefined;
37
+ if (flag !== undefined) {
38
+ console.error(
39
+ `${flag} only applies to --transport=http. Over stdio this package bridges to the hosted Conductor MCP server, which serves its own tools and instructions.`,
40
+ );
41
+ process.exit(1);
42
+ }
43
+ }
44
+
45
+ function readSecretKeyOrExit(): string {
46
+ // Tolerate an accidental "Bearer " prefix; do not enforce an sk_conductor_
47
+ // prefix, legacy keys without it are still active.
48
+ const apiKey = (readEnv('CONDUCTOR_SECRET_KEY') ?? '').replace(/^Bearer\s+/i, '').trim();
49
+ if (apiKey === '' || apiKey.includes(PLACEHOLDER_KEY)) {
50
+ console.error(
51
+ 'CONDUCTOR_SECRET_KEY is not set or is still the sk_conductor_... placeholder. Create a secret key at https://dashboard.conductor.is/ and put it in the "env" block of your MCP config (https://docs.conductor.is/usage/mcp).',
52
+ );
53
+ process.exit(1);
54
+ }
55
+ return apiKey;
56
+ }
package/stdio.d.mts CHANGED
@@ -1,3 +1,4 @@
1
- import { McpOptions } from "./options.mjs";
2
- export declare const launchStdioServer: (mcpOptions: McpOptions) => Promise<void>;
1
+ import { CLIOptions } from "./options.mjs";
2
+ export declare const DEFAULT_UPSTREAM_URL = "https://mcp.conductor.is/";
3
+ export declare const launchStdioServer: (mcpOptions: CLIOptions) => Promise<void>;
3
4
  //# sourceMappingURL=stdio.d.mts.map