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