@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/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,
@@ -12,6 +18,8 @@ import { Tool } from '@modelcontextprotocol/sdk/types.js';
12
18
  import { readEnv, requireValue } from './util';
13
19
  import { WorkerInput, WorkerOutput } from './code-tool-types';
14
20
  import { SdkMethod } from './methods';
21
+ import { McpCodeExecutionMode } from './options';
22
+ import { ClientOptions } from '@roarkanalytics/sdk';
15
23
 
16
24
  const prompt = `Runs JavaScript code to interact with the Roark API.
17
25
 
@@ -40,9 +48,19 @@ Variables will not persist between calls, so make sure to return or log any data
40
48
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
41
49
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
42
50
  *
43
- * @param endpoints - The endpoints to include in the list.
51
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
52
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
53
+ * with limited API keys.
54
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
55
+ * sandbox environment hosted by Stainless.
44
56
  */
45
- export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | undefined }): McpTool {
57
+ export function codeTool({
58
+ blockedMethods,
59
+ codeExecutionMode,
60
+ }: {
61
+ blockedMethods: SdkMethod[] | undefined;
62
+ codeExecutionMode: McpCodeExecutionMode;
63
+ }): McpTool {
46
64
  const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
47
65
  const tool: Tool = {
48
66
  name: 'execute',
@@ -62,6 +80,7 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
62
80
  required: ['code'],
63
81
  },
64
82
  };
83
+
65
84
  const handler = async ({
66
85
  reqContext,
67
86
  args,
@@ -70,9 +89,6 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
70
89
  args: any;
71
90
  }): Promise<ToolCallResult> => {
72
91
  const code = args.code as string;
73
- const intent = args.intent as string | undefined;
74
- const client = reqContext.client;
75
-
76
92
  // Do very basic blocking of code that includes forbidden method names.
77
93
  //
78
94
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -89,51 +105,253 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
89
105
  }
90
106
  }
91
107
 
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
- ROARK_API_BEARER_TOKEN: requireValue(
103
- readEnv('ROARK_API_BEARER_TOKEN') ?? client.bearerToken,
104
- 'set ROARK_API_BEARER_TOKEN environment variable or provide bearerToken client option',
105
- ),
106
- ROARK_BASE_URL: readEnv('ROARK_BASE_URL') ?? client.baseURL ?? undefined,
107
- }),
108
- },
109
- body: JSON.stringify({
110
- project_name: 'roark-analytics',
111
- code,
112
- intent,
113
- client_opts: {},
114
- } satisfies WorkerInput),
115
- });
108
+ if (codeExecutionMode === 'local') {
109
+ return await localDenoHandler({ reqContext, args });
110
+ } else {
111
+ return await remoteStainlessHandler({ reqContext, args });
112
+ }
113
+ };
114
+
115
+ return { metadata, tool, handler };
116
+ }
117
+
118
+ const remoteStainlessHandler = async ({
119
+ reqContext,
120
+ args,
121
+ }: {
122
+ reqContext: McpRequestContext;
123
+ args: any;
124
+ }): Promise<ToolCallResult> => {
125
+ const code = args.code as string;
126
+ const intent = args.intent as string | undefined;
127
+ const client = reqContext.client;
116
128
 
117
- if (!res.ok) {
118
- throw new Error(
119
- `${res.status}: ${
120
- res.statusText
121
- } error when trying to contact Code Tool server. Details: ${await res.text()}`,
129
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
130
+
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
+ ROARK_API_BEARER_TOKEN: requireValue(
139
+ readEnv('ROARK_API_BEARER_TOKEN') ?? client.bearerToken,
140
+ 'set ROARK_API_BEARER_TOKEN environment variable or provide bearerToken client option',
141
+ ),
142
+ ROARK_BASE_URL: readEnv('ROARK_BASE_URL') ?? client.baseURL ?? undefined,
143
+ }),
144
+ },
145
+ body: JSON.stringify({
146
+ project_name: 'roark-analytics',
147
+ code,
148
+ intent,
149
+ client_opts: {},
150
+ } satisfies WorkerInput),
151
+ });
152
+
153
+ if (!res.ok) {
154
+ throw new Error(
155
+ `${res.status}: ${
156
+ res.statusText
157
+ } error when trying to contact Code Tool server. Details: ${await res.text()}`,
158
+ );
159
+ }
160
+
161
+ const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
162
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
163
+ const output = {
164
+ result,
165
+ ...(log_lines.length > 0 && { log_lines }),
166
+ ...(err_lines.length > 0 && { err_lines }),
167
+ };
168
+ if (is_error) {
169
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
170
+ }
171
+ return asTextContentResult(output);
172
+ };
173
+
174
+ const localDenoHandler = async ({
175
+ reqContext,
176
+ args,
177
+ }: {
178
+ reqContext: McpRequestContext;
179
+ args: unknown;
180
+ }): Promise<ToolCallResult> => {
181
+ const client = reqContext.client;
182
+ const baseURLHostname = new URL(client.baseURL).hostname;
183
+ const { code } = args as { code: string };
184
+
185
+ let denoPath: string;
186
+
187
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
188
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
189
+
190
+ // Check if deno is in PATH
191
+ const { execSync } = await import('node:child_process');
192
+ try {
193
+ execSync('command -v deno', { stdio: 'ignore' });
194
+ denoPath = 'deno';
195
+ } catch {
196
+ try {
197
+ // Use deno binary in node_modules if it's found
198
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
199
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
200
+ denoPath = denoNodeModulesPath;
201
+ } catch {
202
+ return asErrorResult(
203
+ 'Deno is required for code execution but was not found. ' +
204
+ 'Install it from https://deno.land or run: npm install deno',
122
205
  );
123
206
  }
207
+ }
208
+
209
+ const allowReadPaths = [
210
+ 'code-tool-worker.mjs',
211
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
212
+ packageRoot,
213
+ ];
124
214
 
125
- const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
126
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
127
- const output = {
128
- result,
129
- ...(log_lines.length > 0 && { log_lines }),
130
- ...(err_lines.length > 0 && { err_lines }),
131
- };
132
- if (is_error) {
133
- return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
215
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
216
+ try {
217
+ const sdkPkgName = '@roarkanalytics/sdk';
218
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
219
+ const realSdkDir = fs.realpathSync(sdkDir);
220
+ if (realSdkDir !== sdkDir) {
221
+ allowReadPaths.push(realSdkDir);
134
222
  }
135
- return asTextContentResult(output);
136
- };
223
+ } catch {
224
+ // Ignore if symlink resolution fails
225
+ }
137
226
 
138
- return { metadata, tool, handler };
139
- }
227
+ const allowRead = allowReadPaths.join(',');
228
+
229
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
230
+ denoExecutable: denoPath,
231
+ runFlags: [
232
+ `--node-modules-dir=manual`,
233
+ `--allow-read=${allowRead}`,
234
+ `--allow-net=${baseURLHostname}`,
235
+ // Allow environment variables because instantiating the client will try to read from them,
236
+ // even though they are not set.
237
+ '--allow-env',
238
+ ],
239
+ printOutput: true,
240
+ spawnOptions: {
241
+ cwd: path.dirname(workerPath),
242
+ },
243
+ });
244
+
245
+ try {
246
+ const resp = await new Promise<Response>((resolve, reject) => {
247
+ worker.addEventListener('exit', (exitCode) => {
248
+ reject(new Error(`Worker exited with code ${exitCode}`));
249
+ });
250
+
251
+ const opts: ClientOptions = {
252
+ baseURL: client.baseURL,
253
+ bearerToken: client.bearerToken,
254
+ defaultHeaders: {
255
+ 'X-Stainless-MCP': 'true',
256
+ },
257
+ };
258
+
259
+ const req = worker.request(
260
+ 'http://localhost',
261
+ {
262
+ headers: {
263
+ 'content-type': 'application/json',
264
+ },
265
+ method: 'POST',
266
+ },
267
+ (resp) => {
268
+ const body: Uint8Array[] = [];
269
+ resp.on('error', (err) => {
270
+ reject(err);
271
+ });
272
+ resp.on('data', (chunk) => {
273
+ body.push(chunk);
274
+ });
275
+ resp.on('end', () => {
276
+ resolve(
277
+ new Response(Buffer.concat(body).toString(), {
278
+ status: resp.statusCode ?? 200,
279
+ headers: resp.headers as any,
280
+ }),
281
+ );
282
+ });
283
+ },
284
+ );
285
+
286
+ const body = JSON.stringify({
287
+ opts,
288
+ code,
289
+ });
290
+
291
+ req.write(body, (err) => {
292
+ if (err != null) {
293
+ reject(err);
294
+ }
295
+ });
296
+
297
+ req.end();
298
+ });
299
+
300
+ if (resp.status === 200) {
301
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
302
+ const returnOutput: ContentBlock | null =
303
+ result == null ? null : (
304
+ {
305
+ type: 'text',
306
+ text: typeof result === 'string' ? result : JSON.stringify(result),
307
+ }
308
+ );
309
+ const logOutput: ContentBlock | null =
310
+ log_lines.length === 0 ?
311
+ null
312
+ : {
313
+ type: 'text',
314
+ text: log_lines.join('\n'),
315
+ };
316
+ const errOutput: ContentBlock | null =
317
+ err_lines.length === 0 ?
318
+ null
319
+ : {
320
+ type: 'text',
321
+ text: 'Error output:\n' + err_lines.join('\n'),
322
+ };
323
+ return {
324
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
325
+ };
326
+ } else {
327
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
328
+ const messageOutput: ContentBlock | null =
329
+ result == null ? null : (
330
+ {
331
+ type: 'text',
332
+ text: typeof result === 'string' ? result : JSON.stringify(result),
333
+ }
334
+ );
335
+ const logOutput: ContentBlock | null =
336
+ log_lines.length === 0 ?
337
+ null
338
+ : {
339
+ type: 'text',
340
+ text: log_lines.join('\n'),
341
+ };
342
+ const errOutput: ContentBlock | null =
343
+ err_lines.length === 0 ?
344
+ null
345
+ : {
346
+ type: 'text',
347
+ text: 'Error output:\n' + err_lines.join('\n'),
348
+ };
349
+ return {
350
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
351
+ isError: true,
352
+ };
353
+ }
354
+ } finally {
355
+ worker.terminate();
356
+ }
357
+ };
package/src/options.ts CHANGED
@@ -19,8 +19,11 @@ export type McpOptions = {
19
19
  codeAllowHttpGets?: boolean | undefined;
20
20
  codeAllowedMethods?: string[] | undefined;
21
21
  codeBlockedMethods?: string[] | undefined;
22
+ codeExecutionMode: McpCodeExecutionMode;
22
23
  };
23
24
 
25
+ export type McpCodeExecutionMode = 'stainless-sandbox' | 'local';
26
+
24
27
  export function parseCLIOptions(): CLIOptions {
25
28
  const opts = yargs(hideBin(process.argv))
26
29
  .option('code-allow-http-gets', {
@@ -40,6 +43,13 @@ export function parseCLIOptions(): CLIOptions {
40
43
  description:
41
44
  'Methods to explicitly block for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.',
42
45
  })
46
+ .option('code-execution-mode', {
47
+ type: 'string',
48
+ choices: ['stainless-sandbox', 'local'],
49
+ default: 'stainless-sandbox',
50
+ description:
51
+ "Where to run code execution in code tool; 'stainless-sandbox' will execute code in Stainless-hosted sandboxes whereas 'local' will execute code locally on the MCP server machine.",
52
+ })
43
53
  .option('debug', { type: 'boolean', description: 'Enable debug logging' })
44
54
  .option('no-tools', {
45
55
  type: 'string',
@@ -93,6 +103,7 @@ export function parseCLIOptions(): CLIOptions {
93
103
  codeAllowHttpGets: argv.codeAllowHttpGets,
94
104
  codeAllowedMethods: argv.codeAllowedMethods,
95
105
  codeBlockedMethods: argv.codeBlockedMethods,
106
+ codeExecutionMode: argv.codeExecutionMode as McpCodeExecutionMode,
96
107
  transport,
97
108
  port: argv.port,
98
109
  socket: argv.socket,
@@ -124,6 +135,7 @@ export function parseQueryOptions(defaultOptions: McpOptions, query: unknown): M
124
135
  : defaultOptions.includeDocsTools;
125
136
 
126
137
  return {
138
+ codeExecutionMode: defaultOptions.codeExecutionMode,
127
139
  ...(docsTools !== undefined && { includeDocsTools: docsTools }),
128
140
  };
129
141
  }
package/src/server.ts CHANGED
@@ -20,7 +20,7 @@ export const newMcpServer = async (stainlessApiKey: string | undefined) =>
20
20
  new McpServer(
21
21
  {
22
22
  name: 'roarkanalytics_sdk_api',
23
- version: '2.25.0',
23
+ version: '2.26.0',
24
24
  },
25
25
  {
26
26
  instructions: await getInstructions(stainlessApiKey),
@@ -159,6 +159,7 @@ export function selectTools(options?: McpOptions): McpTool[] {
159
159
  const includedTools = [
160
160
  codeTool({
161
161
  blockedMethods: blockedMethodsForCodeTool(options),
162
+ codeExecutionMode: options?.codeExecutionMode ?? 'stainless-sandbox',
162
163
  }),
163
164
  ];
164
165
  if (options?.includeDocsTools ?? true) {