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