cas-parser-node-mcp 1.4.1 → 1.7.1

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 (215) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -147
  3. package/auth.d.mts +4 -0
  4. package/auth.d.mts.map +1 -0
  5. package/auth.d.ts +4 -0
  6. package/auth.d.ts.map +1 -0
  7. package/{headers.js → auth.js} +2 -2
  8. package/auth.js.map +1 -0
  9. package/{headers.mjs → auth.mjs} +2 -2
  10. package/auth.mjs.map +1 -0
  11. package/code-tool-types.d.mts +7 -7
  12. package/code-tool-types.d.mts.map +1 -1
  13. package/code-tool-types.d.ts +7 -7
  14. package/code-tool-types.d.ts.map +1 -1
  15. package/code-tool.d.mts +6 -3
  16. package/code-tool.d.mts.map +1 -1
  17. package/code-tool.d.ts +6 -3
  18. package/code-tool.d.ts.map +1 -1
  19. package/code-tool.js +86 -132
  20. package/code-tool.js.map +1 -1
  21. package/code-tool.mjs +86 -99
  22. package/code-tool.mjs.map +1 -1
  23. package/{tools/cas-generator/generate-cas-cas-generator.d.ts → docs-search-tool.d.mts} +17 -11
  24. package/docs-search-tool.d.mts.map +1 -0
  25. package/{tools/cas-generator/generate-cas-cas-generator.d.mts → docs-search-tool.d.ts} +17 -11
  26. package/docs-search-tool.d.ts.map +1 -0
  27. package/docs-search-tool.js +57 -0
  28. package/docs-search-tool.js.map +1 -0
  29. package/docs-search-tool.mjs +53 -0
  30. package/docs-search-tool.mjs.map +1 -0
  31. package/http.d.mts +9 -4
  32. package/http.d.mts.map +1 -1
  33. package/http.d.ts +9 -4
  34. package/http.d.ts.map +1 -1
  35. package/http.js +31 -34
  36. package/http.js.map +1 -1
  37. package/http.mjs +31 -34
  38. package/http.mjs.map +1 -1
  39. package/index.js +8 -40
  40. package/index.js.map +1 -1
  41. package/index.mjs +8 -40
  42. package/index.mjs.map +1 -1
  43. package/methods.d.mts +10 -0
  44. package/methods.d.mts.map +1 -0
  45. package/methods.d.ts +10 -0
  46. package/methods.d.ts.map +1 -0
  47. package/methods.js +167 -0
  48. package/methods.js.map +1 -0
  49. package/methods.mjs +163 -0
  50. package/methods.mjs.map +1 -0
  51. package/options.d.mts +5 -9
  52. package/options.d.mts.map +1 -1
  53. package/options.d.ts +5 -9
  54. package/options.d.ts.map +1 -1
  55. package/options.js +37 -362
  56. package/options.js.map +1 -1
  57. package/options.mjs +37 -362
  58. package/options.mjs.map +1 -1
  59. package/package.json +57 -79
  60. package/server.d.mts +5 -15
  61. package/server.d.mts.map +1 -1
  62. package/server.d.ts +5 -15
  63. package/server.d.ts.map +1 -1
  64. package/server.js +54 -87
  65. package/server.js.map +1 -1
  66. package/server.mjs +53 -82
  67. package/server.mjs.map +1 -1
  68. package/src/{headers.ts → auth.ts} +1 -1
  69. package/src/code-tool-types.ts +7 -5
  70. package/src/code-tool.ts +104 -117
  71. package/src/docs-search-tool.ts +65 -0
  72. package/src/http.ts +44 -40
  73. package/src/index.ts +9 -52
  74. package/src/methods.ts +188 -0
  75. package/src/options.ts +48 -384
  76. package/src/server.ts +63 -97
  77. package/src/stdio.ts +4 -4
  78. package/src/{tools/types.ts → types.ts} +13 -1
  79. package/src/util.ts +25 -0
  80. package/stdio.d.mts +1 -1
  81. package/stdio.d.mts.map +1 -1
  82. package/stdio.d.ts +1 -1
  83. package/stdio.d.ts.map +1 -1
  84. package/stdio.js +3 -3
  85. package/stdio.js.map +1 -1
  86. package/stdio.mjs +3 -3
  87. package/stdio.mjs.map +1 -1
  88. package/{tools/types.d.mts → types.d.mts} +2 -1
  89. package/types.d.mts.map +1 -0
  90. package/{tools/types.d.ts → types.d.ts} +2 -1
  91. package/types.d.ts.map +1 -0
  92. package/{tools/types.js → types.js} +12 -0
  93. package/types.js.map +1 -0
  94. package/{tools/types.mjs → types.mjs} +11 -0
  95. package/types.mjs.map +1 -0
  96. package/util.d.mts +4 -0
  97. package/util.d.mts.map +1 -0
  98. package/util.d.ts +4 -0
  99. package/util.d.ts.map +1 -0
  100. package/util.js +30 -0
  101. package/util.js.map +1 -0
  102. package/util.mjs +24 -0
  103. package/util.mjs.map +1 -0
  104. package/code-tool-paths.cjs +0 -6
  105. package/code-tool-paths.cjs.map +0 -1
  106. package/code-tool-paths.d.cts +0 -2
  107. package/code-tool-paths.d.cts.map +0 -1
  108. package/code-tool-worker.d.mts +0 -5
  109. package/code-tool-worker.d.mts.map +0 -1
  110. package/code-tool-worker.d.ts +0 -5
  111. package/code-tool-worker.d.ts.map +0 -1
  112. package/code-tool-worker.js +0 -45
  113. package/code-tool-worker.js.map +0 -1
  114. package/code-tool-worker.mjs +0 -40
  115. package/code-tool-worker.mjs.map +0 -1
  116. package/compat.d.mts +0 -58
  117. package/compat.d.mts.map +0 -1
  118. package/compat.d.ts +0 -58
  119. package/compat.d.ts.map +0 -1
  120. package/compat.js +0 -387
  121. package/compat.js.map +0 -1
  122. package/compat.mjs +0 -378
  123. package/compat.mjs.map +0 -1
  124. package/dynamic-tools.d.mts +0 -12
  125. package/dynamic-tools.d.mts.map +0 -1
  126. package/dynamic-tools.d.ts +0 -12
  127. package/dynamic-tools.d.ts.map +0 -1
  128. package/dynamic-tools.js +0 -135
  129. package/dynamic-tools.js.map +0 -1
  130. package/dynamic-tools.mjs +0 -132
  131. package/dynamic-tools.mjs.map +0 -1
  132. package/filtering.d.mts +0 -2
  133. package/filtering.d.mts.map +0 -1
  134. package/filtering.d.ts +0 -2
  135. package/filtering.d.ts.map +0 -1
  136. package/filtering.js +0 -20
  137. package/filtering.js.map +0 -1
  138. package/filtering.mjs +0 -13
  139. package/filtering.mjs.map +0 -1
  140. package/headers.d.mts +0 -4
  141. package/headers.d.mts.map +0 -1
  142. package/headers.d.ts +0 -4
  143. package/headers.d.ts.map +0 -1
  144. package/headers.js.map +0 -1
  145. package/headers.mjs.map +0 -1
  146. package/src/code-tool-paths.cts +0 -3
  147. package/src/code-tool-worker.ts +0 -46
  148. package/src/compat.ts +0 -483
  149. package/src/dynamic-tools.ts +0 -159
  150. package/src/filtering.ts +0 -14
  151. package/src/tools/cas-generator/generate-cas-cas-generator.ts +0 -67
  152. package/src/tools/cas-parser/cams-kfintech-cas-parser.ts +0 -47
  153. package/src/tools/cas-parser/cdsl-cas-parser.ts +0 -47
  154. package/src/tools/cas-parser/nsdl-cas-parser.ts +0 -47
  155. package/src/tools/cas-parser/smart-parse-cas-parser.ts +0 -47
  156. package/src/tools/index.ts +0 -79
  157. package/src/tools.ts +0 -1
  158. package/tools/cas-generator/generate-cas-cas-generator.d.mts.map +0 -1
  159. package/tools/cas-generator/generate-cas-cas-generator.d.ts.map +0 -1
  160. package/tools/cas-generator/generate-cas-cas-generator.js +0 -62
  161. package/tools/cas-generator/generate-cas-cas-generator.js.map +0 -1
  162. package/tools/cas-generator/generate-cas-cas-generator.mjs +0 -58
  163. package/tools/cas-generator/generate-cas-cas-generator.mjs.map +0 -1
  164. package/tools/cas-parser/cams-kfintech-cas-parser.d.mts +0 -45
  165. package/tools/cas-parser/cams-kfintech-cas-parser.d.mts.map +0 -1
  166. package/tools/cas-parser/cams-kfintech-cas-parser.d.ts +0 -45
  167. package/tools/cas-parser/cams-kfintech-cas-parser.d.ts.map +0 -1
  168. package/tools/cas-parser/cams-kfintech-cas-parser.js +0 -43
  169. package/tools/cas-parser/cams-kfintech-cas-parser.js.map +0 -1
  170. package/tools/cas-parser/cams-kfintech-cas-parser.mjs +0 -39
  171. package/tools/cas-parser/cams-kfintech-cas-parser.mjs.map +0 -1
  172. package/tools/cas-parser/cdsl-cas-parser.d.mts +0 -45
  173. package/tools/cas-parser/cdsl-cas-parser.d.mts.map +0 -1
  174. package/tools/cas-parser/cdsl-cas-parser.d.ts +0 -45
  175. package/tools/cas-parser/cdsl-cas-parser.d.ts.map +0 -1
  176. package/tools/cas-parser/cdsl-cas-parser.js +0 -43
  177. package/tools/cas-parser/cdsl-cas-parser.js.map +0 -1
  178. package/tools/cas-parser/cdsl-cas-parser.mjs +0 -39
  179. package/tools/cas-parser/cdsl-cas-parser.mjs.map +0 -1
  180. package/tools/cas-parser/nsdl-cas-parser.d.mts +0 -45
  181. package/tools/cas-parser/nsdl-cas-parser.d.mts.map +0 -1
  182. package/tools/cas-parser/nsdl-cas-parser.d.ts +0 -45
  183. package/tools/cas-parser/nsdl-cas-parser.d.ts.map +0 -1
  184. package/tools/cas-parser/nsdl-cas-parser.js +0 -43
  185. package/tools/cas-parser/nsdl-cas-parser.js.map +0 -1
  186. package/tools/cas-parser/nsdl-cas-parser.mjs +0 -39
  187. package/tools/cas-parser/nsdl-cas-parser.mjs.map +0 -1
  188. package/tools/cas-parser/smart-parse-cas-parser.d.mts +0 -45
  189. package/tools/cas-parser/smart-parse-cas-parser.d.mts.map +0 -1
  190. package/tools/cas-parser/smart-parse-cas-parser.d.ts +0 -45
  191. package/tools/cas-parser/smart-parse-cas-parser.d.ts.map +0 -1
  192. package/tools/cas-parser/smart-parse-cas-parser.js +0 -43
  193. package/tools/cas-parser/smart-parse-cas-parser.js.map +0 -1
  194. package/tools/cas-parser/smart-parse-cas-parser.mjs +0 -39
  195. package/tools/cas-parser/smart-parse-cas-parser.mjs.map +0 -1
  196. package/tools/index.d.mts +0 -10
  197. package/tools/index.d.mts.map +0 -1
  198. package/tools/index.d.ts +0 -10
  199. package/tools/index.d.ts.map +0 -1
  200. package/tools/index.js +0 -63
  201. package/tools/index.js.map +0 -1
  202. package/tools/index.mjs +0 -56
  203. package/tools/index.mjs.map +0 -1
  204. package/tools/types.d.mts.map +0 -1
  205. package/tools/types.d.ts.map +0 -1
  206. package/tools/types.js.map +0 -1
  207. package/tools/types.mjs.map +0 -1
  208. package/tools.d.mts +0 -2
  209. package/tools.d.mts.map +0 -1
  210. package/tools.d.ts +0 -2
  211. package/tools.d.ts.map +0 -1
  212. package/tools.js +0 -18
  213. package/tools.js.map +0 -1
  214. package/tools.mjs +0 -2
  215. package/tools.mjs.map +0 -1
