@zavudev/sdk-mcp 0.26.0 → 0.27.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 (98) hide show
  1. package/auth.d.mts +3 -1
  2. package/auth.d.mts.map +1 -1
  3. package/auth.d.ts +3 -1
  4. package/auth.d.ts.map +1 -1
  5. package/auth.js +15 -3
  6. package/auth.js.map +1 -1
  7. package/auth.mjs +12 -1
  8. package/auth.mjs.map +1 -1
  9. package/code-tool-paths.cjs +6 -0
  10. package/code-tool-paths.cjs.map +1 -0
  11. package/code-tool-paths.d.cts +2 -0
  12. package/code-tool-paths.d.cts.map +1 -0
  13. package/code-tool-types.d.mts.map +1 -1
  14. package/code-tool-types.d.ts.map +1 -1
  15. package/code-tool-worker.d.mts +5 -0
  16. package/code-tool-worker.d.mts.map +1 -0
  17. package/code-tool-worker.d.ts +5 -0
  18. package/code-tool-worker.d.ts.map +1 -0
  19. package/code-tool-worker.js +301 -0
  20. package/code-tool-worker.js.map +1 -0
  21. package/code-tool-worker.mjs +296 -0
  22. package/code-tool-worker.mjs.map +1 -0
  23. package/code-tool.d.mts +8 -2
  24. package/code-tool.d.mts.map +1 -1
  25. package/code-tool.d.ts +8 -2
  26. package/code-tool.d.ts.map +1 -1
  27. package/code-tool.js +247 -41
  28. package/code-tool.js.map +1 -1
  29. package/code-tool.mjs +212 -42
  30. package/code-tool.mjs.map +1 -1
  31. package/docs-search-tool.d.mts +9 -3
  32. package/docs-search-tool.d.mts.map +1 -1
  33. package/docs-search-tool.d.ts +9 -3
  34. package/docs-search-tool.d.ts.map +1 -1
  35. package/docs-search-tool.js +2 -4
  36. package/docs-search-tool.js.map +1 -1
  37. package/docs-search-tool.mjs +2 -4
  38. package/docs-search-tool.mjs.map +1 -1
  39. package/http.d.mts +1 -1
  40. package/http.d.mts.map +1 -1
  41. package/http.d.ts +1 -1
  42. package/http.d.ts.map +1 -1
  43. package/http.js +16 -26
  44. package/http.js.map +1 -1
  45. package/http.mjs +17 -27
  46. package/http.mjs.map +1 -1
  47. package/index.js +1 -1
  48. package/index.js.map +1 -1
  49. package/index.mjs +1 -1
  50. package/index.mjs.map +1 -1
  51. package/instructions.d.mts +2 -0
  52. package/instructions.d.mts.map +1 -0
  53. package/instructions.d.ts +2 -0
  54. package/instructions.d.ts.map +1 -0
  55. package/instructions.js +55 -0
  56. package/instructions.js.map +1 -0
  57. package/instructions.mjs +52 -0
  58. package/instructions.mjs.map +1 -0
  59. package/options.d.mts +4 -0
  60. package/options.d.mts.map +1 -1
  61. package/options.d.ts +4 -0
  62. package/options.d.ts.map +1 -1
  63. package/options.js +21 -0
  64. package/options.js.map +1 -1
  65. package/options.mjs +21 -0
  66. package/options.mjs.map +1 -1
  67. package/package.json +29 -3
  68. package/server.d.mts +8 -4
  69. package/server.d.mts.map +1 -1
  70. package/server.d.ts +8 -4
  71. package/server.d.ts.map +1 -1
  72. package/server.js +72 -50
  73. package/server.js.map +1 -1
  74. package/server.mjs +72 -50
  75. package/server.mjs.map +1 -1
  76. package/src/auth.ts +16 -1
  77. package/src/code-tool-paths.cts +3 -0
  78. package/src/code-tool-types.ts +1 -0
  79. package/src/code-tool-worker.ts +347 -0
  80. package/src/code-tool.ts +286 -57
  81. package/src/docs-search-tool.ts +9 -6
  82. package/src/http.ts +22 -26
  83. package/src/index.ts +1 -1
  84. package/src/instructions.ts +74 -0
  85. package/src/options.ts +30 -0
  86. package/src/server.ts +85 -66
  87. package/src/stdio.ts +2 -2
  88. package/src/types.ts +12 -4
  89. package/stdio.js +2 -2
  90. package/stdio.js.map +1 -1
  91. package/stdio.mjs +2 -2
  92. package/stdio.mjs.map +1 -1
  93. package/types.d.mts +8 -1
  94. package/types.d.mts.map +1 -1
  95. package/types.d.ts +8 -1
  96. package/types.d.ts.map +1 -1
  97. package/types.js.map +1 -1
  98. package/types.mjs.map +1 -1
