@llamaindex/llama-cloud-mcp 1.5.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 (131) hide show
  1. package/auth.d.mts +6 -0
  2. package/auth.d.mts.map +1 -0
  3. package/auth.d.ts +6 -0
  4. package/auth.d.ts.map +1 -0
  5. package/{headers.mjs → auth.js} +18 -2
  6. package/auth.js.map +1 -0
  7. package/{headers.js → auth.mjs} +13 -6
  8. package/auth.mjs.map +1 -0
  9. package/code-tool-paths.cjs +6 -0
  10. package/code-tool-paths.cjs.map +1 -0
  11. package/code-tool-paths.d.cts +2 -0
  12. package/code-tool-paths.d.cts.map +1 -0
  13. package/code-tool-types.d.mts.map +1 -1
  14. package/code-tool-types.d.ts.map +1 -1
  15. package/code-tool-worker.d.mts +5 -0
  16. package/code-tool-worker.d.mts.map +1 -0
  17. package/code-tool-worker.d.ts +5 -0
  18. package/code-tool-worker.d.ts.map +1 -0
  19. package/code-tool-worker.js +345 -0
  20. package/code-tool-worker.js.map +1 -0
  21. package/code-tool-worker.mjs +340 -0
  22. package/code-tool-worker.mjs.map +1 -0
  23. package/code-tool.d.mts +8 -2
  24. package/code-tool.d.mts.map +1 -1
  25. package/code-tool.d.ts +8 -2
  26. package/code-tool.d.ts.map +1 -1
  27. package/code-tool.js +264 -42
  28. package/code-tool.js.map +1 -1
  29. package/code-tool.mjs +229 -43
  30. package/code-tool.mjs.map +1 -1
  31. package/docs-search-tool.d.mts +9 -3
  32. package/docs-search-tool.d.mts.map +1 -1
  33. package/docs-search-tool.d.ts +9 -3
  34. package/docs-search-tool.d.ts.map +1 -1
  35. package/docs-search-tool.js +27 -4
  36. package/docs-search-tool.js.map +1 -1
  37. package/docs-search-tool.mjs +27 -4
  38. package/docs-search-tool.mjs.map +1 -1
  39. package/http.d.mts +3 -5
  40. package/http.d.mts.map +1 -1
  41. package/http.d.ts +3 -5
  42. package/http.d.ts.map +1 -1
  43. package/http.js +66 -43
  44. package/http.js.map +1 -1
  45. package/http.mjs +66 -43
  46. package/http.mjs.map +1 -1
  47. package/index.js +13 -12
  48. package/index.js.map +1 -1
  49. package/index.mjs +13 -12
  50. package/index.mjs.map +1 -1
  51. package/instructions.d.mts +2 -0
  52. package/instructions.d.mts.map +1 -0
  53. package/instructions.d.ts +2 -0
  54. package/instructions.d.ts.map +1 -0
  55. package/instructions.js +56 -0
  56. package/instructions.js.map +1 -0
  57. package/instructions.mjs +53 -0
  58. package/instructions.mjs.map +1 -0
  59. package/logger.d.mts +7 -0
  60. package/logger.d.mts.map +1 -0
  61. package/logger.d.ts +7 -0
  62. package/logger.d.ts.map +1 -0
  63. package/logger.js +29 -0
  64. package/logger.js.map +1 -0
  65. package/logger.mjs +22 -0
  66. package/logger.mjs.map +1 -0
  67. package/methods.d.mts.map +1 -1
  68. package/methods.d.ts.map +1 -1
  69. package/methods.js +1 -0
  70. package/methods.js.map +1 -1
  71. package/methods.mjs +1 -0
  72. package/methods.mjs.map +1 -1
  73. package/options.d.mts +5 -0
  74. package/options.d.mts.map +1 -1
  75. package/options.d.ts +5 -0
  76. package/options.d.ts.map +1 -1
  77. package/options.js +31 -0
  78. package/options.js.map +1 -1
  79. package/options.mjs +31 -0
  80. package/options.mjs.map +1 -1
  81. package/package.json +62 -15
  82. package/server.d.mts +8 -9
  83. package/server.d.mts.map +1 -1
  84. package/server.d.ts +8 -9
  85. package/server.d.ts.map +1 -1
  86. package/server.js +73 -75
  87. package/server.js.map +1 -1
  88. package/server.mjs +72 -71
  89. package/server.mjs.map +1 -1
  90. package/src/{headers.ts → auth.ts} +16 -1
  91. package/src/code-tool-paths.cts +3 -0
  92. package/src/code-tool-types.ts +1 -0
  93. package/src/code-tool-worker.ts +391 -0
  94. package/src/code-tool.ts +309 -56
  95. package/src/docs-search-tool.ts +46 -6
  96. package/src/http.ts +74 -45
  97. package/src/index.ts +15 -13
  98. package/src/instructions.ts +75 -0
  99. package/src/logger.ts +28 -0
  100. package/src/methods.ts +2 -0
  101. package/src/options.ts +43 -0
  102. package/src/server.ts +85 -92
  103. package/src/stdio.ts +4 -3
  104. package/src/types.ts +12 -4
  105. package/src/util.ts +25 -0
  106. package/stdio.d.mts.map +1 -1
  107. package/stdio.d.ts.map +1 -1
  108. package/stdio.js +4 -3
  109. package/stdio.js.map +1 -1
  110. package/stdio.mjs +4 -3
  111. package/stdio.mjs.map +1 -1
  112. package/types.d.mts +8 -1
  113. package/types.d.mts.map +1 -1
  114. package/types.d.ts +8 -1
  115. package/types.d.ts.map +1 -1
  116. package/types.js.map +1 -1
  117. package/types.mjs.map +1 -1
  118. package/util.d.mts +4 -0
  119. package/util.d.mts.map +1 -0
  120. package/util.d.ts +4 -0
  121. package/util.d.ts.map +1 -0
  122. package/util.js +30 -0
  123. package/util.js.map +1 -0
  124. package/util.mjs +24 -0
  125. package/util.mjs.map +1 -0
  126. package/headers.d.mts +0 -4
  127. package/headers.d.mts.map +0 -1
  128. package/headers.d.ts +0 -4
  129. package/headers.d.ts.map +0 -1
  130. package/headers.js.map +0 -1
  131. package/headers.mjs.map +0 -1
