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