package/src/code-tool.ts CHANGED
@@ -1,15 +1,29 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
3
- import { McpTool, Metadata, ToolCallResult, asErrorResult, asTextContentResult } from './types';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import url from 'node:url';
6
+ import { newDenoHTTPWorker } from '@valtown/deno-http-worker';
7
+ import { workerPath } from './code-tool-paths.cjs';
8
+ import {
9
+ ContentBlock,
10
+ McpRequestContext,
11
+ McpTool,
12
+ Metadata,
13
+ ToolCallResult,
14
+ asErrorResult,
15
+ asTextContentResult,
16
+ } from './types';
4
17
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
5
18
  import { readEnv, requireValue } from './util';
6
19
  import { WorkerInput, WorkerOutput } from './code-tool-types';
7
20
  import { SdkMethod } from './methods';
8
- import { Zavudev } from '@zavudev/sdk';
21
+ import { McpCodeExecutionMode } from './options';
22
+ import { ClientOptions } from '@zavudev/sdk';
9
23
 
10
24
  const prompt = `Runs JavaScript code to interact with the Zavudev API.
11
25
 
12
- You are a skilled programmer writing code to interface with the service.
26
+ You are a skilled TypeScript programmer writing code to interface with the service.
13
27
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
14
28
  For example:
15
29
 
@@ -25,7 +39,9 @@ You will be returned anything that your function returns, plus the results of an
25
39
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
26
40
  Do not add comments unless necessary for generating better code.
27
41
  Code will run in a container, and cannot interact with the network outside of the given SDK client.
28
- Variables will not persist between calls, so make sure to return or log any data you might need later.`;
42
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
43
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
44
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
29
45
 
30
46
  /**
31
47
  * A tool that runs code against a copy of the SDK.
@@ -34,9 +50,19 @@ Variables will not persist between calls, so make sure to return or log any data
34
50
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
35
51
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
36
52
  *
37
- * @param endpoints - The endpoints to include in the list.
53
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
54
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
55
+ * with limited API keys.
56
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
57
+ * sandbox environment hosted by Stainless.
38
58
  */
