@zavudev/sdk-mcp 0.25.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 (120) hide show
  1. package/auth.d.mts +6 -0
  2. package/auth.d.mts.map +1 -0
  3. package/auth.d.ts +6 -0
  4. package/auth.d.ts.map +1 -0
  5. package/{headers.mjs → auth.js} +18 -2
  6. package/auth.js.map +1 -0
  7. package/{headers.js → auth.mjs} +13 -6
  8. package/auth.mjs.map +1 -0
  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 +248 -42
  28. package/code-tool.js.map +1 -1
  29. package/code-tool.mjs +213 -43
  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 +6 -2
  36. package/docs-search-tool.js.map +1 -1
  37. package/docs-search-tool.mjs +6 -2
  38. package/docs-search-tool.mjs.map +1 -1
  39. package/http.d.mts +2 -2
  40. package/http.d.mts.map +1 -1
  41. package/http.d.ts +2 -2
  42. package/http.d.ts.map +1 -1
  43. package/http.js +17 -27
  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/methods.d.mts.map +1 -1
  60. package/methods.d.ts.map +1 -1
  61. package/methods.js +1 -0
  62. package/methods.js.map +1 -1
  63. package/methods.mjs +1 -0
  64. package/methods.mjs.map +1 -1
  65. package/options.d.mts +4 -0
  66. package/options.d.mts.map +1 -1
  67. package/options.d.ts +4 -0
  68. package/options.d.ts.map +1 -1
  69. package/options.js +22 -0
  70. package/options.js.map +1 -1
  71. package/options.mjs +22 -0
  72. package/options.mjs.map +1 -1
  73. package/package.json +49 -13
  74. package/server.d.mts +8 -9
  75. package/server.d.mts.map +1 -1
  76. package/server.d.ts +8 -9
  77. package/server.d.ts.map +1 -1
  78. package/server.js +73 -75
  79. package/server.js.map +1 -1
  80. package/server.mjs +72 -71
  81. package/server.mjs.map +1 -1
  82. package/src/{headers.ts → auth.ts} +16 -1
  83. package/src/code-tool-paths.cts +3 -0
  84. package/src/code-tool-types.ts +1 -0
  85. package/src/code-tool-worker.ts +347 -0
  86. package/src/code-tool.ts +287 -58
  87. package/src/docs-search-tool.ts +13 -4
  88. package/src/http.ts +24 -27
  89. package/src/index.ts +1 -1
  90. package/src/instructions.ts +74 -0
  91. package/src/methods.ts +2 -0
  92. package/src/options.ts +32 -0
  93. package/src/server.ts +85 -92
  94. package/src/stdio.ts +2 -2
  95. package/src/types.ts +12 -4
  96. package/src/util.ts +25 -0
  97. package/stdio.js +2 -2
  98. package/stdio.js.map +1 -1
  99. package/stdio.mjs +2 -2
  100. package/stdio.mjs.map +1 -1
  101. package/types.d.mts +8 -1
  102. package/types.d.mts.map +1 -1
  103. package/types.d.ts +8 -1
  104. package/types.d.ts.map +1 -1
  105. package/types.js.map +1 -1
  106. package/types.mjs.map +1 -1
  107. package/util.d.mts +4 -0
  108. package/util.d.mts.map +1 -0
  109. package/util.d.ts +4 -0
  110. package/util.d.ts.map +1 -0
  111. package/util.js +30 -0
  112. package/util.js.map +1 -0
  113. package/util.mjs +24 -0
  114. package/util.mjs.map +1 -0
  115. package/headers.d.mts +0 -4
  116. package/headers.d.mts.map +0 -1
  117. package/headers.d.ts +0 -4
  118. package/headers.d.ts.map +0 -1
  119. package/headers.js.map +0 -1
  120. package/headers.mjs.map +0 -1
package/code-tool.js CHANGED
@@ -1,12 +1,53 @@
1
1
  "use strict";
