@stigg/typescript-mcp 0.1.0-alpha.10

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