@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.
Files changed (144) 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} +21 -2
  6. package/auth.js.map +1 -0
  7. package/{headers.js → auth.mjs} +16 -6
  8. package/auth.mjs.map +1 -0
  9. package/code-tool-paths.cjs +8 -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 +314 -0
  20. package/code-tool-worker.js.map +1 -0
  21. package/code-tool-worker.mjs +276 -0
  22. package/code-tool-worker.mjs.map +1 -0
  23. package/code-tool.d.mts +11 -2
  24. package/code-tool.d.mts.map +1 -1
  25. package/code-tool.d.ts +11 -2
  26. package/code-tool.d.ts.map +1 -1
  27. package/code-tool.js +285 -42
  28. package/code-tool.js.map +1 -1
  29. package/code-tool.mjs +253 -43
  30. package/code-tool.mjs.map +1 -1
  31. package/docs-search-tool.d.mts +11 -3
  32. package/docs-search-tool.d.mts.map +1 -1
  33. package/docs-search-tool.d.ts +11 -3
  34. package/docs-search-tool.d.ts.map +1 -1
  35. package/docs-search-tool.js +58 -5
  36. package/docs-search-tool.js.map +1 -1
  37. package/docs-search-tool.mjs +57 -5
  38. package/docs-search-tool.mjs.map +1 -1
  39. package/http.d.mts +6 -3
  40. package/http.d.mts.map +1 -1
  41. package/http.d.ts +6 -3
  42. package/http.d.ts.map +1 -1
  43. package/http.js +130 -28
  44. package/http.js.map +1 -1
  45. package/http.mjs +130 -28
  46. package/http.mjs.map +1 -1
  47. package/index.js +17 -12
  48. package/index.js.map +1 -1
  49. package/index.mjs +17 -12
  50. package/index.mjs.map +1 -1
  51. package/instructions.d.mts +5 -0
  52. package/instructions.d.mts.map +1 -0
  53. package/instructions.d.ts +5 -0
  54. package/instructions.d.ts.map +1 -0
  55. package/instructions.js +61 -0
  56. package/instructions.js.map +1 -0
  57. package/instructions.mjs +55 -0
  58. package/instructions.mjs.map +1 -0
  59. package/local-docs-search.d.mts +28 -0
  60. package/local-docs-search.d.mts.map +1 -0
  61. package/local-docs-search.d.ts +28 -0
  62. package/local-docs-search.d.ts.map +1 -0
  63. package/local-docs-search.js +2807 -0
  64. package/local-docs-search.js.map +1 -0
  65. package/local-docs-search.mjs +2767 -0
  66. package/local-docs-search.mjs.map +1 -0
  67. package/logger.d.mts +7 -0
  68. package/logger.d.mts.map +1 -0
  69. package/logger.d.ts +7 -0
  70. package/logger.d.ts.map +1 -0
  71. package/logger.js +29 -0
  72. package/logger.js.map +1 -0
  73. package/logger.mjs +22 -0
  74. package/logger.mjs.map +1 -0
  75. package/methods.d.mts +10 -0
  76. package/methods.d.mts.map +1 -0
  77. package/methods.d.ts +10 -0
  78. package/methods.d.ts.map +1 -0
  79. package/methods.js +349 -0
  80. package/methods.js.map +1 -0
  81. package/methods.mjs +345 -0
  82. package/methods.mjs.map +1 -0
  83. package/options.d.mts +12 -0
  84. package/options.d.mts.map +1 -1
  85. package/options.d.ts +12 -0
  86. package/options.d.ts.map +1 -1
  87. package/options.js +81 -12
  88. package/options.js.map +1 -1
  89. package/options.mjs +81 -12
  90. package/options.mjs.map +1 -1
  91. package/package.json +89 -15
  92. package/server.d.mts +18 -11
  93. package/server.d.mts.map +1 -1
  94. package/server.d.ts +18 -11
  95. package/server.d.ts.map +1 -1
  96. package/server.js +89 -49
  97. package/server.js.map +1 -1
  98. package/server.mjs +88 -45
  99. package/server.mjs.map +1 -1
  100. package/src/{headers.ts → auth.ts} +18 -1
  101. package/src/code-tool-paths.cts +5 -0
  102. package/src/code-tool-types.ts +1 -0
  103. package/src/code-tool-worker.ts +327 -0
  104. package/src/code-tool.ts +339 -55
  105. package/src/docs-search-tool.ts +86 -7
  106. package/src/http.ts +154 -33
  107. package/src/index.ts +19 -13
  108. package/src/instructions.ts +83 -0
  109. package/src/local-docs-search.ts +3380 -0
  110. package/src/logger.ts +28 -0
  111. package/src/methods.ts +370 -0
  112. package/src/options.ts +105 -12
  113. package/src/server.ts +111 -57
  114. package/src/stdio.ts +9 -4
  115. package/src/types.ts +15 -4
  116. package/src/util.ts +25 -0
  117. package/stdio.d.mts +2 -1
  118. package/stdio.d.mts.map +1 -1
  119. package/stdio.d.ts +2 -1
  120. package/stdio.d.ts.map +1 -1
  121. package/stdio.js +8 -4
  122. package/stdio.js.map +1 -1
  123. package/stdio.mjs +8 -4
  124. package/stdio.mjs.map +1 -1
  125. package/types.d.mts +14 -1
  126. package/types.d.mts.map +1 -1
  127. package/types.d.ts +14 -1
  128. package/types.d.ts.map +1 -1
  129. package/types.js.map +1 -1
  130. package/types.mjs.map +1 -1
  131. package/util.d.mts +4 -0
  132. package/util.d.mts.map +1 -0
  133. package/util.d.ts +4 -0
  134. package/util.d.ts.map +1 -0
  135. package/util.js +30 -0
  136. package/util.js.map +1 -0
  137. package/util.mjs +24 -0
  138. package/util.mjs.map +1 -0
  139. package/headers.d.mts +0 -4
  140. package/headers.d.mts.map +0 -1
  141. package/headers.d.ts +0 -4
  142. package/headers.d.ts.map +0 -1
  143. package/headers.js.map +0 -1
  144. 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 { McpTool, Metadata, ToolCallResult, asErrorResult, asTextContentResult } from './types';
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 './server';
13
+ import { readEnv, requireValue } from './util';
6
14
  import { WorkerInput, WorkerOutput } from './code-tool-types';