2
2
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ var __importDefault = (this && this.__importDefault) || function (mod) {
37
+ return (mod && mod.__esModule) ? mod : { "default": mod };
38
+ };
3
39
  Object.defineProperty(exports, "__esModule", { value: true });
4
40
  exports.codeTool = codeTool;
41
+ const node_fs_1 = __importDefault(require("node:fs"));
42
+ const node_path_1 = __importDefault(require("node:path"));
43
+ const node_url_1 = __importDefault(require("node:url"));
44
+ const deno_http_worker_1 = require("@valtown/deno-http-worker");
45
+ const code_tool_paths_cjs_1 = require("./code-tool-paths.cjs");
5
46
  const types_1 = require("./types.js");
6
- const server_1 = require("./server.js");
47
+ const util_1 = require("./util.js");
7
48
  const prompt = `Runs JavaScript code to interact with the Zavudev API.
8
49
 
9
- You are a skilled programmer writing code to interface with the service.
50
+ You are a skilled TypeScript programmer writing code to interface with the service.
10
51
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
11
52
  For example:
12
53
 
@@ -22,7 +63,9 @@ You will be returned anything that your function returns, plus the results of an
22
63
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
23
64
  Do not add comments unless necessary for generating better code.
24
65
  Code will run in a container, and cannot interact with the network outside of the given SDK client.
25
- Variables will not persist between calls, so make sure to return or log any data you might need later.`;
66
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
67
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
68
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
26
69
  /**
27
70
  * A tool that runs code against a copy of the SDK.
28
71
  *
@@ -30,9 +73,13 @@ Variables will not persist between calls, so make sure to return or log any data
30
73
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
31
74
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
32
75
  *
33
- * @param endpoints - The endpoints to include in the list.
76
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
77
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
78
+ * with limited API keys.
79
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
80
+ * sandbox environment hosted by Stainless.
34
81
  */
