@cjavdev/believe-mcp 0.13.2 → 0.14.1

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