@cjavdev/believe-mcp 0.8.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) 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/methods.d.mts.map +1 -1
  46. package/methods.d.ts.map +1 -1
  47. package/methods.js +0 -6
  48. package/methods.js.map +1 -1
  49. package/methods.mjs +0 -6
  50. package/methods.mjs.map +1 -1
  51. package/options.d.mts +1 -0
  52. package/options.d.mts.map +1 -1
  53. package/options.d.ts +1 -0
  54. package/options.d.ts.map +1 -1
  55. package/options.js +7 -0
  56. package/options.js.map +1 -1
  57. package/options.mjs +7 -0
  58. package/options.mjs.map +1 -1
  59. package/package.json +12 -2
  60. package/server.d.mts +8 -4
  61. package/server.d.mts.map +1 -1
  62. package/server.d.ts +8 -4
  63. package/server.d.ts.map +1 -1
  64. package/server.js +66 -46
  65. package/server.js.map +1 -1
  66. package/server.mjs +66 -46
  67. package/server.mjs.map +1 -1
  68. package/src/auth.ts +16 -1
  69. package/src/code-tool.ts +21 -12
  70. package/src/docs-search-tool.ts +9 -6
  71. package/src/http.ts +22 -26
  72. package/src/index.ts +1 -1
  73. package/src/instructions.ts +74 -0
  74. package/src/methods.ts +0 -6
  75. package/src/options.ts +9 -0
  76. package/src/server.ts +75 -61
  77. package/src/stdio.ts +2 -2
  78. package/src/types.ts +12 -4
  79. package/stdio.js +2 -2
  80. package/stdio.js.map +1 -1
  81. package/stdio.mjs +2 -2
  82. package/stdio.mjs.map +1 -1
  83. package/types.d.mts +8 -1
  84. package/types.d.mts.map +1 -1
  85. package/types.d.ts +8 -1
  86. package/types.d.ts.map +1 -1
  87. package/types.js.map +1 -1
  88. package/types.mjs.map +1 -1
package/server.js CHANGED
@@ -13,39 +13,13 @@ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
13
13
  const believe_1 = __importDefault(require("@cjavdev/believe"));
14
14
  const code_tool_1 = require("./code-tool.js");
15
15
  const docs_search_tool_1 = __importDefault(require("./docs-search-tool.js"));
16
+ const instructions_1 = require("./instructions.js");
16
17
  const methods_1 = require("./methods.js");
17
- const util_1 = require("./util.js");
18
- async function getInstructions() {
19
- // This API key is optional; providing it allows the server to fetch instructions for unreleased versions.
20
- const stainlessAPIKey = (0, util_1.readEnv)('STAINLESS_API_KEY');
21
- const response = await fetch((0, util_1.readEnv)('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/believe', {
22
- method: 'GET',
23
- headers: { ...(stainlessAPIKey && { Authorization: stainlessAPIKey }) },
24
- });
25
- let instructions;
26
- if (!response.ok) {
27
- console.warn('Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...');
28
- instructions = `
29
- This is the believe MCP server. You will use Code Mode to help the user perform
30
- actions. You can use search_docs tool to learn about how to take action with this server. Then,
31
- you will write TypeScript code using the execute tool take action. It is CRITICAL that you be
32
- thoughtful and deliberate when executing code. Always try to entirely solve the problem in code
33
- block: it can be as long as you need to get the job done!
34
- `;
35
- }
36
- instructions ??= (await response.json()).instructions;
37
- instructions = `
38
- The current time in Unix timestamps is ${Date.now()}.
39
-
40
- ${instructions}
41
- `;
42
- return instructions;
43
- }
44
- const newMcpServer = async () => new mcp_js_1.McpServer({
18
+ const newMcpServer = async (stainlessApiKey) => new mcp_js_1.McpServer({
45
19
  name: 'cjavdev_believe_api',
46
- version: '0.8.0',
20
+ version: '0.11.0',
47
21
  }, {
48
- instructions: await getInstructions(),
22
+ instructions: await (0, instructions_1.getInstructions)(stainlessApiKey),
49
23
  capabilities: { tools: {}, logging: {} },
50
24
  });
51
25
  exports.newMcpServer = newMcpServer;
@@ -67,14 +41,33 @@ async function initMcpServer(params) {
67
41
  warn: logAtLevel('warning'),
68
42
  error: logAtLevel('error'),
69
43
  };
70
- let client = new believe_1.default({
71
- logger,
72
- ...params.clientOptions,
73
- defaultHeaders: {
74
- ...params.clientOptions?.defaultHeaders,
75
- 'X-Stainless-MCP': 'true',
76
- },
77
- });
44
+ let _client;
45
+ let _clientError;
46
+ let _logLevel;
47
+ const getClient = () => {
48
+ if (_clientError)
49
+ throw _clientError;
50
+ if (!_client) {
51
+ try {
52
+ _client = new believe_1.default({
53
+ logger,
54
+ ...params.clientOptions,
55
+ defaultHeaders: {
56
+ ...params.clientOptions?.defaultHeaders,
57
+ 'X-Stainless-MCP': 'true',
58
+ },
59
+ });
60
+ if (_logLevel) {
61
+ _client = _client.withOptions({ logLevel: _logLevel });
62
+ }
63
+ }
64
+ catch (e) {
65
+ _clientError = e instanceof Error ? e : new Error(String(e));
66
+ throw _clientError;
67
+ }
68
+ }
69
+ return _client;
70
+ };
78
71
  const providedTools = selectTools(params.mcpOptions);
79
72
  const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool]));
