@revoxai/sdk-mcp 0.1.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/LICENSE +201 -0
  2. package/README.md +101 -0
  3. package/auth.d.mts +6 -0
  4. package/auth.d.mts.map +1 -0
  5. package/auth.d.ts +6 -0
  6. package/auth.d.ts.map +1 -0
  7. package/auth.js +37 -0
  8. package/auth.js.map +1 -0
  9. package/auth.mjs +32 -0
  10. package/auth.mjs.map +1 -0
  11. package/code-tool-paths.cjs +6 -0
  12. package/code-tool-paths.cjs.map +1 -0
  13. package/code-tool-paths.d.cts +2 -0
  14. package/code-tool-paths.d.cts.map +1 -0
  15. package/code-tool-types.d.mts +14 -0
  16. package/code-tool-types.d.mts.map +1 -0
  17. package/code-tool-types.d.ts +14 -0
  18. package/code-tool-types.d.ts.map +1 -0
  19. package/code-tool-types.js +4 -0
  20. package/code-tool-types.js.map +1 -0
  21. package/code-tool-types.mjs +3 -0
  22. package/code-tool-types.mjs.map +1 -0
  23. package/code-tool-worker.d.mts +5 -0
  24. package/code-tool-worker.d.mts.map +1 -0
  25. package/code-tool-worker.d.ts +5 -0
  26. package/code-tool-worker.d.ts.map +1 -0
  27. package/code-tool-worker.js +237 -0
  28. package/code-tool-worker.js.map +1 -0
  29. package/code-tool-worker.mjs +232 -0
  30. package/code-tool-worker.mjs.map +1 -0
  31. package/code-tool.d.mts +21 -0
  32. package/code-tool.d.mts.map +1 -0
  33. package/code-tool.d.ts +21 -0
  34. package/code-tool.d.ts.map +1 -0
  35. package/code-tool.js +331 -0
  36. package/code-tool.js.map +1 -0
  37. package/code-tool.mjs +292 -0
  38. package/code-tool.mjs.map +1 -0
  39. package/docs-search-tool.d.mts +57 -0
  40. package/docs-search-tool.d.mts.map +1 -0
  41. package/docs-search-tool.d.ts +57 -0
  42. package/docs-search-tool.d.ts.map +1 -0
  43. package/docs-search-tool.js +74 -0
  44. package/docs-search-tool.js.map +1 -0
  45. package/docs-search-tool.mjs +70 -0
  46. package/docs-search-tool.mjs.map +1 -0
  47. package/http.d.mts +12 -0
  48. package/http.d.mts.map +1 -0
  49. package/http.d.ts +12 -0
  50. package/http.d.ts.map +1 -0
  51. package/http.js +128 -0
  52. package/http.js.map +1 -0
  53. package/http.mjs +120 -0
  54. package/http.mjs.map +1 -0
  55. package/index.d.mts +3 -0
  56. package/index.d.mts.map +1 -0
  57. package/index.d.ts +3 -0
  58. package/index.d.ts.map +1 -0
  59. package/index.js +60 -0
  60. package/index.js.map +1 -0
  61. package/index.mjs +58 -0
  62. package/index.mjs.map +1 -0
  63. package/instructions.d.mts +2 -0
  64. package/instructions.d.mts.map +1 -0
  65. package/instructions.d.ts +2 -0
  66. package/instructions.d.ts.map +1 -0
  67. package/instructions.js +46 -0
  68. package/instructions.js.map +1 -0
  69. package/instructions.mjs +43 -0
  70. package/instructions.mjs.map +1 -0
  71. package/logger.d.mts +7 -0
  72. package/logger.d.mts.map +1 -0
  73. package/logger.d.ts +7 -0
  74. package/logger.d.ts.map +1 -0
  75. package/logger.js +29 -0
  76. package/logger.js.map +1 -0
  77. package/logger.mjs +22 -0
  78. package/logger.mjs.map +1 -0
  79. package/methods.d.mts +10 -0
  80. package/methods.d.mts.map +1 -0
  81. package/methods.d.ts +10 -0
  82. package/methods.d.ts.map +1 -0
  83. package/methods.js +143 -0
  84. package/methods.js.map +1 -0
  85. package/methods.mjs +139 -0
  86. package/methods.mjs.map +1 -0
  87. package/options.d.mts +20 -0
  88. package/options.d.mts.map +1 -0
  89. package/options.d.ts +20 -0
  90. package/options.d.ts.map +1 -0
  91. package/options.js +122 -0
  92. package/options.js.map +1 -0
  93. package/options.mjs +115 -0
  94. package/options.mjs.map +1 -0
  95. package/package.json +224 -0
  96. package/server.d.mts +29 -0
  97. package/server.d.mts.map +1 -0
  98. package/server.d.ts +29 -0
  99. package/server.d.ts.map +1 -0
  100. package/server.js +158 -0
  101. package/server.js.map +1 -0
  102. package/server.mjs +148 -0
  103. package/server.mjs.map +1 -0
  104. package/src/auth.ts +42 -0
  105. package/src/code-tool-paths.cts +3 -0
  106. package/src/code-tool-types.ts +17 -0
  107. package/src/code-tool-worker.ts +283 -0
  108. package/src/code-tool.ts +383 -0
  109. package/src/docs-search-tool.ts +100 -0
  110. package/src/http.ts +159 -0
  111. package/src/index.ts +67 -0
  112. package/src/instructions.ts +65 -0
  113. package/src/logger.ts +28 -0
  114. package/src/methods.ts +164 -0
  115. package/src/options.ts +161 -0
  116. package/src/server.ts +188 -0
  117. package/src/stdio.ts +14 -0
  118. package/src/tsconfig.json +11 -0
  119. package/src/types.ts +123 -0
  120. package/src/util.ts +25 -0
  121. package/stdio.d.mts +3 -0
  122. package/stdio.d.mts.map +1 -0
  123. package/stdio.d.ts +3 -0
  124. package/stdio.d.ts.map +1 -0
  125. package/stdio.js +15 -0
  126. package/stdio.js.map +1 -0
  127. package/stdio.mjs +11 -0
  128. package/stdio.mjs.map +1 -0
  129. package/types.d.mts +59 -0
  130. package/types.d.mts.map +1 -0
  131. package/types.d.ts +59 -0
  132. package/types.d.ts.map +1 -0
  133. package/types.js +58 -0
  134. package/types.js.map +1 -0
  135. package/types.mjs +53 -0
  136. package/types.mjs.map +1 -0
  137. package/util.d.mts +4 -0
  138. package/util.d.mts.map +1 -0
  139. package/util.d.ts +4 -0
  140. package/util.d.ts.map +1 -0
  141. package/util.js +30 -0
  142. package/util.js.map +1 -0
  143. package/util.mjs +24 -0
  144. package/util.mjs.map +1 -0
