cas-parser-node-mcp 1.8.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 (90) hide show
  1. package/README.md +1 -3
  2. package/code-tool-paths.cjs +6 -0
  3. package/code-tool-paths.cjs.map +1 -0
  4. package/code-tool-paths.d.cts +2 -0
  5. package/code-tool-paths.d.cts.map +1 -0
  6. package/code-tool-types.d.mts.map +1 -1
  7. package/code-tool-types.d.ts.map +1 -1
  8. package/code-tool-worker.d.mts +5 -0
  9. package/code-tool-worker.d.mts.map +1 -0
  10. package/code-tool-worker.d.ts +5 -0
  11. package/code-tool-worker.d.ts.map +1 -0
  12. package/code-tool-worker.js +245 -0
  13. package/code-tool-worker.js.map +1 -0
  14. package/code-tool-worker.mjs +240 -0
  15. package/code-tool-worker.mjs.map +1 -0
  16. package/code-tool.d.mts +8 -2
  17. package/code-tool.d.mts.map +1 -1
  18. package/code-tool.d.ts +8 -2
  19. package/code-tool.d.ts.map +1 -1
  20. package/code-tool.js +257 -39
  21. package/code-tool.js.map +1 -1
  22. package/code-tool.mjs +221 -39
  23. package/code-tool.mjs.map +1 -1
  24. package/docs-search-tool.d.mts +1 -1
  25. package/docs-search-tool.d.mts.map +1 -1
  26. package/docs-search-tool.d.ts +1 -1
  27. package/docs-search-tool.d.ts.map +1 -1
  28. package/docs-search-tool.js +18 -2
  29. package/docs-search-tool.js.map +1 -1
  30. package/docs-search-tool.mjs +18 -2
  31. package/docs-search-tool.mjs.map +1 -1
  32. package/http.d.mts +2 -4
  33. package/http.d.mts.map +1 -1
  34. package/http.d.ts +2 -4
  35. package/http.d.ts.map +1 -1
  36. package/http.js +52 -19
  37. package/http.js.map +1 -1
  38. package/http.mjs +52 -19
  39. package/http.mjs.map +1 -1
  40. package/index.js +12 -11
  41. package/index.js.map +1 -1
  42. package/index.mjs +12 -11
  43. package/index.mjs.map +1 -1
  44. package/instructions.d.mts.map +1 -1
  45. package/instructions.d.ts.map +1 -1
  46. package/instructions.js +2 -1
  47. package/instructions.js.map +1 -1
  48. package/instructions.mjs +2 -1
  49. package/instructions.mjs.map +1 -1
  50. package/logger.d.mts +7 -0
  51. package/logger.d.mts.map +1 -0
  52. package/logger.d.ts +7 -0
  53. package/logger.d.ts.map +1 -0
  54. package/logger.js +29 -0
  55. package/logger.js.map +1 -0
  56. package/logger.mjs +22 -0
  57. package/logger.mjs.map +1 -0
  58. package/options.d.mts +4 -0
  59. package/options.d.mts.map +1 -1
  60. package/options.d.ts +4 -0
  61. package/options.d.ts.map +1 -1
  62. package/options.js +23 -0
  63. package/options.js.map +1 -1
  64. package/options.mjs +23 -0
  65. package/options.mjs.map +1 -1
  66. package/package.json +32 -5
  67. package/server.d.mts.map +1 -1
  68. package/server.d.ts.map +1 -1
  69. package/server.js +7 -7
  70. package/server.js.map +1 -1
  71. package/server.mjs +7 -7
  72. package/server.mjs.map +1 -1
  73. package/src/code-tool-paths.cts +3 -0
  74. package/src/code-tool-types.ts +1 -0
  75. package/src/code-tool-worker.ts +291 -0
  76. package/src/code-tool.ts +287 -51
  77. package/src/docs-search-tool.ts +27 -3
  78. package/src/http.ts +53 -21
  79. package/src/index.ts +14 -12
  80. package/src/instructions.ts +2 -1
  81. package/src/logger.ts +28 -0
  82. package/src/options.ts +32 -0
  83. package/src/server.ts +11 -8
  84. package/src/stdio.ts +2 -1
  85. package/stdio.d.mts.map +1 -1
  86. package/stdio.d.ts.map +1 -1
  87. package/stdio.js +2 -1
  88. package/stdio.js.map +1 -1
  89. package/stdio.mjs +2 -1
  90. package/stdio.mjs.map +1 -1