80
73
  server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
@@ -88,28 +81,55 @@ async function initMcpServer(params) {
88
81
  if (!mcpTool) {
89
82
  throw new Error(`Unknown tool: ${name}`);
90
83
  }
91
- return executeHandler(mcpTool.handler, client, args);
84
+ let client;
85
+ try {
86
+ client = getClient();
87
+ }
88
+ catch (error) {
89
+ return {
90
+ content: [
91
+ {
92
+ type: 'text',
93
+ text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`,
94
+ },
95
+ ],
96
+ isError: true,
97
+ };
98
+ }
99
+ return executeHandler({
100
+ handler: mcpTool.handler,
101
+ reqContext: {
102
+ client,
103
+ stainlessApiKey: params.stainlessApiKey ?? params.mcpOptions?.stainlessApiKey,
104
+ },
105
+ args,
106
+ });
92
107
  });
93
108
  server.setRequestHandler(types_js_1.SetLevelRequestSchema, async (request) => {
94
109
  const { level } = request.params;
110
+ let logLevel;
95
111
  switch (level) {
96
112
  case 'debug':
97
- client = client.withOptions({ logLevel: 'debug' });
113
+ logLevel = 'debug';
98
114
  break;
99
115
  case 'info':
100
- client = client.withOptions({ logLevel: 'info' });
116
+ logLevel = 'info';
101
117
  break;
102
118
  case 'notice':
103
119
  case 'warning':
104
- client = client.withOptions({ logLevel: 'warn' });
120
+ logLevel = 'warn';
105
121
  break;
106
122
  case 'error':
107
- client = client.withOptions({ logLevel: 'error' });
123
+ logLevel = 'error';
108
124
  break;
109
125
  default:
110
- client = client.withOptions({ logLevel: 'off' });
126
+ logLevel = 'off';
111
127
  break;
112
128
  }
129
+ _logLevel = logLevel;
130
+ if (_client) {
131
+ _client = _client.withOptions({ logLevel });
132
+ }
113
133
  return {};
114
134
  });
115
135
  }
@@ -130,7 +150,7 @@ function selectTools(options) {
130
150
  /**
131
151
  * Runs the provided handler with the given client and arguments.
132
152
  */
133
- async function executeHandler(handler, client, args) {
134
- return await handler(client, args || {});
153
+ async function executeHandler({ handler, reqContext, args, }) {
154
+ return await handler({ reqContext, args: args || {} });
135
155
  }
136
156
  //# sourceMappingURL=server.js.map
package/server.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["src/server.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;;AAsEtF,sCAwEC;AAKD,kCAUC;AAKD,wCAMC;AArKD,oEAAoE;AACpE,iEAI4C;AAE5C,+DAAuC;AACvC,8CAAuC;AACvC,6EAAgD;AAEhD,0CAAsD;AAEtD,oCAAiC;AAEjC,KAAK,UAAU,eAAe;IAC5B,0GAA0G;IAC1G,MAAM,eAAe,GAAG,IAAA,cAAO,EAAC,mBAAmB,CAAC,CAAC;IACrD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAC1B,IAAA,cAAO,EAAC,4BAA4B,CAAC,IAAI,uDAAuD,EAChG;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;AAC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B,WAAW,CAAC,OAAoB;IAC9C,MAAM,aAAa,GAAG;QACpB,IAAA,oBAAQ,EAAC;YACP,cAAc,EAAE,IAAA,mCAAyB,EAAC,OAAO,CAAC;SACnD,CAAC;KACH,CAAC;IACF,IAAI,OAAO,EAAE,gBAAgB,IAAI,IAAI,EAAE,CAAC;QACtC,aAAa,CAAC,IAAI,CAAC,0BAAc,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAED;;GAEG;AACI,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/server.mjs CHANGED
@@ -4,39 +4,13 @@ import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema, }
4
4
  import Believe from '@cjavdev/believe';
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
- 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/believe', {
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 believe 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({
9
+ export const newMcpServer = async (stainlessApiKey) => new McpServer({
36
10
  name: 'cjavdev_believe_api',
37
- version: '0.8.0',
11
+ version: '0.11.0',
38
12
  }, {
39
- instructions: await getInstructions(),
13
+ instructions: await getInstructions(stainlessApiKey),
40
14
  capabilities: { tools: {}, logging: {} },
41
15
  });
42
16
  /**
@@ -57,14 +31,33 @@ export async function initMcpServer(params) {
57
31
  warn: logAtLevel('warning'),
58
32
  error: logAtLevel('error'),
59
33
  };
60
- let client = new Believe({
61
- logger,
62
- ...params.clientOptions,
63
- defaultHeaders: {
64
- ...params.clientOptions?.defaultHeaders,
65
- 'X-Stainless-MCP': 'true',
66
- },
67
- });
34
+ let _client;
35
+ let _clientError;
36
+ let _logLevel;
37
+ const getClient = () => {
38
+ if (_clientError)
39
+ throw _clientError;
40
+ if (!_client) {
41
+ try {
42
+ _client = new Believe({
43
+ logger,
44
+ ...params.clientOptions,
45
+ defaultHeaders: {
46
+ ...params.clientOptions?.defaultHeaders,
47
+ 'X-Stainless-MCP': 'true',
48
+ },
49
+ });
50
+ if (_logLevel) {
51
+ _client = _client.withOptions({ logLevel: _logLevel });
52
+ }
53
+ }
54
+ catch (e) {
55
+ _clientError = e instanceof Error ? e : new Error(String(e));
56
+ throw _clientError;
57
+ }
58
+ }
59
+ return _client;
60
+ };
68
61
  const providedTools = selectTools(params.mcpOptions);
69
62
  const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool]));
70
63
  server.setRequestHandler(ListToolsRequestSchema, async () => {
@@ -78,28 +71,55 @@ export async function initMcpServer(params) {
78
71
  if (!mcpTool) {
79
72
  throw new Error(`Unknown tool: ${name}`);
80
73
  }
81
- return executeHandler(mcpTool.handler, client, args);
74
+ let client;
75
+ try {
76
+ client = getClient();
77
+ }
78
+ catch (error) {
79
+ return {
80
+ content: [
81
+ {
82
+ type: 'text',
83
+ text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`,
84
+ },
85
+ ],
86
+ isError: true,
87
+ };
88
+ }
89
+ return executeHandler({
90
+ handler: mcpTool.handler,
91
+ reqContext: {
92
+ client,
93
+ stainlessApiKey: params.stainlessApiKey ?? params.mcpOptions?.stainlessApiKey,
94
+ },
95
+ args,
96
+ });
82
97
  });