7
- import { ImageKit } from '@imagekit/nodejs';
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 endpoints - The endpoints to include in the list.
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(): McpTool {
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
- const handler = async (client: ImageKit, args: any): Promise<ToolCallResult> => {
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
- const intent = args.intent as string | undefined;
61
-
62
- // this is not required, but passing a Stainless API key for the matching project_name
63
- // will allow you to run code-mode queries against non-published versions of your SDK.
64
- const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
65
- const codeModeEndpoint =
66
- readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
67
-
68
- const res = await fetch(codeModeEndpoint, {
69
- method: 'POST',
70
- headers: {
71
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
72
- 'Content-Type': 'application/json',
73
- client_envs: JSON.stringify({
74
- IMAGEKIT_PRIVATE_KEY: requireValue(
75
- readEnv('IMAGEKIT_PRIVATE_KEY') ?? client.privateKey,
76
- 'set IMAGEKIT_PRIVATE_KEY environment variable or provide privateKey client option',
77
- ),
78
- OPTIONAL_IMAGEKIT_IGNORES_THIS:
79
- readEnv('OPTIONAL_IMAGEKIT_IGNORES_THIS') ?? client.password ?? undefined,
80
- IMAGEKIT_WEBHOOK_SECRET: readEnv('IMAGEKIT_WEBHOOK_SECRET') ?? client.webhookSecret ?? undefined,
81
- IMAGE_KIT_BASE_URL: readEnv('IMAGE_KIT_BASE_URL') ?? client.baseURL ?? undefined,
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
- body: JSON.stringify({
85
- project_name: 'imagekit',
86
- code,
87
- intent,
88
- client_opts: {},
89
- } satisfies WorkerInput),
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
- if (!res.ok) {
175
+ if (!res.ok) {
176
+ if (res.status === 404 && !reqContext.stainlessApiKey) {
93
177
  throw new Error(
94
- `${res.status}: ${
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
- const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
101
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
102
- const output = {
103
- result,
104
- ...(log_lines.length > 0 && { log_lines }),
105
- ...(err_lines.length > 0 && { err_lines }),
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
- return { metadata, tool, handler };
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
+ };
@@ -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: 'Search for documentation for how to use the client to interact with the API.',
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
- export const handler = async (_: unknown, args: Record<string, unknown> | undefined) => {
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
- const result = await fetch(`${docsSearchURL}?${query}`);
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: ${await result.text()}`,
107
+ `${result.status}: ${result.statusText} when using doc search tool. Details: ${errorText}`,
53
108
  );
54
109
  }
55
110
 
56
- return asTextContentResult(await result.json());
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 };