cas-parser-node-mcp 1.7.1 → 1.7.2

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 (81) 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.d.mts +1 -1
  10. package/code-tool.d.mts.map +1 -1
  11. package/code-tool.d.ts +1 -1
  12. package/code-tool.d.ts.map +1 -1
  13. package/code-tool.js +7 -8
  14. package/code-tool.js.map +1 -1
  15. package/code-tool.mjs +8 -9
  16. package/code-tool.mjs.map +1 -1
  17. package/docs-search-tool.d.mts +9 -3
  18. package/docs-search-tool.d.mts.map +1 -1
  19. package/docs-search-tool.d.ts +9 -3
  20. package/docs-search-tool.d.ts.map +1 -1
  21. package/docs-search-tool.js +2 -4
  22. package/docs-search-tool.js.map +1 -1
  23. package/docs-search-tool.mjs +2 -4
  24. package/docs-search-tool.mjs.map +1 -1
  25. package/http.d.mts +1 -1
  26. package/http.d.mts.map +1 -1
  27. package/http.d.ts +1 -1
  28. package/http.d.ts.map +1 -1
  29. package/http.js +16 -26
  30. package/http.js.map +1 -1
  31. package/http.mjs +17 -27
  32. package/http.mjs.map +1 -1
  33. package/index.js +1 -1
  34. package/index.js.map +1 -1
  35. package/index.mjs +1 -1
  36. package/index.mjs.map +1 -1
  37. package/instructions.d.mts +2 -0
  38. package/instructions.d.mts.map +1 -0
  39. package/instructions.d.ts +2 -0
  40. package/instructions.d.ts.map +1 -0
  41. package/instructions.js +55 -0
  42. package/instructions.js.map +1 -0
  43. package/instructions.mjs +52 -0
  44. package/instructions.mjs.map +1 -0
  45. package/options.d.mts +1 -0
  46. package/options.d.mts.map +1 -1
  47. package/options.d.ts +1 -0
  48. package/options.d.ts.map +1 -1
  49. package/options.js +7 -0
  50. package/options.js.map +1 -1
  51. package/options.mjs +7 -0
  52. package/options.mjs.map +1 -1
  53. package/package.json +12 -2
  54. package/server.d.mts +8 -4
  55. package/server.d.mts.map +1 -1
  56. package/server.d.ts +8 -4
  57. package/server.d.ts.map +1 -1
  58. package/server.js +67 -46
  59. package/server.js.map +1 -1
  60. package/server.mjs +67 -46
  61. package/server.mjs.map +1 -1
  62. package/src/auth.ts +16 -1
  63. package/src/code-tool.ts +21 -12
  64. package/src/docs-search-tool.ts +9 -6
  65. package/src/http.ts +22 -26
  66. package/src/index.ts +1 -1
  67. package/src/instructions.ts +74 -0
  68. package/src/options.ts +9 -0
  69. package/src/server.ts +76 -61
  70. package/src/stdio.ts +2 -2
  71. package/src/types.ts +12 -4
  72. package/stdio.js +2 -2
  73. package/stdio.js.map +1 -1
  74. package/stdio.mjs +2 -2
  75. package/stdio.mjs.map +1 -1
  76. package/types.d.mts +8 -1
  77. package/types.d.mts.map +1 -1
  78. package/types.d.ts +8 -1
  79. package/types.d.ts.map +1 -1
  80. package/types.js.map +1 -1
  81. package/types.mjs.map +1 -1
package/server.mjs CHANGED
@@ -4,39 +4,14 @@ import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema, }
4
4
  import CasParser from 'cas-parser-node';
5
5
  import { codeTool } from "./code-tool.mjs";
6
6
  import docsSearchTool from "./docs-search-tool.mjs";
7
+ import { getInstructions } from "./instructions.mjs";
7
8
  import { blockedMethodsForCodeTool } from "./methods.mjs";
8
9
  import { readEnv } from "./util.mjs";
