cas-parser-node-mcp 1.9.0 → 1.10.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 (89) hide show
  1. package/code-tool-paths.cjs +6 -0
  2. package/code-tool-paths.cjs.map +1 -0
  3. package/code-tool-paths.d.cts +2 -0
  4. package/code-tool-paths.d.cts.map +1 -0
  5. package/code-tool-types.d.mts.map +1 -1
  6. package/code-tool-types.d.ts.map +1 -1
  7. package/code-tool-worker.d.mts +5 -0
  8. package/code-tool-worker.d.mts.map +1 -0
  9. package/code-tool-worker.d.ts +5 -0
  10. package/code-tool-worker.d.ts.map +1 -0
  11. package/code-tool-worker.js +245 -0
  12. package/code-tool-worker.js.map +1 -0
  13. package/code-tool-worker.mjs +240 -0
  14. package/code-tool-worker.mjs.map +1 -0
  15. package/code-tool.d.mts +8 -2
  16. package/code-tool.d.mts.map +1 -1
  17. package/code-tool.d.ts +8 -2
  18. package/code-tool.d.ts.map +1 -1
  19. package/code-tool.js +257 -37
  20. package/code-tool.js.map +1 -1
  21. package/code-tool.mjs +221 -37
  22. package/code-tool.mjs.map +1 -1
  23. package/docs-search-tool.d.mts +1 -1
  24. package/docs-search-tool.d.mts.map +1 -1
  25. package/docs-search-tool.d.ts +1 -1
  26. package/docs-search-tool.d.ts.map +1 -1
  27. package/docs-search-tool.js +18 -2
  28. package/docs-search-tool.js.map +1 -1
  29. package/docs-search-tool.mjs +18 -2
  30. package/docs-search-tool.mjs.map +1 -1
  31. package/http.d.mts +2 -4
  32. package/http.d.mts.map +1 -1
  33. package/http.d.ts +2 -4
  34. package/http.d.ts.map +1 -1
  35. package/http.js +52 -19
  36. package/http.js.map +1 -1
  37. package/http.mjs +52 -19
  38. package/http.mjs.map +1 -1
  39. package/index.js +12 -11
  40. package/index.js.map +1 -1
  41. package/index.mjs +12 -11
  42. package/index.mjs.map +1 -1
  43. package/instructions.d.mts.map +1 -1
  44. package/instructions.d.ts.map +1 -1
  45. package/instructions.js +2 -1
  46. package/instructions.js.map +1 -1
  47. package/instructions.mjs +2 -1
  48. package/instructions.mjs.map +1 -1
  49. package/logger.d.mts +7 -0
  50. package/logger.d.mts.map +1 -0
  51. package/logger.d.ts +7 -0
  52. package/logger.d.ts.map +1 -0
  53. package/logger.js +29 -0
  54. package/logger.js.map +1 -0
  55. package/logger.mjs +22 -0
  56. package/logger.mjs.map +1 -0
  57. package/options.d.mts +4 -0
  58. package/options.d.mts.map +1 -1
  59. package/options.d.ts +4 -0
  60. package/options.d.ts.map +1 -1
  61. package/options.js +23 -0
  62. package/options.js.map +1 -1
  63. package/options.mjs +23 -0
  64. package/options.mjs.map +1 -1
  65. package/package.json +32 -5
  66. package/server.d.mts.map +1 -1
  67. package/server.d.ts.map +1 -1
  68. package/server.js +7 -5
  69. package/server.js.map +1 -1
  70. package/server.mjs +7 -5
  71. package/server.mjs.map +1 -1
  72. package/src/code-tool-paths.cts +3 -0
  73. package/src/code-tool-types.ts +1 -0
  74. package/src/code-tool-worker.ts +291 -0
  75. package/src/code-tool.ts +287 -48
  76. package/src/docs-search-tool.ts +27 -3
  77. package/src/http.ts +53 -21
  78. package/src/index.ts +14 -12
  79. package/src/instructions.ts +2 -1
  80. package/src/logger.ts +28 -0
  81. package/src/options.ts +32 -0
  82. package/src/server.ts +11 -6
  83. package/src/stdio.ts +2 -1
  84. package/stdio.d.mts.map +1 -1
  85. package/stdio.d.ts.map +1 -1
  86. package/stdio.js +2 -1
  87. package/stdio.js.map +1 -1
  88. package/stdio.mjs +2 -1
  89. package/stdio.mjs.map +1 -1
