@llamaindex/llama-cloud-mcp 1.6.0 → 1.7.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 (91) 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 +345 -0
  12. package/code-tool-worker.js.map +1 -0
  13. package/code-tool-worker.mjs +340 -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 +260 -37
  20. package/code-tool.js.map +1 -1
  21. package/code-tool.mjs +224 -37
  22. package/code-tool.mjs.map +1 -1
  23. package/docs-search-tool.d.mts +1 -1
  24. package/docs-search-tool.d.mts.map +1 -1
  25. package/docs-search-tool.d.ts +1 -1
  26. package/docs-search-tool.d.ts.map +1 -1
  27. package/docs-search-tool.js +21 -2
  28. package/docs-search-tool.js.map +1 -1
  29. package/docs-search-tool.mjs +21 -2
  30. package/docs-search-tool.mjs.map +1 -1
  31. package/http.d.mts +2 -4
  32. package/http.d.mts.map +1 -1
  33. package/http.d.ts +2 -4
  34. package/http.d.ts.map +1 -1
  35. package/http.js +62 -41
  36. package/http.js.map +1 -1
  37. package/http.mjs +62 -41
  38. package/http.mjs.map +1 -1
  39. package/index.js +13 -12
  40. package/index.js.map +1 -1
  41. package/index.mjs +13 -12
  42. package/index.mjs.map +1 -1
  43. package/instructions.d.mts +2 -0
  44. package/instructions.d.mts.map +1 -0
  45. package/instructions.d.ts +2 -0
  46. package/instructions.d.ts.map +1 -0
  47. package/instructions.js +56 -0
  48. package/instructions.js.map +1 -0
  49. package/instructions.mjs +53 -0
  50. package/instructions.mjs.map +1 -0
  51. package/logger.d.mts +7 -0
  52. package/logger.d.mts.map +1 -0
  53. package/logger.d.ts +7 -0
  54. package/logger.d.ts.map +1 -0
  55. package/logger.js +29 -0
  56. package/logger.js.map +1 -0
  57. package/logger.mjs +22 -0
  58. package/logger.mjs.map +1 -0
  59. package/options.d.mts +4 -0
  60. package/options.d.mts.map +1 -1
  61. package/options.d.ts +4 -0
  62. package/options.d.ts.map +1 -1
  63. package/options.js +23 -0
  64. package/options.js.map +1 -1
  65. package/options.mjs +23 -0
  66. package/options.mjs.map +1 -1
  67. package/package.json +42 -5
  68. package/server.d.mts.map +1 -1
  69. package/server.d.ts.map +1 -1
  70. package/server.js +61 -46
  71. package/server.js.map +1 -1
  72. package/server.mjs +60 -45
  73. package/server.mjs.map +1 -1
  74. package/src/code-tool-paths.cts +3 -0
  75. package/src/code-tool-types.ts +1 -0
  76. package/src/code-tool-worker.ts +391 -0
  77. package/src/code-tool.ts +291 -47
  78. package/src/docs-search-tool.ts +34 -3
  79. package/src/http.ts +63 -42
  80. package/src/index.ts +15 -13
  81. package/src/instructions.ts +75 -0
  82. package/src/logger.ts +28 -0
  83. package/src/options.ts +32 -0
  84. package/src/server.ts +63 -56
  85. package/src/stdio.ts +2 -1
  86. package/stdio.d.mts.map +1 -1
  87. package/stdio.d.ts.map +1 -1
  88. package/stdio.js +2 -1
  89. package/stdio.js.map +1 -1
  90. package/stdio.mjs +2 -1
  91. package/stdio.mjs.map +1 -1
package/code-tool.js CHANGED
@@ -1,12 +1,54 @@
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");
48
+ const logger_1 = require("./logger.js");
7
49
  const prompt = `Runs JavaScript code to interact with the Llama Cloud API.
8
50
 
9
- You are a skilled programmer writing code to interface with the service.
51
+ You are a skilled TypeScript programmer writing code to interface with the service.
10
52
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
11
53
  For example:
12
54
 
@@ -26,7 +68,9 @@ You will be returned anything that your function returns, plus the results of an
26
68
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
27
69
  Do not add comments unless necessary for generating better code.
28
70
  Code will run in a container, and cannot interact with the network outside of the given SDK client.
29
- Variables will not persist between calls, so make sure to return or log any data you might need later.`;
71
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
72
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
73
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
30
74
  /**
31
75
  * A tool that runs code against a copy of the SDK.
32
76
  *
@@ -34,9 +78,13 @@ Variables will not persist between calls, so make sure to return or log any data
34
78
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
35
79
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
36
80
  *
37
- * @param endpoints - The endpoints to include in the list.
81
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
82
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
83
+ * with limited API keys.
84
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
85
+ * sandbox environment hosted by Stainless.
38
86
  */
