@roarkanalytics/sdk-mcp 2.24.0 → 2.26.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.
- package/code-tool-paths.cjs +6 -0
- package/code-tool-paths.cjs.map +1 -0
- package/code-tool-paths.d.cts +2 -0
- package/code-tool-paths.d.cts.map +1 -0
- package/code-tool-types.d.mts.map +1 -1
- package/code-tool-types.d.ts.map +1 -1
- package/code-tool-worker.d.mts +5 -0
- package/code-tool-worker.d.mts.map +1 -0
- package/code-tool-worker.d.ts +5 -0
- package/code-tool-worker.d.ts.map +1 -0
- package/code-tool-worker.js +277 -0
- package/code-tool-worker.js.map +1 -0
- package/code-tool-worker.mjs +272 -0
- package/code-tool-worker.mjs.map +1 -0
- package/code-tool.d.mts +8 -2
- package/code-tool.d.mts.map +1 -1
- package/code-tool.d.ts +8 -2
- package/code-tool.d.ts.map +1 -1
- package/code-tool.js +240 -35
- package/code-tool.js.map +1 -1
- package/code-tool.mjs +204 -35
- package/code-tool.mjs.map +1 -1
- package/methods.d.mts.map +1 -1
- package/methods.d.ts.map +1 -1
- package/methods.js +54 -0
- package/methods.js.map +1 -1
- package/methods.mjs +54 -0
- package/methods.mjs.map +1 -1
- package/options.d.mts +2 -0
- package/options.d.mts.map +1 -1
- package/options.d.ts +2 -0
- package/options.d.ts.map +1 -1
- package/options.js +8 -0
- package/options.js.map +1 -1
- package/options.mjs +8 -0
- package/options.mjs.map +1 -1
- package/package.json +18 -2
- package/server.d.mts.map +1 -1
- package/server.d.ts.map +1 -1
- package/server.js +2 -1
- package/server.js.map +1 -1
- package/server.mjs +2 -1
- package/server.mjs.map +1 -1
- package/src/code-tool-paths.cts +3 -0
- package/src/code-tool-types.ts +1 -0
- package/src/code-tool-worker.ts +323 -0
- package/src/code-tool.ts +265 -47
- package/src/methods.ts +54 -0
- package/src/options.ts +12 -0
- package/src/server.ts +2 -1
|
@@ -0,0 +1,323 @@
|
|
|
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 { Roark, ClientOptions } from '@roarkanalytics/sdk';
|
|
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 { Roark } from "@roarkanalytics/sdk";',
|
|
57
|
+
functionSource.type === 'declaration' ?
|
|
58
|
+
`async function run(${functionSource.client}: Roark)`
|
|
59
|
+
: `const run: (${functionSource.client}: Roark) => 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.health.get',
|
|
108
|
+
'client.call.create',
|
|
109
|
+
'client.call.getByID',
|
|
110
|
+
'client.call.getTranscript',
|
|
111
|
+
'client.call.list',
|
|
112
|
+
'client.call.listEvaluationRuns',
|
|
113
|
+
'client.call.listMetrics',
|
|
114
|
+
'client.call.listSentimentRuns',
|
|
115
|
+
'client.metric.createDefinition',
|
|
116
|
+
'client.metric.listDefinitions',
|
|
117
|
+
'client.metricPolicy.create',
|
|
118
|
+
'client.metricPolicy.delete',
|
|
119
|
+
'client.metricPolicy.getByID',
|
|
120
|
+
'client.metricPolicy.list',
|
|
121
|
+
'client.metricPolicy.update',
|
|
122
|
+
'client.metricCollectionJob.create',
|
|
123
|
+
'client.metricCollectionJob.getByID',
|
|
124
|
+
'client.metricCollectionJob.list',
|
|
125
|
+
'client.simulationJob.getByID',
|
|
126
|
+
'client.simulationJob.lookup',
|
|
127
|
+
'client.simulationRunPlan.create',
|
|
128
|
+
'client.simulationRunPlan.delete',
|
|
129
|
+
'client.simulationRunPlan.getByID',
|
|
130
|
+
'client.simulationRunPlan.list',
|
|
131
|
+
'client.simulationRunPlan.update',
|
|
132
|
+
'client.simulationRunPlanJob.getByID',
|
|
133
|
+
'client.simulationRunPlanJob.list',
|
|
134
|
+
'client.simulationRunPlanJob.start',
|
|
135
|
+
'client.simulationScenario.create',
|
|
136
|
+
'client.simulationScenario.delete',
|
|
137
|
+
'client.simulationScenario.getByID',
|
|
138
|
+
'client.simulationScenario.list',
|
|
139
|
+
'client.simulationScenario.update',
|
|
140
|
+
'client.simulationPersona.create',
|
|
141
|
+
'client.simulationPersona.getByID',
|
|
142
|
+
'client.simulationPersona.list',
|
|
143
|
+
'client.simulationPersona.update',
|
|
144
|
+
'client.agent.create',
|
|
145
|
+
'client.agent.getByID',
|
|
146
|
+
'client.agent.list',
|
|
147
|
+
'client.agent.update',
|
|
148
|
+
'client.agentEndpoint.create',
|
|
149
|
+
'client.agentEndpoint.getByID',
|
|
150
|
+
'client.agentEndpoint.list',
|
|
151
|
+
'client.agentEndpoint.update',
|
|
152
|
+
'client.httpRequestDefinition.create',
|
|
153
|
+
'client.httpRequestDefinition.getByID',
|
|
154
|
+
'client.httpRequestDefinition.list',
|
|
155
|
+
'client.httpRequestDefinition.update',
|
|
156
|
+
'client.webhook.create',
|
|
157
|
+
'client.webhook.delete',
|
|
158
|
+
'client.webhook.getByID',
|
|
159
|
+
'client.webhook.list',
|
|
160
|
+
],
|
|
161
|
+
{ threshold: 1, shouldSort: true },
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
function getMethodSuggestions(fullyQualifiedMethodName: string): string[] {
|
|
165
|
+
return fuse
|
|
166
|
+
.search(fullyQualifiedMethodName)
|
|
167
|
+
.map(({ item }) => item)
|
|
168
|
+
.slice(0, 5);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const proxyToObj = new WeakMap<any, any>();
|
|
172
|
+
const objToProxy = new WeakMap<any, any>();
|
|
173
|
+
|
|
174
|
+
type ClientProxyConfig = {
|
|
175
|
+
path: string[];
|
|
176
|
+
isBelievedBad?: boolean;
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }: ClientProxyConfig): T {
|
|
180
|
+
let proxy: T = objToProxy.get(obj);
|
|
181
|
+
|
|
182
|
+
if (!proxy) {
|
|
183
|
+
proxy = new Proxy(obj, {
|
|
184
|
+
get(target, prop, receiver) {
|
|
185
|
+
const propPath = [...path, String(prop)];
|
|
186
|
+
const value = Reflect.get(target, prop, receiver);
|
|
187
|
+
|
|
188
|
+
if (isBelievedBad || (!(prop in target) && value === undefined)) {
|
|
189
|
+
// If we're accessing a path that doesn't exist, it will probably eventually error.
|
|
190
|
+
// Let's proxy it and mark it bad so that we can control the error message.
|
|
191
|
+
// We proxy an empty class so that an invocation or construction attempt is possible.
|
|
192
|
+
return makeSdkProxy(class {}, { path: propPath, isBelievedBad: true });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
|
|
196
|
+
return makeSdkProxy(value, { path: propPath, isBelievedBad });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return value;
|
|
200
|
+
},
|
|
201
|
+
|
|
202
|
+
apply(target, thisArg, args) {
|
|
203
|
+
if (isBelievedBad || typeof target !== 'function') {
|
|
204
|
+
const fullyQualifiedMethodName = path.join('.');
|
|
205
|
+
const suggestions = getMethodSuggestions(fullyQualifiedMethodName);
|
|
206
|
+
throw new Error(
|
|
207
|
+
`${fullyQualifiedMethodName} is not a function. Did you mean: ${suggestions.join(', ')}`,
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return Reflect.apply(target, proxyToObj.get(thisArg) ?? thisArg, args);
|
|
212
|
+
},
|
|
213
|
+
|
|
214
|
+
construct(target, args, newTarget) {
|
|
215
|
+
if (isBelievedBad || typeof target !== 'function') {
|
|
216
|
+
const fullyQualifiedMethodName = path.join('.');
|
|
217
|
+
const suggestions = getMethodSuggestions(fullyQualifiedMethodName);
|
|
218
|
+
throw new Error(
|
|
219
|
+
`${fullyQualifiedMethodName} is not a constructor. Did you mean: ${suggestions.join(', ')}`,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return Reflect.construct(target, args, newTarget);
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
objToProxy.set(obj, proxy);
|
|
228
|
+
proxyToObj.set(proxy, obj);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return proxy;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function parseError(code: string, error: unknown): string | undefined {
|
|
235
|
+
if (!(error instanceof Error)) return;
|
|
236
|
+
const message = error.name ? `${error.name}: ${error.message}` : error.message;
|
|
237
|
+
try {
|
|
238
|
+
// Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
|
|
239
|
+
const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
|
|
240
|
+
// -1 for the zero-based indexing
|
|
241
|
+
const line =
|
|
242
|
+
lineNumber &&
|
|
243
|
+
code
|
|
244
|
+
.split('\n')
|
|
245
|
+
.at(parseInt(lineNumber, 10) - 1)
|
|
246
|
+
?.trim();
|
|
247
|
+
return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
|
|
248
|
+
} catch {
|
|
249
|
+
return message;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const fetch = async (req: Request): Promise<Response> => {
|
|
254
|
+
const { opts, code } = (await req.json()) as { opts: ClientOptions; code: string };
|
|
255
|
+
|
|
256
|
+
const runFunctionSource = code ? getRunFunctionSource(code) : null;
|
|
257
|
+
if (!runFunctionSource) {
|
|
258
|
+
const message =
|
|
259
|
+
code ?
|
|
260
|
+
'The code is missing a top-level `run` function.'
|
|
261
|
+
: 'The code argument is missing. Provide one containing a top-level `run` function.';
|
|
262
|
+
return Response.json(
|
|
263
|
+
{
|
|
264
|
+
is_error: true,
|
|
265
|
+
result: `${message} Write code within this template:\n\n\`\`\`\nasync function run(client) {\n // Fill this out\n}\n\`\`\``,
|
|
266
|
+
log_lines: [],
|
|
267
|
+
err_lines: [],
|
|
268
|
+
} satisfies WorkerOutput,
|
|
269
|
+
{ status: 400, statusText: 'Code execution error' },
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const diagnostics = getTSDiagnostics(code);
|
|
274
|
+
if (diagnostics.length > 0) {
|
|
275
|
+
return Response.json(
|
|
276
|
+
{
|
|
277
|
+
is_error: true,
|
|
278
|
+
result: `The code contains TypeScript diagnostics:\n${diagnostics.join('\n')}`,
|
|
279
|
+
log_lines: [],
|
|
280
|
+
err_lines: [],
|
|
281
|
+
} satisfies WorkerOutput,
|
|
282
|
+
{ status: 400, statusText: 'Code execution error' },
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const client = new Roark({
|
|
287
|
+
...opts,
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
const log_lines: string[] = [];
|
|
291
|
+
const err_lines: string[] = [];
|
|
292
|
+
const console = {
|
|
293
|
+
log: (...args: unknown[]) => {
|
|
294
|
+
log_lines.push(util.format(...args));
|
|
295
|
+
},
|
|
296
|
+
error: (...args: unknown[]) => {
|
|
297
|
+
err_lines.push(util.format(...args));
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
try {
|
|
301
|
+
let run_ = async (client: any) => {};
|
|
302
|
+
eval(`${code}\nrun_ = run;`);
|
|
303
|
+
const result = await run_(makeSdkProxy(client, { path: ['client'] }));
|
|
304
|
+
return Response.json({
|
|
305
|
+
is_error: false,
|
|
306
|
+
result,
|
|
307
|
+
log_lines,
|
|
308
|
+
err_lines,
|
|
309
|
+
} satisfies WorkerOutput);
|
|
310
|
+
} catch (e) {
|
|
311
|
+
return Response.json(
|
|
312
|
+
{
|
|
313
|
+
is_error: true,
|
|
314
|
+
result: parseError(code, e),
|
|
315
|
+
log_lines,
|
|
316
|
+
err_lines,
|
|
317
|
+
} satisfies WorkerOutput,
|
|
318
|
+
{ status: 400, statusText: 'Code execution error' },
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
export default { fetch };
|
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,
|
|
@@ -12,6 +18,8 @@ import { Tool } from '@modelcontextprotocol/sdk/types.js';
|
|
|
12
18
|
import { readEnv, requireValue } from './util';
|
|
13
19
|
import { WorkerInput, WorkerOutput } from './code-tool-types';
|
|
14
20
|
import { SdkMethod } from './methods';
|
|
21
|
+
import { McpCodeExecutionMode } from './options';
|
|
22
|
+
import { ClientOptions } from '@roarkanalytics/sdk';
|
|
15
23
|
|
|
16
24
|
const prompt = `Runs JavaScript code to interact with the Roark API.
|
|
17
25
|
|
|
@@ -40,9 +48,19 @@ Variables will not persist between calls, so make sure to return or log any data
|
|
|
40
48
|
* we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
|
|
41
49
|
* a generic endpoint that can be used to invoke any endpoint with the provided arguments.
|
|
42
50
|
*
|
|
43
|
-
* @param
|
|
51
|
+
* @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
|
|
52
|
+
* matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
|
|
53
|
+
* with limited API keys.
|
|
54
|
+
* @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
|
|
55
|
+
* sandbox environment hosted by Stainless.
|
|
44
56
|
*/
|
|
45
|
-
export function codeTool({
|
|
57
|
+
export function codeTool({
|
|
58
|
+
blockedMethods,
|
|
59
|
+
codeExecutionMode,
|
|
60
|
+
}: {
|
|
61
|
+
blockedMethods: SdkMethod[] | undefined;
|
|
62
|
+
codeExecutionMode: McpCodeExecutionMode;
|
|
63
|
+
}): McpTool {
|
|
46
64
|
const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
|
|
47
65
|
const tool: Tool = {
|
|
48
66
|
name: 'execute',
|
|
@@ -62,6 +80,7 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
|
|
|
62
80
|
required: ['code'],
|
|
63
81
|
},
|
|
64
82
|
};
|
|
83
|
+
|
|
65
84
|
const handler = async ({
|
|
66
85
|
reqContext,
|
|
67
86
|
args,
|
|
@@ -70,9 +89,6 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
|
|
|
70
89
|
args: any;
|
|
71
90
|
}): Promise<ToolCallResult> => {
|
|
72
91
|
const code = args.code as string;
|
|
73
|
-
const intent = args.intent as string | undefined;
|
|
74
|
-
const client = reqContext.client;
|
|
75
|
-
|
|
76
92
|
// Do very basic blocking of code that includes forbidden method names.
|
|
77
93
|
//
|
|
78
94
|
// WARNING: This is not secure against obfuscation and other evasion methods. If
|
|
@@ -89,51 +105,253 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und
|
|
|
89
105
|
}
|
|
90
106
|
}
|
|
91
107
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
intent,
|
|
113
|
-
client_opts: {},
|
|
114
|
-
} satisfies WorkerInput),
|
|
115
|
-
});
|
|
108
|
+
if (codeExecutionMode === 'local') {
|
|
109
|
+
return await localDenoHandler({ reqContext, args });
|
|
110
|
+
} else {
|
|
111
|
+
return await remoteStainlessHandler({ reqContext, args });
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
return { metadata, tool, handler };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const remoteStainlessHandler = async ({
|
|
119
|
+
reqContext,
|
|
120
|
+
args,
|
|
121
|
+
}: {
|
|
122
|
+
reqContext: McpRequestContext;
|
|
123
|
+
args: any;
|
|
124
|
+
}): Promise<ToolCallResult> => {
|
|
125
|
+
const code = args.code as string;
|
|
126
|
+
const intent = args.intent as string | undefined;
|
|
127
|
+
const client = reqContext.client;
|
|
116
128
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
129
|
+
const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool';
|
|
130
|
+
|
|
131
|
+
// Setting a Stainless API key authenticates requests to the code tool endpoint.
|
|
132
|
+
const res = await fetch(codeModeEndpoint, {
|
|
133
|
+
method: 'POST',
|
|
134
|
+
headers: {
|
|
135
|
+
...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
|
|
136
|
+
'Content-Type': 'application/json',
|
|
137
|
+
client_envs: JSON.stringify({
|
|
138
|
+
ROARK_API_BEARER_TOKEN: requireValue(
|
|
139
|
+
readEnv('ROARK_API_BEARER_TOKEN') ?? client.bearerToken,
|
|
140
|
+
'set ROARK_API_BEARER_TOKEN environment variable or provide bearerToken client option',
|
|
141
|
+
),
|
|
142
|
+
ROARK_BASE_URL: readEnv('ROARK_BASE_URL') ?? client.baseURL ?? undefined,
|
|
143
|
+
}),
|
|
144
|
+
},
|
|
145
|
+
body: JSON.stringify({
|
|
146
|
+
project_name: 'roark-analytics',
|
|
147
|
+
code,
|
|
148
|
+
intent,
|
|
149
|
+
client_opts: {},
|
|
150
|
+
} satisfies WorkerInput),
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
if (!res.ok) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`${res.status}: ${
|
|
156
|
+
res.statusText
|
|
157
|
+
} error when trying to contact Code Tool server. Details: ${await res.text()}`,
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput;
|
|
162
|
+
const hasLogs = log_lines.length > 0 || err_lines.length > 0;
|
|
163
|
+
const output = {
|
|
164
|
+
result,
|
|
165
|
+
...(log_lines.length > 0 && { log_lines }),
|
|
166
|
+
...(err_lines.length > 0 && { err_lines }),
|
|
167
|
+
};
|
|
168
|
+
if (is_error) {
|
|
169
|
+
return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
|
|
170
|
+
}
|
|
171
|
+
return asTextContentResult(output);
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const localDenoHandler = async ({
|
|
175
|
+
reqContext,
|
|
176
|
+
args,
|
|
177
|
+
}: {
|
|
178
|
+
reqContext: McpRequestContext;
|
|
179
|
+
args: unknown;
|
|
180
|
+
}): Promise<ToolCallResult> => {
|
|
181
|
+
const client = reqContext.client;
|
|
182
|
+
const baseURLHostname = new URL(client.baseURL).hostname;
|
|
183
|
+
const { code } = args as { code: string };
|
|
184
|
+
|
|
185
|
+
let denoPath: string;
|
|
186
|
+
|
|
187
|
+
const packageRoot = path.resolve(path.dirname(workerPath), '..');
|
|
188
|
+
const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
|
|
189
|
+
|
|
190
|
+
// Check if deno is in PATH
|
|
191
|
+
const { execSync } = await import('node:child_process');
|
|
192
|
+
try {
|
|
193
|
+
execSync('command -v deno', { stdio: 'ignore' });
|
|
194
|
+
denoPath = 'deno';
|
|
195
|
+
} catch {
|
|
196
|
+
try {
|
|
197
|
+
// Use deno binary in node_modules if it's found
|
|
198
|
+
const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
|
|
199
|
+
await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
|
|
200
|
+
denoPath = denoNodeModulesPath;
|
|
201
|
+
} catch {
|
|
202
|
+
return asErrorResult(
|
|
203
|
+
'Deno is required for code execution but was not found. ' +
|
|
204
|
+
'Install it from https://deno.land or run: npm install deno',
|
|
122
205
|
);
|
|
123
206
|
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const allowReadPaths = [
|
|
210
|
+
'code-tool-worker.mjs',
|
|
211
|
+
`${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
|
|
212
|
+
packageRoot,
|
|
213
|
+
];
|
|
124
214
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
if (is_error) {
|
|
133
|
-
return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2));
|
|
215
|
+
// Follow symlinks in node_modules to allow read access to workspace-linked packages
|
|
216
|
+
try {
|
|
217
|
+
const sdkPkgName = '@roarkanalytics/sdk';
|
|
218
|
+
const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
|
|
219
|
+
const realSdkDir = fs.realpathSync(sdkDir);
|
|
220
|
+
if (realSdkDir !== sdkDir) {
|
|
221
|
+
allowReadPaths.push(realSdkDir);
|
|
134
222
|
}
|
|
135
|
-
|
|
136
|
-
|
|
223
|
+
} catch {
|
|
224
|
+
// Ignore if symlink resolution fails
|
|
225
|
+
}
|
|
137
226
|
|
|
138
|
-
|
|
139
|
-
|
|
227
|
+
const allowRead = allowReadPaths.join(',');
|
|
228
|
+
|
|
229
|
+
const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
|
|
230
|
+
denoExecutable: denoPath,
|
|
231
|
+
runFlags: [
|
|
232
|
+
`--node-modules-dir=manual`,
|
|
233
|
+
`--allow-read=${allowRead}`,
|
|
234
|
+
`--allow-net=${baseURLHostname}`,
|
|
235
|
+
// Allow environment variables because instantiating the client will try to read from them,
|
|
236
|
+
// even though they are not set.
|
|
237
|
+
'--allow-env',
|
|
238
|
+
],
|
|
239
|
+
printOutput: true,
|
|
240
|
+
spawnOptions: {
|
|
241
|
+
cwd: path.dirname(workerPath),
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
const resp = await new Promise<Response>((resolve, reject) => {
|
|
247
|
+
worker.addEventListener('exit', (exitCode) => {
|
|
248
|
+
reject(new Error(`Worker exited with code ${exitCode}`));
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
const opts: ClientOptions = {
|
|
252
|
+
baseURL: client.baseURL,
|
|
253
|
+
bearerToken: client.bearerToken,
|
|
254
|
+
defaultHeaders: {
|
|
255
|
+
'X-Stainless-MCP': 'true',
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
const req = worker.request(
|
|
260
|
+
'http://localhost',
|
|
261
|
+
{
|
|
262
|
+
headers: {
|
|
263
|
+
'content-type': 'application/json',
|
|
264
|
+
},
|
|
265
|
+
method: 'POST',
|
|
266
|
+
},
|
|
267
|
+
(resp) => {
|
|
268
|
+
const body: Uint8Array[] = [];
|
|
269
|
+
resp.on('error', (err) => {
|
|
270
|
+
reject(err);
|
|
271
|
+
});
|
|
272
|
+
resp.on('data', (chunk) => {
|
|
273
|
+
body.push(chunk);
|
|
274
|
+
});
|
|
275
|
+
resp.on('end', () => {
|
|
276
|
+
resolve(
|
|
277
|
+
new Response(Buffer.concat(body).toString(), {
|
|
278
|
+
status: resp.statusCode ?? 200,
|
|
279
|
+
headers: resp.headers as any,
|
|
280
|
+
}),
|
|
281
|
+
);
|
|
282
|
+
});
|
|
283
|
+
},
|
|
284
|
+
);
|
|
285
|
+
|
|
286
|
+
const body = JSON.stringify({
|
|
287
|
+
opts,
|
|
288
|
+
code,
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
req.write(body, (err) => {
|
|
292
|
+
if (err != null) {
|
|
293
|
+
reject(err);
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
req.end();
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
if (resp.status === 200) {
|
|
301
|
+
const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
|
|
302
|
+
const returnOutput: ContentBlock | null =
|
|
303
|
+
result == null ? null : (
|
|
304
|
+
{
|
|
305
|
+
type: 'text',
|
|
306
|
+
text: typeof result === 'string' ? result : JSON.stringify(result),
|
|
307
|
+
}
|
|
308
|
+
);
|
|
309
|
+
const logOutput: ContentBlock | null =
|
|
310
|
+
log_lines.length === 0 ?
|
|
311
|
+
null
|
|
312
|
+
: {
|
|
313
|
+
type: 'text',
|
|
314
|
+
text: log_lines.join('\n'),
|
|
315
|
+
};
|
|
316
|
+
const errOutput: ContentBlock | null =
|
|
317
|
+
err_lines.length === 0 ?
|
|
318
|
+
null
|
|
319
|
+
: {
|
|
320
|
+
type: 'text',
|
|
321
|
+
text: 'Error output:\n' + err_lines.join('\n'),
|
|
322
|
+
};
|
|
323
|
+
return {
|
|
324
|
+
content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
|
|
325
|
+
};
|
|
326
|
+
} else {
|
|
327
|
+
const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
|
|
328
|
+
const messageOutput: 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: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
|
|
351
|
+
isError: true,
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
} finally {
|
|
355
|
+
worker.terminate();
|
|
356
|
+
}
|
|
357
|
+
};
|