cas-parser-node-mcp 1.9.0 → 1.10.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 (89) hide show
  1. package/code-tool-paths.cjs +6 -0
  2. package/code-tool-paths.cjs.map +1 -0
  3. package/code-tool-paths.d.cts +2 -0
  4. package/code-tool-paths.d.cts.map +1 -0
  5. package/code-tool-types.d.mts.map +1 -1
  6. package/code-tool-types.d.ts.map +1 -1
  7. package/code-tool-worker.d.mts +5 -0
  8. package/code-tool-worker.d.mts.map +1 -0
  9. package/code-tool-worker.d.ts +5 -0
  10. package/code-tool-worker.d.ts.map +1 -0
  11. package/code-tool-worker.js +245 -0
  12. package/code-tool-worker.js.map +1 -0
  13. package/code-tool-worker.mjs +240 -0
  14. package/code-tool-worker.mjs.map +1 -0
  15. package/code-tool.d.mts +8 -2
  16. package/code-tool.d.mts.map +1 -1
  17. package/code-tool.d.ts +8 -2
  18. package/code-tool.d.ts.map +1 -1
  19. package/code-tool.js +260 -37
  20. package/code-tool.js.map +1 -1
  21. package/code-tool.mjs +224 -37
  22. package/code-tool.mjs.map +1 -1
  23. package/docs-search-tool.d.mts +1 -1
  24. package/docs-search-tool.d.mts.map +1 -1
  25. package/docs-search-tool.d.ts +1 -1
  26. package/docs-search-tool.d.ts.map +1 -1
  27. package/docs-search-tool.js +22 -3
  28. package/docs-search-tool.js.map +1 -1
  29. package/docs-search-tool.mjs +22 -3
  30. package/docs-search-tool.mjs.map +1 -1
  31. package/http.d.mts +2 -4
  32. package/http.d.mts.map +1 -1
  33. package/http.d.ts +2 -4
  34. package/http.d.ts.map +1 -1
  35. package/http.js +52 -19
  36. package/http.js.map +1 -1
  37. package/http.mjs +52 -19
  38. package/http.mjs.map +1 -1
  39. package/index.js +12 -11
  40. package/index.js.map +1 -1
  41. package/index.mjs +12 -11
  42. package/index.mjs.map +1 -1
  43. package/instructions.d.mts.map +1 -1
  44. package/instructions.d.ts.map +1 -1
  45. package/instructions.js +4 -13
  46. package/instructions.js.map +1 -1
  47. package/instructions.mjs +4 -13
  48. package/instructions.mjs.map +1 -1
  49. package/logger.d.mts +7 -0
  50. package/logger.d.mts.map +1 -0
  51. package/logger.d.ts +7 -0
  52. package/logger.d.ts.map +1 -0
  53. package/logger.js +29 -0
  54. package/logger.js.map +1 -0
  55. package/logger.mjs +22 -0
  56. package/logger.mjs.map +1 -0
  57. package/options.d.mts +4 -0
  58. package/options.d.mts.map +1 -1
  59. package/options.d.ts +4 -0
  60. package/options.d.ts.map +1 -1
  61. package/options.js +23 -0
  62. package/options.js.map +1 -1
  63. package/options.mjs +23 -0
  64. package/options.mjs.map +1 -1
  65. package/package.json +32 -5
  66. package/server.d.mts.map +1 -1
  67. package/server.d.ts.map +1 -1
  68. package/server.js +7 -5
  69. package/server.js.map +1 -1
  70. package/server.mjs +7 -5
  71. package/server.mjs.map +1 -1
  72. package/src/code-tool-paths.cts +3 -0
  73. package/src/code-tool-types.ts +1 -0
  74. package/src/code-tool-worker.ts +291 -0
  75. package/src/code-tool.ts +291 -47
  76. package/src/docs-search-tool.ts +36 -4
  77. package/src/http.ts +53 -21
  78. package/src/index.ts +14 -12
  79. package/src/instructions.ts +4 -13
  80. package/src/logger.ts +28 -0
  81. package/src/options.ts +32 -0
  82. package/src/server.ts +11 -6
  83. package/src/stdio.ts +2 -1
  84. package/stdio.d.mts.map +1 -1
  85. package/stdio.d.ts.map +1 -1
  86. package/stdio.js +2 -1
  87. package/stdio.js.map +1 -1
  88. package/stdio.mjs +2 -1
  89. package/stdio.mjs.map +1 -1
