context.dev-mcp 0.1.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 (144) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +101 -0
  3. package/auth.d.mts +6 -0
  4. package/auth.d.mts.map +1 -0
  5. package/auth.d.ts +6 -0
  6. package/auth.d.ts.map +1 -0
  7. package/auth.js +37 -0
  8. package/auth.js.map +1 -0
  9. package/auth.mjs +32 -0
  10. package/auth.mjs.map +1 -0
  11. package/code-tool-paths.cjs +8 -0
  12. package/code-tool-paths.cjs.map +1 -0
  13. package/code-tool-paths.d.cts +2 -0
  14. package/code-tool-paths.d.cts.map +1 -0
  15. package/code-tool-types.d.mts +14 -0
  16. package/code-tool-types.d.mts.map +1 -0
  17. package/code-tool-types.d.ts +14 -0
  18. package/code-tool-types.d.ts.map +1 -0
  19. package/code-tool-types.js +4 -0
  20. package/code-tool-types.js.map +1 -0
  21. package/code-tool-types.mjs +3 -0
  22. package/code-tool-types.mjs.map +1 -0
  23. package/code-tool-worker.d.mts +5 -0
  24. package/code-tool-worker.d.mts.map +1 -0
  25. package/code-tool-worker.d.ts +5 -0
  26. package/code-tool-worker.d.ts.map +1 -0
  27. package/code-tool-worker.js +244 -0
  28. package/code-tool-worker.js.map +1 -0
  29. package/code-tool-worker.mjs +239 -0
  30. package/code-tool-worker.mjs.map +1 -0
  31. package/code-tool.d.mts +21 -0
  32. package/code-tool.d.mts.map +1 -0
  33. package/code-tool.d.ts +21 -0
  34. package/code-tool.d.ts.map +1 -0
  35. package/code-tool.js +337 -0
  36. package/code-tool.js.map +1 -0
  37. package/code-tool.mjs +301 -0
  38. package/code-tool.mjs.map +1 -0
  39. package/docs-search-tool.d.mts +57 -0
  40. package/docs-search-tool.d.mts.map +1 -0
  41. package/docs-search-tool.d.ts +57 -0
  42. package/docs-search-tool.d.ts.map +1 -0
  43. package/docs-search-tool.js +74 -0
  44. package/docs-search-tool.js.map +1 -0
  45. package/docs-search-tool.mjs +70 -0
  46. package/docs-search-tool.mjs.map +1 -0
  47. package/http.d.mts +12 -0
  48. package/http.d.mts.map +1 -0
  49. package/http.d.ts +12 -0
  50. package/http.d.ts.map +1 -0
  51. package/http.js +142 -0
  52. package/http.js.map +1 -0
  53. package/http.mjs +134 -0
  54. package/http.mjs.map +1 -0
  55. package/index.d.mts +3 -0
  56. package/index.d.mts.map +1 -0
  57. package/index.d.ts +3 -0
  58. package/index.d.ts.map +1 -0
  59. package/index.js +60 -0
  60. package/index.js.map +1 -0
  61. package/index.mjs +58 -0
  62. package/index.mjs.map +1 -0
  63. package/instructions.d.mts +2 -0
  64. package/instructions.d.mts.map +1 -0
  65. package/instructions.d.ts +2 -0
  66. package/instructions.d.ts.map +1 -0
  67. package/instructions.js +42 -0
  68. package/instructions.js.map +1 -0
  69. package/instructions.mjs +39 -0
  70. package/instructions.mjs.map +1 -0
  71. package/logger.d.mts +7 -0
  72. package/logger.d.mts.map +1 -0
  73. package/logger.d.ts +7 -0
  74. package/logger.d.ts.map +1 -0
  75. package/logger.js +29 -0
  76. package/logger.js.map +1 -0
  77. package/logger.mjs +22 -0
  78. package/logger.mjs.map +1 -0
  79. package/methods.d.mts +10 -0
  80. package/methods.d.mts.map +1 -0
  81. package/methods.d.ts +10 -0
  82. package/methods.d.ts.map +1 -0
  83. package/methods.js +185 -0
  84. package/methods.js.map +1 -0
  85. package/methods.mjs +181 -0
  86. package/methods.mjs.map +1 -0
  87. package/options.d.mts +20 -0
  88. package/options.d.mts.map +1 -0
  89. package/options.d.ts +20 -0
  90. package/options.d.ts.map +1 -0
  91. package/options.js +122 -0
  92. package/options.js.map +1 -0
  93. package/options.mjs +115 -0
  94. package/options.mjs.map +1 -0
  95. package/package.json +225 -0
  96. package/server.d.mts +30 -0
  97. package/server.d.mts.map +1 -0
  98. package/server.d.ts +30 -0
  99. package/server.d.ts.map +1 -0
  100. package/server.js +159 -0
  101. package/server.js.map +1 -0
  102. package/server.mjs +149 -0
  103. package/server.mjs.map +1 -0
  104. package/src/auth.ts +42 -0
  105. package/src/code-tool-paths.cts +5 -0
  106. package/src/code-tool-types.ts +17 -0
  107. package/src/code-tool-worker.ts +290 -0
  108. package/src/code-tool.ts +396 -0
  109. package/src/docs-search-tool.ts +100 -0
  110. package/src/http.ts +173 -0
  111. package/src/index.ts +67 -0
  112. package/src/instructions.ts +60 -0
  113. package/src/logger.ts +28 -0
  114. package/src/methods.ts +206 -0
  115. package/src/options.ts +161 -0
  116. package/src/server.ts +190 -0
  117. package/src/stdio.ts +14 -0
  118. package/src/tsconfig.json +11 -0
  119. package/src/types.ts +124 -0
  120. package/src/util.ts +25 -0
  121. package/stdio.d.mts +3 -0
  122. package/stdio.d.mts.map +1 -0
  123. package/stdio.d.ts +3 -0
  124. package/stdio.d.ts.map +1 -0
  125. package/stdio.js +15 -0
  126. package/stdio.js.map +1 -0
  127. package/stdio.mjs +11 -0
  128. package/stdio.mjs.map +1 -0
  129. package/types.d.mts +60 -0
  130. package/types.d.mts.map +1 -0
  131. package/types.d.ts +60 -0
  132. package/types.d.ts.map +1 -0
  133. package/types.js +58 -0
  134. package/types.js.map +1 -0
  135. package/types.mjs +53 -0
  136. package/types.mjs.map +1 -0
  137. package/util.d.mts +4 -0
  138. package/util.d.mts.map +1 -0
  139. package/util.d.ts +4 -0
  140. package/util.d.ts.map +1 -0
  141. package/util.js +30 -0
  142. package/util.js.map +1 -0
  143. package/util.mjs +24 -0
  144. package/util.mjs.map +1 -0
