|
| 1 | +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. |
| 2 | + |
| 3 | +import { type ClientOptions } from 'isaacus/client'; |
| 4 | + |
| 5 | +import { dirname } from 'node:path'; |
| 6 | +import { pathToFileURL } from 'node:url'; |
| 7 | +import Isaacus from 'isaacus'; |
| 8 | +import { Endpoint, ContentBlock, Metadata } from './tools/types'; |
| 9 | + |
| 10 | +import { Tool } from '@modelcontextprotocol/sdk/types.js'; |
| 11 | + |
| 12 | +import { newDenoHTTPWorker } from '@valtown/deno-http-worker'; |
| 13 | +import { WorkerInput, WorkerError, WorkerSuccess } from './code-tool-types'; |
| 14 | +import { workerPath } from './code-tool-paths.cjs'; |
| 15 | + |
| 16 | +/** |
| 17 | + * A tool that runs code against a copy of the SDK. |
| 18 | + * |
| 19 | + * Instead of exposing every endpoint as it's own tool, which uses up too many tokens for LLMs to use at once, |
| 20 | + * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then |
| 21 | + * a generic endpoint that can be used to invoke any endpoint with the provided arguments. |
| 22 | + * |
| 23 | + * @param endpoints - The endpoints to include in the list. |
| 24 | + */ |
| 25 | +export function codeTool(): Endpoint { |
| 26 | + const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] }; |
| 27 | + const tool: Tool = { |
| 28 | + name: 'execute', |
| 29 | + description: |
| 30 | + 'Runs Typescript code to interact with the API.\nYou are a skilled programmer writing code to interface with the service.\nDefine an async function named "run" that takes a single parameter of an initialized client, and it will be run.\nDo not initialize a client, but instead use the client that you are given as a parameter.\nYou will be returned anything that your function returns, plus the results of any console.log statements.\nIf any code triggers an error, the tool will return an error response, so you do not need to add error handling unless you want to output something more helpful than the raw error.\nIt is not necessary to add comments to code, unless by adding those comments you believe that you can generate better code.\nThis code will run in a container, and you will not be able to use fetch or otherwise interact with the network calls other than through the client you are given.\nAny variables you define won\'t live between successive uses of this call, so make sure to return or log any data you might need later.', |
| 31 | + inputSchema: { type: 'object', properties: { code: { type: 'string' } } }, |
| 32 | + }; |
| 33 | + |
| 34 | + const handler = async (client: Isaacus, args: unknown) => { |
| 35 | + const baseURLHostname = new URL(client.baseURL).hostname; |
| 36 | + const { code } = args as { code: string }; |
| 37 | + |
| 38 | + const worker = await newDenoHTTPWorker(pathToFileURL(workerPath), { |
| 39 | + runFlags: [ |
| 40 | + `--node-modules-dir=manual`, |
| 41 | + `--allow-read=code-tool-worker.mjs,${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`, |
| 42 | + `--allow-net=${baseURLHostname}`, |
| 43 | + // Allow environment variables because instantiating the client will try to read from them, |
| 44 | + // even though they are not set. |
| 45 | + '--allow-env', |
| 46 | + ], |
| 47 | + printOutput: true, |
| 48 | + spawnOptions: { |
| 49 | + cwd: dirname(workerPath), |
| 50 | + }, |
| 51 | + }); |
| 52 | + |
| 53 | + try { |
| 54 | + const resp = await new Promise<Response>((resolve, reject) => { |
| 55 | + worker.addEventListener('exit', (exitCode) => { |
| 56 | + reject(new Error(`Worker exited with code ${exitCode}`)); |
| 57 | + }); |
| 58 | + |
| 59 | + const opts: ClientOptions = { |
| 60 | + baseURL: client.baseURL, |
| 61 | + apiKey: client.apiKey, |
| 62 | + defaultHeaders: { |
| 63 | + 'X-Stainless-MCP': 'true', |
| 64 | + }, |
| 65 | + }; |
| 66 | + |
| 67 | + const req = worker.request( |
| 68 | + 'http://localhost', |
| 69 | + { |
| 70 | + headers: { |
| 71 | + 'content-type': 'application/json', |
| 72 | + }, |
| 73 | + method: 'POST', |
| 74 | + }, |
| 75 | + (resp) => { |
| 76 | + const body: Uint8Array[] = []; |
| 77 | + resp.on('error', (err) => { |
| 78 | + reject(err); |
| 79 | + }); |
| 80 | + resp.on('data', (chunk) => { |
| 81 | + body.push(chunk); |
| 82 | + }); |
| 83 | + resp.on('end', () => { |
| 84 | + resolve( |
| 85 | + new Response(Buffer.concat(body).toString(), { |
| 86 | + status: resp.statusCode ?? 200, |
| 87 | + headers: resp.headers as any, |
| 88 | + }), |
| 89 | + ); |
| 90 | + }); |
| 91 | + }, |
| 92 | + ); |
| 93 | + |
| 94 | + const body = JSON.stringify({ |
| 95 | + opts, |
| 96 | + code, |
| 97 | + } satisfies WorkerInput); |
| 98 | + |
| 99 | + req.write(body, (err) => { |
| 100 | + if (err !== null && err !== undefined) { |
| 101 | + reject(err); |
| 102 | + } |
| 103 | + }); |
| 104 | + |
| 105 | + req.end(); |
| 106 | + }); |
| 107 | + |
| 108 | + if (resp.status === 200) { |
| 109 | + const { result, logLines, errLines } = (await resp.json()) as WorkerSuccess; |
| 110 | + const returnOutput: ContentBlock | null = |
| 111 | + result === null ? null |
| 112 | + : result === undefined ? null |
| 113 | + : { |
| 114 | + type: 'text', |
| 115 | + text: typeof result === 'string' ? (result as string) : JSON.stringify(result), |
| 116 | + }; |
| 117 | + const logOutput: ContentBlock | null = |
| 118 | + logLines.length === 0 ? |
| 119 | + null |
| 120 | + : { |
| 121 | + type: 'text', |
| 122 | + text: logLines.join('\n'), |
| 123 | + }; |
| 124 | + const errOutput: ContentBlock | null = |
| 125 | + errLines.length === 0 ? |
| 126 | + null |
| 127 | + : { |
| 128 | + type: 'text', |
| 129 | + text: 'Error output:\n' + errLines.join('\n'), |
| 130 | + }; |
| 131 | + return { |
| 132 | + content: [returnOutput, logOutput, errOutput].filter((block) => block !== null), |
| 133 | + }; |
| 134 | + } else { |
| 135 | + const { message } = (await resp.json()) as WorkerError; |
| 136 | + throw new Error(message); |
| 137 | + } |
| 138 | + } catch (e) { |
| 139 | + throw e; |
| 140 | + } finally { |
| 141 | + worker.terminate(); |
| 142 | + } |
| 143 | + }; |
| 144 | + |
| 145 | + return { metadata, tool, handler }; |
| 146 | +} |
0 commit comments