package/src/code-tool.ts CHANGED
@@ -1,15 +1,30 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
3
- import { McpTool, Metadata, ToolCallResult, asErrorResult, asTextContentResult } from './types';
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';
8
+ import {
9
+ ContentBlock,
10
+ McpRequestContext,
11
+ McpTool,
12
+ Metadata,
13
+ ToolCallResult,
14
+ asErrorResult,
15
+ asTextContentResult,
16
+ } from './types';
4
17
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
5
- import { readEnv, requireValue } from './server';
18
+ import { readEnv, requireValue } from './util';
6
19
  import { WorkerInput, WorkerOutput } from './code-tool-types';
20
+ import { getLogger } from './logger';
7
21
  import { SdkMethod } from './methods';
8
- import { LlamaCloud } from '@llamaindex/llama-cloud';
22
+ import { McpCodeExecutionMode } from './options';
23
+ import { ClientOptions } from '@llamaindex/llama-cloud';
9
24
 
10
25
  const prompt = `Runs JavaScript code to interact with the Llama Cloud API.
11
26
 
12
- You are a skilled programmer writing code to interface with the service.
27
+ You are a skilled TypeScript programmer writing code to interface with the service.
13
28
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
14
29
  For example:
15
30
 
@@ -29,7 +44,9 @@ You will be returned anything that your function returns, plus the results of an
29
44
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
30
45
  Do not add comments unless necessary for generating better code.
31
46
  Code will run in a container, and cannot interact with the network outside of the given SDK client.
32
- Variables will not persist between calls, so make sure to return or log any data you might need later.`;
47
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
48
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
49
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
33
50
 
34
51
  /**
35
52
  * A tool that runs code against a copy of the SDK.
@@ -38,9 +55,19 @@ Variables will not persist between calls, so make sure to return or log any data
38
55
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
39
56
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
40
57
  *
41
- * @param endpoints - The endpoints to include in the list.
58
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
59
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
60
+ * with limited API keys.
61
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
62
+ * sandbox environment hosted by Stainless.
42
63
  */
