@roarkanalytics/sdk-mcp 2.25.0 → 2.26.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.
package/code-tool.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { McpTool } from "./types.mjs";
2
2
  import { SdkMethod } from "./methods.mjs";
3
+ import { McpCodeExecutionMode } from "./options.mjs";
3
4
  /**
4
5
  * A tool that runs code against a copy of the SDK.
5
6
  *
@@ -7,9 +8,14 @@ import { SdkMethod } from "./methods.mjs";
7
8
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
8
9
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
9
10
  *
10
- * @param endpoints - The endpoints to include in the list.
11
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
12
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
13
+ * with limited API keys.
14
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
15
+ * sandbox environment hosted by Stainless.
11
16
  */
12
- export declare function codeTool({ blockedMethods }: {
17
+ export declare function codeTool({ blockedMethods, codeExecutionMode, }: {
13
18
  blockedMethods: SdkMethod[] | undefined;
19
+ codeExecutionMode: McpCodeExecutionMode;
14
20
  }): McpTool;
15
21
  //# sourceMappingURL=code-tool.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"code-tool.d.mts","sourceRoot":"","sources":["src/code-tool.ts"],"names":[],"mappings":"OAEO,EAEL,OAAO,EAKR;OAIM,EAAE,SAAS,EAAE;AAsBpB;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,SAAS,EAAE,GAAG,SAAS,CAAA;CAAE,GAAG,OAAO,CA8FjG"}
1
+ {"version":3,"file":"code-tool.d.mts","sourceRoot":"","sources":["src/code-tool.ts"],"names":[],"mappings":"OAOO,EAGL,OAAO,EAKR;OAIM,EAAE,SAAS,EAAE;OACb,EAAE,oBAAoB,EAAE;AAuB/B;;;;;;;;;;;;GAYG;AACH,wBAAgB,QAAQ,CAAC,EACvB,cAAc,EACd,iBAAiB,GAClB,EAAE;IACD,cAAc,EAAE,SAAS,EAAE,GAAG,SAAS,CAAC;IACxC,iBAAiB,EAAE,oBAAoB,CAAC;CACzC,GAAG,OAAO,CAqDV"}
package/code-tool.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { McpTool } from "./types.js";
2
2
  import { SdkMethod } from "./methods.js";
3
+ import { McpCodeExecutionMode } from "./options.js";
3
4
  /**
4
5
  * A tool that runs code against a copy of the SDK.
5
6
  *
@@ -7,9 +8,14 @@ import { SdkMethod } from "./methods.js";
7
8
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
8
9
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
9
10
  *
10
- * @param endpoints - The endpoints to include in the list.
11
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
12
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
13
+ * with limited API keys.
14
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
15
+ * sandbox environment hosted by Stainless.
11
16
  */
12
- export declare function codeTool({ blockedMethods }: {
17
+ export declare function codeTool({ blockedMethods, codeExecutionMode, }: {
13
18
  blockedMethods: SdkMethod[] | undefined;
19
+ codeExecutionMode: McpCodeExecutionMode;
14
20
  }): McpTool;
15
21
  //# sourceMappingURL=code-tool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"code-tool.d.ts","sourceRoot":"","sources":["src/code-tool.ts"],"names":[],"mappings":"OAEO,EAEL,OAAO,EAKR;OAIM,EAAE,SAAS,EAAE;AAsBpB;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,SAAS,EAAE,GAAG,SAAS,CAAA;CAAE,GAAG,OAAO,CA8FjG"}
1
+ {"version":3,"file":"code-tool.d.ts","sourceRoot":"","sources":["src/code-tool.ts"],"names":[],"mappings":"OAOO,EAGL,OAAO,EAKR;OAIM,EAAE,SAAS,EAAE;OACb,EAAE,oBAAoB,EAAE;AAuB/B;;;;;;;;;;;;GAYG;AACH,wBAAgB,QAAQ,CAAC,EACvB,cAAc,EACd,iBAAiB,GAClB,EAAE;IACD,cAAc,EAAE,SAAS,EAAE,GAAG,SAAS,CAAC;IACxC,iBAAiB,EAAE,oBAAoB,CAAC;CACzC,GAAG,OAAO,CAqDV"}
package/code-tool.js CHANGED
@@ -1,7 +1,48 @@
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");
7
48
  const prompt = `Runs JavaScript code to interact with the Roark API.
@@ -30,9 +71,13 @@ Variables will not persist between calls, so make sure to return or log any data
30
71
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
31
72
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
32
73
  *
33
- * @param endpoints - The endpoints to include in the list.
74
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
75
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
76
+ * with limited API keys.
77
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
78
+ * sandbox environment hosted by Stainless.
34
79
  */
35
- function codeTool({ blockedMethods }) {
80
+ function codeTool({ blockedMethods, codeExecutionMode, }) {
36
81
  const metadata = { resource: 'all', operation: 'write', tags: [] };
37
82
  const tool = {
38
83
  name: 'execute',
@@ -54,8 +99,6 @@ function codeTool({ blockedMethods }) {
54
99
  };
55
100
  const handler = async ({ reqContext, args, }) => {
56
101
  const code = args.code;
57
- const intent = args.intent;
58
- const client = reqContext.client;
59
102
  // Do very basic blocking of code that includes forbidden method names.
60
103
  //
61
104
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -69,40 +112,202 @@ function codeTool({ blockedMethods }) {
69
112
  .join(', ')}`);
70
113
  }
71
114
  }
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
- ROARK_API_BEARER_TOKEN: (0, util_1.requireValue)((0, util_1.readEnv)('ROARK_API_BEARER_TOKEN') ?? client.bearerToken, 'set ROARK_API_BEARER_TOKEN environment variable or provide bearerToken client option'),
81
- ROARK_BASE_URL: (0, util_1.readEnv)('ROARK_BASE_URL') ?? client.baseURL ?? undefined,
82
- }),
83
- },
84
- body: JSON.stringify({
85
- project_name: 'roark-analytics',
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()}`);
115
+ if (codeExecutionMode === 'local') {
116
+ return await localDenoHandler({ reqContext, args });
93
117
  }
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));
118
+ else {
119
+ return await remoteStainlessHandler({ reqContext, args });
103
120
  }
104
- return (0, types_1.asTextContentResult)(output);
105
121
  };
106
122
  return { metadata, tool, handler };
107
123
  }
124
+ const remoteStainlessHandler = async ({ reqContext, args, }) => {
125
+ const code = args.code;
126
+ const intent = args.intent;
127
+ const client = reqContext.client;
128
+ const codeModeEndpoint = (0, util_1.readEnv)('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
129
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
130
+ const res = await fetch(codeModeEndpoint, {
131
+ method: 'POST',
132
+ headers: {
133
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
134
+ 'Content-Type': 'application/json',
135
+ client_envs: JSON.stringify({
136
+ ROARK_API_BEARER_TOKEN: (0, util_1.requireValue)((0, util_1.readEnv)('ROARK_API_BEARER_TOKEN') ?? client.bearerToken, 'set ROARK_API_BEARER_TOKEN environment variable or provide bearerToken client option'),
137
+ ROARK_BASE_URL: (0, util_1.readEnv)('ROARK_BASE_URL') ?? client.baseURL ?? undefined,
138
+ }),
139
+ },
140
+ body: JSON.stringify({
141
+ project_name: 'roark-analytics',
142
+ code,
143
+ intent,
144
+ client_opts: {},
145
+ }),
146
+ });
147
+ if (!res.ok) {
148
+ throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
149
+ }
150
+ const { is_error, result, log_lines, err_lines } = (await res.json());
151
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
152
+ const output = {
153
+ result,
154
+ ...(log_lines.length > 0 && { log_lines }),
155
+ ...(err_lines.length > 0 && { err_lines }),
156
+ };
157
+ if (is_error) {
158
+ return (0, types_1.asErrorResult)(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
159
+ }
160
+ return (0, types_1.asTextContentResult)(output);
161
+ };
162
+ const localDenoHandler = async ({ reqContext, args, }) => {
163
+ const client = reqContext.client;
164
+ const baseURLHostname = new URL(client.baseURL).hostname;
165
+ const { code } = args;
166
+ let denoPath;
167
+ const packageRoot = node_path_1.default.resolve(node_path_1.default.dirname(code_tool_paths_cjs_1.workerPath), '..');
168
+ const packageNodeModulesPath = node_path_1.default.resolve(packageRoot, 'node_modules');
169
+ // Check if deno is in PATH
170
+ const { execSync } = await Promise.resolve().then(() => __importStar(require('node:child_process')));
171
+ try {
172
+ execSync('command -v deno', { stdio: 'ignore' });
173
+ denoPath = 'deno';
174
+ }
175
+ catch {
176
+ try {
177
+ // Use deno binary in node_modules if it's found
178
+ const denoNodeModulesPath = node_path_1.default.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
179
+ await node_fs_1.default.promises.access(denoNodeModulesPath, node_fs_1.default.constants.X_OK);
180
+ denoPath = denoNodeModulesPath;
181
+ }
182
+ catch {
183
+ return (0, types_1.asErrorResult)('Deno is required for code execution but was not found. ' +
184
+ 'Install it from https://deno.land or run: npm install deno');
185
+ }
186
+ }
187
+ const allowReadPaths = [
188
+ 'code-tool-worker.mjs',
189
+ `${code_tool_paths_cjs_1.workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
190
+ packageRoot,
191
+ ];
192
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
193
+ try {
194
+ const sdkPkgName = '@roarkanalytics/sdk';
195
+ const sdkDir = node_path_1.default.resolve(packageNodeModulesPath, sdkPkgName);
196
+ const realSdkDir = node_fs_1.default.realpathSync(sdkDir);
197
+ if (realSdkDir !== sdkDir) {
198
+ allowReadPaths.push(realSdkDir);
199
+ }
200
+ }
201
+ catch {
202
+ // Ignore if symlink resolution fails
203
+ }
204
+ const allowRead = allowReadPaths.join(',');
205
+ const worker = await (0, deno_http_worker_1.newDenoHTTPWorker)(node_url_1.default.pathToFileURL(code_tool_paths_cjs_1.workerPath), {
206
+ denoExecutable: denoPath,
207
+ runFlags: [
208
+ `--node-modules-dir=manual`,
209
+ `--allow-read=${allowRead}`,
210
+ `--allow-net=${baseURLHostname}`,
211
+ // Allow environment variables because instantiating the client will try to read from them,
212
+ // even though they are not set.
213
+ '--allow-env',
214
+ ],
215
+ printOutput: true,
216
+ spawnOptions: {
217
+ cwd: node_path_1.default.dirname(code_tool_paths_cjs_1.workerPath),
218
+ },
219
+ });
220
+ try {
221
+ const resp = await new Promise((resolve, reject) => {
222
+ worker.addEventListener('exit', (exitCode) => {
223
+ reject(new Error(`Worker exited with code ${exitCode}`));
224
+ });
225
+ const opts = {
226
+ baseURL: client.baseURL,
227
+ bearerToken: client.bearerToken,
228
+ defaultHeaders: {
229
+ 'X-Stainless-MCP': 'true',
230
+ },
231
+ };
232
+ const req = worker.request('http://localhost', {
233
+ headers: {
234
+ 'content-type': 'application/json',
235
+ },
236
+ method: 'POST',
237
+ }, (resp) => {
238
+ const body = [];
239
+ resp.on('error', (err) => {
240
+ reject(err);
241
+ });
242
+ resp.on('data', (chunk) => {
243
+ body.push(chunk);
244
+ });
245
+ resp.on('end', () => {
246
+ resolve(new Response(Buffer.concat(body).toString(), {
247
+ status: resp.statusCode ?? 200,
248
+ headers: resp.headers,
249
+ }));
250
+ });
251
+ });
252
+ const body = JSON.stringify({
253
+ opts,
254
+ code,
255
+ });
256
+ req.write(body, (err) => {
257
+ if (err != null) {
258
+ reject(err);
259
+ }
260
+ });
261
+ req.end();
262
+ });
263
+ if (resp.status === 200) {
264
+ const { result, log_lines, err_lines } = (await resp.json());
265
+ const returnOutput = result == null ? null : ({
266
+ type: 'text',
267
+ text: typeof result === 'string' ? result : JSON.stringify(result),
268
+ });
269
+ const logOutput = log_lines.length === 0 ?
270
+ null
271
+ : {
272
+ type: 'text',
273
+ text: log_lines.join('\n'),
274
+ };
275
+ const errOutput = err_lines.length === 0 ?
276
+ null
277
+ : {
278
+ type: 'text',
279
+ text: 'Error output:\n' + err_lines.join('\n'),
280
+ };
281
+ return {
282
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
283
+ };
284
+ }
285
+ else {
286
+ const { result, log_lines, err_lines } = (await resp.json());
287
+ const messageOutput = result == null ? null : ({
288
+ type: 'text',
289
+ text: typeof result === 'string' ? result : JSON.stringify(result),
290
+ });
291
+ const logOutput = log_lines.length === 0 ?
292
+ null
293
+ : {
294
+ type: 'text',
295
+ text: log_lines.join('\n'),
296
+ };
297
+ const errOutput = err_lines.length === 0 ?
298
+ null
299
+ : {
300
+ type: 'text',
301
+ text: 'Error output:\n' + err_lines.join('\n'),
302
+ };
303
+ return {
304
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
305
+ isError: true,
306
+ };
307
+ }
308
+ }
309
+ finally {
310
+ worker.terminate();
311
+ }
312
+ };
108
313
  //# 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,CAAC;QAEjC,uEAAuE;QACvE,EAAE;QACF,gFAAgF;QAChF,yFAAyF;QACzF,0FAA0F;QAC1F,IAAI,cAAc,EAAE,CAAC;YACnB,MAAM,cAAc,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ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,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,4 +1,9 @@
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";
4
9
  const prompt = `Runs JavaScript code to interact with the Roark API.
@@ -27,9 +32,13 @@ Variables will not persist between calls, so make sure to return or log any data
27
32
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
28
33
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
29
34
  *
30
- * @param endpoints - The endpoints to include in the list.
35
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
36
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
37
+ * with limited API keys.
38
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
39
+ * sandbox environment hosted by Stainless.
31
40
  */
32
- export function codeTool({ blockedMethods }) {
41
+ export function codeTool({ blockedMethods, codeExecutionMode, }) {
33
42
  const metadata = { resource: 'all', operation: 'write', tags: [] };
34
43
  const tool = {
35
44
  name: 'execute',
@@ -51,8 +60,6 @@ export function codeTool({ blockedMethods }) {
51
60
  };
52
61
  const handler = async ({ reqContext, args, }) => {
53
62
  const code = args.code;
54
- const intent = args.intent;
55
- const client = reqContext.client;
56
63
  // Do very basic blocking of code that includes forbidden method names.
57
64
  //
58
65
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -66,40 +73,202 @@ export function codeTool({ blockedMethods }) {
66
73
  .join(', ')}`);