83
98
  server.setRequestHandler(SetLevelRequestSchema, async (request) => {
84
99
  const { level } = request.params;
100
+ let logLevel;
85
101
  switch (level) {
86
102
  case 'debug':
87
- client = client.withOptions({ logLevel: 'debug' });
103
+ logLevel = 'debug';
88
104
  break;
89
105
  case 'info':
90
- client = client.withOptions({ logLevel: 'info' });
106
+ logLevel = 'info';
91
107
  break;
92
108
  case 'notice':
93
109
  case 'warning':
94
- client = client.withOptions({ logLevel: 'warn' });
110
+ logLevel = 'warn';
95
111
  break;
96
112
  case 'error':
97
- client = client.withOptions({ logLevel: 'error' });
113
+ logLevel = 'error';
98
114
  break;
99
115
  default:
100
- client = client.withOptions({ logLevel: 'off' });
116
+ logLevel = 'off';
101
117
  break;
102
118
  }
119
+ _logLevel = logLevel;
120
+ if (_client) {
121
+ _client = _client.withOptions({ logLevel });
122
+ }
103
123
  return {};
104
124
  });
105
125
  }
@@ -120,7 +140,7 @@ export function selectTools(options) {
120
140
  /**
121
141
  * Runs the provided handler with the given client and arguments.
122
142
  */
123
- export async function executeHandler(handler, client, args) {
124
- return await handler(client, args || {});
143
+ export async function executeHandler({ handler, reqContext, args, }) {
144
+ return await handler({ reqContext, args: args || {} });
125
145
  }
126
146
  //# 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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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,8 +2,9 @@
2
2
 
3
3
  import { IncomingMessage } from 'node:http';
4
4
  import { ClientOptions } from '@cjavdev/believe';
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
  if (req.headers.authorization) {
8
9
  const scheme = req.headers.authorization.split(' ')[0]!;
9
10
  const value = req.headers.authorization.slice(scheme.length + 1);
@@ -25,3 +26,17 @@ export const parseAuthHeaders = (req: IncomingMessage, required?: boolean): Part
25
26
  : req.headers['x-believe-api-key'];
26
27
  return { apiKey };
27
28
  };
29
+
30
+ export const getStainlessApiKey = (req: IncomingMessage, mcpOptions: McpOptions): string | undefined => {
31
+ // Try to get the key from the x-stainless-api-key header
32
+ const headerKey =
33
+ Array.isArray(req.headers['x-stainless-api-key']) ?
34
+ req.headers['x-stainless-api-key'][0]
35
+ : req.headers['x-stainless-api-key'];
36
+ if (headerKey && typeof headerKey === 'string') {
37
+ return headerKey;
38
+ }
39
+
40
+ // Fall back to value set in the mcpOptions (e.g. from environment variable), if provided
41
+ return mcpOptions.stainlessApiKey;
42
+ };
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 { Believe } from '@cjavdev/believe';
9
15
 
10
16
  const prompt = `Runs JavaScript code to interact with the Believe API.
11
17
 
@@ -37,7 +43,7 @@ Variables will not persist between calls, so make sure to return or log any data
37
43
  *
38
44
  * @param endpoints - The endpoints to include in the list.
39
45
  */
40
- export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): McpTool {
46
+ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | undefined }): McpTool {
41
47
  const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
42
48
  const tool: Tool = {
43
49
  name: 'execute',
@@ -57,19 +63,24 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M
57
63
  required: ['code'],
58
64
  },
59
65
  };
60
- const handler = async (client: Believe, args: any): Promise<ToolCallResult> => {
66
+ const handler = async ({
67
+ reqContext,
68
+ args,
69
+ }: {
70
+ reqContext: McpRequestContext;
71
+ args: any;
72
+ }): Promise<ToolCallResult> => {
61
73
  const code = args.code as string;
62
74
  const intent = args.intent as string | undefined;
75
+ const client = reqContext.client;
63
76
 
64
77
  // Do very basic blocking of code that includes forbidden method names.
65
78
  //
66
79
  // WARNING: This is not secure against obfuscation and other evasion methods. If
67
80
  // stronger security blocks are required, then these should be enforced in the downstream
68
81
  // API (e.g., by having users call the MCP server with API keys with limited permissions).
69
- if (params.blockedMethods) {
70
- const blockedMatches = params.blockedMethods.filter((method) =>
71
- code.includes(method.fullyQualifiedName),
72
- );
82
+ if (blockedMethods) {
83
+ const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
73
84
  if (blockedMatches.length > 0) {
74
85
  return asErrorResult(
75
86
  `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
@@ -79,16 +90,14 @@ export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): M
79
90
  }
80
91
  }
81
92
 
82
- // this is not required, but passing a Stainless API key for the matching project_name
83
- // will allow you to run code-mode queries against non-published versions of your SDK.
84
- const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
85
93
  const codeModeEndpoint =
86
94
  readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
87
95
 
96
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
88
97
  const res = await fetch(codeModeEndpoint, {
89
98
  method: 'POST',
90
99
  headers: {
91
- ...(stainlessAPIKey && { Authorization: stainlessAPIKey }),
100
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
92
101
  'Content-Type': 'application/json',
93
102
  client_envs: JSON.stringify({
94
103
  BELIEVE_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/believe/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 '@cjavdev/believe';
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/believe',
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 believe 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
+ }