@@ -0,0 +1,383 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
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';
17
+ import { Tool } from '@modelcontextprotocol/sdk/types.js';
18
+ import { readEnv, requireValue } from './util';
19
+ import { WorkerInput, WorkerOutput } from './code-tool-types';
20
+ import { getLogger } from './logger';
21
+ import { SdkMethod } from './methods';
22
+ import { McpCodeExecutionMode } from './options';
23
+ import { ClientOptions } from '@revoxai/sdk';
24
+
25
+ const prompt = `Runs JavaScript code to interact with the Revox API.
26
+
27
+ You are a skilled TypeScript programmer writing code to interface with the service.
28
+ Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
29
+ For example:
30
+
31
+ \`\`\`
32
+ async function run(client) {
33
+ const assistant = await client.assistants.create({ name: 'REPLACE_ME', prompt: 'REPLACE_ME' });
34
+
35
+ console.log(assistant.assistant);
36
+ }
37
+ \`\`\`
38
+
39
+ You will be returned anything that your function returns, plus the results of any console.log statements.
40
+ Do not add try-catch blocks for single API calls. The tool will handle errors for you.
41
+ Do not add comments unless necessary for generating better code.
42
+ Code will run in a container, and cannot interact with the network outside of the given SDK client.
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 {}.`;
46
+
47
+ /**
48
+ * A tool that runs code against a copy of the SDK.
49
+ *
50
+ * Instead of exposing every endpoint as its own tool, which uses up too many tokens for LLMs to use at once,
51
+ * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
52
+ * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
53
+ *
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.
59
+ */
60
+ export function codeTool({
61
+ blockedMethods,
62
+ codeExecutionMode,
63
+ }: {
64
+ blockedMethods: SdkMethod[] | undefined;
65
+ codeExecutionMode: McpCodeExecutionMode;
66
+ }): McpTool {
67
+ const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
68
+ const tool: Tool = {
69
+ name: 'execute',
70
+ description: prompt,
71
+ inputSchema: {
72
+ type: 'object',
73
+ properties: {
74
+ code: {
75
+ type: 'string',
76
+ description: 'Code to execute.',
77
+ },
78
+ intent: {
79
+ type: 'string',
80
+ description: 'Task you are trying to perform. Used for improving the service.',
81
+ },
82
+ },
83
+ required: ['code'],
84
+ },
85
+ };
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;
97
+ // Do very basic blocking of code that includes forbidden method names.
98
+ //
99
+ // WARNING: This is not secure against obfuscation and other evasion methods. If
100
+ // stronger security blocks are required, then these should be enforced in the downstream
101
+ // API (e.g., by having users call the MCP server with API keys with limited permissions).
102
+ if (blockedMethods) {
103
+ const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
104
+ if (blockedMatches.length > 0) {
105
+ return asErrorResult(
106
+ `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
107
+ .map((m) => m.fullyQualifiedName)
108
+ .join(', ')}`,
109
+ );
110
+ }
111
+ }
112
+
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,
130
+ },
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';
151
+
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
+ REVOX_API_KEY: requireValue(
160
+ readEnv('REVOX_API_KEY') ?? client.apiKey,
161
+ 'set REVOX_API_KEY environment variable or provide apiKey client option',
162
+ ),
163
+ REVOX_BASE_URL: readEnv('REVOX_BASE_URL') ?? client.baseURL ?? undefined,
164
+ }),
165
+ },
166
+ body: JSON.stringify({
167
+ project_name: 'revox',
168
+ code,
169
+ intent,
170
+ client_opts: {},
171
+ } satisfies WorkerInput),
172
+ });
173
+
174
+ if (!res.ok) {
175
+ if (res.status === 404 && !reqContext.stainlessApiKey) {
176
+ throw new Error(
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.',
178
+ );
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
+ }
186
+
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 }),
193
+ };
194
+ if (is_error) {
195
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
196
+ }
197
+ return asTextContentResult(output);
198
+ };
199
+
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 = '@revoxai/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
+ };
@@ -0,0 +1,100 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import { Tool } from '@modelcontextprotocol/sdk/types.js';
4
+ import { Metadata, McpRequestContext, asTextContentResult } from './types';
5
+ import { getLogger } from './logger';
6
+
7
+ export const metadata: Metadata = {
8
+ resource: 'all',
9
+ operation: 'read',
10
+ tags: [],
11
+ httpMethod: 'get',
12
+ };
13
+
14
+ export const tool: Tool = {
15
+ name: 'search_docs',
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
+ inputSchema: {
19
+ type: 'object',
20
+ properties: {
21
+ query: {
22
+ type: 'string',
23
+ description: 'The query to search for.',
24
+ },
25
+ language: {
26
+ type: 'string',
27
+ description: 'The language for the SDK to search for.',
28
+ enum: ['http', 'python', 'go', 'typescript', 'javascript', 'terraform', 'ruby', 'java', 'kotlin'],
29
+ },
30
+ detail: {
31
+ type: 'string',
32
+ description: 'The amount of detail to return.',
33
+ enum: ['default', 'verbose'],
34
+ },
35
+ },
36
+ required: ['query', 'language'],
37
+ },
38
+ annotations: {
39
+ readOnlyHint: true,
40
+ },
41
+ };
42
+
43
+ const docsSearchURL =
44
+ process.env['DOCS_SEARCH_URL'] || 'https://api.stainless.com/api/projects/revox/docs/search';
45
+
46
+ export const handler = async ({
47
+ reqContext,
48
+ args,
49
+ }: {
50
+ reqContext: McpRequestContext;
51
+ args: Record<string, unknown> | undefined;
52
+ }) => {
53
+ const body = args as any;
54
+ const query = new URLSearchParams(body).toString();
55
+
56
+ const startTime = Date.now();
57
+ const result = await fetch(`${docsSearchURL}?${query}`, {
58
+ headers: {
59
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
60
+ },
61
+ });
62
+
63
+ const logger = getLogger();
64
+
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
+
84
+ throw new Error(
85
+ `${result.status}: ${result.statusText} when using doc search tool. Details: ${errorText}`,
86
+ );
87
+ }
88
+
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);
98
+ };
99
+
100
+ export default { metadata, tool, handler };
package/src/http.ts ADDED
@@ -0,0 +1,159 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
4
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
5
+ import { ClientOptions } from '@revoxai/sdk';
6
+ import express from 'express';
7
+ import pino from 'pino';
8
+ import pinoHttp from 'pino-http';
9
+ import { getStainlessApiKey, parseClientAuthHeaders } from './auth';
10
+ import { getLogger } from './logger';
11
+ import { McpOptions } from './options';
12
+ import { initMcpServer, newMcpServer } from './server';
13
+
14
+ const newServer = async ({
15
+ clientOptions,
16
+ mcpOptions,
17
+ req,
18
+ res,
19
+ }: {
20
+ clientOptions: ClientOptions;
21
+ mcpOptions: McpOptions;
22
+ req: express.Request;
23
+ res: express.Response;
24
+ }): Promise<McpServer | null> => {
25
+ const stainlessApiKey = getStainlessApiKey(req, mcpOptions);
26
+ const server = await newMcpServer(stainlessApiKey);
27
+
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
+ });
39
+
40
+ return server;
41
+ };
42
+
43
+ const post =
44
+ (options: { clientOptions: ClientOptions; mcpOptions: McpOptions }) =>
45
+ async (req: express.Request, res: express.Response) => {
46
+ const server = await newServer({ ...options, req, res });
47
+ // If we return null, we already set the authorization error.
48
+ if (server === null) return;
49
+ const transport = new StreamableHTTPServerTransport();
50
+ await server.connect(transport as any);
51
+ await transport.handleRequest(req, res, req.body);
52
+ };
53
+
54
+ const get = async (req: express.Request, res: express.Response) => {
55
+ res.status(405).json({
56
+ jsonrpc: '2.0',
57
+ error: {
58
+ code: -32000,
59
+ message: 'Method not supported',
60
+ },
61
+ });
62
+ };
63
+
64
+ const del = async (req: express.Request, res: express.Response) => {
65
+ res.status(405).json({
66
+ jsonrpc: '2.0',
67
+ error: {
68
+ code: -32000,
69
+ message: 'Method not supported',
70
+ },
71
+ });
72
+ };
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
+
85
+ export const streamableHTTPApp = ({
86
+ clientOptions = {},
87
+ mcpOptions,
88
+ }: {
89
+ clientOptions?: ClientOptions;
90
+ mcpOptions: McpOptions;
91
+ }): express.Express => {
92
+ const app = express();
93
+ app.set('query parser', 'extended');
94
+ app.use(express.json());
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
+ );
128
+
129
+ app.get('/health', async (req: express.Request, res: express.Response) => {
130
+ res.status(200).send('OK');
131
+ });
132
+ app.get('/', get);
133
+ app.post('/', post({ clientOptions, mcpOptions }));
134
+ app.delete('/', del);
135
+
136
+ return app;
137
+ };
138
+
139
+ export const launchStreamableHTTPServer = async ({
140
+ mcpOptions,
141
+ port,
142
+ }: {
143
+ mcpOptions: McpOptions;
144
+ port: number | string | undefined;
145
+ }) => {
146
+ const app = streamableHTTPApp({ mcpOptions });
147
+ const server = app.listen(port);
148
+ const address = server.address();
149
+
150
+ const logger = getLogger();
151
+
152
+ if (typeof address === 'string') {
153
+ logger.info(`MCP Server running on streamable HTTP at ${address}`);
154
+ } else if (address !== null) {
155
+ logger.info(`MCP Server running on streamable HTTP on port ${address.port}`);
156
+ } else {
157
+ logger.info(`MCP Server running on streamable HTTP on port ${port}`);
158
+ }
159
+ };
package/src/index.ts ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { selectTools } from './server';
4
+ import { McpOptions, parseCLIOptions } from './options';
5
+ import { launchStdioServer } from './stdio';
6
+ import { launchStreamableHTTPServer } from './http';
7
+ import type { McpTool } from './types';
8
+ import { configureLogger, getLogger } from './logger';
9
+
10
+ async function main() {
11
+ const options = parseOptionsOrError();
12
+ configureLogger({
13
+ level: options.debug ? 'debug' : 'info',
14
+ pretty: options.logFormat === 'pretty',
15
+ });
16
+
17
+ const selectedTools = await selectToolsOrError(options);
18
+
19
+ getLogger().info(
20
+ { tools: selectedTools.map((e) => e.tool.name) },
21
+ `MCP Server starting with ${selectedTools.length} tools`,
22
+ );
23
+
24
+ switch (options.transport) {
25
+ case 'stdio':
26
+ await launchStdioServer(options);
27
+ break;
28
+ case 'http':
29
+ await launchStreamableHTTPServer({
30
+ mcpOptions: options,
31
+ port: options.socket ?? options.port,
32
+ });
33
+ break;
34
+ }
35
+ }
36
+
37
+ if (require.main === module) {
38
+ main().catch((error) => {
39
+ // Logger might not be initialized yet
40
+ console.error('Fatal error in main()', error);
41
+ process.exit(1);
42
+ });
43
+ }
44
+
45
+ function parseOptionsOrError() {
46
+ try {
47
+ return parseCLIOptions();
48
+ } catch (error) {
49
+ // Logger is initialized after options, so use console.error here
50
+ console.error('Error parsing options', error);
51
+ process.exit(1);
52
+ }
53
+ }
54
+
55
+ async function selectToolsOrError(options: McpOptions): Promise<McpTool[]> {
56
+ try {
57
+ const includedTools = selectTools(options);
58
+ if (includedTools.length === 0) {
59
+ getLogger().error('No tools match the provided filters');
60
+ process.exit(1);
61
+ }
62
+ return includedTools;
63
+ } catch (error) {
64
+ getLogger().error({ error }, 'Error filtering tools');
65
+ process.exit(1);
66
+ }
67
+ }