39
- export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): McpTool {
59
+ export function codeTool({
60
+ blockedMethods,
61
+ codeExecutionMode,
62
+ }: {
63
+ blockedMethods: SdkMethod[] | undefined;
64
+ codeExecutionMode: McpCodeExecutionMode;
65
+ }): McpTool {
40
66
  const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
41
67
  const tool: Tool = {
42
68
  name: 'execute',
@@ -56,19 +82,22 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M
56
82
  required: ['code'],
57
83
  },
58
84
  };
59
- const handler = async (client: Zavudev, args: any): Promise<ToolCallResult> => {
60
- const code = args.code as string;
61
- const intent = args.intent as string | undefined;
62
85
 
86
+ const handler = async ({
87
+ reqContext,
88
+ args,
89
+ }: {
90
+ reqContext: McpRequestContext;
91
+ args: any;
92
+ }): Promise<ToolCallResult> => {
93
+ const code = args.code as string;
63
94
  // Do very basic blocking of code that includes forbidden method names.
64
95
  //
65
96
  // WARNING: This is not secure against obfuscation and other evasion methods. If
66
97
  // stronger security blocks are required, then these should be enforced in the downstream
67
98
  // API (e.g., by having users call the MCP server with API keys with limited permissions).
68
- if (params.blockedMethods) {
69
- const blockedMatches = params.blockedMethods.filter((method) =>
70
- code.includes(method.fullyQualifiedName),
71
- );
99
+ if (blockedMethods) {
100
+ const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
72
101
  if (blockedMatches.length > 0) {
73
102
  return asErrorResult(
74
103
  `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
@@ -78,53 +107,253 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M
78
107
  }
79
108
  }
80
109
 
81
- // this is not required, but passing a Stainless API key for the matching project_name
82
- // will allow you to run code-mode queries against non-published versions of your SDK.
83
- const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
84
- const codeModeEndpoint =
85
- readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
86
-
87
- const res = await fetch(codeModeEndpoint, {
88
- method: 'POST',
89
- headers: {
90
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
91
- 'Content-Type': 'application/json',
92
- client_envs: JSON.stringify({
93
- ZAVUDEV_API_KEY: requireValue(
94
- readEnv('ZAVUDEV_API_KEY') ?? client.apiKey,
95
- 'set ZAVUDEV_API_KEY environment variable or provide apiKey client option',
96
- ),
97
- ZAVUDEV_BASE_URL: readEnv('ZAVUDEV_BASE_URL') ?? client.baseURL ?? undefined,
98
- }),
99
- },
100
- body: JSON.stringify({
101
- project_name: 'zavudev',
102
- code,
103
- intent,
104
- client_opts: {},
105
- } satisfies WorkerInput),
106
- });
110
+ if (codeExecutionMode === 'local') {
111
+ return await localDenoHandler({ reqContext, args });
112
+ } else {
113
+ return await remoteStainlessHandler({ reqContext, args });
114
+ }
115
+ };
116
+
117
+ return { metadata, tool, handler };
118
+ }
107
119
 
108
- if (!res.ok) {
109
- throw new Error(
110
- `${res.status}: ${
111
- res.statusText
112
- } error when trying to contact Code Tool server. Details: ${await res.text()}`,
120
+ const remoteStainlessHandler = async ({
121
+ reqContext,
122
+ args,
123
+ }: {
124
+ reqContext: McpRequestContext;
125
+ args: any;
126
+ }): Promise<ToolCallResult> => {
127
+ const code = args.code as string;
128
+ const intent = args.intent as string | undefined;
129
+ const client = reqContext.client;
130
+
131
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
132
+
133
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
134
+ const res = await fetch(codeModeEndpoint, {
135
+ method: 'POST',
136
+ headers: {
137
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
138
+ 'Content-Type': 'application/json',
139
+ client_envs: JSON.stringify({
140
+ ZAVUDEV_API_KEY: requireValue(
141
+ readEnv('ZAVUDEV_API_KEY') ?? client.apiKey,
142
+ 'set ZAVUDEV_API_KEY environment variable or provide apiKey client option',
143
+ ),
144
+ ZAVUDEV_BASE_URL: readEnv('ZAVUDEV_BASE_URL') ?? client.baseURL ?? undefined,
145
+ }),
146
+ },
147
+ body: JSON.stringify({
148
+ project_name: 'zavudev',
149
+ code,
150
+ intent,
151
+ client_opts: {},
152
+ } satisfies WorkerInput),
153
+ });
154
+
155
+ if (!res.ok) {
156
+ throw new Error(
157
+ `${res.status}: ${
158
+ res.statusText
159
+ } error when trying to contact Code Tool server. Details: ${await res.text()}`,
160
+ );
161
+ }
162
+
163
+ const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
164
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
165
+ const output = {
166
+ result,
167
+ ...(log_lines.length > 0 && { log_lines }),
168
+ ...(err_lines.length > 0 && { err_lines }),
169
+ };
170
+ if (is_error) {
171
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
172
+ }
173
+ return asTextContentResult(output);
174
+ };
175
+
176
+ const localDenoHandler = async ({
177
+ reqContext,
178
+ args,
179
+ }: {
180
+ reqContext: McpRequestContext;
181
+ args: unknown;
182
+ }): Promise<ToolCallResult> => {
183
+ const client = reqContext.client;
184
+ const baseURLHostname = new URL(client.baseURL).hostname;
185
+ const { code } = args as { code: string };
186
+
187
+ let denoPath: string;
188
+
189
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
190
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
191
+
192
+ // Check if deno is in PATH
193
+ const { execSync } = await import('node:child_process');
194
+ try {
195
+ execSync('command -v deno', { stdio: 'ignore' });
196
+ denoPath = 'deno';
197
+ } catch {
198
+ try {
199
+ // Use deno binary in node_modules if it's found
200
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
201
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
202
+ denoPath = denoNodeModulesPath;
203
+ } catch {
204
+ return asErrorResult(
205
+ 'Deno is required for code execution but was not found. ' +
206
+ 'Install it from https://deno.land or run: npm install deno',
113
207
  );
114
208
  }
209
+ }
210
+
211
+ const allowReadPaths = [
212
+ 'code-tool-worker.mjs',
213
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
214
+ packageRoot,
215
+ ];
115
216
 
116
- const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
117
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
118
- const output = {
119
- result,
120
- ...(log_lines.length > 0 && { log_lines }),
121
- ...(err_lines.length > 0 && { err_lines }),
122
- };
123
- if (is_error) {
124
- return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
217
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
218
+ try {
219
+ const sdkPkgName = '@zavudev/sdk';
220
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
221
+ const realSdkDir = fs.realpathSync(sdkDir);
222
+ if (realSdkDir !== sdkDir) {
223
+ allowReadPaths.push(realSdkDir);
125
224
  }
126
- return asTextContentResult(output);
127
- };
225
+ } catch {
226
+ // Ignore if symlink resolution fails
227
+ }
128
228
 
129
- return { metadata, tool, handler };
130
- }
229
+ const allowRead = allowReadPaths.join(',');
230
+
231
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
232
+ denoExecutable: denoPath,
233
+ runFlags: [
234
+ `--node-modules-dir=manual`,
235
+ `--allow-read=${allowRead}`,
236
+ `--allow-net=${baseURLHostname}`,
237
+ // Allow environment variables because instantiating the client will try to read from them,
238
+ // even though they are not set.
239
+ '--allow-env',
240
+ ],
241
+ printOutput: true,
242
+ spawnOptions: {
243
+ cwd: path.dirname(workerPath),
244
+ },
245
+ });
246
+
247
+ try {
248
+ const resp = await new Promise<Response>((resolve, reject) => {
249
+ worker.addEventListener('exit', (exitCode) => {
250
+ reject(new Error(`Worker exited with code ${exitCode}`));
251
+ });
252
+
253
+ const opts: ClientOptions = {
254
+ baseURL: client.baseURL,
255
+ apiKey: client.apiKey,
256
+ defaultHeaders: {
257
+ 'X-Stainless-MCP': 'true',
258
+ },
259
+ };
260
+
261
+ const req = worker.request(
262
+ 'http://localhost',
263
+ {
264
+ headers: {
265
+ 'content-type': 'application/json',
266
+ },
267
+ method: 'POST',
268
+ },
269
+ (resp) => {
270
+ const body: Uint8Array[] = [];
271
+ resp.on('error', (err) => {
272
+ reject(err);
273
+ });
274
+ resp.on('data', (chunk) => {
275
+ body.push(chunk);
276
+ });
277
+ resp.on('end', () => {
278
+ resolve(
279
+ new Response(Buffer.concat(body).toString(), {
280
+ status: resp.statusCode ?? 200,
281
+ headers: resp.headers as any,
282
+ }),
283
+ );
284
+ });
285
+ },
286
+ );
287
+
288
+ const body = JSON.stringify({
289
+ opts,
290
+ code,
291
+ });
292
+
293
+ req.write(body, (err) => {
294
+ if (err != null) {
295
+ reject(err);
296
+ }
297
+ });
298
+
299
+ req.end();
300
+ });
301
+
302
+ if (resp.status === 200) {
303
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
304
+ const returnOutput: ContentBlock | null =
305
+ result == null ? null : (
306
+ {
307
+ type: 'text',
308
+ text: typeof result === 'string' ? result : JSON.stringify(result),
309
+ }
310
+ );
311
+ const logOutput: ContentBlock | null =
312
+ log_lines.length === 0 ?
313
+ null
314
+ : {
315
+ type: 'text',
316
+ text: log_lines.join('\n'),
317
+ };
318
+ const errOutput: ContentBlock | null =
319
+ err_lines.length === 0 ?
320
+ null
321
+ : {
322
+ type: 'text',
323
+ text: 'Error output:\n' + err_lines.join('\n'),
324
+ };
325
+ return {
326
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
327
+ };
328
+ } else {
329
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
330
+ const messageOutput: ContentBlock | null =
331
+ result == null ? null : (
332
+ {
333
+ type: 'text',
334
+ text: typeof result === 'string' ? result : JSON.stringify(result),
335
+ }
336
+ );
337
+ const logOutput: ContentBlock | null =
338
+ log_lines.length === 0 ?
339
+ null
340
+ : {
341
+ type: 'text',
342
+ text: log_lines.join('\n'),
343
+ };
344
+ const errOutput: ContentBlock | null =
345
+ err_lines.length === 0 ?
346
+ null
347
+ : {
348
+ type: 'text',
349
+ text: 'Error output:\n' + err_lines.join('\n'),
350
+ };
351
+ return {
352
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
353
+ isError: true,
354
+ };
355
+ }
356
+ } finally {
357
+ worker.terminate();
358
+ }
359
+ };
@@ -1,8 +1,6 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
3
- import { Metadata, asTextContentResult } from './types';
4
- import { readEnv } from './util';
5
-
3
+ import { Metadata, McpRequestContext, asTextContentResult } from './types';
6
4
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
7
5
 
8
6
  export const metadata: Metadata = {
@@ -43,13 +41,18 @@ export const tool: Tool = {
43
41
  const docsSearchURL =
44
42
  process.env['DOCS_SEARCH_URL'] || 'https://api.stainless.com/api/projects/zavudev/docs/search';
45
43
 
46
- export const handler = async (_: unknown, args: Record<string, unknown> | undefined) => {
44
+ export const handler = async ({
45
+ reqContext,
46
+ args,
47
+ }: {
48
+ reqContext: McpRequestContext;
49
+ args: Record<string, unknown> | undefined;
50
+ }) => {
47
51
  const body = args as any;
48
52
  const query = new URLSearchParams(body).toString();
49
- const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
50
53
  const result = await fetch(`${docsSearchURL}?${query}`, {
51
54
  headers: {
52
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
55
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
53
56
  },
54
57
  });
55
58
 
package/src/http.ts CHANGED
@@ -6,7 +6,7 @@ import { ClientOptions } from '@zavudev/sdk';
6
6
  import express from 'express';
7
7
  import morgan from 'morgan';
8
8
  import morganBody from 'morgan-body';
9
- import { parseAuthHeaders } from './auth';
9
+ import { getStainlessApiKey, parseClientAuthHeaders } from './auth';
10
10
  import { McpOptions } from './options';
11
11
  import { initMcpServer, newMcpServer } from './server';
12
12
 
@@ -21,28 +21,20 @@ const newServer = async ({
21
21
  req: express.Request;
22
22
  res: express.Response;
23
23
  }): Promise<McpServer | null> => {
24
- const server = await newMcpServer();
24
+ const stainlessApiKey = getStainlessApiKey(req, mcpOptions);
25
+ const server = await newMcpServer(stainlessApiKey);
25
26
 
26
- try {
27
- const authOptions = parseAuthHeaders(req, false);
28
- await initMcpServer({
29
- server: server,
30
- mcpOptions: mcpOptions,
31
- clientOptions: {
32
- ...clientOptions,
33
- ...authOptions,
34
- },
35
- });
36
- } catch (error) {
37
- res.status(401).json({
38
- jsonrpc: '2.0',
39
- error: {
40
- code: -32000,
41
- message: `Unauthorized: ${error instanceof Error ? error.message : error}`,
42
- },
43
- });
44
- return null;
45
- }
27
+ const authOptions = parseClientAuthHeaders(req, false);
28
+
29
+ await initMcpServer({
30
+ server: server,
31
+ mcpOptions: mcpOptions,
32
+ clientOptions: {
33
+ ...clientOptions,
34
+ ...authOptions,
35
+ },
36
+ stainlessApiKey: stainlessApiKey,
37
+ });
46
38
 
47
39
  return server;
48
40
  };
@@ -112,13 +104,17 @@ export const streamableHTTPApp = ({
112
104
  return app;
113
105
  };
114
106
 
115
- export const launchStreamableHTTPServer = async (params: {
107
+ export const launchStreamableHTTPServer = async ({
108
+ mcpOptions,
109
+ debug,
110
+ port,
111
+ }: {
116
112
  mcpOptions: McpOptions;
117
113
  debug: boolean;
118
114
  port: number | string | undefined;
119
115
  }) => {
120
- const app = streamableHTTPApp({ mcpOptions: params.mcpOptions, debug: params.debug });
121
- const server = app.listen(params.port);
116
+ const app = streamableHTTPApp({ mcpOptions, debug });
117
+ const server = app.listen(port);
122
118
  const address = server.address();
123
119
 
124
120
  if (typeof address === 'string') {
@@ -126,6 +122,6 @@ export const launchStreamableHTTPServer = async (params: {
126
122
  } else if (address !== null) {
127
123
  console.error(`MCP Server running on streamable HTTP on port ${address.port}`);
128
124
  } else {
129
- console.error(`MCP Server running on streamable HTTP on port ${params.port}`);
125
+ console.error(`MCP Server running on streamable HTTP on port ${port}`);
130
126
  }
131
127
  };
package/src/index.ts CHANGED
@@ -24,7 +24,7 @@ async function main() {
24
24
  await launchStreamableHTTPServer({
25
25
  mcpOptions: options,
26
26
  debug: options.debug,
27
- port: options.port ?? options.socket,
27
+ port: options.socket ?? options.port,
28
28
  });
29
29
  break;
30
30
  }
@@ -0,0 +1,74 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import { readEnv } from './util';
4
+
5
+ const INSTRUCTIONS_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes
6
+
7
+ interface InstructionsCacheEntry {
8
+ fetchedInstructions: string;
9
+ fetchedAt: number;
10
+ }
11
+
12
+ const instructionsCache = new Map<string, InstructionsCacheEntry>();
13
+
14
+ // Periodically evict stale entries so the cache doesn't grow unboundedly.
15
+ const _cacheCleanupInterval = setInterval(() => {
16
+ const now = Date.now();
17
+ for (const [key, entry] of instructionsCache) {
18
+ if (now - entry.fetchedAt > INSTRUCTIONS_CACHE_TTL_MS) {
19
+ instructionsCache.delete(key);
20
+ }
21
+ }
22
+ }, INSTRUCTIONS_CACHE_TTL_MS);
23
+
24
+ // Don't keep the process alive just for cleanup.
25
+ _cacheCleanupInterval.unref();
26
+
27
+ export async function getInstructions(stainlessApiKey: string | undefined): Promise<string> {
28
+ const cacheKey = stainlessApiKey ?? '';
29
+ const cached = instructionsCache.get(cacheKey);
30
+
31
+ if (cached && Date.now() - cached.fetchedAt <= INSTRUCTIONS_CACHE_TTL_MS) {
32
+ return cached.fetchedInstructions;
33
+ }
34
+
35
+ const fetchedInstructions = await fetchLatestInstructions(stainlessApiKey);
36
+ instructionsCache.set(cacheKey, { fetchedInstructions, fetchedAt: Date.now() });
37
+ return fetchedInstructions;
38
+ }
39
+
40
+ async function fetchLatestInstructions(stainlessApiKey: string | undefined): Promise<string> {
41
+ // Setting the stainless API key is optional, but may be required
42
+ // to authenticate requests to the Stainless API.
43
+ const response = await fetch(
44
+ readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/zavudev',
45
+ {
46
+ method: 'GET',
47
+ headers: { ...(stainlessApiKey && { Authorization: stainlessApiKey }) },
48
+ },
49
+ );
50
+
51
+ let instructions: string | undefined;
52
+ if (!response.ok) {
53
+ console.warn(
54
+ 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...',
55
+ );
56
+
57
+ instructions = `
58
+ This is the zavudev MCP server. You will use Code Mode to help the user perform
59
+ actions. You can use search_docs tool to learn about how to take action with this server. Then,
60
+ you will write TypeScript code using the execute tool take action. It is CRITICAL that you be
61
+ thoughtful and deliberate when executing code. Always try to entirely solve the problem in code
62
+ block: it can be as long as you need to get the job done!
63
+ `;
64
+ }
65
+
66
+ instructions ??= ((await response.json()) as { instructions: string }).instructions;
67
+ instructions = `
68
+ If needed, you can get the current time by executing Date.now().
69
+
70
+ ${instructions}
71
+ `;
72
+
73
+ return instructions;
74
+ }
package/src/options.ts CHANGED
@@ -4,6 +4,7 @@ import qs from 'qs';
4
4
  import yargs from 'yargs';
5
5
  import { hideBin } from 'yargs/helpers';
6
6
  import z from 'zod';
7
+ import { readEnv } from './util';
7
8
 
8
9
  export type CLIOptions = McpOptions & {
9
10
  debug: boolean;
@@ -13,12 +14,17 @@ export type CLIOptions = McpOptions & {
13
14
  };
14
15
 
15
16
  export type McpOptions = {
17
+ includeCodeTool?: boolean | undefined;
16
18
  includeDocsTools?: boolean | undefined;
19
+ stainlessApiKey?: string | undefined;
17
20
  codeAllowHttpGets?: boolean | undefined;
18
21
  codeAllowedMethods?: string[] | undefined;
19
22
  codeBlockedMethods?: string[] | undefined;
23
+ codeExecutionMode: McpCodeExecutionMode;
20
24
  };
21
25
 
26
+ export type McpCodeExecutionMode = 'stainless-sandbox' | 'local';
27
+
22
28
  export function parseCLIOptions(): CLIOptions {
23
29
  const opts = yargs(hideBin(process.argv))
24
30
  .option('code-allow-http-gets', {
@@ -38,6 +44,13 @@ export function parseCLIOptions(): CLIOptions {
38
44
  description:
39
45
  'Methods to explicitly block for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.',
40
46
  })
47
+ .option('code-execution-mode', {
48
+ type: 'string',
49
+ choices: ['stainless-sandbox', 'local'],
50
+ default: 'stainless-sandbox',
51
+ description:
52
+ "Where to run code execution in code tool; 'stainless-sandbox' will execute code in Stainless-hosted sandboxes whereas 'local' will execute code locally on the MCP server machine.",
53
+ })
41
54
  .option('debug', { type: 'boolean', description: 'Enable debug logging' })
42
55
  .option('no-tools', {
43
56
  type: 'string',
@@ -51,6 +64,12 @@ export function parseCLIOptions(): CLIOptions {
51
64
  description: 'Port to serve on if using http transport',
52
65
  })
53
66
  .option('socket', { type: 'string', description: 'Unix socket to serve on if using http transport' })
67
+ .option('stainless-api-key', {
68
+ type: 'string',
69
+ default: readEnv('STAINLESS_API_KEY'),
70
+ description:
71
+ 'API key for Stainless. Used to authenticate requests to Stainless-hosted tools endpoints.',
72
+ })
54
73
  .option('tools', {
55
74
  type: 'string',
56
75
  array: true,
@@ -74,16 +93,20 @@ export function parseCLIOptions(): CLIOptions {
74
93
  : argv.tools?.includes(toolType) ? true
75
94
  : undefined;
76
95
 
96
+ const includeCodeTool = shouldIncludeToolType('code');
77
97
  const includeDocsTools = shouldIncludeToolType('docs');
78
98
 
79
99
  const transport = argv.transport as 'stdio' | 'http';
80
100
 
81
101
  return {
102
+ ...(includeCodeTool !== undefined && { includeCodeTool }),
82
103
  ...(includeDocsTools !== undefined && { includeDocsTools }),
83
104
  debug: !!argv.debug,
105
+ stainlessApiKey: argv.stainlessApiKey,
84
106
  codeAllowHttpGets: argv.codeAllowHttpGets,
85
107
  codeAllowedMethods: argv.codeAllowedMethods,
86
108
  codeBlockedMethods: argv.codeBlockedMethods,
109
+ codeExecutionMode: argv.codeExecutionMode as McpCodeExecutionMode,
87
110
  transport,
88
111
  port: argv.port,
89
112
  socket: argv.socket,
@@ -109,12 +132,19 @@ export function parseQueryOptions(defaultOptions: McpOptions, query: unknown): M
109
132
  const queryObject = typeof query === 'string' ? qs.parse(query) : query;
110
133
  const queryOptions = QueryOptions.parse(queryObject);
111
134
 
135
+ let codeTool: boolean | undefined =
136
+ queryOptions.no_tools && queryOptions.no_tools?.includes('code') ? false
137
+ : queryOptions.tools?.includes('code') ? true
138
+ : defaultOptions.includeCodeTool;
139
+
112
140
  let docsTools: boolean | undefined =
113
141
  queryOptions.no_tools && queryOptions.no_tools?.includes('docs') ? false
114
142
  : queryOptions.tools?.includes('docs') ? true
115
143
  : defaultOptions.includeDocsTools;
116
144
 
117
145
  return {
146
+ ...(codeTool !== undefined && { includeCodeTool: codeTool }),
118
147
  ...(docsTools !== undefined && { includeDocsTools: docsTools }),
148
+ codeExecutionMode: defaultOptions.codeExecutionMode,
119
149
  };
120
150
  }