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