67
74
  }
68
75
  }
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
- ROARK_API_BEARER_TOKEN: requireValue(readEnv('ROARK_API_BEARER_TOKEN') ?? client.bearerToken, 'set ROARK_API_BEARER_TOKEN environment variable or provide bearerToken client option'),
78
- ROARK_BASE_URL: readEnv('ROARK_BASE_URL') ?? client.baseURL ?? undefined,
79
- }),
80
- },
81
- body: JSON.stringify({
82
- project_name: 'roark-analytics',
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()}`);
76
+ if (codeExecutionMode === 'local') {
77
+ return await localDenoHandler({ reqContext, args });
90
78
  }
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));
79
+ else {
80
+ return await remoteStainlessHandler({ reqContext, args });
100
81
  }
101
- return asTextContentResult(output);
102
82
  };
103
83
  return { metadata, tool, handler };
104
84
  }
85
+ const remoteStainlessHandler = async ({ reqContext, args, }) => {
86
+ const code = args.code;
87
+ const intent = args.intent;
88
+ const client = reqContext.client;
89
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
90
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
91
+ const res = await fetch(codeModeEndpoint, {
92
+ method: 'POST',
93
+ headers: {
94
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
95
+ 'Content-Type': 'application/json',
96
+ client_envs: JSON.stringify({
97
+ ROARK_API_BEARER_TOKEN: requireValue(readEnv('ROARK_API_BEARER_TOKEN') ?? client.bearerToken, 'set ROARK_API_BEARER_TOKEN environment variable or provide bearerToken client option'),
98
+ ROARK_BASE_URL: readEnv('ROARK_BASE_URL') ?? client.baseURL ?? undefined,
99
+ }),
100
+ },
101
+ body: JSON.stringify({
102
+ project_name: 'roark-analytics',
103
+ code,
104
+ intent,
105
+ client_opts: {},
106
+ }),
107
+ });
108
+ if (!res.ok) {
109
+ throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
110
+ }
111
+ const { is_error, result, log_lines, err_lines } = (await res.json());
112
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
113
+ const output = {
114
+ result,
115
+ ...(log_lines.length > 0 && { log_lines }),
116
+ ...(err_lines.length > 0 && { err_lines }),
117
+ };
118
+ if (is_error) {
119
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
120
+ }
121
+ return asTextContentResult(output);
122
+ };
123
+ const localDenoHandler = async ({ reqContext, args, }) => {
124
+ const client = reqContext.client;
125
+ const baseURLHostname = new URL(client.baseURL).hostname;
126
+ const { code } = args;
127
+ let denoPath;
128
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
129
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
130
+ // Check if deno is in PATH
131
+ const { execSync } = await import('node:child_process');
132
+ try {
133
+ execSync('command -v deno', { stdio: 'ignore' });
134
+ denoPath = 'deno';
135
+ }
136
+ catch {
137
+ try {
138
+ // Use deno binary in node_modules if it's found
139
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
140
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
141
+ denoPath = denoNodeModulesPath;
142
+ }
143
+ catch {
144
+ return asErrorResult('Deno is required for code execution but was not found. ' +
145
+ 'Install it from https://deno.land or run: npm install deno');
146
+ }
147
+ }
148
+ const allowReadPaths = [
149
+ 'code-tool-worker.mjs',
150
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
151
+ packageRoot,
152
+ ];
153
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
154
+ try {
155
+ const sdkPkgName = '@roarkanalytics/sdk';
156
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
157
+ const realSdkDir = fs.realpathSync(sdkDir);
158
+ if (realSdkDir !== sdkDir) {
159
+ allowReadPaths.push(realSdkDir);
160
+ }
161
+ }
162
+ catch {
163
+ // Ignore if symlink resolution fails
164
+ }
165
+ const allowRead = allowReadPaths.join(',');
166
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
167
+ denoExecutable: denoPath,
168
+ runFlags: [
169
+ `--node-modules-dir=manual`,
170
+ `--allow-read=${allowRead}`,
171
+ `--allow-net=${baseURLHostname}`,
172
+ // Allow environment variables because instantiating the client will try to read from them,
173
+ // even though they are not set.
174
+ '--allow-env',
175
+ ],
176
+ printOutput: true,
177
+ spawnOptions: {
178
+ cwd: path.dirname(workerPath),
179
+ },
180
+ });
181
+ try {
182
+ const resp = await new Promise((resolve, reject) => {
183
+ worker.addEventListener('exit', (exitCode) => {
184
+ reject(new Error(`Worker exited with code ${exitCode}`));
185
+ });
186
+ const opts = {
187
+ baseURL: client.baseURL,
188
+ bearerToken: client.bearerToken,
189
+ defaultHeaders: {
190
+ 'X-Stainless-MCP': 'true',
191
+ },
192
+ };
193
+ const req = worker.request('http://localhost', {
194
+ headers: {
195
+ 'content-type': 'application/json',
196
+ },
197
+ method: 'POST',
198
+ }, (resp) => {
199
+ const body = [];
200
+ resp.on('error', (err) => {
201
+ reject(err);
202
+ });
203
+ resp.on('data', (chunk) => {
204
+ body.push(chunk);
205
+ });
206
+ resp.on('end', () => {
207
+ resolve(new Response(Buffer.concat(body).toString(), {
208
+ status: resp.statusCode ?? 200,
209
+ headers: resp.headers,
210
+ }));
211
+ });
212
+ });
213
+ const body = JSON.stringify({
214
+ opts,
215
+ code,
216
+ });
217
+ req.write(body, (err) => {
218
+ if (err != null) {
219
+ reject(err);
220
+ }
221
+ });
222
+ req.end();
223
+ });
224
+ if (resp.status === 200) {
225
+ const { result, log_lines, err_lines } = (await resp.json());
226
+ const returnOutput = result == null ? null : ({
227
+ type: 'text',
228
+ text: typeof result === 'string' ? result : JSON.stringify(result),
229
+ });
230
+ const logOutput = log_lines.length === 0 ?
231
+ null
232
+ : {
233
+ type: 'text',
234
+ text: log_lines.join('\n'),
235
+ };
236
+ const errOutput = err_lines.length === 0 ?
237
+ null
238
+ : {
239
+ type: 'text',
240
+ text: 'Error output:\n' + err_lines.join('\n'),
241
+ };
242
+ return {
243
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
244
+ };
245
+ }
246
+ else {
247
+ const { result, log_lines, err_lines } = (await resp.json());
248
+ const messageOutput = result == null ? null : ({
249
+ type: 'text',
250
+ text: typeof result === 'string' ? result : JSON.stringify(result),
251
+ });
252
+ const logOutput = log_lines.length === 0 ?
253
+ null
254
+ : {
255
+ type: 'text',
256
+ text: log_lines.join('\n'),
257
+ };
258
+ const errOutput = err_lines.length === 0 ?
259
+ null
260
+ : {
261
+ type: 'text',
262
+ text: 'Error output:\n' + err_lines.join('\n'),
263
+ };
264
+ return {
265
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
266
+ isError: true,
267
+ };
268
+ }
269
+ }
270
+ finally {
271
+ worker.terminate();
272
+ }
273
+ };
105
274
  //# sourceMappingURL=code-tool.mjs.map