package/code-tool.js CHANGED
@@ -1,12 +1,54 @@
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
47
  const util_1 = require("./util.js");
48
+ const logger_1 = require("./logger.js");
7
49
  const prompt = `Runs JavaScript code to interact with the Cas Parser API.
8
50
 
9
- You are a skilled programmer writing code to interface with the service.
51
+ You are a skilled TypeScript programmer writing code to interface with the service.
10
52
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
11
53
  For example:
12
54
 
@@ -22,7 +64,9 @@ You will be returned anything that your function returns, plus the results of an
22
64
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
23
65
  Do not add comments unless necessary for generating better code.
24
66
  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.`;
67
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
68
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
69
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
26
70
  /**
27
71
  * A tool that runs code against a copy of the SDK.
28
72
  *
@@ -30,9 +74,13 @@ Variables will not persist between calls, so make sure to return or log any data
30
74
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
31
75
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
32
76
  *
33
- * @param endpoints - The endpoints to include in the list.
77
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
78
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
79
+ * with limited API keys.
80
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
81
+ * sandbox environment hosted by Stainless.
34
82
  */
35
- function codeTool({ blockedMethods }) {
83
+ function codeTool({ blockedMethods, codeExecutionMode, }) {
36
84
  const metadata = { resource: 'all', operation: 'write', tags: [] };
37
85
  const tool = {
38
86
  name: 'execute',
@@ -52,10 +100,9 @@ function codeTool({ blockedMethods }) {
52
100
  required: ['code'],
53
101
  },
54
102
  };
103
+ const logger = (0, logger_1.getLogger)();
55
104
  const handler = async ({ reqContext, args, }) => {
56
105
  const code = args.code;
57
- const intent = args.intent;
58
- const client = reqContext.client;
59
106
  // Do very basic blocking of code that includes forbidden method names.
60
107
  //
61
108
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -69,40 +116,213 @@ function codeTool({ blockedMethods }) {
69
116
  .join(', ')}`);
70
117
  }
71
118
  }
72
- const codeModeEndpoint = (0, util_1.readEnv)('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
73
- // Setting a Stainless API key authenticates requests to the code tool endpoint.
74
- const res = await fetch(codeModeEndpoint, {
75
- method: 'POST',
76
- headers: {
77
- ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
78
- 'Content-Type': 'application/json',
79
- client_envs: JSON.stringify({
80
- CAS_PARSER_API_KEY: (0, util_1.requireValue)((0, util_1.readEnv)('CAS_PARSER_API_KEY') ?? client.apiKey, 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option'),
81
- CAS_PARSER_BASE_URL: (0, util_1.readEnv)('CAS_PARSER_BASE_URL') ?? client.baseURL ?? undefined,
82
- }),
83
- },
84
- body: JSON.stringify({
85
- project_name: 'cas-parser',
86
- code,
87
- intent,
88
- client_opts: {},
89
- }),
90
- });
91
- if (!res.ok) {
92
- throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
119
+ let result;
120
+ const startTime = Date.now();
121
+ if (codeExecutionMode === 'local') {
122
+ logger.debug('Executing code in local Deno environment');
123
+ result = await localDenoHandler({ reqContext, args });
93
124
  }
94
- const { is_error, result, log_lines, err_lines } = (await res.json());
95
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
96
- const output = {
97
- result,
98
- ...(log_lines.length > 0 && { log_lines }),
99
- ...(err_lines.length > 0 && { err_lines }),
100
- };
101
- if (is_error) {
102
- return (0, types_1.asErrorResult)(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
125
+ else {
126
+ logger.debug('Executing code in remote Stainless environment');
127
+ result = await remoteStainlessHandler({ reqContext, args });
103
128
  }
104
- return (0, types_1.asTextContentResult)(output);
129
+ logger.info({
130
+ codeExecutionMode,
131
+ durationMs: Date.now() - startTime,
132
+ isError: result.isError,
133
+ contentRows: result.content?.length ?? 0,
134
+ }, 'Got code tool execution result');
135
+ return result;
105
136
  };
106
137
  return { metadata, tool, handler };
107
138
  }
139
+ const remoteStainlessHandler = async ({ reqContext, args, }) => {
140
+ const code = args.code;
141
+ const intent = args.intent;
142
+ const client = reqContext.client;
143
+ const codeModeEndpoint = (0, util_1.readEnv)('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
144
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
145
+ const res = await fetch(codeModeEndpoint, {
146
+ method: 'POST',
147
+ headers: {
148
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
149
+ 'Content-Type': 'application/json',
150
+ client_envs: JSON.stringify({
151
+ CAS_PARSER_API_KEY: (0, util_1.requireValue)((0, util_1.readEnv)('CAS_PARSER_API_KEY') ?? client.apiKey, 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option'),
152
+ CAS_PARSER_BASE_URL: (0, util_1.readEnv)('CAS_PARSER_BASE_URL') ?? client.baseURL ?? undefined,
153
+ }),
154
+ },
155
+ body: JSON.stringify({
156
+ project_name: 'cas-parser',
157
+ code,
158
+ intent,
159
+ client_opts: {},
160
+ }),
161
+ });
162
+ if (!res.ok) {
163
+ throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
164
+ }
165
+ const { is_error, result, log_lines, err_lines } = (await res.json());
166
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
167
+ const output = {
168
+ result,
169
+ ...(log_lines.length > 0 && { log_lines }),
170
+ ...(err_lines.length > 0 && { err_lines }),
171
+ };
172
+ if (is_error) {
173
+ return (0, types_1.asErrorResult)(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
174
+ }
175
+ return (0, types_1.asTextContentResult)(output);
176
+ };
177
+ const localDenoHandler = async ({ reqContext, args, }) => {
178
+ const client = reqContext.client;
179
+ const baseURLHostname = new URL(client.baseURL).hostname;
180
+ const { code } = args;
181
+ let denoPath;
182
+ const packageRoot = node_path_1.default.resolve(node_path_1.default.dirname(code_tool_paths_cjs_1.workerPath), '..');
183
+ const packageNodeModulesPath = node_path_1.default.resolve(packageRoot, 'node_modules');
184
+ // Check if deno is in PATH
185
+ const { execSync } = await Promise.resolve().then(() => __importStar(require('node:child_process')));
186
+ try {
187
+ execSync('command -v deno', { stdio: 'ignore' });
188
+ denoPath = 'deno';
189
+ }
190
+ catch {
191
+ try {
192
+ // Use deno binary in node_modules if it's found
193
+ const denoNodeModulesPath = node_path_1.default.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
194
+ await node_fs_1.default.promises.access(denoNodeModulesPath, node_fs_1.default.constants.X_OK);
195
+ denoPath = denoNodeModulesPath;
196
+ }
197
+ catch {
198
+ return (0, types_1.asErrorResult)('Deno is required for code execution but was not found. ' +
199
+ 'Install it from https://deno.land or run: npm install deno');
200
+ }
201
+ }
202
+ const allowReadPaths = [
203
+ 'code-tool-worker.mjs',
204
+ `${code_tool_paths_cjs_1.workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
205
+ packageRoot,
206
+ ];
207
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
208
+ try {
209
+ const sdkPkgName = 'cas-parser-node';
210
+ const sdkDir = node_path_1.default.resolve(packageNodeModulesPath, sdkPkgName);
211
+ const realSdkDir = node_fs_1.default.realpathSync(sdkDir);
212
+ if (realSdkDir !== sdkDir) {
213
+ allowReadPaths.push(realSdkDir);
214
+ }
215
+ }
216
+ catch {
217
+ // Ignore if symlink resolution fails
218
+ }
219
+ const allowRead = allowReadPaths.join(',');
220
+ const worker = await (0, deno_http_worker_1.newDenoHTTPWorker)(node_url_1.default.pathToFileURL(code_tool_paths_cjs_1.workerPath), {
221
+ denoExecutable: denoPath,
222
+ runFlags: [
223
+ `--node-modules-dir=manual`,
224
+ `--allow-read=${allowRead}`,
225
+ `--allow-net=${baseURLHostname}`,
226
+ // Allow environment variables because instantiating the client will try to read from them,
227
+ // even though they are not set.
228
+ '--allow-env',
229
+ ],
230
+ printOutput: true,
231
+ spawnOptions: {
232
+ cwd: node_path_1.default.dirname(code_tool_paths_cjs_1.workerPath),
233
+ },
234
+ });
235
+ try {
236
+ const resp = await new Promise((resolve, reject) => {
237
+ worker.addEventListener('exit', (exitCode) => {
238
+ reject(new Error(`Worker exited with code ${exitCode}`));
239
+ });
240
+ const opts = {
241
+ baseURL: client.baseURL,
242
+ apiKey: client.apiKey,
243
+ defaultHeaders: {
244
+ 'X-Stainless-MCP': 'true',
245
+ },
246
+ };
247
+ const req = worker.request('http://localhost', {
248
+ headers: {
249
+ 'content-type': 'application/json',
250
+ },
251
+ method: 'POST',
252
+ }, (resp) => {
253
+ const body = [];
254
+ resp.on('error', (err) => {
255
+ reject(err);
256
+ });
257
+ resp.on('data', (chunk) => {
258
+ body.push(chunk);
259
+ });
260
+ resp.on('end', () => {
261
+ resolve(new Response(Buffer.concat(body).toString(), {
262
+ status: resp.statusCode ?? 200,
263
+ headers: resp.headers,
264
+ }));
265
+ });
266
+ });
267
+ const body = JSON.stringify({
268
+ opts,
269
+ code,
270
+ });
271
+ req.write(body, (err) => {
272
+ if (err != null) {
273
+ reject(err);
274
+ }
275
+ });
276
+ req.end();
277
+ });
278
+ if (resp.status === 200) {
279
+ const { result, log_lines, err_lines } = (await resp.json());
280
+ const returnOutput = result == null ? null : ({
281
+ type: 'text',
282
+ text: typeof result === 'string' ? result : JSON.stringify(result),
283
+ });
284
+ const logOutput = log_lines.length === 0 ?
285
+ null
286
+ : {
287
+ type: 'text',
288
+ text: log_lines.join('\n'),
289
+ };
290
+ const errOutput = err_lines.length === 0 ?
291
+ null
292
+ : {
293
+ type: 'text',
294
+ text: 'Error output:\n' + err_lines.join('\n'),
295
+ };
296
+ return {
297
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
298
+ };
299
+ }
300
+ else {
301
+ const { result, log_lines, err_lines } = (await resp.json());
302
+ const messageOutput = result == null ? null : ({
303
+ type: 'text',
304
+ text: typeof result === 'string' ? result : JSON.stringify(result),
305
+ });
306
+ const logOutput = log_lines.length === 0 ?
307
+ null
308
+ : {
309
+ type: 'text',
310
+ text: log_lines.join('\n'),
311
+ };
312
+ const errOutput = err_lines.length === 0 ?
313
+ null
314
+ : {
315
+ type: 'text',
316
+ text: 'Error output:\n' + err_lines.join('\n'),
317
+ };
318
+ return {
319
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
320
+ isError: true,
321
+ };
322
+ }
323
+ }
324
+ finally {
325
+ worker.terminate();
326
+ }
327
+ };
108
328
  //# 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;;AA4CtF,4BA8FC;AAxID,sCAOiB;AAEjB,oCAA+C;AAI/C,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;;;uGAkBwF,CAAC;AAExG;;;;;;;;GAQG;AACH,SAAgB,QAAQ,CAAC,EAAE,cAAc,EAA+C;IACtF,MAAM,QAAQ,GAAa,EAAE,QAAQ,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;IAC7E,MAAM,IAAI,GAAS;QACjB,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,MAAM;QACnB,WAAW,EAAE;YACX,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE;gBACV,IAAI,EAAE;oBACJ,IAAI,EAAE,QAAQ;oBACd,WAAW,EAAE,kBAAkB;iBAChC;gBACD,MAAM,EAAE;oBACN,IAAI,EAAE,QAAQ;oBACd,WAAW,EAAE,iEAAiE;iBAC/E;aACF;YACD,QAAQ,EAAE,CAAC,MAAM,CAAC;SACnB;KACF,CAAC;IACF,MAAM,OAAO,GAAG,KAAK,EAAE,EACrB,UAAU,EACV,IAAI,GAIL,EAA2B,EAAE;QAC5B,MAAM,IAAI,GAAG,IAAI,CAAC,IAAc,CAAC;QACjC,MAAM,MAAM,GAAG,IAAI,CAAC,MAA4B,CAAC;QACjD,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,C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IAAI,EAAE,CAAiB,CAAC;YAC7E,MAAM,aAAa,GACjB,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CACtB;gBACE,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;aACnE,CACF,CAAC;YACJ,MAAM,SAAS,GACb,SAAS,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;gBACtB,IAAI;gBACN,CAAC,CAAC;oBACE,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;iBAC3B,CAAC;YACN,MAAM,SAAS,GACb,SAAS,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC;gBACtB,IAAI;gBACN,CAAC,CAAC;oBACE,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,iBAAiB,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;iBAC/C,CAAC;YACN,OAAO;gBACL,OAAO,EAAE,CAAC,aAAa,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC;gBAChF,OAAO,EAAE,IAAI;aACd,CAAC;QACJ,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,SAAS,EAAE,CAAC;IACrB,CAAC;AACH,CAAC,CAAC"}
package/code-tool.mjs CHANGED
@@ -1,9 +1,15 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
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';
2
7
  import { asErrorResult, asTextContentResult, } from "./types.mjs";
3
8
  import { readEnv, requireValue } from "./util.mjs";
9
+ import { getLogger } from "./logger.mjs";
4
10
  const prompt = `Runs JavaScript code to interact with the Cas Parser API.
5
11
 
6
- You are a skilled programmer writing code to interface with the service.
12
+ You are a skilled TypeScript programmer writing code to interface with the service.
7
13
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
8
14
  For example:
9
15
 
@@ -19,7 +25,9 @@ You will be returned anything that your function returns, plus the results of an
19
25
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
20
26
  Do not add comments unless necessary for generating better code.
21
27
  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.`;
28
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
29
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
30
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
23
31
  /**
24
32
  * A tool that runs code against a copy of the SDK.
25
33
  *
@@ -27,9 +35,13 @@ Variables will not persist between calls, so make sure to return or log any data
27
35
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
28
36
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
29
37
  *
30
- * @param endpoints - The endpoints to include in the list.
38
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
39
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
40
+ * with limited API keys.
41
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
42
+ * sandbox environment hosted by Stainless.
31
43
  */
32
- export function codeTool({ blockedMethods }) {
44
+ export function codeTool({ blockedMethods, codeExecutionMode, }) {
33
45
  const metadata = { resource: 'all', operation: 'write', tags: [] };
34
46
  const tool = {
35
47
  name: 'execute',
@@ -49,10 +61,9 @@ export function codeTool({ blockedMethods }) {
49
61
  required: ['code'],
50
62
  },
51
63
  };
64
+ const logger = getLogger();
52
65
  const handler = async ({ reqContext, args, }) => {
53
66
  const code = args.code;
54
- const intent = args.intent;
55
- const client = reqContext.client;
56
67
  // Do very basic blocking of code that includes forbidden method names.
57
68
  //
58
69
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -66,40 +77,213 @@ export function codeTool({ blockedMethods }) {
66
77
  .join(', ')}`);
67
78
  }
68
79
  }
69
- const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
70
- // Setting a Stainless API key authenticates requests to the code tool endpoint.
71
- const res = await fetch(codeModeEndpoint, {
72
- method: 'POST',
73
- headers: {
74
- ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
75
- 'Content-Type': 'application/json',
76
- client_envs: JSON.stringify({
77
- CAS_PARSER_API_KEY: requireValue(readEnv('CAS_PARSER_API_KEY') ?? client.apiKey, 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option'),
78
- CAS_PARSER_BASE_URL: readEnv('CAS_PARSER_BASE_URL') ?? client.baseURL ?? undefined,
79
- }),
80
- },
81
- body: JSON.stringify({
82
- project_name: 'cas-parser',
83
- code,
84
- intent,
85
- client_opts: {},
86
- }),
87
- });
88
- if (!res.ok) {
89
- throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
80
+ let result;
81
+ const startTime = Date.now();
82
+ if (codeExecutionMode === 'local') {
83
+ logger.debug('Executing code in local Deno environment');
84
+ result = await localDenoHandler({ reqContext, args });
90
85
  }
91
- const { is_error, result, log_lines, err_lines } = (await res.json());
92
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
93
- const output = {
94
- result,
95
- ...(log_lines.length > 0 && { log_lines }),
96
- ...(err_lines.length > 0 && { err_lines }),
97
- };
98
- if (is_error) {
99
- return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
86
+ else {
87
+ logger.debug('Executing code in remote Stainless environment');
88
+ result = await remoteStainlessHandler({ reqContext, args });
100
89
  }
101
- return asTextContentResult(output);
90
+ logger.info({
91
+ codeExecutionMode,
92
+ durationMs: Date.now() - startTime,
93
+ isError: result.isError,
94
+ contentRows: result.content?.length ?? 0,
95
+ }, 'Got code tool execution result');
96
+ return result;
102
97
  };
103
98
  return { metadata, tool, handler };
104
99
  }
100
+ const remoteStainlessHandler = async ({ reqContext, args, }) => {
101
+ const code = args.code;
102
+ const intent = args.intent;
103
+ const client = reqContext.client;
104
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
105
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
106
+ const res = await fetch(codeModeEndpoint, {
107
+ method: 'POST',
108
+ headers: {
109
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
110
+ 'Content-Type': 'application/json',
111
+ client_envs: JSON.stringify({
112
+ CAS_PARSER_API_KEY: requireValue(readEnv('CAS_PARSER_API_KEY') ?? client.apiKey, 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option'),
113
+ CAS_PARSER_BASE_URL: readEnv('CAS_PARSER_BASE_URL') ?? client.baseURL ?? undefined,
114
+ }),
115
+ },
116
+ body: JSON.stringify({
117
+ project_name: 'cas-parser',
118
+ code,
119
+ intent,
120
+ client_opts: {},
121
+ }),
122
+ });
123
+ if (!res.ok) {
124
+ throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
125
+ }
126
+ const { is_error, result, log_lines, err_lines } = (await res.json());
127
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
128
+ const output = {
129
+ result,
130
+ ...(log_lines.length > 0 && { log_lines }),
131
+ ...(err_lines.length > 0 && { err_lines }),
132
+ };
133
+ if (is_error) {
134
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
135
+ }
136
+ return asTextContentResult(output);
137
+ };
138
+ const localDenoHandler = async ({ reqContext, args, }) => {
139
+ const client = reqContext.client;
140
+ const baseURLHostname = new URL(client.baseURL).hostname;
141
+ const { code } = args;
142
+ let denoPath;
143
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
144
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
145
+ // Check if deno is in PATH
146
+ const { execSync } = await import('node:child_process');
147
+ try {
148
+ execSync('command -v deno', { stdio: 'ignore' });
149
+ denoPath = 'deno';
150
+ }
151
+ catch {
152
+ try {
153
+ // Use deno binary in node_modules if it's found
154
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
155
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
156
+ denoPath = denoNodeModulesPath;
157
+ }
158
+ catch {
159
+ return asErrorResult('Deno is required for code execution but was not found. ' +
160
+ 'Install it from https://deno.land or run: npm install deno');
161
+ }
162
+ }
163
+ const allowReadPaths = [
164
+ 'code-tool-worker.mjs',
165
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
166
+ packageRoot,
167
+ ];
168
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
169
+ try {
170
+ const sdkPkgName = 'cas-parser-node';
171
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
172
+ const realSdkDir = fs.realpathSync(sdkDir);
173
+ if (realSdkDir !== sdkDir) {
174
+ allowReadPaths.push(realSdkDir);
175
+ }
176
+ }
177
+ catch {
178
+ // Ignore if symlink resolution fails
179
+ }
180
+ const allowRead = allowReadPaths.join(',');
181
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
182
+ denoExecutable: denoPath,
183
+ runFlags: [
184
+ `--node-modules-dir=manual`,
185
+ `--allow-read=${allowRead}`,
186
+ `--allow-net=${baseURLHostname}`,
187
+ // Allow environment variables because instantiating the client will try to read from them,
188
+ // even though they are not set.
189
+ '--allow-env',
190
+ ],
191
+ printOutput: true,
192
+ spawnOptions: {
193
+ cwd: path.dirname(workerPath),
194
+ },
195
+ });
196
+ try {
197
+ const resp = await new Promise((resolve, reject) => {
198
+ worker.addEventListener('exit', (exitCode) => {
199
+ reject(new Error(`Worker exited with code ${exitCode}`));
200
+ });
201
+ const opts = {
202
+ baseURL: client.baseURL,
203
+ apiKey: client.apiKey,
204
+ defaultHeaders: {
205
+ 'X-Stainless-MCP': 'true',
206
+ },
207
+ };
208
+ const req = worker.request('http://localhost', {
209
+ headers: {
210
+ 'content-type': 'application/json',
211
+ },
212
+ method: 'POST',
213
+ }, (resp) => {
214
+ const body = [];
215
+ resp.on('error', (err) => {
216
+ reject(err);
217
+ });
218
+ resp.on('data', (chunk) => {
219
+ body.push(chunk);
220
+ });
221
+ resp.on('end', () => {
222
+ resolve(new Response(Buffer.concat(body).toString(), {
223
+ status: resp.statusCode ?? 200,
224
+ headers: resp.headers,
225
+ }));
226
+ });
227
+ });
228
+ const body = JSON.stringify({
229
+ opts,
230
+ code,
231
+ });
232
+ req.write(body, (err) => {
233
+ if (err != null) {
234
+ reject(err);
235
+ }
236
+ });
237
+ req.end();
238
+ });
239
+ if (resp.status === 200) {
240
+ const { result, log_lines, err_lines } = (await resp.json());
241
+ const returnOutput = result == null ? null : ({
242
+ type: 'text',
243
+ text: typeof result === 'string' ? result : JSON.stringify(result),
244
+ });
245
+ const logOutput = log_lines.length === 0 ?
246
+ null
247
+ : {
248
+ type: 'text',
249
+ text: log_lines.join('\n'),
250
+ };
251
+ const errOutput = err_lines.length === 0 ?
252
+ null
253
+ : {
254
+ type: 'text',
255
+ text: 'Error output:\n' + err_lines.join('\n'),
256
+ };
257
+ return {
258
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
259
+ };
260
+ }
261
+ else {
262
+ const { result, log_lines, err_lines } = (await resp.json());
263
+ const messageOutput = result == null ? null : ({
264
+ type: 'text',
265
+ text: typeof result === 'string' ? result : JSON.stringify(result),
266
+ });
267
+ const logOutput = log_lines.length === 0 ?
268
+ null
269
+ : {
270
+ type: 'text',
271
+ text: log_lines.join('\n'),
272
+ };
273
+ const errOutput = err_lines.length === 0 ?
274
+ null
275
+ : {
276
+ type: 'text',
277
+ text: 'Error output:\n' + err_lines.join('\n'),
278
+ };
279
+ return {
280
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
281
+ isError: true,
282
+ };
283
+ }
284
+ }
285
+ finally {
286
+ worker.terminate();
287
+ }
288
+ };
105
289
  //# sourceMappingURL=code-tool.mjs.map