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