9
- async function getInstructions() {
10
- // This API key is optional; providing it allows the server to fetch instructions for unreleased versions.
11
- const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
12
- const response = await fetch(readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/cas-parser', {
13
- method: 'GET',
14
- headers: { ...(stainlessAPIKey && { Authorization: stainlessAPIKey }) },
15
- });
16
- let instructions;
17
- if (!response.ok) {
18
- console.warn('Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...');
19
- instructions = `
20
- This is the cas-parser MCP server. You will use Code Mode to help the user perform
21
- actions. You can use search_docs tool to learn about how to take action with this server. Then,
22
- you will write TypeScript code using the execute tool take action. It is CRITICAL that you be
23
- thoughtful and deliberate when executing code. Always try to entirely solve the problem in code
24
- block: it can be as long as you need to get the job done!
25
- `;
26
- }
27
- instructions ??= (await response.json()).instructions;
28
- instructions = `
29
- The current time in Unix timestamps is ${Date.now()}.
30
-
31
- ${instructions}
32
- `;
33
- return instructions;
34
- }
35
- export const newMcpServer = async () => new McpServer({
10
+ export const newMcpServer = async (stainlessApiKey) => new McpServer({
36
11
  name: 'cas_parser_node_api',
37
- version: '1.7.1',
12
+ version: '1.7.2',
38
13
  }, {
39
- instructions: await getInstructions(),
14
+ instructions: await getInstructions(stainlessApiKey),
40
15
  capabilities: { tools: {}, logging: {} },
41
16
  });
42
17
  /**
@@ -57,15 +32,34 @@ export async function initMcpServer(params) {
57
32
  warn: logAtLevel('warning'),
58
33
  error: logAtLevel('error'),
59
34
  };
60
- let client = new CasParser({
61
- ...{ environment: (readEnv('CAS_PARSER_ENVIRONMENT') || undefined) },
62
- logger,
63
- ...params.clientOptions,
64
- defaultHeaders: {
65
- ...params.clientOptions?.defaultHeaders,
66
- 'X-Stainless-MCP': 'true',
67
- },
68
- });
35
+ let _client;
36
+ let _clientError;
37
+ let _logLevel;
38
+ const getClient = () => {
39
+ if (_clientError)
40
+ throw _clientError;
41
+ if (!_client) {
42
+ try {
43
+ _client = new CasParser({
44
+ ...{ environment: (readEnv('CAS_PARSER_ENVIRONMENT') || undefined) },
45
+ logger,
46
+ ...params.clientOptions,
47
+ defaultHeaders: {
48
+ ...params.clientOptions?.defaultHeaders,
49
+ 'X-Stainless-MCP': 'true',
50
+ },
51
+ });
52
+ if (_logLevel) {
53
+ _client = _client.withOptions({ logLevel: _logLevel });
54
+ }
55
+ }
56
+ catch (e) {
57
+ _clientError = e instanceof Error ? e : new Error(String(e));
58
+ throw _clientError;
59
+ }
60
+ }
61
+ return _client;
62
+ };
69
63
  const providedTools = selectTools(params.mcpOptions);
70
64
  const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool]));
71
65
  server.setRequestHandler(ListToolsRequestSchema, async () => {
@@ -79,28 +73,55 @@ export async function initMcpServer(params) {
79
73
  if (!mcpTool) {
80
74
  throw new Error(`Unknown tool: ${name}`);
81
75
  }
82
- return executeHandler(mcpTool.handler, client, args);
76
+ let client;
77
+ try {
78
+ client = getClient();
79
+ }
80
+ catch (error) {
81
+ return {
82
+ content: [
83
+ {
84
+ type: 'text',
85
+ text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`,
86
+ },
87
+ ],
88
+ isError: true,
89
+ };
90
+ }
91
+ return executeHandler({
92
+ handler: mcpTool.handler,
93
+ reqContext: {
94
+ client,
95
+ stainlessApiKey: params.stainlessApiKey ?? params.mcpOptions?.stainlessApiKey,
96
+ },
97
+ args,
98
+ });
83
99
  });
84
100
  server.setRequestHandler(SetLevelRequestSchema, async (request) => {
85
101
  const { level } = request.params;
102
+ let logLevel;
86
103
  switch (level) {
87
104
  case 'debug':
88
- client = client.withOptions({ logLevel: 'debug' });
105
+ logLevel = 'debug';
89
106
  break;
90
107
  case 'info':
91
- client = client.withOptions({ logLevel: 'info' });
108
+ logLevel = 'info';
92
109
  break;
93
110
  case 'notice':
94
111
  case 'warning':
95
- client = client.withOptions({ logLevel: 'warn' });
112
+ logLevel = 'warn';
96
113
  break;
97
114
  case 'error':
98
- client = client.withOptions({ logLevel: 'error' });
115
+ logLevel = 'error';
99
116
  break;
100
117
  default:
101
- client = client.withOptions({ logLevel: 'off' });
118
+ logLevel = 'off';
102
119
  break;
103
120
  }
121
+ _logLevel = logLevel;
122
+ if (_client) {
123
+ _client = _client.withOptions({ logLevel });
124
+ }
104
125
  return {};
105
126
  });
106
127
  }
@@ -121,7 +142,7 @@ export function selectTools(options) {
121
142
  /**
122
143
  * Runs the provided handler with the given client and arguments.
123
144
  */
124
- export async function executeHandler(handler, client, args) {
125
- return await handler(client, args || {});
145
+ export async function executeHandler({ handler, reqContext, args, }) {
146
+ return await handler({ reqContext, args: args || {} });
126
147
  }
127
148
  //# sourceMappingURL=server.mjs.map
package/server.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","sourceRoot":"","sources":["src/server.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAG/E,EAAE,SAAS,EAAE,MAAM,yCAAyC;OAC5D,EACL,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,oCAAoC;OAEpC,SAAS,MAAM,iBAAiB;OAChC,EAAE,QAAQ,EAAE;OACZ,cAAc;OAEd,EAAE,yBAAyB,EAAE;OAE7B,EAAE,OAAO,EAAE;AAElB,KAAK,UAAU,eAAe;IAC5B,0GAA0G;IAC1G,MAAM,eAAe,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACrD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAC1B,OAAO,CAAC,4BAA4B,CAAC,IAAI,0DAA0D,EACnG;QACE,MAAM,EAAE,KAAK;QACb,OAAO,EAAE,EAAE,GAAG,CAAC,eAAe,IAAI,EAAE,aAAa,EAAE,eAAe,EAAE,CAAC,EAAE;KACxE,CACF,CAAC;IAEF,IAAI,YAAgC,CAAC;IACrC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,OAAO,CAAC,IAAI,CACV,8FAA8F,CAC/F,CAAC;QAEF,YAAY,GAAG;;;;;;KAMd,CAAC;IACJ,CAAC;IAED,YAAY,KAAM,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAA8B,CAAC,YAAY,CAAC;IACpF,YAAY,GAAG;6CAC4B,IAAI,CAAC,GAAG,EAAE;;MAEjD,YAAY;GACf,CAAC;IAEF,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,K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AAG,QAAQ,CAAC;QACrB,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO,GAAG,OAAO,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,WAAW,CAAC,OAAoB;IAC9C,MAAM,aAAa,GAAG;QACpB,QAAQ,CAAC;YACP,cAAc,EAAE,yBAAyB,CAAC,OAAO,CAAC;SACnD,CAAC;KACH,CAAC;IACF,IAAI,OAAO,EAAE,gBAAgB,IAAI,IAAI,EAAE,CAAC;QACtC,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,EACnC,OAAO,EACP,UAAU,EACV,IAAI,GAKL;IACC,OAAO,MAAM,OAAO,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,IAAI,IAAI,EAAE,EAAE,CAAC,CAAC;AACzD,CAAC"}
package/src/auth.ts CHANGED
@@ -2,9 +2,24 @@
2
2
 
3
3
  import { IncomingMessage } from 'node:http';
4
4
  import { ClientOptions } from 'cas-parser-node';
5
+ import { McpOptions } from './options';
5
6
 
6
- export const parseAuthHeaders = (req: IncomingMessage, required?: boolean): Partial<ClientOptions> => {
7
+ export const parseClientAuthHeaders = (req: IncomingMessage, required?: boolean): Partial<ClientOptions> => {
7
8
  const apiKey =
8
9
  Array.isArray(req.headers['x-api-key']) ? req.headers['x-api-key'][0] : req.headers['x-api-key'];
9
10
  return { apiKey };
10
11
  };
12
+
13
+ export const getStainlessApiKey = (req: IncomingMessage, mcpOptions: McpOptions): string | undefined => {
14
+ // Try to get the key from the x-stainless-api-key header
15
+ const headerKey =
16
+ Array.isArray(req.headers['x-stainless-api-key']) ?
17
+ req.headers['x-stainless-api-key'][0]
18
+ : req.headers['x-stainless-api-key'];
19
+ if (headerKey && typeof headerKey === 'string') {
20
+ return headerKey;
21
+ }
22
+
23
+ // Fall back to value set in the mcpOptions (e.g. from environment variable), if provided
24
+ return mcpOptions.stainlessApiKey;
25
+ };
package/src/code-tool.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
3
- import { McpTool, Metadata, ToolCallResult, asErrorResult, asTextContentResult } from './types';
3
+ import {
4
+ McpRequestContext,
5
+ McpTool,
6
+ Metadata,
7
+ ToolCallResult,
8
+ asErrorResult,
9
+ asTextContentResult,
10
+ } from './types';
4
11
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
5
12
  import { readEnv, requireValue } from './util';
6
13
  import { WorkerInput, WorkerOutput } from './code-tool-types';
7
14
  import { SdkMethod } from './methods';
8
- import { CasParser } from 'cas-parser-node';
9
15
 
10
16
  const prompt = `Runs JavaScript code to interact with the Cas Parser API.
11
17
 
@@ -36,7 +42,7 @@ Variables will not persist between calls, so make sure to return or log any data
36
42
  *
37
43
  * @param endpoints - The endpoints to include in the list.
38
44
  */
39
- export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): McpTool {
45
+ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | undefined }): McpTool {
40
46
  const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
41
47
  const tool: Tool = {
42
48
  name: 'execute',
@@ -56,19 +62,24 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M
56
62
  required: ['code'],
57
63
  },
58
64
  };
59
- const handler = async (client: CasParser, args: any): Promise<ToolCallResult> => {
65
+ const handler = async ({
66
+ reqContext,
67
+ args,
68
+ }: {
69
+ reqContext: McpRequestContext;
70
+ args: any;
71
+ }): Promise<ToolCallResult> => {
60
72
  const code = args.code as string;
61
73
  const intent = args.intent as string | undefined;
74
+ const client = reqContext.client;
62
75
 
63
76
  // Do very basic blocking of code that includes forbidden method names.
64
77
  //
65
78
  // WARNING: This is not secure against obfuscation and other evasion methods. If
66
79
  // stronger security blocks are required, then these should be enforced in the downstream
67
80
  // 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
- );
81
+ if (blockedMethods) {
82
+ const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
72
83
  if (blockedMatches.length > 0) {
73
84
  return asErrorResult(
74
85
  `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
@@ -78,16 +89,14 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M
78
89
  }
79
90
  }
80
91
 
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
92
  const codeModeEndpoint =
85
93
  readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
86
94
 
95
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
87
96
  const res = await fetch(codeModeEndpoint, {
88
97
  method: 'POST',
89
98
  headers: {
90
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
99
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
91
100
  'Content-Type': 'application/json',
92
101
  client_envs: JSON.stringify({
93
102
  CAS_PARSER_API_KEY: requireValue(
@@ -1,8 +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
- import { readEnv } from './util';
5
-
3
+ import { Metadata, McpRequestContext, asTextContentResult } from './types';
6
4
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
7
5
 
8
6
  export const metadata: Metadata = {
@@ -43,13 +41,18 @@ export const tool: Tool = {
43
41
  const docsSearchURL =
44
42
  process.env['DOCS_SEARCH_URL'] || 'https://api.stainless.com/api/projects/cas-parser/docs/search';
45
43
 
46
- 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
+ }) => {
47
51
  const body = args as any;
48
52
  const query = new URLSearchParams(body).toString();
49
- const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
50
53
  const result = await fetch(`${docsSearchURL}?${query}`, {
51
54
  headers: {
52
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
55
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
53
56
  },
54
57
  });
55
58
 
package/src/http.ts CHANGED
@@ -6,7 +6,7 @@ import { ClientOptions } from 'cas-parser-node';
6
6
  import express from 'express';
7
7
  import morgan from 'morgan';
8
8
  import morganBody from 'morgan-body';
9
- import { parseAuthHeaders } from './auth';
9
+ import { getStainlessApiKey, parseClientAuthHeaders } from './auth';
10
10
  import { McpOptions } from './options';
11
11
  import { initMcpServer, newMcpServer } from './server';
12
12
 
@@ -21,28 +21,20 @@ const newServer = async ({
21
21
  req: express.Request;
22
22
  res: express.Response;
23
23
  }): Promise<McpServer | null> => {
24
- const server = await newMcpServer();
24
+ const stainlessApiKey = getStainlessApiKey(req, mcpOptions);
25
+ const server = await newMcpServer(stainlessApiKey);
25
26
 
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
- }
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
+ });
46
38
 
47
39
  return server;
48
40
  };
@@ -112,13 +104,17 @@ export const streamableHTTPApp = ({
112
104
  return app;
113
105
  };
114
106
 
115
- export const launchStreamableHTTPServer = async (params: {
107
+ export const launchStreamableHTTPServer = async ({
108
+ mcpOptions,
109
+ debug,
110
+ port,
111
+ }: {
116
112
  mcpOptions: McpOptions;
117
113
  debug: boolean;
118
114
  port: number | string | undefined;
119
115
  }) => {
120
- const app = streamableHTTPApp({ mcpOptions: params.mcpOptions, debug: params.debug });
121
- const server = app.listen(params.port);
116
+ const app = streamableHTTPApp({ mcpOptions, debug });
117
+ const server = app.listen(port);
122
118
  const address = server.address();
123
119
 
124
120
  if (typeof address === 'string') {
@@ -126,6 +122,6 @@ export const launchStreamableHTTPServer = async (params: {
126
122
  } else if (address !== null) {
127
123
  console.error(`MCP Server running on streamable HTTP on port ${address.port}`);
128
124
  } else {
129
- console.error(`MCP Server running on streamable HTTP on port ${params.port}`);
125
+ console.error(`MCP Server running on streamable HTTP on port ${port}`);
130
126
  }
131
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/cas-parser',
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 cas-parser 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/options.ts CHANGED
@@ -4,6 +4,7 @@ import qs from 'qs';
4
4
  import yargs from 'yargs';
5
5
  import { hideBin } from 'yargs/helpers';
6
6
  import z from 'zod';
7
+ import { readEnv } from './util';
7
8
 
8
9
  export type CLIOptions = McpOptions & {
9
10
  debug: boolean;
@@ -14,6 +15,7 @@ export type CLIOptions = McpOptions & {
14
15
 
15
16
  export type McpOptions = {
16
17
  includeDocsTools?: boolean | undefined;
18
+ stainlessApiKey?: string | undefined;
17
19
  codeAllowHttpGets?: boolean | undefined;
18
20
  codeAllowedMethods?: string[] | undefined;
19
21
  codeBlockedMethods?: string[] | undefined;
@@ -51,6 +53,12 @@ export function parseCLIOptions(): CLIOptions {
51
53
  description: 'Port to serve on if using http transport',
52
54
  })
53
55
  .option('socket', { type: 'string', description: 'Unix socket to serve on if using http transport' })
56
+ .option('stainless-api-key', {
57
+ type: 'string',
58
+ default: readEnv('STAINLESS_API_KEY'),
59
+ description:
60
+ 'API key for Stainless. Used to authenticate requests to Stainless-hosted tools endpoints.',
61
+ })
54
62
  .option('tools', {
55
63
  type: 'string',
56
64
  array: true,
@@ -81,6 +89,7 @@ export function parseCLIOptions(): CLIOptions {
81
89
  return {
82
90
  ...(includeDocsTools !== undefined && { includeDocsTools }),
83
91
  debug: !!argv.debug,
92
+ stainlessApiKey: argv.stainlessApiKey,
84
93
  codeAllowHttpGets: argv.codeAllowHttpGets,
85
94
  codeAllowedMethods: argv.codeAllowedMethods,
86
95
  codeBlockedMethods: argv.codeBlockedMethods,