43
- export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): McpTool {
64
+ export function codeTool({
65
+ blockedMethods,
66
+ codeExecutionMode,
67
+ }: {
68
+ blockedMethods: SdkMethod[] | undefined;
69
+ codeExecutionMode: McpCodeExecutionMode;
70
+ }): McpTool {
44
71
  const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
45
72
  const tool: Tool = {
46
73
  name: 'execute',
@@ -60,19 +87,24 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M
60
87
  required: ['code'],
61
88
  },
62
89
  };
63
- const handler = async (client: LlamaCloud, args: any): Promise<ToolCallResult> => {
64
- const code = args.code as string;
65
- const intent = args.intent as string | undefined;
66
90
 
91
+ const logger = getLogger();
92
+
93
+ const handler = async ({
94
+ reqContext,
95
+ args,
96
+ }: {
97
+ reqContext: McpRequestContext;
98
+ args: any;
99
+ }): Promise<ToolCallResult> => {
100
+ const code = args.code as string;
67
101
  // Do very basic blocking of code that includes forbidden method names.
68
102
  //
69
103
  // WARNING: This is not secure against obfuscation and other evasion methods. If
70
104
  // stronger security blocks are required, then these should be enforced in the downstream
71
105
  // API (e.g., by having users call the MCP server with API keys with limited permissions).
72
- if (params.blockedMethods) {
73
- const blockedMatches = params.blockedMethods.filter((method) =>
74
- code.includes(method.fullyQualifiedName),
75
- );
106
+ if (blockedMethods) {
107
+ const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
76
108
  if (blockedMatches.length > 0) {
77
109
  return asErrorResult(
78
110
  `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
@@ -82,53 +114,274 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M
82
114
  }
83
115
  }
84
116
 
85
- // this is not required, but passing a Stainless API key for the matching project_name
86
- // will allow you to run code-mode queries against non-published versions of your SDK.
87
- const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
88
- const codeModeEndpoint =
89
- readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
90
-
91
- const res = await fetch(codeModeEndpoint, {
92
- method: 'POST',
93
- headers: {
94
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
95
- 'Content-Type': 'application/json',
96
- client_envs: JSON.stringify({
97
- LLAMA_CLOUD_API_KEY: requireValue(
98
- readEnv('LLAMA_CLOUD_API_KEY') ?? client.apiKey,
99
- 'set LLAMA_CLOUD_API_KEY environment variable or provide apiKey client option',
100
- ),
101
- LLAMA_CLOUD_BASE_URL: readEnv('LLAMA_CLOUD_BASE_URL') ?? client.baseURL ?? undefined,
102
- }),
117
+ let result: ToolCallResult;
118
+ const startTime = Date.now();
119
+
120
+ if (codeExecutionMode === 'local') {
121
+ logger.debug('Executing code in local Deno environment');
122
+ result = await localDenoHandler({ reqContext, args });
123
+ } else {
124
+ logger.debug('Executing code in remote Stainless environment');
125
+ result = await remoteStainlessHandler({ reqContext, args });
126
+ }
127
+
128
+ logger.info(
129
+ {
130
+ codeExecutionMode,
131
+ durationMs: Date.now() - startTime,
132
+ isError: result.isError,
133
+ contentRows: result.content?.length ?? 0,
103
134
  },
104
- body: JSON.stringify({
105
- project_name: 'llamacloud-prod',
106
- code,
107
- intent,
108
- client_opts: {},
109
- } satisfies WorkerInput),
110
- });
135
+ 'Got code tool execution result',
136
+ );
137
+ return result;
138
+ };
139
+
140
+ return { metadata, tool, handler };
141
+ }
111
142
 
112
- if (!res.ok) {
143
+ const remoteStainlessHandler = async ({
144
+ reqContext,
145
+ args,
146
+ }: {
147
+ reqContext: McpRequestContext;
148
+ args: any;
149
+ }): Promise<ToolCallResult> => {
150
+ const code = args.code as string;
151
+ const intent = args.intent as string | undefined;
152
+ const client = reqContext.client;
153
+
154
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
155
+
156
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
157
+ const res = await fetch(codeModeEndpoint, {
158
+ method: 'POST',
159
+ headers: {
160
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
161
+ 'Content-Type': 'application/json',
162
+ client_envs: JSON.stringify({
163
+ LLAMA_CLOUD_API_KEY: requireValue(
164
+ readEnv('LLAMA_CLOUD_API_KEY') ?? client.apiKey,
165
+ 'set LLAMA_CLOUD_API_KEY environment variable or provide apiKey client option',
166
+ ),
167
+ LLAMA_CLOUD_BASE_URL: readEnv('LLAMA_CLOUD_BASE_URL') ?? client.baseURL ?? undefined,
168
+ }),
169
+ },
170
+ body: JSON.stringify({
171
+ project_name: 'llamacloud-prod',
172
+ code,
173
+ intent,
174
+ client_opts: {},
175
+ } satisfies WorkerInput),
176
+ });
177
+
178
+ if (!res.ok) {
179
+ if (res.status === 404 && !reqContext.stainlessApiKey) {
113
180
  throw new Error(
114
- `${res.status}: ${
115
- res.statusText
116
- } error when trying to contact Code Tool server. Details: ${await res.text()}`,
181
+ '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.',
117
182
  );
118
183
  }
184
+ throw new Error(
185
+ `${res.status}: ${
186
+ res.statusText
187
+ } error when trying to contact Code Tool server. Details: ${await res.text()}`,
188
+ );
189
+ }
119
190
 
120
- const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
121
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
122
- const output = {
123
- result,
124
- ...(log_lines.length > 0 && { log_lines }),
125
- ...(err_lines.length > 0 && { err_lines }),
126
- };
127
- if (is_error) {
128
- return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
129
- }
130
- return asTextContentResult(output);
191
+ const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
192
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
193
+ const output = {
194
+ result,
195
+ ...(log_lines.length > 0 && { log_lines }),
196
+ ...(err_lines.length > 0 && { err_lines }),
131
197
  };
198
+ if (is_error) {
199
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
200
+ }
201
+ return asTextContentResult(output);
202
+ };
132
203
 
133
- return { metadata, tool, handler };
134
- }
204
+ const localDenoHandler = async ({
205
+ reqContext,
206
+ args,
207
+ }: {
208
+ reqContext: McpRequestContext;
209
+ args: unknown;
210
+ }): Promise<ToolCallResult> => {
211
+ const client = reqContext.client;
212
+ const baseURLHostname = new URL(client.baseURL).hostname;
213
+ const { code } = args as { code: string };
214
+
215
+ let denoPath: string;
216
+
217
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
218
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
219
+
220
+ // Check if deno is in PATH
221
+ const { execSync } = await import('node:child_process');
222
+ try {
223
+ execSync('command -v deno', { stdio: 'ignore' });
224
+ denoPath = 'deno';
225
+ } catch {
226
+ try {
227
+ // Use deno binary in node_modules if it's found
228
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
229
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
230
+ denoPath = denoNodeModulesPath;
231
+ } catch {
232
+ return asErrorResult(
233
+ 'Deno is required for code execution but was not found. ' +
234
+ 'Install it from https://deno.land or run: npm install deno',
235
+ );
236
+ }
237
+ }
238
+
239
+ const allowReadPaths = [
240
+ 'code-tool-worker.mjs',
241
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
242
+ packageRoot,
243
+ ];
244
+
245
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
246
+ try {
247
+ const sdkPkgName = '@llamaindex/llama-cloud';
248
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
249
+ const realSdkDir = fs.realpathSync(sdkDir);
250
+ if (realSdkDir !== sdkDir) {
251
+ allowReadPaths.push(realSdkDir);
252
+ }
253
+ } catch {
254
+ // Ignore if symlink resolution fails
255
+ }
256
+
257
+ const allowRead = allowReadPaths.join(',');
258
+
259
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
260
+ denoExecutable: denoPath,
261
+ runFlags: [
262
+ `--node-modules-dir=manual`,
263
+ `--allow-read=${allowRead}`,
264
+ `--allow-net=${baseURLHostname}`,
265
+ // Allow environment variables because instantiating the client will try to read from them,
266
+ // even though they are not set.
267
+ '--allow-env',
268
+ ],
269
+ printOutput: true,
270
+ spawnOptions: {
271
+ cwd: path.dirname(workerPath),
272
+ },
273
+ });
274
+
275
+ try {
276
+ const resp = await new Promise<Response>((resolve, reject) => {
277
+ worker.addEventListener('exit', (exitCode) => {
278
+ reject(new Error(`Worker exited with code ${exitCode}`));
279
+ });
280
+
281
+ const opts: ClientOptions = {
282
+ baseURL: client.baseURL,
283
+ apiKey: client.apiKey,
284
+ defaultHeaders: {
285
+ 'X-Stainless-MCP': 'true',
286
+ },
287
+ };
288
+
289
+ const req = worker.request(
290
+ 'http://localhost',
291
+ {
292
+ headers: {
293
+ 'content-type': 'application/json',
294
+ },
295
+ method: 'POST',
296
+ },
297
+ (resp) => {
298
+ const body: Uint8Array[] = [];
299
+ resp.on('error', (err) => {
300
+ reject(err);
301
+ });
302
+ resp.on('data', (chunk) => {
303
+ body.push(chunk);
304
+ });
305
+ resp.on('end', () => {
306
+ resolve(
307
+ new Response(Buffer.concat(body).toString(), {
308
+ status: resp.statusCode ?? 200,
309
+ headers: resp.headers as any,
310
+ }),
311
+ );
312
+ });
313
+ },
314
+ );
315
+
316
+ const body = JSON.stringify({
317
+ opts,
318
+ code,
319
+ });
320
+
321
+ req.write(body, (err) => {
322
+ if (err != null) {
323
+ reject(err);
324
+ }
325
+ });
326
+
327
+ req.end();
328
+ });
329
+
330
+ if (resp.status === 200) {
331
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
332
+ const returnOutput: ContentBlock | null =
333
+ result == null ? null : (
334
+ {
335
+ type: 'text',
336
+ text: typeof result === 'string' ? result : JSON.stringify(result),
337
+ }
338
+ );
339
+ const logOutput: ContentBlock | null =
340
+ log_lines.length === 0 ?
341
+ null
342
+ : {
343
+ type: 'text',
344
+ text: log_lines.join('\n'),
345
+ };
346
+ const errOutput: ContentBlock | null =
347
+ err_lines.length === 0 ?
348
+ null
349
+ : {
350
+ type: 'text',
351
+ text: 'Error output:\n' + err_lines.join('\n'),
352
+ };
353
+ return {
354
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
355
+ };
356
+ } else {
357
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
358
+ const messageOutput: ContentBlock | null =
359
+ result == null ? null : (
360
+ {
361
+ type: 'text',
362
+ text: typeof result === 'string' ? result : JSON.stringify(result),
363
+ }
364
+ );
365
+ const logOutput: ContentBlock | null =
366
+ log_lines.length === 0 ?
367
+ null
368
+ : {
369
+ type: 'text',
370
+ text: log_lines.join('\n'),
371
+ };
372
+ const errOutput: ContentBlock | null =
373
+ err_lines.length === 0 ?
374
+ null
375
+ : {
376
+ type: 'text',
377
+ text: 'Error output:\n' + err_lines.join('\n'),
378
+ };
379
+ return {
380
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
381
+ isError: true,
382
+ };
383
+ }
384
+ } finally {
385
+ worker.terminate();
386
+ }
387
+ };
@@ -1,8 +1,8 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
3
- import { Metadata, asTextContentResult } from './types';
4
-
5
3
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
4
+ import { Metadata, McpRequestContext, asTextContentResult } from './types';
5
+ import { getLogger } from './logger';
6
6
 
7
7
  export const metadata: Metadata = {
8
8
  resource: 'all',
@@ -42,18 +42,58 @@ export const tool: Tool = {
42
42
  const docsSearchURL =
43
43
  process.env['DOCS_SEARCH_URL'] || 'https://api.stainless.com/api/projects/llamacloud-prod/docs/search';
44
44
 
45
- export const handler = async (_: unknown, args: Record<string, unknown> | undefined) => {
45
+ export const handler = async ({
46
+ reqContext,
47
+ args,
48
+ }: {
49
+ reqContext: McpRequestContext;
50
+ args: Record<string, unknown> | undefined;
51
+ }) => {
46
52
  const body = args as any;
47
53
  const query = new URLSearchParams(body).toString();
48
- const result = await fetch(`${docsSearchURL}?${query}`);
54
+
55
+ const startTime = Date.now();
56
+ const result = await fetch(`${docsSearchURL}?${query}`, {
57
+ headers: {
58
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
59
+ },
60
+ });
61
+
62
+ const logger = getLogger();
49
63
 
50
64
  if (!result.ok) {
65
+ const errorText = await result.text();
66
+ logger.warn(
67
+ {
68
+ durationMs: Date.now() - startTime,
69
+ query: body.query,
70
+ status: result.status,
71
+ statusText: result.statusText,
72
+ errorText,
73
+ },
74
+ 'Got error response from docs search tool',
75
+ );
76
+
77
+ if (result.status === 404 && !reqContext.stainlessApiKey) {
78
+ throw new Error(
79
+ 'Could not find docs 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.',
80
+ );
81
+ }
82
+
51
83
  throw new Error(
52
- `${result.status}: ${result.statusText} when using doc search tool. Details: ${await result.text()}`,
84
+ `${result.status}: ${result.statusText} when using doc search tool. Details: ${errorText}`,
53
85
  );
54
86
  }
55
87
 
56
- return asTextContentResult(await result.json());
88
+ const resultBody = await result.json();
89
+ logger.info(
90
+ {
91
+ durationMs: Date.now() - startTime,
92
+ query: body.query,
93
+ },
94
+ 'Got docs search result',
95
+ );
96
+ return asTextContentResult(resultBody);
57
97
  };
58
98
 
59
99
  export default { metadata, tool, handler };
package/src/http.ts CHANGED
@@ -2,12 +2,14 @@
2
2
 
3
3
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
4
4
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
5
+ import { ClientOptions } from '@llamaindex/llama-cloud';
5
6
  import express from 'express';
6
- import morgan from 'morgan';
7
- import morganBody from 'morgan-body';
7
+ import pino from 'pino';
8
+ import pinoHttp from 'pino-http';
9
+ import { getStainlessApiKey, parseClientAuthHeaders } from './auth';
10
+ import { getLogger } from './logger';
8
11
  import { McpOptions } from './options';
9
- import { ClientOptions, initMcpServer, newMcpServer } from './server';
10
- import { parseAuthHeaders } from './headers';
12
+ import { initMcpServer, newMcpServer } from './server';
11
13
 
12
14
  const newServer = async ({
13
15
  clientOptions,
@@ -20,28 +22,20 @@ const newServer = async ({
20
22
  req: express.Request;
21
23
  res: express.Response;
22
24
  }): Promise<McpServer | null> => {
23
- const server = await newMcpServer();
25
+ const stainlessApiKey = getStainlessApiKey(req, mcpOptions);
26
+ const server = await newMcpServer(stainlessApiKey);
24
27
 
25
- try {
26
- const authOptions = parseAuthHeaders(req, false);
27
- await initMcpServer({
28
- server: server,
29
- mcpOptions: mcpOptions,
30
- clientOptions: {
31
- ...clientOptions,
32
- ...authOptions,
33
- },
34
- });
35
- } catch (error) {
36
- res.status(401).json({
37
- jsonrpc: '2.0',
38
- error: {
39
- code: -32000,
40
- message: `Unauthorized: ${error instanceof Error ? error.message : error}`,
41
- },
42
- });
43
- return null;
44
- }
28
+ const authOptions = parseClientAuthHeaders(req, false);
29
+
30
+ await initMcpServer({
31
+ server: server,
32
+ mcpOptions: mcpOptions,
33
+ clientOptions: {
34
+ ...clientOptions,
35
+ ...authOptions,
36
+ },
37
+ stainlessApiKey: stainlessApiKey,
38
+ });
45
39
 
46
40
  return server;
47
41
  };
@@ -77,29 +71,60 @@ const del = async (req: express.Request, res: express.Response) => {
77
71
  });
78
72
  };
79
73
 
74
+ const redactHeaders = (headers: Record<string, any>) => {
75
+ const hiddenHeaders = /auth|cookie|key|token/i;
76
+ const filtered = { ...headers };
77
+ Object.keys(filtered).forEach((key) => {
78
+ if (hiddenHeaders.test(key)) {
79
+ filtered[key] = '[REDACTED]';
80
+ }
81
+ });
82
+ return filtered;
83
+ };
84
+
80
85
  export const streamableHTTPApp = ({
81
86
  clientOptions = {},
82
87
  mcpOptions,
83
- debug,
84
88
  }: {
85
89
  clientOptions?: ClientOptions;
86
90
  mcpOptions: McpOptions;
87
- debug: boolean;
88
91
  }): express.Express => {
89
92
  const app = express();
90
93
  app.set('query parser', 'extended');
91
94
  app.use(express.json());
92
-
93
- if (debug) {
94
- morganBody(app, {
95
- logAllReqHeader: true,
96
- logAllResHeader: true,
97
- logRequestBody: true,
98
- logResponseBody: true,
99
- });
100
- } else {
101
- app.use(morgan('combined'));
102
- }
95
+ app.use(
96
+ pinoHttp({
97
+ logger: getLogger(),
98
+ customLogLevel: (req, res) => {
99
+ if (res.statusCode >= 500) {
100
+ return 'error';
101
+ } else if (res.statusCode >= 400) {
102
+ return 'warn';
103
+ }
104
+ return 'info';
105
+ },
106
+ customSuccessMessage: function (req, res) {
107
+ return `Request ${req.method} to ${req.url} completed with status ${res.statusCode}`;
108
+ },
109
+ customErrorMessage: function (req, res, err) {
110
+ return `Request ${req.method} to ${req.url} errored with status ${res.statusCode}`;
111
+ },
112
+ serializers: {
113
+ req: pino.stdSerializers.wrapRequestSerializer((req) => {
114
+ return {
115
+ ...req,
116
+ headers: redactHeaders(req.raw.headers),
117
+ };
118
+ }),
119
+ res: pino.stdSerializers.wrapResponseSerializer((res) => {
120
+ return {
121
+ ...res,
122
+ headers: redactHeaders(res.headers),
123
+ };
124
+ }),
125
+ },
126
+ }),
127
+ );
103
128
 
104
129
  app.get('/health', async (req: express.Request, res: express.Response) => {
105
130
  res.status(200).send('OK');
@@ -111,20 +136,24 @@ export const streamableHTTPApp = ({
111
136
  return app;
112
137
  };
113
138
 
114
- export const launchStreamableHTTPServer = async (params: {
139
+ export const launchStreamableHTTPServer = async ({
140
+ mcpOptions,
141
+ port,
142
+ }: {
115
143
  mcpOptions: McpOptions;
116
- debug: boolean;
117
144
  port: number | string | undefined;
118
145
  }) => {
119
- const app = streamableHTTPApp({ mcpOptions: params.mcpOptions, debug: params.debug });
120
- const server = app.listen(params.port);
146
+ const app = streamableHTTPApp({ mcpOptions });
147
+ const server = app.listen(port);
121
148
  const address = server.address();
122
149
 
150
+ const logger = getLogger();
151
+
123
152
  if (typeof address === 'string') {
124
- console.error(`MCP Server running on streamable HTTP at ${address}`);
153
+ logger.info(`MCP Server running on streamable HTTP at ${address}`);
125
154
  } else if (address !== null) {
126
- console.error(`MCP Server running on streamable HTTP on port ${address.port}`);
155
+ logger.info(`MCP Server running on streamable HTTP on port ${address.port}`);
127
156
  } else {
128
- console.error(`MCP Server running on streamable HTTP on port ${params.port}`);
157
+ logger.info(`MCP Server running on streamable HTTP on port ${port}`);
129
158
  }
130
159
  };