diff --git a/.oxlintrc.jsonc b/.oxlintrc.jsonc index 0bf6cf98..93ba0983 100644 --- a/.oxlintrc.jsonc +++ b/.oxlintrc.jsonc @@ -25,12 +25,17 @@ // - perf (11 rules): Performance-related issues // - style (168 rules): Code style rules // Note: restriction category should be enabled per-rule basis + // + // pedantic and style are off. oxlint only reads .oxlintrc.jsonc from 1.52.0, so until the nix + // flake moved to 1.88 this file was never loaded and CI ran oxlint's 104 default rules. Turned on + // as written, the two categories report about 4,000 findings in code never held to them; adopting + // them is its own change. The rules named one by one below still apply. "categories": { "correctness": "error", "suspicious": "error", - "pedantic": "error", + "pedantic": "off", "perf": "error", - "style": "error", + "style": "off", }, "rules": { // =================== @@ -139,7 +144,7 @@ // Import Rules // =================== // Enforce top-level type specifier style - "import/consistent-type-specifier-style": ["error", "top-level"], + "import/consistent-type-specifier-style": ["error", "prefer-top-level"], // =================== // Unicorn Rules // =================== diff --git a/examples/ai-sdk-integration.ts b/examples/ai-sdk-integration.ts index aec03e93..be312b07 100644 --- a/examples/ai-sdk-integration.ts +++ b/examples/ai-sdk-integration.ts @@ -18,11 +18,11 @@ import { StackOneToolSet } from '@stackone/ai'; import { generateText, stepCountIs } from 'ai'; const apiKey = process.env.STACKONE_API_KEY; -if (!apiKey) { +if (apiKey === undefined || apiKey === '') { console.error('STACKONE_API_KEY environment variable is required'); process.exit(1); } -if (!process.env.OPENAI_API_KEY) { +if ((process.env.OPENAI_API_KEY ?? '') === '') { console.log('Skipping: OPENAI_API_KEY is not set'); process.exit(0); } @@ -30,7 +30,8 @@ if (!process.env.OPENAI_API_KEY) { const aiSdkIntegration = async (): Promise => { // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; // without one, the toolset uses every active shared account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); + const accountId = process.env.STACKONE_ACCOUNT_ID; + const toolset = new StackOneToolSet({ accountId: accountId === '' ? undefined : accountId }); // Filter to specific tools to keep token usage manageable const tools = await toolset.fetchTools({ @@ -53,7 +54,7 @@ const aiSdkIntegration = async (): Promise => { console.log(`Steps taken: ${steps.length}`); for (const step of steps) { - if (step.toolCalls && step.toolCalls.length > 0) { + if (step.toolCalls.length > 0) { for (const toolCall of step.toolCalls) { console.log(` Tool call: ${toolCall.toolName}`); console.log(` Arguments: ${JSON.stringify((toolCall as Record).args)}`); diff --git a/examples/anthropic-integration.ts b/examples/anthropic-integration.ts index 535511ec..61762159 100644 --- a/examples/anthropic-integration.ts +++ b/examples/anthropic-integration.ts @@ -7,11 +7,11 @@ import Anthropic from '@anthropic-ai/sdk'; import { StackOneToolSet } from '@stackone/ai'; const apiKey = process.env.STACKONE_API_KEY; -if (!apiKey) { +if (apiKey === undefined || apiKey === '') { console.error('STACKONE_API_KEY environment variable is required'); process.exit(1); } -if (!process.env.ANTHROPIC_API_KEY) { +if ((process.env.ANTHROPIC_API_KEY ?? '') === '') { console.log('Skipping: ANTHROPIC_API_KEY is not set'); process.exit(0); } @@ -19,7 +19,8 @@ if (!process.env.ANTHROPIC_API_KEY) { const anthropicIntegration = async (): Promise => { // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; // without one, the toolset uses every active shared account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); + const accountId = process.env.STACKONE_ACCOUNT_ID; + const toolset = new StackOneToolSet({ accountId: accountId === '' ? undefined : accountId }); // Filter for any relevant tools const tools = await toolset.fetchTools({ diff --git a/examples/auth-management.ts b/examples/auth-management.ts index 5ec144ca..8467a2fb 100644 --- a/examples/auth-management.ts +++ b/examples/auth-management.ts @@ -13,11 +13,17 @@ import process from 'node:process'; import { StackOneToolSet } from '@stackone/ai'; -if (!process.env.STACKONE_API_KEY) { +if ((process.env.STACKONE_API_KEY ?? '') === '') { console.error('Set STACKONE_API_KEY to run this example.'); process.exit(1); } +/** STACKONE_ACCOUNT_ID, or undefined when it is unset or empty. */ +const envAccountId = (): string | undefined => { + const accountId = process.env.STACKONE_ACCOUNT_ID; + return accountId === '' ? undefined : accountId; +}; + // --- 1. API Key setup --- const apiKeyFromEnv = async (): Promise => { console.log('=== 1a. API Key from environment ===\n'); @@ -54,8 +60,8 @@ const accountIdFromEnv = async (): Promise => { // The SDK only reads the API key from env; read the account id yourself and pass it. // Unset or empty, it is undefined and the toolset discovers every active shared account instead. - const accountId = process.env.STACKONE_ACCOUNT_ID || undefined; - console.log(` STACKONE_ACCOUNT_ID is ${accountId ? 'set' : 'not set'}`); + const accountId = envAccountId(); + console.log(` STACKONE_ACCOUNT_ID is ${accountId === undefined ? 'not set' : 'set'}`); const toolset = new StackOneToolSet({ accountId }); const tools = await toolset.fetchTools(); @@ -66,7 +72,7 @@ const accountIdFromEnv = async (): Promise => { const accountIdInConstructor = async (): Promise => { console.log('=== 3. Account ID in constructor ===\n'); - const accountId = process.env.STACKONE_ACCOUNT_ID || 'my-account'; + const accountId = envAccountId() ?? 'my-account'; const toolset = new StackOneToolSet({ accountId }); const tools = await toolset.fetchTools(); console.log(` Loaded ${tools.toOpenAI().length} tools for configured account\n`); @@ -76,7 +82,7 @@ const accountIdInConstructor = async (): Promise => { const setAccountsGlobally = async (): Promise => { console.log('=== 4. setAccounts() — global account list ===\n'); - const accountId = process.env.STACKONE_ACCOUNT_ID || 'my-account'; + const accountId = envAccountId() ?? 'my-account'; const toolset = new StackOneToolSet(); toolset.setAccounts([accountId]); console.log(' Called setAccounts() with configured account'); diff --git a/examples/claude-agent-sdk-integration.ts b/examples/claude-agent-sdk-integration.ts index f79219b3..28d13d97 100644 --- a/examples/claude-agent-sdk-integration.ts +++ b/examples/claude-agent-sdk-integration.ts @@ -13,11 +13,11 @@ import { query } from '@anthropic-ai/claude-agent-sdk'; import { StackOneToolSet } from '@stackone/ai'; const apiKey = process.env.STACKONE_API_KEY; -if (!apiKey) { +if (apiKey === undefined || apiKey === '') { console.error('STACKONE_API_KEY environment variable is required'); process.exit(1); } -if (!process.env.ANTHROPIC_API_KEY) { +if ((process.env.ANTHROPIC_API_KEY ?? '') === '') { console.log('Skipping: ANTHROPIC_API_KEY is not set'); process.exit(0); } @@ -25,7 +25,8 @@ if (!process.env.ANTHROPIC_API_KEY) { const claudeAgentSdkIntegration = async (): Promise => { // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; // without one, the toolset uses every active shared account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); + const accountId = process.env.STACKONE_ACCOUNT_ID; + const toolset = new StackOneToolSet({ accountId: accountId === '' ? undefined : accountId }); // Fetch tools from StackOne and convert to Claude Agent SDK format const tools = await toolset.fetchTools(); @@ -39,7 +40,7 @@ const claudeAgentSdkIntegration = async (): Promise => { options: { model: 'claude-sonnet-4-5-20250929', mcpServers: { - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Compatible MCP server type + // oxlint-disable-next-line typescript/no-explicit-any, typescript/no-unsafe-type-assertion -- Compatible MCP server type 'stackone-tools': mcpServer as any, }, // Disable built-in tools, only use our custom tools diff --git a/examples/openai-integration.ts b/examples/openai-integration.ts index 6937ecf7..f1b7c5a4 100644 --- a/examples/openai-integration.ts +++ b/examples/openai-integration.ts @@ -7,19 +7,33 @@ import { StackOneToolSet } from '@stackone/ai'; import OpenAI from 'openai'; const apiKey = process.env.STACKONE_API_KEY; -if (!apiKey) { +if (apiKey === undefined || apiKey === '') { console.error('STACKONE_API_KEY environment variable is required'); process.exit(1); } -if (!process.env.OPENAI_API_KEY) { +if ((process.env.OPENAI_API_KEY ?? '') === '') { console.log('Skipping: OPENAI_API_KEY is not set'); process.exit(0); } +/** The text of a completion's first choice, or `''` when it has none. */ +const replyText = (completion: OpenAI.ChatCompletion): string => + completion.choices[0]?.message.content ?? ''; + +const printToolCalls = (toolCalls: OpenAI.ChatCompletionMessageToolCall[]): void => { + for (const toolCall of toolCalls) { + if (toolCall.type === 'function') { + console.log(` Tool: ${toolCall.function.name}`); + console.log(` Arguments: ${toolCall.function.arguments}`); + } + } +}; + const openaiIntegration = async (): Promise => { // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; // without one, the toolset uses every active shared account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); + const accountId = process.env.STACKONE_ACCOUNT_ID; + const toolset = new StackOneToolSet({ accountId: accountId === '' ? undefined : accountId }); // Filter to specific tools to stay within OpenAI's 128-tool limit const tools = await toolset.fetchTools({ @@ -51,16 +65,11 @@ const openaiIntegration = async (): Promise => { const message = response.choices[0]?.message; const toolCalls = message?.tool_calls ?? []; console.log(`Tool calls made: ${toolCalls.length}`); - if (!message || toolCalls.length === 0) { + if (message === undefined || toolCalls.length === 0) { return; } - for (const toolCall of toolCalls) { - if (toolCall.type === 'function') { - console.log(` Tool: ${toolCall.function.name}`); - console.log(` Arguments: ${toolCall.function.arguments}`); - } - } + printToolCalls(toolCalls); // Run the tool calls and hand the results back. The assistant turn must come before its tool // results, or OpenAI returns a 400. A failed call becomes a tool message the model can read. @@ -71,7 +80,7 @@ const openaiIntegration = async (): Promise => { messages, tools: openAITools, }); - console.log(`Answer: ${final.choices[0]?.message.content ?? ''}`); + console.log(`Answer: ${replyText(final)}`); }; // Run the example diff --git a/examples/openai-responses-integration.ts b/examples/openai-responses-integration.ts index 65161bf8..09536b50 100644 --- a/examples/openai-responses-integration.ts +++ b/examples/openai-responses-integration.ts @@ -7,11 +7,11 @@ import { StackOneToolSet } from '@stackone/ai'; import OpenAI from 'openai'; const apiKey = process.env.STACKONE_API_KEY; -if (!apiKey) { +if (apiKey === undefined || apiKey === '') { console.error('STACKONE_API_KEY environment variable is required'); process.exit(1); } -if (!process.env.OPENAI_API_KEY) { +if ((process.env.OPENAI_API_KEY ?? '') === '') { console.log('Skipping: OPENAI_API_KEY is not set'); process.exit(0); } @@ -19,7 +19,8 @@ if (!process.env.OPENAI_API_KEY) { const openaiResponsesIntegration = async (): Promise => { // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; // without one, the toolset uses every active shared account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); + const accountId = process.env.STACKONE_ACCOUNT_ID; + const toolset = new StackOneToolSet({ accountId: accountId === '' ? undefined : accountId }); // Fetch tools via MCP const tools = await toolset.fetchTools({ diff --git a/examples/search-and-execute.ts b/examples/search-and-execute.ts index 85ac3bdd..697bf88d 100644 --- a/examples/search-and-execute.ts +++ b/examples/search-and-execute.ts @@ -16,30 +16,40 @@ import process from 'node:process'; import { StackOneError, StackOneToolSet, ToolSetError } from '@stackone/ai'; +import type { SearchResult, StackOneAccount } from '@stackone/ai'; -if (!process.env.STACKONE_API_KEY) { +if ((process.env.STACKONE_API_KEY ?? '') === '') { console.error('STACKONE_API_KEY environment variable is required'); process.exit(1); } +const printAccounts = (accounts: StackOneAccount[]): void => { + for (const account of accounts) { + console.log(`${account.id} ${account.provider ?? '?'} ${account.status ?? '?'}`); + } +}; + +const printRankedMatches = (actions: SearchResult[]): void => { + console.log('\nRanked matches:'); + for (const action of actions) { + // oxlint-disable-next-line typescript/no-unnecessary-type-conversion -- a server can send the score as a numeric string + console.log(` ${Number(action.similarity_score ?? 0).toFixed(3)} ${action.action_id}`); + } +}; + const searchAndExecute = async (): Promise => { const toolset = new StackOneToolSet(); - for (const account of await toolset.fetchAccounts()) { - console.log(`${account.id} ${account.provider ?? '?'} ${account.status ?? '?'}`); - } + printAccounts(await toolset.fetchAccounts()); const actions = await toolset.search('list recent comments', { topK: 3 }); const [best] = actions; - if (!best) { + if (best === undefined) { console.error('No actions matched. Try a different query, or link an account.'); process.exit(1); } - console.log('\nRanked matches:'); - for (const action of actions) { - console.log(` ${Number(action.similarity_score ?? 0).toFixed(3)} ${action.action_id}`); - } + printRankedMatches(actions); // input_schema is how you find out what an action accepts. Build the call from it and from // example_request: arguments that do not match are dropped by the server without an error, diff --git a/flake.nix b/flake.nix index 933d1920..d037d68c 100644 --- a/flake.nix +++ b/flake.nix @@ -65,7 +65,7 @@ # runtime nodejs_24 pnpm_10 - typescript-go + typescript # formatting and linting tools similarity diff --git a/mocks/handlers.openai.ts b/mocks/handlers.openai.ts index 6f004c2e..994d2fe2 100644 --- a/mocks/handlers.openai.ts +++ b/mocks/handlers.openai.ts @@ -1,5 +1,21 @@ import { http, HttpResponse } from 'msw'; -import { extractTextFromInput } from './handlers.utils'; +import { bodyField, extractTextFromInput, isRecord, offersTools } from './handlers.utils'; + +/** The first user message of a chat completion that mentions an employee, or `''`. */ +const employeeQuestion = (messages: unknown): string => { + if (!Array.isArray(messages)) { + return ''; + } + const candidates: unknown[] = messages; + for (const message of candidates) { + if (isRecord(message) && message.role === 'user' && typeof message.content === 'string') { + if (message.content.includes('employee')) { + return message.content; + } + } + } + return ''; +}; /** * OpenAI API endpoints for AI SDK and OpenAI integration examples @@ -7,12 +23,9 @@ import { extractTextFromInput } from './handlers.utils'; export const openaiHandlers = [ // OpenAI Responses API (used by AI SDK) http.post('https://api.openai.com/v1/responses', async ({ request }) => { - const body = (await request.json()) as { - input?: unknown; - tools?: Array<{ name?: string }>; - }; - const userMessage = extractTextFromInput(body.input); - const hasTools = body.tools && body.tools.length > 0; + const body = await request.json(); + const userMessage = extractTextFromInput(bodyField(body, 'input')); + const hasTools = offersTools(body); // For ai-sdk-integration.ts if (hasTools && userMessage.includes('Get all details')) { @@ -115,14 +128,9 @@ export const openaiHandlers = [ // OpenAI Chat Completions API (used by OpenAI SDK directly) http.post('https://api.openai.com/v1/chat/completions', async ({ request }) => { - const body = (await request.json()) as { - messages?: Array<{ content?: string; role?: string }>; - tools?: Array<{ function?: { name?: string } }>; - }; - const userMessage = - body.messages?.find((m) => m.role === 'user' && m.content?.includes('employee'))?.content ?? - ''; - const hasTools = body.tools && body.tools.length > 0; + const body = await request.json(); + const userMessage = employeeQuestion(bodyField(body, 'messages')); + const hasTools = offersTools(body); // For openai-integration.ts - returns tool call for bamboohr_get_employee if (hasTools && userMessage.includes('c28xIQaWQ6MzM5MzczMDA2NzMzMzkwNzIwNA')) { diff --git a/mocks/handlers.stackone-accounts.ts b/mocks/handlers.stackone-accounts.ts index 293cc2f9..f38a3b31 100644 --- a/mocks/handlers.stackone-accounts.ts +++ b/mocks/handlers.stackone-accounts.ts @@ -12,7 +12,7 @@ export const mockAccounts = [ export const stackoneAccountsHandlers = [ http.get(`${TEST_BASE_URL}/accounts`, ({ request }) => { - if (!request.headers.get('Authorization')?.startsWith('Basic ')) { + if (request.headers.get('Authorization')?.startsWith('Basic ') !== true) { return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 }); } return HttpResponse.json(mockAccounts); diff --git a/mocks/handlers.utils.ts b/mocks/handlers.utils.ts index da473868..c8225dfa 100644 --- a/mocks/handlers.utils.ts +++ b/mocks/handlers.utils.ts @@ -1,29 +1,56 @@ +/** Whether a parsed JSON value is an object whose fields can be read. */ +export const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null; + +/** A field of a parsed JSON request body, or undefined when the body is not an object. */ +export const bodyField = (body: unknown, key: string): unknown => + isRecord(body) ? body[key] : undefined; + +/** Whether a parsed OpenAI request body offers the model at least one tool. */ +export const offersTools = (body: unknown): boolean => { + const tools = bodyField(body, 'tools'); + return Array.isArray(tools) && tools.length > 0; +}; + +const isInputText = (content: unknown): content is Record => + isRecord(content) && content.type === 'input_text'; + +/** The text of a user message: its string content, or the text of its first `input_text` part. */ +const userMessageText = (item: unknown): string | undefined => { + if (!isRecord(item) || item.role !== 'user') { + return undefined; + } + // For chat completions format + if (typeof item.content === 'string') { + return item.content; + } + if (!Array.isArray(item.content)) { + return undefined; + } + const parts: unknown[] = item.content; + const inputText = parts.find(isInputText); + if (inputText === undefined) { + return undefined; + } + return typeof inputText.text === 'string' ? inputText.text : ''; +}; + /** * Helper to extract text content from OpenAI responses API input */ export const extractTextFromInput = (input: unknown): string => { // Handle string input directly (OpenAI Responses API can accept plain strings) - if (typeof input === 'string') return input; - if (!Array.isArray(input)) return ''; - for (const item of input) { - if (typeof item === 'object' && item !== null) { - const obj = item as Record; - if (obj.role === 'user' && Array.isArray(obj.content)) { - for (const content of obj.content) { - if ( - typeof content === 'object' && - content !== null && - (content as Record).type === 'input_text' - ) { - const textValue = (content as Record).text; - return typeof textValue === 'string' ? textValue : ''; - } - } - } - // For chat completions format - if (obj.role === 'user' && typeof obj.content === 'string') { - return obj.content; - } + if (typeof input === 'string') { + return input; + } + if (!Array.isArray(input)) { + return ''; + } + const items: unknown[] = input; + for (const item of items) { + const text = userMessageText(item); + if (text !== undefined) { + return text; } } return ''; diff --git a/mocks/mcp-server.ts b/mocks/mcp-server.ts index 7ecdf633..f92760cb 100644 --- a/mocks/mcp-server.ts +++ b/mocks/mcp-server.ts @@ -9,13 +9,11 @@ import type { Hono as HonoApp } from 'hono'; import { StreamableHTTPTransport } from '@hono/mcp'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; -import { - CallToolRequestSchema, - type CallToolResult, - ListToolsRequestSchema, -} from '@modelcontextprotocol/sdk/types.js'; +import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { Hono } from 'hono'; import { basicAuth } from 'hono/basic-auth'; +import { isRecord } from './handlers.utils'; export interface McpToolDefinition { name: string; @@ -156,6 +154,49 @@ const callMetaTool = (name: string, args: Record): CallToolResu return undefined; }; +/** The feedback tool's answer: recorded, against the session it names. */ +const feedbackRecorded = (args: Record): CallToolResult => + wrapped({ + message: 'Feedback recorded', + submitted_at: new Date(0).toISOString(), + session_id: args.session_id ?? null, + }); + +/** The `method` a JSON-RPC message calls, if it names one. */ +export const jsonRpcMethod = (message: unknown): string | undefined => + isRecord(message) && typeof message.method === 'string' ? message.method : undefined; + +/** The tool a JSON-RPC message calls, and its arguments, when it is a `tools/call`. */ +const toolCallIn = (message: unknown): Pick | undefined => { + if (jsonRpcMethod(message) !== 'tools/call' || !isRecord(message) || !isRecord(message.params)) { + return undefined; + } + const { name, arguments: args } = message.params; + return typeof name === 'string' ? { name, arguments: isRecord(args) ? args : {} } : undefined; +}; + +/** + * Report each `tools/call` in a POST to `record`. Read from the raw body: the server's schema + * parsing rebuilds the arguments, and drops a `__proto__` key on the way, so a call recorded after + * it is not what was sent. + */ +const recordToolCalls = async ( + request: Request, + record: MockMcpServerOptions['onToolCall'], + scope: Pick, +): Promise => { + if (record === undefined || request.method !== 'POST') { + return; + } + const body: unknown = await request.clone().json(); + for (const message of Array.isArray(body) ? body : [body]) { + const call = toolCallIn(message); + if (call !== undefined) { + record({ ...scope, ...call }); + } + } +}; + /** * Creates a Hono app speaking the MCP protocol at `/mcp`, for use from an MSW handler. * @@ -170,6 +211,10 @@ const callMetaTool = (name: string, args: Record): CallToolResu */ export function createMcpApp(options: MockMcpServerOptions): HonoApp { const { accountTools, submitFeedback = false, onToolCall, toolResults = {} } = options; + const listedTools = (accountId: string, toolMode: string | undefined): McpToolDefinition[] => [ + ...(submitFeedback ? [submitFeedbackTool] : []), + ...(toolMode === 'search_execute' ? metaTools(accountId) : accountTools[accountId]), + ]; // Create a Hono app that handles MCP protocol const app = new Hono(); @@ -188,7 +233,7 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { // permissive than production and hid a fatal SDK bug: an SDK that never sent the header // still got a full catalog. const accountId = c.req.header('x-account-id') ?? c.req.query('x-account-id'); - if (!accountId) { + if (accountId === undefined || accountId === '') { return c.json( { statusCode: 400, message: 'Missing x-account-id header or query parameter in request' }, 400, @@ -201,10 +246,7 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { } const toolMode = c.req.query('tool-mode'); - const listed: McpToolDefinition[] = [ - ...(submitFeedback ? [submitFeedbackTool] : []), - ...(toolMode === 'search_execute' ? metaTools(accountId) : (accountTools[accountId] ?? [])), - ]; + const listed = listedTools(accountId, toolMode); // A low-level Server rather than McpServer: McpServer.registerTool expects a Zod shape and // lists a plain JSON Schema as `properties: {}`. The real endpoint serves each schema @@ -224,15 +266,11 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { return text({ error: `Unknown tool ${name}`, status_code: 404 }, true); } const literal = toolResults[name]; - if (literal) { + if (literal !== undefined) { return structuredClone(literal); } if (name === submitFeedbackTool.name) { - return wrapped({ - message: 'Feedback recorded', - submitted_at: new Date(0).toISOString(), - session_id: args.session_id ?? null, - }); + return feedbackRecorded(args); } // An action tool echoes what reached it, so a test can see the arguments and account. // Only search_execute serves meta tools: in individual mode a per-action tool whose @@ -243,20 +281,7 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { ); }); - // Recorded from the raw body: the server's schema parsing rebuilds the arguments, and drops - // a `__proto__` key on the way, so a call recorded after it is not what was sent. - if (onToolCall && c.req.method === 'POST') { - const body = (await c.req.raw.clone().json()) as unknown; - for (const message of Array.isArray(body) ? body : [body]) { - const { method, params } = (message ?? {}) as { - method?: string; - params?: { name?: string; arguments?: Record }; - }; - if (method === 'tools/call' && typeof params?.name === 'string') { - onToolCall({ accountId, toolMode, name: params.name, arguments: params.arguments ?? {} }); - } - } - } + await recordToolCalls(c.req.raw, onToolCall, { accountId, toolMode }); const transport = new StreamableHTTPTransport(); await mcp.connect(transport); diff --git a/scripts/package-exports.test.ts b/scripts/package-exports.test.ts index 519a0d04..a2d9d5f6 100644 --- a/scripts/package-exports.test.ts +++ b/scripts/package-exports.test.ts @@ -16,8 +16,10 @@ const rootDir = fileURLToPath(new URL('..', import.meta.url)); // map surfaces as a test failure rather than a compile error in this file. const rootExport: string | { require?: string; import?: string } = publishConfig.exports['.']; const conditions = typeof rootExport === 'string' ? { import: rootExport } : rootExport; -const cjsEntry = conditions.require ? path.resolve(rootDir, conditions.require) : undefined; -const esmEntry = conditions.import ? path.resolve(rootDir, conditions.import) : undefined; +const entryPath = (file: string | undefined) => + file === undefined || file === '' ? undefined : path.resolve(rootDir, file); +const cjsEntry = entryPath(conditions.require); +const esmEntry = entryPath(conditions.import); const cjsReady = cjsEntry !== undefined && existsSync(cjsEntry); const esmReady = esmEntry !== undefined && existsSync(esmEntry); @@ -47,7 +49,7 @@ async function createConsumerFixture(tempDir: string): Promise { { cwd: rootDir }, ); const tarballName = (await readdir(tempDir)).find((file) => file.endsWith('.tgz')); - if (!tarballName) { + if (tarballName === undefined) { throw new Error('pnpm pack did not produce a tarball'); } await execFileAsync('tar', ['-xzf', tarballName], { cwd: tempDir }); @@ -100,17 +102,16 @@ describe('published package output', () => { it.skipIf(!cjsReady)('exposes the public API from the CJS entry via require()', () => { const requireFromTest = createRequire(import.meta.url); - const moduleExports = requireFromTest(String(cjsEntry)) as Record; + const moduleExports: Record = requireFromTest(String(cjsEntry)); for (const exportName of PUBLIC_API_SAMPLE) { expect(moduleExports[exportName], exportName).toBeTypeOf('function'); } }); it.skipIf(!esmReady)('exposes the public API from the ESM entry via import()', async () => { - const moduleExports = (await import(pathToFileURL(String(esmEntry)).href)) as Record< - string, - unknown - >; + const moduleExports: Record = await import( + pathToFileURL(String(esmEntry)).href + ); for (const exportName of PUBLIC_API_SAMPLE) { expect(moduleExports[exportName], exportName).toBeTypeOf('function'); } @@ -128,9 +129,11 @@ describe('published package output', () => { await execFileAsync('pnpm', ['exec', 'tsc', '-p', consumerDir], { cwd: rootDir }); } catch (error) { const execError = (error ?? {}) as { stdout?: string; stderr?: string }; - const details = - `${execError.stdout ?? ''}${execError.stderr ?? ''}`.trim() || String(error); - throw new Error(`tsc failed for the Node16 consumer fixture:\n${details}`); + const output = `${execError.stdout ?? ''}${execError.stderr ?? ''}`.trim(); + const details = output === '' ? String(error) : output; + throw new Error(`tsc failed for the Node16 consumer fixture:\n${details}`, { + cause: error, + }); } } finally { await rm(tempDir, { recursive: true, force: true }); diff --git a/src/end-user-id.test.ts b/src/end-user-id.test.ts index fbfe986f..bfc30fcc 100644 --- a/src/end-user-id.test.ts +++ b/src/end-user-id.test.ts @@ -5,7 +5,7 @@ */ import { http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; -import { accountMcpTools, createMcpApp } from '../mocks/mcp-server'; +import { accountMcpTools, createMcpApp, jsonRpcMethod } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { StackOneToolSet } from './toolsets'; import type { StackOneTool, Tools } from './tool'; @@ -62,10 +62,10 @@ const serve = ( }), http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { if (request.method === 'POST') { - const body = (await request.clone().json()) as unknown; + const body: unknown = await request.clone().json(); for (const message of Array.isArray(body) ? body : [body]) { exchanges.push({ - method: String((message as { method?: unknown }).method), + method: String(jsonRpcMethod(message)), accountId: request.headers.get('x-account-id'), endUserId: request.headers.get('x-end-user-id'), }); @@ -99,15 +99,17 @@ const endUserIdsFor = (exchanges: McpExchange[], accountId: string) => const getTool = (tools: Tools, name: string): StackOneTool => { const tool = tools.getStackOneTools().find((candidate) => candidate.name === name); - if (!tool) { + if (tool === undefined) { throw new Error(`${name} was not listed`); } return tool; }; +const silence = (): void => undefined; + let warnSpy: ReturnType; beforeEach(() => { - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(silence); }); afterEach(() => { vi.restoreAllMocks(); @@ -143,9 +145,8 @@ describe('x-end-user-id after account discovery', () => { await toolset.execute('mock_list_items', {}, { accountIds: ['acc1'] }); await toolset.submitFeedback({ rating: 'positive', toolNames: ['mock_list_items'] }); - const calls = exchanges - .filter((exchange) => exchange.method === 'tools/call') - .sort((left, right) => String(left.accountId).localeCompare(String(right.accountId))); + const calls = exchanges.filter((exchange) => exchange.method === 'tools/call'); + calls.sort((left, right) => String(left.accountId).localeCompare(String(right.accountId))); expect(calls).toEqual([ { method: 'tools/call', accountId: 'acc1', endUserId: 'alice' }, { method: 'tools/call', accountId: 'acc1', endUserId: 'alice' }, @@ -272,10 +273,10 @@ describe('x-end-user-id after fetchAccounts()', () => { }), http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { if (request.method === 'POST') { - const body = (await request.clone().json()) as unknown; + const body: unknown = await request.clone().json(); for (const message of Array.isArray(body) ? body : [body]) { exchanges.push({ - method: String((message as { method?: unknown }).method), + method: String(jsonRpcMethod(message)), accountId: request.headers.get('x-account-id'), endUserId: request.headers.get('x-end-user-id'), }); @@ -426,13 +427,18 @@ describe('x-end-user-id as a model-supplied header argument', () => { }); }); -describe('non-shared accounts in discovery', () => { - const skipped = (accounts: string) => - `[@stackone/ai] Discovery skipped ${accounts.split(', ').length} non-shared account(s) (${accounts}): each belongs to a single end user. Pass their account ids, or opt in to non-shared accounts, to use them.`; - const warnings = (): string[] => warnSpy.mock.calls.map((args: unknown[]) => String(args[0])); - const accountsOf = (tools: Tools) => - [...new Set(tools.getStackOneTools().map((tool) => String(tool.getAccountId())))].sort(); +const skipped = (accounts: string) => + `[@stackone/ai] Discovery skipped ${accounts.split(', ').length} non-shared account(s) (${accounts}): each belongs to a single end user. Pass their account ids, or opt in to non-shared accounts, to use them.`; +const warnings = (): string[] => warnSpy.mock.calls.map((args: unknown[]) => String(args[0])); +const accountsOf = (tools: Tools) => { + const accounts = [ + ...new Set(tools.getStackOneTools().map((tool) => String(tool.getAccountId()))), + ]; + accounts.sort(); + return accounts; +}; +describe('non-shared accounts in discovery', () => { it('are skipped by default, with one warning per discovery', async () => { const { exchanges } = serve([ ...ACCOUNTS, @@ -586,9 +592,9 @@ describe('x-end-user-id for an explicit account the API says is not shared', () .fetchTools() .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(400); - expect((error as Error).message).toContain( + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(400); + expect(error.message).toContain( 'x-end-user-id header does not match account end user id for account acc1', ); expect(accountRequests()).toBe(1); @@ -604,15 +610,15 @@ describe('x-end-user-id for an explicit account the API says is not shared', () .fetchTools() .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(400); - expect((error as Error).message).toContain( + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(400); + expect(error.message).toContain( 'x-end-user-id header does not match account end user id for account acc1', ); - const cause = (error as Error).cause; - expect(cause).toBeInstanceOf(StackOneAPIError); - expect((cause as StackOneAPIError).statusCode).toBe(403); - expect((cause as Error).message).toContain('missing scope platform.read'); + const cause = error.cause; + assert.instanceOf(cause, StackOneAPIError); + expect(cause.statusCode).toBe(403); + expect(cause.message).toContain('missing scope platform.read'); }); it('is not looked up again when one is already recorded', async () => { @@ -645,8 +651,8 @@ describe('x-end-user-id for an explicit account the API says is not shared', () .fetchTools() .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); }); it('is looked up whatever the refusal names the account as', async () => { @@ -654,7 +660,7 @@ describe('x-end-user-id for an explicit account the API says is not shared', () server.use( // With the header, fall through to serve()'s own guard and catalog. http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => - request.headers.get('x-end-user-id') + (request.headers.get('x-end-user-id') ?? '') !== '' ? undefined : HttpResponse.json( { diff --git a/src/headers.test.ts b/src/headers.test.ts index a6d93147..48aa70a8 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -7,6 +7,19 @@ import { } from './headers'; import type { JsonObject } from './types'; +describe('buildRequestHeaders with values the types forbid', () => { + it('treats a falsy endUserId as not given, keeping the caller header', () => { + const headers = buildRequestHeaders({ + apiKey: 'k', + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- what a JavaScript caller can pass + endUserId: false as unknown as string, + extraHeaders: { 'x-end-user-id': 'carol' }, + }); + + expect(headers['x-end-user-id']).toBe('carol'); + }); +}); + describe('normalizeHeaders', () => { it('returns empty object for undefined input', () => { expect(normalizeHeaders(undefined)).toEqual({}); @@ -102,11 +115,13 @@ describe('declaredHeaders', () => { }); }); +const silence = (): void => undefined; + describe('sanitiseHeaders', () => { const allowed = new Set(['x-trace']); beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(silence); }); afterEach(() => { vi.restoreAllMocks(); @@ -129,10 +144,11 @@ describe('sanitiseHeaders', () => { }); }); +/** An object whose first own key is `__proto__`, as only parsed JSON can make one. */ +const withProto = (rest: string): JsonObject => JSON.parse(`{"__proto__":"p",${rest}}`); + // Assigning to `__proto__` sets the prototype, so each of these once dropped the entry. describe('an entry named __proto__', () => { - const withProto = (rest: string) => JSON.parse(`{"__proto__":"p",${rest}}`) as JsonObject; - it('is kept as an own key by sanitiseHeaderArguments', () => { const clean = sanitiseHeaderArguments(withProto('"constructor":"c","q":1'), { nested: new Set(), @@ -161,7 +177,7 @@ describe('an entry named __proto__', () => { it('is kept by buildRequestHeaders', () => { const headers = buildRequestHeaders({ apiKey: 'k', - extraHeaders: JSON.parse('{"__proto__":"p"}') as Record, + extraHeaders: JSON.parse('{"__proto__":"p"}'), }); expect(Object.hasOwn(headers, '__proto__')).toBe(true); expect(Object.getPrototypeOf(headers)).toBe(Object.prototype); diff --git a/src/headers.ts b/src/headers.ts index 981e5f97..e2a6dd05 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -2,6 +2,7 @@ import { USER_AGENT } from './consts'; import type { JsonObject, JsonValue } from './types'; import { warn } from './utils/logger'; import { setEntry } from './utils/set-entry'; +import { isTruthyString } from './utils/type'; /** * Header names the SDK owns. They are applied after every other header is merged, so neither a @@ -30,6 +31,13 @@ export function isSdkOwnedHeader(name: string): boolean { const isEndUserIdHeader = (name: string): boolean => name.trim().toLowerCase() === END_USER_ID_HEADER; +/** + * Whether a caller's extra header is sent: never an SDK-owned one, and not `x-end-user-id` when + * the SDK sets it from `endUserId`. + */ +const keepsCallerHeader = (name: string, endUserId: string | undefined): boolean => + !isSdkOwnedHeader(name) && !(isTruthyString(endUserId) && isEndUserIdHeader(name)); + /** * HTTP Basic credentials for an API key, as every StackOne endpoint expects them. */ @@ -55,16 +63,16 @@ export function buildRequestHeaders(options: { }): Record { const headers: Record = {}; for (const [name, value] of Object.entries(options.extraHeaders ?? {})) { - if (!isSdkOwnedHeader(name) && !(options.endUserId && isEndUserIdHeader(name))) { + if (keepsCallerHeader(name, options.endUserId)) { setEntry(headers, name, value); } } headers['User-Agent'] = USER_AGENT; headers.Authorization = buildAuthHeader(options.apiKey); - if (options.accountId) { + if (isTruthyString(options.accountId)) { headers['x-account-id'] = options.accountId; } - if (options.endUserId) { + if (isTruthyString(options.endUserId)) { headers[END_USER_ID_HEADER] = options.endUserId; } return headers; @@ -142,6 +150,14 @@ export interface DeclaredHeaders { ordinaryHeadersField: boolean; } +/** Whether a schema's `type` is given: a type name or a list of them. */ +const isTyped = (type: JsonValue | undefined): boolean => + typeof type === 'string' || Array.isArray(type); + +/** Whether a schema's `type` is or includes `"object"`. */ +const isObjectTyped = (type: JsonValue | undefined): boolean => + type === 'object' || (Array.isArray(type) && type.includes('object')); + /** The header arguments a served tool schema's `properties` declare. */ export function declaredHeaders(properties: Record): DeclaredHeaders { const flat = new Set( @@ -151,12 +167,9 @@ export function declaredHeaders(properties: Record): DeclaredHe if (!isPlainObject(schema)) { return { nested: new Set(), flat, ordinaryHeadersField: false }; } - const typed = typeof schema.type === 'string' || Array.isArray(schema.type); - const objectTyped = - schema.type === 'object' || (Array.isArray(schema.type) && schema.type.includes('object')); - const ordinaryHeadersField = typed && !objectTyped; + const ordinaryHeadersField = isTyped(schema.type) && !isObjectTyped(schema.type); if (!('properties' in schema)) { - const open = objectTyped && schema.additionalProperties !== false; + const open = isObjectTyped(schema.type) && schema.additionalProperties !== false; return { nested: open ? 'any' : new Set(), flat, ordinaryHeadersField }; } const nestedProperties = isPlainObject(schema.properties) ? schema.properties : {}; @@ -208,7 +221,7 @@ export function sanitiseHeaders( const name = key.trim(); const declared = allowed === 'any' || allowed.has(name.toLowerCase()); const reason = refuseHeader(name, value, declared); - if (reason) { + if (reason !== undefined) { warn(`Dropping header ${JSON.stringify(name)} from a tool call: ${reason}`); continue; } @@ -234,35 +247,52 @@ export function sanitiseHeaderArguments(args: JsonObject, declared: DeclaredHead const clean: JsonObject = {}; for (const [key, value] of Object.entries(args)) { if (key === 'headers') { - if (declared.ordinaryHeadersField) { - setEntry(clean, key, value); - } else if (isPlainObject(value)) { - clean.headers = sanitiseHeaders(value, declared.nested); - } else { - warn(`Dropping header argument ${JSON.stringify(key)} from a tool call: not an object`); - } - continue; - } - if (!key.startsWith(FLAT_HEADER_PREFIX)) { + sanitiseHeadersArgument(clean, value, declared); + } else if (!key.startsWith(FLAT_HEADER_PREFIX) || keepsFlatHeader(key, value, declared.flat)) { setEntry(clean, key, value); - continue; - } - if (isPlainObject(value) || Array.isArray(value)) { - warn( - `Dropping header argument ${JSON.stringify(key)} from a tool call: not a string, number or boolean`, - ); - continue; - } - const text = headerText(value); - if (text === undefined) { - continue; } - const reason = refuseHeader(key.slice(FLAT_HEADER_PREFIX.length), text, declared.flat.has(key)); - if (reason) { - warn(`Dropping header argument ${JSON.stringify(key)} from a tool call: ${reason}`); - continue; - } - setEntry(clean, key, value); } return clean; } + +/** + * Copy a top-level `headers` argument into `clean`: unchanged when the schema declares it as an + * ordinary field, sanitised when it is a plain object, and otherwise dropped. + */ +function sanitiseHeadersArgument( + clean: JsonObject, + value: JsonValue | undefined, + declared: DeclaredHeaders, +): void { + if (declared.ordinaryHeadersField) { + setEntry(clean, 'headers', value); + } else if (isPlainObject(value)) { + clean.headers = sanitiseHeaders(value, declared.nested); + } else { + warn(`Dropping header argument "headers" from a tool call: not an object`); + } +} + +/** Whether a flat `headers_` argument may be forwarded, warning when it is dropped. */ +function keepsFlatHeader( + key: string, + value: JsonValue | undefined, + declaredFlat: ReadonlySet, +): boolean { + if (isPlainObject(value) || Array.isArray(value)) { + warn( + `Dropping header argument ${JSON.stringify(key)} from a tool call: not a string, number or boolean`, + ); + return false; + } + const text = headerText(value); + if (text === undefined) { + return false; + } + const reason = refuseHeader(key.slice(FLAT_HEADER_PREFIX.length), text, declaredFlat.has(key)); + if (reason !== undefined) { + warn(`Dropping header argument ${JSON.stringify(key)} from a tool call: ${reason}`); + return false; + } + return true; +} diff --git a/src/mcp-client.test.ts b/src/mcp-client.test.ts index 50750061..09187559 100644 --- a/src/mcp-client.test.ts +++ b/src/mcp-client.test.ts @@ -1,4 +1,5 @@ -import { createServer, type Server as NetServer, type Socket } from 'node:net'; +import { createServer } from 'node:net'; +import type { Server as NetServer, Socket } from 'node:net'; import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; import { http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; @@ -26,6 +27,7 @@ describe('listMcpTools', () => { const cursors: unknown[] = []; server.use( http.post(`${TEST_BASE_URL}/mcp`, async ({ request }) => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a stand-in server reading the JSON-RPC messages it is sent const message = (await request.json()) as { id?: number; method: string; @@ -78,11 +80,9 @@ describe('listMcpTools', () => { }); it('surfaces an unscoped request as a 400 StackOneAPIError', async () => { - const error = (await listMcpTools(requestFor(undefined)).catch( - (caught: unknown) => caught, - )) as StackOneAPIError; + const error = await listMcpTools(requestFor(undefined)).catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); + assert.instanceOf(error, StackOneAPIError); expect(error.statusCode).toBe(400); expect(error.message).toContain('x-account-id'); }); @@ -96,11 +96,9 @@ describe('listMcpTools', () => { ), ); - const error = (await listMcpTools(requestFor('acc1')).catch( - (caught: unknown) => caught, - )) as StackOneAPIError; + const error = await listMcpTools(requestFor('acc1')).catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); + assert.instanceOf(error, StackOneAPIError); expect(error.statusCode).toBe(412); expect(error.responseBody).toEqual({ message: 're-link the account to resume' }); expect(error.message).toBe( @@ -130,13 +128,19 @@ describe('describeMcpFailure', () => { new StreamableHTTPError(503, 'Error POSTing to endpoint: upstream down'), endpoint, 1, - ) as StackOneAPIError; + ); - expect(error.statusCode).toBe(503); - expect(error.responseBody).toBe('upstream down'); + expect(error).toHaveProperty('statusCode', 503); + expect(error).toHaveProperty('responseBody', 'upstream down'); }); }); +/** A tool result the way the server writes it: structured content, mirrored as text. */ +const served = (structuredContent: Record) => ({ + content: [{ type: 'text', text: JSON.stringify(structuredContent) }], + structuredContent, +}); + describe('parseToolResult', () => { it('parses the text content as JSON', () => { expect( @@ -191,11 +195,6 @@ describe('parseToolResult', () => { }); describe('the server’s success wrapper', () => { - const served = (structuredContent: Record) => ({ - content: [{ type: 'text', text: JSON.stringify(structuredContent) }], - structuredContent, - }); - // The server wraps every action tool, execute and feedback as { isError: false, result }, // with defender and policy metadata beside it. That is returned exactly as written. it('returns { isError: false, result, ...metadata } as the server wrote it', () => { @@ -239,9 +238,9 @@ describe('parseToolResult', () => { caught = error; } - expect(caught).toBeInstanceOf(StackOneAPIError); - expect((caught as StackOneAPIError).message).toContain('Lambda execution failed'); - expect((caught as StackOneAPIError).statusCode).toBe(502); + assert.instanceOf(caught, StackOneAPIError); + expect(caught.message).toContain('Lambda execution failed'); + expect(caught.statusCode).toBe(502); }); it.each([ @@ -257,7 +256,7 @@ describe('parseToolResult', () => { { isError: true, content: [{ type: 'text', text: JSON.stringify(payload) }] }, 't', ), - ).toThrow(expect.objectContaining({ statusCode: status }) as Error); + ).toThrow(expect.objectContaining({ statusCode: status })); }); }); @@ -289,7 +288,9 @@ describe('MCP timeouts', () => { // open for far longer than the toolset's timeout. silent = createServer((socket) => sockets.push(socket)); await new Promise((resolve) => silent.listen(0, '127.0.0.1', resolve)); - port = (silent.address() as { port: number }).port; + const address = silent.address(); + assert(typeof address === 'object' && address !== null, 'the silent server has no port'); + port = address.port; }); afterAll(async () => { for (const socket of sockets) { @@ -308,10 +309,8 @@ describe('MCP timeouts', () => { const started = Date.now(); const error = await listMcpTools(silentRequest()).catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetLoadError); - expect((error as Error).message).toBe( - `MCP request to http://127.0.0.1:${port}/mcp timed out after 0.3s`, - ); + assert.instanceOf(error, ToolSetLoadError); + expect(error.message).toBe(`MCP request to http://127.0.0.1:${port}/mcp timed out after 0.3s`); expect(Date.now() - started).toBeLessThan(5_000); }); diff --git a/src/mcp-client.ts b/src/mcp-client.ts index 18d69170..b9f34aba 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -6,11 +6,12 @@ import { } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; import { version } from '../package.json'; -import type { JsonObject } from './types'; +import type { JsonObject, JsonValue } from './types'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { ToolSetLoadError } from './utils/error-toolset'; import { fetchWithRetry, retryTiming } from './utils/fetch-retry'; +import { isTruthyString } from './utils/type'; /** A tool exactly as the MCP server listed it. */ export interface McpToolDefinition { @@ -39,7 +40,7 @@ class McpDeadlineError extends Error { const TRANSPORT_ERROR_PREFIX = /^Streamable HTTP error: Error POSTing to endpoint:\s*/; const parseBody = (text: string): unknown => { - if (!text) { + if (text === '') { return null; } try { @@ -62,16 +63,7 @@ export function describeMcpFailure(error: unknown, endpoint: string, timeout: nu return error; } if (error instanceof StreamableHTTPError && typeof error.code === 'number' && error.code > 0) { - const text = error.message.replace(TRANSPORT_ERROR_PREFIX, '').trim(); - const detail = text ? `: ${text}` : ''; - const reason = STATUS_CODES[error.code] ?? ''; - return new StackOneAPIError( - `MCP request to ${endpoint} failed with ${error.code} ${reason}`.trimEnd() + detail, - error.code, - parseBody(text), - undefined, - { cause: error }, - ); + return describeHttpFailure(error, error.code, endpoint); } if (isTimeout(error)) { // In seconds, written as a number (0.5s, 60s), as the Python SDK writes it. @@ -79,14 +71,39 @@ export function describeMcpFailure(error: unknown, endpoint: string, timeout: nu cause: error, }); } + return new ToolSetLoadError( + `MCP request to ${endpoint} failed: ${describeInnermostCause(error)}`, + { + cause: error, + }, + ); +} + +/** The transport's HTTP error as a {@link StackOneAPIError} with its status and response body. */ +function describeHttpFailure( + error: StreamableHTTPError, + status: number, + endpoint: string, +): StackOneAPIError { + const text = error.message.replace(TRANSPORT_ERROR_PREFIX, '').trim(); + const detail = text === '' ? '' : `: ${text}`; + const reason = STATUS_CODES[status] ?? ''; + return new StackOneAPIError( + `MCP request to ${endpoint} failed with ${status} ${reason}`.trimEnd() + detail, + status, + parseBody(text), + undefined, + { cause: error }, + ); +} + +/** The innermost cause of an error, as `Name: message`. */ +function describeInnermostCause(error: unknown): string { let leaf: unknown = error; while (leaf instanceof Error && leaf.cause !== undefined) { leaf = leaf.cause; } - const description = leaf instanceof Error ? `${leaf.name}: ${leaf.message}` : String(leaf); - return new ToolSetLoadError(`MCP request to ${endpoint} failed: ${description}`, { - cause: error, - }); + return leaf instanceof Error ? `${leaf.name}: ${leaf.message}` : String(leaf); } /** @@ -121,13 +138,11 @@ export class HttpRateLimitError extends Error { * Whether an MCP request was refused by the API's end-user check on `accountId`: the 400 it * answers a non-shared account's request with when `x-end-user-id` does not name its end user. */ -function isEndUserMismatch(error: unknown, accountId: string): boolean { +function isEndUserMismatch(error: unknown, accountId: string): error is StackOneAPIError { if (!(error instanceof StackOneAPIError) || error.statusCode !== 400) { return false; } - const body = error.responseBody; - const message = - typeof body === 'object' && body !== null && 'message' in body ? body.message : body; + const message = bodyMessage(error.responseBody); // The guard's fixed wording, ending with this account's id, quoted or not: not an exact string, // so a change to how the id is written does not silently turn the lookup off. if ( @@ -145,6 +160,10 @@ function isEndUserMismatch(error: unknown, accountId: string): boolean { ); } +/** The `message` of an error body, or the body itself when it has none. */ +const bodyMessage = (body: unknown): unknown => + typeof body === 'object' && body !== null && 'message' in body ? body.message : body; + /** How a request finds the end user to send as `x-end-user-id` for an account. */ export interface EndUserSource { /** The end user recorded for the account, if any. */ @@ -167,33 +186,20 @@ export async function withEndUser( source: EndUserSource | undefined, request: (endUserId: string | undefined) => Promise, ): Promise { - const recorded = accountId && source ? source.recorded(accountId) : undefined; + if (!isTruthyString(accountId) || source === undefined) { + return request(undefined); + } + const recorded = source.recorded(accountId); + if (recorded !== undefined) { + return request(recorded); + } try { - return await request(recorded); + return await request(undefined); } catch (error) { - if (!accountId || !source || recorded !== undefined || !isEndUserMismatch(error, accountId)) { + if (!isEndUserMismatch(error, accountId)) { throw error; } - // A failed lookup leaves the refusal to be thrown, with the lookup's error as its cause — - // a key without platform.read would otherwise be told only that the header is wrong. A rate - // limit is thrown instead: that is the key's, not the account's, and must stay fatal to a - // fan-out. - let endUserId: string | undefined; - try { - endUserId = await source.lookUp(accountId); - } catch (lookupError) { - if (isRateLimitFailure(lookupError)) { - throw lookupError; - } - const refusal = error as StackOneAPIError; - throw new StackOneAPIError( - refusal.message, - refusal.statusCode, - refusal.responseBody, - refusal.requestBody, - { cause: lookupError }, - ); - } + const endUserId = await lookUpAfterRefusal(error, accountId, source); if (endUserId === undefined) { throw error; } @@ -201,6 +207,34 @@ export async function withEndUser( } } +/** + * Look up an account's end user after the API refused a request without one. + * + * A failed lookup leaves the refusal to be thrown, with the lookup's error as its cause — a key + * without platform.read would otherwise be told only that the header is wrong. A rate limit is + * thrown instead: that is the key's, not the account's, and must stay fatal to a fan-out. + */ +async function lookUpAfterRefusal( + refusal: StackOneAPIError, + accountId: string, + source: EndUserSource, +): Promise { + try { + return await source.lookUp(accountId); + } catch (lookupError) { + if (isRateLimitFailure(lookupError)) { + throw lookupError; + } + throw new StackOneAPIError( + refusal.message, + refusal.statusCode, + refusal.responseBody, + refusal.requestBody, + { cause: lookupError }, + ); + } +} + /** A session that timed out while a 429 was being retried. */ class RateLimitTimeoutError extends Error { constructor(options: ErrorOptions) { @@ -209,9 +243,12 @@ class RateLimitTimeoutError extends Error { } } +/** The MCP request-timeout error code, as the number an {@link McpError} carries. */ +const REQUEST_TIMEOUT_CODE: number = ErrorCode.RequestTimeout; + const isTimeout = (error: unknown): boolean => error instanceof McpDeadlineError || - (error instanceof McpError && error.code === ErrorCode.RequestTimeout); + (error instanceof McpError && error.code === REQUEST_TIMEOUT_CODE); /** * Open an MCP session, run `work` in it and close it, all within one deadline. @@ -292,18 +329,19 @@ export async function listMcpTools(request: McpRequest): Promise, + inputSchema: tool.inputSchema ?? {}, }); } cursor = page.nextCursor; - } while (cursor); + } while (isTruthyString(cursor)); return collected; }); } @@ -313,6 +351,12 @@ interface ContentPart { text?: unknown; } +const isTextPart = (part: ContentPart): part is ContentPart & { text: string } => + part.type === 'text' && typeof part.text === 'string' && part.text !== ''; + +const isJsonObject = (value: JsonValue | undefined): value is JsonObject => + typeof value === 'object' && value !== null && !Array.isArray(value); + /** * Dig the HTTP status out of an MCP error payload. * @@ -322,11 +366,11 @@ interface ContentPart { */ function statusOf(parsed: JsonObject): number { for (const candidate of [parsed, parsed.result, parsed.error, parsed.data]) { - if (typeof candidate !== 'object' || candidate === null || Array.isArray(candidate)) { + if (!isJsonObject(candidate)) { continue; } for (const key of ['status_code', 'statusCode']) { - const status = (candidate as JsonObject)[key]; + const status = candidate[key]; if (typeof status === 'number' && Number.isInteger(status)) { return status; } @@ -349,33 +393,19 @@ function statusOf(parsed: JsonObject): number { * to the caller as though it were a success. */ export function parseToolResult(result: Record, name: string): JsonObject { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- served MCP content, read as the protocol defines it const content = (Array.isArray(result.content) ? result.content : []) as ContentPart[]; - const texts = content.filter( - (part): part is ContentPart & { text: string } => - part.type === 'text' && typeof part.text === 'string' && part.text !== '', - ); - const nonText = content.filter((part) => !texts.includes(part as ContentPart & { text: string })); - const payload = texts.map((part) => part.text).join(''); - - let parsed: JsonObject = {}; - if (payload) { - let loaded: unknown; - try { - loaded = JSON.parse(payload); - } catch { - loaded = payload; - } - parsed = - typeof loaded === 'object' && loaded !== null && !Array.isArray(loaded) - ? (loaded as JsonObject) - : { result: loaded as JsonObject[string] }; - } else if (typeof result.structuredContent === 'object' && result.structuredContent !== null) { - parsed = result.structuredContent as JsonObject; - } + const payload = content + .filter(isTextPart) + .map((part) => part.text) + .join(''); + const nonText = content.filter((part) => !isTextPart(part)); + const parsed = + payload === '' ? structuredObject(result.structuredContent) : parsePayload(payload); if (result.isError === true) { throw new StackOneAPIError( - `Tool ${JSON.stringify(name)} failed: ${payload || JSON.stringify(parsed)}`, + `Tool ${JSON.stringify(name)} failed: ${payload === '' ? JSON.stringify(parsed) : payload}`, statusOf(parsed), parsed, ); @@ -384,11 +414,31 @@ export function parseToolResult(result: Record, name: string): // A copy, so content_parts below never writes into the caller's structuredContent. const returned = { ...parsed }; if (nonText.length > 0) { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- served MCP content parts are JSON objects returned.content_parts = nonText as unknown as JsonObject[]; } return returned; } +/** Joined text parts parsed as JSON; a non-object, or text that is not JSON, is wrapped as `{ result }`. */ +function parsePayload(payload: string): JsonObject { + let loaded: JsonValue; + try { + loaded = JSON.parse(payload); + } catch { + loaded = payload; + } + return isJsonObject(loaded) ? loaded : { result: loaded }; +} + +/** A result's `structuredContent`, if it is an object. */ +function structuredObject(structuredContent: unknown): JsonObject { + return typeof structuredContent === 'object' && structuredContent !== null + ? // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- served MCP structured content is JSON + (structuredContent as JsonObject) + : {}; +} + /** * Invoke a tool over MCP `tools/call`. */ @@ -401,6 +451,6 @@ export async function callMcpTool( const result = await client.callTool({ name, arguments: args }, undefined, { timeout: request.timeout, }); - return parseToolResult(result as Record, name); + return parseToolResult(result, name); }); } diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts index 1bbbfd5c..1535c081 100644 --- a/src/rate-limit.test.ts +++ b/src/rate-limit.test.ts @@ -6,7 +6,8 @@ import { delay, http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; import { mockAccounts } from '../mocks/handlers.stackone-accounts'; -import { type RecordedToolCall, accountMcpTools, createMcpApp } from '../mocks/mcp-server'; +import { accountMcpTools, createMcpApp, jsonRpcMethod } from '../mocks/mcp-server'; +import type { RecordedToolCall } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { StackOneToolSet } from './toolsets'; import { StackOneAPIError } from './utils/error-stackone-api'; @@ -18,9 +19,11 @@ const newToolSet = (config: ConstructorParameters[0] = { const RATE_LIMITED = { message: 'Too many requests' }; +const silence = (): void => undefined; + let warnSpy: ReturnType; beforeEach(() => { - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(silence); }); afterEach(() => { vi.restoreAllMocks(); @@ -38,6 +41,14 @@ interface Throttle { retryAfter?: string; } +/** The JSON-RPC method a request to the MCP endpoint calls: only a POST carries one. */ +const methodOf = async (request: Request): Promise => + request.method === 'POST' ? jsonRpcMethod(await request.clone().json()) : undefined; + +const throttles = (throttle: Throttle, method: string | undefined, accountId: string | undefined) => + (throttle.method === undefined || method === throttle.method) && + (throttle.accountId === undefined || accountId === throttle.accountId); + /** * Serve the mock MCP app, answering 429 (with `Retry-After: 0`) to the requests the throttle * matches, and 412 to account `dead`. Returns the attempts the throttle saw and the tools/calls @@ -56,13 +67,7 @@ const serveThrottled = (throttle: Throttle) => { if (accountId === 'dead') { return HttpResponse.json({ message: 're-link the account to resume' }, { status: 412 }); } - const message = - request.method === 'POST' - ? ((await request.clone().json()) as { method?: string }) - : undefined; - const matches = - (throttle.method === undefined || message?.method === throttle.method) && - (throttle.accountId === undefined || accountId === throttle.accountId); + const matches = throttles(throttle, await methodOf(request), accountId); if (matches && attempts.matched++ < (throttle.times ?? Number.POSITIVE_INFINITY)) { return HttpResponse.json(RATE_LIMITED, { status: 429, @@ -76,9 +81,9 @@ const serveThrottled = (throttle: Throttle) => { }; const expectRateLimited = (error: unknown) => { - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); - expect((error as StackOneAPIError).responseBody).toEqual(RATE_LIMITED); + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); + expect(error.responseBody).toEqual(RATE_LIMITED); }; describe('a 429 that clears on retry', () => { @@ -150,9 +155,9 @@ describe('a 429 that outlasts its retries', () => { .fetchAccounts() .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); - expect((error as StackOneAPIError).responseBody).toBe('slow down'); + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); + expect(error.responseBody).toBe('slow down'); expect(requests).toBe(4); expect(retryWarnings()).toHaveLength(3); }); @@ -217,10 +222,10 @@ describe('a 429 that outlasts its retries', () => { .fetchTools() .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); // GET /accounts keeps its error body as text. - expect((error as StackOneAPIError).responseBody).toBe(JSON.stringify(RATE_LIMITED)); + expect(error.responseBody).toBe(JSON.stringify(RATE_LIMITED)); }); it('fails a search instead of skipping the throttled connector', async () => { @@ -235,22 +240,22 @@ describe('a 429 that outlasts its retries', () => { }); }); -describe('a 429 whose wait would outlast the timeout', () => { - /** - * Replace the retry clock with a fake one that each wait advances, so nothing really waits. - * Returns the waits requested. - */ - const fakeClock = () => { - const clock = { now: 0 }; - const waits: number[] = []; - vi.spyOn(retryTiming, 'now').mockImplementation(() => clock.now); - vi.spyOn(retryTiming, 'sleep').mockImplementation(async (ms) => { - waits.push(ms); - clock.now += ms; - }); - return waits; - }; +/** + * Replace the retry clock with a fake one that each wait advances, so nothing really waits. + * Returns the waits requested. + */ +const fakeClock = () => { + const clock = { now: 0 }; + const waits: number[] = []; + vi.spyOn(retryTiming, 'now').mockImplementation(() => clock.now); + vi.spyOn(retryTiming, 'sleep').mockImplementation(async (ms) => { + waits.push(ms); + clock.now += ms; + }); + return waits; +}; +describe('a 429 whose wait would outlast the timeout', () => { it('fails a multi-account listing with the 429 instead of timing the account out', async () => { const waits = fakeClock(); const { attempts } = serveThrottled({ accountId: 'acc2', retryAfter: '2' }); @@ -280,8 +285,8 @@ describe('a 429 whose wait would outlast the timeout', () => { .fetchAccounts() .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); expect(requests).toBe(1); expect(waits).toEqual([]); expect(retryWarnings()).toEqual([ @@ -303,7 +308,7 @@ describe('a 429 whose wait would outlast the timeout', () => { .fetchAccounts() .catch((caught: unknown) => caught); - expect((error as StackOneAPIError).statusCode).toBe(429); + expect(error).toHaveProperty('statusCode', 429); expect(waits).toEqual([1_000, 1_000]); expect(requests).toBe(3); }); @@ -334,9 +339,9 @@ describe('a timeout while a 429 is retried', () => { .fetchTools({ accountIds: ['acc1', 'acc2'] }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); - expect((error as Error).message).toBe( + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); + expect(error.message).toBe( `MCP request to ${TEST_BASE_URL}/mcp was rate limited (429) and timed out after 0.3s while retrying`, ); expect(warnings().filter((message) => message.includes('Skipping'))).toEqual([]); @@ -355,8 +360,7 @@ describe('a timeout while a 429 is retried', () => { answeredMeanwhile = listAttempts === 2; return new HttpResponse(null, { status: 405 }); } - const message = (await request.clone().json()) as { method?: string }; - if (message.method === 'tools/list') { + if (jsonRpcMethod(await request.clone().json()) === 'tools/list') { if (listAttempts++ === 0) { return HttpResponse.json(RATE_LIMITED, { status: 429, @@ -374,8 +378,8 @@ describe('a timeout while a 429 is retried', () => { .catch((caught: unknown) => caught); expect(answeredMeanwhile).toBe(true); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); }); it('fails GET /accounts with a 429', async () => { @@ -394,8 +398,8 @@ describe('a timeout while a 429 is retried', () => { .fetchAccounts() .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); expect(requests).toBe(2); }); }); @@ -409,17 +413,14 @@ describe('a 429 that clears on retry, followed by an unrelated timeout', () => { let initializeAttempts = 0; server.use( http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { - const message = - request.method === 'POST' - ? ((await request.clone().json()) as { method?: string }) - : undefined; - if (message?.method === 'initialize' && initializeAttempts++ === 0) { + const method = await methodOf(request); + if (method === 'initialize' && initializeAttempts++ === 0) { return HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '0' }, }); } - if (message?.method === 'tools/list') { + if (method === 'tools/list') { await delay('infinite'); } return app.fetch(request); @@ -430,11 +431,9 @@ describe('a 429 that clears on retry, followed by an unrelated timeout', () => { .fetchTools({ accountIds: ['acc1'] }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetLoadError); + assert.instanceOf(error, ToolSetLoadError); expect(error).not.toBeInstanceOf(StackOneAPIError); - expect((error as Error).message).toBe( - `MCP request to ${TEST_BASE_URL}/mcp timed out after 0.3s`, - ); + expect(error.message).toBe(`MCP request to ${TEST_BASE_URL}/mcp timed out after 0.3s`); }); // The same request this time: its retry is answered 200, and then the stream stalls. That is @@ -444,18 +443,15 @@ describe('a 429 that clears on retry, followed by an unrelated timeout', () => { let listAttempts = 0; server.use( http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { - const message = - request.method === 'POST' - ? ((await request.clone().json()) as { method?: string }) - : undefined; - if (request.headers.get('x-account-id') === 'acc2' && message?.method === 'tools/list') { + const method = await methodOf(request); + if (request.headers.get('x-account-id') === 'acc2' && method === 'tools/list') { if (listAttempts++ === 0) { return HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '0' }, }); } - return new HttpResponse(new ReadableStream({ start() {} }), { + return new HttpResponse(new ReadableStream({ start: silence }), { headers: { 'Content-Type': 'text/event-stream' }, }); } @@ -487,7 +483,7 @@ describe('other statuses', () => { .fetchAccounts() .catch((caught: unknown) => caught); - expect((error as StackOneAPIError).statusCode).toBe(status); + expect(error).toHaveProperty('statusCode', status); expect(requests).toBe(1); expect(retryWarnings()).toEqual([]); }); @@ -505,7 +501,7 @@ describe('other statuses', () => { .fetchTools({ accountIds: ['acc1'] }) .catch((caught: unknown) => caught); - expect((error as StackOneAPIError).statusCode).toBe(500); + expect(error).toHaveProperty('statusCode', 500); expect(requests).toBe(1); }); }); diff --git a/src/schema.test.ts b/src/schema.test.ts index 9ba138b1..f49d503c 100644 --- a/src/schema.test.ts +++ b/src/schema.test.ts @@ -23,7 +23,7 @@ describe('toolParametersFromInputSchema', () => { const parameters = toolParametersFromInputSchema(served); const nested = parameters.properties.a?.properties; - assert(nested); + assert(nested !== undefined); (nested as Record).injected = { type: 'string' }; expect(served.properties.a.properties).toEqual({}); @@ -61,9 +61,9 @@ describe('toolParametersFromInputSchema', () => { describe('foldRootComposition', () => { it('keeps a branch property named __proto__', () => { - const schema = JSON.parse( + const schema: JSONSchema = JSON.parse( '{"type":"object","anyOf":[{"properties":{"__proto__":{"type":"string"},"q":{"type":"string"}}}]}', - ) as JSONSchema; + ); const folded = foldRootComposition(schema); expect(Object.keys(folded.properties ?? {})).toEqual(['__proto__', 'q']); expect(Object.getPrototypeOf(folded.properties)).toBe(Object.prototype); diff --git a/src/schema.ts b/src/schema.ts index d0b61f60..48af84a8 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -47,10 +47,11 @@ export function toolParametersFromInputSchema(inputSchema: unknown): ToolParamet const parameters: ToolParameters = { ...rest, type: typeof type === 'string' ? type : 'object', + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- served JSON: the property schemas are passed through, not validated properties: (isPlainObject(properties) ? properties : {}) as JsonSchemaProperties, }; const required = servedRequired(served); - if (required) { + if (required !== undefined) { parameters.required = required; } return parameters; @@ -63,6 +64,43 @@ export function toolParametersFromInputSchema(inputSchema: unknown): ToolParamet */ const ROOT_KEYWORDS_PROVIDERS_REJECT = ['oneOf', 'anyOf', 'allOf', 'enum', 'not'] as const; +/** Fold every `allOf`, `oneOf` and `anyOf` branch of `schema` into `properties` and `required`. */ +function foldCombinators( + schema: JSONSchema, + properties: JsonSchemaProperties, + required: Set, +): void { + for (const keyword of ['allOf', 'oneOf', 'anyOf'] as const) { + for (const branch of schema[keyword] ?? []) { + if (isPlainObject(branch)) { + foldBranch(branch, keyword === 'allOf', properties, required); + } + } + } +} + +/** + * Fold one combinator branch into the root's `properties` (the root's own definition wins) and, + * when every branch must hold, into its `required` names. + */ +function foldBranch( + branch: JSONSchema, + mustHold: boolean, + properties: JsonSchemaProperties, + required: Set, +): void { + for (const [name, definition] of Object.entries(branch.properties ?? {})) { + if (!Object.hasOwn(properties, name)) { + setEntry(properties, name, definition); + } + } + if (mustHold) { + for (const name of branch.required ?? []) { + required.add(name); + } + } +} + /** * Make a lossless schema acceptable to a provider that requires a plain object at the root. * @@ -81,23 +119,7 @@ export function foldRootComposition(schema: JSONSchema): JSONSchema { const properties: JsonSchemaProperties = { ...folded.properties }; const required = new Set(folded.required ?? []); - for (const keyword of ['allOf', 'oneOf', 'anyOf'] as const) { - for (const branch of folded[keyword] ?? []) { - if (!isPlainObject(branch)) { - continue; - } - for (const [name, definition] of Object.entries(branch.properties ?? {})) { - if (!Object.hasOwn(properties, name)) { - setEntry(properties, name, definition); - } - } - if (keyword === 'allOf') { - for (const name of branch.required ?? []) { - required.add(name); - } - } - } - } + foldCombinators(folded, properties, required); for (const keyword of ROOT_KEYWORDS_PROVIDERS_REJECT) { delete folded[keyword]; } diff --git a/src/tool.test-d.ts b/src/tool.test-d.ts index ad58b8c6..ef1db48b 100644 --- a/src/tool.test-d.ts +++ b/src/tool.test-d.ts @@ -32,10 +32,10 @@ test('BaseTool.toAISDK result has typed properties', async () => { const toolDef = result.test_tool; // TODO: Remove ts-ignore once AISDKToolDefinition properly types description as required - // @ts-ignore - description is optional in Tool but we always set it + // @ts-expect-error - description is optional in Tool but we always set it assertType(toolDef.description); // TODO: Remove ts-ignore once AISDKToolDefinition properly types inputSchema.jsonSchema - // @ts-ignore - inputSchema is FlexibleSchema which may not have jsonSchema + // @ts-expect-error - inputSchema is FlexibleSchema which may not have jsonSchema assertType<{ jsonSchema: unknown }>(toolDef.inputSchema); }); diff --git a/src/tool.test.ts b/src/tool.test.ts index 4346beca..083252c3 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -2,7 +2,8 @@ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { jsonSchema } from 'ai'; import { http } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; -import { type RecordedToolCall, createMcpApp } from '../mocks/mcp-server'; +import { createMcpApp } from '../mocks/mcp-server'; +import type { RecordedToolCall } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { toolParametersFromInputSchema } from './schema'; import { BaseTool, StackOneMcpTool, StackOneTool, Tools } from './tool'; @@ -20,6 +21,7 @@ const executeAISDKTool = ( name: string, args: Record, ): Promise => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the plain signature above, across ai majors const execute = tools[name]?.execute as unknown as ( args: Record, options?: unknown, @@ -65,6 +67,21 @@ const richSchema = { required: ['start_date'], } as const; +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null; + +/** The JSON Schema inside an AI SDK `inputSchema`, whose type differs across ai majors. */ +const aiSdkJsonSchema = (inputSchema: unknown): Record => { + assert(isRecord(inputSchema) && isRecord(inputSchema.jsonSchema)); + return inputSchema.jsonSchema; +}; + +/** A value an adapter's types leave optional, though it always sets it. */ +const present = (value: Value | null | undefined): Value => { + assert.exists(value); + return value; +}; + const localTool = (name: string, schema: unknown, description = 'Test tool') => new BaseTool(name, description, toolParametersFromInputSchema(schema), { kind: 'local' }); @@ -92,9 +109,10 @@ describe('BaseTool', () => { const tool = localTool('rich', richSchema); const schema = tool.toJsonSchema(); const address = schema.properties?.address?.properties; - assert(address); - (address as Record).injected = {}; - (schema.$defs as Record).Evil = {}; + assert.isDefined(address); + address.injected = {}; + assert.isDefined(schema.$defs); + schema.$defs.Evil = {}; expect(tool.toJsonSchema()).toEqual(richSchema); }); @@ -119,33 +137,25 @@ describe('BaseTool', () => { const { oneOf: _rejected, ...providerRoot } = richSchema; const adapters: Array<[string, () => Promise>]> = [ - ['toOpenAI', async () => tool.toOpenAI().function.parameters as Record], - ['toAnthropic', async () => tool.toAnthropic().input_schema as Record], - [ - 'toOpenAIResponses (strict)', - async () => tool.toOpenAIResponses().parameters as Record, - ], + ['toOpenAI', async () => present(tool.toOpenAI().function.parameters)], + ['toAnthropic', async () => tool.toAnthropic().input_schema], + ['toOpenAIResponses (strict)', async () => present(tool.toOpenAIResponses().parameters)], [ 'toOpenAIResponses (non-strict)', - async () => tool.toOpenAIResponses({ strict: false }).parameters as Record, + async () => present(tool.toOpenAIResponses({ strict: false }).parameters), ], [ 'toAISDK', async () => { const aiTools = await tool.toAISDK({ executable: false }); const aiTool = aiTools.hris_rich_probe; - assert(aiTool); - return (aiTool.inputSchema as { jsonSchema: Record }).jsonSchema; + assert.isDefined(aiTool); + return aiSdkJsonSchema(aiTool.inputSchema); }, ], [ 'toClaudeAgentSdkTool', - async () => - ( - (await tool.toClaudeAgentSdkTool()).inputSchema as { - jsonSchema: Record; - } - ).jsonSchema, + async () => aiSdkJsonSchema((await tool.toClaudeAgentSdkTool()).inputSchema), ], ]; @@ -170,10 +180,10 @@ describe('BaseTool', () => { expect(schema).not.toHaveProperty(keyword); } // The nested union is untouched: only the root is a problem for the provider. - expect((schema.properties as Record).identifier?.oneOf).toEqual([ - { type: 'string' }, - { type: 'integer' }, - ]); + expect(schema).toHaveProperty( + ['properties', 'identifier', 'oneOf'], + [{ type: 'string' }, { type: 'integer' }], + ); }); it.each(adapters)('%s is otherwise exactly the served root', async (_name, adapt) => { @@ -191,16 +201,14 @@ describe('BaseTool', () => { expect(open.toOpenAIResponses().parameters?.additionalProperties).toBe(false); const aiTools = await open.toAISDK({ executable: false }); const aiTool = aiTools.open; - assert(aiTool); - expect( - (aiTool.inputSchema as { jsonSchema: JSONSchema }).jsonSchema.additionalProperties, - ).toBe(false); + assert.isDefined(aiTool); + expect(aiSdkJsonSchema(aiTool.inputSchema).additionalProperties).toBe(false); }); it('closes the root in strict mode without rewriting anything nested', () => { - const parameters = tool.toOpenAIResponses().parameters as JSONSchema; + const parameters = present(tool.toOpenAIResponses().parameters); expect(parameters.additionalProperties).toBe(false); - expect(parameters.properties?.address).toEqual(richSchema.properties.address); + expect(parameters).toHaveProperty(['properties', 'address'], richSchema.properties.address); }); }); @@ -235,7 +243,7 @@ describe('BaseTool', () => { it('builds an AI SDK tool whose schema the ai package accepts', async () => { const aiTools = await simpleTool().toAISDK(); expect(typeof aiTools.test_tool?.execute).toBe('function'); - expect(jsonSchema(simpleTool().toOpenAI().function.parameters as JSONSchema)).toBeDefined(); + expect(jsonSchema(present(simpleTool().toOpenAI().function.parameters))).toBeDefined(); }); it('returns an AI SDK execution error as a string rather than throwing', async () => { @@ -256,6 +264,7 @@ describe('BaseTool', () => { it('serialises a Claude Agent SDK result for the model, bytes as base64', async () => { const tool = simpleTool(); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately bytes, not JSON tool.execute = async () => ({ content: Buffer.from('%PDF') as never, ok: true }); const definition = await tool.toClaudeAgentSdkTool(); @@ -284,7 +293,7 @@ describe('StackOneMcpTool as an action tool', () => { const serve = (toolResults: Record = {}) => { const app = createMcpApp({ accountTools: { acc1: [listed], acc2: [listed] }, - onToolCall: (call) => calls.push(call), + onToolCall: (recorded) => calls.push(recorded), toolResults, }); server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); @@ -360,7 +369,7 @@ describe('StackOneMcpTool as an action tool', () => { ['x-stackone-account-id', 'victim'], ['Cookie', 'session=x'], ])('drops a model-supplied %j header', async (name, value) => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); await actionTool().execute({ headers: { [name]: value } }); @@ -370,7 +379,7 @@ describe('StackOneMcpTool as an action tool', () => { }); it('keeps a header a nested schema declares, and drops one carrying CR/LF', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); await actionTool().execute({ headers: { 'X-Trace': 'abc', 'X-Other': 'no' } }); await actionTool().execute({ headers: { 'x-trace': 'a\r\nInjected: 1' } }); expect(calls[0]?.arguments.headers).toEqual({ 'X-Trace': 'abc' }); @@ -403,8 +412,8 @@ describe('StackOneMcpTool as an action tool', () => { .execute(value) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolArgumentsError); - expect((error as Error).message).toMatch(/must be a JSON object/); + assert.instanceOf(error, ToolArgumentsError); + expect(error.message).toMatch(/must be a JSON object/); expect(calls).toEqual([]); }); @@ -415,7 +424,7 @@ describe('StackOneMcpTool as an action tool', () => { ['a Map', { body: { cache: new Map() } }, 'a Map'], ['a Set', { query: { ids: new Set([1, 2]) } }, 'a Set'], ['a RegExp', { pattern: /x/ }, 'a RegExp'], - ['a function', { cb: () => {} }, 'a function'], + ['a function', { cb: () => undefined }, 'a function'], ['a symbol', { tag: Symbol('x') }, 'a symbol'], ['a bigint', { amount: 10n }, 'a bigint'], ['a Uint8Array', { bytes: new Uint8Array([1]) }, 'binary data'], @@ -424,11 +433,12 @@ describe('StackOneMcpTool as an action tool', () => { 'rejects %s nested in the arguments, without calling the server', async (_name, args, hint) => { const error = await actionTool() + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately not JSON .execute(args as unknown as JsonObject) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolArgumentsError); - expect((error as Error).message).toContain( + assert.instanceOf(error, ToolArgumentsError); + expect(error.message).toContain( `Arguments for "crm_update_contact" could not be encoded as JSON: ${hint}`, ); expect(calls).toEqual([]); @@ -442,11 +452,11 @@ describe('StackOneMcpTool as an action tool', () => { ['a lone surrogate in a top-level key', { '\uDFFF': 'x' }], ])('rejects %s without calling the server', async (_name, args) => { const error = await actionTool() - .execute(args as JsonObject) + .execute(args) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolArgumentsError); - expect((error as Error).message).toMatch( + assert.instanceOf(error, ToolArgumentsError); + expect(error.message).toMatch( /^Arguments for "crm_update_contact" could not be encoded as JSON: a (string|key) holding a lone surrogate is not Unicode text/, ); expect(calls).toEqual([]); @@ -465,21 +475,20 @@ describe('StackOneMcpTool as an action tool', () => { .execute(text) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolArgumentsError); - expect((error as Error).message).toMatch( - /^Invalid JSON in arguments for "crm_update_contact": /, - ); + assert.instanceOf(error, ToolArgumentsError); + expect(error.message).toMatch(/^Invalid JSON in arguments for "crm_update_contact": /); expect(calls).toEqual([]); }, ); it('rejects undefined inside an array', async () => { const error = await actionTool() + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately not JSON .execute({ query: { ids: [1, undefined, 3] } } as unknown as JsonObject) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolArgumentsError); - expect((error as Error).message).toMatch(/undefined is not a JSON value/); + assert.instanceOf(error, ToolArgumentsError); + expect(error.message).toMatch(/undefined is not a JSON value/); expect(calls).toEqual([]); }); @@ -488,11 +497,11 @@ describe('StackOneMcpTool as an action tool', () => { // eslint-disable-next-line @typescript-eslint/no-array-delete -- deliberately punching a hole delete ids[1]; const error = await actionTool() - .execute({ query: { ids } } as unknown as JsonObject) + .execute({ query: { ids } }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolArgumentsError); - expect((error as Error).message).toMatch(/undefined is not a JSON value/); + assert.instanceOf(error, ToolArgumentsError); + expect(error.message).toMatch(/undefined is not a JSON value/); expect(calls).toEqual([]); }); @@ -504,23 +513,24 @@ describe('StackOneMcpTool as an action tool', () => { .execute({ body }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolArgumentsError); - expect((error as Error).message).toMatch(/circular reference/); + assert.instanceOf(error, ToolArgumentsError); + expect(error.message).toMatch(/circular reference/); expect(calls).toEqual([]); }); it('drops an object property set to undefined, rather than rejecting it', async () => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately not JSON await actionTool().execute({ path: { id: '1' }, extra: undefined } as unknown as JsonObject); expect(calls[0]?.arguments).toEqual({ path: { id: '1' } }); }); it('is refused by the server when it has no account', async () => { - const error = (await actionTool() + const error = await actionTool() .setAccountId(undefined) .execute({}) - .catch((caught: unknown) => caught)) as StackOneAPIError; + .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); + assert.instanceOf(error, StackOneAPIError); expect(error.statusCode).toBe(400); }); @@ -557,11 +567,11 @@ describe('StackOneMcpTool as an action tool', () => { }, }); - const error = (await actionTool() + const error = await actionTool() .execute({}) - .catch((caught: unknown) => caught)) as StackOneAPIError; + .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); + assert.instanceOf(error, StackOneAPIError); expect(error.statusCode).toBe(501); }); @@ -576,28 +586,28 @@ describe('StackOneMcpTool as an action tool', () => { }); }); +const mcpTool = (properties: Record = {}) => + new StackOneMcpTool({ + name: 'mock_acc1_execute_action', + description: 'Execute', + parameters: toolParametersFromInputSchema({ type: 'object', properties }), + endpoint: `${TEST_BASE_URL}/mcp?tool-mode=search_execute`, + apiKey: 'test-key', + accountId: 'acc1', + timeout: 5_000, + }); + describe('StackOneMcpTool', () => { const calls: RecordedToolCall[] = []; beforeEach(() => { calls.length = 0; const app = createMcpApp({ accountTools: { acc1: [] }, - onToolCall: (call) => calls.push(call), + onToolCall: (recorded) => calls.push(recorded), }); server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); }); - const mcpTool = (properties: Record = {}) => - new StackOneMcpTool({ - name: 'mock_acc1_execute_action', - description: 'Execute', - parameters: toolParametersFromInputSchema({ type: 'object', properties }), - endpoint: `${TEST_BASE_URL}/mcp?tool-mode=search_execute`, - apiKey: 'test-key', - accountId: 'acc1', - timeout: 5_000, - }); - it('calls the tool over tools/call and returns the parsed result', async () => { const result = await mcpTool().execute({ action_id: 'mock_list_items', @@ -621,7 +631,7 @@ describe('StackOneMcpTool', () => { // The meta tools take a `headers` object the server unpacks, and these arguments are // model-controlled. This schema declares no headers at all, so nothing survives. it('drops every model-supplied header', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); await mcpTool().execute({ action_id: 'mock_list_items', @@ -640,7 +650,7 @@ describe('StackOneMcpTool', () => { }); it('keeps a header its own schema declares', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); await mcpTool({ headers: { type: 'object', properties: { 'x-trace': { type: 'string' } } }, }).execute({ @@ -652,11 +662,11 @@ describe('StackOneMcpTool', () => { }); it('raises when the result carries isError', async () => { - const error = (await mcpTool() + const error = await mcpTool() .execute({ action_id: 'mock_not_a_real_action' }) - .catch((caught: unknown) => caught)) as StackOneAPIError; + .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); + assert.instanceOf(error, StackOneAPIError); expect(error.message).toContain('Unknown action mock_not_a_real_action'); expect(error.statusCode).toBe(404); }); @@ -668,9 +678,9 @@ describe('StackOneMcpTool', () => { }); }); -describe('Tools', () => { - const named = (name: string) => localTool(name, { type: 'object', properties: {} }); +const named = (name: string) => localTool(name, { type: 'object', properties: {} }); +describe('Tools', () => { it('looks tools up by name, first match wins', () => { const first = named('dup'); const tools = new Tools([first, named('dup'), named('other')]); @@ -751,25 +761,30 @@ describe('ToolParameters typing', () => { }); }); -describe('Tools.executeOpenAIToolCalls', () => { - const toolsWith = (behaviour: (args: unknown) => Promise) => { - const tool = localTool('linear_list_issues', { - type: 'object', - properties: { body_variables: { type: 'object' } }, - }); - const seen: unknown[] = []; - tool.execute = async (args) => { - seen.push(args); - return behaviour(args); - }; - return { tools: new Tools([tool]), seen }; - }; - const call = (name: string, args = '{}', id = 'call_1') => ({ - id, - type: 'function' as const, - function: { name, arguments: args }, +const toolsWith = (behaviour: (args: unknown) => Promise) => { + const tool = localTool('linear_list_issues', { + type: 'object', + properties: { body_variables: { type: 'object' } }, }); + const seen: unknown[] = []; + tool.execute = async (args) => { + seen.push(args); + return behaviour(args); + }; + return { tools: new Tools([tool]), seen }; +}; +/** A tool message's content, which executeOpenAIToolCalls always writes as a string. */ +const contentOf = (message: { content?: unknown } | undefined): string => { + assert(typeof message?.content === 'string'); + return message.content; +}; +const call = (name: string, args = '{}', id = 'call_1') => ({ + id, + type: 'function' as const, + function: { name, arguments: args }, +}); +describe('Tools.executeOpenAIToolCalls', () => { it('runs each call and pairs its result with the call id', async () => { const { tools, seen } = toolsWith(async () => ({ data: { n: 1 } })); @@ -784,7 +799,7 @@ describe('Tools.executeOpenAIToolCalls', () => { }); it('keeps the order of several calls', async () => { - const { tools } = toolsWith(async (args) => ({ echoed: args as string })); + const { tools } = toolsWith(async (args) => ({ echoed: String(args) })); const messages = await tools.executeOpenAIToolCalls([ call('linear_list_issues', '{"a":1}', 'c1'), @@ -811,7 +826,7 @@ describe('Tools.executeOpenAIToolCalls', () => { const [message] = await tools.executeOpenAIToolCalls([call('linear_list_issues')]); - expect(JSON.parse(message?.content as string)).toEqual({ + expect(JSON.parse(contentOf(message))).toEqual({ error: '400 Bad Request: path.id is missing', response_body: { message: 'path.id is missing' }, }); @@ -830,13 +845,13 @@ describe('Tools.executeOpenAIToolCalls', () => { const [message] = await new Tools([tool]).executeOpenAIToolCalls([ call('linear_list_issues', '{not json'), ]); - expect(JSON.parse(message?.content as string).error).toMatch(/Invalid JSON in arguments/); + expect(JSON.parse(contentOf(message)).error).toMatch(/Invalid JSON in arguments/); }); it('reports an unknown tool rather than throwing', async () => { const { tools } = toolsWith(async () => ({})); const [message] = await tools.executeOpenAIToolCalls([call('invented_tool')]); - expect(JSON.parse(message?.content as string)).toEqual({ + expect(JSON.parse(contentOf(message))).toEqual({ error: 'Unknown tool "invented_tool"', }); }); @@ -846,20 +861,22 @@ describe('Tools.executeOpenAIToolCalls', () => { const [message] = await tools.executeOpenAIToolCalls([ { id: 'c', type: 'custom', custom: { name: 'linear_list_issues', input: '' } }, ]); - expect(JSON.parse(message?.content as string)).toEqual({ + expect(JSON.parse(contentOf(message))).toEqual({ error: 'Unsupported tool call type "custom"', }); }); it('serialises file bytes as base64 instead of a byte array', async () => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately bytes, not JSON const { tools } = toolsWith(async () => ({ content: Buffer.from('%PDF-1.4') as never })); const [message] = await tools.executeOpenAIToolCalls([call('linear_list_issues')]); - expect(JSON.parse(message?.content as string)).toEqual({ + expect(JSON.parse(contentOf(message))).toEqual({ content: Buffer.from('%PDF-1.4').toString('base64'), }); }); it('sends "null" for a tool that returns nothing, as the Python SDK does', async () => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately returns nothing const { tools } = toolsWith(async () => undefined as never); const [message] = await tools.executeOpenAIToolCalls([call('linear_list_issues')]); expect(message?.content).toBe('null'); diff --git a/src/tool.ts b/src/tool.ts index f9aee9be..840713c8 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -1,4 +1,3 @@ -import type { JSONSchema7 as AISDKJSONSchema } from 'ai'; import type { Tool as AnthropicTool } from '@anthropic-ai/sdk/resources'; import type { McpSdkServerConfigWithInstance } from '@anthropic-ai/claude-agent-sdk'; import type { @@ -10,13 +9,10 @@ import type { FunctionTool as OpenAIResponsesFunctionTool } from 'openai/resourc import type { OverrideProperties } from 'type-fest'; import { peerDependencies } from '../package.json'; import { SUBMIT_FEEDBACK_TOOL_NAME } from './consts'; -import { - type DeclaredHeaders, - buildRequestHeaders, - declaredHeaders, - sanitiseHeaderArguments, -} from './headers'; -import { type EndUserSource, callMcpTool, withEndUser } from './mcp-client'; +import { buildRequestHeaders, declaredHeaders, sanitiseHeaderArguments } from './headers'; +import type { DeclaredHeaders } from './headers'; +import { callMcpTool, withEndUser } from './mcp-client'; +import type { EndUserSource } from './mcp-client'; import { cloneJson, foldRootComposition } from './schema'; import type { AISDKToolDefinition, @@ -34,8 +30,10 @@ import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { ToolArgumentsError } from './utils/error-tool-arguments'; import { warn } from './utils/logger'; +import { sorted } from './utils/array'; import { serializeToolResult } from './utils/serialize'; import { tryImport } from './utils/try-import'; +import { isTruthy } from './utils/type'; /** * JSON Schema with type narrowed to 'object' @@ -119,12 +117,13 @@ export class BaseTool { const { required, ...rest } = cloneJson(this.parameters); const schema: Record = { ...rest, - type: rest.type || 'object', + type: isTruthy(rest.type) ? rest.type : 'object', properties: rest.properties ?? {}, }; if (Array.isArray(required) && required.length > 0) { schema.required = required; } + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the served schema, typed as an object schema for the provider SDKs return schema as ObjectJSONSchema; } @@ -136,6 +135,7 @@ export class BaseTool { * lost. Everything else is passed through. */ #toProviderSchema(): ObjectJSONSchema { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- folding keeps the root an object schema return foldRootComposition(this.toJsonSchema()) as ObjectJSONSchema; } @@ -224,7 +224,7 @@ export class BaseTool { 'ai', `npm install ai (requires ${peerDependencies.ai})`, ); - const inputSchema = ai.jsonSchema(this.#toProviderSchema() as AISDKJSONSchema); + const inputSchema = ai.jsonSchema(this.#toProviderSchema()); const execute = this.execute.bind(this); return { @@ -232,6 +232,7 @@ export class BaseTool { description: this.description, inputSchema, handler: async (args: Record) => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the SDK hands over the model's parsed JSON arguments const result = await execute(args as JsonObject); return { content: [{ type: 'text' as const, text: serializeToolResult(result) }], @@ -257,7 +258,7 @@ export class BaseTool { const schema = { ...this.#toProviderSchema(), additionalProperties: false, - } as AISDKJSONSchema; + }; /** AI SDK is optional dependency, import only when needed */ const ai = await tryImport( @@ -281,6 +282,7 @@ export class BaseTool { (options.executable ?? true) ? async (args: Record) => { try { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the AI SDK hands over the model's parsed JSON arguments return await this.execute(args as JsonObject); } catch (error) { return `Error executing tool: ${ @@ -431,7 +433,7 @@ export class StackOneMcpTool extends StackOneTool { const args = sanitiseHeaderArguments(parsed, this.#declaredHeaders); assertEncodable(this.name, args); - if (options?.dryRun) { + if (options?.dryRun === true) { return { url: this.#endpoint, method: 'tools/call', name: this.name, arguments: args }; } @@ -459,33 +461,41 @@ export class StackOneMcpTool extends StackOneTool { * Describe why `value` is not a JSON value, for the message {@link assertJsonValue} throws. */ function describeUnencodableType(value: unknown): string { - if (typeof value === 'bigint') { - return 'a bigint'; - } - if (typeof value === 'symbol') { - return 'a symbol'; - } - if (typeof value === 'function') { - return 'a function'; - } - if (value instanceof Date) { - return 'a Date'; - } - if (value instanceof Map) { - return 'a Map'; - } - if (value instanceof Set) { - return 'a Set'; + const primitive = UNENCODABLE_PRIMITIVES[typeof value]; + if (primitive !== undefined) { + return primitive; } - if (value instanceof RegExp) { - return 'a RegExp'; + const instance = UNENCODABLE_INSTANCES.find(([type]) => value instanceof type); + if (instance !== undefined) { + return instance[1]; } if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) { return 'binary data'; } - return `an instance of ${(value as object).constructor?.name ?? typeof value}`; + return `an instance of ${constructorName(value) ?? typeof value}`; } +/** The non-JSON types `typeof` names, as {@link describeUnencodableType} describes them. */ +const UNENCODABLE_PRIMITIVES: Partial> = { + bigint: 'a bigint', + symbol: 'a symbol', + function: 'a function', +}; + +/** Built-in objects `JSON.stringify` would silently convert, as {@link describeUnencodableType} describes them. */ +const UNENCODABLE_INSTANCES: ReadonlyArray< + readonly [abstract new (...args: never[]) => unknown, string] +> = [ + [Date, 'a Date'], + [Map, 'a Map'], + [Set, 'a Set'], + [RegExp, 'a RegExp'], +]; + +/** The name of the class an object was built by, if it has one. */ +const constructorName = (value: unknown): string | undefined => + typeof value === 'object' && value !== null ? value.constructor?.name : undefined; + /** A ToolArgumentsError for arguments that cannot be encoded as JSON. */ const unencodable = (toolName: string, detail: string): ToolArgumentsError => new ToolArgumentsError( @@ -516,53 +526,19 @@ function assertJsonValue(value: unknown, path: string, toolName: string, seen: S return; } if (typeof value === 'string') { - if (LONE_SURROGATE.test(value)) { - throw unencodable( - toolName, - `a string holding a lone surrogate is not Unicode text (at ${JSON.stringify(path)})`, - ); - } + assertJsonString(value, path, toolName); return; } if (typeof value === 'number') { - if (!Number.isFinite(value)) { - throw unencodable(toolName, `${value} is not a JSON number`); - } + assertJsonNumber(value, toolName); return; } if (Array.isArray(value)) { - if (seen.has(value)) { - throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); - } - seen.add(value); - for (let index = 0; index < value.length; index++) { - const item = value[index]; - const itemPath = `${path}[${index}]`; - if (item === undefined) { - throw unencodable( - toolName, - `undefined is not a JSON value (at ${JSON.stringify(itemPath)})`, - ); - } - assertJsonValue(item, itemPath, toolName, seen); - } - seen.delete(value); + assertJsonArray(value, path, toolName, seen); return; } if (isPlainObject(value)) { - if (seen.has(value)) { - throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); - } - seen.add(value); - for (const [key, entry] of Object.entries(value)) { - // An object property set to undefined is treated as absent, as JSON.stringify treats it. - if (entry === undefined) { - continue; - } - assertJsonKey(key, path, toolName); - assertJsonValue(entry, `${path}.${key}`, toolName, seen); - } - seen.delete(value); + assertJsonObject(value, path, toolName, seen); return; } throw unencodable( @@ -571,6 +547,63 @@ function assertJsonValue(value: unknown, path: string, toolName: string, seen: S ); } +function assertJsonString(value: string, path: string, toolName: string): void { + if (LONE_SURROGATE.test(value)) { + throw unencodable( + toolName, + `a string holding a lone surrogate is not Unicode text (at ${JSON.stringify(path)})`, + ); + } +} + +function assertJsonNumber(value: number, toolName: string): void { + if (!Number.isFinite(value)) { + throw unencodable(toolName, `${value} is not a JSON number`); + } +} + +function assertJsonArray( + value: unknown[], + path: string, + toolName: string, + seen: Set, +): void { + if (seen.has(value)) { + throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); + } + seen.add(value); + for (let index = 0; index < value.length; index++) { + const item = value[index]; + const itemPath = `${path}[${index}]`; + if (item === undefined) { + throw unencodable(toolName, `undefined is not a JSON value (at ${JSON.stringify(itemPath)})`); + } + assertJsonValue(item, itemPath, toolName, seen); + } + seen.delete(value); +} + +function assertJsonObject( + value: JsonObject, + path: string, + toolName: string, + seen: Set, +): void { + if (seen.has(value)) { + throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); + } + seen.add(value); + for (const [key, entry] of Object.entries(value)) { + // An object property set to undefined is treated as absent, as JSON.stringify treats it. + if (entry === undefined) { + continue; + } + assertJsonKey(key, path, toolName); + assertJsonValue(entry, `${path}.${key}`, toolName, seen); + } + seen.delete(value); +} + /** * Throw if an object key holds a lone surrogate. `path` is where the object is, if anywhere. * @@ -617,8 +650,8 @@ function readOpenAIToolCall(call: OpenAIToolCall): { args: string | JsonObject; unsupported?: string; } { - const id = String(call.id ?? ''); - if (!('function' in call) || !call.function) { + const id = fieldText(call.id ?? ''); + if (!('function' in call) || call.function == null || !isTruthy(call.function)) { return { id, name: '', @@ -627,9 +660,12 @@ function readOpenAIToolCall(call: OpenAIToolCall): { }; } const { name, arguments: args } = call.function; - return { id, name: String(name), args: args || {} }; + return { id, name: fieldText(name), args: args != null && isTruthy(args) ? args : {} }; } +/** A tool call's field as text: a call read back from storage has no checked type. */ +const fieldText = (value: unknown): string => String(value); + /** * Collection of tools with utility methods */ @@ -663,7 +699,13 @@ export class Tools implements Iterable { #uniqueTools(): BaseTool[] { warnOnDuplicateNames(this.tools); const seen = new Set(); - return this.tools.filter((tool) => !seen.has(tool.name) && seen.add(tool.name)); + return this.tools.filter((tool) => { + if (seen.has(tool.name)) { + return false; + } + seen.add(tool.name); + return true; + }); } /** @@ -733,31 +775,36 @@ export class Tools implements Iterable { const messages: ChatCompletionToolMessageParam[] = []; for (const call of toolCalls ?? []) { const { id, name, args, unsupported } = readOpenAIToolCall(call); - const tool = unsupported ? undefined : this.getTool(name); - let result: unknown; - if (unsupported) { - result = { error: unsupported }; - } else if (!tool) { - result = { error: `Unknown tool ${JSON.stringify(name)}` }; - } else { - try { - result = await tool.execute(args); - } catch (error) { - if (!(error instanceof StackOneError)) { - throw error; - } - const body = error instanceof StackOneAPIError ? error.responseBody : undefined; - result = { - error: error.message, - ...(body != null && body !== '' ? { response_body: body } : {}), - }; - } - } + const result = + unsupported === undefined + ? // oxlint-disable-next-line eslint/no-await-in-loop -- calls run one at a time, in order, as documented + await this.#runToolCall(name, args) + : { error: unsupported }; messages.push({ role: 'tool', tool_call_id: id, content: serializeToolResult(result) }); } return messages; } + /** Run one tool call, turning a StackOne error into a result the model can read. */ + async #runToolCall(name: string, args: string | JsonObject): Promise { + const tool = this.getTool(name); + if (tool === undefined) { + return { error: `Unknown tool ${JSON.stringify(name)}` }; + } + try { + return await tool.execute(args); + } catch (error) { + if (!(error instanceof StackOneError)) { + throw error; + } + const body = error instanceof StackOneAPIError ? error.responseBody : undefined; + return { + error: error.message, + ...(body != null && body !== '' ? { response_body: body } : {}), + }; + } + } + /** * Convert all tools to Anthropic format * @see https://docs.anthropic.com/en/docs/build-with-claude/tool-use @@ -784,6 +831,7 @@ export class Tools implements Iterable { ): Promise { const result: AISDKToolResult = {}; for (const tool of this.#uniqueTools()) { + // oxlint-disable-next-line no-await-in-loop -- converted one at a time, as before this lint pass Object.assign(result, await tool.toAISDK(options)); } return result; @@ -829,12 +877,12 @@ export class Tools implements Iterable { const sdkTools = await Promise.all( this.#uniqueTools().map(async (baseTool) => { const toolDef = await baseTool.toClaudeAgentSdkTool(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic Zod schema types return claudeAgentSdk.tool( toolDef.name, toolDef.description, + // oxlint-disable-next-line typescript/no-explicit-any, typescript/no-unsafe-type-assertion -- the SDK types a Zod shape; it is handed the AI SDK's JSON schema toolDef.inputSchema as any, - toolDef.handler as any, + toolDef.handler, ); }), ); @@ -866,7 +914,7 @@ export class Tools implements Iterable { if (index < tools.length) { return { value: tools[index++], done: false }; } - return { value: undefined as unknown as BaseTool, done: true }; + return { value: undefined, done: true }; }, }; } @@ -904,10 +952,11 @@ export function warnOnDuplicateNames(tools: readonly BaseTool[]): void { for (const tool of tools) { counts.set(tool.name, (counts.get(tool.name) ?? 0) + 1); } - const clashing = [...counts] - .filter(([name, count]) => count > 1 && name !== SUBMIT_FEEDBACK_TOOL_NAME) - .map(([name]) => name) - .sort(); + const clashing = sorted( + [...counts] + .filter(([name, count]) => count > 1 && name !== SUBMIT_FEEDBACK_TOOL_NAME) + .map(([name]) => name), + ); if (clashing.length > 0) { warn( `${clashing.length} tool name(s) are served by more than one account (${clashing.slice(0, 5).join(', ')}). The first one listed, from the lowest account id, is used — pass account ids to choose.`, diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 1f51d3a2..6b23f0ff 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -4,14 +4,11 @@ */ import { http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; -import { - MOCK_SEARCH_SESSION_ID, - type RecordedToolCall, - accountMcpTools, - createMcpApp, -} from '../mocks/mcp-server'; +import { MOCK_SEARCH_SESSION_ID, accountMcpTools, createMcpApp } from '../mocks/mcp-server'; +import type { RecordedToolCall } from '../mocks/mcp-server'; import { server } from '../mocks/node'; -import { type McpToolDefinition, listMcpTools } from './mcp-client'; +import { listMcpTools } from './mcp-client'; +import type { McpToolDefinition } from './mcp-client'; import { StackOneMcpTool } from './tool'; import { StackOneToolSet } from './toolsets'; import type { JsonObject } from './types'; @@ -28,12 +25,21 @@ const listMock = vi.mocked(listMcpTools); const { listMcpTools: realListMcpTools } = await vi.importActual('./mcp-client'); +/** The listing `listMock` serves now, for a test to wrap in its own. */ +const currentListing = (): typeof listMcpTools => { + const listing = listMock.getMockImplementation(); + assert(listing !== undefined, 'listMcpTools has no implementation'); + return listing; +}; + const newToolSet = (config: ConstructorParameters[0] = {}) => new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); +const silence = (): void => undefined; + let warnSpy: ReturnType; beforeEach(() => { - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(silence); }); afterEach(() => { vi.unstubAllEnvs(); @@ -62,12 +68,16 @@ const fakeMetaTools = ( .map((name): McpToolDefinition => ({ name, description: '', inputSchema: {} })), ); const calls: Array<{ tool: string; args: JsonObject }> = []; - vi.spyOn(StackOneMcpTool.prototype, 'execute').mockImplementation( - async function (this: StackOneMcpTool, args) { - calls.push({ tool: this.name, args: args as JsonObject }); - return respond(this, args as JsonObject); - }, - ); + vi.spyOn(StackOneMcpTool.prototype, 'execute').mockImplementation(async function ( + this: StackOneMcpTool, + args, + ) { + if (typeof args !== 'object') { + throw new TypeError(`${this.name} was called without JSON object arguments`); + } + calls.push({ tool: this.name, args }); + return respond(this, args); + }); return calls; }; @@ -231,6 +241,7 @@ describe('search()', () => { 'rejects topK=%j before any round trip', async (topK) => { await expect( + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a topK the types forbid, to test the runtime check newToolSet({ accountId: 'acc1' }).search('x', { topK: topK as never }), ).rejects.toThrow(/topK must be an integer between 1 and 50/); expect(listMock).not.toHaveBeenCalled(); @@ -274,9 +285,9 @@ describe('execute()', () => { const [hit] = await toolset.search('list items'); expect(hit?.example_request).toEqual({ query: { page_size: 25 } }); - const result = await toolset.execute(hit?.action_id ?? '', hit?.example_request as JsonObject); + const result = await toolset.execute(hit?.action_id ?? '', hit?.example_request); - expect((result.result as JsonObject).echoed_query).toEqual({ page_size: 25 }); + expect(result.result).toHaveProperty('echoed_query', { page_size: 25 }); }); // Contract §5: session_id is forwarded as a top-level argument when given, never otherwise, @@ -305,7 +316,7 @@ describe('execute()', () => { await newToolSet().execute( 'mock_list_items', - JSON.parse('{"__proto__":"p","constructor":"c","action_id":"other","q":1}') as JsonObject, + JSON.parse('{"__proto__":"p","constructor":"c","action_id":"other","q":1}'), { sessionId: 'real' }, ); @@ -374,11 +385,11 @@ describe('execute()', () => { it('raises on an isError result rather than returning it as data', async () => { serveMock(); - const error = (await newToolSet() + const error = await newToolSet() .execute('mock_not_a_real_action') - .catch((caught: unknown) => caught)) as StackOneAPIError; + .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); + assert.instanceOf(error, StackOneAPIError); expect(error.message).toContain('Unknown action mock_not_a_real_action'); expect(error.statusCode).toBe(404); }); @@ -406,8 +417,8 @@ describe('execute()', () => { .execute('linear_list_issues') .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetConfigError); - expect((error as Error).message).toMatch( + assert.instanceOf(error, ToolSetConfigError); + expect(error.message).toMatch( new RegExp( '^"linear_list_issues" matches 2 connectors on different accounts \\(linear_acc1_execute_action on acc1, linear_acc2_execute_action on acc2\\)\\. Pass the account id to use', ), @@ -439,7 +450,8 @@ describe('execute()', () => { ); const hit = (await toolset.search('x')).find((found) => found.account_id === 'acc2'); - await toolset.execute('linear_list_issues', {}, { accountIds: [hit?.account_id as string] }); + assert(hit !== undefined, 'acc2 has no search hit'); + await toolset.execute('linear_list_issues', {}, { accountIds: [hit.account_id] }); expect(calls.at(-1)?.tool).toBe('linear_acc2_execute_action'); }); @@ -467,6 +479,7 @@ describe('execute()', () => { ], [ 'array arguments', + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- arguments the types forbid, to test the runtime check () => newToolSet({ accountId: 'acc1' }).execute('x_y', [1, 2] as never), /arguments must be a JSON object, got array/, ], @@ -477,6 +490,7 @@ describe('execute()', () => { ], [ 'a numeric sessionId', + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a sessionId the types forbid, to test the runtime check () => newToolSet({ accountId: 'acc1' }).execute('x_y', {}, { sessionId: 42 as never }), /sessionId must be a non-empty string/, ], @@ -623,8 +637,8 @@ describe('submitFeedback()', () => { .submitFeedback({ rating: 'positive', toolNames: ['a'] }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetLoadError); - expect((error as Error).message).toBe( + assert.instanceOf(error, ToolSetLoadError); + expect(error.message).toBe( 'The server did not serve stackone_submit_feedback: feedback is not enabled for this project.', ); }); @@ -650,8 +664,8 @@ describe('submitFeedback()', () => { .submitFeedback({ rating: 'positive', toolNames: ['a'], accountIds: [''] }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetConfigError); - expect((error as Error).message).toBe('accountIds must not contain an empty account id'); + assert.instanceOf(error, ToolSetConfigError); + expect(error.message).toBe('accountIds must not contain an empty account id'); expect(calls).toEqual([]); }); @@ -659,6 +673,7 @@ describe('submitFeedback()', () => { await expect( newToolSet({ accountId: 'acc1' }).submitFeedback({ rating: 'positive', + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- toolNames the types forbid, to test the runtime check toolNames: 'a' as never, }), ).rejects.toThrow( @@ -673,11 +688,12 @@ describe('submitFeedback()', () => { ['a number', 42], ])('rejects %s as sessionId, as execute() does, before any round trip', async (_name, bad) => { const error = await newToolSet({ accountId: 'acc1' }) + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a sessionId the types forbid, to test the runtime check .submitFeedback({ rating: 'positive', toolNames: ['a'], sessionId: bad as never }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetConfigError); - expect((error as Error).message).toMatch(/sessionId must be a non-empty string/); + assert.instanceOf(error, ToolSetConfigError); + expect(error.message).toMatch(/sessionId must be a non-empty string/); expect(listMock).not.toHaveBeenCalled(); }); @@ -717,6 +733,7 @@ describe('execute() while an account in scope has failed to list', () => { ]; const failing = new Set(); const listed: string[] = []; + const listings = (accountId: string) => listed.filter((id) => id === accountId).length; /** Serve `accounts` from GET /accounts, and meta tools for each, failing those in `failing`. */ const serve = (accounts: typeof ACCOUNTS) => { @@ -724,14 +741,14 @@ describe('execute() while an account in scope has failed to list', () => { const calls = fakeMetaTools( accounts.map(({ id, provider }) => `${provider}_${id}_execute_action`), ); - const serveListing = listMock.getMockImplementation(); + const serveListing = currentListing(); listMock.mockImplementation(async (request) => { - const accountId = request.headers['x-account-id'] as string; + const accountId = request.headers['x-account-id']; listed.push(accountId); if (failing.has(accountId)) { throw new Error(`${accountId} is down`); } - return (serveListing as typeof listMcpTools)(request); + return serveListing(request); }); return calls; }; @@ -749,8 +766,8 @@ describe('execute() while an account in scope has failed to list', () => { .execute('linear_list_issues') .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetLoadError); - expect((error as Error).message).toBe( + assert.instanceOf(error, ToolSetLoadError); + expect(error.message).toBe( `"linear_list_issues" may be served by an account that failed to list (acc1: acc1 is down). Pass the account id to use, such as a search hit's account_id.`, ); expect(calls).toEqual([]); @@ -804,7 +821,8 @@ describe('execute() while an account in scope has failed to list', () => { .execute('linear_list_issues') .catch((caught: unknown) => caught); - expect((error as Error).message).toBe( + expect(error).toHaveProperty( + 'message', `"linear_list_issues" may be served by an account that failed to list (acc2: acc2 is down; acc3: acc3 is down). Pass the account id to use, such as a search hit's account_id.`, ); expect(calls).toEqual([]); @@ -826,8 +844,8 @@ describe('execute() while an account in scope has failed to list', () => { .execute('linear_list_issues') .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); + assert.instanceOf(error, StackOneAPIError); + expect(error.statusCode).toBe(429); }); describe('when the provider lookup cannot name a failed account', () => { @@ -849,9 +867,11 @@ describe('execute() while an account in scope has failed to list', () => { const refuses = async (toolset: StackOneToolSet) => { now += 1_000; const error = await toolset.execute('linear_x').catch((caught: unknown) => caught); - expect((error as Error).message).toMatch(/may be served by an account that failed to list/); + expect(error).toHaveProperty( + 'message', + expect.stringMatching(/may be served by an account that failed to list/), + ); }; - const listings = (accountId: string) => listed.filter((id) => id === accountId).length; beforeEach(() => { now = 0; @@ -899,7 +919,7 @@ describe('execute() while an account in scope has failed to list', () => { it('does not record a miss across a clear made during the lookup', async () => { const toolset = serveUnnameable(); - let release = () => {}; + let release: () => void = silence; const held = new Promise((resolve) => { release = resolve; }); @@ -950,19 +970,19 @@ describe('execute() while an account in scope has failed to list', () => { // Long before the failed account would be due again. expect(listed).toEqual(['acc1', 'acc2', 'acc1']); - expect(error).toBeInstanceOf(ToolSetConfigError); - expect((error as Error).message).toMatch(/^"linear_list_issues" matches 2 connectors/); + assert.instanceOf(error, ToolSetConfigError); + expect(error.message).toMatch(/^"linear_list_issues" matches 2 connectors/); expect(calls).toEqual([]); }); it('does not re-list a failed account on another provider', async () => { const calls = serve([ACCOUNTS[0], ACCOUNTS[2]] as typeof ACCOUNTS); // acc3 never answers: listing it again would make every linear action wait out its timeout. - const listOnce = listMock.getMockImplementation() as typeof listMcpTools; + const listOnce = currentListing(); listMock.mockImplementation(async (request) => { if (request.headers['x-account-id'] === 'acc3' && listed.includes('acc3')) { listed.push('acc3'); - return new Promise(() => {}); + return new Promise(silence); } return listOnce(request); }); diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index f2721132..705af3e2 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -3,19 +3,19 @@ * tool-mode routing and the failure modes of each. Search, execute and feedback live in * toolsets.search-execute.test.ts. */ -import { createServer, type Server as NetServer, type Socket } from 'node:net'; +import { createServer } from 'node:net'; +import type { Server as NetServer, Socket } from 'node:net'; import { http, HttpResponse } from 'msw'; +import type { PathParams } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; -import { - type McpToolDefinition, - type RecordedToolCall, - accountMcpTools, - createMcpApp, -} from '../mocks/mcp-server'; +import { accountMcpTools, createMcpApp } from '../mocks/mcp-server'; +import type { McpToolDefinition, RecordedToolCall } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { FAILED_ACCOUNT_RETRY_MS } from './consts'; -import { type McpToolDefinition as ListedTool, listMcpTools } from './mcp-client'; -import { StackOneMcpTool, type StackOneTool } from './tool'; +import { listMcpTools } from './mcp-client'; +import type { McpToolDefinition as ListedTool } from './mcp-client'; +import { StackOneMcpTool, StackOneTool } from './tool'; +import type { BaseTool } from './tool'; import { StackOneToolSet } from './toolsets'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; @@ -47,10 +47,15 @@ const newToolSet = (config: ConstructorParameters[0] = { new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); const names = (tools: { toArray(): Array<{ name: string }> }) => tools.toArray().map((tool) => tool.name); +/** The account a listed tool is bound to; every tool a toolset lists is a StackOneTool. */ +const accountIdOf = (tool: BaseTool | undefined): string | undefined => { + assert.instanceOf(tool, StackOneTool); + return tool.getAccountId(); +}; let warnSpy: ReturnType; beforeEach(() => { - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); }); afterEach(() => { vi.unstubAllEnvs(); @@ -125,14 +130,18 @@ describe('configuration', () => { ); it('refuses both accountId and accountIds', () => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately invalid config, refused at runtime expect(() => newToolSet({ accountId: 'a', accountIds: ['b'] } as never)).toThrow( /Cannot provide both accountId and accountIds/, ); }); it.each([ + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately a string, refused at runtime ['accountIds', () => newToolSet({ accountIds: 'acc1' as never })], + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately a string, refused at runtime ['setAccounts', () => newToolSet().setAccounts('acc1' as never)], + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately a string, refused at runtime ['fetchTools', () => newToolSet().fetchTools({ accountIds: 'acc1' as never })], ])('refuses a string where %s expects a list', async (_name, act) => { await expect(async () => act()).rejects.toThrow( @@ -207,8 +216,8 @@ describe('account scope', () => { it('binds each tool to the account it was listed for', async () => { const tools = await newToolSet().fetchTools({ accountIds: ['acc1', 'acc2', 'acc3'] }); - for (const tool of tools.toArray() as StackOneTool[]) { - expect(tool.getAccountId()).toBe(tool.name.split('_')[0]); + for (const tool of tools.toArray()) { + expect(accountIdOf(tool)).toBe(tool.name.split('_')[0]); } }); @@ -219,14 +228,8 @@ describe('account scope', () => { toolset.fetchTools({ accountIds: ['acc2'] }), ]); - expect((acc1.toArray() as StackOneTool[]).map((tool) => tool.getAccountId())).toEqual([ - 'acc1', - 'acc1', - ]); - expect((acc2.toArray() as StackOneTool[]).map((tool) => tool.getAccountId())).toEqual([ - 'acc2', - 'acc2', - ]); + expect(acc1.toArray().map(accountIdOf)).toEqual(['acc1', 'acc1']); + expect(acc2.toArray().map(accountIdOf)).toEqual(['acc2', 'acc2']); }); }); @@ -422,11 +425,11 @@ describe('account discovery', () => { HttpResponse.json({ message: 'bad key' }, { status: 401, statusText: 'Unauthorized' }), ), ); - const error = (await newToolSet() + const error = await newToolSet() .fetchAccounts() - .catch((caught: unknown) => caught)) as StackOneAPIError; + .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); + assert.instanceOf(error, StackOneAPIError); expect(error.statusCode).toBe(401); expect(error.message).toContain('401 Unauthorized: {"message":"bad key"}'); }); @@ -455,8 +458,8 @@ describe('account discovery', () => { .fetchAccounts() .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetLoadError); - expect((error as Error).message).toMatch(message); + assert.instanceOf(error, ToolSetLoadError); + expect(error.message).toMatch(message); }); it('reports an unreachable API as a ToolSetLoadError', async () => { @@ -480,11 +483,11 @@ describe('server refusals', () => { }); it('refuses an unknown account rather than serving a default catalog', async () => { - const error = (await newToolSet() + const error = await newToolSet() .fetchTools({ accountIds: ['no-such-account'] }) - .catch((caught: unknown) => caught)) as StackOneAPIError; + .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(StackOneAPIError); + assert.instanceOf(error, StackOneAPIError); expect(error.statusCode).toBe(404); }); @@ -494,13 +497,13 @@ describe('server refusals', () => { ); tool.setAccountId(undefined); - const error = (await tool - .execute({ foo: 'bar' }) - .catch((caught: unknown) => caught)) as StackOneAPIError; - expect(error.statusCode).toBe(400); + const error = await tool.execute({ foo: 'bar' }).catch((caught: unknown) => caught); + expect(error).toHaveProperty('statusCode', 400); }); }); +const listedAccounts = () => listMock.mock.calls.map(([request]) => accountOf(request)); + describe('listing', () => { // No param-style pin: tools/call arguments are mapped by the server, whichever style it serves. it('lists from the bare MCP endpoint, taking the server’s param-style', async () => { @@ -669,21 +672,22 @@ describe('listing', () => { }); it('treats every account failing as a failure, not an empty catalog, keeping each cause', async () => { - const failures = { a: new Error('boom for a'), b: new StackOneAPIError('gone', 412, null) }; + const failures: Record = { + a: new Error('boom for a'), + b: new StackOneAPIError('gone', 412, null), + }; fakeListing((request) => { - throw failures[accountOf(request) as 'a' | 'b']; + throw failures[String(accountOf(request))]; }); const error = await newToolSet() .fetchTools({ accountIds: ['a', 'b'] }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetLoadError); - expect((error as Error).message).toBe( - 'Every account failed to list tools: a: boom for a; b: gone', - ); - expect((error as Error).cause).toBeInstanceOf(AggregateError); - expect(((error as Error).cause as AggregateError).errors).toEqual([failures.a, failures.b]); + assert.instanceOf(error, ToolSetLoadError); + expect(error.message).toBe('Every account failed to list tools: a: boom for a; b: gone'); + assert.instanceOf(error.cause, AggregateError); + expect(error.cause.errors).toEqual([failures.a, failures.b]); }); // A revoked key is a 401 however many accounts it has, as it is with one. @@ -705,23 +709,21 @@ describe('listing', () => { }); it('summarises rather than rethrows when every account fails, with differing statuses', async () => { - const failures = { + const failures: Record = { a: new StackOneAPIError('revoked', 401, null), b: new StackOneAPIError('forbidden', 403, null), }; fakeListing((request) => { - throw failures[accountOf(request) as 'a' | 'b']; + throw failures[String(accountOf(request))]; }); const error = await newToolSet() .fetchTools({ accountIds: ['a', 'b'] }) .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ToolSetLoadError); - expect((error as Error).message).toBe( - 'Every account failed to list tools: a: revoked; b: forbidden', - ); - expect(((error as Error).cause as AggregateError).errors).toEqual([failures.a, failures.b]); + assert.instanceOf(error, ToolSetLoadError); + expect(error.message).toBe('Every account failed to list tools: a: revoked; b: forbidden'); + expect(error.cause).toHaveProperty('errors', [failures.a, failures.b]); }); describe('an account that fails', () => { @@ -738,7 +740,6 @@ describe('listing', () => { return [def(`tool_${accountOf(request)}`)]; }); }); - const listedAccounts = () => listMock.mock.calls.map(([request]) => accountOf(request)); // Otherwise one broken account costs every call a re-list of every account — and the full // timeout, if it hangs. @@ -806,6 +807,7 @@ describe('listing', () => { }); it('wraps an unexpected error as a ToolSetLoadError', async () => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately a malformed listing fakeListing(() => [{ name: 'broken' } as ListedTool]); listMock.mockImplementationOnce(() => { throw new TypeError('unexpected'); @@ -816,9 +818,9 @@ describe('listing', () => { }); }); -describe('filtering', () => { - const mixed = () => newToolSet({ accountId: 'mixed' }); +const mixed = () => newToolSet({ accountId: 'mixed' }); +describe('filtering', () => { it('filters by provider, case-insensitively', async () => { expect(names(await mixed().fetchTools({ providers: ['HiBob', 'bamboohr'] }))).toEqual([ 'hibob_list_employees', @@ -869,9 +871,9 @@ describe('filtering', () => { }); }); -describe('catalog cache', () => { - const listingCount = () => listMock.mock.calls.length; +const listingCount = () => listMock.mock.calls.length; +describe('catalog cache', () => { it('lists once for repeated calls', async () => { const toolset = newToolSet({ accountId: 'acc1' }); await toolset.fetchTools(); @@ -1010,7 +1012,7 @@ describe('catalog cache', () => { const first = (await toolset.fetchTools()).getTool('t'); const nested = first?.parameters.properties.body_x?.properties; - assert(nested); + assert.isDefined(nested); (nested as Record).injected = { type: 'string' }; const second = (await toolset.fetchTools()).getTool('t'); @@ -1058,7 +1060,7 @@ describe('duplicate tool names', () => { const tools = await newToolSet().fetchTools({ accountIds: ['a', 'b'] }); expect(tools.length).toBe(4); - expect((tools.getTool('hibob_list_employees') as StackOneTool).getAccountId()).toBe('a'); + expect(accountIdOf(tools.getTool('hibob_list_employees'))).toBe('a'); expect(String(warnSpy.mock.calls[0]?.[0])).toBe( '[@stackone/ai] 2 tool name(s) are served by more than one account (hibob_get_employee, hibob_list_employees). The first one listed, from the lowest account id, is used — pass account ids to choose.', ); @@ -1071,10 +1073,7 @@ describe('duplicate tool names', () => { const tools = await newToolSet().fetchTools({ accountIds: ['b', 'a'] }); - expect(tools.toArray().map((tool) => (tool as StackOneTool).getAccountId())).toEqual([ - 'a', - 'b', - ]); + expect(tools.toArray().map(accountIdOf)).toEqual(['a', 'b']); expect(tools.getTool('hibob_list_employees')).toBe(tools.toArray()[0]); }); @@ -1109,23 +1108,26 @@ describe('duplicate tool names', () => { }); }); -describe('stackone_submit_feedback in the catalog', () => { - const serveFeedback = (submitFeedback: boolean) => { - const rpcRequests: string[] = []; - const app = createMcpApp({ - accountTools: { acc1: accountMcpTools.acc1, acc2: accountMcpTools.acc2 }, - submitFeedback, - }); - server.use( - http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request)), - http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { - rpcRequests.push(((await request.json()) as { action: string }).action); +const serveFeedback = (submitFeedback: boolean) => { + const rpcRequests: string[] = []; + const app = createMcpApp({ + accountTools: { acc1: accountMcpTools.acc1, acc2: accountMcpTools.acc2 }, + submitFeedback, + }); + server.use( + http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request)), + http.post( + `${TEST_BASE_URL}/actions/rpc`, + async ({ request }) => { + rpcRequests.push((await request.json()).action); return HttpResponse.json({ data: {} }); - }), - ); - return rpcRequests; - }; + }, + ), + ); + return rpcRequests; +}; +describe('stackone_submit_feedback in the catalog', () => { it('appears once however many accounts list it, without a duplicate warning', async () => { serveFeedback(true); @@ -1191,26 +1193,26 @@ describe('execution through fetched tools', () => { }); }); -describe('model-supplied headers', () => { - const serveTool = (inputSchema: McpToolDefinition['inputSchema']) => { - const calls: RecordedToolCall[] = []; - const app = createMcpApp({ - accountTools: { - 'tenant-a': [{ name: 'crm_list_contacts', description: 'List contacts', inputSchema }], - }, - onToolCall: (call) => calls.push(call), - }); - server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); - return calls; - }; - const fetchTool = async () => { - const tool = (await newToolSet({ accountId: 'tenant-a' }).fetchTools()).getTool( - 'crm_list_contacts', - ); - assert(tool, 'tool should be listed'); - return tool; - }; +const serveTool = (inputSchema: McpToolDefinition['inputSchema']) => { + const calls: RecordedToolCall[] = []; + const app = createMcpApp({ + accountTools: { + 'tenant-a': [{ name: 'crm_list_contacts', description: 'List contacts', inputSchema }], + }, + onToolCall: (call) => calls.push(call), + }); + server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); + return calls; +}; +const fetchTool = async () => { + const tool = (await newToolSet({ accountId: 'tenant-a' }).fetchTools()).getTool( + 'crm_list_contacts', + ); + assert.isDefined(tool, 'tool should be listed'); + return tool; +}; +describe('model-supplied headers', () => { // Regression: the RPC envelope's headers were merged OVER the tool's own, so a model-supplied // x-account-id replaced the account the tool was fetched for. Over tools/call the tenant is // the transport's x-account-id, which the SDK sets; the argument never reaches the server. @@ -1345,7 +1347,9 @@ describe('timeouts', () => { beforeAll(async () => { silent = createServer((socket) => sockets.push(socket)); await new Promise((resolve) => silent.listen(0, '127.0.0.1', resolve)); - port = (silent.address() as { port: number }).port; + const address = silent.address(); + assert(typeof address === 'object' && address !== null); + port = address.port; }); afterAll(async () => { for (const socket of sockets) { diff --git a/src/toolsets.ts b/src/toolsets.ts index bda10d93..7f6dc12d 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -8,22 +8,18 @@ import { SUBMIT_FEEDBACK_TOOL_NAME, } from './consts'; import { buildRequestHeaders, isSdkOwnedHeader } from './headers'; -import { - type EndUserSource, - HttpRateLimitError, - type McpToolDefinition, - isRateLimitFailure, - listMcpTools, - withEndUser, -} from './mcp-client'; +import { HttpRateLimitError, isRateLimitFailure, listMcpTools, withEndUser } from './mcp-client'; +import type { EndUserSource, McpToolDefinition } from './mcp-client'; import { cloneJson, toolParametersFromInputSchema } from './schema'; -import { StackOneMcpTool, type StackOneTool, Tools, warnOnDuplicateNames } from './tool'; +import { StackOneMcpTool, Tools, warnOnDuplicateNames } from './tool'; +import type { StackOneTool } from './tool'; import type { ActionResult, FeedbackCategory, FeedbackRating, FeedbackSource, JsonObject, + JsonValue, SearchResult, StackOneAccount, ToolMode, @@ -34,6 +30,8 @@ import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; import { settleWithConcurrency } from './utils/concurrency'; import { fetchWithRetry, retryTiming } from './utils/fetch-retry'; import { warn } from './utils/logger'; +import { sorted } from './utils/array'; +import { isNonEmpty, isTruthy, isTruthyString } from './utils/type'; /** * Configuration with a single account ID @@ -258,33 +256,17 @@ function matchesProvider(toolName: string, providers: readonly string[]): boolea function matchGlob(value: string, pattern: string): boolean { let source = ''; for (let index = 0; index < pattern.length; index++) { - const char = pattern[index] as string; + const char = pattern[index]; if (char === '*') { source += '.*'; } else if (char === '?') { source += '.'; } else if (char === '[') { - let end = index + 1; - if (pattern[end] === '!') { - end++; - } - if (pattern[end] === ']') { - end++; - } - end = pattern.indexOf(']', end); + const end = characterClassEnd(pattern, index); if (end === -1) { source += '\\['; } else { - let body = pattern - .slice(index + 1, end) - .replaceAll('\\', '\\\\') - .replaceAll(']', '\\]'); - if (body.startsWith('!')) { - body = `^${body.slice(1)}`; - } else if (body.startsWith('^')) { - body = `\\${body}`; - } - source += `[${body}]`; + source += characterClass(pattern.slice(index + 1, end)); index = end; } } else { @@ -294,6 +276,29 @@ function matchGlob(value: string, pattern: string): boolean { return new RegExp(`^${source}$`, 's').test(value); } +/** Where the `[` at `start` closes, as `fnmatch` reads it: a leading `!` or `]` is in the class. */ +function characterClassEnd(pattern: string, start: number): number { + let end = start + 1; + if (pattern[end] === '!') { + end++; + } + if (pattern[end] === ']') { + end++; + } + return pattern.indexOf(']', end); +} + +/** A glob character class's body as a regular-expression class: `!` negates, `^` is literal. */ +function characterClass(glob: string): string { + let body = glob.replaceAll('\\', '\\\\').replaceAll(']', '\\]'); + if (body.startsWith('!')) { + body = `^${body.slice(1)}`; + } else if (body.startsWith('^')) { + body = `\\${body}`; + } + return `[${body}]`; +} + const isPlainObject = (value: unknown): value is JsonObject => typeof value === 'object' && value !== null && !Array.isArray(value); @@ -319,7 +324,7 @@ function longestConnector(actionId: string, connectors: string[]): string | unde function connectorOf(tool: StackOneTool, suffix: string): string { let stem = tool.name.endsWith(suffix) ? tool.name.slice(0, -suffix.length) : tool.name; const account = tool.getAccountId(); - if (account && stem.endsWith(`_${account}`)) { + if (isTruthyString(account) && stem.endsWith(`_${account}`)) { stem = stem.slice(0, -(account.length + 1)); } return stem.toLowerCase(); @@ -335,6 +340,9 @@ function scoreOf(action: SearchResult): number { const jsonType = (value: unknown): string => value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value; +/** A caller's value as JSON, or as `String` writes it when JSON cannot (`undefined`, a function). */ +const describeValue = (value: unknown): string => JSON.stringify(value) ?? String(value); + /** Refuse an account-id list the toolset cannot use. `null`, like `undefined`, is not given. */ const assertAccountIdList = (accountIds: unknown, parameter: string): void => { if (accountIds == null) { @@ -355,6 +363,169 @@ const assertAccountIdList = (accountIds: unknown, parameter: string): void => { } }; +/** Refuse an action id that is not a non-empty string, or arguments that are not a JSON object. */ +function assertExecuteArguments(actionId: unknown, args: unknown): void { + if (typeof actionId !== 'string' || actionId === '') { + throw new ToolSetConfigError( + `actionId must be a non-empty string, got ${describeValue(actionId)}`, + ); + } + if (args !== undefined && !isPlainObject(args)) { + throw new ToolSetConfigError(`arguments must be a JSON object, got ${jsonType(args)}`); + } +} + +/** Refuse a session id that is given but is not a non-empty string. `null` is not given. */ +function assertSessionId(sessionId: unknown): void { + if (sessionId != null && (typeof sessionId !== 'string' || sessionId === '')) { + throw new ToolSetConfigError( + `sessionId must be a non-empty string, got ${JSON.stringify(sessionId)}`, + ); + } +} + +/** + * Refuse a search the server would reject. It rejects a `topK` outside 1..50, but only after a + * round trip per connector — and that reads like an outage rather than a typo. Fail here, where + * the caller can see why. + */ +function assertSearchArguments(query: unknown, topK: unknown): void { + if (typeof topK !== 'number' || !Number.isInteger(topK) || topK < 1 || topK > MAX_TOP_K) { + throw new ToolSetConfigError( + `topK must be an integer between 1 and ${MAX_TOP_K}, got ${describeValue(topK)}`, + ); + } + if (typeof query !== 'string') { + throw new ToolSetConfigError(`query must be a string, got ${typeof query}`); + } +} + +/** Search one connector, tagging each hit with the search's session and the connector's account. */ +async function searchConnector( + tool: StackOneTool, + query: string, + topK: number, +): Promise { + const found = await tool.execute({ query, top_k: topK }); + const actions = (Array.isArray(found.actions) ? found.actions : []).filter( + (action): action is SearchResult => isPlainObject(action), + ); + // The server returns session_id once per search, beside the actions. Results from every + // connector are merged and re-ranked, so this is the last point at which a hit can still be + // traced to the search, and the account, that produced it. + const sessionId = found.session_id; + const traced = typeof sessionId === 'string' && sessionId !== '' ? { session_id: sessionId } : {}; + const accountId = tool.getAccountId(); + const owner = isTruthyString(accountId) ? { account_id: accountId } : {}; + return actions.map((action) => Object.assign(action, traced, owner)); +} + +/** + * Whether a tool is one of the providers and matches one of the action patterns a fetch asked + * for. An absent or empty list asks for every tool. + */ +function isAskedFor(toolName: string, { providers, actions }: FetchToolsOptions): boolean { + const providerAsked = + providers == null || providers.length === 0 || matchesProvider(toolName, providers); + return ( + providerAsked && + (actions == null || + actions.length === 0 || + actions.some((pattern) => matchGlob(toolName, pattern))) + ); +} + +/** A cached catalog narrowed to the accounts in `scope`, in scope order. */ +function catalogInScope( + { listings, failed }: CachedCatalog, + scope: readonly string[], +): ScopedCatalog { + return { + entries: scope.flatMap((accountId) => listings.get(accountId) ?? []), + failed: scope.flatMap((accountId): ScopedCatalog['failed'] => { + const failure = failed.get(accountId); + return failure === undefined ? [] : [[accountId, failure.message, failure.at]]; + }), + }; +} + +/** The failed accounts of a cached catalog to list again: those in `retry`, and those due at `now`. */ +function dueAccounts(cached: CachedCatalog, retry: ReadonlySet, now: number): string[] { + return [...cached.failed] + .filter(([accountId, { at }]) => retry.has(accountId) || now - at >= FAILED_ACCOUNT_RETRY_MS) + .map(([accountId]) => accountId); +} + +/** + * Refuse account options the toolset cannot use: both `accountId` and `accountIds`, an empty + * `accountId`, or a malformed id list. + */ +function assertAccountConfig(config: StackOneToolSetConfig): void { + if (config.accountId != null && config.accountIds != null) { + throw new ToolSetConfigError( + 'Cannot provide both accountId and accountIds. Use accountId for a single account or accountIds for multiple accounts.', + ); + } + // An empty accountId is usually an unset variable, and treating it as unset would silently + // widen every call to every discovered account. + if (config.accountId === '') { + throw new ToolSetConfigError('accountId must not be an empty string'); + } + assertAccountIdList(config.accountIds, 'accountIds'); + assertAccountIdList(config.execute?.accountIds, 'execute.accountIds'); +} + +/** The first of `values` that is a non-empty string. */ +const firstNonEmpty = (...values: Array): string | undefined => + values.find(isNonEmpty); + +/** The API key given, or else `STACKONE_API_KEY`. */ +function apiKeyOf(config: StackOneToolSetConfig): string { + const apiKey = firstNonEmpty(config.apiKey, process.env.STACKONE_API_KEY); + if (apiKey === undefined) { + throw new ToolSetConfigError( + 'An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable', + ); + } + return apiKey; +} + +const timeoutOf = (config: StackOneToolSetConfig): number => + config.timeout ?? config.execute?.timeout ?? DEFAULT_TIMEOUT_MS; + +const accountIdsOf = (config: StackOneToolSetConfig): string[] => [ + ...(config.accountIds ?? config.execute?.accountIds ?? []), +]; + +/** Warn about caller headers the SDK sets itself, which are ignored. */ +function warnOnIgnoredHeaders(headers: Record | undefined): void { + const ignoredHeaders = Object.keys(headers ?? {}).filter(isSdkOwnedHeader); + if (ignoredHeaders.length > 0) { + warn( + `Ignoring headers ${ignoredHeaders.map((name) => `"${name}"`).join(', ')}: the SDK sets them itself. Pass the API key and account ids through their own options instead.`, + ); + } +} + +/** + * 2.x read STACKONE_ACCOUNT_ID. An upgrade that keeps relying on it would silently widen to + * every account on the key — other end users' accounts included — so say so, once. + */ +function warnOnUnreadAccountIdVariable( + accountId: string | undefined, + accountIds: readonly string[], +): void { + if ( + isTruthyString(process.env.STACKONE_ACCOUNT_ID) && + accountId == null && + accountIds.length === 0 + ) { + warn( + 'STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active shared account on this API key is used. Pass an account id to scope the toolset.', + ); + } +} + /** * The StackOne toolset: lists the served tool catalog and exposes it to agent frameworks. * @@ -449,53 +620,20 @@ export class StackOneToolSet { * `accountId` and `accountIds` are given, or `accountId` is an empty string. */ constructor(config: StackOneToolSetConfig = {}) { - if (config.accountId != null && config.accountIds != null) { - throw new ToolSetConfigError( - 'Cannot provide both accountId and accountIds. Use accountId for a single account or accountIds for multiple accounts.', - ); - } - // An empty accountId is usually an unset variable, and treating it as unset would silently - // widen every call to every discovered account. - if (config.accountId === '') { - throw new ToolSetConfigError('accountId must not be an empty string'); - } - assertAccountIdList(config.accountIds, 'accountIds'); - assertAccountIdList(config.execute?.accountIds, 'execute.accountIds'); - - const apiKey = config.apiKey || process.env.STACKONE_API_KEY; - if (!apiKey) { - throw new ToolSetConfigError( - 'An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable', - ); - } - - const ignoredHeaders = Object.keys(config.headers ?? {}).filter(isSdkOwnedHeader); - if (ignoredHeaders.length > 0) { - warn( - `Ignoring headers ${ignoredHeaders.map((name) => `"${name}"`).join(', ')}: the SDK sets them itself. Pass the API key and account ids through their own options instead.`, - ); - } + assertAccountConfig(config); + const apiKey = apiKeyOf(config); + warnOnIgnoredHeaders(config.headers); this.#apiKey = apiKey; - this.#baseUrl = config.baseUrl || process.env.STACKONE_BASE_URL || DEFAULT_BASE_URL; + this.#baseUrl = + firstNonEmpty(config.baseUrl, process.env.STACKONE_BASE_URL) ?? DEFAULT_BASE_URL; this.#headers = { ...config.headers }; - this.#timeout = config.timeout ?? config.execute?.timeout ?? DEFAULT_TIMEOUT_MS; + this.#timeout = timeoutOf(config); this.#toolMode = config.toolMode; this.#includeNonShared = config.includeNonShared ?? false; this.#accountId = config.accountId; - this.#accountIds = [...(config.accountIds ?? config.execute?.accountIds ?? [])]; - - // 2.x read STACKONE_ACCOUNT_ID. An upgrade that keeps relying on it would silently widen to - // every account on the key — other end users' accounts included — so say so, once. - if ( - process.env.STACKONE_ACCOUNT_ID && - this.#accountId == null && - this.#accountIds.length === 0 - ) { - warn( - 'STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active shared account on this API key is used. Pass an account id to scope the toolset.', - ); - } + this.#accountIds = accountIdsOf(config); + warnOnUnreadAccountIdVariable(this.#accountId, this.#accountIds); } /** @@ -572,6 +710,7 @@ export class StackOneToolSet { return fetching; } + // oxlint-disable-next-line eslint/complexity -- one request's failure modes, each with its own error; split, the order they are checked in is lost async #requestAccounts(): Promise { const url = `${this.#baseUrl.replace(/\/+$/, '')}/accounts`; const started = ++this.#accountsStarted; @@ -641,7 +780,7 @@ export class StackOneToolSet { } const accounts = typeof body === 'object' && body !== null && !Array.isArray(body) && 'data' in body - ? (body as { data: unknown }).data + ? body.data : body; if (!Array.isArray(accounts)) { throw new ToolSetLoadError( @@ -657,6 +796,7 @@ export class StackOneToolSet { this.#providerMisses.delete(accountId); } } + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- served JSON: the accounts are read field by field where used return accounts as StackOneAccount[]; } @@ -677,12 +817,12 @@ export class StackOneToolSet { * non-shared and `includeNonShared` is not set. */ async #discoverAccountIds(): Promise { - if (this.#discoveredAccountIds) { + if (this.#discoveredAccountIds !== undefined) { return this.#discoveredAccountIds; } // Shared while in flight, so concurrent search() and fetchTools() calls on a fresh toolset // make one GET /accounts between them rather than one each. - if (!this.#discovering) { + if (this.#discovering === undefined) { const discovering = this.#fetchActiveAccountIds().finally(() => { if (this.#discovering === discovering) { this.#discovering = undefined; @@ -698,7 +838,8 @@ export class StackOneToolSet { const accounts = await this.fetchAccounts(); const active = accounts .filter( - (account) => account?.status === 'active' && typeof account.id === 'string' && account.id, + (account) => + account?.status === 'active' && typeof account.id === 'string' && account.id !== '', ) .map((account) => account.id); if (active.length === 0) { @@ -725,7 +866,7 @@ export class StackOneToolSet { `None of this API key's ${active.length} active account(s) are shared: each belongs to a single end user. Pass their account ids, or opt in to non-shared accounts, to use them.`, ); } - const skipped = active.filter((id) => !usable.includes(id)).sort(); + const skipped = sorted(active.filter((id) => !usable.includes(id))); if (skipped.length > 0) { warn( `Discovery skipped ${skipped.length} non-shared account(s) (${skipped.join(', ')}): each belongs to a single end user. Pass their account ids, or opt in to non-shared accounts, to use them.`, @@ -744,8 +885,8 @@ export class StackOneToolSet { */ async #accountsInOrder(accountIds: string[] | null | undefined): Promise { assertAccountIdList(accountIds, 'accountIds'); - let scope = accountIds?.length ? accountIds : this.#accountIds; - if (scope.length === 0 && this.#accountId) { + let scope = accountIds != null && accountIds.length > 0 ? accountIds : this.#accountIds; + if (scope.length === 0 && isTruthyString(this.#accountId)) { scope = [this.#accountId]; } if (scope.length === 0) { @@ -757,12 +898,12 @@ export class StackOneToolSet { async #resolveAccountScope(accountIds: string[] | null | undefined): Promise { // Sorted and deduplicated: the listing order, and the cache key, must not depend on the // order the caller happened to name the accounts in. - return [...new Set(await this.#accountsInOrder(accountIds))].sort(); + return sorted(new Set(await this.#accountsInOrder(accountIds))); } #endpoint(mode: ToolMode | undefined): string { const endpoint = `${this.#baseUrl.replace(/\/+$/, '')}/mcp`; - return mode ? `${endpoint}?tool-mode=${mode}` : endpoint; + return isTruthy(mode) ? `${endpoint}?tool-mode=${mode}` : endpoint; } /** @@ -797,34 +938,34 @@ export class StackOneToolSet { generation: number, retry: ReadonlySet = new Set(), ): Promise { - const inScope = ({ listings, failed }: CachedCatalog): ScopedCatalog => ({ - entries: scope.flatMap((accountId) => listings.get(accountId) ?? []), - failed: scope.flatMap((accountId): ScopedCatalog['failed'] => { - const failure = failed.get(accountId); - return failure ? [[accountId, failure.message, failure.at]] : []; - }), - }); if (scope.length === 0) { return { entries: [], failed: [] }; } const key = this.#cacheKey(scope, mode); const cached = this.#catalogCache.get(key); - const now = retryTiming.now(); - const due = cached - ? [...cached.failed] - .filter( - ([accountId, { at }]) => retry.has(accountId) || now - at >= FAILED_ACCOUNT_RETRY_MS, - ) - .map(([accountId]) => accountId) - : scope; - if (cached && due.length === 0) { - return inScope(cached); + const due = cached === undefined ? scope : dueAccounts(cached, retry, retryTiming.now()); + if (cached !== undefined && due.length === 0) { + return catalogInScope(cached, scope); } + return catalogInScope(await this.#joinOrList(key, scope, due, cached, mode, generation), scope); + } + /** + * The listing in flight for `key`, if it is of the current generation, or else a new one, + * shared while it runs. + */ + async #joinOrList( + key: string, + scope: readonly string[], + due: readonly string[], + cached: CachedCatalog | undefined, + mode: ToolMode | undefined, + generation: number, + ): Promise { // A listing that started before a clear is not joined: it belongs to the old generation. const inFlight = this.#catalogInFlight.get(key); - if (inFlight && generation === this.#cacheGeneration) { - return inScope(await inFlight); + if (inFlight !== undefined && generation === this.#cacheGeneration) { + return inFlight; } const listing = this.#listCatalog(key, scope, due, cached, mode, generation); @@ -833,7 +974,7 @@ export class StackOneToolSet { this.#catalogInFlight.set(key, listing); } try { - return inScope(await listing); + return await listing; } finally { if (this.#catalogInFlight.get(key) === listing) { this.#catalogInFlight.delete(key); @@ -878,7 +1019,7 @@ export class StackOneToolSet { }; if (scope.length === 1) { - const accountId = scope[0] as string; + const accountId = scope[0]; const listings = new Map([[accountId, await listAccount(accountId)]]); const catalog = { listings, failed: new Map() }; store(catalog); @@ -895,7 +1036,7 @@ export class StackOneToolSet { const failed = new Map(cached?.failed); const failures: [accountId: string, reason: unknown][] = []; settled.forEach((outcome, index) => { - const accountId = due[index] as string; + const accountId = due[index]; if (outcome.status === 'fulfilled') { listings.set(accountId, outcome.value); failed.delete(accountId); @@ -980,7 +1121,7 @@ export class StackOneToolSet { const { entries, failed } = await this.#catalog(scope, mode, generation, retry); let seenFeedbackTool = false; - let tools = entries + const tools = entries .filter(({ definition }) => { // Global rather than account-scoped, so every account's listing carries an // identical copy. Keep the first. @@ -991,16 +1132,8 @@ export class StackOneToolSet { seenFeedbackTool = true; return first; }) - .map((entry) => this.#createTool(entry)); - - if (options.providers?.length) { - const providers = options.providers; - tools = tools.filter((tool) => matchesProvider(tool.name, providers)); - } - if (options.actions?.length) { - const actions = options.actions; - tools = tools.filter((tool) => actions.some((pattern) => matchGlob(tool.name, pattern))); - } + .map((entry) => this.#createTool(entry)) + .filter((tool) => isAskedFor(tool.name, options)); warnOnDuplicateNames(tools); return { tools: new Tools(tools), failed }; @@ -1058,46 +1191,19 @@ export class StackOneToolSet { */ async search(query: string, options: SearchOptions = {}): Promise { const topK = options.topK === undefined ? 10 : options.topK; - // The server rejects anything outside 1..50, but only after a round trip per connector — - // and that reads like an outage rather than a typo. Fail here, where the caller can see why. - if (typeof topK !== 'number' || !Number.isInteger(topK) || topK < 1 || topK > MAX_TOP_K) { - throw new ToolSetConfigError( - `topK must be an integer between 1 and ${MAX_TOP_K}, got ${JSON.stringify(topK) ?? String(topK)}`, - ); - } - if (typeof query !== 'string') { - throw new ToolSetConfigError(`query must be a string, got ${typeof query}`); - } + assertSearchArguments(query, topK); const { tools } = await this.#metaTools('_search_actions', options.accountIds); if (tools.length === 0) { return []; } - const searchOne = async (tool: StackOneTool): Promise => { - const found = await tool.execute({ query, top_k: topK }); - const actions = (Array.isArray(found.actions) ? found.actions : []).filter( - (action): action is SearchResult => isPlainObject(action), - ); - // The server returns session_id once per search, beside the actions. Results from every - // connector are merged and re-ranked below, so this is the last point at which a hit can - // still be traced to the search, and the account, that produced it. - const sessionId = found.session_id; - const traced = typeof sessionId === 'string' && sessionId ? { session_id: sessionId } : {}; - const accountId = tool.getAccountId(); - return actions.map((action) => ({ - ...action, - ...traced, - ...(accountId ? { account_id: accountId } : {}), - })); - }; - // Fan out the way fetchTools() does: serially, a dozen connectors would cost the sum of // their latencies on the headline call. const settled = await settleWithConcurrency( tools, MAX_CONCURRENCY, - searchOne, + (tool) => searchConnector(tool, query, topK), isRateLimitFailure, ); const results: SearchResult[] = []; @@ -1120,7 +1226,7 @@ export class StackOneToolSet { // would be the best hit of whichever connector answered first rather than the best hit // overall. The server scores every action on the same scale, so rank globally, then cut to // topK: each connector was asked for topK, so the merged list can hold many more. - return results.sort((left, right) => scoreOf(right) - scoreOf(left)).slice(0, topK); + return sorted(results, (left, right) => scoreOf(right) - scoreOf(left)).slice(0, topK); } /** @@ -1151,25 +1257,15 @@ export class StackOneToolSet { * @throws StackOneAPIError If the action fails, or the lookup of a failed account's provider * is rate limited. */ + // oxlint-disable-next-line eslint/complexity -- the routing rules for failed accounts read in order here; split, they would not async execute( actionId: string, args?: JsonObject, options: ExecuteActionOptions = {}, ): Promise { - if (typeof actionId !== 'string' || !actionId) { - throw new ToolSetConfigError( - `actionId must be a non-empty string, got ${JSON.stringify(actionId) ?? String(actionId)}`, - ); - } - if (args !== undefined && !isPlainObject(args)) { - throw new ToolSetConfigError(`arguments must be a JSON object, got ${jsonType(args)}`); - } + assertExecuteArguments(actionId, args); const { sessionId } = options; - if (sessionId != null && (typeof sessionId !== 'string' || !sessionId)) { - throw new ToolSetConfigError( - `sessionId must be a non-empty string, got ${JSON.stringify(sessionId)}`, - ); - } + assertSessionId(sessionId); const suffix = '_execute_action'; const lowered = actionId.toLowerCase(); @@ -1258,6 +1354,7 @@ export class StackOneToolSet { // token alone would route every browser_linkedin action to browser. const longest = Math.max(...matches.map((tool) => connectorOf(tool, suffix).length)); const finalists = matches.filter((tool) => connectorOf(tool, suffix).length === longest); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- matches is non-empty, so finalists, its longest, is too const [tool] = finalists as [StackOneTool, ...StackOneTool[]]; if (finalists.length > 1) { // The same provider linked twice, which discovery makes common. Picking one would run the @@ -1280,6 +1377,7 @@ export class StackOneToolSet { callArguments.action_id = actionId; // `*_execute_action` answers with the action's result wrapper; see ActionResult. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- served JSON in the documented ActionResult shape return (await tool.execute(callArguments)) as ActionResult; } @@ -1329,11 +1427,7 @@ export class StackOneToolSet { if (!Array.isArray(toolNames)) { throw new ToolSetConfigError('toolNames must be an array of tool names'); } - if (sessionId != null && (typeof sessionId !== 'string' || !sessionId)) { - throw new ToolSetConfigError( - `sessionId must be a non-empty string, got ${JSON.stringify(sessionId)}`, - ); - } + assertSessionId(sessionId); // One account, one tools/call: the tool is global, so every account's copy records the same // feedback, and calling each would record it once per account. The lowest id is the one a @@ -1343,25 +1437,24 @@ export class StackOneToolSet { const tool = (await this.fetchTools({ accountIds, mode: 'search_execute' })).getTool( SUBMIT_FEEDBACK_TOOL_NAME, ); - if (!tool) { + if (tool === undefined) { throw new ToolSetLoadError( `The server did not serve ${SUBMIT_FEEDBACK_TOOL_NAME}: feedback is not enabled for this project.`, ); } - const args: JsonObject = { rating, tool_names: [...toolNames] }; - const optional = { - feedback, - category, - session_id: sessionId, - action_run_id: actionRunId, - source, + const args: JsonObject = { + rating, + tool_names: [...toolNames], + ...givenEntries({ + feedback, + category, + session_id: sessionId, + action_run_id: actionRunId, + source, + }), }; - for (const [key, value] of Object.entries(optional)) { - if (value !== undefined && value !== null) { - args[key] = value; - } - } + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- served JSON in the documented ActionResult shape return (await tool.execute(args)) as ActionResult; } } @@ -1373,32 +1466,44 @@ export class StackOneToolSet { function endUserIdsOf(accounts: readonly unknown[]): Map { const endUserIds = new Map(); for (const account of accounts) { - if ( - isPlainObject(account) && - typeof account.id === 'string' && - account.id && - account.shared === false && - typeof account.origin_username === 'string' && - account.origin_username - ) { - endUserIds.set(account.id, account.origin_username); + if (!isPlainObject(account) || account.shared !== false) { + continue; + } + const id = nonEmptyText(account.id); + const endUserId = nonEmptyText(account.origin_username); + if (id !== undefined && endUserId !== undefined) { + endUserIds.set(id, endUserId); } } return endUserIds; } +/** The entries of `fields` that are given: neither `undefined` nor `null`. */ +function givenEntries(fields: Record): JsonObject { + const given: JsonObject = {}; + for (const [key, value] of Object.entries(fields)) { + if (value !== undefined && value !== null) { + given[key] = value; + } + } + return given; +} + +/** A field's value if it is a non-empty string. */ +const nonEmptyText = (value: JsonValue | undefined): string | undefined => + typeof value === 'string' && value !== '' ? value : undefined; + /** The provider of each account in a `GET /accounts` listing that names one. */ function providersOf(accounts: readonly unknown[]): Map { const providers = new Map(); for (const account of accounts) { - if ( - isPlainObject(account) && - typeof account.id === 'string' && - account.id && - typeof account.provider === 'string' && - account.provider - ) { - providers.set(account.id, account.provider); + if (!isPlainObject(account)) { + continue; + } + const id = nonEmptyText(account.id); + const provider = nonEmptyText(account.provider); + if (id !== undefined && provider !== undefined) { + providers.set(id, provider); } } return providers; diff --git a/src/utils/array.ts b/src/utils/array.ts index d7092d99..e0b2465b 100644 --- a/src/utils/array.ts +++ b/src/utils/array.ts @@ -4,10 +4,18 @@ import type { Nullable } from './type'; /** * Convert `Arrayable` to `Array` * - * @category Array - * @link https://github.com/antfu/utils/blob/929fdd7e70f2b5095f51218be48362901923d62e/src/array.ts + * @see https://github.com/antfu/utils/blob/929fdd7e70f2b5095f51218be48362901923d62e/src/array.ts */ export function toArray(array?: Nullable>): Array { - const _array = array ?? []; - return Array.isArray(_array) ? _array : [_array]; + const items = array ?? []; + return Array.isArray(items) ? items : [items]; +} + +/** + * The items of `items` in a new, sorted array. `Array#toSorted` is not in the ES2022 lib this + * package targets. + */ +export function sorted(items: Iterable, compare?: (a: T, b: T) => number): T[] { + // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy; toSorted is not in the ES2022 lib + return [...items].sort(compare); } diff --git a/src/utils/concurrency.ts b/src/utils/concurrency.ts index 8c94805c..fee2cfb9 100644 --- a/src/utils/concurrency.ts +++ b/src/utils/concurrency.ts @@ -20,7 +20,8 @@ export async function settleWithConcurrency( while (!stopped && next < items.length) { const index = next++; try { - results[index] = { status: 'fulfilled', value: await work(items[index] as T) }; + // oxlint-disable-next-line eslint/no-await-in-loop -- each worker runs its items one at a time; the workers run in parallel + results[index] = { status: 'fulfilled', value: await work(items[index]) }; } catch (reason) { if (isFatal(reason)) { stopped = true; diff --git a/src/utils/error-stackone-api.ts b/src/utils/error-stackone-api.ts index 343f5762..6133576f 100644 --- a/src/utils/error-stackone-api.ts +++ b/src/utils/error-stackone-api.ts @@ -26,8 +26,8 @@ export class StackOneAPIError extends StackOneError { // Extract provider errors if they exist if ( - responseBody && typeof responseBody === 'object' && + responseBody !== null && 'provider_errors' in responseBody && Array.isArray(responseBody.provider_errors) ) { @@ -36,17 +36,17 @@ export class StackOneAPIError extends StackOneError { } toString(): string { - return this._formatErrorMessage(); + return this.formatErrorMessage(); } // Format the error message for better readability - private _formatErrorMessage(): string { + private formatErrorMessage(): string { // Format the main error message - let errorMessage = `API Error: ${this.statusCode} - ${this.message.replace(` for ${this._getUrlFromMessage()}`, '')}`; + let errorMessage = `API Error: ${this.statusCode} - ${this.message.replace(` for ${this.getUrlFromMessage()}`, '')}`; // Add the URL on a new line for better readability - const url = this._getUrlFromMessage(); - if (url) { + const url = this.getUrlFromMessage(); + if (url !== null && url !== '') { errorMessage += `\nEndpoint: ${url}`; } @@ -56,64 +56,72 @@ export class StackOneAPIError extends StackOneError { errorMessage += `\n- User-Agent: ${USER_AGENT}`; // Add request body information if available - if (this.requestBody) { - errorMessage += '\n\nRequest Body:'; - try { - if (typeof this.requestBody === 'object') { - errorMessage += `\n${JSON.stringify(this.requestBody, null, 2)}`; - } else if (typeof this.requestBody === 'string') { - errorMessage += ` ${this.requestBody}`; - } else { - errorMessage += ` ${JSON.stringify(this.requestBody)}`; - } - } catch { - errorMessage += ' [Unable to stringify request body]'; - } + const hasRequestBody = Boolean(this.requestBody); + if (hasRequestBody) { + errorMessage += `\n\nRequest Body:${formatRequestBody(this.requestBody)}`; } // Add provider error information if available - if (this.providerErrors && this.providerErrors.length > 0) { - errorMessage += this._formatProviderErrors(); + if (this.providerErrors != null && this.providerErrors.length > 0) { + errorMessage += formatProviderError(this.providerErrors[0]); } return errorMessage; } - // Format provider errors - private _formatProviderErrors(): string { - let errorMessage = ''; - const providerError = this.providerErrors?.[0]; - - if (typeof providerError === 'object' && providerError !== null) { - errorMessage += '\n\nProvider Error:'; - - if ('status' in providerError && typeof providerError.status === 'number') { - errorMessage += ` ${providerError.status}`; - } - - // Include raw error message if available - if ( - 'raw' in providerError && - typeof providerError.raw === 'object' && - providerError.raw !== null && - 'error' in providerError.raw && - typeof providerError.raw.error === 'string' - ) { - errorMessage += ` - ${providerError.raw.error}`; - } - - // Add provider URL on a new line - if ('url' in providerError && typeof providerError.url === 'string') { - errorMessage += `\nProvider Endpoint: ${providerError.url}`; - } + // Helper method to extract URL from the error message + private getUrlFromMessage(): string | null { + const match = this.message.match(/ for (https?:\/\/[^\s:]+)/); + return match === null ? null : match[1]; + } +} + +// Format a request body: an object as indented JSON, a string as is, anything else as JSON +function formatRequestBody(requestBody: unknown): string { + try { + if (typeof requestBody === 'object') { + return `\n${JSON.stringify(requestBody, null, 2)}`; } + if (typeof requestBody === 'string') { + return ` ${requestBody}`; + } + return ` ${JSON.stringify(requestBody)}`; + } catch { + return ' [Unable to stringify request body]'; + } +} - return errorMessage; +// Format the first provider error: its status, raw error message and endpoint, where present +function formatProviderError(providerError: unknown): string { + if (typeof providerError !== 'object' || providerError === null) { + return ''; } + const status: unknown = Reflect.get(providerError, 'status'); + const rawError = rawErrorMessage(Reflect.get(providerError, 'raw')); + const url: unknown = Reflect.get(providerError, 'url'); + let errorMessage = '\n\nProvider Error:'; - // Helper method to extract URL from the error message - private _getUrlFromMessage(): string | null { - const match = this.message.match(/ for (https?:\/\/[^\s:]+)/); - return match ? match[1] : null; + if (typeof status === 'number') { + errorMessage += ` ${status}`; + } + + // Include raw error message if available + if (rawError !== undefined) { + errorMessage += ` - ${rawError}`; + } + + // Add provider URL on a new line + if (typeof url === 'string') { + errorMessage += `\nProvider Endpoint: ${url}`; + } + + return errorMessage; +} + +// The `error` string of a provider's raw response, if it has one +function rawErrorMessage(raw: unknown): string | undefined { + if (typeof raw === 'object' && raw !== null && 'error' in raw && typeof raw.error === 'string') { + return raw.error; } + return undefined; } diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index 2bc9f97c..6d453739 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -1,4 +1,5 @@ -import { http, HttpResponse, type JsonBodyType } from 'msw'; +import { http, HttpResponse } from 'msw'; +import type { JsonBodyType } from 'msw'; import { TEST_BASE_URL } from '../../mocks/constants'; import { server } from '../../mocks/node'; import { fetchWithRetry, retryAfterMs } from './fetch-retry'; @@ -43,7 +44,7 @@ const recordedTiming = (random = () => 0.5) => { let warnSpy: ReturnType; beforeEach(() => { - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); }); afterEach(() => { vi.restoreAllMocks(); diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index 5db2cff2..417f660b 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -27,7 +27,7 @@ interface RetryOptions { const sleep = (ms: number, signal?: AbortSignal | null): Promise => new Promise((resolve, reject) => { - if (signal?.aborted) { + if (signal?.aborted === true) { reject(signal.reason); return; } @@ -109,30 +109,56 @@ function addYears(time: number, years: number): number { function parseHttpDate(value: string, now: number): number | undefined { const rfc850 = RFC850_DATE.exec(value); const fields = (rfc850 ?? IMF_FIXDATE.exec(value) ?? ASCTIME_DATE.exec(value))?.groups; - if (!fields) { + if (fields === undefined) { return undefined; } + if (rfc850 === null) { + return httpDateTime(fields, Number(fields.year)); + } const thisYear = new Date(now).getUTCFullYear(); - const year = Number(fields.year) + (rfc850 ? thisYear - (thisYear % 100) : 0); + const when = httpDateTime(fields, Number(fields.year) + thisYear - (thisYear % 100)); + return when === undefined ? undefined : nearestRfc850Year(when, now); +} + +/** The time an HTTP-date's fields name in `year`, or undefined if they name no real time. */ +function httpDateTime( + fields: Record, + year: number, +): number | undefined { const month = MONTHS.indexOf(fields.month ?? ''); const d = Number(fields.day); const h = Number(fields.hour); const m = Number(fields.minute); const s = Number(fields.second); - // Second 60 is a leap second: the instant the next minute starts. - if (year < 1 || d < 1 || d > daysInMonth(year, month) || h > 23 || m > 59 || s > 60) { + if (!isValidDateTime(year, month, d, h, m, s)) { return undefined; } - let when = utcTime(year, month, d, h, m, s); - if (rfc850) { - // RFC 9110 §5.6.7: a two-digit year more than 50 years ahead is the most recent past year - // with those digits. - const horizon = addYears(now, 50); - if (when > horizon) { - when = addYears(when, -100); - } else if (addYears(when, 100) <= horizon) { - when = addYears(when, 100); - } + return utcTime(year, month, d, h, m, s); +} + +/** Whether the fields name a real day and time. Second 60 is a leap second: the instant the next minute starts. */ +function isValidDateTime( + year: number, + month: number, + d: number, + h: number, + m: number, + s: number, +): boolean { + return !(year < 1 || d < 1 || d > daysInMonth(year, month) || h > 23 || m > 59 || s > 60); +} + +/** + * RFC 9110 §5.6.7: a two-digit year more than 50 years ahead is the most recent past year with + * those digits. + */ +function nearestRfc850Year(when: number, now: number): number { + const horizon = addYears(now, 50); + if (when > horizon) { + return addYears(when, -100); + } + if (addYears(when, 100) <= horizon) { + return addYears(when, 100); } return when; } @@ -144,7 +170,7 @@ function parseHttpDate(value: string, now: number): number | undefined { */ export function retryAfterMs(header: string | null, now: number = Date.now()): number | undefined { const value = header?.trim(); - if (!value) { + if (value === undefined || value === '') { return undefined; } if (/^\d+$/.test(value)) { @@ -189,12 +215,14 @@ const formatSeconds = (ms: number): string => String(Math.floor((ms / 1000) * 10 * Waiting anyway would only let the caller's timeout fire, turning a rate limit — which fails a * multi-account call — into a timeout, which skips one account and returns a partial result. */ +// oxlint-disable-next-line eslint/complexity -- one retry loop; splitting it would scatter the 429 policy export async function fetchWithRetry( input: string | URL, init?: RequestInit, { deadline, timing = retryTiming, onRetry }: RetryOptions = {}, ): Promise { for (let retry = 1; ; retry++) { + // oxlint-disable-next-line eslint/no-await-in-loop -- each attempt waits on the one before: retries are sequential by design const response = await fetch(input, init); if (response.status !== 429 || retry > RATE_LIMIT_MAX_RETRIES) { return response; @@ -217,6 +245,7 @@ export async function fetchWithRetry( onRetry?.(response); warn(`${limited}; retrying in ${formatSeconds(delay)}s`); if (delay > 0) { + // oxlint-disable-next-line eslint/no-await-in-loop -- the backoff must elapse before the next attempt await timing.sleep(delay, init?.signal); } } diff --git a/src/utils/serialize.ts b/src/utils/serialize.ts index ff8342a3..a843f83b 100644 --- a/src/utils/serialize.ts +++ b/src/utils/serialize.ts @@ -14,8 +14,8 @@ export function serializeToolResult(result: unknown): string { const serialized: string | undefined = JSON.stringify( result, - function replacer(this: unknown, key: string, value: unknown) { - const original = (this as Record)[key]; + function replacer(this: Record, key: string, value: unknown) { + const original = this[key]; if (original instanceof Uint8Array) { return Buffer.from(original).toString('base64'); } diff --git a/src/utils/type.test.ts b/src/utils/type.test.ts new file mode 100644 index 00000000..1e949401 --- /dev/null +++ b/src/utils/type.test.ts @@ -0,0 +1,18 @@ +import { isTruthy, isTruthyString } from './type'; + +// Both stand in for a bare `if (value)`, so they must agree with it for every value a plain +// JavaScript caller can pass, including ones the types forbid. +const values: unknown[] = ['', 'a', 0, 1, Number.NaN, false, true, null, undefined, {}, []]; + +describe('isTruthy', () => { + it.each(values)('agrees with a bare truthiness test for %o', (value) => { + expect(isTruthy(value)).toBe(Boolean(value)); + }); +}); + +describe('isTruthyString', () => { + it.each(values)('agrees with a bare truthiness test for %o', (value) => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- values a JavaScript caller can pass + expect(isTruthyString(value as string)).toBe(Boolean(value)); + }); +}); diff --git a/src/utils/type.ts b/src/utils/type.ts index ef5dde97..4804b13e 100644 --- a/src/utils/type.ts +++ b/src/utils/type.ts @@ -2,3 +2,21 @@ * A type that can be null or undefined */ export type Nullable = T | null | undefined; + +/** Whether a string is present and not empty: what a bare truthiness test on it would check. */ +export const isNonEmpty = (value: Nullable): value is string => + value !== undefined && value !== null && value !== ''; + +/** + * Whether a value is truthy: exactly what `if (value)` checks, for values a plain JavaScript caller + * can make falsy in ways the types do not allow (`false`, `0`, `''`). A plain boolean rather than a + * type guard: a guard cannot say "truthy" for a broad type like `string` or `number` without + * claiming its false branch is unreachable. Pair it with `!= null` where the type must narrow. + */ +export const isTruthy = (value: unknown): boolean => Boolean(value); + +/** + * Whether a string is truthy: exactly what `if (value)` checks, whatever a plain JavaScript caller + * actually passes. Narrows to `string` as {@link isNonEmpty} does. + */ +export const isTruthyString = (value: Nullable): value is string => Boolean(value); diff --git a/src/vectors.test.ts b/src/vectors.test.ts index 9a172349..9dad7b39 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -13,8 +13,7 @@ import { describeMcpFailure, listMcpTools, parseToolResult } from './mcp-client' import { toolParametersFromInputSchema } from './schema'; import { BaseTool, StackOneMcpTool, Tools } from './tool'; import { StackOneToolSet } from './toolsets'; -import type { JsonObject } from './types'; -import type { StackOneAPIError } from './utils/error-stackone-api'; +import type { JsonObject, JsonValue } from './types'; import { fetchWithRetry, rateLimitDelayMs, retryAfterMs, waitsForRetry } from './utils/fetch-retry'; vi.mock('./mcp-client', async (importOriginal) => { @@ -33,25 +32,28 @@ const decodeNumbers = (value: unknown): unknown => { return value.map(decodeNumbers); } if (typeof value === 'object' && value !== null) { - const entries = Object.entries(value); - if (entries.length === 1 && entries[0]?.[0] === '$number') { - return Number(entries[0][1]); - } - // defineProperty, so a `__proto__` key stays an own property, as JSON.parse leaves it. - const decoded = {}; - for (const [key, entry] of entries) { - Object.defineProperty(decoded, key, { - value: decodeNumbers(entry), - enumerable: true, - writable: true, - configurable: true, - }); - } - return decoded; + return decodeObject(Object.entries(value)); } return value; }; +const decodeObject = (entries: Array<[string, unknown]>): unknown => { + if (entries.length === 1 && entries[0]?.[0] === '$number') { + return Number(entries[0][1]); + } + // defineProperty, so a `__proto__` key stays an own property, as JSON.parse leaves it. + const decoded = {}; + for (const [key, entry] of entries) { + Object.defineProperty(decoded, key, { + value: decodeNumbers(entry), + enumerable: true, + writable: true, + configurable: true, + }); + } + return decoded; +}; + interface VectorFile { version: number; cases: Case[]; @@ -59,11 +61,26 @@ interface VectorFile { } /** A vector file, its NaN markers decoded. */ +// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- the caller names the file's shape function loadFile(name: string): File { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- parsed JSON, in the shape the caller names return decodeNumbers(JSON.parse(readFileSync(join(VECTORS, name), 'utf8'))) as File; } const load = (name: string): VectorFile => loadFile>(name); +/** A sorted copy; `toSorted()` is ES2023, past this package's ES2022 lib. */ +const sorted = (items: readonly string[]): string[] => { + const copy = [...items]; + copy.sort(); + return copy; +}; + +/** A rejection reason, which these tests only ever see as an Error. */ +const asError = (error: unknown): Error => { + assert.instanceOf(error, Error); + return error; +}; + /** Every vector file a describe() below grades. */ const GRADED = [ 'account-ids.json', @@ -79,7 +96,7 @@ const GRADED = [ // A new vector file fails here until a test loads it, rather than passing ungraded. it('grades every vector file', () => { const files = readdirSync(VECTORS).filter((name) => name.endsWith('.json')); - expect(files.sort()).toEqual([...GRADED].sort()); + expect(sorted(files)).toEqual(sorted(GRADED)); }); /** Seconds are compared with a relative tolerance of 1e-9 (README, "Reading the values"). */ @@ -122,11 +139,11 @@ const formatValue = (value: unknown, format: Placeholder['format']): string => { case 'seconds': return String(value); case 'seconds-2dp': - return String(Math.floor((value as number) * 100 + 0.5) / 100); + return String(Math.floor(Number(value) * 100 + 0.5) / 100); case 'json-type': return jsonType(value); case 'reason': { - const text = messages.reasons[value as string]; + const text = messages.reasons[String(value)]; if (text === undefined) { throw new Error(`No reason text for ${String(value)}`); } @@ -140,25 +157,26 @@ const formatValue = (value: unknown, format: Placeholder['format']): string => { /** A message's template, rendered with these values. */ const render = (id: string, values: Record = {}): string => { const message = messageById.get(id); - if (!message) { + if (message === undefined) { throw new Error(`messages.json has no message ${id}`); } return message.template.replace(/\{(\w+)\}/g, (_match, name: string) => { const placeholder = message.placeholders[name]; - if (!placeholder || !(name in values)) { + if (placeholder === undefined || !(name in values)) { throw new Error(`No value for {${name}} in ${id}`); } return formatValue(values[name], placeholder.format); }); }; +const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + /** A message's template as a pattern, with these values and every other placeholder open. */ const pattern = (id: string, values: Record = {}): RegExp => { const message = messageById.get(id); - if (!message) { + if (message === undefined) { throw new Error(`messages.json has no message ${id}`); } - const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const source = message.template .split(/(\{\w+\})/) .map((part) => { @@ -167,7 +185,7 @@ const pattern = (id: string, values: Record = {}): RegExp => { return escape(part); } const placeholder = message.placeholders[name]; - return name in values && placeholder + return name in values && placeholder !== undefined ? escape(formatValue(values[name], placeholder.format)) : '.*'; }) @@ -180,7 +198,7 @@ const PREFIX = '[@stackone/ai] '; let warnSpy: ReturnType; const warnings = (): string[] => warnSpy.mock.calls.map(([message]: unknown[]) => String(message)); beforeEach(() => { - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); }); afterEach(() => { vi.restoreAllMocks(); @@ -193,23 +211,33 @@ const toolWith = (inputSchema: Record, name = 'vector_tool') => new StackOneMcpTool({ name, description: '', - parameters: toolParametersFromInputSchema(inputSchema as never), + parameters: toolParametersFromInputSchema(inputSchema), endpoint: `${TEST_BASE_URL}/mcp`, apiKey: 'test-key', accountId: 'acc-1', timeout: 5_000, }); +const isJsonObject = (value: JsonValue | undefined): value is JsonObject => + typeof value === 'object' && value !== null && !Array.isArray(value); + const sentArguments = async ( inputSchema: Record, args: unknown, ): Promise => { + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- vector input, valid or not, as a model would send it const call = await toolWith(inputSchema).execute(args as JsonObject, { dryRun: true }); - return call.arguments as JsonObject; + assert(isJsonObject(call.arguments)); + return call.arguments; }; const OPEN_HEADERS = { type: 'object', properties: { headers: { type: 'object' } } }; +const newToolSet = (config: Record = {}) => + new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); + +const outcomeOf = (act: () => Promise) => act().then(() => 'ok' as const, asError); + // --------------------------------------------------------------------------------------------- describe('retry-after.json', () => { @@ -253,12 +281,12 @@ describe('backoff.json', () => { }); it.each(file.cases)('$id', ({ retry, random, retry_after_seconds, expected_delay_seconds }) => { - const delay = rateLimitDelayMs( + const delayMs = rateLimitDelayMs( retry, retry_after_seconds === null ? undefined : retry_after_seconds * 1000, () => random, ); - expectSeconds(delay / 1000, expected_delay_seconds); + expectSeconds(delayMs / 1000, expected_delay_seconds); }); it.each(file.deadline_cases)('$id', ({ delay_seconds, remaining_seconds, expected }) => { @@ -278,11 +306,10 @@ describe('header-values.json', () => { it.each(file.cases)('$id', async ({ value, expected }) => { const sent = await sentArguments(OPEN_HEADERS, { headers: { 'x-probe': value } }); - const headers = sent.headers as Record; if (typeof expected === 'string') { - expect(headers).toEqual({ 'x-probe': expected }); + expect(sent.headers).toEqual({ 'x-probe': expected }); } else { - expect(headers).toEqual({}); + expect(sent.headers).toEqual({}); } }); }); @@ -301,7 +328,7 @@ describe('header-names.json', () => { it.each(file.cases)('$id', async ({ name, expected }) => { const sent = await sentArguments(OPEN_HEADERS, { headers: { [name]: 'v' } }); if ('forwarded' in expected) { - expect(Object.entries(sent.headers as object)).toEqual([[expected.forwarded, 'v']]); + expect(Object.entries(sent.headers ?? {})).toEqual([[expected.forwarded, 'v']]); expect(warnings()).toEqual([]); } else { expect(sent.headers).toEqual({}); @@ -360,9 +387,9 @@ describe('argument-encoding.json', () => { case 'invalid-json': { let detail = ''; try { - JSON.parse(input as string); + JSON.parse(String(input)); } catch (error) { - detail = (error as Error).message; + detail = asError(error).message; } return pattern('arguments-invalid-json', { tool: TOOL, detail }); } @@ -382,10 +409,11 @@ describe('argument-encoding.json', () => { it.each(file.cases)('$id', async (testCase) => { const input = 'arguments_json' in testCase ? testCase.arguments_json : testCase.arguments; const outcome = await toolWith({ type: 'object', properties: {} }, TOOL) + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- vector input, valid or not, as a model would send it .execute(input as JsonObject, { dryRun: true }) .then( (call) => ({ ok: call }), - (error: unknown) => ({ error: error as Error }), + (error: unknown) => ({ error: asError(error) }), ); if (testCase.expected === 'ok') { expect(outcome).toHaveProperty('ok'); @@ -406,23 +434,16 @@ describe('account-ids.json', () => { expected: 'ok' | { error: { node: string } }; }>('account-ids.json'); - const newToolSet = (config: Record = {}) => - new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); - /** Every place that takes an account-id list, each refusing before any request. */ const listTakers: Array<[string, (value: unknown) => Promise]> = [ ['the constructor', async (value) => newToolSet({ accountIds: value })], ['execute.accountIds', async (value) => newToolSet({ execute: { accountIds: value } })], + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- vector value, valid or not, as a caller would pass it ['setAccounts()', async (value) => newToolSet().setAccounts(value as string[])], + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- vector value, valid or not, as a caller would pass it ['fetchTools()', async (value) => newToolSet().fetchTools({ accountIds: value as string[] })], ]; - const outcomeOf = (act: () => Promise) => - act().then( - () => 'ok' as const, - (error: unknown) => error as Error, - ); - it('is the version these tests were written for', () => { expect(file.version).toBe(1); }); @@ -440,7 +461,7 @@ describe('account-ids.json', () => { expect(outcome).toBe('ok'); } else { expect(outcome).toBeInstanceOf(Error); - expect((outcome as Error).name).toBe(expected.error.node); + expect(outcome !== 'ok' && outcome.name).toBe(expected.error.node); } if (expected !== 'ok' || parameter === 'account_id') { expect(listMock).not.toHaveBeenCalled(); @@ -452,9 +473,6 @@ describe('account-ids.json', () => { // --------------------------------------------------------------------------------------------- // messages.json: every shared message, through the code that emits it. -const newToolSet = (config: Record = {}) => - new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); - /** Serve these tools on the accounts their names end in, as `_[_]`. */ const listByAccount = (names: string[]) => { listMock.mockImplementation(async ({ headers }) => @@ -470,22 +488,19 @@ const listByAccount = (names: string[]) => { /** Answer every tools/call with `respond`, without a server. */ const respondToCalls = (respond: (tool: StackOneMcpTool) => JsonObject | Promise) => { - vi.spyOn(StackOneMcpTool.prototype, 'execute').mockImplementation( - async function (this: StackOneMcpTool) { - return respond(this); - }, - ); + vi.spyOn(StackOneMcpTool.prototype, 'execute').mockImplementation(async function ( + this: StackOneMcpTool, + ) { + return respond(this); + }); }; const errorOf = (act: () => unknown): Promise => Promise.resolve() .then(act) - .then( - () => { - throw new Error('expected an error'); - }, - (error: unknown) => error as Error, - ); + .then(() => { + throw new Error('expected an error'); + }, asError); type Emitted = { error: Error } | { warnings: string[] } | { toolResult: string }; @@ -524,7 +539,7 @@ const emitters: Record< await fetchWithRetry( url, { method: 'POST' }, - { timing: { sleep: async () => {}, random: () => 0.5, now: () => 0 } }, + { timing: { sleep: async () => undefined, random: () => 0.5, now: () => 0 } }, ); return { emitted: { warnings: warnings() }, @@ -541,7 +556,7 @@ const emitters: Record< { method: 'POST' }, { deadline: 1_000, - timing: { sleep: async () => {}, random: () => 0.5, now: () => 0 }, + timing: { sleep: async () => undefined, random: () => 0.5, now: () => 0 }, }, ); return { @@ -674,16 +689,16 @@ const emitters: Record< let requests = 0; server.use( http.all(endpoint, async () => { - if (requests++ === 0) { - return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); + if (requests++ > 0) { + await delay('infinite'); } - await delay('infinite'); + return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); }), ); const error = await errorOf(() => realListMcpTools({ endpoint, headers: { 'x-account-id': 'acc-1' }, timeout }), ); - expect((error as StackOneAPIError).statusCode).toBe(429); + expect(error).toHaveProperty('statusCode', 429); return { emitted: { error }, values: { endpoint, timeout: timeout / 1_000 } }; }, 'accounts-rate-limit-timeout': async () => { @@ -692,14 +707,14 @@ const emitters: Record< let requests = 0; server.use( http.get(url, async () => { - if (requests++ === 0) { - return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); + if (requests++ > 0) { + await delay('infinite'); } - await delay('infinite'); + return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); }), ); const error = await errorOf(() => newToolSet({ timeout }).fetchAccounts()); - expect((error as StackOneAPIError).statusCode).toBe(429); + expect(error).toHaveProperty('statusCode', 429); return { emitted: { error }, values: { url, timeout: timeout / 1_000 } }; }, 'mcp-http-failure': async () => { @@ -873,7 +888,10 @@ const emitters: Record< }), 'execute-arguments-not-an-object': async () => ({ emitted: { - error: await errorOf(() => newToolSet({ accountId: 'acc-1' }).execute('x_y', [1] as never)), + error: await errorOf(() => + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately not an object + newToolSet({ accountId: 'acc-1' }).execute('x_y', [1] as never), + ), }, values: { json_type: [1] }, }), @@ -888,6 +906,7 @@ const emitters: Record< error: await errorOf(() => newToolSet({ accountId: 'acc-1' }).submitFeedback({ rating: 'positive', + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately not a list toolNames: 'a' as never, }), ), @@ -940,7 +959,7 @@ const emitters: Record< try { JSON.parse('{'); } catch (error) { - detail = (error as Error).message; + detail = asError(error).message; } return { emitted: { @@ -951,7 +970,10 @@ const emitters: Record< }, 'arguments-not-an-object': async () => ({ emitted: { - error: await errorOf(() => toolWith({ type: 'object', properties: {} }).execute(5 as never)), + error: await errorOf(() => + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- deliberately not an object + toolWith({ type: 'object', properties: {} }).execute(5 as never), + ), }, values: { tool: 'vector_tool' }, }), @@ -966,9 +988,12 @@ const emitters: Record< 'no-executor': async () => ({ emitted: { error: await errorOf(() => - new BaseTool('hand_built', '', { type: 'object', properties: {} }, { - kind: 'local', - } as never).execute({}), + new BaseTool( + 'hand_built', + '', + { type: 'object', properties: {} }, + { kind: 'local' }, + ).execute({}), ), }, values: { tool: 'hand_built' }, @@ -977,8 +1002,9 @@ const emitters: Record< const [message] = await new Tools([]).executeOpenAIToolCalls([ { id: 'c', type: 'function', function: { name: 'invented', arguments: '{}' } }, ]); + assert(typeof message?.content === 'string'); return { - emitted: { toolResult: JSON.parse(message?.content as string).error }, + emitted: { toolResult: JSON.parse(message.content).error }, values: { name: 'invented' }, }; }, @@ -990,14 +1016,14 @@ describe('messages.json', () => { }); it('has an emitter for every shared message', () => { - expect(Object.keys(emitters).sort()).toEqual( - messages.messages.map((message) => message.id).sort(), + expect(sorted(Object.keys(emitters))).toEqual( + sorted(messages.messages.map((message) => message.id)), ); }); it.each(messages.messages)('$id', async ({ id, kind, error: errorClass }) => { const emit = emitters[id]; - if (!emit) { + if (emit === undefined) { throw new Error(`No emitter for ${id}`); } const { emitted, values } = await emit(); @@ -1011,9 +1037,9 @@ describe('messages.json', () => { } else if (kind === 'tool-result') { expect('toolResult' in emitted && emitted.toolResult).toMatch(expected); } else { - const { error } = emitted as { error: Error }; - expect(error.name).toBe(errorClass?.node); - expect(error.message).toMatch(expected); + assert('error' in emitted); + expect(emitted.error.name).toBe(errorClass?.node); + expect(emitted.error.message).toMatch(expected); } }); }); diff --git a/tests/examples/claude-agent-sdk-integration.test.ts b/tests/examples/claude-agent-sdk-integration.test.ts index 77c2ba3f..de44a900 100644 --- a/tests/examples/claude-agent-sdk-integration.test.ts +++ b/tests/examples/claude-agent-sdk-integration.test.ts @@ -125,7 +125,7 @@ describe('claude-agent-sdk-integration example e2e', () => { // Execute the tool handler directly const result = await getEmployeeTool.handler( { id: 'c28xIQaWQ6MzM5MzczMDA2NzMzMzkwNzIwNA' }, - {} as unknown, + {}, ); expect(result).toBeDefined(); diff --git a/tests/examples/fetch-tools.test.ts b/tests/examples/fetch-tools.test.ts index ce0de301..30e8f876 100644 --- a/tests/examples/fetch-tools.test.ts +++ b/tests/examples/fetch-tools.test.ts @@ -5,6 +5,7 @@ */ import { http, HttpResponse } from 'msw'; +import { isRecord } from '../../mocks/handlers.utils'; import { server } from '../../mocks/node'; import { TEST_BASE_URL } from '../../mocks/constants'; import { StackOneToolSet } from '../../src'; @@ -23,8 +24,8 @@ describe('fetch-tools example e2e', () => { server.use( http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { const body: unknown = await request.json(); - assert(typeof body === 'object' && body !== null); - const { action } = body as Record; + assert(isRecord(body)); + const { action } = body; if (action === 'bamboohr_list_employees') { return HttpResponse.json({ data: [ @@ -94,9 +95,11 @@ describe('fetch-tools example e2e', () => { }); // The mock echoes what reached tools/call, inside the server's { isError, result }. expect(result.isError).toBe(false); - expect((result.result as { data: unknown }).data).toMatchObject({ - action: 'bamboohr_list_employees', - arguments: { query: { limit: 5 } }, + expect(result.result).toMatchObject({ + data: { + action: 'bamboohr_list_employees', + arguments: { query: { limit: 5 } }, + }, }); }); }); diff --git a/tests/examples/openai-integration.test.ts b/tests/examples/openai-integration.test.ts index e8dd5d12..3ccf586e 100644 --- a/tests/examples/openai-integration.test.ts +++ b/tests/examples/openai-integration.test.ts @@ -74,7 +74,9 @@ describe('openai-integration example e2e', () => { const toolMessages = await tools.executeOpenAIToolCalls(choice.message.tool_calls); expect(toolMessages).toHaveLength(1); expect(toolMessages[0]).toMatchObject({ role: 'tool', tool_call_id: 'call_mock' }); - expect(JSON.parse(toolMessages[0]?.content as string)).toMatchObject({ + const content = toolMessages[0]?.content; + assert(typeof content === 'string', 'the tool message carries no text'); + expect(JSON.parse(content)).toMatchObject({ isError: false, result: { data: { diff --git a/tests/examples/search-and-execute.test.ts b/tests/examples/search-and-execute.test.ts index ade5a5e7..734eeea0 100644 --- a/tests/examples/search-and-execute.test.ts +++ b/tests/examples/search-and-execute.test.ts @@ -8,11 +8,8 @@ import { http } from 'msw'; import { TEST_BASE_URL } from '../../mocks/constants'; import { mockAccountTools } from '../../mocks/handlers.mcp'; -import { - type RecordedToolCall, - MOCK_SEARCH_SESSION_ID, - createMcpApp, -} from '../../mocks/mcp-server'; +import { MOCK_SEARCH_SESSION_ID, createMcpApp } from '../../mocks/mcp-server'; +import type { RecordedToolCall } from '../../mocks/mcp-server'; import { server } from '../../mocks/node'; import { StackOneToolSet, ToolSetLoadError } from '../../src'; @@ -35,7 +32,7 @@ describe('search-and-execute example e2e', () => { onToolCall: (call) => calls.push(call), }); server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); - const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined); await import('../../examples/search-and-execute'); @@ -54,7 +51,7 @@ describe('search-and-execute example e2e', () => { const toolset = new StackOneToolSet(); const [best] = await toolset.search('list recent comments', { topK: 3 }); - assert(best); + assert(best !== undefined); expect(await toolset.execute(best.action_id, {}, { sessionId: best.session_id })).toMatchObject( { isError: false, result: { data: { nodes: [] } } }, ); diff --git a/tests/examples/tanstack-ai-integration.test.ts b/tests/examples/tanstack-ai-integration.test.ts index 4b82b77a..044e2898 100644 --- a/tests/examples/tanstack-ai-integration.test.ts +++ b/tests/examples/tanstack-ai-integration.test.ts @@ -34,7 +34,7 @@ describe('tanstack-ai-integration example e2e', () => { // Get a specific tool const employeeTool = tools.getTool('bamboohr_get_employee'); - assert(employeeTool, 'Expected bamboohr_get_employee tool to exist'); + assert(employeeTool !== undefined, 'Expected bamboohr_get_employee tool to exist'); // Create TanStack AI compatible tool wrapper // Use toJsonSchema() to get the parameter schema in JSON Schema format