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