package/src/code-tool.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
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';
3
8
  import {
9
+ ContentBlock,
4
10
  McpRequestContext,
5
11
  McpTool,
6
12
  Metadata,
@@ -11,11 +17,14 @@ import {
11
17
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
12
18
  import { readEnv, requireValue } from './util';
13
19
  import { WorkerInput, WorkerOutput } from './code-tool-types';
20
+ import { getLogger } from './logger';
14
21
  import { SdkMethod } from './methods';
22
+ import { McpCodeExecutionMode } from './options';
23
+ import { ClientOptions } from 'cas-parser-node';
15
24
 
16
25
  const prompt = `Runs JavaScript code to interact with the Cas Parser API.
17
26
 
18
- You are a skilled programmer writing code to interface with the service.
27
+ You are a skilled TypeScript programmer writing code to interface with the service.
19
28
  Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
20
29
  For example:
21
30
 
@@ -31,7 +40,9 @@ You will be returned anything that your function returns, plus the results of an
31
40
  Do not add try-catch blocks for single API calls. The tool will handle errors for you.
32
41
  Do not add comments unless necessary for generating better code.
33
42
  Code will run in a container, and cannot interact with the network outside of the given SDK client.
34
- Variables will not persist between calls, so make sure to return or log any data you might need later.`;
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 {}.`;
35
46
 
36
47
  /**
37
48
  * A tool that runs code against a copy of the SDK.
@@ -40,9 +51,19 @@ Variables will not persist between calls, so make sure to return or log any data
40
51
  * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
41
52
  * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
42
53
  *
43
- * @param endpoints - The endpoints to include in the list.
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.
44
59
  */
45
- export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | undefined }): McpTool {
60
+ export function codeTool({
61
+ blockedMethods,
62
+ codeExecutionMode,
63
+ }: {
64
+ blockedMethods: SdkMethod[] | undefined;
65
+ codeExecutionMode: McpCodeExecutionMode;
66
+ }): McpTool {
46
67
  const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
47
68
  const tool: Tool = {
48
69
  name: 'execute',
@@ -62,6 +83,9 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
62
83
  required: ['code'],
63
84
  },
64
85
  };
86
+
87
+ const logger = getLogger();
88
+
65
89
  const handler = async ({
66
90
  reqContext,
67
91
  args,
@@ -70,9 +94,6 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
70
94
  args: any;
71
95
  }): Promise<ToolCallResult> => {
72
96
  const code = args.code as string;
73
- const intent = args.intent as string | undefined;
74
- const client = reqContext.client;
75
-
76
97
  // Do very basic blocking of code that includes forbidden method names.
77
98
  //
78
99
  // WARNING: This is not secure against obfuscation and other evasion methods. If
@@ -89,51 +110,274 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
89
110
  }
90
111
  }
91
112
 
92
- const codeModeEndpoint =
93
- readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
94
-
95
- // Setting a Stainless API key authenticates requests to the code tool endpoint.
96
- const res = await fetch(codeModeEndpoint, {
97
- method: 'POST',
98
- headers: {
99
- ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
100
- 'Content-Type': 'application/json',
101
- client_envs: JSON.stringify({
102
- CAS_PARSER_API_KEY: requireValue(
103
- readEnv('CAS_PARSER_API_KEY') ?? client.apiKey,
104
- 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option',
105
- ),
106
- CAS_PARSER_BASE_URL: readEnv('CAS_PARSER_BASE_URL') ?? client.baseURL ?? undefined,
107
- }),
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,
108
130
  },
109
- body: JSON.stringify({
110
- project_name: 'cas-parser',
111
- code,
112
- intent,
113
- client_opts: {},
114
- } satisfies WorkerInput),
115
- });
131
+ 'Got code tool execution result',
132
+ );
133
+ return result;
134
+ };
135
+
136
+ return { metadata, tool, handler };
137
+ }
116
138
 
117
- if (!res.ok) {
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
+ CAS_PARSER_API_KEY: requireValue(
160
+ readEnv('CAS_PARSER_API_KEY') ?? client.apiKey,
161
+ 'set CAS_PARSER_API_KEY environment variable or provide apiKey client option',
162
+ ),
163
+ CAS_PARSER_BASE_URL: readEnv('CAS_PARSER_BASE_URL') ?? client.baseURL ?? undefined,
164
+ }),
165
+ },
166
+ body: JSON.stringify({
167
+ project_name: 'cas-parser',
168
+ code,
169
+ intent,
170
+ client_opts: {},
171
+ } satisfies WorkerInput),
172
+ });
173
+
174
+ if (!res.ok) {
175
+ if (res.status === 404 && !reqContext.stainlessApiKey) {
118
176
  throw new Error(
119
- `${res.status}: ${
120
- res.statusText
121
- } error when trying to contact Code Tool server. Details: ${await res.text()}`,
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.',
122
178
  );
123
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
+ }
124
186
 
125
- const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
126
- const hasLogs = log_lines.length > 0 || err_lines.length > 0;
127
- const output = {
128
- result,
129
- ...(log_lines.length > 0 && { log_lines }),
130
- ...(err_lines.length > 0 && { err_lines }),
131
- };
132
- if (is_error) {
133
- return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
134
- }
135
- return asTextContentResult(output);
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 }),
136
193
  };
194
+ if (is_error) {
195
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
196
+ }
197
+ return asTextContentResult(output);
198
+ };
137
199
 
138
- return { metadata, tool, handler };
139
- }
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 = 'cas-parser-node';
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
+ };
@@ -1,7 +1,8 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
3
- import { Metadata, McpRequestContext, asTextContentResult } from './types';
4
3
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
4
+ import { Metadata, McpRequestContext, asTextContentResult } from './types';
5
+ import { getLogger } from './logger';
5
6
 
6
7
  export const metadata: Metadata = {
7
8
  resource: 'all',
@@ -12,7 +13,8 @@ export const metadata: Metadata = {
12
13
 
13
14
  export const tool: Tool = {
14
15
  name: 'search_docs',
15
- description: 'Search for documentation for how to use the client to interact with the API.',
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.',
16
18
  inputSchema: {
17
19
  type: 'object',
18
20
  properties: {
@@ -50,19 +52,49 @@ export const handler = async ({
50
52
  }) => {
51
53
  const body = args as any;
52
54
  const query = new URLSearchParams(body).toString();
55
+
56
+ const startTime = Date.now();
53
57
  const result = await fetch(`${docsSearchURL}?${query}`, {
54
58
  headers: {
55
59
  ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
56
60
  },
57
61
  });
58
62
 
63
+ const logger = getLogger();
64
+
59
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
+
60
84
  throw new Error(
61
- `${result.status}: ${result.statusText} when using doc search tool. Details: ${await result.text()}`,
85
+ `${result.status}: ${result.statusText} when using doc search tool. Details: ${errorText}`,
62
86
  );
63
87
  }
64
88
 
65
- return asTextContentResult(await result.json());
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);
66
98
  };
67
99
 
68
100
  export default { metadata, tool, handler };
package/src/http.ts CHANGED
@@ -4,9 +4,10 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
4
4
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
5
5
  import { ClientOptions } from 'cas-parser-node';
6
6
  import express from 'express';
7
- import morgan from 'morgan';
8
- import morganBody from 'morgan-body';
7
+ import pino from 'pino';
8
+ import pinoHttp from 'pino-http';
9
9
  import { getStainlessApiKey, parseClientAuthHeaders } from './auth';
10
+ import { getLogger } from './logger';
10
11
  import { McpOptions } from './options';
11
12
  import { initMcpServer, newMcpServer } from './server';
12
13
 
@@ -70,29 +71,60 @@ const del = async (req: express.Request, res: express.Response) => {
70
71
  });
71
72
  };
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
+
73
85
  export const streamableHTTPApp = ({
74
86
  clientOptions = {},
75
87
  mcpOptions,
76
- debug,
77
88
  }: {
78
89
  clientOptions?: ClientOptions;
79
90
  mcpOptions: McpOptions;
80
- debug: boolean;
81
91
  }): express.Express => {
82
92
  const app = express();
83
93
  app.set('query parser', 'extended');
84
94
  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
- }
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
+ );
96
128
 
97
129
  app.get('/health', async (req: express.Request, res: express.Response) => {
98
130
  res.status(200).send('OK');
@@ -106,22 +138,22 @@ export const streamableHTTPApp = ({
106
138
 
107
139
  export const launchStreamableHTTPServer = async ({
108
140
  mcpOptions,
109
- debug,
110
141
  port,
111
142
  }: {
112
143
  mcpOptions: McpOptions;
113
- debug: boolean;
114
144
  port: number | string | undefined;
115
145
  }) => {
116
- const app = streamableHTTPApp({ mcpOptions, debug });
146
+ const app = streamableHTTPApp({ mcpOptions });
117
147
  const server = app.listen(port);
118
148
  const address = server.address();
119
149
 
150
+ const logger = getLogger();
151
+
120
152
  if (typeof address === 'string') {
121
- console.error(`MCP Server running on streamable HTTP at ${address}`);
153
+ logger.info(`MCP Server running on streamable HTTP at ${address}`);
122
154
  } else if (address !== null) {
123
- console.error(`MCP Server running on streamable HTTP on port ${address.port}`);
155
+ logger.info(`MCP Server running on streamable HTTP on port ${address.port}`);
124
156
  } else {
125
- console.error(`MCP Server running on streamable HTTP on port ${port}`);
157
+ logger.info(`MCP Server running on streamable HTTP on port ${port}`);
126
158
  }
127
159
  };
package/src/index.ts CHANGED
@@ -5,15 +5,20 @@ import { McpOptions, parseCLIOptions } from './options';
5
5
  import { launchStdioServer } from './stdio';
6
6
  import { launchStreamableHTTPServer } from './http';
7
7
  import type { McpTool } from './types';
8
+ import { configureLogger, getLogger } from './logger';
8
9
 
9
10
  async function main() {
10
11
  const options = parseOptionsOrError();
12
+ configureLogger({
13
+ level: options.debug ? 'debug' : 'info',
14
+ pretty: options.logFormat === 'pretty',
15
+ });
11
16
 
12
17
  const selectedTools = await selectToolsOrError(options);
13
18
 
14
- console.error(
15
- `MCP Server starting with ${selectedTools.length} tools:`,
16
- selectedTools.map((e) => e.tool.name),
19
+ getLogger().info(
20
+ { tools: selectedTools.map((e) => e.tool.name) },
21
+ `MCP Server starting with ${selectedTools.length} tools`,
17
22
  );
18
23
 
19
24
  switch (options.transport) {
@@ -23,7 +28,6 @@ async function main() {
23
28
  case 'http':
24
29
  await launchStreamableHTTPServer({
25
30
  mcpOptions: options,
26
- debug: options.debug,
27
31
  port: options.socket ?? options.port,
28
32
  });
29
33
  break;
@@ -32,7 +36,8 @@ async function main() {
32
36
 
33
37
  if (require.main === module) {
34
38
  main().catch((error) => {
35
- console.error('Fatal error in main():', error);
39
+ // Logger might not be initialized yet
40
+ console.error('Fatal error in main()', error);
36
41
  process.exit(1);
37
42
  });
38
43
  }
@@ -41,7 +46,8 @@ function parseOptionsOrError() {
41
46
  try {
42
47
  return parseCLIOptions();
43
48
  } catch (error) {
44
- console.error('Error parsing options:', error);
49
+ // Logger is initialized after options, so use console.error here
50
+ console.error('Error parsing options', error);
45
51
  process.exit(1);
46
52
  }
47
53
  }
@@ -50,16 +56,12 @@ async function selectToolsOrError(options: McpOptions): Promise<McpTool[]> {
50
56
  try {
51
57
  const includedTools = selectTools(options);
52
58
  if (includedTools.length === 0) {
53
- console.error('No tools match the provided filters.');
59
+ getLogger().error('No tools match the provided filters');
54
60
  process.exit(1);
55
61
  }
56
62
  return includedTools;
57
63
  } 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
- }
64
+ getLogger().error({ error }, 'Error filtering tools');
63
65
  process.exit(1);
64
66
  }
65
67
  }
@@ -1,6 +1,7 @@
1
1
  // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
2
 
3
3
  import { readEnv } from './util';
4
+ import { getLogger } from './logger';
4
5
 
5
6
  const INSTRUCTIONS_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes
6
7
 
@@ -50,25 +51,15 @@ async function fetchLatestInstructions(stainlessApiKey: string | undefined): Pro
50
51
 
51
52
  let instructions: string | undefined;
52
53
  if (!response.ok) {
53
- console.warn(
54
+ getLogger().warn(
54
55
  'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...',
55
56
  );
56
57
 
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
- `;
58
+ instructions =
59
+ '\n This is the cas-parser MCP server.\n\n Available tools:\n - search_docs: Search SDK documentation to find the right methods and parameters.\n - execute: Run TypeScript code against a pre-authenticated SDK client. Define an async run(client) function.\n\n Workflow:\n - If unsure about the API, call search_docs first.\n - Write complete solutions in a single execute call when possible. For large datasets, use API filters to narrow results or paginate within a single execute block.\n - If execute returns an error, read the error and fix your code rather than retrying the same approach.\n - Variables do not persist between execute calls. Return or log all data you need.\n - Individual HTTP requests to the API have a 30-second timeout. If a request times out, try a smaller query or add filters.\n - Code execution has a total timeout of approximately 5 minutes. If your code times out, simplify it or break it into smaller steps.\n ';
64
60
  }
65
61
 
66
62
  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
63
 
73
64
  return instructions;
74
65
  }