@@ -0,0 +1,17 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import { ClientOptions } from 'context.dev';
4
+
5
+ export type WorkerInput = {
6
+ project_name: string;
7
+ code: string;
8
+ client_opts: ClientOptions;
9
+ intent?: string | undefined;
10
+ };
11
+
12
+ export type WorkerOutput = {
13
+ is_error: boolean;
14
+ result: unknown | null;
15
+ log_lines: string[];
16
+ err_lines: string[];
17
+ };
@@ -0,0 +1,290 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import path from 'node:path';
4
+ import util from 'node:util';
5
+ import Fuse from 'fuse.js';
6
+ import ts from 'typescript';
7
+ import { WorkerOutput } from './code-tool-types';
8
+ import { ContextDev, ClientOptions } from 'context.dev';
9
+
10
+ function getRunFunctionSource(code: string): {
11
+ type: 'declaration' | 'expression';
12
+ client: string | undefined;
13
+ code: string;
14
+ } | null {
15
+ const sourceFile = ts.createSourceFile('code.ts', code, ts.ScriptTarget.Latest, true);
16
+ const printer = ts.createPrinter();
17
+
18
+ for (const statement of sourceFile.statements) {
19
+ // Check for top-level function declarations
20
+ if (ts.isFunctionDeclaration(statement)) {
21
+ if (statement.name?.text === 'run') {
22
+ return {
23
+ type: 'declaration',
24
+ client: statement.parameters[0]?.name.getText(),
25
+ code: printer.printNode(ts.EmitHint.Unspecified, statement.body!, sourceFile),
26
+ };
27
+ }
28
+ }
29
+
30
+ // Check for variable declarations: const run = () => {} or const run = function() {}
31
+ if (ts.isVariableStatement(statement)) {
32
+ for (const declaration of statement.declarationList.declarations) {
33
+ if (
34
+ ts.isIdentifier(declaration.name) &&
35
+ declaration.name.text === 'run' &&
36
+ // Check if it's initialized with a function
37
+ declaration.initializer &&
38
+ (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer))
39
+ ) {
40
+ return {
41
+ type: 'expression',
42
+ client: declaration.initializer.parameters[0]?.name.getText(),
43
+ code: printer.printNode(ts.EmitHint.Unspecified, declaration.initializer, sourceFile),
44
+ };
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ return null;
51
+ }
52
+
53
+ function getTSDiagnostics(code: string): string[] {
54
+ const functionSource = getRunFunctionSource(code)!;
55
+ const codeWithImport = [
56
+ 'import { ContextDev } from "context.dev";',
57
+ functionSource.type === 'declaration' ?
58
+ `async function run(${functionSource.client}: ContextDev)`
59
+ : `const run: (${functionSource.client}: ContextDev) => Promise<unknown> =`,
60
+ functionSource.code,
61
+ ].join('\n');
62
+ const sourcePath = path.resolve('code.ts');
63
+ const ast = ts.createSourceFile(sourcePath, codeWithImport, ts.ScriptTarget.Latest, true);
64
+ const options = ts.getDefaultCompilerOptions();
65
+ options.target = ts.ScriptTarget.Latest;
66
+ options.module = ts.ModuleKind.NodeNext;
67
+ options.moduleResolution = ts.ModuleResolutionKind.NodeNext;
68
+ const host = ts.createCompilerHost(options, true);
69
+ const newHost: typeof host = {
70
+ ...host,
71
+ getSourceFile: (...args) => {
72
+ if (path.resolve(args[0]) === sourcePath) {
73
+ return ast;
74
+ }
75
+ return host.getSourceFile(...args);
76
+ },
77
+ readFile: (...args) => {
78
+ if (path.resolve(args[0]) === sourcePath) {
79
+ return codeWithImport;
80
+ }
81
+ return host.readFile(...args);
82
+ },
83
+ fileExists: (...args) => {
84
+ if (path.resolve(args[0]) === sourcePath) {
85
+ return true;
86
+ }
87
+ return host.fileExists(...args);
88
+ },
89
+ };
90
+ const program = ts.createProgram({
91
+ options,
92
+ rootNames: [sourcePath],
93
+ host: newHost,
94
+ });
95
+ const diagnostics = ts.getPreEmitDiagnostics(program, ast);
96
+ return diagnostics.map((d) => {
97
+ const message = ts.flattenDiagnosticMessageText(d.messageText, '\n');
98
+ if (!d.file || !d.start) return `- ${message}`;
99
+ const { line: lineNumber } = ts.getLineAndCharacterOfPosition(d.file, d.start);
100
+ const line = codeWithImport.split('\n').at(lineNumber)?.trim();
101
+ return line ? `- ${message}\n ${line}` : `- ${message}`;
102
+ });
103
+ }
104
+
105
+ const fuse = new Fuse(
106
+ [
107
+ 'client.brand.aiProduct',
108
+ 'client.brand.aiProducts',
109
+ 'client.brand.aiQuery',
110
+ 'client.brand.fonts',
111
+ 'client.brand.identifyFromTransaction',
112
+ 'client.brand.prefetch',
113
+ 'client.brand.prefetchByEmail',
114
+ 'client.brand.retrieve',
115
+ 'client.brand.retrieveByEmail',
116
+ 'client.brand.retrieveByIsin',
117
+ 'client.brand.retrieveByName',
118
+ 'client.brand.retrieveByTicker',
119
+ 'client.brand.retrieveNaics',
120
+ 'client.brand.retrieveSimplified',
121
+ 'client.brand.screenshot',
122
+ 'client.brand.styleguide',
123
+ 'client.brand.webScrapeHTML',
124
+ 'client.brand.webScrapeImages',
125
+ 'client.brand.webScrapeMd',
126
+ 'client.brand.webScrapeSitemap',
127
+ ],
128
+ { threshold: 1, shouldSort: true },
129
+ );
130
+
131
+ function getMethodSuggestions(fullyQualifiedMethodName: string): string[] {
132
+ return fuse
133
+ .search(fullyQualifiedMethodName)
134
+ .map(({ item }) => item)
135
+ .slice(0, 5);
136
+ }
137
+
138
+ const proxyToObj = new WeakMap<any, any>();
139
+ const objToProxy = new WeakMap<any, any>();
140
+
141
+ type ClientProxyConfig = {
142
+ path: string[];
143
+ isBelievedBad?: boolean;
144
+ };
145
+
146
+ function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }: ClientProxyConfig): T {
147
+ let proxy: T = objToProxy.get(obj);
148
+
149
+ if (!proxy) {
150
+ proxy = new Proxy(obj, {
151
+ get(target, prop, receiver) {
152
+ const propPath = [...path, String(prop)];
153
+ const value = Reflect.get(target, prop, receiver);
154
+
155
+ if (isBelievedBad || (!(prop in target) && value === undefined)) {
156
+ // If we're accessing a path that doesn't exist, it will probably eventually error.
157
+ // Let's proxy it and mark it bad so that we can control the error message.
158
+ // We proxy an empty class so that an invocation or construction attempt is possible.
159
+ return makeSdkProxy(class {}, { path: propPath, isBelievedBad: true });
160
+ }
161
+
162
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
163
+ return makeSdkProxy(value, { path: propPath, isBelievedBad });
164
+ }
165
+
166
+ return value;
167
+ },
168
+
169
+ apply(target, thisArg, args) {
170
+ if (isBelievedBad || typeof target !== 'function') {
171
+ const fullyQualifiedMethodName = path.join('.');
172
+ const suggestions = getMethodSuggestions(fullyQualifiedMethodName);
173
+ throw new Error(
174
+ `${fullyQualifiedMethodName} is not a function. Did you mean: ${suggestions.join(', ')}`,
175
+ );
176
+ }
177
+
178
+ return Reflect.apply(target, proxyToObj.get(thisArg) ?? thisArg, args);
179
+ },
180
+
181
+ construct(target, args, newTarget) {
182
+ if (isBelievedBad || typeof target !== 'function') {
183
+ const fullyQualifiedMethodName = path.join('.');
184
+ const suggestions = getMethodSuggestions(fullyQualifiedMethodName);
185
+ throw new Error(
186
+ `${fullyQualifiedMethodName} is not a constructor. Did you mean: ${suggestions.join(', ')}`,
187
+ );
188
+ }
189
+
190
+ return Reflect.construct(target, args, newTarget);
191
+ },
192
+ });
193
+
194
+ objToProxy.set(obj, proxy);
195
+ proxyToObj.set(proxy, obj);
196
+ }
197
+
198
+ return proxy;
199
+ }
200
+
201
+ function parseError(code: string, error: unknown): string | undefined {
202
+ if (!(error instanceof Error)) return;
203
+ const message = error.name ? `${error.name}: ${error.message}` : error.message;
204
+ try {
205
+ // Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
206
+ const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
207
+ // -1 for the zero-based indexing
208
+ const line =
209
+ lineNumber &&
210
+ code
211
+ .split('\n')
212
+ .at(parseInt(lineNumber, 10) - 1)
213
+ ?.trim();
214
+ return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
215
+ } catch {
216
+ return message;
217
+ }
218
+ }
219
+
220
+ const fetch = async (req: Request): Promise<Response> => {
221
+ const { opts, code } = (await req.json()) as { opts: ClientOptions; code: string };
222
+
223
+ const runFunctionSource = code ? getRunFunctionSource(code) : null;
224
+ if (!runFunctionSource) {
225
+ const message =
226
+ code ?
227
+ 'The code is missing a top-level `run` function.'
228
+ : 'The code argument is missing. Provide one containing a top-level `run` function.';
229
+ return Response.json(
230
+ {
231
+ is_error: true,
232
+ result: `${message} Write code within this template:\n\n\`\`\`\nasync function run(client) {\n // Fill this out\n}\n\`\`\``,
233
+ log_lines: [],
234
+ err_lines: [],
235
+ } satisfies WorkerOutput,
236
+ { status: 400, statusText: 'Code execution error' },
237
+ );
238
+ }
239
+
240
+ const diagnostics = getTSDiagnostics(code);
241
+ if (diagnostics.length > 0) {
242
+ return Response.json(
243
+ {
244
+ is_error: true,
245
+ result: `The code contains TypeScript diagnostics:\n${diagnostics.join('\n')}`,
246
+ log_lines: [],
247
+ err_lines: [],
248
+ } satisfies WorkerOutput,
249
+ { status: 400, statusText: 'Code execution error' },
250
+ );
251
+ }
252
+
253
+ const client = new ContextDev({
254
+ ...opts,
255
+ });
256
+
257
+ const log_lines: string[] = [];
258
+ const err_lines: string[] = [];
259
+ const console = {
260
+ log: (...args: unknown[]) => {
261
+ log_lines.push(util.format(...args));
262
+ },
263
+ error: (...args: unknown[]) => {
264
+ err_lines.push(util.format(...args));
265
+ },
266
+ };
267
+ try {
268
+ let run_ = async (client: any) => {};
269
+ eval(`${code}\nrun_ = run;`);
270
+ const result = await run_(makeSdkProxy(client, { path: ['client'] }));
271
+ return Response.json({
272
+ is_error: false,
273
+ result,
274
+ log_lines,
275
+ err_lines,
276
+ } satisfies WorkerOutput);
277
+ } catch (e) {
278
+ return Response.json(
279
+ {
280
+ is_error: true,
281
+ result: parseError(code, e),
282
+ log_lines,
283
+ err_lines,
284
+ } satisfies WorkerOutput,
285
+ { status: 400, statusText: 'Code execution error' },
286
+ );
287
+ }
288
+ };
289
+
290
+ export default { fetch };
@@ -0,0 +1,396 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import {
4
+ ContentBlock,
5
+ McpRequestContext,
6
+ McpTool,
7
+ Metadata,
8
+ ToolCallResult,
9
+ asErrorResult,
10
+ asTextContentResult,
11
+ } from './types';
12
+ import { Tool } from '@modelcontextprotocol/sdk/types.js';
13
+ import { readEnv, requireValue } from './util';
14
+ import { WorkerInput, WorkerOutput } from './code-tool-types';
15
+ import { getLogger } from './logger';
16
+ import { SdkMethod } from './methods';
17
+ import { McpCodeExecutionMode } from './options';
18
+ import { ClientOptions } from 'context.dev';
19
+
20
+ const prompt = `Runs JavaScript code to interact with the Context Dev API.
21
+
22
+ You are a skilled TypeScript programmer writing code to interface with the service.
23
+ Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
24
+ For example:
25
+
26
+ \`\`\`
27
+ async function run(client) {
28
+ const brand = await client.brand.retrieve({ domain: 'REPLACE_ME' });
29
+
30
+ console.log(brand.brand);
31
+ }
32
+ \`\`\`
33
+
34
+ You will be returned anything that your function returns, plus the results of any console.log statements.
35
+ Do not add try-catch blocks for single API calls. The tool will handle errors for you.
36
+ Do not add comments unless necessary for generating better code.
37
+ Code will run in a container, and cannot interact with the network outside of the given SDK client.
38
+ Variables will not persist between calls, so make sure to return or log any data you might need later.
39
+ Remember that you are writing TypeScript code, so you need to be careful with your types.
40
+ Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
41
+
42
+ /**
43
+ * A tool that runs code against a copy of the SDK.
44
+ *
45
+ * Instead of exposing every endpoint as its own tool, which uses up too many tokens for LLMs to use at once,
46
+ * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
47
+ * a generic endpoint that can be used to invoke any endpoint with the provided arguments.
48
+ *
49
+ * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
50
+ * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
51
+ * with limited API keys.
52
+ * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
53
+ * sandbox environment hosted by Stainless.
54
+ */
55
+ export function codeTool({
56
+ blockedMethods,
57
+ codeExecutionMode,
58
+ }: {
59
+ blockedMethods: SdkMethod[] | undefined;
60
+ codeExecutionMode: McpCodeExecutionMode;
61
+ }): McpTool {
62
+ const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
63
+ const tool: Tool = {
64
+ name: 'execute',
65
+ description: prompt,
66
+ inputSchema: {
67
+ type: 'object',
68
+ properties: {
69
+ code: {
70
+ type: 'string',
71
+ description: 'Code to execute.',
72
+ },
73
+ intent: {
74
+ type: 'string',
75
+ description: 'Task you are trying to perform. Used for improving the service.',
76
+ },
77
+ },
78
+ required: ['code'],
79
+ },
80
+ };
81
+
82
+ const logger = getLogger();
83
+
84
+ const handler = async ({
85
+ reqContext,
86
+ args,
87
+ }: {
88
+ reqContext: McpRequestContext;
89
+ args: any;
90
+ }): Promise<ToolCallResult> => {
91
+ const code = args.code as string;
92
+ // Do very basic blocking of code that includes forbidden method names.
93
+ //
94
+ // WARNING: This is not secure against obfuscation and other evasion methods. If
95
+ // stronger security blocks are required, then these should be enforced in the downstream
96
+ // API (e.g., by having users call the MCP server with API keys with limited permissions).
97
+ if (blockedMethods) {
98
+ const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
99
+ if (blockedMatches.length > 0) {
100
+ return asErrorResult(
101
+ `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
102
+ .map((m) => m.fullyQualifiedName)
103
+ .join(', ')}`,
104
+ );
105
+ }
106
+ }
107
+
108
+ let result: ToolCallResult;
109
+ const startTime = Date.now();
110
+
111
+ if (codeExecutionMode === 'local') {
112
+ logger.debug('Executing code in local Deno environment');
113
+ result = await localDenoHandler({ reqContext, args });
114
+ } else {
115
+ logger.debug('Executing code in remote Stainless environment');
116
+ result = await remoteStainlessHandler({ reqContext, args });
117
+ }
118
+
119
+ logger.info(
120
+ {
121
+ codeExecutionMode,
122
+ durationMs: Date.now() - startTime,
123
+ isError: result.isError,
124
+ contentRows: result.content?.length ?? 0,
125
+ },
126
+ 'Got code tool execution result',
127
+ );
128
+ return result;
129
+ };
130
+
131
+ return { metadata, tool, handler };
132
+ }
133
+
134
+ const remoteStainlessHandler = async ({
135
+ reqContext,
136
+ args,
137
+ }: {
138
+ reqContext: McpRequestContext;
139
+ args: any;
140
+ }): Promise<ToolCallResult> => {
141
+ const code = args.code as string;
142
+ const intent = args.intent as string | undefined;
143
+ const client = reqContext.client;
144
+
145
+ const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
146
+
147
+ const localClientEnvs = {
148
+ CONTEXT_DEV_API_KEY: requireValue(
149
+ readEnv('CONTEXT_DEV_API_KEY') ?? client.apiKey,
150
+ 'set CONTEXT_DEV_API_KEY environment variable or provide apiKey client option',
151
+ ),
152
+ CONTEXT_DEV_BASE_URL: readEnv('CONTEXT_DEV_BASE_URL') ?? client.baseURL ?? undefined,
153
+ };
154
+ // Merge any upstream client envs from the request header, with upstream values taking precedence.
155
+ const mergedClientEnvs = { ...localClientEnvs, ...reqContext.upstreamClientEnvs };
156
+
157
+ // Setting a Stainless API key authenticates requests to the code tool endpoint.
158
+ const res = await fetch(codeModeEndpoint, {
159
+ method: 'POST',
160
+ headers: {
161
+ ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
162
+ 'Content-Type': 'application/json',
163
+ 'x-stainless-mcp-client-envs': JSON.stringify(mergedClientEnvs),
164
+ },
165
+ body: JSON.stringify({
166
+ project_name: 'context.dev',
167
+ code,
168
+ intent,
169
+ client_opts: {},
170
+ } satisfies WorkerInput),
171
+ });
172
+
173
+ if (!res.ok) {
174
+ if (res.status === 404 && !reqContext.stainlessApiKey) {
175
+ throw new Error(
176
+ '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.',
177
+ );
178
+ }
179
+ throw new Error(
180
+ `${res.status}: ${
181
+ res.statusText
182
+ } error when trying to contact Code Tool server. Details: ${await res.text()}`,
183
+ );
184
+ }
185
+
186
+ const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
187
+ const hasLogs = log_lines.length > 0 || err_lines.length > 0;
188
+ const output = {
189
+ result,
190
+ ...(log_lines.length > 0 && { log_lines }),
191
+ ...(err_lines.length > 0 && { err_lines }),
192
+ };
193
+ if (is_error) {
194
+ return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
195
+ }
196
+ return asTextContentResult(output);
197
+ };
198
+
199
+ const localDenoHandler = async ({
200
+ reqContext,
201
+ args,
202
+ }: {
203
+ reqContext: McpRequestContext;
204
+ args: unknown;
205
+ }): Promise<ToolCallResult> => {
206
+ const fs = await import('node:fs');
207
+ const path = await import('node:path');
208
+ const url = await import('node:url');
209
+ const { newDenoHTTPWorker } = await import('@valtown/deno-http-worker');
210
+ const { getWorkerPath } = await import('./code-tool-paths.cjs');
211
+ const workerPath = getWorkerPath();
212
+
213
+ const client = reqContext.client;
214
+ const baseURLHostname = new URL(client.baseURL).hostname;
215
+ const { code } = args as { code: string };
216
+
217
+ let denoPath: string;
218
+
219
+ const packageRoot = path.resolve(path.dirname(workerPath), '..');
220
+ const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
221
+
222
+ // Check if deno is in PATH
223
+ const { execSync } = await import('node:child_process');
224
+ try {
225
+ execSync('command -v deno', { stdio: 'ignore' });
226
+ denoPath = 'deno';
227
+ } catch {
228
+ try {
229
+ // Use deno binary in node_modules if it's found
230
+ const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
231
+ await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
232
+ denoPath = denoNodeModulesPath;
233
+ } catch {
234
+ return asErrorResult(
235
+ 'Deno is required for code execution but was not found. ' +
236
+ 'Install it from https://deno.land or run: npm install deno',
237
+ );
238
+ }
239
+ }
240
+
241
+ const allowReadPaths = [
242
+ 'code-tool-worker.mjs',
243
+ `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
244
+ packageRoot,
245
+ ];
246
+
247
+ // Follow symlinks in node_modules to allow read access to workspace-linked packages
248
+ try {
249
+ const sdkPkgName = 'context.dev';
250
+ const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
251
+ const realSdkDir = fs.realpathSync(sdkDir);
252
+ if (realSdkDir !== sdkDir) {
253
+ allowReadPaths.push(realSdkDir);
254
+ }
255
+ } catch {
256
+ // Ignore if symlink resolution fails
257
+ }
258
+
259
+ const allowRead = allowReadPaths.join(',');
260
+
261
+ const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
262
+ denoExecutable: denoPath,
263
+ runFlags: [
264
+ `--node-modules-dir=manual`,
265
+ `--allow-read=${allowRead}`,
266
+ `--allow-net=${baseURLHostname}`,
267
+ // Allow environment variables because instantiating the client will try to read from them,
268
+ // even though they are not set.
269
+ '--allow-env',
270
+ ],
271
+ printOutput: true,
272
+ spawnOptions: {
273
+ cwd: path.dirname(workerPath),
274
+ // Merge any upstream client envs into the Deno subprocess environment,
275
+ // with the upstream env vars taking precedence.
276
+ env: { ...process.env, ...reqContext.upstreamClientEnvs },
277
+ },
278
+ });
279
+
280
+ try {
281
+ const resp = await new Promise<Response>((resolve, reject) => {
282
+ worker.addEventListener('exit', (exitCode) => {
283
+ reject(new Error(`Worker exited with code ${exitCode}`));
284
+ });
285
+
286
+ // Strip null/undefined values so that the worker SDK client can fall back to
287
+ // reading from environment variables (including any upstreamClientEnvs).
288
+ const opts: ClientOptions = Object.fromEntries(
289
+ Object.entries({
290
+ baseURL: client.baseURL,
291
+ apiKey: client.apiKey,
292
+ defaultHeaders: {
293
+ 'X-Stainless-MCP': 'true',
294
+ },
295
+ }).filter(([_, v]) => v != null),
296
+ ) as ClientOptions;
297
+
298
+ const req = worker.request(
299
+ 'http://localhost',
300
+ {
301
+ headers: {
302
+ 'content-type': 'application/json',
303
+ },
304
+ method: 'POST',
305
+ },
306
+ (resp) => {
307
+ const body: Uint8Array[] = [];
308
+ resp.on('error', (err) => {
309
+ reject(err);
310
+ });
311
+ resp.on('data', (chunk) => {
312
+ body.push(chunk);
313
+ });
314
+ resp.on('end', () => {
315
+ resolve(
316
+ new Response(Buffer.concat(body).toString(), {
317
+ status: resp.statusCode ?? 200,
318
+ headers: resp.headers as any,
319
+ }),
320
+ );
321
+ });
322
+ },
323
+ );
324
+
325
+ const body = JSON.stringify({
326
+ opts,
327
+ code,
328
+ });
329
+
330
+ req.write(body, (err) => {
331
+ if (err != null) {
332
+ reject(err);
333
+ }
334
+ });
335
+
336
+ req.end();
337
+ });
338
+
339
+ if (resp.status === 200) {
340
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
341
+ const returnOutput: ContentBlock | null =
342
+ result == null ? null : (
343
+ {
344
+ type: 'text',
345
+ text: typeof result === 'string' ? result : JSON.stringify(result),
346
+ }
347
+ );
348
+ const logOutput: ContentBlock | null =
349
+ log_lines.length === 0 ?
350
+ null
351
+ : {
352
+ type: 'text',
353
+ text: log_lines.join('\n'),
354
+ };
355
+ const errOutput: ContentBlock | null =
356
+ err_lines.length === 0 ?
357
+ null
358
+ : {
359
+ type: 'text',
360
+ text: 'Error output:\n' + err_lines.join('\n'),
361
+ };
362
+ return {
363
+ content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
364
+ };
365
+ } else {
366
+ const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
367
+ const messageOutput: ContentBlock | null =
368
+ result == null ? null : (
369
+ {
370
+ type: 'text',
371
+ text: typeof result === 'string' ? result : JSON.stringify(result),
372
+ }
373
+ );
374
+ const logOutput: ContentBlock | null =
375
+ log_lines.length === 0 ?
376
+ null
377
+ : {
378
+ type: 'text',
379
+ text: log_lines.join('\n'),
380
+ };
381
+ const errOutput: ContentBlock | null =
382
+ err_lines.length === 0 ?
383
+ null
384
+ : {
385
+ type: 'text',
386
+ text: 'Error output:\n' + err_lines.join('\n'),
387
+ };
388
+ return {
389
+ content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
390
+ isError: true,
391
+ };
392
+ }
393
+ } finally {
394
+ worker.terminate();
395
+ }
396
+ };