package/server.mjs CHANGED
@@ -1,42 +1,50 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
- import { endpoints, query } from "./tools.mjs";
4
3
  import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
4
  import CasParser from 'cas-parser-node';
6
- import { applyCompatibilityTransformations, defaultClientCapabilities, knownClients, parseEmbeddedJSON, } from "./compat.mjs";
7
- import { dynamicTools } from "./dynamic-tools.mjs";
8
5
  import { codeTool } from "./code-tool.mjs";
9
- export { ClientType } from "./compat.mjs";
10
- export { endpoints } from "./tools.mjs";
11
- export const newMcpServer = () => new McpServer({
6
+ import docsSearchTool from "./docs-search-tool.mjs";
7
+ import { blockedMethodsForCodeTool } from "./methods.mjs";
8
+ 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({
12
36
  name: 'cas_parser_node_api',
13
- version: '1.4.1',
14
- }, { capabilities: { tools: {}, logging: {} } });
15
- // Create server instance
16
- export const server = newMcpServer();
37
+ version: '1.7.1',
38
+ }, {
39
+ instructions: await getInstructions(),
40
+ capabilities: { tools: {}, logging: {} },
41
+ });
17
42
  /**
18
43
  * Initializes the provided MCP Server with the given tools and handlers.
19
44
  * If not provided, the default client, tools and handlers will be used.
20
45
  */
