diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 8e3d9554..47582228 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.31.0" + ".": "0.32.0" } diff --git a/.stats.yml b/.stats.yml index d92f0726..1645b898 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 23 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/hyperspell%2Fhyperspell-be19b15cbcf156f621134060e45ab8129def46ceb32d075f44bc2229b7927eb2.yml -openapi_spec_hash: d91cba474f423492510b46439da6a3d7 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/hyperspell%2Fhyperspell-c588b46dd6bb770b1fc6b04b0eb61e064cd7266232ae9fbed8d73c0b41c52f6e.yml +openapi_spec_hash: f5a62027999d75f404e9ee63bddc145b config_hash: 983708fc30c86269c2149a960d0bfec1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d4c62c0..739ec087 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog +## 0.32.0 (2026-02-27) + +Full Changelog: [v0.31.0...v0.32.0](https://github.com/hyperspell/node-sdk/compare/v0.31.0...v0.32.0) + +### Features + +* **api:** api update ([58dfd3c](https://github.com/hyperspell/node-sdk/commit/58dfd3cf50972db3ffe9479eaffb2fd2a39a9182)) +* **api:** api update ([07490e4](https://github.com/hyperspell/node-sdk/commit/07490e4a52d6d8ac7b38f11dc38a4b23af3dd2f7)) +* **api:** api update ([5a6e5c7](https://github.com/hyperspell/node-sdk/commit/5a6e5c74e6ddcc376450e94b0f5bdafe073ba801)) +* **api:** api update ([44dc1e7](https://github.com/hyperspell/node-sdk/commit/44dc1e76ae1637fa4e889409f6755cde9ec41d8f)) +* **api:** api update ([c85924d](https://github.com/hyperspell/node-sdk/commit/c85924dccb934adba75421f757b5c2c226984e00)) + + +### Bug Fixes + +* **docs/contributing:** correct pnpm link command ([8904a4f](https://github.com/hyperspell/node-sdk/commit/8904a4f7743ce268f189871f0ca4bb49672ad0fd)) +* **mcp:** initialize SDK lazily to avoid failing the connection on init errors ([ff10988](https://github.com/hyperspell/node-sdk/commit/ff10988f658c9ba9fe926f3ae5b9ecc2b6f1908e)) + + +### Chores + +* **internal:** cache fetch instruction calls in MCP server ([ccacaac](https://github.com/hyperspell/node-sdk/commit/ccacaaccdae08b289609ed69dd272f952007e3e2)) +* **internal:** fix MCP Dockerfiles so they can be built without buildkit ([9958397](https://github.com/hyperspell/node-sdk/commit/99583972b4d0533b87ba48e0cd431dcab5bb0333)) +* **internal:** fix MCP Dockerfiles so they can be built without buildkit ([c38098d](https://github.com/hyperspell/node-sdk/commit/c38098da6c6d46eba456572b142bc071147fcbcc)) +* **internal:** make MCP code execution location configurable via a flag ([6ae4a00](https://github.com/hyperspell/node-sdk/commit/6ae4a00a4d3f0eb59041c2e1b49046bc1a55ed40)) +* **internal:** upgrade @modelcontextprotocol/sdk and hono ([f6fdb27](https://github.com/hyperspell/node-sdk/commit/f6fdb27d81b75495ef4e2399699c9153dc056490)) +* **mcp:** correctly update version in sync with sdk ([54f2bff](https://github.com/hyperspell/node-sdk/commit/54f2bffc32d97851ded586a4a0840e5b74bddd54)) +* update mock server docs ([0417d08](https://github.com/hyperspell/node-sdk/commit/0417d08178a0efe5b858d15c3a2c6763964e8bbe)) + ## 0.31.0 (2026-02-18) Full Changelog: [v0.30.0...v0.31.0](https://github.com/hyperspell/node-sdk/compare/v0.30.0...v0.31.0) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4108c69b..0d767f59 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,7 +60,7 @@ $ yarn link hyperspell # With pnpm $ pnpm link --global $ cd ../my-package -$ pnpm link -—global hyperspell +$ pnpm link --global hyperspell ``` ## Running tests @@ -68,7 +68,7 @@ $ pnpm link -—global hyperspell Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. ```sh -$ npx prism mock path/to/your/openapi.yml +$ ./scripts/mock ``` ```sh diff --git a/package.json b/package.json index 655d2f79..5fc34580 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hyperspell", - "version": "0.31.0", + "version": "0.32.0", "description": "The official TypeScript library for the Hyperspell API", "author": "Hyperspell ", "types": "dist/index.d.ts", diff --git a/packages/mcp-server/Dockerfile b/packages/mcp-server/Dockerfile index 800712db..1be5c2cb 100644 --- a/packages/mcp-server/Dockerfile +++ b/packages/mcp-server/Dockerfile @@ -37,8 +37,12 @@ COPY . . RUN yarn install --frozen-lockfile && \ yarn build -# Production stage -FROM node:24-alpine +FROM denoland/deno:alpine-2.7.1 + +# Install node and npm +RUN apk add --no-cache nodejs npm + +ENV LD_LIBRARY_PATH=/usr/lib:/usr/local/lib # Add non-root user RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001 @@ -57,6 +61,7 @@ COPY --from=builder /build/dist ./node_modules/hyperspell # Change ownership to nodejs user RUN chown -R nodejs:nodejs /app +RUN chown -R nodejs:nodejs /deno-dir # Switch to non-root user USER nodejs diff --git a/packages/mcp-server/manifest.json b/packages/mcp-server/manifest.json index 6b52fd89..a10efcdd 100644 --- a/packages/mcp-server/manifest.json +++ b/packages/mcp-server/manifest.json @@ -1,7 +1,7 @@ { "dxt_version": "0.2", "name": "hyperspell-mcp", - "version": "0.27.0", + "version": "0.32.0", "description": "The official MCP Server for the Hyperspell API", "author": { "name": "Hyperspell", @@ -18,7 +18,9 @@ "entry_point": "index.js", "mcp_config": { "command": "node", - "args": ["${__dirname}/index.js"], + "args": [ + "${__dirname}/index.js" + ], "env": { "HYPERSPELL_API_KEY": "${user_config.HYPERSPELL_API_KEY}", "HYPERSPELL_USER_ID": "${user_config.HYPERSPELL_USER_ID}" @@ -46,5 +48,7 @@ "node": ">=18.0.0" } }, - "keywords": ["api"] + "keywords": [ + "api" + ] } diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 0e369567..6004bf72 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "hyperspell-mcp", - "version": "0.31.0", + "version": "0.32.0", "description": "The official MCP Server for the Hyperspell API", "author": "Hyperspell ", "types": "dist/index.d.ts", @@ -32,7 +32,7 @@ "dependencies": { "hyperspell": "file:../../dist/", "@cloudflare/cabidela": "^0.2.4", - "@modelcontextprotocol/sdk": "^1.25.2", + "@modelcontextprotocol/sdk": "^1.26.0", "@valtown/deno-http-worker": "^0.0.21", "cookie-parser": "^1.4.6", "cors": "^2.8.5", diff --git a/packages/mcp-server/src/code-tool-paths.cts b/packages/mcp-server/src/code-tool-paths.cts new file mode 100644 index 00000000..15ce7f55 --- /dev/null +++ b/packages/mcp-server/src/code-tool-paths.cts @@ -0,0 +1,3 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +export const workerPath = require.resolve('./code-tool-worker.mjs'); diff --git a/packages/mcp-server/src/code-tool-types.ts b/packages/mcp-server/src/code-tool-types.ts index 1598dcd9..4c069221 100644 --- a/packages/mcp-server/src/code-tool-types.ts +++ b/packages/mcp-server/src/code-tool-types.ts @@ -8,6 +8,7 @@ export type WorkerInput = { client_opts: ClientOptions; intent?: string | undefined; }; + export type WorkerOutput = { is_error: boolean; result: unknown | null; diff --git a/packages/mcp-server/src/code-tool-worker.ts b/packages/mcp-server/src/code-tool-worker.ts new file mode 100644 index 00000000..067906ee --- /dev/null +++ b/packages/mcp-server/src/code-tool-worker.ts @@ -0,0 +1,293 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import path from 'node:path'; +import util from 'node:util'; +import Fuse from 'fuse.js'; +import ts from 'typescript'; +import { WorkerOutput } from './code-tool-types'; +import { Hyperspell, ClientOptions } from 'hyperspell'; + +function getRunFunctionSource(code: string): { + type: 'declaration' | 'expression'; + client: string | undefined; + code: string; +} | null { + const sourceFile = ts.createSourceFile('code.ts', code, ts.ScriptTarget.Latest, true); + const printer = ts.createPrinter(); + + for (const statement of sourceFile.statements) { + // Check for top-level function declarations + if (ts.isFunctionDeclaration(statement)) { + if (statement.name?.text === 'run') { + return { + type: 'declaration', + client: statement.parameters[0]?.name.getText(), + code: printer.printNode(ts.EmitHint.Unspecified, statement.body!, sourceFile), + }; + } + } + + // Check for variable declarations: const run = () => {} or const run = function() {} + if (ts.isVariableStatement(statement)) { + for (const declaration of statement.declarationList.declarations) { + if ( + ts.isIdentifier(declaration.name) && + declaration.name.text === 'run' && + // Check if it's initialized with a function + declaration.initializer && + (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer)) + ) { + return { + type: 'expression', + client: declaration.initializer.parameters[0]?.name.getText(), + code: printer.printNode(ts.EmitHint.Unspecified, declaration.initializer, sourceFile), + }; + } + } + } + } + + return null; +} + +function getTSDiagnostics(code: string): string[] { + const functionSource = getRunFunctionSource(code)!; + const codeWithImport = [ + 'import { Hyperspell } from "hyperspell";', + functionSource.type === 'declaration' ? + `async function run(${functionSource.client}: Hyperspell)` + : `const run: (${functionSource.client}: Hyperspell) => Promise =`, + functionSource.code, + ].join('\n'); + const sourcePath = path.resolve('code.ts'); + const ast = ts.createSourceFile(sourcePath, codeWithImport, ts.ScriptTarget.Latest, true); + const options = ts.getDefaultCompilerOptions(); + options.target = ts.ScriptTarget.Latest; + options.module = ts.ModuleKind.NodeNext; + options.moduleResolution = ts.ModuleResolutionKind.NodeNext; + const host = ts.createCompilerHost(options, true); + const newHost: typeof host = { + ...host, + getSourceFile: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return ast; + } + return host.getSourceFile(...args); + }, + readFile: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return codeWithImport; + } + return host.readFile(...args); + }, + fileExists: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return true; + } + return host.fileExists(...args); + }, + }; + const program = ts.createProgram({ + options, + rootNames: [sourcePath], + host: newHost, + }); + const diagnostics = ts.getPreEmitDiagnostics(program, ast); + return diagnostics.map((d) => { + const message = ts.flattenDiagnosticMessageText(d.messageText, '\n'); + if (!d.file || !d.start) return `- ${message}`; + const { line: lineNumber } = ts.getLineAndCharacterOfPosition(d.file, d.start); + const line = codeWithImport.split('\n').at(lineNumber)?.trim(); + return line ? `- ${message}\n ${line}` : `- ${message}`; + }); +} + +const fuse = new Fuse( + [ + 'client.connections.list', + 'client.connections.revoke', + 'client.integrations.connect', + 'client.integrations.list', + 'client.integrations.googleCalendar.list', + 'client.integrations.webCrawler.index', + 'client.integrations.slack.list', + 'client.memories.add', + 'client.memories.addBulk', + 'client.memories.delete', + 'client.memories.get', + 'client.memories.list', + 'client.memories.search', + 'client.memories.status', + 'client.memories.update', + 'client.memories.upload', + 'client.evaluate.getQuery', + 'client.evaluate.scoreHighlight', + 'client.evaluate.scoreQuery', + 'client.vaults.list', + 'client.auth.deleteUser', + 'client.auth.me', + 'client.auth.userToken', + ], + { threshold: 1, shouldSort: true }, +); + +function getMethodSuggestions(fullyQualifiedMethodName: string): string[] { + return fuse + .search(fullyQualifiedMethodName) + .map(({ item }) => item) + .slice(0, 5); +} + +const proxyToObj = new WeakMap(); +const objToProxy = new WeakMap(); + +type ClientProxyConfig = { + path: string[]; + isBelievedBad?: boolean; +}; + +function makeSdkProxy(obj: T, { path, isBelievedBad = false }: ClientProxyConfig): T { + let proxy: T = objToProxy.get(obj); + + if (!proxy) { + proxy = new Proxy(obj, { + get(target, prop, receiver) { + const propPath = [...path, String(prop)]; + const value = Reflect.get(target, prop, receiver); + + if (isBelievedBad || (!(prop in target) && value === undefined)) { + // If we're accessing a path that doesn't exist, it will probably eventually error. + // Let's proxy it and mark it bad so that we can control the error message. + // We proxy an empty class so that an invocation or construction attempt is possible. + return makeSdkProxy(class {}, { path: propPath, isBelievedBad: true }); + } + + if (value !== null && (typeof value === 'object' || typeof value === 'function')) { + return makeSdkProxy(value, { path: propPath, isBelievedBad }); + } + + return value; + }, + + apply(target, thisArg, args) { + if (isBelievedBad || typeof target !== 'function') { + const fullyQualifiedMethodName = path.join('.'); + const suggestions = getMethodSuggestions(fullyQualifiedMethodName); + throw new Error( + `${fullyQualifiedMethodName} is not a function. Did you mean: ${suggestions.join(', ')}`, + ); + } + + return Reflect.apply(target, proxyToObj.get(thisArg) ?? thisArg, args); + }, + + construct(target, args, newTarget) { + if (isBelievedBad || typeof target !== 'function') { + const fullyQualifiedMethodName = path.join('.'); + const suggestions = getMethodSuggestions(fullyQualifiedMethodName); + throw new Error( + `${fullyQualifiedMethodName} is not a constructor. Did you mean: ${suggestions.join(', ')}`, + ); + } + + return Reflect.construct(target, args, newTarget); + }, + }); + + objToProxy.set(obj, proxy); + proxyToObj.set(proxy, obj); + } + + return proxy; +} + +function parseError(code: string, error: unknown): string | undefined { + if (!(error instanceof Error)) return; + const message = error.name ? `${error.name}: ${error.message}` : error.message; + try { + // Deno uses V8; the first ":LINE:COLUMN" is the top of stack. + const lineNumber = error.stack?.match(/:([0-9]+):[0-9]+/)?.[1]; + // -1 for the zero-based indexing + const line = + lineNumber && + code + .split('\n') + .at(parseInt(lineNumber, 10) - 1) + ?.trim(); + return line ? `${message}\n at line ${lineNumber}\n ${line}` : message; + } catch { + return message; + } +} + +const fetch = async (req: Request): Promise => { + const { opts, code } = (await req.json()) as { opts: ClientOptions; code: string }; + + const runFunctionSource = code ? getRunFunctionSource(code) : null; + if (!runFunctionSource) { + const message = + code ? + 'The code is missing a top-level `run` function.' + : 'The code argument is missing. Provide one containing a top-level `run` function.'; + return Response.json( + { + is_error: true, + result: `${message} Write code within this template:\n\n\`\`\`\nasync function run(client) {\n // Fill this out\n}\n\`\`\``, + log_lines: [], + err_lines: [], + } satisfies WorkerOutput, + { status: 400, statusText: 'Code execution error' }, + ); + } + + const diagnostics = getTSDiagnostics(code); + if (diagnostics.length > 0) { + return Response.json( + { + is_error: true, + result: `The code contains TypeScript diagnostics:\n${diagnostics.join('\n')}`, + log_lines: [], + err_lines: [], + } satisfies WorkerOutput, + { status: 400, statusText: 'Code execution error' }, + ); + } + + const client = new Hyperspell({ + ...opts, + }); + + const log_lines: string[] = []; + const err_lines: string[] = []; + const console = { + log: (...args: unknown[]) => { + log_lines.push(util.format(...args)); + }, + error: (...args: unknown[]) => { + err_lines.push(util.format(...args)); + }, + }; + try { + let run_ = async (client: any) => {}; + eval(`${code}\nrun_ = run;`); + const result = await run_(makeSdkProxy(client, { path: ['client'] })); + return Response.json({ + is_error: false, + result, + log_lines, + err_lines, + } satisfies WorkerOutput); + } catch (e) { + return Response.json( + { + is_error: true, + result: parseError(code, e), + log_lines, + err_lines, + } satisfies WorkerOutput, + { status: 400, statusText: 'Code execution error' }, + ); + } +}; + +export default { fetch }; diff --git a/packages/mcp-server/src/code-tool.ts b/packages/mcp-server/src/code-tool.ts index 4036b38a..514da218 100644 --- a/packages/mcp-server/src/code-tool.ts +++ b/packages/mcp-server/src/code-tool.ts @@ -1,6 +1,12 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import fs from 'node:fs'; +import path from 'node:path'; +import url from 'node:url'; +import { newDenoHTTPWorker } from '@valtown/deno-http-worker'; +import { workerPath } from './code-tool-paths.cjs'; import { + ContentBlock, McpRequestContext, McpTool, Metadata, @@ -12,6 +18,8 @@ import { Tool } from '@modelcontextprotocol/sdk/types.js'; import { readEnv, requireValue } from './util'; import { WorkerInput, WorkerOutput } from './code-tool-types'; import { SdkMethod } from './methods'; +import { McpCodeExecutionMode } from './options'; +import { ClientOptions } from 'hyperspell'; const prompt = `Runs JavaScript code to interact with the Hyperspell API. @@ -40,9 +48,19 @@ Variables will not persist between calls, so make sure to return or log any data * we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then * a generic endpoint that can be used to invoke any endpoint with the provided arguments. * - * @param endpoints - The endpoints to include in the list. + * @param blockedMethods - The methods to block for code execution. Blocking is done by simple string + * matching, so it is not secure against obfuscation. For stronger security, block in the downstream API + * with limited API keys. + * @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote + * sandbox environment hosted by Stainless. */ -export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | undefined }): McpTool { +export function codeTool({ + blockedMethods, + codeExecutionMode, +}: { + blockedMethods: SdkMethod[] | undefined; + codeExecutionMode: McpCodeExecutionMode; +}): McpTool { const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] }; const tool: Tool = { name: 'execute', @@ -62,6 +80,7 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und required: ['code'], }, }; + const handler = async ({ reqContext, args, @@ -70,9 +89,6 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und args: any; }): Promise => { const code = args.code as string; - const intent = args.intent as string | undefined; - const client = reqContext.client; - // Do very basic blocking of code that includes forbidden method names. // // WARNING: This is not secure against obfuscation and other evasion methods. If @@ -89,51 +105,254 @@ export function codeTool({ blockedMethods }: { blockedMethods: SdkMethod[] | und } } - const codeModeEndpoint = - readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool'; - - // Setting a Stainless API key authenticates requests to the code tool endpoint. - const res = await fetch(codeModeEndpoint, { - method: 'POST', - headers: { - ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }), - 'Content-Type': 'application/json', - client_envs: JSON.stringify({ - HYPERSPELL_API_KEY: requireValue( - readEnv('HYPERSPELL_API_KEY') ?? client.apiKey, - 'set HYPERSPELL_API_KEY environment variable or provide apiKey client option', - ), - HYPERSPELL_BASE_URL: readEnv('HYPERSPELL_BASE_URL') ?? client.baseURL ?? undefined, - }), - }, - body: JSON.stringify({ - project_name: 'hyperspell', - code, - intent, - client_opts: { userID: readEnv('HYPERSPELL_USER_ID') }, - } satisfies WorkerInput), - }); + if (codeExecutionMode === 'local') { + return await localDenoHandler({ reqContext, args }); + } else { + return await remoteStainlessHandler({ reqContext, args }); + } + }; + + return { metadata, tool, handler }; +} + +const remoteStainlessHandler = async ({ + reqContext, + args, +}: { + reqContext: McpRequestContext; + args: any; +}): Promise => { + const code = args.code as string; + const intent = args.intent as string | undefined; + const client = reqContext.client; - if (!res.ok) { - throw new Error( - `${res.status}: ${ - res.statusText - } error when trying to contact Code Tool server. Details: ${await res.text()}`, + const codeModeEndpoint = readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool'; + + // Setting a Stainless API key authenticates requests to the code tool endpoint. + const res = await fetch(codeModeEndpoint, { + method: 'POST', + headers: { + ...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }), + 'Content-Type': 'application/json', + client_envs: JSON.stringify({ + HYPERSPELL_API_KEY: requireValue( + readEnv('HYPERSPELL_API_KEY') ?? client.apiKey, + 'set HYPERSPELL_API_KEY environment variable or provide apiKey client option', + ), + HYPERSPELL_BASE_URL: readEnv('HYPERSPELL_BASE_URL') ?? client.baseURL ?? undefined, + }), + }, + body: JSON.stringify({ + project_name: 'hyperspell', + code, + intent, + client_opts: { userID: readEnv('HYPERSPELL_USER_ID') }, + } satisfies WorkerInput), + }); + + if (!res.ok) { + throw new Error( + `${res.status}: ${ + res.statusText + } error when trying to contact Code Tool server. Details: ${await res.text()}`, + ); + } + + const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput; + const hasLogs = log_lines.length > 0 || err_lines.length > 0; + const output = { + result, + ...(log_lines.length > 0 && { log_lines }), + ...(err_lines.length > 0 && { err_lines }), + }; + if (is_error) { + return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2)); + } + return asTextContentResult(output); +}; + +const localDenoHandler = async ({ + reqContext, + args, +}: { + reqContext: McpRequestContext; + args: unknown; +}): Promise => { + const client = reqContext.client; + const baseURLHostname = new URL(client.baseURL).hostname; + const { code } = args as { code: string }; + + let denoPath: string; + + const packageRoot = path.resolve(path.dirname(workerPath), '..'); + const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules'); + + // Check if deno is in PATH + const { execSync } = await import('node:child_process'); + try { + execSync('command -v deno', { stdio: 'ignore' }); + denoPath = 'deno'; + } catch { + try { + // Use deno binary in node_modules if it's found + const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs'); + await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK); + denoPath = denoNodeModulesPath; + } catch { + return asErrorResult( + 'Deno is required for code execution but was not found. ' + + 'Install it from https://deno.land or run: npm install deno', ); } + } + + const allowReadPaths = [ + 'code-tool-worker.mjs', + `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`, + packageRoot, + ]; - const { is_error, result, log_lines, err_lines } = (await res.json()) as WorkerOutput; - const hasLogs = log_lines.length > 0 || err_lines.length > 0; - const output = { - result, - ...(log_lines.length > 0 && { log_lines }), - ...(err_lines.length > 0 && { err_lines }), - }; - if (is_error) { - return asErrorResult(typeof result === 'string' && !hasLogs ? result : JSON.stringify(output, null, 2)); + // Follow symlinks in node_modules to allow read access to workspace-linked packages + try { + const sdkPkgName = 'hyperspell'; + const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName); + const realSdkDir = fs.realpathSync(sdkDir); + if (realSdkDir !== sdkDir) { + allowReadPaths.push(realSdkDir); } - return asTextContentResult(output); - }; + } catch { + // Ignore if symlink resolution fails + } - return { metadata, tool, handler }; -} + const allowRead = allowReadPaths.join(','); + + const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), { + denoExecutable: denoPath, + runFlags: [ + `--node-modules-dir=manual`, + `--allow-read=${allowRead}`, + `--allow-net=${baseURLHostname}`, + // Allow environment variables because instantiating the client will try to read from them, + // even though they are not set. + '--allow-env', + ], + printOutput: true, + spawnOptions: { + cwd: path.dirname(workerPath), + }, + }); + + try { + const resp = await new Promise((resolve, reject) => { + worker.addEventListener('exit', (exitCode) => { + reject(new Error(`Worker exited with code ${exitCode}`)); + }); + + const opts: ClientOptions = { + baseURL: client.baseURL, + apiKey: client.apiKey, + userID: client.userID, + defaultHeaders: { + 'X-Stainless-MCP': 'true', + }, + }; + + const req = worker.request( + 'http://localhost', + { + headers: { + 'content-type': 'application/json', + }, + method: 'POST', + }, + (resp) => { + const body: Uint8Array[] = []; + resp.on('error', (err) => { + reject(err); + }); + resp.on('data', (chunk) => { + body.push(chunk); + }); + resp.on('end', () => { + resolve( + new Response(Buffer.concat(body).toString(), { + status: resp.statusCode ?? 200, + headers: resp.headers as any, + }), + ); + }); + }, + ); + + const body = JSON.stringify({ + opts, + code, + }); + + req.write(body, (err) => { + if (err != null) { + reject(err); + } + }); + + req.end(); + }); + + if (resp.status === 200) { + const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput; + const returnOutput: ContentBlock | null = + result == null ? null : ( + { + type: 'text', + text: typeof result === 'string' ? result : JSON.stringify(result), + } + ); + const logOutput: ContentBlock | null = + log_lines.length === 0 ? + null + : { + type: 'text', + text: log_lines.join('\n'), + }; + const errOutput: ContentBlock | null = + err_lines.length === 0 ? + null + : { + type: 'text', + text: 'Error output:\n' + err_lines.join('\n'), + }; + return { + content: [returnOutput, logOutput, errOutput].filter((block) => block !== null), + }; + } else { + const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput; + const messageOutput: ContentBlock | null = + result == null ? null : ( + { + type: 'text', + text: typeof result === 'string' ? result : JSON.stringify(result), + } + ); + const logOutput: ContentBlock | null = + log_lines.length === 0 ? + null + : { + type: 'text', + text: log_lines.join('\n'), + }; + const errOutput: ContentBlock | null = + err_lines.length === 0 ? + null + : { + type: 'text', + text: 'Error output:\n' + err_lines.join('\n'), + }; + return { + content: [messageOutput, logOutput, errOutput].filter((block) => block !== null), + isError: true, + }; + } + } finally { + worker.terminate(); + } +}; diff --git a/packages/mcp-server/src/http.ts b/packages/mcp-server/src/http.ts index e5d2f463..9a539974 100644 --- a/packages/mcp-server/src/http.ts +++ b/packages/mcp-server/src/http.ts @@ -24,28 +24,17 @@ const newServer = async ({ const stainlessApiKey = getStainlessApiKey(req, mcpOptions); const server = await newMcpServer(stainlessApiKey); - try { - const authOptions = parseClientAuthHeaders(req, false); + const authOptions = parseClientAuthHeaders(req, false); - await initMcpServer({ - server: server, - mcpOptions: mcpOptions, - clientOptions: { - ...clientOptions, - ...authOptions, - }, - stainlessApiKey: stainlessApiKey, - }); - } catch (error) { - res.status(401).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: `Unauthorized: ${error instanceof Error ? error.message : error}`, - }, - }); - return null; - } + await initMcpServer({ + server: server, + mcpOptions: mcpOptions, + clientOptions: { + ...clientOptions, + ...authOptions, + }, + stainlessApiKey: stainlessApiKey, + }); return server; }; diff --git a/packages/mcp-server/src/index.ts b/packages/mcp-server/src/index.ts index 003a7655..654d25cf 100644 --- a/packages/mcp-server/src/index.ts +++ b/packages/mcp-server/src/index.ts @@ -24,7 +24,7 @@ async function main() { await launchStreamableHTTPServer({ mcpOptions: options, debug: options.debug, - port: options.port ?? options.socket, + port: options.socket ?? options.port, }); break; } diff --git a/packages/mcp-server/src/instructions.ts b/packages/mcp-server/src/instructions.ts new file mode 100644 index 00000000..42ddc65a --- /dev/null +++ b/packages/mcp-server/src/instructions.ts @@ -0,0 +1,74 @@ +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import { readEnv } from './util'; + +const INSTRUCTIONS_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes + +interface InstructionsCacheEntry { + fetchedInstructions: string; + fetchedAt: number; +} + +const instructionsCache = new Map(); + +// Periodically evict stale entries so the cache doesn't grow unboundedly. +const _cacheCleanupInterval = setInterval(() => { + const now = Date.now(); + for (const [key, entry] of instructionsCache) { + if (now - entry.fetchedAt > INSTRUCTIONS_CACHE_TTL_MS) { + instructionsCache.delete(key); + } + } +}, INSTRUCTIONS_CACHE_TTL_MS); + +// Don't keep the process alive just for cleanup. +_cacheCleanupInterval.unref(); + +export async function getInstructions(stainlessApiKey: string | undefined): Promise { + const cacheKey = stainlessApiKey ?? ''; + const cached = instructionsCache.get(cacheKey); + + if (cached && Date.now() - cached.fetchedAt <= INSTRUCTIONS_CACHE_TTL_MS) { + return cached.fetchedInstructions; + } + + const fetchedInstructions = await fetchLatestInstructions(stainlessApiKey); + instructionsCache.set(cacheKey, { fetchedInstructions, fetchedAt: Date.now() }); + return fetchedInstructions; +} + +async function fetchLatestInstructions(stainlessApiKey: string | undefined): Promise { + // Setting the stainless API key is optional, but may be required + // to authenticate requests to the Stainless API. + const response = await fetch( + readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/hyperspell', + { + method: 'GET', + headers: { ...(stainlessApiKey && { Authorization: stainlessApiKey }) }, + }, + ); + + let instructions: string | undefined; + if (!response.ok) { + console.warn( + 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...', + ); + + instructions = ` + This is the hyperspell MCP server. You will use Code Mode to help the user perform + actions. You can use search_docs tool to learn about how to take action with this server. Then, + you will write TypeScript code using the execute tool take action. It is CRITICAL that you be + thoughtful and deliberate when executing code. Always try to entirely solve the problem in code + block: it can be as long as you need to get the job done! + `; + } + + instructions ??= ((await response.json()) as { instructions: string }).instructions; + instructions = ` + If needed, you can get the current time by executing Date.now(). + + ${instructions} + `; + + return instructions; +} diff --git a/packages/mcp-server/src/options.ts b/packages/mcp-server/src/options.ts index 32a88713..9e9d15cd 100644 --- a/packages/mcp-server/src/options.ts +++ b/packages/mcp-server/src/options.ts @@ -19,8 +19,11 @@ export type McpOptions = { codeAllowHttpGets?: boolean | undefined; codeAllowedMethods?: string[] | undefined; codeBlockedMethods?: string[] | undefined; + codeExecutionMode: McpCodeExecutionMode; }; +export type McpCodeExecutionMode = 'stainless-sandbox' | 'local'; + export function parseCLIOptions(): CLIOptions { const opts = yargs(hideBin(process.argv)) .option('code-allow-http-gets', { @@ -40,6 +43,13 @@ export function parseCLIOptions(): CLIOptions { description: 'Methods to explicitly block for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.', }) + .option('code-execution-mode', { + type: 'string', + choices: ['stainless-sandbox', 'local'], + default: 'stainless-sandbox', + description: + "Where to run code execution in code tool; 'stainless-sandbox' will execute code in Stainless-hosted sandboxes whereas 'local' will execute code locally on the MCP server machine.", + }) .option('debug', { type: 'boolean', description: 'Enable debug logging' }) .option('no-tools', { type: 'string', @@ -93,6 +103,7 @@ export function parseCLIOptions(): CLIOptions { codeAllowHttpGets: argv.codeAllowHttpGets, codeAllowedMethods: argv.codeAllowedMethods, codeBlockedMethods: argv.codeBlockedMethods, + codeExecutionMode: argv.codeExecutionMode as McpCodeExecutionMode, transport, port: argv.port, socket: argv.socket, @@ -124,6 +135,7 @@ export function parseQueryOptions(defaultOptions: McpOptions, query: unknown): M : defaultOptions.includeDocsTools; return { + codeExecutionMode: defaultOptions.codeExecutionMode, ...(docsTools !== undefined && { includeDocsTools: docsTools }), }; } diff --git a/packages/mcp-server/src/server.ts b/packages/mcp-server/src/server.ts index b592d58e..7e96073e 100644 --- a/packages/mcp-server/src/server.ts +++ b/packages/mcp-server/src/server.ts @@ -11,52 +11,17 @@ import { ClientOptions } from 'hyperspell'; import Hyperspell from 'hyperspell'; import { codeTool } from './code-tool'; import docsSearchTool from './docs-search-tool'; +import { getInstructions } from './instructions'; import { McpOptions } from './options'; import { blockedMethodsForCodeTool } from './methods'; import { HandlerFunction, McpRequestContext, ToolCallResult, McpTool } from './types'; import { readEnv } from './util'; -async function getInstructions(stainlessApiKey: string | undefined): Promise { - // Setting the stainless API key is optional, but may be required - // to authenticate requests to the Stainless API. - const response = await fetch( - readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/hyperspell', - { - method: 'GET', - headers: { ...(stainlessApiKey && { Authorization: stainlessApiKey }) }, - }, - ); - - let instructions: string | undefined; - if (!response.ok) { - console.warn( - 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...', - ); - - instructions = ` - This is the hyperspell MCP server. You will use Code Mode to help the user perform - actions. You can use search_docs tool to learn about how to take action with this server. Then, - you will write TypeScript code using the execute tool take action. It is CRITICAL that you be - thoughtful and deliberate when executing code. Always try to entirely solve the problem in code - block: it can be as long as you need to get the job done! - `; - } - - instructions ??= ((await response.json()) as { instructions: string }).instructions; - instructions = ` - The current time in Unix timestamps is ${Date.now()}. - - ${instructions} - `; - - return instructions; -} - export const newMcpServer = async (stainlessApiKey: string | undefined) => new McpServer( { name: 'hyperspell_api', - version: '0.31.0', + version: '0.32.0', }, { instructions: await getInstructions(stainlessApiKey), @@ -91,15 +56,33 @@ export async function initMcpServer(params: { error: logAtLevel('error'), }; - let client = new Hyperspell({ - ...{ userID: readEnv('HYPERSPELL_USER_ID') }, - logger, - ...params.clientOptions, - defaultHeaders: { - ...params.clientOptions?.defaultHeaders, - 'X-Stainless-MCP': 'true', - }, - }); + let _client: Hyperspell | undefined; + let _clientError: Error | undefined; + let _logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off' | undefined; + + const getClient = (): Hyperspell => { + if (_clientError) throw _clientError; + if (!_client) { + try { + _client = new Hyperspell({ + ...{ userID: readEnv('HYPERSPELL_USER_ID') }, + logger, + ...params.clientOptions, + defaultHeaders: { + ...params.clientOptions?.defaultHeaders, + 'X-Stainless-MCP': 'true', + }, + }); + if (_logLevel) { + _client = _client.withOptions({ logLevel: _logLevel }); + } + } catch (e) { + _clientError = e instanceof Error ? e : new Error(String(e)); + throw _clientError; + } + } + return _client; + }; const providedTools = selectTools(params.mcpOptions); const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool])); @@ -117,6 +100,21 @@ export async function initMcpServer(params: { throw new Error(`Unknown tool: ${name}`); } + let client: Hyperspell; + try { + client = getClient(); + } catch (error) { + return { + content: [ + { + type: 'text' as const, + text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`, + }, + ], + isError: true, + }; + } + return executeHandler({ handler: mcpTool.handler, reqContext: { @@ -129,24 +127,29 @@ export async function initMcpServer(params: { server.setRequestHandler(SetLevelRequestSchema, async (request) => { const { level } = request.params; + let logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off'; switch (level) { case 'debug': - client = client.withOptions({ logLevel: 'debug' }); + logLevel = 'debug'; break; case 'info': - client = client.withOptions({ logLevel: 'info' }); + logLevel = 'info'; break; case 'notice': case 'warning': - client = client.withOptions({ logLevel: 'warn' }); + logLevel = 'warn'; break; case 'error': - client = client.withOptions({ logLevel: 'error' }); + logLevel = 'error'; break; default: - client = client.withOptions({ logLevel: 'off' }); + logLevel = 'off'; break; } + _logLevel = logLevel; + if (_client) { + _client = _client.withOptions({ logLevel }); + } return {}; }); } @@ -158,6 +161,7 @@ export function selectTools(options?: McpOptions): McpTool[] { const includedTools = [ codeTool({ blockedMethods: blockedMethodsForCodeTool(options), + codeExecutionMode: options?.codeExecutionMode ?? 'stainless-sandbox', }), ]; if (options?.includeDocsTools ?? true) { diff --git a/packages/mcp-server/tests/options.test.ts b/packages/mcp-server/tests/options.test.ts index 7a2d5114..17306295 100644 --- a/packages/mcp-server/tests/options.test.ts +++ b/packages/mcp-server/tests/options.test.ts @@ -1,4 +1,4 @@ -import { parseCLIOptions, parseQueryOptions } from '../src/options'; +import { parseCLIOptions } from '../src/options'; // Mock process.argv const mockArgv = (args: string[]) => { @@ -30,21 +30,3 @@ describe('parseCLIOptions', () => { cleanup(); }); }); - -describe('parseQueryOptions', () => { - const defaultOptions = {}; - - it('default parsing should be empty', () => { - const query = ''; - const result = parseQueryOptions(defaultOptions, query); - - expect(result).toEqual({}); - }); - - it('should handle invalid query string gracefully', () => { - const query = 'invalid=value&tools=invalid-operation'; - - // Should throw due to Zod validation for invalid tools - expect(() => parseQueryOptions(defaultOptions, query)).toThrow(); - }); -}); diff --git a/release-please-config.json b/release-please-config.json index b1909804..9b042792 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -68,6 +68,11 @@ "type": "json", "path": "packages/mcp-server/package.json", "jsonpath": "$.version" + }, + { + "type": "json", + "path": "packages/mcp-server/manifest.json", + "jsonpath": "$.version" } ] } diff --git a/src/resources/auth.ts b/src/resources/auth.ts index d91efc02..fa1d2801 100644 --- a/src/resources/auth.ts +++ b/src/resources/auth.ts @@ -63,8 +63,10 @@ export interface AuthMeResponse { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' | 'web_crawler' + | 'trace' >; /** @@ -79,8 +81,10 @@ export interface AuthMeResponse { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' | 'web_crawler' + | 'trace' >; /** diff --git a/src/resources/connections.ts b/src/resources/connections.ts index 658ad531..9f842b06 100644 --- a/src/resources/connections.ts +++ b/src/resources/connections.ts @@ -55,8 +55,10 @@ export namespace ConnectionListResponse { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; } } diff --git a/src/resources/integrations/integrations.ts b/src/resources/integrations/integrations.ts index 582a18d5..245c6676 100644 --- a/src/resources/integrations/integrations.ts +++ b/src/resources/integrations/integrations.ts @@ -90,8 +90,10 @@ export namespace IntegrationListResponse { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; } } diff --git a/src/resources/integrations/web-crawler.ts b/src/resources/integrations/web-crawler.ts index b4d91963..90cbab8e 100644 --- a/src/resources/integrations/web-crawler.ts +++ b/src/resources/integrations/web-crawler.ts @@ -32,8 +32,10 @@ export interface WebCrawlerIndexResponse { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; status: 'pending' | 'processing' | 'completed' | 'failed'; } diff --git a/src/resources/memories.ts b/src/resources/memories.ts index a39c85b4..0e75b4ff 100644 --- a/src/resources/memories.ts +++ b/src/resources/memories.ts @@ -199,8 +199,10 @@ export interface Memory { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; /** * The type of document (e.g. Document, Website, Email) @@ -236,8 +238,10 @@ export interface MemoryStatus { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; status: 'pending' | 'processing' | 'completed' | 'failed'; } @@ -254,8 +258,10 @@ export interface MemoryListResponse { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; metadata?: Shared.Metadata; @@ -283,8 +289,10 @@ export interface MemoryDeleteResponse { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; success: boolean; } @@ -325,12 +333,14 @@ export interface MemoryUpdateParams { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; /** - * Body param: The collection to move the document to. Set to null to remove the - * collection. + * @deprecated Body param: The collection to move the document to — deprecated, set + * the collection using metadata instead. */ collection?: string | unknown | null; @@ -377,8 +387,10 @@ export interface MemoryListParams extends CursorPageParams { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' | 'web_crawler' + | 'trace' | null; /** @@ -397,8 +409,10 @@ export interface MemoryDeleteParams { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; } export interface MemoryAddParams { @@ -408,7 +422,8 @@ export interface MemoryAddParams { text: string; /** - * The collection to add the document to for easier retrieval. + * @deprecated The collection to add the document to — deprecated, set the + * collection using metadata instead. */ collection?: string | null; @@ -453,7 +468,8 @@ export namespace MemoryAddBulkParams { text: string; /** - * The collection to add the document to for easier retrieval. + * @deprecated The collection to add the document to — deprecated, set the + * collection using metadata instead. */ collection?: string | null; @@ -494,8 +510,10 @@ export interface MemoryGetParams { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; } export interface MemorySearchParams { @@ -531,8 +549,10 @@ export interface MemorySearchParams { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' | 'web_crawler' + | 'trace' >; } @@ -549,7 +569,15 @@ export namespace MemorySearchParams { /** * Model to use for answer generation when answer=True */ - answer_model?: 'llama-3.1' | 'gemma2' | 'qwen-qwq' | 'mistral-saba' | 'llama-4-scout' | 'deepseek-r1'; + answer_model?: + | 'llama-3.1' + | 'gemma2' + | 'qwen-qwq' + | 'mistral-saba' + | 'llama-4-scout' + | 'deepseek-r1' + | 'gpt-oss-20b' + | 'gpt-oss-120b'; /** * Only query documents created before this date. @@ -618,8 +646,6 @@ export namespace MemorySearchParams { * Search options for Box */ export interface Box { - collection?: string | null; - /** * Weight of results from this source. A weight greater than 1.0 means more results * from this source will be returned, a weight less than 1.0 means fewer results @@ -640,8 +666,6 @@ export namespace MemorySearchParams { */ calendar_id?: string | null; - collection?: string | null; - /** * Weight of results from this source. A weight greater than 1.0 means more results * from this source will be returned, a weight less than 1.0 means fewer results @@ -655,8 +679,6 @@ export namespace MemorySearchParams { * Search options for Google Drive */ export interface GoogleDrive { - collection?: string | null; - /** * Weight of results from this source. A weight greater than 1.0 means more results * from this source will be returned, a weight less than 1.0 means fewer results @@ -670,8 +692,6 @@ export namespace MemorySearchParams { * Search options for Gmail */ export interface GoogleMail { - collection?: string | null; - /** * List of label IDs to filter messages (e.g., ['INBOX', 'SENT', 'DRAFT']). * Multiple labels are combined with OR logic - messages matching ANY specified @@ -693,8 +713,6 @@ export namespace MemorySearchParams { * Search options for Notion */ export interface Notion { - collection?: string | null; - /** * List of Notion page IDs to search. If not provided, all pages in the workspace * will be searched. @@ -714,8 +732,6 @@ export namespace MemorySearchParams { * Search options for Reddit */ export interface Reddit { - collection?: string | null; - /** * The time period to search. Defaults to 'month'. */ @@ -750,8 +766,6 @@ export namespace MemorySearchParams { */ channels?: Array; - collection?: string | null; - /** * If set, pass 'exclude_archived' to Slack. If None, omit the param. */ @@ -786,8 +800,6 @@ export namespace MemorySearchParams { * Search options for vault */ export interface Vault { - collection?: string | null; - /** * Weight of results from this source. A weight greater than 1.0 means more results * from this source will be returned, a weight less than 1.0 means fewer results @@ -801,8 +813,6 @@ export namespace MemorySearchParams { * Search options for Web Crawler */ export interface WebCrawler { - collection?: string | null; - /** * Maximum depth to crawl from the starting URL */ @@ -831,7 +841,8 @@ export interface MemoryUploadParams { file: Uploadable; /** - * The collection to add the document to. + * @deprecated The collection to add the document to — deprecated, set the + * collection using metadata instead. */ collection?: string | null; diff --git a/src/resources/shared.ts b/src/resources/shared.ts index 0b317e8d..92d6891f 100644 --- a/src/resources/shared.ts +++ b/src/resources/shared.ts @@ -65,8 +65,10 @@ export namespace QueryResult { | 'box' | 'dropbox' | 'google_drive' + | 'github' | 'vault' - | 'web_crawler'; + | 'web_crawler' + | 'trace'; metadata?: Shared.Metadata; diff --git a/src/version.ts b/src/version.ts index b6314c28..b413d151 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.31.0'; // x-release-please-version +export const VERSION = '0.32.0'; // x-release-please-version diff --git a/tests/api-resources/memories.test.ts b/tests/api-resources/memories.test.ts index 8af38cd4..59824d2f 100644 --- a/tests/api-resources/memories.test.ts +++ b/tests/api-resources/memories.test.ts @@ -160,27 +160,14 @@ describe('resource memories', () => { after: '2019-12-27T18:11:19.117Z', answer_model: 'llama-3.1', before: '2019-12-27T18:11:19.117Z', - box: { collection: 'collection', weight: 0 }, + box: { weight: 0 }, filter: { foo: 'bar' }, - google_calendar: { - calendar_id: 'calendar_id', - collection: 'collection', - weight: 0, - }, - google_drive: { collection: 'collection', weight: 0 }, - google_mail: { - collection: 'collection', - label_ids: ['string'], - weight: 0, - }, + google_calendar: { calendar_id: 'calendar_id', weight: 0 }, + google_drive: { weight: 0 }, + google_mail: { label_ids: ['string'], weight: 0 }, max_results: 0, - notion: { - collection: 'collection', - notion_page_ids: ['string'], - weight: 0, - }, + notion: { notion_page_ids: ['string'], weight: 0 }, reddit: { - collection: 'collection', period: 'hour', sort: 'relevance', subreddit: 'subreddit', @@ -188,16 +175,14 @@ describe('resource memories', () => { }, slack: { channels: ['string'], - collection: 'collection', exclude_archived: true, include_dms: true, include_group_dms: true, include_private: true, weight: 0, }, - vault: { collection: 'collection', weight: 0 }, + vault: { weight: 0 }, web_crawler: { - collection: 'collection', max_depth: 0, url: 'url', weight: 0,