35
- function codeTool(params) {
82
+ function codeTool({ blockedMethods, codeExecutionMode, }) {
36
83
  const metadata = { resource: 'all', operation: 'write', tags: [] };
37
84
  const tool = {
38
85
  name: 'execute',
@@ -52,58 +99,217 @@ function codeTool(params) {
52
99
  required: ['code'],
53
100
  },
54
101
  };
55
- const handler = async (client, args) => {
102
+ const handler = async ({ reqContext, args, }) => {
56
103
  const code = args.code;
57
- const intent = args.intent;
58
104
  // Do very basic blocking of code that includes forbidden method names.
59
105
  //
60
106
  // WARNING: This is not secure against obfuscation and other evasion methods. If
61
107
  // stronger security blocks are required, then these should be enforced in the downstream
62
108
  // API (e.g., by having users call the MCP server with API keys with limited permissions).
63
- if (params.blockedMethods) {
64
- const blockedMatches = params.blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
109
+ if (blockedMethods) {
110
+ const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
65
111
  if (blockedMatches.length > 0) {
66
112
  return (0, types_1.asErrorResult)(`The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
67
113
  .map((m) => m.fullyQualifiedName)
68
114
  .join(', ')}`);
69
115
  }
70
116
  }
71
- // this is not required, but passing a Stainless API key for the matching project_name
72
- // will allow you to run code-mode queries against non-published versions of your SDK.
73
- const stainlessAPIKey = (0, server_1.readEnv)('STAINLESS_API_KEY');
74
- const codeModeEndpoint = (0, server_1.readEnv)('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
75
- const res = await fetch(codeModeEndpoint, {
76
- method: 'POST',
77
- headers: {
78
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
79
- 'Content-Type': 'application/json',
80
- client_envs: JSON.stringify({
81
- ZAVUDEV_API_KEY: (0, server_1.requireValue)((0, server_1.readEnv)('ZAVUDEV_API_KEY') ?? client.apiKey, 'set ZAVUDEV_API_KEY environment variable or provide apiKey client option'),
82
- ZAVUDEV_BASE_URL: (0, server_1.readEnv)('ZAVUDEV_BASE_URL') ?? client.baseURL ?? undefined,
83
- }),
84
- },
85
- body: JSON.stringify({
86
- project_name: 'zavudev',
87
- code,
88
- intent,
89
- client_opts: {},
90
- }),
91
- });
92
- if (!res.ok) {
93
- throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
117
+ if (codeExecutionMode === 'local') {
118
+ return await localDenoHandler({ reqContext, args });
94
119
  }
95
- const { is_error, result, log_lines, err_lines } = (await res.json());
96
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
97
- const output = {
98
- result,
99
- ...(log_lines.length > 0 && { log_lines }),
100
- ...(err_lines.length > 0 && { err_lines }),
101
- };
102
- if (is_error) {
103
- return (0, types_1.asErrorResult)(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
120
+ else {
121
+ return await remoteStainlessHandler({ reqContext, args });
104
122
  }
105
- return (0, types_1.asTextContentResult)(output);
106
123
  };
107
124
  return { metadata, tool, handler };
108
125
  }
126
+ const remoteStainlessHandler = async ({ reqContext, args, }) => {
127
+ const code = args.code;
128
+ const intent = args.intent;
129
+ const client = reqContext.client;
130
+ const codeModeEndpoint = (0, util_1.readEnv)('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
131
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
132
+ const res = await fetch(codeModeEndpoint, {
133
+ method: 'POST',
134
+ headers: {
135
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
136
+ 'Content-Type': 'application/json',
137
+ client_envs: JSON.stringify({
138
+ ZAVUDEV_API_KEY: (0, util_1.requireValue)((0, util_1.readEnv)('ZAVUDEV_API_KEY') ?? client.apiKey, 'set ZAVUDEV_API_KEY environment variable or provide apiKey client option'),
139
+ ZAVUDEV_BASE_URL: (0, util_1.readEnv)('ZAVUDEV_BASE_URL') ?? client.baseURL ?? undefined,
140
+ }),
141
+ },
142
+ body: JSON.stringify({
143
+ project_name: 'zavudev',
144
+ code,
145
+ intent,
146
+ client_opts: {},
147
+ }),
148
+ });
149
+ if (!res.ok) {
150
+ throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
151
+ }
152
+ const { is_error, result, log_lines, err_lines } = (await res.json());
153
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
154
+ const output = {
155
+ result,
156
+ ...(log_lines.length > 0 && { log_lines }),
157
+ ...(err_lines.length > 0 && { err_lines }),
158
+ };
159
+ if (is_error) {
160
+ return (0, types_1.asErrorResult)(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
161
+ }
162
+ return (0, types_1.asTextContentResult)(output);
163
+ };
164
+ const localDenoHandler = async ({ reqContext, args, }) => {
165
+ const client = reqContext.client;
166
+ const baseURLHostname = new URL(client.baseURL).hostname;
167
+ const { code } = args;
168
+ let denoPath;
169
+ const packageRoot = node_path_1.default.resolve(node_path_1.default.dirname(code_tool_paths_cjs_1.workerPath), '..');
170
+ const packageNodeModulesPath = node_path_1.default.resolve(packageRoot, 'node_modules');
171
+ // Check if deno is in PATH
172
+ const { execSync } = await Promise.resolve().then(() => __importStar(require('node:child_process')));
173
+ try {
174
+ execSync('command -v deno', { stdio: 'ignore' });
175
+ denoPath = 'deno';
176
+ }
177
+ catch {
178
+ try {
179
+ // Use deno binary in node_modules if it's found
180
+ const denoNodeModulesPath = node_path_1.default.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
181
+ await node_fs_1.default.promises.access(denoNodeModulesPath, node_fs_1.default.constants.X_OK);
182
+ denoPath = denoNodeModulesPath;
183
+ }
184
+ catch {
185
+ return (0, types_1.asErrorResult)('Deno is required for code execution but was not found. ' +
186
+ 'Install it from https://deno.land or run: npm install deno');
187
+ }
188
+ }
189
+ const allowReadPaths = [
190
+ 'code-tool-worker.mjs',
191
+ `${code_tool_paths_cjs_1.workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
192
+ packageRoot,
193
+ ];
194
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
195
+ try {
196
+ const sdkPkgName = '@zavudev/sdk';
197
+ const sdkDir = node_path_1.default.resolve(packageNodeModulesPath, sdkPkgName);
198
+ const realSdkDir = node_fs_1.default.realpathSync(sdkDir);
199
+ if (realSdkDir !== sdkDir) {
200
+ allowReadPaths.push(realSdkDir);
201
+ }
202
+ }
203
+ catch {
204
+ // Ignore if symlink resolution fails
205
+ }
206
+ const allowRead = allowReadPaths.join(',');
207
+ const worker = await (0, deno_http_worker_1.newDenoHTTPWorker)(node_url_1.default.pathToFileURL(code_tool_paths_cjs_1.workerPath), {
208
+ denoExecutable: denoPath,
209
+ runFlags: [
210
+ `--node-modules-dir=manual`,
211
+ `--allow-read=${allowRead}`,
212
+ `--allow-net=${baseURLHostname}`,
213
+ // Allow environment variables because instantiating the client will try to read from them,
214
+ // even though they are not set.
215
+ '--allow-env',
216
+ ],
217
+ printOutput: true,
218
+ spawnOptions: {
219
+ cwd: node_path_1.default.dirname(code_tool_paths_cjs_1.workerPath),
220
+ },
221
+ });
222
+ try {
223
+ const resp = await new Promise((resolve, reject) => {
224
+ worker.addEventListener('exit', (exitCode) => {
225
+ reject(new Error(`Worker exited with code ${exitCode}`));
226
+ });
227
+ const opts = {
228
+ baseURL: client.baseURL,
229
+ apiKey: client.apiKey,
230
+ defaultHeaders: {
231
+ 'X-Stainless-MCP': 'true',
232
+ },
233
+ };
234
+ const req = worker.request('http://localhost', {
235
+ headers: {
236
+ 'content-type': 'application/json',
237
+ },
238
+ method: 'POST',
239
+ }, (resp) => {
240
+ const body = [];
241
+ resp.on('error', (err) => {
242
+ reject(err);
243
+ });
244
+ resp.on('data', (chunk) => {
245
+ body.push(chunk);
246
+ });
247
+ resp.on('end', () => {
248
+ resolve(new Response(Buffer.concat(body).toString(), {
249
+ status: resp.statusCode ?? 200,
250
+ headers: resp.headers,
251
+ }));
252
+ });
253
+ });
254
+ const body = JSON.stringify({
255
+ opts,
256
+ code,
257
+ });
258
+ req.write(body, (err) => {
259
+ if (err != null) {
260
+ reject(err);
261
+ }
262
+ });
263
+ req.end();
264
+ });
265
+ if (resp.status === 200) {
266
+ const { result, log_lines, err_lines } = (await resp.json());
267
+ const returnOutput = result == null ? null : ({
268
+ type: 'text',
269
+ text: typeof result === 'string' ? result : JSON.stringify(result),
270
+ });
271
+ const logOutput = log_lines.length === 0 ?
272
+ null
273
+ : {
274
+ type: 'text',
275
+ text: log_lines.join('\n'),
276
+ };
277
+ const errOutput = err_lines.length === 0 ?
278
+ null
279
+ : {
280
+ type: 'text',
281
+ text: 'Error output:\n' + err_lines.join('\n'),
282
+ };
283
+ return {
284
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
285
+ };
286
+ }
287
+ else {
288
+ const { result, log_lines, err_lines } = (await resp.json());
289
+ const messageOutput = result == null ? null : ({
290
+ type: 'text',
291
+ text: typeof result === 'string' ? result : JSON.stringify(result),
292
+ });
293
+ const logOutput = log_lines.length === 0 ?
294
+ null
295
+ : {
296
+ type: 'text',
297
+ text: log_lines.join('\n'),
298
+ };
299
+ const errOutput = err_lines.length === 0 ?
300
+ null
301
+ : {
302
+ type: 'text',
303
+ text: 'Error output:\n' + err_lines.join('\n'),
304
+ };
305
+ return {
306
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
307
+ isError: true,
308
+ };
309
+ }
310
+ }
311
+ finally {
312
+ worker.terminate();
313
+ }
314
+ };
109
315
  //# sourceMappingURL=code-tool.js.map
package/code-tool.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"code-tool.js","sourceRoot":"","sources":["src/code-tool.ts"],"names":[],"mappings":";AAAA,sFAAsF;;AAsCtF,4BA2FC;AA/HD,sCAAgG;AAEhG,wCAAiD;AAKjD,MA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AAC,CAAC"}
package/code-tool.mjs CHANGED
@@ -1,9 +1,14 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
- import { asErrorResult, asTextContentResult } from "./types.mjs";
3
- import { readEnv, requireValue } from "./server.mjs";
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import url from 'node:url';
5
+ import { newDenoHTTPWorker } from '@valtown/deno-http-worker';
6
+ import { workerPath } from './code-tool-paths.cjs';
7
+ import { asErrorResult, asTextContentResult, } from "./types.mjs";
8
+ import { readEnv, requireValue } from "./util.mjs";
4
9
  const prompt = `Runs JavaScript code to interact with the Zavudev API.
5
10
 
6
- You are a skilled programmer writing code to interface with the service.
11
+ You are a skilled TypeScript programmer writing code to interface with the service.
7
12
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
8
13
  For example:
9
14
 
@@ -19,7 +24,9 @@ You will be returned anything that your function returns, plus the results of an
19
24
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
20
25
  Do not add comments unless necessary for generating better code.
21
26
  Code will run in a container, and cannot interact with the network outside of the given SDK client.
22
- Variables will not persist between calls, so make sure to return or log any data you might need later.`;
27
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
28
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
29
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
23
30
  /**
24
31
  * A tool that runs code against a copy of the SDK.
25
32
  *
@@ -27,9 +34,13 @@ Variables will not persist between calls, so make sure to return or log any data
27
34
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
28
35
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
29
36
  *
30
- * @param endpoints - The endpoints to include in the list.
37
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
38
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
39
+ * with limited API keys.
40
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
41
+ * sandbox environment hosted by Stainless.
31
42
  */
32
- export function codeTool(params) {
43
+ export function codeTool({ blockedMethods, codeExecutionMode, }) {
33
44
  const metadata = { resource: 'all', operation: 'write', tags: [] };
34
45
  const tool = {
35
46
  name: 'execute',
@@ -49,58 +60,217 @@ export function codeTool(params) {
49
60
  required: ['code'],
50
61
  },
51
62
  };
52
- const handler = async (client, args) => {
63
+ const handler = async ({ reqContext, args, }) => {
53
64
  const code = args.code;
54
- const intent = args.intent;
55
65
  // Do very basic blocking of code that includes forbidden method names.
56
66
  //
57
67
  // WARNING: This is not secure against obfuscation and other evasion methods. If
58
68
  // stronger security blocks are required, then these should be enforced in the downstream
59
69
  // API (e.g., by having users call the MCP server with API keys with limited permissions).
60
- if (params.blockedMethods) {
61
- const blockedMatches = params.blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
70
+ if (blockedMethods) {
71
+ const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
62
72
  if (blockedMatches.length > 0) {
63
73
  return asErrorResult(`The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
64
74
  .map((m) => m.fullyQualifiedName)
65
75
  .join(', ')}`);
66
76
  }
67
77
  }
68
- // this is not required, but passing a Stainless API key for the matching project_name
69
- // will allow you to run code-mode queries against non-published versions of your SDK.
70
- const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
71
- const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
72
- const res = await fetch(codeModeEndpoint, {
73
- method: 'POST',
74
- headers: {
75
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
76
- 'Content-Type': 'application/json',
77
- client_envs: JSON.stringify({
78
- ZAVUDEV_API_KEY: requireValue(readEnv('ZAVUDEV_API_KEY') ?? client.apiKey, 'set ZAVUDEV_API_KEY environment variable or provide apiKey client option'),
79
- ZAVUDEV_BASE_URL: readEnv('ZAVUDEV_BASE_URL') ?? client.baseURL ?? undefined,
80
- }),
81
- },
82
- body: JSON.stringify({
83
- project_name: 'zavudev',
84
- code,
85
- intent,
86
- client_opts: {},
87
- }),
88
- });
89
- if (!res.ok) {
90
- throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
78
+ if (codeExecutionMode === 'local') {
79
+ return await localDenoHandler({ reqContext, args });
91
80
  }
92
- const { is_error, result, log_lines, err_lines } = (await res.json());
93
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
94
- const output = {
95
- result,
96
- ...(log_lines.length > 0 && { log_lines }),
97
- ...(err_lines.length > 0 && { err_lines }),
98
- };
99
- if (is_error) {
100
- return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
81
+ else {
82
+ return await remoteStainlessHandler({ reqContext, args });
101
83
  }
102
- return asTextContentResult(output);
103
84
  };
104
85
  return { metadata, tool, handler };
105
86
  }
87
+ const remoteStainlessHandler = async ({ reqContext, args, }) => {
88
+ const code = args.code;
89
+ const intent = args.intent;
90
+ const client = reqContext.client;
91
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
92
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
93
+ const res = await fetch(codeModeEndpoint, {
94
+ method: 'POST',
95
+ headers: {
96
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
97
+ 'Content-Type': 'application/json',
98
+ client_envs: JSON.stringify({
99
+ ZAVUDEV_API_KEY: requireValue(readEnv('ZAVUDEV_API_KEY') ?? client.apiKey, 'set ZAVUDEV_API_KEY environment variable or provide apiKey client option'),
100
+ ZAVUDEV_BASE_URL: readEnv('ZAVUDEV_BASE_URL') ?? client.baseURL ?? undefined,
101
+ }),
102
+ },
103
+ body: JSON.stringify({
104
+ project_name: 'zavudev',
105
+ code,
106
+ intent,
107
+ client_opts: {},
108
+ }),
109
+ });
110
+ if (!res.ok) {
111
+ throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
112
+ }
113
+ const { is_error, result, log_lines, err_lines } = (await res.json());
114
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
115
+ const output = {
116
+ result,
117
+ ...(log_lines.length > 0 && { log_lines }),
118
+ ...(err_lines.length > 0 && { err_lines }),
119
+ };
120
+ if (is_error) {
121
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
122
+ }
123
+ return asTextContentResult(output);
124
+ };
125
+ const localDenoHandler = async ({ reqContext, args, }) => {
126
+ const client = reqContext.client;
127
+ const baseURLHostname = new URL(client.baseURL).hostname;
128
+ const { code } = args;
129
+ let denoPath;
130
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
131
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
132
+ // Check if deno is in PATH
133
+ const { execSync } = await import('node:child_process');
134
+ try {
135
+ execSync('command -v deno', { stdio: 'ignore' });
136
+ denoPath = 'deno';
137
+ }
138
+ catch {
139
+ try {
140
+ // Use deno binary in node_modules if it's found
141
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
142
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
143
+ denoPath = denoNodeModulesPath;
144
+ }
145
+ catch {
146
+ return asErrorResult('Deno is required for code execution but was not found. ' +
147
+ 'Install it from https://deno.land or run: npm install deno');
148
+ }
149
+ }
150
+ const allowReadPaths = [
151
+ 'code-tool-worker.mjs',
152
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
153
+ packageRoot,
154
+ ];
155
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
156
+ try {
157
+ const sdkPkgName = '@zavudev/sdk';
158
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
159
+ const realSdkDir = fs.realpathSync(sdkDir);
160
+ if (realSdkDir !== sdkDir) {
161
+ allowReadPaths.push(realSdkDir);
162
+ }
163
+ }
164
+ catch {
165
+ // Ignore if symlink resolution fails
166
+ }
167
+ const allowRead = allowReadPaths.join(',');
168
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
169
+ denoExecutable: denoPath,
170
+ runFlags: [
171
+ `--node-modules-dir=manual`,
172
+ `--allow-read=${allowRead}`,
173
+ `--allow-net=${baseURLHostname}`,
174
+ // Allow environment variables because instantiating the client will try to read from them,
175
+ // even though they are not set.
176
+ '--allow-env',
177
+ ],
178
+ printOutput: true,
179
+ spawnOptions: {
180
+ cwd: path.dirname(workerPath),
181
+ },
182
+ });
183
+ try {
184
+ const resp = await new Promise((resolve, reject) => {
185
+ worker.addEventListener('exit', (exitCode) => {
186
+ reject(new Error(`Worker exited with code ${exitCode}`));
187
+ });
188
+ const opts = {
189
+ baseURL: client.baseURL,
190
+ apiKey: client.apiKey,
191
+ defaultHeaders: {
192
+ 'X-Stainless-MCP': 'true',
193
+ },
194
+ };
195
+ const req = worker.request('http://localhost', {
196
+ headers: {
197
+ 'content-type': 'application/json',
198
+ },
199
+ method: 'POST',
200
+ }, (resp) => {
201
+ const body = [];
202
+ resp.on('error', (err) => {
203
+ reject(err);
204
+ });
205
+ resp.on('data', (chunk) => {
206
+ body.push(chunk);
207
+ });
208
+ resp.on('end', () => {
209
+ resolve(new Response(Buffer.concat(body).toString(), {
210
+ status: resp.statusCode ?? 200,
211
+ headers: resp.headers,
212
+ }));
213
+ });
214
+ });
215
+ const body = JSON.stringify({
216
+ opts,
217
+ code,
218
+ });
219
+ req.write(body, (err) => {
220
+ if (err != null) {
221
+ reject(err);
222
+ }
223
+ });
224
+ req.end();
225
+ });
226
+ if (resp.status === 200) {
227
+ const { result, log_lines, err_lines } = (await resp.json());
228
+ const returnOutput = result == null ? null : ({
229
+ type: 'text',
230
+ text: typeof result === 'string' ? result : JSON.stringify(result),
231
+ });
232
+ const logOutput = log_lines.length === 0 ?
233
+ null
234
+ : {
235
+ type: 'text',
236
+ text: log_lines.join('\n'),
237
+ };
238
+ const errOutput = err_lines.length === 0 ?
239
+ null
240
+ : {
241
+ type: 'text',
242
+ text: 'Error output:\n' + err_lines.join('\n'),
243
+ };
244
+ return {
245
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
246
+ };
247
+ }
248
+ else {
249
+ const { result, log_lines, err_lines } = (await resp.json());
250
+ const messageOutput = result == null ? null : ({
251
+ type: 'text',
252
+ text: typeof result === 'string' ? result : JSON.stringify(result),
253
+ });
254
+ const logOutput = log_lines.length === 0 ?
255
+ null
256
+ : {
257
+ type: 'text',
258
+ text: log_lines.join('\n'),
259
+ };
260
+ const errOutput = err_lines.length === 0 ?
261
+ null
262
+ : {
263
+ type: 'text',
264
+ text: 'Error output:\n' + err_lines.join('\n'),
265
+ };
266
+ return {
267
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
268
+ isError: true,
269
+ };
270
+ }
271
+ }
272
+ finally {
273
+ worker.terminate();
274
+ }
275
+ };
106
276
  //# sourceMappingURL=code-tool.mjs.map