@@ -0,0 +1,291 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import path from 'node:path';
4
+ import util from 'node:util';
5
+ import Fuse from 'fuse.js';
6
+ import ts from 'typescript';
7
+ import { WorkerOutput } from './code-tool-types';
8
+ import { CasParser, ClientOptions } from 'cas-parser-node';
9
+
10
+ function getRunFunctionSource(code: string): {
11
+ type: 'declaration' | 'expression';
12
+ client: string | undefined;
13
+ code: string;
14
+ } | null {
15
+ const sourceFile = ts.createSourceFile('code.ts', code, ts.ScriptTarget.Latest, true);
16
+ const printer = ts.createPrinter();
17
+
18
+ for (const statement of sourceFile.statements) {
19
+ // Check for top-level function declarations
20
+ if (ts.isFunctionDeclaration(statement)) {
21
+ if (statement.name?.text === 'run') {
22
+ return {
23
+ type: 'declaration',
24
+ client: statement.parameters[0]?.name.getText(),
25
+ code: printer.printNode(ts.EmitHint.Unspecified, statement.body!, sourceFile),
26
+ };
27
+ }
28
+ }
29
+
30
+ // Check for variable declarations: const run = () => {} or const run = function() {}
31
+ if (ts.isVariableStatement(statement)) {
32
+ for (const declaration of statement.declarationList.declarations) {
33
+ if (
34
+ ts.isIdentifier(declaration.name) &&
35
+ declaration.name.text === 'run' &&
36
+ // Check if it's initialized with a function
37
+ declaration.initializer &&
38
+ (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer))
39
+ ) {
40
+ return {
41
+ type: 'expression',
42
+ client: declaration.initializer.parameters[0]?.name.getText(),
43
+ code: printer.printNode(ts.EmitHint.Unspecified, declaration.initializer, sourceFile),
44
+ };
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ return null;
51
+ }
52
+
53
+ function getTSDiagnostics(code: string): string[] {
54
+ const functionSource = getRunFunctionSource(code)!;
55
+ const codeWithImport = [
56
+ 'import { CasParser } from "cas-parser-node";',
57
+ functionSource.type === 'declaration' ?
58
+ `async function run(${functionSource.client}: CasParser)`
59
+ : `const run: (${functionSource.client}: CasParser) => Promise<unknown> =`,
60
+ functionSource.code,
61
+ ].join('\n');
62
+ const sourcePath = path.resolve('code.ts');
63
+ const ast = ts.createSourceFile(sourcePath, codeWithImport, ts.ScriptTarget.Latest, true);
64
+ const options = ts.getDefaultCompilerOptions();
65
+ options.target = ts.ScriptTarget.Latest;
66
+ options.module = ts.ModuleKind.NodeNext;
67
+ options.moduleResolution = ts.ModuleResolutionKind.NodeNext;
68
+ const host = ts.createCompilerHost(options, true);
69
+ const newHost: typeof host = {
70
+ ...host,
71
+ getSourceFile: (...args) => {
72
+ if (path.resolve(args[0]) === sourcePath) {
73
+ return ast;
74
+ }
75
+ return host.getSourceFile(...args);
76
+ },
77
+ readFile: (...args) => {
78
+ if (path.resolve(args[0]) === sourcePath) {
79
+ return codeWithImport;
80
+ }
81
+ return host.readFile(...args);
82
+ },
83
+ fileExists: (...args) => {
84
+ if (path.resolve(args[0]) === sourcePath) {
85
+ return true;
86
+ }
87
+ return host.fileExists(...args);
88
+ },
89
+ };
90
+ const program = ts.createProgram({
91
+ options,
92
+ rootNames: [sourcePath],
93
+ host: newHost,
94
+ });
95
+ const diagnostics = ts.getPreEmitDiagnostics(program, ast);
96
+ return diagnostics.map((d) => {
97
+ const message = ts.flattenDiagnosticMessageText(d.messageText, '\n');
98
+ if (!d.file || !d.start) return `- ${message}`;
99
+ const { line: lineNumber } = ts.getLineAndCharacterOfPosition(d.file, d.start);
100
+ const line = codeWithImport.split('\n').at(lineNumber)?.trim();
101
+ return line ? `- ${message}\n ${line}` : `- ${message}`;
102
+ });
103
+ }
104
+
105
+ const fuse = new Fuse(
106
+ [
107
+ 'client.credits.check',
108
+ 'client.logs.create',
109
+ 'client.logs.getSummary',
110
+ 'client.accessToken.create',
111
+ 'client.verifyToken.verify',
112
+ 'client.camsKfintech.parse',
113
+ 'client.cdsl.parsePdf',
114
+ 'client.cdsl.fetch.requestOtp',
115
+ 'client.cdsl.fetch.verifyOtp',
116
+ 'client.contractNote.parse',
117
+ 'client.inbox.checkConnectionStatus',
118
+ 'client.inbox.connectEmail',
119
+ 'client.inbox.disconnectEmail',
120
+ 'client.inbox.listCasFiles',
121
+ 'client.kfintech.generateCas',
122
+ 'client.nsdl.parse',
123
+ 'client.smart.parseCasPdf',
124
+ 'client.inboundEmail.create',
125
+ 'client.inboundEmail.delete',
126
+ 'client.inboundEmail.list',
127
+ 'client.inboundEmail.retrieve',
128
+ ],
129
+ { threshold: 1, shouldSort: true },
130
+ );
131
+
132
+ function getMethodSuggestions(fullyQualifiedMethodName: string): string[] {
133
+ return fuse
134
+ .search(fullyQualifiedMethodName)
135
+ .map(({ item }) => item)
136
+ .slice(0, 5);
137
+ }
138
+
139
+ const proxyToObj = new WeakMap<any, any>();
140
+ const objToProxy = new WeakMap<any, any>();
141
+
142
+ type ClientProxyConfig = {
143
+ path: string[];
144
+ isBelievedBad?: boolean;
145
+ };
146
+
147
+ function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }: ClientProxyConfig): T {
148
+ let proxy: T = objToProxy.get(obj);
149
+
150
+ if (!proxy) {
151
+ proxy = new Proxy(obj, {
152
+ get(target, prop, receiver) {
153
+ const propPath = [...path, String(prop)];
154
+ const value = Reflect.get(target, prop, receiver);
155
+
156
+ if (isBelievedBad || (!(prop in target) && value === undefined)) {
157
+ // If we're accessing a path that doesn't exist, it will probably eventually error.
158
+ // Let's proxy it and mark it bad so that we can control the error message.
159
+ // We proxy an empty class so that an invocation or construction attempt is possible.
160
+ return makeSdkProxy(class {}, { path: propPath, isBelievedBad: true });
161
+ }
162
+
163
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
164
+ return makeSdkProxy(value, { path: propPath, isBelievedBad });
165
+ }
166
+
167
+ return value;
168
+ },
169
+
170
+ apply(target, thisArg, args) {
171
+ if (isBelievedBad || typeof target !== 'function') {
172
+ const fullyQualifiedMethodName = path.join('.');
173
+ const suggestions = getMethodSuggestions(fullyQualifiedMethodName);
174
+ throw new Error(
175
+ `${fullyQualifiedMethodName} is not a function. Did you mean: ${suggestions.join(', ')}`,
176
+ );
177
+ }
178
+
179
+ return Reflect.apply(target, proxyToObj.get(thisArg) ?? thisArg, args);
180
+ },
181
+
182
+ construct(target, args, newTarget) {
183
+ if (isBelievedBad || typeof target !== 'function') {
184
+ const fullyQualifiedMethodName = path.join('.');
185
+ const suggestions = getMethodSuggestions(fullyQualifiedMethodName);
186
+ throw new Error(
187
+ `${fullyQualifiedMethodName} is not a constructor. Did you mean: ${suggestions.join(', ')}`,
188
+ );
189
+ }
190
+
191
+ return Reflect.construct(target, args, newTarget);
192
+ },
193
+ });
194
+
195
+ objToProxy.set(obj, proxy);
196
+ proxyToObj.set(proxy, obj);
197
+ }
198
+
199
+ return proxy;
200
+ }
201
+
202
+ function parseError(code: string, error: unknown): string | undefined {
203
+ if (!(error instanceof Error)) return;
204
+ const message = error.name ? `${error.name}: ${error.message}` : error.message;
205
+ try {
206
+ // Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
207
+ const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
208
+ // -1 for the zero-based indexing
209
+ const line =
210
+ lineNumber &&
211
+ code
212
+ .split('\n')
213
+ .at(parseInt(lineNumber, 10) - 1)
214
+ ?.trim();
215
+ return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
216
+ } catch {
217
+ return message;
218
+ }
219
+ }
220
+
221
+ const fetch = async (req: Request): Promise<Response> => {
222
+ const { opts, code } = (await req.json()) as { opts: ClientOptions; code: string };
223
+
224
+ const runFunctionSource = code ? getRunFunctionSource(code) : null;
225
+ if (!runFunctionSource) {
226
+ const message =
227
+ code ?
228
+ 'The code is missing a top-level `run` function.'
229
+ : 'The code argument is missing. Provide one containing a top-level `run` function.';
230
+ return Response.json(
231
+ {
232
+ is_error: true,
233
+ result: `${message} Write code within this template:\n\n\`\`\`\nasync function run(client) {\n // Fill this out\n}\n\`\`\``,
234
+ log_lines: [],
235
+ err_lines: [],
236
+ } satisfies WorkerOutput,
237
+ { status: 400, statusText: 'Code execution error' },
238
+ );
239
+ }
240
+
241
+ const diagnostics = getTSDiagnostics(code);
242
+ if (diagnostics.length > 0) {
243
+ return Response.json(
244
+ {
245
+ is_error: true,
246
+ result: `The code contains TypeScript diagnostics:\n${diagnostics.join('\n')}`,
247
+ log_lines: [],
248
+ err_lines: [],
249
+ } satisfies WorkerOutput,
250
+ { status: 400, statusText: 'Code execution error' },
251
+ );
252
+ }
253
+
254
+ const client = new CasParser({
255
+ ...opts,
256
+ });
257
+
258
+ const log_lines: string[] = [];
259
+ const err_lines: string[] = [];
260
+ const console = {
261
+ log: (...args: unknown[]) => {
262
+ log_lines.push(util.format(...args));
263
+ },
264
+ error: (...args: unknown[]) => {
265
+ err_lines.push(util.format(...args));
266
+ },
267
+ };
268
+ try {
269
+ let run_ = async (client: any) => {};
270
+ eval(`${code}\nrun_ = run;`);
271
+ const result = await run_(makeSdkProxy(client, { path: ['client'] }));
272
+ return Response.json({
273
+ is_error: false,
274
+ result,
275
+ log_lines,
276
+ err_lines,
277
+ } satisfies WorkerOutput);
278
+ } catch (e) {
279
+ return Response.json(
280
+ {
281
+ is_error: true,
282
+ result: parseError(code, e),
283
+ log_lines,
284
+ err_lines,
285
+ } satisfies WorkerOutput,
286
+ { status: 400, statusText: 'Code execution error' },
287
+ );
288
+ }
289
+ };
290
+
291
+ export default { fetch };
package/src/code-tool.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
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';
3
8
  import {
9
+ ContentBlock,
4
10
  McpRequestContext,
5
11
  McpTool,
6
12
  Metadata,
@@ -11,11 +17,14 @@ import {
11
17
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
12
18
  import { readEnv, requireValue } from './util';
13
19
  import { WorkerInput, WorkerOutput } from './code-tool-types';
20
+ import { getLogger } from './logger';
14
21
  import { SdkMethod } from './methods';
22
+ import { McpCodeExecutionMode } from './options';
23
+ import { ClientOptions } from 'cas-parser-node';
15
24
 
16
25
  const prompt = `Runs JavaScript code to interact with the Cas Parser API.
17
26
 
18
- You are a skilled programmer writing code to interface with the service.
27
+ You are a skilled TypeScript programmer writing code to interface with the service.
19
28
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
20
29
  For example:
21
30
 
@@ -31,7 +40,9 @@ You will be returned anything that your function returns, plus the results of an
31
40
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
32
41
  Do not add comments unless necessary for generating better code.
33
42
  Code will run in a container, and cannot interact with the network outside of the given SDK client.
34
- Variables will not persist between calls, so make sure to return or log any data you might need later.`;
43
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
44
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
45
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
35
46
 
36
47
  /**
37
48
  * A tool that runs code against a copy of the SDK.
@@ -40,9 +51,19 @@ Variables will not persist between calls, so make sure to return or log any data
40
51
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
41
52
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
42
53
  *
43
- * @param endpoints - The endpoints to include in the list.
54
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
55
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
56
+ * with limited API keys.
57
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
58
+ * sandbox environment hosted by Stainless.
44
59
  */
45
- export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | undefined }): McpTool {
60
+ export function codeTool({
61
+ blockedMethods,
62
+ codeExecutionMode,
63
+ }: {
64
+ blockedMethods: SdkMethod[] | undefined;
65
+ codeExecutionMode: McpCodeExecutionMode;
66
+ }): McpTool {
46
67
  const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
47
68
  const tool: Tool = {
48
69
  name: 'execute',
@@ -62,6 +83,9 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
62
83
  required: ['code'],
63
84
  },
64
85
  };
86
+
87
+ const logger = getLogger();
88
+
65
89
  const handler = async ({
66
90
  reqContext,
67
91
  args,
@@ -70,9 +94,6 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
70
94
  args: any;
71
95
  }): Promise<ToolCallResult> => {
72
96
  const code = args.code as string;
73
- const intent = args.intent as string | undefined;
74
- const client = reqContext.client;
75
-
76
97
  // Do very basic blocking of code that includes forbidden method names.
77
98
  //
78
99
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -89,54 +110,269 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
89
110
  }
90
111
  }
