@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.
- package/code-tool-paths.cjs +6 -0
- package/code-tool-paths.cjs.map +1 -0
- package/code-tool-paths.d.cts +2 -0
- package/code-tool-paths.d.cts.map +1 -0
- package/code-tool-types.d.mts.map +1 -1
- package/code-tool-types.d.ts.map +1 -1
- package/code-tool-worker.d.mts +5 -0
- package/code-tool-worker.d.mts.map +1 -0
- package/code-tool-worker.d.ts +5 -0
- package/code-tool-worker.d.ts.map +1 -0
- package/code-tool-worker.js +345 -0
- package/code-tool-worker.js.map +1 -0
- package/code-tool-worker.mjs +340 -0
- package/code-tool-worker.mjs.map +1 -0
- package/code-tool.d.mts +8 -2
- package/code-tool.d.mts.map +1 -1
- package/code-tool.d.ts +8 -2
- package/code-tool.d.ts.map +1 -1
- package/code-tool.js +260 -37
- package/code-tool.js.map +1 -1
- package/code-tool.mjs +224 -37
- package/code-tool.mjs.map +1 -1
- package/docs-search-tool.d.mts +1 -1
- package/docs-search-tool.d.mts.map +1 -1
- package/docs-search-tool.d.ts +1 -1
- package/docs-search-tool.d.ts.map +1 -1
- package/docs-search-tool.js +21 -2
- package/docs-search-tool.js.map +1 -1
- package/docs-search-tool.mjs +21 -2
- package/docs-search-tool.mjs.map +1 -1
- package/http.d.mts +2 -4
- package/http.d.mts.map +1 -1
- package/http.d.ts +2 -4
- package/http.d.ts.map +1 -1
- package/http.js +62 -41
- package/http.js.map +1 -1
- package/http.mjs +62 -41
- package/http.mjs.map +1 -1
- package/index.js +13 -12
- package/index.js.map +1 -1
- package/index.mjs +13 -12
- package/index.mjs.map +1 -1
- package/instructions.d.mts +2 -0
- package/instructions.d.mts.map +1 -0
- package/instructions.d.ts +2 -0
- package/instructions.d.ts.map +1 -0
- package/instructions.js +56 -0
- package/instructions.js.map +1 -0
- package/instructions.mjs +53 -0
- package/instructions.mjs.map +1 -0
- package/logger.d.mts +7 -0
- package/logger.d.mts.map +1 -0
- package/logger.d.ts +7 -0
- package/logger.d.ts.map +1 -0
- package/logger.js +29 -0
- package/logger.js.map +1 -0
- package/logger.mjs +22 -0
- package/logger.mjs.map +1 -0
- package/options.d.mts +4 -0
- package/options.d.mts.map +1 -1
- package/options.d.ts +4 -0
- package/options.d.ts.map +1 -1
- package/options.js +23 -0
- package/options.js.map +1 -1
- package/options.mjs +23 -0
- package/options.mjs.map +1 -1
- package/package.json +42 -5
- package/server.d.mts.map +1 -1
- package/server.d.ts.map +1 -1
- package/server.js +61 -46
- package/server.js.map +1 -1
- package/server.mjs +60 -45
- package/server.mjs.map +1 -1
- package/src/code-tool-paths.cts +3 -0
- package/src/code-tool-types.ts +1 -0
- package/src/code-tool-worker.ts +391 -0
- package/src/code-tool.ts +291 -47
- package/src/docs-search-tool.ts +34 -3
- package/src/http.ts +63 -42
- package/src/index.ts +15 -13
- package/src/instructions.ts +75 -0
- package/src/logger.ts +28 -0
- package/src/options.ts +32 -0
- package/src/server.ts +63 -56
- package/src/stdio.ts +2 -1
- package/stdio.d.mts.map +1 -1
- package/stdio.d.ts.map +1 -1
- package/stdio.js +2 -1
- package/stdio.js.map +1 -1
- package/stdio.mjs +2 -1
- package/stdio.mjs.map +1 -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,
|
|
@@ -11,11 +17,14 @@ import {
|
|
|
11
17
|
import { Tool } from '@modelcontextprotocol/sdk/types.js';
|
|
12
18
|
import { readEnv, requireValue } from './util';
|
|
13
19
|
import { WorkerInput, WorkerOutput } from './code-tool-types';
|
|
20
|
+
import { getLogger } from './logger';
|
|
14
21
|
import { SdkMethod } from './methods';
|
|
22
|
+
import { McpCodeExecutionMode } from './options';
|
|
23
|
+
import { ClientOptions } from '@llamaindex/llama-cloud';
|
|
15
24
|
|
|
16
25
|
const prompt = `Runs JavaScript code to interact with the Llama Cloud API.
|
|
17
26
|
|
|
18
|
-
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.
|
|
19
28
|
Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
|
|
20
29
|
For example:
|
|
21
30
|
|
|
@@ -35,7 +44,9 @@ You will be returned anything that your function returns, plus the results of an
|
|
|
35
44
|
Do not add try-catch blocks for single API calls. The tool will handle errors for you.
|
|
36
45
|
Do not add comments unless necessary for generating better code.
|
|
37
46
|
Code will run in a container, and cannot interact with the network outside of the given SDK client.
|
|
38
|
-
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 {}.`;
|
|
39
50
|
|
|
40
51
|
/**
|
|
41
52
|
* A tool that runs code against a copy of the SDK.
|
|
@@ -44,9 +55,19 @@ Variables will not persist between calls, so make sure to return or log any data
|
|
|
44
55
|
* we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
|
|
45
56
|
* a generic endpoint that can be used to invoke any endpoint with the provided arguments.
|
|
46
57
|
*
|
|
47
|
-
* @param
|
|
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.
|
|
48
63
|
*/
|
|
49
|
-
export function codeTool({
|
|
64
|
+
export function codeTool({
|
|
65
|
+
blockedMethods,
|
|
66
|
+
codeExecutionMode,
|
|
67
|
+
}: {
|
|
68
|
+
blockedMethods: SdkMethod[] | undefined;
|
|
69
|
+
codeExecutionMode: McpCodeExecutionMode;
|
|
70
|
+
}): McpTool {
|
|
50
71
|
const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
|
|
51
72
|
const tool: Tool = {
|
|
52
73
|
name: 'execute',
|
|
@@ -66,6 +87,9 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
|
|
|
66
87
|
required: ['code'],
|
|
67
88
|
},
|
|
68
89
|
};
|
|
90
|
+
|
|
91
|
+
const logger = getLogger();
|
|
92
|
+
|
|
69
93
|
const handler = async ({
|
|
70
94
|
reqContext,
|
|
71
95
|
args,
|
|
@@ -74,9 +98,6 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
|
|
|
74
98
|
args: any;
|
|
75
99
|
}): Promise<ToolCallResult> => {
|
|
76
100
|
const code = args.code as string;
|
|
77
|
-
const intent = args.intent as string | undefined;
|
|
78
|
-
const client = reqContext.client;
|
|
79
|
-
|
|
80
101
|
// Do very basic blocking of code that includes forbidden method names.
|
|
81
102
|
//
|
|
82
103
|
// WARNING: This is not secure against obfuscation and other evasion methods. If
|
|
@@ -93,51 +114,274 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
|
|
|
93
114
|
}
|
|
94
115
|
}
|
|
95
116
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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,
|
|
112
134
|
},
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
135
|
+
'Got code tool execution result',
|
|
136
|
+
);
|
|
137
|
+
return result;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
return { metadata, tool, handler };
|
|
141
|
+
}
|
|
120
142
|
|
|
121
|
-
|
|
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) {
|
|
122
180
|
throw new Error(
|
|
123
|
-
|
|
124
|
-
res.statusText
|
|
125
|
-
} 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.',
|
|
126
182
|
);
|
|
127
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
|
+
}
|
|
128
190
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
};
|
|
136
|
-
if (is_error) {
|
|
137
|
-
return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
|
|
138
|
-
}
|
|
139
|
-
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 }),
|
|
140
197
|
};
|
|
198
|
+
if (is_error) {
|
|
199
|
+
return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
|
|
200
|
+
}
|
|
201
|
+
return asTextContentResult(output);
|
|
202
|
+
};
|
|
141
203
|
|
|
142
|
-
|
|
143
|
-
|
|
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
|
+
};
|
package/src/docs-search-tool.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
2
|
|
|
3
|
-
import { Metadata, McpRequestContext, asTextContentResult } from './types';
|
|
4
3
|
import { Tool } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
import { Metadata, McpRequestContext, asTextContentResult } from './types';
|
|
5
|
+
import { getLogger } from './logger';
|
|
5
6
|
|
|
6
7
|
export const metadata: Metadata = {
|
|
7
8
|
resource: 'all',
|
|
@@ -50,19 +51,49 @@ export const handler = async ({
|
|
|
50
51
|
}) => {
|
|
51
52
|
const body = args as any;
|
|
52
53
|
const query = new URLSearchParams(body).toString();
|
|
54
|
+
|
|
55
|
+
const startTime = Date.now();
|
|
53
56
|
const result = await fetch(`${docsSearchURL}?${query}`, {
|
|
54
57
|
headers: {
|
|
55
58
|
...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
|
|
56
59
|
},
|
|
57
60
|
});
|
|
58
61
|
|
|
62
|
+
const logger = getLogger();
|
|
63
|
+
|
|
59
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
|
+
|
|
60
83
|
throw new Error(
|
|
61
|
-
`${result.status}: ${result.statusText} when using doc search tool. Details: ${
|
|
84
|
+
`${result.status}: ${result.statusText} when using doc search tool. Details: ${errorText}`,
|
|
62
85
|
);
|
|
63
86
|
}
|
|
64
87
|
|
|
65
|
-
|
|
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);
|
|
66
97
|
};
|
|
67
98
|
|
|
68
99
|
export default { metadata, tool, handler };
|
package/src/http.ts
CHANGED
|
@@ -4,9 +4,10 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
|
|
4
4
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
5
5
|
import { ClientOptions } from '@llamaindex/llama-cloud';
|
|
6
6
|
import express from 'express';
|
|
7
|
-
import
|
|
8
|
-
import
|
|
7
|
+
import pino from 'pino';
|
|
8
|
+
import pinoHttp from 'pino-http';
|
|
9
9
|
import { getStainlessApiKey, parseClientAuthHeaders } from './auth';
|
|
10
|
+
import { getLogger } from './logger';
|
|
10
11
|
import { McpOptions } from './options';
|
|
11
12
|
import { initMcpServer, newMcpServer } from './server';
|
|
12
13
|
|
|
@@ -24,28 +25,17 @@ const newServer = async ({
|
|
|
24
25
|
const stainlessApiKey = getStainlessApiKey(req, mcpOptions);
|
|
25
26
|
const server = await newMcpServer(stainlessApiKey);
|
|
26
27
|
|
|
27
|
-
|
|
28
|
-
const authOptions = parseClientAuthHeaders(req, false);
|
|
28
|
+
const authOptions = parseClientAuthHeaders(req, false);
|
|
29
29
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
} catch (error) {
|
|
40
|
-
res.status(401).json({
|
|
41
|
-
jsonrpc: '2.0',
|
|
42
|
-
error: {
|
|
43
|
-
code: -32000,
|
|
44
|
-
message: `Unauthorized: ${error instanceof Error ? error.message : error}`,
|
|
45
|
-
},
|
|
46
|
-
});
|
|
47
|
-
return null;
|
|
48
|
-
}
|
|
30
|
+
await initMcpServer({
|
|
31
|
+
server: server,
|
|
32
|
+
mcpOptions: mcpOptions,
|
|
33
|
+
clientOptions: {
|
|
34
|
+
...clientOptions,
|
|
35
|
+
...authOptions,
|
|
36
|
+
},
|
|
37
|
+
stainlessApiKey: stainlessApiKey,
|
|
38
|
+
});
|
|
49
39
|
|
|
50
40
|
return server;
|
|
51
41
|
};
|
|
@@ -81,29 +71,60 @@ const del = async (req: express.Request, res: express.Response) => {
|
|
|
81
71
|
});
|
|
82
72
|
};
|
|
83
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
|
+
|
|
84
85
|
export const streamableHTTPApp = ({
|
|
85
86
|
clientOptions = {},
|
|
86
87
|
mcpOptions,
|
|
87
|
-
debug,
|
|
88
88
|
}: {
|
|
89
89
|
clientOptions?: ClientOptions;
|
|
90
90
|
mcpOptions: McpOptions;
|
|
91
|
-
debug: boolean;
|
|
92
91
|
}): express.Express => {
|
|
93
92
|
const app = express();
|
|
94
93
|
app.set('query parser', 'extended');
|
|
95
94
|
app.use(express.json());
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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
|
+
);
|
|
107
128
|
|
|
108
129
|
app.get('/health', async (req: express.Request, res: express.Response) => {
|
|
109
130
|
res.status(200).send('OK');
|
|
@@ -117,22 +138,22 @@ export const streamableHTTPApp = ({
|
|
|
117
138
|
|
|
118
139
|
export const launchStreamableHTTPServer = async ({
|
|
119
140
|
mcpOptions,
|
|
120
|
-
debug,
|
|
121
141
|
port,
|
|
122
142
|
}: {
|
|
123
143
|
mcpOptions: McpOptions;
|
|
124
|
-
debug: boolean;
|
|
125
144
|
port: number | string | undefined;
|
|
126
145
|
}) => {
|
|
127
|
-
const app = streamableHTTPApp({ mcpOptions
|
|
146
|
+
const app = streamableHTTPApp({ mcpOptions });
|
|
128
147
|
const server = app.listen(port);
|
|
129
148
|
const address = server.address();
|
|
130
149
|
|
|
150
|
+
const logger = getLogger();
|
|
151
|
+
|
|
131
152
|
if (typeof address === 'string') {
|
|
132
|
-
|
|
153
|
+
logger.info(`MCP Server running on streamable HTTP at ${address}`);
|
|
133
154
|
} else if (address !== null) {
|
|
134
|
-
|
|
155
|
+
logger.info(`MCP Server running on streamable HTTP on port ${address.port}`);
|
|
135
156
|
} else {
|
|
136
|
-
|
|
157
|
+
logger.info(`MCP Server running on streamable HTTP on port ${port}`);
|
|
137
158
|
}
|
|
138
159
|
};
|
package/src/index.ts
CHANGED
|
@@ -5,15 +5,20 @@ import { McpOptions, parseCLIOptions } from './options';
|
|
|
5
5
|
import { launchStdioServer } from './stdio';
|
|
6
6
|
import { launchStreamableHTTPServer } from './http';
|
|
7
7
|
import type { McpTool } from './types';
|
|
8
|
+
import { configureLogger, getLogger } from './logger';
|
|
8
9
|
|
|
9
10
|
async function main() {
|
|
10
11
|
const options = parseOptionsOrError();
|
|
12
|
+
configureLogger({
|
|
13
|
+
level: options.debug ? 'debug' : 'info',
|
|
14
|
+
pretty: options.logFormat === 'pretty',
|
|
15
|
+
});
|
|
11
16
|
|
|
12
17
|
const selectedTools = await selectToolsOrError(options);
|
|
13
18
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
selectedTools.
|
|
19
|
+
getLogger().info(
|
|
20
|
+
{ tools: selectedTools.map((e) => e.tool.name) },
|
|
21
|
+
`MCP Server starting with ${selectedTools.length} tools`,
|
|
17
22
|
);
|
|
18
23
|
|
|
19
24
|
switch (options.transport) {
|
|
@@ -23,8 +28,7 @@ async function main() {
|
|
|
23
28
|
case 'http':
|
|
24
29
|
await launchStreamableHTTPServer({
|
|
25
30
|
mcpOptions: options,
|
|
26
|
-
|
|
27
|
-
port: options.port ?? options.socket,
|
|
31
|
+
port: options.socket ?? options.port,
|
|
28
32
|
});
|
|
29
33
|
break;
|
|
30
34
|
}
|
|
@@ -32,7 +36,8 @@ async function main() {
|
|
|
32
36
|
|
|
33
37
|
if (require.main === module) {
|
|
34
38
|
main().catch((error) => {
|
|
35
|
-
|
|
39
|
+
// Logger might not be initialized yet
|
|
40
|
+
console.error('Fatal error in main()', error);
|
|
36
41
|
process.exit(1);
|
|
37
42
|
});
|
|
38
43
|
}
|
|
@@ -41,7 +46,8 @@ function parseOptionsOrError() {
|
|
|
41
46
|
try {
|
|
42
47
|
return parseCLIOptions();
|
|
43
48
|
} catch (error) {
|
|
44
|
-
|
|
49
|
+
// Logger is initialized after options, so use console.error here
|
|
50
|
+
console.error('Error parsing options', error);
|
|
45
51
|
process.exit(1);
|
|
46
52
|
}
|
|
47
53
|
}
|
|
@@ -50,16 +56,12 @@ async function selectToolsOrError(options: McpOptions): Promise<McpTool[]> {
|
|
|
50
56
|
try {
|
|
51
57
|
const includedTools = selectTools(options);
|
|
52
58
|
if (includedTools.length === 0) {
|
|
53
|
-
|
|
59
|
+
getLogger().error('No tools match the provided filters');
|
|
54
60
|
process.exit(1);
|
|
55
61
|
}
|
|
56
62
|
return includedTools;
|
|
57
63
|
} catch (error) {
|
|
58
|
-
|
|
59
|
-
console.error('Error filtering tools:', error.message);
|
|
60
|
-
} else {
|
|
61
|
-
console.error('Error filtering tools:', error);
|
|
62
|
-
}
|
|
64
|
+
getLogger().error({ error }, 'Error filtering tools');
|
|
63
65
|
process.exit(1);
|
|
64
66
|
}
|
|
65
67
|
}
|