21
- export function initMcpServer(params) {
46
+ export async function initMcpServer(params) {
22
47
  const server = params.server instanceof McpServer ? params.server.server : params.server;
23
- const mcpOptions = params.mcpOptions ?? {};
24
- let providedEndpoints = null;
25
- let endpointMap = null;
26
- const initTools = async (implementation) => {
27
- if (implementation && (!mcpOptions.client || mcpOptions.client === 'infer')) {
28
- mcpOptions.client =
29
- implementation.name.toLowerCase().includes('claude') ? 'claude'
30
- : implementation.name.toLowerCase().includes('cursor') ? 'cursor'
31
- : undefined;
32
- mcpOptions.capabilities = {
33
- ...(mcpOptions.client && knownClients[mcpOptions.client]),
34
- ...mcpOptions.capabilities,
35
- };
36
- }
37
- providedEndpoints ?? (providedEndpoints = await selectTools(endpoints, mcpOptions));
38
- endpointMap ?? (endpointMap = Object.fromEntries(providedEndpoints.map((endpoint) => [endpoint.tool.name, endpoint])));
39
- };
40
48
  const logAtLevel = (level) => (message, ...rest) => {
41
49
  void server.sendLoggingMessage({
42
50
  level,
@@ -50,6 +58,7 @@ export function initMcpServer(params) {
50
58
  error: logAtLevel('error'),
51
59
  };
52
60
  let client = new CasParser({
61
+ ...{ environment: (readEnv('CAS_PARSER_ENVIRONMENT') || undefined) },
53
62
  logger,
54
63
  ...params.clientOptions,
55
64
  defaultHeaders: {
@@ -57,24 +66,20 @@ export function initMcpServer(params) {
57
66
  'X-Stainless-MCP': 'true',
58
67
  },
59
68
  });
69
+ const providedTools = selectTools(params.mcpOptions);
70
+ const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool]));
60
71
  server.setRequestHandler(ListToolsRequestSchema, async () => {
61
- if (providedEndpoints === null) {
62
- await initTools(server.getClientVersion());
63
- }
64
72
  return {
65
- tools: providedEndpoints.map((endpoint) => endpoint.tool),
73
+ tools: providedTools.map((mcpTool) => mcpTool.tool),
66
74
  };
67
75
  });
68
76
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
69
- if (endpointMap === null) {
70
- await initTools(server.getClientVersion());
71
- }
72
77
  const { name, arguments: args } = request.params;
73
- const endpoint = endpointMap[name];
74
- if (!endpoint) {
78
+ const mcpTool = toolMap[name];
79
+ if (!mcpTool) {
75
80
  throw new Error(`Unknown tool: ${name}`);
76
81
  }
77
- return executeHandler(endpoint.tool, endpoint.handler, client, args, mcpOptions.capabilities);
82
+ return executeHandler(mcpTool.handler, client, args);
78
83
  });
79
84
  server.setRequestHandler(SetLevelRequestSchema, async (request) => {
80
85
  const { level } = request.params;
@@ -102,55 +107,21 @@ export function initMcpServer(params) {
102
107
  /**
103
108
  * Selects the tools to include in the MCP Server based on the provided options.
104
109
  */
105
- export async function selectTools(endpoints, options) {
106
- const filteredEndpoints = query(options?.filters ?? [], endpoints);
107
- let includedTools = filteredEndpoints;
108
- if (includedTools.length > 0) {
109
- if (options?.includeDynamicTools) {
110
- includedTools = dynamicTools(includedTools);
111
- }
110
+ export function selectTools(options) {
111
+ const includedTools = [
112
+ codeTool({
113
+ blockedMethods: blockedMethodsForCodeTool(options),
114
+ }),
115
+ ];
116
+ if (options?.includeDocsTools ?? true) {
117
+ includedTools.push(docsSearchTool);
112
118
  }
113
- else {
114
- if (options?.includeAllTools) {
115
- includedTools = endpoints;
116
- }
117
- else if (options?.includeDynamicTools) {
118
- includedTools = dynamicTools(endpoints);
119
- }
120
- else if (options?.includeCodeTools) {
121
- includedTools = [await codeTool()];
122
- }
123
- else {
124
- includedTools = endpoints;
125
- }
126
- }
127
- const capabilities = { ...defaultClientCapabilities, ...options?.capabilities };
128
- return applyCompatibilityTransformations(includedTools, capabilities);
119
+ return includedTools;
129
120
  }
130
121
  /**
131
122
  * Runs the provided handler with the given client and arguments.
132
123
  */
133
- export async function executeHandler(tool, handler, client, args, compatibilityOptions) {
134
- const options = { ...defaultClientCapabilities, ...compatibilityOptions };
135
- if (!options.validJson && args) {
136
- args = parseEmbeddedJSON(args, tool.inputSchema);
137
- }
124
+ export async function executeHandler(handler, client, args) {
138
125
  return await handler(client, args || {});
139
126
  }
140
- export const readEnv = (env) => {
141
- if (typeof globalThis.process !== 'undefined') {
142
- return globalThis.process.env?.[env]?.trim();
143
- }
144
- else if (typeof globalThis.Deno !== 'undefined') {
145
- return globalThis.Deno.env?.get?.(env)?.trim();
146
- }
147
- return;
148
- };
149
- export const readEnvOrError = (env) => {
150
- let envValue = readEnv(env);
151
- if (envValue === undefined) {
152
- throw new Error(`Environment variable ${env} is not set`);
153
- }
154
- return envValue;
155
- };
156
127
  //# 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,EAAY,SAAS,EAAmB,KAAK,EAAE;OAC/C,EACL,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,GAGtB,MAAM,oCAAoC;OAEpC,SAAS,MAAM,iBAAiB;OAChC,EACL,iCAAiC,EAEjC,yBAAyB,EACzB,YAAY,EACZ,iBAAiB,GAClB;OACM,EAAE,YAAY,EAAE;OAChB,EAAE,QAAQ,EAAE;OAIZ,EAAE,UAAU,EAAE;OAGd,EAAE,SAAS,EAAE;AAEpB,MAAM,CAAC,MAAM,YAAY,GAAG,GAAG,EAAE,CAC/B,IAAI,SAAS,CACX;IACE,IAAI,EAAE,qBAAqB;IAC3B,OAAO,EAAE,OAAO;CACjB,EACD,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CAC7C,CAAC;AAEJ,yBAAyB;AACzB,MAA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C;IACrC,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,OAAwB,EACxB,MAAiB,EACjB,IAAyC;IAEzC,OAAO,MAAM,OAAO,CAAC,MAAM,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;AAC3C,CAAC"}
@@ -3,7 +3,7 @@
3
3
  import { IncomingMessage } from 'node:http';
4
4
  import { ClientOptions } from 'cas-parser-node';
5
5
 
6
- export const parseAuthHeaders = (req: IncomingMessage): Partial<ClientOptions> => {
6
+ export const parseAuthHeaders = (req: IncomingMessage, required?: boolean): Partial<ClientOptions> => {
7
7
  const apiKey =
8
8
  Array.isArray(req.headers['x-api-key']) ? req.headers['x-api-key'][0] : req.headers['x-api-key'];
9
9
  return { apiKey };
@@ -3,12 +3,14 @@
3
3
  import { ClientOptions } from 'cas-parser-node';
4
4
 
5
5
  export type WorkerInput = {
6
- opts: ClientOptions;
6
+ project_name: string;
7
7
  code: string;
8
+ client_opts: ClientOptions;
9
+ intent?: string | undefined;
8
10
  };
9
- export type WorkerSuccess = {
11
+ export type WorkerOutput = {
12
+ is_error: boolean;
10
13
  result: unknown | null;
11
- logLines: string[];
12
- errLines: string[];
14
+ log_lines: string[];
15
+ err_lines: string[];
13
16
  };
14
- export type WorkerError = { message: string | undefined };
package/src/code-tool.ts CHANGED
@@ -1,145 +1,132 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
3
- import { dirname } from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
- import CasParser, { ClientOptions } from 'cas-parser-node';
6
- import { Endpoint, ContentBlock, Metadata } from './tools/types';
7
-
3
+ import { McpTool, Metadata, ToolCallResult, asErrorResult, asTextContentResult } from './types';
8
4
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
5
+ import { readEnv, requireValue } from './util';
6
+ import { WorkerInput, WorkerOutput } from './code-tool-types';
7
+ import { SdkMethod } from './methods';
8
+ import { CasParser } from 'cas-parser-node';
9
+
10
+ const prompt = `Runs JavaScript code to interact with the Cas Parser API.
11
+
12
+ You are a skilled programmer writing code to interface with the service.
13
+ Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
14
+ For example:
9
15
 
10
- import { WorkerInput, WorkerError, WorkerSuccess } from './code-tool-types';
16
+ \`\`\`
17
+ async function run(client) {
18
+ const response = await client.credits.check();
19
+
20
+ console.log(response.enabled_features);
21
+ }
22
+ \`\`\`
23
+
24
+ You will be returned anything that your function returns, plus the results of any console.log statements.
25
+ Do not add try-catch blocks for single API calls. The tool will handle errors for you.
26
+ Do not add comments unless necessary for generating better code.
27
+ 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.`;
11
29
 
12
30
  /**
13
31
  * A tool that runs code against a copy of the SDK.
14
32
  *
15
- * Instead of exposing every endpoint as it's own tool, which uses up too many tokens for LLMs to use at once,
33
+ * Instead of exposing every endpoint as its own tool, which uses up too many tokens for LLMs to use at once,
16
34
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
17
35
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
18
36
  *
19
37
  * @param endpoints - The endpoints to include in the list.
20
38
  */
21
- export async function codeTool(): Promise<Endpoint> {
39
+ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): McpTool {
22
40
  const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
23
41
  const tool: Tool = {
24
42
  name: 'execute',
25
- description:
26
- 'Runs Typescript code to interact with the API.\nYou are a skilled programmer writing code to interface with the service.\nDefine an async function named "run" that takes a single parameter of an initialized client, and it will be run.\nDo not initialize a client, but instead use the client that you are given as a parameter.\nYou will be returned anything that your function returns, plus the results of any console.log statements.\nIf any code triggers an error, the tool will return an error response, so you do not need to add error handling unless you want to output something more helpful than the raw error.\nIt is not necessary to add comments to code, unless by adding those comments you believe that you can generate better code.\nThis code will run in a container, and you will not be able to use fetch or otherwise interact with the network calls other than through the client you are given.\nAny variables you define won\'t live between successive uses of this call, so make sure to return or log any data you might need later.',
27
- inputSchema: { type: 'object', properties: { code: { type: 'string' } } },
43
+ description: prompt,
44
+ inputSchema: {
45
+ type: 'object',
46
+ properties: {
47
+ code: {
48
+ type: 'string',
49
+ description: 'Code to execute.',
50
+ },
51
+ intent: {
52
+ type: 'string',
53
+ description: 'Task you are trying to perform. Used for improving the service.',
54
+ },
55
+ },
56
+ required: ['code'],
57
+ },
28
58
  };
59
+ const handler = async (client: CasParser, args: any): Promise<ToolCallResult> => {
60
+ const code = args.code as string;
61
+ const intent = args.intent as string | undefined;
29
62
 
30
- // Import dynamically to avoid failing at import time in cases where the environment is not well-supported.
31
- const { newDenoHTTPWorker } = await import('@valtown/deno-http-worker');
32
- const { workerPath } = await import('./code-tool-paths.cjs');
63
+ // Do very basic blocking of code that includes forbidden method names.
64
+ //
65
+ // WARNING: This is not secure against obfuscation and other evasion methods. If
66
+ // stronger security blocks are required, then these should be enforced in the downstream
67
+ // 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
+ );
72
+ if (blockedMatches.length > 0) {
73
+ return asErrorResult(
74
+ `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
75
+ .map((m) => m.fullyQualifiedName)
76
+ .join(', ')}`,
77
+ );
78
+ }
79
+ }
33
80
 
34
- const handler = async (client: CasParser, args: unknown) => {
35
- const baseURLHostname = new URL(client.baseURL).hostname;
36
- const { code } = args as { code: string };
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';
37
86
 
38
- const worker = await newDenoHTTPWorker(pathToFileURL(workerPath), {
39
- runFlags: [
40
- `--node-modules-dir=manual`,
41
- `--allow-read=code-tool-worker.mjs,${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
42
- `--allow-net=${baseURLHostname}`,
43
- // Allow environment variables because instantiating the client will try to read from them,
44
- // even though they are not set.
45
- '--allow-env',
46
- ],
47
- printOutput: true,
48
- spawnOptions: {
49
- cwd: dirname(workerPath),
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
+ CAS_PARSER_API_KEY: requireValue(
94
+ readEnv('CAS_PARSER_API_KEY') ?? client.apiKey,
95
+ 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option',
96
+ ),
97
+ CAS_PARSER_BASE_URL:
98
+ readEnv('CAS_PARSER_BASE_URL') ?? readEnv('CAS_PARSER_ENVIRONMENT') ?
99
+ undefined
100
+ : client.baseURL ?? undefined,
101
+ }),
50
102
  },
103
+ body: JSON.stringify({
104
+ project_name: 'cas-parser',
105
+ code,
106
+ intent,
107
+ client_opts: { environment: (readEnv('CAS_PARSER_ENVIRONMENT') || undefined) as any },
108
+ } satisfies WorkerInput),
51
109
  });
52
110
 
53
- try {
54
- const resp = await new Promise<Response>((resolve, reject) => {
55
- worker.addEventListener('exit', (exitCode) => {
56
- reject(new Error(`Worker exited with code ${exitCode}`));
57
- });
58
-
59
- const opts: ClientOptions = {
60
- baseURL: client.baseURL,
61
- apiKey: client.apiKey,
62
- defaultHeaders: {
63
- 'X-Stainless-MCP': 'true',
64
- },
65
- };
66
-
67
- const req = worker.request(
68
- 'http://localhost',
69
- {
70
- headers: {
71
- 'content-type': 'application/json',
72
- },
73
- method: 'POST',
74
- },
75
- (resp) => {
76
- const body: Uint8Array[] = [];
77
- resp.on('error', (err) => {
78
- reject(err);
79
- });
80
- resp.on('data', (chunk) => {
81
- body.push(chunk);
82
- });
83
- resp.on('end', () => {
84
- resolve(
85
- new Response(Buffer.concat(body).toString(), {
86
- status: resp.statusCode ?? 200,
87
- headers: resp.headers as any,
88
- }),
89
- );
90
- });
91
- },
92
- );
93
-
94
- const body = JSON.stringify({
95
- opts,
96
- code,
97
- } satisfies WorkerInput);
98
-
99
- req.write(body, (err) => {
100
- if (err !== null && err !== undefined) {
101
- reject(err);
102
- }
103
- });
104
-
105
- req.end();
106
- });
111
+ if (!res.ok) {
112
+ throw new Error(
113
+ `${res.status}: ${
114
+ res.statusText
115
+ } error when trying to contact Code Tool server. Details: ${await res.text()}`,
116
+ );
117
+ }
107
118
 
108
- if (resp.status === 200) {
109
- const { result, logLines, errLines } = (await resp.json()) as WorkerSuccess;
110
- const returnOutput: ContentBlock | null =
111
- result === null ? null
112
- : result === undefined ? null
113
- : {
114
- type: 'text',
115
- text: typeof result === 'string' ? (result as string) : JSON.stringify(result),
116
- };
117
- const logOutput: ContentBlock | null =
118
- logLines.length === 0 ?
119
- null
120
- : {
121
- type: 'text',
122
- text: logLines.join('\n'),
123
- };
124
- const errOutput: ContentBlock | null =
125
- errLines.length === 0 ?
126
- null
127
- : {
128
- type: 'text',
129
- text: 'Error output:\n' + errLines.join('\n'),
130
- };
131
- return {
132
- content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
133
- };
134
- } else {
135
- const { message } = (await resp.json()) as WorkerError;
136
- throw new Error(message);
137
- }
138
- } catch (e) {
139
- throw e;
140
- } finally {
141
- worker.terminate();
119
+ const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
120
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
121
+ const output = {
122
+ result,
123
+ ...(log_lines.length > 0 && { log_lines }),
124
+ ...(err_lines.length > 0 && { err_lines }),
125
+ };
126
+ if (is_error) {
127
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
142
128
  }
129
+ return asTextContentResult(output);
143
130
  };
144
131
 
145
132
  return { metadata, tool, handler };
@@ -0,0 +1,65 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import { Metadata, asTextContentResult } from './types';
4
+ import { readEnv } from './util';
5
+
6
+ import { Tool } from '@modelcontextprotocol/sdk/types.js';
7
+
8
+ export const metadata: Metadata = {
9
+ resource: 'all',
10
+ operation: 'read',
11
+ tags: [],
12
+ httpMethod: 'get',
13
+ };
14
+
15
+ export const tool: Tool = {
16
+ name: 'search_docs',
17
+ description: 'Search for documentation for how to use the client to interact with the API.',
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/cas-parser/docs/search';
45
+
46
+ export const handler = async (_: unknown, args: Record<string, unknown> | undefined) => {
47
+ const body = args as any;
48
+ const query = new URLSearchParams(body).toString();
49
+ const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
50
+ const result = await fetch(`${docsSearchURL}?${query}`, {
51
+ headers: {
52
+ ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
53
+ },
54
+ });
55
+
56
+ if (!result.ok) {
57
+ throw new Error(
58
+ `${result.status}: ${result.statusText} when using doc search tool. Details: ${await result.text()}`,
59
+ );
60
+ }
61
+
62
+ return asTextContentResult(await result.json());
63
+ };
64
+
65
+ export default { metadata, tool, handler };