91
112
 
92
- const codeModeEndpoint =
93
- readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
94
-
95
- // Setting a Stainless API key authenticates requests to the code tool endpoint.
96
- const res = await fetch(codeModeEndpoint, {
97
- method: 'POST',
98
- headers: {
99
- ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
100
- 'Content-Type': 'application/json',
101
- client_envs: JSON.stringify({
102
- CAS_PARSER_API_KEY: requireValue(
103
- readEnv('CAS_PARSER_API_KEY') ?? client.apiKey,
104
- 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option',
105
- ),
106
- CAS_PARSER_BASE_URL:
107
- readEnv('CAS_PARSER_BASE_URL') ?? readEnv('CAS_PARSER_ENVIRONMENT') ?
108
- undefined
109
- : client.baseURL ?? undefined,
110
- }),
111
- },
112
- body: JSON.stringify({
113
- project_name: 'cas-parser',
114
- code,
115
- intent,
116
- client_opts: { environment: (readEnv('CAS_PARSER_ENVIRONMENT') || undefined) as any },
117
- } satisfies WorkerInput),
118
- });
113
+ let result: ToolCallResult;
114
+ const startTime = Date.now();
119
115
 
120
- if (!res.ok) {
121
- throw new Error(
122
- `${res.status}: ${
123
- res.statusText
124
- } error when trying to contact Code Tool server. Details: ${await res.text()}`,
125
- );
116
+ if (codeExecutionMode === 'local') {
117
+ logger.debug('Executing code in local Deno environment');
118
+ result = await localDenoHandler({ reqContext, args });
119
+ } else {
120
+ logger.debug('Executing code in remote Stainless environment');
121
+ result = await remoteStainlessHandler({ reqContext, args });
126
122
  }
127
123
 
128
- const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
129
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
130
- const output = {
131
- result,
132
- ...(log_lines.length > 0 && { log_lines }),
133
- ...(err_lines.length > 0 && { err_lines }),
134
- };
135
- if (is_error) {
136
- return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
137
- }
138
- return asTextContentResult(output);
124
+ logger.info(
125
+ {
126
+ codeExecutionMode,
127
+ durationMs: Date.now() - startTime,
128
+ isError: result.isError,
129
+ contentRows: result.content?.length ?? 0,
130
+ },
131
+ 'Got code tool execution result',
132
+ );
133
+ return result;
139
134
  };