39
- function codeTool({ blockedMethods }) {
87
+ function codeTool({ blockedMethods, codeExecutionMode, }) {
40
88
  const metadata = { resource: 'all', operation: 'write', tags: [] };
41
89
  const tool = {
42
90
  name: 'execute',
@@ -56,10 +104,9 @@ function codeTool({ blockedMethods }) {
56
104
  required: ['code'],
57
105
  },
58
106
  };
107
+ const logger = (0, logger_1.getLogger)();
59
108
  const handler = async ({ reqContext, args, }) => {
60
109
  const code = args.code;
61
- const intent = args.intent;
62
- const client = reqContext.client;
63
110
  // Do very basic blocking of code that includes forbidden method names.
64
111
  //
65
112
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -73,40 +120,216 @@ function codeTool({ blockedMethods }) {
73
120
  .join(', ')}`);
74
121
  }
75
122
  }
76
- const codeModeEndpoint = (0, util_1.readEnv)('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
77
- // Setting a Stainless API key authenticates requests to the code tool endpoint.
78
- const res = await fetch(codeModeEndpoint, {
79
- method: 'POST',
80
- headers: {
81
- ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
82
- 'Content-Type': 'application/json',
83
- client_envs: JSON.stringify({
84
- LLAMA_CLOUD_API_KEY: (0, util_1.requireValue)((0, util_1.readEnv)('LLAMA_CLOUD_API_KEY') ?? client.apiKey, 'set LLAMA_CLOUD_API_KEY environment variable or provide apiKey client option'),
85
- LLAMA_CLOUD_BASE_URL: (0, util_1.readEnv)('LLAMA_CLOUD_BASE_URL') ?? client.baseURL ?? undefined,
86
- }),
87
- },
88
- body: JSON.stringify({
89
- project_name: 'llamacloud-prod',
90
- code,
91
- intent,
92
- client_opts: {},
93
- }),
94
- });
95
- if (!res.ok) {
96
- throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
123
+ let result;
124
+ const startTime = Date.now();
125
+ if (codeExecutionMode === 'local') {
126
+ logger.debug('Executing code in local Deno environment');
127
+ result = await localDenoHandler({ reqContext, args });
97
128
  }
98
- const { is_error, result, log_lines, err_lines } = (await res.json());
99
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
100
- const output = {
101
- result,
102
- ...(log_lines.length > 0 && { log_lines }),
103
- ...(err_lines.length > 0 && { err_lines }),
104
- };
105
- if (is_error) {
106
- return (0, types_1.asErrorResult)(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
129
+ else {
130
+ logger.debug('Executing code in remote Stainless environment');
131
+ result = await remoteStainlessHandler({ reqContext, args });
107
132
  }
108
- return (0, types_1.asTextContentResult)(output);
133
+ logger.info({
134
+ codeExecutionMode,
135
+ durationMs: Date.now() - startTime,
136
+ isError: result.isError,
137
+ contentRows: result.content?.length ?? 0,
138
+ }, 'Got code tool execution result');
139
+ return result;
109
140
  };
110
141
  return { metadata, tool, handler };
111
142
  }
143
+ const remoteStainlessHandler = async ({ reqContext, args, }) => {
144
+ const code = args.code;
145
+ const intent = args.intent;
146
+ const client = reqContext.client;
147
+ const codeModeEndpoint = (0, util_1.readEnv)('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
148
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
149
+ const res = await fetch(codeModeEndpoint, {
150
+ method: 'POST',
151
+ headers: {
152
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
153
+ 'Content-Type': 'application/json',
154
+ client_envs: JSON.stringify({
155
+ LLAMA_CLOUD_API_KEY: (0, util_1.requireValue)((0, util_1.readEnv)('LLAMA_CLOUD_API_KEY') ?? client.apiKey, 'set LLAMA_CLOUD_API_KEY environment variable or provide apiKey client option'),
156
+ LLAMA_CLOUD_BASE_URL: (0, util_1.readEnv)('LLAMA_CLOUD_BASE_URL') ?? client.baseURL ?? undefined,
157
+ }),
158
+ },
159
+ body: JSON.stringify({
160
+ project_name: 'llamacloud-prod',
161
+ code,
162
+ intent,
163
+ client_opts: {},
164
+ }),
165
+ });
166
+ if (!res.ok) {
167
+ if (res.status === 404 && !reqContext.stainlessApiKey) {
168
+ throw new Error('Could not access code tool for this project. You may need to provide a Stainless API key via the STAINLESS_API_KEY environment variable, the --stainless-api-key flag, or the x-stainless-api-key HTTP header.');
169
+ }
170
+ throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
171
+ }
172
+ const { is_error, result, log_lines, err_lines } = (await res.json());
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 (0, types_1.asErrorResult)(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
181
+ }
182
+ return (0, types_1.asTextContentResult)(output);
183
+ };
184
+ const localDenoHandler = async ({ reqContext, args, }) => {
185
+ const client = reqContext.client;
186
+ const baseURLHostname = new URL(client.baseURL).hostname;
187
+ const { code } = args;
188
+ let denoPath;
189
+ const packageRoot = node_path_1.default.resolve(node_path_1.default.dirname(code_tool_paths_cjs_1.workerPath), '..');
190
+ const packageNodeModulesPath = node_path_1.default.resolve(packageRoot, 'node_modules');
191
+ // Check if deno is in PATH
192
+ const { execSync } = await Promise.resolve().then(() => __importStar(require('node:child_process')));
193
+ try {
194
+ execSync('command -v deno', { stdio: 'ignore' });
195
+ denoPath = 'deno';
196
+ }
197
+ catch {
198
+ try {
199
+ // Use deno binary in node_modules if it's found
200
+ const denoNodeModulesPath = node_path_1.default.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
201
+ await node_fs_1.default.promises.access(denoNodeModulesPath, node_fs_1.default.constants.X_OK);
202
+ denoPath = denoNodeModulesPath;
203
+ }
204
+ catch {
205
+ return (0, types_1.asErrorResult)('Deno is required for code execution but was not found. ' +
206
+ 'Install it from https://deno.land or run: npm install deno');
207
+ }
208
+ }
209
+ const allowReadPaths = [
210
+ 'code-tool-worker.mjs',
211
+ `${code_tool_paths_cjs_1.workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
212
+ packageRoot,
213
+ ];
214
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
215
+ try {
216
+ const sdkPkgName = '@llamaindex/llama-cloud';
217
+ const sdkDir = node_path_1.default.resolve(packageNodeModulesPath, sdkPkgName);
218
+ const realSdkDir = node_fs_1.default.realpathSync(sdkDir);
219
+ if (realSdkDir !== sdkDir) {
220
+ allowReadPaths.push(realSdkDir);
221
+ }
222
+ }
223
+ catch {
224
+ // Ignore if symlink resolution fails
225
+ }
226
+ const allowRead = allowReadPaths.join(',');
227
+ const worker = await (0, deno_http_worker_1.newDenoHTTPWorker)(node_url_1.default.pathToFileURL(code_tool_paths_cjs_1.workerPath), {
228
+ denoExecutable: denoPath,
229
+ runFlags: [
230
+ `--node-modules-dir=manual`,
231
+ `--allow-read=${allowRead}`,
232
+ `--allow-net=${baseURLHostname}`,
233
+ // Allow environment variables because instantiating the client will try to read from them,
234
+ // even though they are not set.
235
+ '--allow-env',
236
+ ],
237
+ printOutput: true,
238
+ spawnOptions: {
239
+ cwd: node_path_1.default.dirname(code_tool_paths_cjs_1.workerPath),
240
+ },
241
+ });
242
+ try {
243
+ const resp = await new Promise((resolve, reject) => {
244
+ worker.addEventListener('exit', (exitCode) => {
245
+ reject(new Error(`Worker exited with code ${exitCode}`));
246
+ });
247
+ const opts = {
248
+ baseURL: client.baseURL,
249
+ apiKey: client.apiKey,
250
+ defaultHeaders: {
251
+ 'X-Stainless-MCP': 'true',
252
+ },
253
+ };
254
+ const req = worker.request('http://localhost', {
255
+ headers: {
256
+ 'content-type': 'application/json',
257
+ },
258
+ method: 'POST',
259
+ }, (resp) => {
260
+ const body = [];
261
+ resp.on('error', (err) => {
262
+ reject(err);
263
+ });
264
+ resp.on('data', (chunk) => {
265
+ body.push(chunk);
266
+ });
267
+ resp.on('end', () => {
268
+ resolve(new Response(Buffer.concat(body).toString(), {
269
+ status: resp.statusCode ?? 200,
270
+ headers: resp.headers,
271
+ }));
272
+ });
273
+ });
274
+ const body = JSON.stringify({
275
+ opts,
276
+ code,
277
+ });
278
+ req.write(body, (err) => {
279
+ if (err != null) {
280
+ reject(err);
281
+ }
282
+ });
283
+ req.end();
284
+ });
285
+ if (resp.status === 200) {
286
+ const { result, log_lines, err_lines } = (await resp.json());
287
+ const returnOutput = 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: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
305
+ };
306
+ }
307
+ else {
308
+ const { result, log_lines, err_lines } = (await resp.json());
309
+ const messageOutput = result == null ? null : ({
310
+ type: 'text',
311
+ text: typeof result === 'string' ? result : JSON.stringify(result),
312
+ });
313
+ const logOutput = log_lines.length === 0 ?
314
+ null
315
+ : {
316
+ type: 'text',
317
+ text: log_lines.join('\n'),
318
+ };
319
+ const errOutput = err_lines.length === 0 ?
320
+ null
321
+ : {
322
+ type: 'text',
323
+ text: 'Error output:\n' + err_lines.join('\n'),
324
+ };
325
+ return {
326
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
327
+ isError: true,
328
+ };
329
+ }
330
+ }
331
+ finally {
332
+ worker.terminate();
333
+ }
334
+ };
112
335
  //# 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;;AAgDtF,4BA8FC;AA5ID,sCAOiB;AAEjB,oCAA+C;AAI/C,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;;;;;;;uGAsBwF,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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ChF,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,9 +1,15 @@
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";
9
+ import { getLogger } from "./logger.mjs";
4
10
  const prompt = `Runs JavaScript code to interact with the Llama Cloud API.
5
11
 
6
- You are a skilled programmer writing code to interface with the service.
12
+ You are a skilled TypeScript programmer writing code to interface with the service.
7
13
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
8
14
  For example:
9
15
 
@@ -23,7 +29,9 @@ You will be returned anything that your function returns, plus the results of an
23
29
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
24
30
  Do not add comments unless necessary for generating better code.
25
31
  Code will run in a container, and cannot interact with the network outside of the given SDK client.
26
- Variables will not persist between calls, so make sure to return or log any data you might need later.`;
32
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
33
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
34
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
27
35
  /**
28
36
  * A tool that runs code against a copy of the SDK.
29
37
  *
@@ -31,9 +39,13 @@ Variables will not persist between calls, so make sure to return or log any data
31
39
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
32
40
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
33
41
  *
34
- * @param endpoints - The endpoints to include in the list.
42
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
43
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
44
+ * with limited API keys.
45
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
46
+ * sandbox environment hosted by Stainless.
35
47
  */
36
- export function codeTool({ blockedMethods }) {
48
+ export function codeTool({ blockedMethods, codeExecutionMode, }) {
37
49
  const metadata = { resource: 'all', operation: 'write', tags: [] };
38
50
  const tool = {
39
51
  name: 'execute',
@@ -53,10 +65,9 @@ export function codeTool({ blockedMethods }) {
53
65
  required: ['code'],
54
66
  },
55
67
  };
68
+ const logger = getLogger();
56
69
  const handler = async ({ reqContext, args, }) => {
57
70
  const code = args.code;
58
- const intent = args.intent;
59
- const client = reqContext.client;
60
71
  // Do very basic blocking of code that includes forbidden method names.
61
72
  //
62
73
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -70,40 +81,216 @@ export function codeTool({ blockedMethods }) {
70
81
  .join(', ')}`);
71
82
  }
72
83
  }
73
- const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
74
- // Setting a Stainless API key authenticates requests to the code tool endpoint.
75
- const res = await fetch(codeModeEndpoint, {
76
- method: 'POST',
77
- headers: {
78
- ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
79
- 'Content-Type': 'application/json',
80
- client_envs: JSON.stringify({
81
- LLAMA_CLOUD_API_KEY: requireValue(readEnv('LLAMA_CLOUD_API_KEY') ?? client.apiKey, 'set LLAMA_CLOUD_API_KEY environment variable or provide apiKey client option'),
82
- LLAMA_CLOUD_BASE_URL: readEnv('LLAMA_CLOUD_BASE_URL') ?? client.baseURL ?? undefined,
83
- }),
84
- },
85
- body: JSON.stringify({
86
- project_name: 'llamacloud-prod',
87
- code,
88
- intent,
89
- client_opts: {},
90
- }),
91
- });
92
- if (!res.ok) {
93
- throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
84
+ let result;
85
+ const startTime = Date.now();
86
+ if (codeExecutionMode === 'local') {
87
+ logger.debug('Executing code in local Deno environment');
88
+ result = await localDenoHandler({ reqContext, args });
94
89
  }
95
- const { is_error, result, log_lines, err_lines } = (await res.json());
96
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
97
- const output = {
98
- result,
99
- ...(log_lines.length > 0 && { log_lines }),
100
- ...(err_lines.length > 0 && { err_lines }),
101
- };
102
- if (is_error) {
103
- return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
90
+ else {
91
+ logger.debug('Executing code in remote Stainless environment');
92
+ result = await remoteStainlessHandler({ reqContext, args });
104
93
  }
105
- return asTextContentResult(output);
94
+ logger.info({
95
+ codeExecutionMode,
96
+ durationMs: Date.now() - startTime,
97
+ isError: result.isError,
98
+ contentRows: result.content?.length ?? 0,
99
+ }, 'Got code tool execution result');
100
+ return result;
106
101
  };
107
102
  return { metadata, tool, handler };
108
103
  }
104
+ const remoteStainlessHandler = async ({ reqContext, args, }) => {
105
+ const code = args.code;
106
+ const intent = args.intent;
107
+ const client = reqContext.client;
108
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
109
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
110
+ const res = await fetch(codeModeEndpoint, {
111
+ method: 'POST',
112
+ headers: {
113
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
114
+ 'Content-Type': 'application/json',
115
+ client_envs: JSON.stringify({
116
+ LLAMA_CLOUD_API_KEY: requireValue(readEnv('LLAMA_CLOUD_API_KEY') ?? client.apiKey, 'set LLAMA_CLOUD_API_KEY environment variable or provide apiKey client option'),
117
+ LLAMA_CLOUD_BASE_URL: readEnv('LLAMA_CLOUD_BASE_URL') ?? client.baseURL ?? undefined,
118
+ }),
119
+ },
120
+ body: JSON.stringify({
121
+ project_name: 'llamacloud-prod',
122
+ code,
123
+ intent,
124
+ client_opts: {},
125
+ }),
126
+ });
127
+ if (!res.ok) {
128
+ if (res.status === 404 && !reqContext.stainlessApiKey) {
129
+ throw new Error('Could not access code tool for this project. You may need to provide a Stainless API key via the STAINLESS_API_KEY environment variable, the --stainless-api-key flag, or the x-stainless-api-key HTTP header.');
130
+ }
131
+ throw new Error(`${res.status}: ${res.statusText} error when trying to contact Code Tool server. Details: ${await res.text()}`);
132
+ }
133
+ const { is_error, result, log_lines, err_lines } = (await res.json());
134
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
135
+ const output = {
136
+ result,
137
+ ...(log_lines.length > 0 && { log_lines }),
138
+ ...(err_lines.length > 0 && { err_lines }),
139
+ };
140
+ if (is_error) {
141
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
142
+ }
143
+ return asTextContentResult(output);
144
+ };
145
+ const localDenoHandler = async ({ reqContext, args, }) => {
146
+ const client = reqContext.client;
147
+ const baseURLHostname = new URL(client.baseURL).hostname;
148
+ const { code } = args;
149
+ let denoPath;
150
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
151
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
152
+ // Check if deno is in PATH
153
+ const { execSync } = await import('node:child_process');
154
+ try {
155
+ execSync('command -v deno', { stdio: 'ignore' });
156
+ denoPath = 'deno';
157
+ }
158
+ catch {
159
+ try {
160
+ // Use deno binary in node_modules if it's found
161
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
162
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
163
+ denoPath = denoNodeModulesPath;
164
+ }
165
+ catch {
166
+ return asErrorResult('Deno is required for code execution but was not found. ' +
167
+ 'Install it from https://deno.land or run: npm install deno');
168
+ }
169
+ }
170
+ const allowReadPaths = [
171
+ 'code-tool-worker.mjs',
172
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
173
+ packageRoot,
174
+ ];
175
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
176
+ try {
177
+ const sdkPkgName = '@llamaindex/llama-cloud';
178
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
179
+ const realSdkDir = fs.realpathSync(sdkDir);
180
+ if (realSdkDir !== sdkDir) {
181
+ allowReadPaths.push(realSdkDir);
182
+ }
183
+ }
184
+ catch {
185
+ // Ignore if symlink resolution fails
186
+ }
187
+ const allowRead = allowReadPaths.join(',');
188
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
189
+ denoExecutable: denoPath,
190
+ runFlags: [
191
+ `--node-modules-dir=manual`,
192
+ `--allow-read=${allowRead}`,
193
+ `--allow-net=${baseURLHostname}`,
194
+ // Allow environment variables because instantiating the client will try to read from them,
195
+ // even though they are not set.
196
+ '--allow-env',
197
+ ],
198
+ printOutput: true,
199
+ spawnOptions: {
200
+ cwd: path.dirname(workerPath),
201
+ },
202
+ });
203
+ try {
204
+ const resp = await new Promise((resolve, reject) => {
205
+ worker.addEventListener('exit', (exitCode) => {
206
+ reject(new Error(`Worker exited with code ${exitCode}`));
207
+ });
208
+ const opts = {
209
+ baseURL: client.baseURL,
210
+ apiKey: client.apiKey,
211
+ defaultHeaders: {
212
+ 'X-Stainless-MCP': 'true',
213
+ },
214
+ };
215
+ const req = worker.request('http://localhost', {
216
+ headers: {
217
+ 'content-type': 'application/json',
218
+ },
219
+ method: 'POST',
220
+ }, (resp) => {
221
+ const body = [];
222
+ resp.on('error', (err) => {
223
+ reject(err);
224
+ });
225
+ resp.on('data', (chunk) => {
226
+ body.push(chunk);
227
+ });
228
+ resp.on('end', () => {
229
+ resolve(new Response(Buffer.concat(body).toString(), {
230
+ status: resp.statusCode ?? 200,
231
+ headers: resp.headers,
232
+ }));
233
+ });
234
+ });
235
+ const body = JSON.stringify({
236
+ opts,
237
+ code,
238
+ });
239
+ req.write(body, (err) => {
240
+ if (err != null) {
241
+ reject(err);
242
+ }
243
+ });
244
+ req.end();
245
+ });
246
+ if (resp.status === 200) {
247
+ const { result, log_lines, err_lines } = (await resp.json());
248
+ const returnOutput = 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: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
266
+ };
267
+ }
268
+ else {
269
+ const { result, log_lines, err_lines } = (await resp.json());
270
+ const messageOutput = result == null ? null : ({
271
+ type: 'text',
272
+ text: typeof result === 'string' ? result : JSON.stringify(result),
273
+ });
274
+ const logOutput = log_lines.length === 0 ?
275
+ null
276
+ : {
277
+ type: 'text',
278
+ text: log_lines.join('\n'),
279
+ };
280
+ const errOutput = err_lines.length === 0 ?
281
+ null
282
+ : {
283
+ type: 'text',
284
+ text: 'Error output:\n' + err_lines.join('\n'),
285
+ };
286
+ return {
287
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
288
+ isError: true,
289
+ };
290
+ }
291
+ }
292
+ finally {
293
+ worker.terminate();
294
+ }
295
+ };
109
296
  //# sourceMappingURL=code-tool.mjs.map