140
135
 
141
136
  return { metadata, tool, handler };
142
137
  }
138
+
139
+ const remoteStainlessHandler = async ({
140
+ reqContext,
141
+ args,
142
+ }: {
143
+ reqContext: McpRequestContext;
144
+ args: any;
145
+ }): Promise<ToolCallResult> => {
146
+ const code = args.code as string;
147
+ const intent = args.intent as string | undefined;
148
+ const client = reqContext.client;
149
+
150
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
151
+
152
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
153
+ const res = await fetch(codeModeEndpoint, {
154
+ method: 'POST',
155
+ headers: {
156
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
157
+ 'Content-Type': 'application/json',
158
+ client_envs: JSON.stringify({
159
+ CAS_PARSER_API_KEY: requireValue(
160
+ readEnv('CAS_PARSER_API_KEY') ?? client.apiKey,
161
+ 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option',
162
+ ),
163
+ CAS_PARSER_BASE_URL: readEnv('CAS_PARSER_BASE_URL') ?? client.baseURL ?? undefined,
164
+ }),
165
+ },
166
+ body: JSON.stringify({
167
+ project_name: 'cas-parser',
168
+ code,
169
+ intent,
170
+ client_opts: {},
171
+ } satisfies WorkerInput),
172
+ });
173
+
174
+ if (!res.ok) {
175
+ throw new Error(
176
+ `${res.status}: ${
177
+ res.statusText
178
+ } error when trying to contact Code Tool server. Details: ${await res.text()}`,
179
+ );
180
+ }
181
+
182
+ const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
183
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
184
+ const output = {
185
+ result,
186
+ ...(log_lines.length > 0 && { log_lines }),
187
+ ...(err_lines.length > 0 && { err_lines }),
188
+ };
189
+ if (is_error) {
190
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
191
+ }
192
+ return asTextContentResult(output);
193
+ };
194
+
195
+ const localDenoHandler = async ({
196
+ reqContext,
197
+ args,
198
+ }: {
199
+ reqContext: McpRequestContext;
200
+ args: unknown;
201
+ }): Promise<ToolCallResult> => {
202
+ const client = reqContext.client;
203
+ const baseURLHostname = new URL(client.baseURL).hostname;
204
+ const { code } = args as { code: string };
205
+
206
+ let denoPath: string;
207
+
208
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
209
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
210
+
211
+ // Check if deno is in PATH
212
+ const { execSync } = await import('node:child_process');
213
+ try {
214
+ execSync('command -v deno', { stdio: 'ignore' });
215
+ denoPath = 'deno';
216
+ } catch {
217
+ try {
218
+ // Use deno binary in node_modules if it's found
219
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
220
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
221
+ denoPath = denoNodeModulesPath;
222
+ } catch {
223
+ return asErrorResult(
224
+ 'Deno is required for code execution but was not found. ' +
225
+ 'Install it from https://deno.land or run: npm install deno',
226
+ );
227
+ }
228
+ }
229
+
230
+ const allowReadPaths = [
231
+ 'code-tool-worker.mjs',
232
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
233
+ packageRoot,
234
+ ];
235
+
236
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
237
+ try {
238
+ const sdkPkgName = 'cas-parser-node';
239
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
240
+ const realSdkDir = fs.realpathSync(sdkDir);
241
+ if (realSdkDir !== sdkDir) {
242
+ allowReadPaths.push(realSdkDir);
243
+ }
244
+ } catch {
245
+ // Ignore if symlink resolution fails
246
+ }
247
+
248
+ const allowRead = allowReadPaths.join(',');
249
+
250
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
251
+ denoExecutable: denoPath,
252
+ runFlags: [
253
+ `--node-modules-dir=manual`,
254
+ `--allow-read=${allowRead}`,
255
+ `--allow-net=${baseURLHostname}`,
256
+ // Allow environment variables because instantiating the client will try to read from them,
257
+ // even though they are not set.
258
+ '--allow-env',
259
+ ],
260
+ printOutput: true,
261
+ spawnOptions: {
262
+ cwd: path.dirname(workerPath),
263
+ },
264
+ });
265
+
266
+ try {
267
+ const resp = await new Promise<Response>((resolve, reject) => {
268
+ worker.addEventListener('exit', (exitCode) => {
269
+ reject(new Error(`Worker exited with code ${exitCode}`));
270
+ });
271
+
272
+ const opts: ClientOptions = {
273
+ baseURL: client.baseURL,
274
+ apiKey: client.apiKey,
275
+ defaultHeaders: {
276
+ 'X-Stainless-MCP': 'true',
277
+ },
278
+ };
279
+
280
+ const req = worker.request(
281
+ 'http://localhost',
282
+ {
283
+ headers: {
284
+ 'content-type': 'application/json',
285
+ },
286
+ method: 'POST',
287
+ },
288
+ (resp) => {
289
+ const body: Uint8Array[] = [];
290
+ resp.on('error', (err) => {
291
+ reject(err);
292
+ });
293
+ resp.on('data', (chunk) => {
294
+ body.push(chunk);
295
+ });
296
+ resp.on('end', () => {
297
+ resolve(
298
+ new Response(Buffer.concat(body).toString(), {
299
+ status: resp.statusCode ?? 200,
300
+ headers: resp.headers as any,
301
+ }),
302
+ );
303
+ });
304
+ },
305
+ );
306
+
307
+ const body = JSON.stringify({
308
+ opts,
309
+ code,
310
+ });
311
+
312
+ req.write(body, (err) => {
313
+ if (err != null) {
314
+ reject(err);
315
+ }
316
+ });
317
+
318
+ req.end();
319
+ });
320
+
321
+ if (resp.status === 200) {
322
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
323
+ const returnOutput: ContentBlock | null =
324
+ result == null ? null : (
325
+ {
326
+ type: 'text',
327
+ text: typeof result === 'string' ? result : JSON.stringify(result),
328
+ }
329
+ );
330
+ const logOutput: ContentBlock | null =
331
+ log_lines.length === 0 ?
332
+ null
333
+ : {
334
+ type: 'text',
335
+ text: log_lines.join('\n'),
336
+ };
337
+ const errOutput: ContentBlock | null =
338
+ err_lines.length === 0 ?
339
+ null
340
+ : {
341
+ type: 'text',
342
+ text: 'Error output:\n' + err_lines.join('\n'),
343
+ };
344
+ return {
345
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
346
+ };
347
+ } else {
348
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
349
+ const messageOutput: ContentBlock | null =
350
+ result == null ? null : (
351
+ {
352
+ type: 'text',
353
+ text: typeof result === 'string' ? result : JSON.stringify(result),
354
+ }
355
+ );
356
+ const logOutput: ContentBlock | null =
357
+ log_lines.length === 0 ?
358
+ null
359
+ : {
360
+ type: 'text',
361
+ text: log_lines.join('\n'),
362
+ };
363
+ const errOutput: ContentBlock | null =
364
+ err_lines.length === 0 ?
365
+ null
366
+ : {
367
+ type: 'text',
368
+ text: 'Error output:\n' + err_lines.join('\n'),
369
+ };
370
+ return {
371
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
372
+ isError: true,
373
+ };
374
+ }
375
+ } finally {
376
+ worker.terminate();
377
+ }
378
+ };