From 6ffcca3819403084450e94c4c8cc48e83f51c78e Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 15 Sep 2026 15:41:57 +0100 Subject: [PATCH 001/151] refactor!: remove client-side search from the Node SDK MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mirrors the same removal in stackone-ai-python. Search is absent from the sdk-conformance wire contract — the mock serves no /actions/search and no runner exercises any search method — and the contract docs flag client-side search as something that belongs server-side. BREAKING: removes searchTools(), searchActionNames(), getSearchTool(), the SearchTool class, the tool_search/tool_execute meta tools, openai({ mode: 'search_and_execute' }), the StackOneToolSet `search` option, and the SearchMode / SearchConfig / SearchToolsOptions / SearchActionNamesOptions types. Scope the catalog with `providers` / `actions` on fetchTools() instead. Deletes semantic-search.ts, local-search.ts, utils/tfidf-index.ts and utils/normalize.ts, and drops the now-unused @orama/orama dependency and its catalog entry. Methods were removed by brace-matching rather than line ranges, and knip caught two leftovers the grep missed: an unresolved `normalizeActionName` import in toolsets.ts and the orphaned DEFAULT_HYBRID_ALPHA constant. 255 tests pass, no type errors, lint and knip clean. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 56 --- examples/README.md | 6 +- examples/search-tools.ts | 176 ---------- package.json | 1 - pnpm-lock.yaml | 71 ++-- pnpm-workspace.yaml | 1 - src/agent-tools.test.ts | 384 -------------------- src/consts.ts | 11 - src/index.ts | 13 - src/local-search.test.ts | 176 ---------- src/local-search.ts | 204 ----------- src/semantic-search.test.ts | 192 ---------- src/semantic-search.ts | 244 ------------- src/toolsets.test.ts | 304 ---------------- src/toolsets.ts | 635 ---------------------------------- src/types.ts | 19 - src/utils/normalize.test.ts | 41 --- src/utils/normalize.ts | 33 -- src/utils/tfidf-index.test.ts | 206 ----------- src/utils/tfidf-index.ts | 192 ---------- 20 files changed, 35 insertions(+), 2930 deletions(-) delete mode 100644 examples/search-tools.ts delete mode 100644 src/agent-tools.test.ts delete mode 100644 src/local-search.test.ts delete mode 100644 src/local-search.ts delete mode 100644 src/semantic-search.test.ts delete mode 100644 src/semantic-search.ts delete mode 100644 src/utils/normalize.test.ts delete mode 100644 src/utils/normalize.ts delete mode 100644 src/utils/tfidf-index.test.ts delete mode 100644 src/utils/tfidf-index.ts diff --git a/README.md b/README.md index 5557f042..747b8e7d 100644 --- a/README.md +++ b/README.md @@ -297,62 +297,6 @@ This is especially useful when you want to: - Focus on specific HR/CRM/ATS providers - Get only certain types of operations (e.g., all "list" operations) -### Search Tool - -Search for tools using natural language queries. Works with both semantic (cloud) and local BM25+TF-IDF search. - -#### Basic Usage - -```typescript -import { StackOneToolSet } from '@stackone/ai'; - -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment -const toolset = new StackOneToolSet(); -const searchTool = toolset.getSearchTool(); - -// Search for relevant tools — returns a Tools collection -const tools = await searchTool.search('manage employees', { topK: 5 }); - -// Execute a discovered tool directly -const listTool = tools.getTool('workday_list_workers'); -const result = await listTool.execute({ query: { limit: 10 } }); -``` - -### Semantic Search - -Discover tools using natural language instead of exact names. Queries like "onboard new hire" resolve to the right actions even when the tool is called `workday_create_employee`. - -```typescript -import { StackOneToolSet } from '@stackone/ai'; - -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment -const toolset = new StackOneToolSet(); - -// Search by intent — returns Tools collection ready for any framework -const tools = await toolset.searchTools('manage employee records', { topK: 5 }); -const openAITools = tools.toOpenAI(); - -// Lightweight: inspect results without fetching full tool definitions -const results = await toolset.searchActionNames('time off requests', { topK: 5 }); -``` - -#### Search Modes - -Control which search backend `searchTools()` uses via the `search` option: - -```typescript -// 'auto' (default) — tries semantic search first, falls back to local -const tools = await toolset.searchTools('manage employees', { search: 'auto' }); - -// 'semantic' — semantic API only, throws if unavailable -const tools = await toolset.searchTools('manage employees', { search: 'semantic' }); - -// 'local' — local BM25+TF-IDF only, no semantic API call -const tools = await toolset.searchTools('manage employees', { search: 'local' }); -``` - -Results are automatically scoped to connectors in your linked accounts. See [Search Tools Example](examples/search-tools.ts) for `SearchTool` (`getSearchTool`) integration, AI SDK, and agent loop patterns. - ### Custom Base URL ```typescript diff --git a/examples/README.md b/examples/README.md index 06af90b9..8e7ffd18 100644 --- a/examples/README.md +++ b/examples/README.md @@ -66,10 +66,6 @@ Integrates with the Vercel AI SDK via `tools.toAISDK()`. Runs a multi-step agent Converts StackOne tools into an MCP server with `tools.toClaudeAgentSdk()` and passes it to the Claude Agent SDK `query()` function. Streams agent messages and logs tool-use blocks as they arrive. -### [`search-tools.ts`](./search-tools.ts) -- Tool Discovery - -Covers five approaches to finding the right tools at runtime: direct fetch with action-pattern filters, semantic (embedding-based) search, local BM25/TF-IDF search, auto search that falls back gracefully, and a search-and-execute mode that hands `tool_search` + `tool_execute` to an LLM agent via the Vercel AI SDK. - ### [`auth-management.ts`](./auth-management.ts) -- Authentication Patterns Walks through every way to configure API keys and account IDs: reading from environment variables, passing them explicitly to the constructor, setting multiple accounts with `setAccounts()`, overriding per-tool collection or per individual tool, and fetching tools for multiple accounts in one call. @@ -84,5 +80,5 @@ Demonstrates the four ways to configure prompt-injection detection on a `StackOn | --------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ | | `STACKONE_API_KEY` | Yes | All examples | | `STACKONE_ACCOUNT_ID` | Recommended | All examples (read automatically by `new StackOneToolSet()`) | -| `OPENAI_API_KEY` | For OpenAI / AI SDK examples | `openai-integration.ts`, `openai-responses-integration.ts`, `ai-sdk-integration.ts`, `search-tools.ts` (section 5) | +| `OPENAI_API_KEY` | For OpenAI / AI SDK examples | `openai-integration.ts`, `openai-responses-integration.ts`, `ai-sdk-integration.ts` | | `ANTHROPIC_API_KEY` | For Anthropic examples | `anthropic-integration.ts`, `claude-agent-sdk-integration.ts` | diff --git a/examples/search-tools.ts b/examples/search-tools.ts deleted file mode 100644 index 3bf23baf..00000000 --- a/examples/search-tools.ts +++ /dev/null @@ -1,176 +0,0 @@ -/** - * Tool discovery with the StackOne AI SDK. - * - * Covers: direct fetch, semantic search, local search, auto search, - * and the search-and-execute pattern. - * - * Run with: - * STACKONE_API_KEY=xxx STACKONE_ACCOUNT_ID=xxx npx tsx examples/search-tools.ts - */ - -import process from 'node:process'; -import { StackOneToolSet } from '@stackone/ai'; - -const apiKey = process.env.STACKONE_API_KEY; -const accountId = process.env.STACKONE_ACCOUNT_ID; - -if (!apiKey) { - console.error('Set STACKONE_API_KEY to run this example.'); - process.exit(1); -} -if (!accountId) { - console.error('Set STACKONE_ACCOUNT_ID to run this example.'); - process.exit(1); -} - -// --------------------------------------------------------------------------- -// 1. Direct fetch — no search, just action-pattern filtering -// --------------------------------------------------------------------------- -async function directFetch(): Promise { - console.log('\n=== 1. Direct Fetch (action filters) ===\n'); - - const toolset = new StackOneToolSet({ apiKey, accountId }); - - // Glob pattern: fetch only Workday tools - const tools = await toolset.fetchTools({ actions: ['workday_*'] }); - const names = tools.toArray().map((t) => t.name); - console.log(` Fetched ${names.length} tools matching "workday_*"`); - console.log(` First 5: ${names.slice(0, 5).join(', ')}`); -} - -// --------------------------------------------------------------------------- -// 2. Semantic search — remote embedding-based similarity -// --------------------------------------------------------------------------- -async function semanticSearch(): Promise { - console.log('\n=== 2. Semantic Search ===\n'); - - const toolset = new StackOneToolSet({ - apiKey, - accountId, - search: { method: 'semantic', topK: 5 }, - }); - - const tools = await toolset.searchTools('manage employees'); - const names = tools.toArray().map((t) => t.name); - console.log(` Query: "manage employees" -> ${names.length} results`); - for (const name of names) { - console.log(` - ${name}`); - } -} - -// --------------------------------------------------------------------------- -// 3. Local search — BM25 + TF-IDF, no API call to semantic endpoint -// --------------------------------------------------------------------------- -async function localSearch(): Promise { - console.log('\n=== 3. Local Search (BM25 + TF-IDF) ===\n'); - - const toolset = new StackOneToolSet({ - apiKey, - accountId, - search: { method: 'local', topK: 5 }, - }); - - const tools = await toolset.searchTools('time off requests', { search: 'local' }); - const names = tools.toArray().map((t) => t.name); - console.log(` Query: "time off requests" -> ${names.length} results`); - for (const name of names) { - console.log(` - ${name}`); - } -} - -// --------------------------------------------------------------------------- -// 4. Auto search + getSearchTool() callable -// Tries semantic first, falls back to local if the API is unavailable. -// --------------------------------------------------------------------------- -async function autoSearchWithCallable(): Promise { - console.log('\n=== 4. Auto Search + getSearchTool() Callable ===\n'); - - const toolset = new StackOneToolSet({ - apiKey, - accountId, - search: { method: 'auto', topK: 5 }, - }); - - // 4a. Direct searchTools() with auto mode - const tools = await toolset.searchTools('send a message', { search: 'auto' }); - console.log(` searchTools("send a message") -> ${tools.length} results`); - - // 4b. getSearchTool() — a callable wrapper for agent loops - const searchTool = toolset.getSearchTool(); - - const queries = ['cancel an event', 'list employees', 'create a job posting']; - for (const query of queries) { - const results = await searchTool.search(query, { topK: 3 }); - const names = results.toArray().map((t) => t.name); - console.log(` searchTool.search("${query}") -> ${names.join(', ') || '(none)'}`); - } - - // 4c. Constructor topK vs per-call override - console.log('\n -- topK override --'); - const defaultResults = await toolset.searchTools('manage employee records'); - console.log(` Constructor topK=5: got ${defaultResults.length} tools`); - - const overrideResults = await toolset.searchTools('manage employee records', { topK: 10 }); - console.log(` Per-call topK=10: got ${overrideResults.length} tools`); -} - -// --------------------------------------------------------------------------- -// 5. Search & execute mode — getTools() with Vercel AI SDK -// The LLM receives tool_search + tool_execute and discovers tools on demand. -// --------------------------------------------------------------------------- -async function searchAndExecute(): Promise { - console.log('\n=== 5. Search & Execute (Vercel AI SDK) ===\n'); - - // Dynamic imports — these are optional peer dependencies - const [{ openai }, { generateText, stepCountIs }] = await Promise.all([ - import('@ai-sdk/openai'), - import('ai'), - ]); - - const toolset = new StackOneToolSet({ - apiKey, - accountId, - search: { method: 'semantic', topK: 3 }, - timeout: 120_000, // increase for slow providers (default: 60s) - }); - - // getTools() returns tool_search + tool_execute as a Tools collection - const tools = toolset.getTools({ accountIds: [accountId as string] }); - console.log(' Tools provided to model: tool_search, tool_execute'); - - const { text, steps } = await generateText({ - model: openai('gpt-5.1'), - tools: await tools.toAISDK(), - prompt: 'List employees and return a short summary.', - stopWhen: stepCountIs(5), - }); - - console.log(` Model completed in ${steps.length} step(s)`); - console.log(` Response: ${text.slice(0, 200)}${text.length > 200 ? '...' : ''}`); -} - -// --------------------------------------------------------------------------- -// Main — run each section in order -// --------------------------------------------------------------------------- -async function main(): Promise { - await directFetch(); - await semanticSearch(); - await localSearch(); - await autoSearchWithCallable(); - - // Section 5 requires @ai-sdk/openai and ai packages + an OPENAI_API_KEY. - // Skip gracefully if not available. - try { - await searchAndExecute(); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - if (message.includes('Cannot find module') || message.includes('Cannot find package')) { - console.log('\n=== 5. Search & Execute (Vercel AI SDK) ===\n'); - console.log(' Skipped: install @ai-sdk/openai and ai to run this section.'); - } else { - throw error; - } - } -} - -await main(); diff --git a/package.json b/package.json index 435f649f..7e5d25c6 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,6 @@ }, "dependencies": { "@modelcontextprotocol/sdk": "catalog:prod", - "@orama/orama": "catalog:prod", "defu": "catalog:prod" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f69b367d..8d177fca 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -81,9 +81,6 @@ catalogs: '@modelcontextprotocol/sdk': specifier: ^1.24.3 version: 1.24.3 - '@orama/orama': - specifier: ^3.1.11 - version: 3.1.16 defu: specifier: ^6.1.4 version: 6.1.4 @@ -101,9 +98,6 @@ importers: '@modelcontextprotocol/sdk': specifier: catalog:prod version: 1.24.3(zod@4.3.5) - '@orama/orama': - specifier: catalog:prod - version: 3.1.16 defu: specifier: catalog:prod version: 6.1.4 @@ -134,7 +128,7 @@ importers: version: 2.12.3(@types/node@22.19.1)(typescript@5.9.3) node: specifier: runtime:^24.11.0 - version: runtime:24.13.0 + version: runtime:24.21.0 openai: specifier: catalog:peer version: 6.9.1(zod@4.3.5) @@ -198,7 +192,7 @@ importers: version: 2.12.3(@types/node@22.19.1)(typescript@5.9.3) node: specifier: runtime:^24.11.0 - version: runtime:24.13.0 + version: runtime:24.21.0 packages: @@ -792,10 +786,6 @@ packages: resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==} engines: {node: '>=8.0.0'} - '@orama/orama@3.1.16': - resolution: {integrity: sha512-scSmQBD8eANlMUOglxHrN1JdSW8tDghsPuS83otqealBiIeMukCQMOf/wc0JJjDXomqwNdEQFLXLGHrU6PGxuA==} - engines: {node: '>= 20.0.0'} - '@oxc-project/types@0.101.0': resolution: {integrity: sha512-nuFhqlUzJX+gVIPPfuE6xurd4lST3mdcWOhyK/rZO0B9XWMKm79SuszIQEnSMmmDhq1DC8WWVYGVd+6F93o1gQ==} @@ -1757,94 +1747,103 @@ packages: resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==} engines: {node: '>= 0.6'} - node@runtime:24.13.0: + node@runtime:24.21.0: resolution: type: variations variants: - resolution: archive: tarball bin: bin/node - integrity: sha256-rCHprwik1UsFfYAMA7yVMilGlSuNqoEcramL+2aozo8= + integrity: sha256-rseyRkr7mfB4wZywbSAdVDvTsxHLoHEoK84bF8l+WLs= type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-aix-ppc64.tar.gz + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-aix-ppc64.tar.gz targets: - cpu: ppc64 os: aix - resolution: archive: tarball bin: bin/node - integrity: sha256-1ZWWHlY/yuBX1KD7mS8XWlTZf8xKFNwtR02S3e6jufg= + integrity: sha256-vtfupTJeEQjzLOUijd1qXw8IpJnuQqp0Qq6lg3AvYFc= type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-darwin-arm64.tar.gz + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-darwin-arm64.tar.gz targets: - cpu: arm64 os: darwin - resolution: archive: tarball bin: bin/node - integrity: sha256-bwPBtI3b4bEppvgDi+COCJnwXxcYW00+Q1AYCrZpp/M= + integrity: sha256-FGLLOzBGuBXPjqQ209pFDsGp8R2sflpGsK2lMF1+gJc= type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-darwin-x64.tar.gz + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-darwin-x64.tar.gz targets: - cpu: x64 os: darwin - resolution: archive: tarball bin: bin/node - integrity: sha256-D21AuUxqLra0wkD/yLn9Otp6sETBd91BPAbh75pj8IE= + integrity: sha256-ckKCw7Q67JmKqVJzgEZbRdIp4CG1gDX19PYwleq/5dU= type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-linux-arm64.tar.gz + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-linux-arm64.tar.gz targets: - cpu: arm64 os: linux - resolution: archive: tarball bin: bin/node - integrity: sha256-GAEZMLGCocW0nSMmGR/bpYJwvfe0W4x9+FXvMZMbFIo= + integrity: sha256-UcXVMGbukpILYXg7A7Buy5nzZhFg97Fcp36EdBFaZ7w= type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-linux-ppc64le.tar.gz + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-linux-ppc64le.tar.gz targets: - cpu: ppc64le os: linux - resolution: archive: tarball bin: bin/node - integrity: sha256-V0RhC2JPLoKuHKJ52OznuMpGZDcjlTPS0DNWUwO8HTk= + integrity: sha256-Xy+jdCLgx13jXBaG/lHXgyTywqj+LMI5pB2cAAop2Tg= type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-linux-s390x.tar.gz + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-linux-s390x.tar.gz targets: - cpu: s390x os: linux - resolution: archive: tarball bin: bin/node - integrity: sha256-YiOq0agfnR57aCxZ0S4t4jP3tMN0dc1A0cicQrc3/6g= + integrity: sha256-PWNAX8ZaDS0pdsHwvC/Se7C9ByEkaecFqsPwOuWrTJw= type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-linux-x64.tar.gz + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-linux-x64-musl.tar.gz + targets: + - cpu: x64-musl + os: linux + - resolution: + archive: tarball + bin: bin/node + integrity: sha256-bh24fvWLiBnl1UAu/xU2SRsY7djre+5e94l4duiNxf8= + type: binary + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-linux-x64.tar.gz targets: - cpu: x64 os: linux - resolution: archive: zip bin: node.exe - integrity: sha256-krn5sMDBI+EeSvxTXw7BnNmHRl7qUGQnVTpJlxNkFYo= - prefix: node-v24.13.0-win-arm64 + integrity: sha256-h3mxveHTn41CDjtXqmV7OYka9DTT3kSpGQRM7AZ4WSE= + prefix: node-v24.21.0-win-arm64 type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-win-arm64.zip + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-win-arm64.zip targets: - cpu: arm64 os: win32 - resolution: archive: zip bin: node.exe - integrity: sha256-yidCaVvo3kQCfXGz9TpL2zYAm5VXX+Gub38LXOCRy4g= - prefix: node-v24.13.0-win-x64 + integrity: sha256-FY92hbRN5R9sDfHRU1JsvNPhvHOajfxgdyHO913p5UE= + prefix: node-v24.21.0-win-x64 type: binary - url: https://nodejs.org/download/release/v24.13.0/node-v24.13.0-win-x64.zip + url: https://nodejs.org/download/release/v24.21.0/node-v24.21.0-win-x64.zip targets: - cpu: x64 os: win32 - version: 24.13.0 + version: 24.21.0 hasBin: true object-assign@4.1.1: @@ -2798,8 +2797,6 @@ snapshots: '@opentelemetry/api@1.9.0': optional: true - '@orama/orama@3.1.16': {} - '@oxc-project/types@0.101.0': {} '@oxc-resolver/binding-android-arm-eabi@11.15.0': @@ -3654,7 +3651,7 @@ snapshots: negotiator@1.0.0: {} - node@runtime:24.13.0: {} + node@runtime:24.21.0: {} object-assign@4.1.1: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 800bccc4..6f602476 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -34,7 +34,6 @@ catalogs: zod: '>=3.25.0 <5' prod: '@modelcontextprotocol/sdk': ^1.24.3 - '@orama/orama': ^3.1.11 defu: ^6.1.4 enablePrePostScripts: true diff --git a/src/agent-tools.test.ts b/src/agent-tools.test.ts deleted file mode 100644 index 0695c5aa..00000000 --- a/src/agent-tools.test.ts +++ /dev/null @@ -1,384 +0,0 @@ -import { createExecuteTool, createSearchTool } from './toolsets'; -import { BaseTool, Tools } from './tool'; -import type { ToolParameters } from './types'; -import { StackOneAPIError } from './utils/error-stackone-api'; - -// --- Helpers --- - -function createMockToolset(options?: { searchResults?: BaseTool[]; fetchResults?: BaseTool[] }): { - toolset: { - searchTools: ReturnType; - fetchTools: ReturnType; - getSearchConfig: ReturnType; - }; -} { - const mockTool = new BaseTool( - 'test_tool', - 'A test tool', - { - type: 'object', - properties: { - id: { type: 'string', description: 'The ID' }, - count: { type: 'integer', description: 'A count' }, - }, - } satisfies ToolParameters, - { kind: 'local', identifier: 'test:mock' }, - ); - - const tools = new Tools(options?.searchResults ?? [mockTool]); - const fetchTools = new Tools(options?.fetchResults ?? [mockTool]); - - return { - toolset: { - searchTools: vi.fn().mockResolvedValue(tools), - fetchTools: vi.fn().mockResolvedValue(fetchTools), - getSearchConfig: vi.fn().mockReturnValue({ method: 'auto' }), - }, - }; -} - -// --- Tests --- - -describe('createSearchTool', () => { - it('returns a BaseTool named tool_search', () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never); - expect(tool).toBeInstanceOf(BaseTool); - expect(tool.name).toBe('tool_search'); - }); - - it('delegates to toolset.searchTools', async () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never); - - await tool.execute({ query: 'find employees' }); - - expect(toolset.searchTools).toHaveBeenCalledOnce(); - expect(toolset.searchTools).toHaveBeenCalledWith('find employees', expect.any(Object)); - }); - - it('returns tool names, descriptions, and parameter properties', async () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never); - - const result = await tool.execute({ query: 'test' }); - - expect(result.total).toBe(1); - const tools = result.tools as Array<{ - name: string; - description: string; - parameters: Record; - }>; - expect(tools[0].name).toBe('test_tool'); - expect(tools[0].description).toBe('A test tool'); - expect(tools[0].parameters).toHaveProperty('id'); - }); - - it('passes accountIds to searchTools', async () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never, ['acc-1']); - - await tool.execute({ query: 'test' }); - - const callOpts = toolset.searchTools.mock.calls[0][1]; - expect(callOpts.accountIds).toEqual(['acc-1']); - }); - - it('does not hardcode topK fallback — lets searchTools default', async () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never); - - await tool.execute({ query: 'test' }); - - const callOpts = toolset.searchTools.mock.calls[0][1]; - expect(callOpts.topK).toBeUndefined(); - }); - - it('accepts string JSON arguments', async () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never); - - const result = await tool.execute(JSON.stringify({ query: 'employees' })); - - expect(result).toHaveProperty('tools'); - expect(toolset.searchTools).toHaveBeenCalledOnce(); - }); - - it('returns error dict on invalid JSON', async () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never); - - const result = await tool.execute('not valid json'); - - expect(result).toHaveProperty('error'); - expect(toolset.searchTools).not.toHaveBeenCalled(); - }); - - it('returns error dict on validation failure', async () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never); - - const result = await tool.execute({ query: '' }); - - expect(result).toHaveProperty('error'); - expect(toolset.searchTools).not.toHaveBeenCalled(); - }); - - it('returns error dict on missing query', async () => { - const { toolset } = createMockToolset(); - const tool = createSearchTool(toolset as never); - - const result = await tool.execute({}); - - expect(result).toHaveProperty('error'); - }); -}); - -describe('createExecuteTool', () => { - it('returns a BaseTool named tool_execute', () => { - const { toolset } = createMockToolset(); - const tool = createExecuteTool(toolset as never); - expect(tool).toBeInstanceOf(BaseTool); - expect(tool.name).toBe('tool_execute'); - }); - - it('delegates to fetchTools and executes the target tool', async () => { - const executeMock = vi.fn().mockResolvedValue({ result: 'ok' }); - const mockTarget = new BaseTool( - 'test_tool', - 'Test', - { type: 'object', properties: {} }, - { kind: 'local', identifier: 'test:target' }, - ); - mockTarget.execute = executeMock; - - const { toolset } = createMockToolset({ fetchResults: [mockTarget] }); - const tool = createExecuteTool(toolset as never); - - const result = await tool.execute({ tool_name: 'test_tool', parameters: { id: '123' } }); - - expect(result).toEqual({ result: 'ok' }); - expect(executeMock).toHaveBeenCalledOnce(); - }); - - it('returns error when tool not found', async () => { - const { toolset } = createMockToolset(); - const tool = createExecuteTool(toolset as never); - - const result = await tool.execute({ tool_name: 'nonexistent_tool' }); - - expect(result).toHaveProperty('error'); - expect(result.error as string).toContain('not found'); - }); - - it('returns API errors as error dict with response_body', async () => { - const mockTarget = new BaseTool( - 'test_tool', - 'Test', - { type: 'object', properties: {} }, - { kind: 'local', identifier: 'test:target' }, - ); - mockTarget.execute = vi - .fn() - .mockRejectedValue(new StackOneAPIError('Bad Request', 400, { message: 'Invalid params' })); - - const { toolset } = createMockToolset({ fetchResults: [mockTarget] }); - const tool = createExecuteTool(toolset as never); - - const result = await tool.execute({ tool_name: 'test_tool', parameters: {} }); - - expect(result).toHaveProperty('error'); - expect(result.status_code).toBe(400); - expect(result.tool_name).toBe('test_tool'); - expect(result.response_body).toEqual({ message: 'Invalid params' }); - }); - - it('returns error dict on invalid JSON', async () => { - const { toolset } = createMockToolset(); - const tool = createExecuteTool(toolset as never); - - const result = await tool.execute('not valid json'); - - expect(result).toHaveProperty('error'); - }); - - it('returns error dict on validation failure', async () => { - const { toolset } = createMockToolset(); - const tool = createExecuteTool(toolset as never); - - const result = await tool.execute({ tool_name: '' }); - - expect(result).toHaveProperty('error'); - }); - - it('caches fetchTools calls', async () => { - const mockTarget = new BaseTool( - 'test_tool', - 'Test', - { type: 'object', properties: {} }, - { kind: 'local', identifier: 'test:target' }, - ); - mockTarget.execute = vi.fn().mockResolvedValue({ ok: true }); - - const { toolset } = createMockToolset({ fetchResults: [mockTarget] }); - const tool = createExecuteTool(toolset as never); - - await tool.execute({ tool_name: 'test_tool' }); - await tool.execute({ tool_name: 'test_tool' }); - - expect(toolset.fetchTools).toHaveBeenCalledOnce(); - }); - - it('passes accountIds to fetchTools', async () => { - const mockTarget = new BaseTool( - 'test_tool', - 'Test', - { type: 'object', properties: {} }, - { kind: 'local', identifier: 'test:target' }, - ); - mockTarget.execute = vi.fn().mockResolvedValue({ ok: true }); - - const { toolset } = createMockToolset({ fetchResults: [mockTarget] }); - const tool = createExecuteTool(toolset as never, ['acc-1']); - - await tool.execute({ tool_name: 'test_tool' }); - - expect(toolset.fetchTools).toHaveBeenCalledWith({ accountIds: ['acc-1'] }); - }); - - it('accepts string JSON arguments', async () => { - const mockTarget = new BaseTool( - 'test_tool', - 'Test', - { type: 'object', properties: {} }, - { kind: 'local', identifier: 'test:target' }, - ); - mockTarget.execute = vi.fn().mockResolvedValue({ ok: true }); - - const { toolset } = createMockToolset({ fetchResults: [mockTarget] }); - const tool = createExecuteTool(toolset as never); - - const result = await tool.execute(JSON.stringify({ tool_name: 'test_tool', parameters: {} })); - - expect(result).toEqual({ ok: true }); - }); -}); - -describe('StackOneToolSet.openai()', () => { - function createMockToolSetInstance(options?: { - executeConfig?: { accountIds?: string[] }; - searchConfig?: Record; - }): { - toolset: { - fetchTools: ReturnType; - buildTools: ReturnType; - openai: (opts?: { mode?: 'search_and_execute'; accountIds?: string[] }) => Promise; - }; - } { - const mockTool = new BaseTool( - 'test_tool', - 'A test tool', - { type: 'object', properties: {} } satisfies ToolParameters, - { kind: 'local', identifier: 'test:mock' }, - ); - const tools = new Tools([mockTool]); - - const metaSearchTool = new BaseTool( - 'tool_search', - 'Search for tools', - { type: 'object', properties: { query: { type: 'string' } } } satisfies ToolParameters, - { kind: 'local', identifier: 'meta:search' }, - ); - const metaExecuteTool = new BaseTool( - 'tool_execute', - 'Execute a tool', - { type: 'object', properties: { tool_name: { type: 'string' } } } satisfies ToolParameters, - { kind: 'local', identifier: 'meta:execute' }, - ); - const builtTools = new Tools([metaSearchTool, metaExecuteTool]); - - const fetchTools = vi.fn().mockResolvedValue(tools); - const buildTools = vi.fn().mockReturnValue(builtTools); - - const executeConfig = options?.executeConfig; - - const toolset = { - fetchTools, - buildTools, - async openai(opts?: { - mode?: 'search_and_execute'; - accountIds?: string[]; - }): Promise { - const effectiveAccountIds = opts?.accountIds ?? executeConfig?.accountIds; - - if (opts?.mode === 'search_and_execute') { - return buildTools(effectiveAccountIds).toOpenAI(); - } - - const fetchedTools = await fetchTools({ accountIds: effectiveAccountIds }); - return fetchedTools.toOpenAI(); - }, - }; - - return { toolset }; - } - - it('default fetches all tools', async () => { - const { toolset } = createMockToolSetInstance(); - - const result = await toolset.openai(); - - expect(toolset.fetchTools).toHaveBeenCalledOnce(); - expect(toolset.fetchTools).toHaveBeenCalledWith({ accountIds: undefined }); - expect(result).toHaveLength(1); - expect(result[0]).toHaveProperty('type', 'function'); - }); - - it('search_and_execute returns search and execute tools', async () => { - const { toolset } = createMockToolSetInstance(); - - const result = await toolset.openai({ mode: 'search_and_execute' }); - - expect(toolset.buildTools).toHaveBeenCalledOnce(); - expect(toolset.fetchTools).not.toHaveBeenCalled(); - expect(result).toHaveLength(2); - }); - - it('passes accountIds to fetchTools', async () => { - const { toolset } = createMockToolSetInstance(); - - await toolset.openai({ accountIds: ['acc-1'] }); - - expect(toolset.fetchTools).toHaveBeenCalledWith({ accountIds: ['acc-1'] }); - }); - - it('uses executeConfig.accountIds as fallback', async () => { - const { toolset } = createMockToolSetInstance({ - executeConfig: { accountIds: ['default-acc'] }, - }); - - await toolset.openai(); - - expect(toolset.fetchTools).toHaveBeenCalledWith({ accountIds: ['default-acc'] }); - }); - - it('accountIds overrides executeConfig', async () => { - const { toolset } = createMockToolSetInstance({ - executeConfig: { accountIds: ['default-acc'] }, - }); - - await toolset.openai({ accountIds: ['override-acc'] }); - - expect(toolset.fetchTools).toHaveBeenCalledWith({ accountIds: ['override-acc'] }); - }); - - it('search_and_execute with executeConfig passes accountIds to buildTools', async () => { - const { toolset } = createMockToolSetInstance({ - executeConfig: { accountIds: ['meta-acc'] }, - }); - - await toolset.openai({ mode: 'search_and_execute' }); - - expect(toolset.buildTools).toHaveBeenCalledWith(['meta-acc']); - }); -}); diff --git a/src/consts.ts b/src/consts.ts index 58aad190..0353291b 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -7,14 +7,3 @@ export const USER_AGENT = 'stackone-ai-node'; * Default base URL for StackOne API */ export const DEFAULT_BASE_URL = 'https://api.stackone.com'; - -/** - * Default weight for BM25 in hybrid BM25 + TF-IDF search. - * - * - alpha=0.2 means: 20% BM25 + 80% TF-IDF - * - This value was optimized through validation testing - * - Provides 10.8% improvement in tool discovery accuracy - * - Lower values favor BM25 scoring (better keyword matching) - * - Higher values favor TF-IDF scoring (better semantic matching) - */ -export const DEFAULT_HYBRID_ALPHA = 0.2; diff --git a/src/index.ts b/src/index.ts index fa54c85f..3e63a72b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,7 +9,6 @@ export { StackOneError } from './utils/error-stackone'; export { StackOneAPIError } from './utils/error-stackone-api'; export { - SearchTool, StackOneToolSet, ToolSetConfigError, ToolSetError, @@ -17,20 +16,9 @@ export { type AuthenticationConfig, type BaseToolSetConfig, type ExecuteToolsConfig, - type SearchMode, - type SearchToolsOptions, - type SearchActionNamesOptions, type StackOneToolSetConfig, } from './toolsets'; -export { - SemanticSearchClient, - SemanticSearchError, - type SemanticSearchOptions, - type SemanticSearchResponse, - type SemanticSearchResult, -} from './semantic-search'; - export { DEFAULT_DEFENDER_CONFIG } from './types'; export type { @@ -43,6 +31,5 @@ export type { JsonObject, JsonValue, ParameterLocation, - SearchConfig, ToolDefinition, } from './types'; diff --git a/src/local-search.test.ts b/src/local-search.test.ts deleted file mode 100644 index d66852b7..00000000 --- a/src/local-search.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -import { ToolIndex } from './local-search'; -import { BaseTool } from './tool'; - -function createMockTools(): BaseTool[] { - return [ - new BaseTool( - 'bamboohr_create_employee', - 'Create a new employee record in the HRIS system', - { type: 'object', properties: {} }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/hris/employees', - bodyType: 'json', - params: [], - }, - ), - new BaseTool( - 'bamboohr_list_employees', - 'List all employees in the HRIS system', - { type: 'object', properties: {} }, - { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/hris/employees', - bodyType: 'json', - params: [], - }, - ), - new BaseTool( - 'bamboohr_create_time_off', - 'Create a time off request for an employee', - { type: 'object', properties: {} }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/hris/time-off', - bodyType: 'json', - params: [], - }, - ), - new BaseTool( - 'workday_create_candidate', - 'Create a new candidate in the ATS', - { type: 'object', properties: {} }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/ats/candidates', - bodyType: 'json', - params: [], - }, - ), - new BaseTool( - 'workday_list_candidates', - 'List all candidates in the ATS', - { type: 'object', properties: {} }, - { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/ats/candidates', - bodyType: 'json', - params: [], - }, - ), - new BaseTool( - 'salesforce_create_contact', - 'Create a new contact in the CRM', - { type: 'object', properties: {} }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/crm/contacts', - bodyType: 'json', - params: [], - }, - ), - ]; -} - -describe('ToolIndex', () => { - describe('search', () => { - it('should find relevant employee tools', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools); - const results = await index.search('manage employees'); - - const resultNames = results.map((r) => r.name); - expect(resultNames).toContain('bamboohr_create_employee'); - expect(resultNames).toContain('bamboohr_list_employees'); - }); - - it('should find time off tools', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools); - const results = await index.search('time off request vacation leave'); - - const resultNames = results.map((r) => r.name); - expect(resultNames).toContain('bamboohr_create_time_off'); - }); - - it('should respect limit parameter', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools); - const results = await index.search('create', 2); - - expect(results.length).toBeLessThanOrEqual(2); - }); - - it('should filter by minimum score', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools); - const results = await index.search('xyz123 nonexistent', 5, 0.8); - - expect(results).toHaveLength(0); - }); - - it('should return scores between 0 and 1', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools); - const results = await index.search('employee', 10); - - for (const result of results) { - expect(result.score).toBeGreaterThanOrEqual(0); - expect(result.score).toBeLessThanOrEqual(1); - } - }); - - it('should find candidate tools', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools); - const results = await index.search('candidates'); - - const resultNames = results.map((r) => r.name); - const hasCandidateTool = - resultNames.includes('workday_create_candidate') || - resultNames.includes('workday_list_candidates'); - expect(hasCandidateTool).toBe(true); - }); - - it('should handle empty query', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools); - const results = await index.search('', 5); - - expect(Array.isArray(results)).toBe(true); - }); - }); - - describe('custom alpha', () => { - it('should work with custom alpha value', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools, 0.7); - const results = await index.search('create candidate'); - - const resultNames = results.map((r) => r.name); - expect(resultNames).toContain('workday_create_candidate'); - }); - - it('should work with alpha=0 (TF-IDF only)', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools, 0); - const results = await index.search('employee'); - - expect(results.length).toBeGreaterThan(0); - }); - - it('should work with alpha=1 (BM25 only)', async () => { - const tools = createMockTools(); - const index = new ToolIndex(tools, 1); - const results = await index.search('employee'); - - expect(results.length).toBeGreaterThan(0); - }); - }); -}); diff --git a/src/local-search.ts b/src/local-search.ts deleted file mode 100644 index 9c5e1ffd..00000000 --- a/src/local-search.ts +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Local BM25 + TF-IDF hybrid keyword search for tool discovery. - * - * Provides offline tool search as a fallback when the semantic search API - * is unavailable, or when explicitly requested via `search: "local"`. - * - * Algorithm: - * - BM25 scoring via Orama library - * - TF-IDF cosine similarity via custom TfidfIndex - * - Hybrid fusion: `alpha * bm25 + (1 - alpha) * tfidf` - * - Default alpha = 0.2 (20% BM25, 80% TF-IDF) - */ - -import * as orama from '@orama/orama'; -import { DEFAULT_HYBRID_ALPHA } from './consts'; -import type { BaseTool } from './tool'; -import { TfidfIndex } from './utils/tfidf-index'; - -/** - * Result from local tool search - */ -interface ToolSearchResult { - name: string; - description: string; - score: number; -} - -type OramaDb = ReturnType; - -/** - * Clamp value to [0, 1] - */ -function clamp01(x: number): number { - return x < 0 ? 0 : x > 1 ? 1 : x; -} - -/** - * Initialize TF-IDF index for tool search - */ -function initializeTfidfIndex(tools: BaseTool[]): TfidfIndex { - const index = new TfidfIndex(); - const corpus = tools.map((tool) => { - const parts = tool.name.split('_'); - const integration = parts[0]; - - const actionTypes = ['create', 'update', 'delete', 'get', 'list', 'search']; - const actions = parts.filter((p) => actionTypes.includes(p)); - - const text = [ - `${tool.name} ${tool.name} ${tool.name}`, // boost name - `${integration} ${actions.join(' ')}`, - tool.description, - parts.join(' '), - ].join(' '); - - return { id: tool.name, text }; - }); - - index.build(corpus); - return index; -} - -/** - * Initialize Orama database with BM25 algorithm for tool search - * @see https://docs.orama.com/open-source/usage/create - * @see https://docs.orama.com/open-source/usage/search/bm25-algorithm/ - */ -async function initializeOramaDb(tools: BaseTool[]): Promise { - const oramaDb = orama.create({ - schema: { - name: 'string' as const, - description: 'string' as const, - integration: 'string' as const, - tags: 'string[]' as const, - }, - components: { - tokenizer: { - stemming: true, - }, - }, - }); - - for (const tool of tools) { - const parts = tool.name.split('_'); - const integration = parts[0]; - - const actionTypes = ['create', 'update', 'delete', 'get', 'list', 'search']; - const actions = parts.filter((p) => actionTypes.includes(p)); - - await orama.insert(oramaDb, { - name: tool.name, - description: tool.description, - integration: integration, - tags: [...parts, ...actions], - }); - } - - return oramaDb; -} - -/** - * Hybrid BM25 + TF-IDF tool search index. - * - * Provides local tool discovery without API calls. - * Used as a fallback when semantic search is unavailable. - */ -export class ToolIndex { - private tools: BaseTool[]; - private hybridAlpha: number; - private oramaDbPromise: Promise; - private tfidfIndex: TfidfIndex; - - /** - * Initialize tool index with hybrid search - * - * @param tools - List of tools to index - * @param hybridAlpha - Weight for BM25 in hybrid search (0-1). Default 0.2. - */ - constructor(tools: BaseTool[], hybridAlpha?: number) { - this.tools = tools; - const alpha = hybridAlpha ?? DEFAULT_HYBRID_ALPHA; - this.hybridAlpha = Math.max(0, Math.min(1, alpha)); - this.oramaDbPromise = initializeOramaDb(tools); - this.tfidfIndex = initializeTfidfIndex(tools); - } - - /** - * Search for relevant tools using hybrid BM25 + TF-IDF - * - * @param query - Natural language query - * @param limit - Maximum number of results (default 5) - * @param minScore - Minimum relevance score 0-1 (default 0.0) - * @returns List of search results sorted by relevance - */ - async search(query: string, limit = 5, minScore = 0.0): Promise { - if (this.tools.length === 0) { - return []; - } - - const fetchLimit = Math.max(50, limit); - const oramaDb = await this.oramaDbPromise; - - const [bm25Results, tfidfResults] = await Promise.all([ - orama.search(oramaDb, { - term: query, - limit: Math.max(50, limit), - } as Parameters[1]), - Promise.resolve(this.tfidfIndex.search(query, fetchLimit)), - ]); - - // Build score map for fusion - const scoreMap = new Map(); - - for (const hit of bm25Results.hits) { - const doc = hit.document as { name: string }; - scoreMap.set(doc.name, { - ...scoreMap.get(doc.name), - bm25: clamp01(hit.score), - }); - } - - for (const r of tfidfResults) { - scoreMap.set(r.id, { - ...scoreMap.get(r.id), - tfidf: clamp01(r.score), - }); - } - - // Fuse scores: hybrid_score = alpha * bm25 + (1 - alpha) * tfidf - const fused: Array<{ name: string; score: number }> = []; - for (const [name, scores] of scoreMap) { - const bm25 = scores.bm25 ?? 0; - const tfidf = scores.tfidf ?? 0; - const score = this.hybridAlpha * bm25 + (1 - this.hybridAlpha) * tfidf; - fused.push({ name, score }); - } - - fused.sort((a, b) => b.score - a.score); - - const results: ToolSearchResult[] = []; - for (const r of fused) { - if (r.score < minScore) { - continue; - } - - const tool = this.tools.find((t) => t.name === r.name); - if (!tool) { - continue; - } - - results.push({ - name: tool.name, - description: tool.description, - score: r.score, - }); - - if (results.length >= limit) { - break; - } - } - - return results; - } -} diff --git a/src/semantic-search.test.ts b/src/semantic-search.test.ts deleted file mode 100644 index 25a62fca..00000000 --- a/src/semantic-search.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { http, HttpResponse } from 'msw'; -import { setupServer } from 'msw/node'; -import { SemanticSearchClient, SemanticSearchError } from './semantic-search'; - -const server = setupServer(); - -beforeAll(() => server.listen()); -afterEach(() => server.resetHandlers()); -afterAll(() => server.close()); - -const TEST_API_KEY = 'test-api-key'; -const TEST_BASE_URL = 'http://localhost'; - -function createClient(options?: { baseUrl?: string; timeout?: number }): SemanticSearchClient { - return new SemanticSearchClient({ - apiKey: TEST_API_KEY, - baseUrl: options?.baseUrl ?? TEST_BASE_URL, - timeout: options?.timeout, - }); -} - -describe('SemanticSearchClient', () => { - describe('search', () => { - test('returns parsed search results', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, async ({ request }) => { - const body = (await request.json()) as Record; - expect(body.query).toBe('create employee'); - expect(body.connector).toBe('bamboohr'); - expect(body.top_k).toBe(5); - - return HttpResponse.json({ - results: [ - { - id: 'bamboohr_1.0.0_bamboohr_create_employee_global', - similarity_score: 0.95, - }, - { - id: 'bamboohr_1.0.0_bamboohr_update_employee_global', - similarity_score: 0.82, - }, - ], - total_count: 2, - query: 'create employee', - connector_filter: 'bamboohr', - }); - }), - ); - - const client = createClient(); - const response = await client.search('create employee', { - connector: 'bamboohr', - topK: 5, - }); - - expect(response.results).toHaveLength(2); - expect(response.results[0].id).toBe('bamboohr_1.0.0_bamboohr_create_employee_global'); - expect(response.results[0].similarityScore).toBe(0.95); - expect(response.totalCount).toBe(2); - expect(response.query).toBe('create employee'); - expect(response.connectorFilter).toBe('bamboohr'); - }); - - test('sends correct auth header', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, ({ request }) => { - const auth = request.headers.get('Authorization'); - const expected = `Basic ${Buffer.from(`${TEST_API_KEY}:`).toString('base64')}`; - expect(auth).toBe(expected); - - return HttpResponse.json({ - results: [], - total_count: 0, - query: 'test', - }); - }), - ); - - const client = createClient(); - await client.search('test'); - }); - - test('sends optional parameters only when provided', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, async ({ request }) => { - const body = (await request.json()) as Record; - expect(body.query).toBe('test'); - expect(body).not.toHaveProperty('connector'); - expect(body).not.toHaveProperty('top_k'); - expect(body).not.toHaveProperty('project_id'); - expect(body).not.toHaveProperty('min_similarity'); - - return HttpResponse.json({ - results: [], - total_count: 0, - query: 'test', - }); - }), - ); - - const client = createClient(); - await client.search('test'); - }); - - test('sends min_similarity when provided', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, async ({ request }) => { - const body = (await request.json()) as Record; - expect(body.min_similarity).toBe(0.7); - - return HttpResponse.json({ - results: [], - total_count: 0, - query: 'test', - }); - }), - ); - - const client = createClient(); - await client.search('test', { minSimilarity: 0.7 }); - }); - - test('throws SemanticSearchError on HTTP error', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return new HttpResponse('Internal Server Error', { status: 500 }); - }), - ); - - const client = createClient(); - await expect(client.search('test')).rejects.toThrow(SemanticSearchError); - await expect(client.search('test')).rejects.toThrow('API error: 500'); - }); - - test('throws SemanticSearchError on network error', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return HttpResponse.error(); - }), - ); - - const client = createClient(); - await expect(client.search('test')).rejects.toThrow(SemanticSearchError); - }); - - test('strips trailing slashes from base URL', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return HttpResponse.json({ - results: [], - total_count: 0, - query: 'test', - }); - }), - ); - - const client = createClient({ baseUrl: `${TEST_BASE_URL}///` }); - const response = await client.search('test'); - expect(response.totalCount).toBe(0); - }); - }); - - describe('searchActionNames', () => { - test('returns just action IDs', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return HttpResponse.json({ - results: [ - { - id: 'bamboohr_1.0.0_bamboohr_create_employee_global', - similarity_score: 0.95, - }, - { - id: 'hibob_1.0.0_hibob_create_employee_global', - similarity_score: 0.88, - }, - ], - total_count: 2, - query: 'create employee', - }); - }), - ); - - const client = createClient(); - const names = await client.searchActionNames('create employee'); - expect(names).toEqual([ - 'bamboohr_1.0.0_bamboohr_create_employee_global', - 'hibob_1.0.0_hibob_create_employee_global', - ]); - }); - }); -}); diff --git a/src/semantic-search.ts b/src/semantic-search.ts deleted file mode 100644 index 2c861eb8..00000000 --- a/src/semantic-search.ts +++ /dev/null @@ -1,244 +0,0 @@ -/** - * Semantic search client for StackOne action search API. - * - * How Semantic Search Works - * ========================= - * - * The SDK provides three ways to discover tools using semantic search. - * Each path trades off between speed, filtering, and completeness. - * - * 1. `searchTools(query)` — Full tool discovery (recommended for agent frameworks) - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * This is the primary method used when integrating with OpenAI, Anthropic, or AI SDK. - * The internal flow is: - * - * 1. Fetch tools from linked accounts via MCP (provides connectors and tool schemas) - * 2. Search EACH connector in parallel via the semantic search API (/actions/search) - * 3. Match search results to MCP tool definitions - * 4. Deduplicate, sort by relevance score, apply topK - * 5. Return Tools sorted by relevance score - * - * Key point: only the user's own connectors are searched — no wasted results - * from connectors the user doesn't have. Tool schemas come from MCP (source - * of truth), while the search API provides relevance ranking. - * - * If the semantic API is unavailable, the SDK falls back to a local - * BM25 + TF-IDF hybrid search over the fetched tools (unless - * `search: "semantic"` is specified). - * - * - * 2. `searchActionNames(query)` — Lightweight discovery - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * Queries the semantic API directly and returns action IDs with - * similarity scores, **without** building full tool objects. Useful - * for previewing results before committing to a full fetch. - * - * When `accountIds` are provided, each connector is searched in - * parallel (same as `searchTools`). Without `accountIds`, results - * come from the full StackOne catalog. - * - * - * 3. `toolset.getSearchTool()` — Agent-loop callable - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * Returns a `SearchTool` instance that wraps `searchTools()`. - * Call it with a natural language query to get a `Tools` collection - * back. Designed for agent loops where the LLM decides what to search for. - */ - -import { DEFAULT_BASE_URL } from './consts'; -import { StackOneError } from './utils/error-stackone'; - -/** - * Raised when semantic search fails. - */ -export class SemanticSearchError extends StackOneError { - constructor(message: string, options?: ErrorOptions) { - super(message, options); - this.name = 'SemanticSearchError'; - } -} - -/** - * Single result from semantic search API. - */ -export interface SemanticSearchResult { - id: string; - similarityScore: number; -} - -/** - * Response from /actions/search endpoint. - */ -export interface SemanticSearchResponse { - results: SemanticSearchResult[]; - totalCount: number; - query: string; - connectorFilter?: string; - projectFilter?: string; -} - -/** - * Options for semantic search - */ -export interface SemanticSearchOptions { - connector?: string; - topK?: number; - projectId?: string; - minSimilarity?: number; -} - -/** - * Client for StackOne semantic search API. - * - * This client provides access to the semantic search endpoint which uses - * enhanced embeddings for higher accuracy than local BM25+TF-IDF search. - * - * @example - * ```typescript - * const client = new SemanticSearchClient({ apiKey: 'sk-xxx' }); - * const response = await client.search('create employee', { connector: 'bamboohr', topK: 5 }); - * for (const result of response.results) { - * console.log(`${result.id}: ${result.similarityScore.toFixed(2)}`); - * } - * ``` - */ -export class SemanticSearchClient { - private readonly apiKey: string; - private readonly baseUrl: string; - private readonly timeout: number; - - constructor({ - apiKey, - baseUrl = DEFAULT_BASE_URL, - timeout = 30_000, - }: { - apiKey: string; - baseUrl?: string; - timeout?: number; - }) { - this.apiKey = apiKey; - this.baseUrl = baseUrl.replace(/\/+$/, ''); - this.timeout = timeout; - } - - /** - * Build the Basic auth header. - */ - private buildAuthHeader(): string { - const token = Buffer.from(`${this.apiKey}:`).toString('base64'); - return `Basic ${token}`; - } - - /** - * Search for relevant actions using semantic search. - * - * @param query - Natural language query describing what tools/actions you need - * @param options - Search options (connector, topK, projectId, minSimilarity) - * @returns SemanticSearchResponse containing matching actions with similarity scores - * @throws SemanticSearchError if the API call fails - * - * @example - * ```typescript - * const response = await client.search('onboard a new team member', { topK: 5 }); - * for (const result of response.results) { - * console.log(`${result.id}: ${result.similarityScore.toFixed(2)}`); - * } - * ``` - */ - async search(query: string, options?: SemanticSearchOptions): Promise { - const url = `${this.baseUrl}/actions/search`; - const headers: Record = { - Authorization: this.buildAuthHeader(), - 'Content-Type': 'application/json', - }; - - const payload: Record = { query }; - if (options?.topK != null) { - payload.top_k = options.topK; - } - if (options?.connector) { - payload.connector = options.connector; - } - if (options?.projectId) { - payload.project_id = options.projectId; - } - if (options?.minSimilarity != null) { - payload.min_similarity = options.minSimilarity; - } - - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.timeout); - - try { - const response = await fetch(url, { - method: 'POST', - headers, - body: JSON.stringify(payload), - signal: controller.signal, - }); - - if (!response.ok) { - const text = await response.text(); - throw new SemanticSearchError(`API error: ${response.status} - ${text}`); - } - - const data = (await response.json()) as { - results: Array<{ - id: string; - similarity_score: number; - }>; - total_count: number; - query: string; - connector_filter?: string; - project_filter?: string; - }; - - return { - results: data.results.map((r) => ({ - id: r.id, - similarityScore: r.similarity_score, - })), - totalCount: data.total_count, - query: data.query, - connectorFilter: data.connector_filter, - projectFilter: data.project_filter, - }; - } catch (error) { - if (error instanceof SemanticSearchError) { - throw error; - } - if (error instanceof Error && error.name === 'AbortError') { - throw new SemanticSearchError(`Request timed out after ${this.timeout}ms`); - } - throw new SemanticSearchError( - `Search failed: ${error instanceof Error ? error.message : String(error)}`, - { cause: error }, - ); - } finally { - clearTimeout(timeoutId); - } - } - - /** - * Convenience method returning just action names. - * - * @param query - Natural language query - * @param options - Search options (connector, topK, minSimilarity, projectId) - * @returns List of action names sorted by relevance - * - * @example - * ```typescript - * const actionNames = await client.searchActionNames('create employee', { - * connector: 'bamboohr', - * minSimilarity: 0.5, - * }); - * ``` - */ - async searchActionNames(query: string, options?: SemanticSearchOptions): Promise { - const response = await this.search(query, options); - return response.results.map((r) => r.id); - } -} diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 4e5f1b1d..e23016a4 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -11,7 +11,6 @@ import { http, HttpResponse } from 'msw'; import { type McpToolDefinition, createMcpApp, defaultMcpTools } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { TEST_BASE_URL } from '../mocks/constants'; -import { SemanticSearchError } from './semantic-search'; import { SearchTool, StackOneToolSet, @@ -1085,309 +1084,6 @@ describe('StackOneToolSet', () => { }); }); - describe('searchTools', () => { - it('returns tools from semantic search results', async () => { - // Set up MCP with mixed provider tools (hibob, bamboohr, workday) - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - // Mock the semantic search endpoint - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, async ({ request }) => { - const body = (await request.json()) as Record; - expect(body.query).toBe('list employees'); - - return HttpResponse.json({ - results: [ - { - id: 'hibob_1.0.0_hibob_list_employees_global', - similarity_score: 0.95, - }, - { - id: 'bamboohr_1.0.0_bamboohr_list_employees_global', - similarity_score: 0.88, - }, - ], - total_count: 2, - query: 'list employees', - connector_filter: body.connector, - }); - }), - ); - - const tools = await toolset.searchTools('list employees', { topK: 5 }); - const toolNames = tools.toArray().map((t) => t.name); - - expect(toolNames).toContain('hibob_list_employees'); - expect(toolNames).toContain('bamboohr_list_employees'); - }); - - it('falls back to local search in auto mode when semantic fails', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - // Mock semantic search to fail - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return new HttpResponse('Service Unavailable', { status: 503 }); - }), - ); - - // Should fall back to local search without throwing - const tools = await toolset.searchTools('list employees', { - search: 'auto', - topK: 5, - }); - - // Local search should return some results from the mixed provider tools - expect(tools.length).toBeGreaterThan(0); - }); - - it('throws SemanticSearchError in semantic mode when API fails', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - // Mock semantic search to fail - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return new HttpResponse('Internal Server Error', { status: 500 }); - }), - ); - - await expect(toolset.searchTools('list employees', { search: 'semantic' })).rejects.toThrow( - SemanticSearchError, - ); - }); - - it('uses local search mode directly', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - const tools = await toolset.searchTools('list employees', { - search: 'local', - topK: 3, - }); - - // Local search should return results without calling semantic API - expect(tools.length).toBeGreaterThan(0); - const toolNames = tools.toArray().map((t) => t.name); - // Should find employee-related tools - const hasEmployeeTool = toolNames.some((name) => name.includes('employee')); - expect(hasEmployeeTool).toBe(true); - }); - - it('returns empty tools when no connectors available', async () => { - // Use default account (no mixed tools, just default tools without connectors) - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - search: {}, - }); - - // test-account only has dummy_action which has a connector prefix "dummy" - // but semantic search for "list employees" on dummy connector returns nothing useful - - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return HttpResponse.json({ - results: [], - total_count: 0, - query: 'list employees', - }); - }), - ); - - const tools = await toolset.searchTools('list employees'); - // No matching tools from semantic search - expect(tools.length).toBe(0); - }); - - it('auto mode falls back to local search when semantic results do not match MCP tools', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - // Semantic returns results with IDs that won't match any MCP tool names - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return HttpResponse.json({ - results: [ - { - id: 'unknown_1.0.0_nonexistent_action_global', - similarity_score: 0.95, - }, - ], - total_count: 1, - query: 'list employees', - }); - }), - ); - - const tools = await toolset.searchTools('list employees'); - - // Should fall back to local search and return results (not empty) - expect(tools.length).toBeGreaterThan(0); - }); - - it('semantic mode does not fall back when results do not match MCP tools', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - // Semantic returns results with IDs that won't match any MCP tool names - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return HttpResponse.json({ - results: [ - { - id: 'unknown_1.0.0_nonexistent_action_global', - similarity_score: 0.95, - }, - ], - total_count: 1, - query: 'list employees', - }); - }), - ); - - const tools = await toolset.searchTools('list employees', { search: 'semantic' }); - - // Semantic mode should return empty, not fall back - expect(tools.length).toBe(0); - }); - }); - - describe('searchActionNames', () => { - it('returns semantic search results with normalized action names', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return HttpResponse.json({ - results: [ - { - id: 'hibob_1.0.0_hibob_list_employees_global', - similarity_score: 0.95, - }, - ], - total_count: 1, - query: 'list employees', - }); - }), - ); - - const results = await toolset.searchActionNames('list employees'); - - expect(results.length).toBeGreaterThan(0); - expect(results[0].id).toBe('hibob_1.0.0_hibob_list_employees_global'); - }); - - it('returns empty array when semantic search fails', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return new HttpResponse('Internal Server Error', { status: 500 }); - }), - ); - - const results = await toolset.searchActionNames('list employees'); - expect(results).toEqual([]); - }); - }); - - describe('getSearchTool', () => { - it('returns a SearchTool instance', () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - search: {}, - }); - - const searchTool = toolset.getSearchTool(); - expect(searchTool).toBeInstanceOf(SearchTool); - }); - - it('SearchTool.search delegates to searchTools', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return HttpResponse.json({ - results: [ - { - id: 'hibob_1.0.0_hibob_list_employees_global', - similarity_score: 0.95, - }, - ], - total_count: 1, - query: 'list employees', - }); - }), - ); - - const searchTool = toolset.getSearchTool(); - const tools = await searchTool.search('list employees'); - const toolNames = tools.toArray().map((t) => t.name); - - expect(toolNames).toContain('hibob_list_employees'); - }); - - it('uses configured search mode', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); - - // Create search tool with local mode - const searchTool = toolset.getSearchTool({ search: 'local' }); - - // Should not call semantic API at all - const tools = await searchTool.search('list employees', { topK: 3 }); - expect(tools.length).toBeGreaterThan(0); - }); - }); - describe('catalog cache', () => { const installMcpSpy = ( accountTools: Record = { diff --git a/src/toolsets.ts b/src/toolsets.ts index a42d046f..ea8d90d0 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -4,14 +4,8 @@ import { z } from 'zod/v4'; import { DEFAULT_BASE_URL } from './consts'; import { createFeedbackTool } from './feedback'; import { type StackOneHeaders, normalizeHeaders, stackOneHeadersSchema } from './headers'; -import { ToolIndex } from './local-search'; import { createMCPClient } from './mcp-client'; import { type RpcActionResponse, RpcClient } from './rpc-client'; -import { - SemanticSearchClient, - SemanticSearchError, - type SemanticSearchResult, -} from './semantic-search'; import { BaseTool, Tools } from './tool'; import type { DefenderConfig, @@ -21,14 +15,12 @@ import type { JsonSchemaProperties, LocalExecuteConfig, RpcExecuteConfig, - SearchConfig, ToolParameters, } from './types'; import { DEFAULT_DEFENDER_CONFIG } from './types'; import type { BinaryDownloadResult } from './utils/binary-response'; import { StackOneError } from './utils/error-stackone'; import { StackOneAPIError } from './utils/error-stackone-api'; -import { normalizeActionName } from './utils/normalize'; /** * Param-style pinned on the /mcp tool-listing URL. The MCP schema and the RPC-execution @@ -174,18 +166,6 @@ export interface ExecuteToolsConfig { interface StackOneToolSetBaseConfig extends BaseToolSetConfig { apiKey?: string; strict?: boolean; - /** - * Search configuration. Controls default search behavior for `searchTools()`, - * `getSearchTool()`, and `searchActionNames()`. - * - * - Omit or pass `undefined` → search disabled (`null`) - * - Pass `null` → search disabled - * - Pass `{}` or `{ method: 'auto' }` → search enabled with defaults - * - Pass `{ method, topK, minSimilarity }` → search enabled with custom defaults - * - * Per-call options always override these defaults. - */ - search?: SearchConfig | null; /** * Execution configuration. Controls default account scoping for tool execution. * Pass `{ accountIds: ['acc-1'] }` to scope tools to specific accounts. @@ -233,258 +213,6 @@ interface FetchToolsOptions { actions?: string[]; } -/** - * Search mode for tool discovery. - * - * - `"auto"` (default): try semantic search first, fall back to local BM25+TF-IDF if the API is unavailable - * - `"semantic"`: use only the semantic search API; throws SemanticSearchError on failure - * - `"local"`: use only local BM25+TF-IDF search (no API call to the semantic search endpoint) - */ -export type SearchMode = 'auto' | 'semantic' | 'local'; - -/** - * Options for searchTools() and SearchTool - */ -export interface SearchToolsOptions { - /** Optional provider/connector filter (e.g., "bamboohr", "slack") */ - connector?: string; - /** Maximum number of tools to return */ - topK?: number; - /** Minimum similarity score threshold 0-1 */ - minSimilarity?: number; - /** Optional account IDs (uses setAccounts() if not provided) */ - accountIds?: string[]; - /** Search backend to use */ - search?: SearchMode; -} - -/** - * Options for searchActionNames() - */ -export interface SearchActionNamesOptions { - /** Optional provider/connector filter */ - connector?: string; - /** Optional account IDs to scope results */ - accountIds?: string[]; - /** Maximum number of results */ - topK?: number; - /** Minimum similarity score threshold 0-1 */ - minSimilarity?: number; -} - -/** - * Callable search tool that wraps StackOneToolSet.searchTools(). - * - * Designed for agent loops — call `search()` with a query to get Tools back. - * - * @example - * ```typescript - * const toolset = new StackOneToolSet({ apiKey: 'sk-xxx' }); - * const searchTool = toolset.getSearchTool(); - * const tools = await searchTool.search('manage employee records', { accountIds: ['acc-123'] }); - * ``` - */ -export class SearchTool { - private readonly toolset: StackOneToolSet; - private readonly defaultConfig: SearchConfig; - - constructor(toolset: StackOneToolSet, config: SearchConfig = {}) { - this.toolset = toolset; - this.defaultConfig = config; - } - - /** - * Search for tools using natural language. - * - * @param query - Natural language description of needed functionality - * @param options - Search options (connector, topK, minSimilarity, accountIds, search). - * Per-call options override the defaults from the constructor config. - * @returns Tools collection with matched tools - */ - async search(query: string, options?: SearchToolsOptions): Promise { - return this.toolset.searchTools(query, { - ...options, - search: options?.search ?? this.defaultConfig.method, - topK: options?.topK ?? this.defaultConfig.topK, - minSimilarity: options?.minSimilarity ?? this.defaultConfig.minSimilarity, - }); - } -} - -// --- Internal tool_search + tool_execute --- - -const searchInputSchema = z.object({ - query: z - .string() - .transform((v) => v.trim()) - .refine((v) => v.length > 0, { message: 'query must be a non-empty string' }), - connector: z.string().optional(), - top_k: z.number().int().min(1).max(50).optional(), -}); - -const searchParameters = { - type: 'object', - properties: { - query: { - type: 'string', - description: - 'Natural language description of what you need (e.g. "create an employee", "list time off requests")', - }, - connector: { - type: 'string', - description: 'Optional connector filter (e.g. "bamboohr", "hibob")', - }, - top_k: { - type: 'integer', - description: 'Max results to return (1-50, default 5)', - minimum: 1, - maximum: 50, - }, - }, - required: ['query'], -} as const satisfies ToolParameters; - -const executeInputSchema = z.object({ - tool_name: z - .string() - .transform((v) => v.trim()) - .refine((v) => v.length > 0, { message: 'tool_name must be a non-empty string' }), - parameters: z.record(z.string(), z.unknown()).optional().default({}), -}); - -const executeParameters = { - type: 'object', - properties: { - tool_name: { - type: 'string', - description: 'Exact tool name from tool_search results', - }, - parameters: { - type: 'object', - description: 'Parameters for the tool. Pass an empty object {} if no parameters are needed.', - }, - }, - required: ['tool_name'], -} as const satisfies ToolParameters; - -const localConfig = (id: string): LocalExecuteConfig => ({ - kind: 'local', - identifier: `meta:${id}`, -}); - -/** @internal */ -export function createSearchTool( - toolset: StackOneToolSet, - accountIds?: string[], - connectors?: string, -): BaseTool { - const connectorLine = connectors ? ` Available connectors: ${connectors}.` : ''; - const tool = new BaseTool( - 'tool_search', - `Search for available tools by describing what you need. Returns matching tool names, descriptions, and parameter schemas. Use the returned parameter schemas to know exactly what to pass when calling tool_execute.${connectorLine}`, - searchParameters, - localConfig('search'), - ); - - tool.execute = async (inputParams?: JsonObject | string): Promise => { - try { - const raw = typeof inputParams === 'string' ? JSON.parse(inputParams) : inputParams || {}; - const parsed = searchInputSchema.parse(raw); - - const searchConfig = toolset.getSearchConfig() ?? {}; - const results = await toolset.searchTools(parsed.query, { - connector: parsed.connector, - topK: parsed.top_k ?? searchConfig.topK, - minSimilarity: searchConfig.minSimilarity, - search: searchConfig.method, - accountIds, - }); - - return { - tools: results.toArray().map((t) => ({ - name: t.name, - description: t.description, - parameters: t.parameters.properties as unknown as JsonObject, - })), - total: results.length, - query: parsed.query, - }; - } catch (error) { - if (error instanceof StackOneAPIError) { - return { error: error.message, status_code: error.statusCode }; - } - if (error instanceof SyntaxError || error instanceof z.ZodError) { - return { - error: `Invalid input: ${error instanceof z.ZodError ? error.issues.map((i) => i.message).join(', ') : error.message}`, - }; - } - throw error; - } - }; - - return tool; -} - -/** @internal */ -export function createExecuteTool( - toolset: StackOneToolSet, - accountIds?: string[], - connectors?: string, -): BaseTool { - let cachedTools: Awaited> | null = null; - - const connectorLine = connectors ? ` Available connectors: ${connectors}.` : ''; - const tool = new BaseTool( - 'tool_execute', - `Execute a tool by name with the given parameters. Use tool_search first to find available tools. The parameters field must match the parameter schema returned by tool_search. Pass parameters as a nested object matching the schema structure.${connectorLine}`, - executeParameters, - localConfig('execute'), - ); - - tool.execute = async ( - inputParams?: JsonObject | string, - executeOptions?: ExecuteOptions, - ): Promise => { - let toolName = 'unknown'; - try { - const raw = typeof inputParams === 'string' ? JSON.parse(inputParams) : inputParams || {}; - const parsed = executeInputSchema.parse(raw); - toolName = parsed.tool_name; - - if (!cachedTools) { - cachedTools = await toolset.fetchTools({ accountIds }); - } - const target = cachedTools.getTool(parsed.tool_name); - - if (!target) { - return { - error: `Tool "${parsed.tool_name}" not found. Use tool_search to find available tools.`, - }; - } - - return await target.execute(parsed.parameters as JsonObject, executeOptions); - } catch (error) { - if (error instanceof StackOneAPIError) { - return { - error: error.message, - status_code: error.statusCode, - response_body: error.responseBody as JsonObject, - tool_name: toolName, - }; - } - if (error instanceof SyntaxError || error instanceof z.ZodError) { - return { - error: `Invalid input: ${error instanceof z.ZodError ? error.issues.map((i) => i.message).join(', ') : error.message}`, - tool_name: toolName, - }; - } - throw error; - } - }; - - return tool; -} - /** Wire-format defender config sent to the backend RPC action. */ interface DefenderApiConfig { enabled: boolean; @@ -594,7 +322,6 @@ export class StackOneToolSet { private headers: Record; private rpcClient?: RpcClient; private readonly timeout: number; - private readonly searchConfig: SearchConfig | null; private readonly executeConfig: ExecuteToolsConfig | undefined; private readonly defenderConfig: DefenderConfig | null; private readonly defenderFields: { defender_config: DefenderApiConfig } | Record; @@ -656,7 +383,6 @@ export class StackOneToolSet { this.accountIds = config?.accountIds ?? []; // Resolve search config: undefined/null → disabled, object → custom with defaults - this.searchConfig = config?.search != null ? { method: 'auto', ...config.search } : null; this.executeConfig = config?.execute; // Resolve defender config: @@ -715,9 +441,7 @@ export class StackOneToolSet { } } - private semanticSearchClient?: SemanticSearchClient; private catalogCache: Map = new Map(); - private toolIndexCache?: { tools: Tools; index: ToolIndex }; /** * Resolved defender behavior for this toolset. @@ -751,29 +475,9 @@ export class StackOneToolSet { */ clearCatalogCache(): void { this.catalogCache.clear(); - this.toolIndexCache = undefined; } - /** - * Get or lazily create the semantic search client. - */ - private getSemanticClient(): SemanticSearchClient { - if (!this.semanticSearchClient) { - const apiKey = this.getApiKey(); - this.semanticSearchClient = new SemanticSearchClient({ - apiKey, - baseUrl: this.baseUrl, - }); - } - return this.semanticSearchClient; - } - /** - * Get the current search config. - */ - getSearchConfig(): SearchConfig | null { - return this.searchConfig; - } /** * Extract the API key from authentication config. @@ -796,34 +500,6 @@ export class StackOneToolSet { return apiKey; } - /** - * Get a callable search tool that returns Tools collections. - * - * Returns a SearchTool instance that wraps `searchTools()` for use in agent loops. - * - * @param options - Options including the default search mode - * @returns SearchTool instance - * - * @example - * ```typescript - * const toolset = new StackOneToolSet({ apiKey: 'sk-xxx' }); - * const searchTool = toolset.getSearchTool(); - * const tools = await searchTool.search('manage employee records', { accountIds: ['acc-123'] }); - * ``` - */ - getSearchTool(options?: { search?: SearchMode }): SearchTool { - if (this.searchConfig === null) { - throw new ToolSetConfigError( - 'Search is disabled. Initialize StackOneToolSet with a search config to enable.', - ); - } - - const config: SearchConfig = options?.search - ? { ...this.searchConfig, method: options.search } - : this.searchConfig; - - return new SearchTool(this, config); - } /** * Get tool_search + tool_execute for agent-driven discovery. @@ -842,20 +518,6 @@ export class StackOneToolSet { return this.buildTools(accountIds); } - /** - * Build tool_search + tool_execute tools scoped to this toolset. - */ - private buildTools(accountIds?: string[], connectors?: string): Tools { - if (this.searchConfig === null) { - throw new ToolSetConfigError( - 'Search is disabled. Initialize StackOneToolSet with a search config to enable.', - ); - } - - const searchTool = createSearchTool(this, accountIds, connectors); - const executeTool = createExecuteTool(this, accountIds, connectors); - return new Tools([searchTool, executeTool]); - } /** * Get tools in OpenAI function calling format. @@ -905,305 +567,8 @@ export class StackOneToolSet { return tools.toOpenAI(); } - /** - * Search for and fetch tools using semantic or local search. - * - * This method discovers relevant tools based on natural language queries. - * - * @param query - Natural language description of needed functionality - * (e.g., "create employee", "send a message") - * @param options - Search options - * @returns Tools collection with matched tools from linked accounts - * @throws SemanticSearchError if the API call fails and search is "semantic" - * - * @example - * ```typescript - * // Semantic search (default with local fallback) - * const tools = await toolset.searchTools('manage employee records', { topK: 5 }); - * - * // Explicit semantic search - * const tools = await toolset.searchTools('manage employees', { search: 'semantic' }); - * - * // Local BM25+TF-IDF search - * const tools = await toolset.searchTools('manage employees', { search: 'local' }); - * - * // Filter by connector - * const tools = await toolset.searchTools('create time off request', { - * connector: 'bamboohr', - * search: 'semantic', - * }); - * ``` - */ - async searchTools(query: string, options?: SearchToolsOptions): Promise { - if (this.searchConfig === null) { - throw new ToolSetConfigError( - 'Search is disabled. Initialize StackOneToolSet with a search config to enable.', - ); - } - - const search = options?.search ?? this.searchConfig.method ?? 'auto'; - const topK = options?.topK ?? this.searchConfig.topK; - const minSimilarity = options?.minSimilarity ?? this.searchConfig.minSimilarity; - const mergedOptions = { ...options, search, topK, minSimilarity }; - - const allTools = await this.fetchTools({ accountIds: mergedOptions.accountIds }); - const availableConnectors = allTools.getConnectors(); - - if (availableConnectors.size === 0) { - return new Tools([]); - } - - // Local-only search — skip semantic API entirely - if (search === 'local') { - return this.localSearch(query, allTools, mergedOptions); - } - - try { - // Determine which connectors to search - let connectorsToSearch: Set; - if (mergedOptions.connector) { - const connectorLower = mergedOptions.connector.toLowerCase(); - connectorsToSearch = availableConnectors.has(connectorLower) - ? new Set([connectorLower]) - : new Set(); - if (connectorsToSearch.size === 0) { - return new Tools([]); - } - } else { - connectorsToSearch = availableConnectors; - } - - // Search each connector in parallel — in auto mode, treat missing - // API key as "semantic unavailable" and fall back to local search. - let client: SemanticSearchClient; - try { - client = this.getSemanticClient(); - } catch (error) { - if (search === 'auto' && error instanceof ToolSetConfigError) { - return this.localSearch(query, allTools, mergedOptions); - } - throw error; - } - const allResults: SemanticSearchResult[] = []; - let lastError: SemanticSearchError | undefined; - - const searchPromises = [...connectorsToSearch].map(async (connector) => { - try { - const response = await client.search(query, { - connector, - topK: mergedOptions.topK, - minSimilarity: mergedOptions.minSimilarity, - }); - return response.results; - } catch (error) { - if (error instanceof SemanticSearchError) { - lastError = error; - return []; - } - throw error; - } - }); - - const resultArrays = await Promise.all(searchPromises); - for (const results of resultArrays) { - allResults.push(...results); - } - - // If ALL connector searches failed, re-raise to trigger fallback - if (allResults.length === 0 && lastError) { - throw lastError; - } - - // Sort by score, apply topK - allResults.sort((a, b) => b.similarityScore - a.similarityScore); - const topResults = - mergedOptions.topK != null ? allResults.slice(0, mergedOptions.topK) : allResults; - - if (topResults.length === 0) { - return new Tools([]); - } - - // 1. Parse composite IDs to MCP-format action names, deduplicate - const seenNames = new Set(); - const actionNames: string[] = []; - for (const result of topResults) { - const name = normalizeActionName(result.id); - if (seenNames.has(name)) { - continue; - } - seenNames.add(name); - actionNames.push(name); - } - - if (actionNames.length === 0) { - return new Tools([]); - } - - // 2. Use MCP tools (already fetched) — schemas come from the source of truth - // 3. Filter to only the tools search found, preserving search relevance order - const actionOrder = new Map(actionNames.map((name, i) => [name, i])); - const matchedTools = allTools.toArray().filter((t) => seenNames.has(t.name)); - matchedTools.sort( - (a, b) => - (actionOrder.get(a.name) ?? Number.POSITIVE_INFINITY) - - (actionOrder.get(b.name) ?? Number.POSITIVE_INFINITY), - ); - - // Auto mode: if semantic returned results but none matched MCP tools, fall back to local - if (search === 'auto' && matchedTools.length === 0) { - return this.localSearch(query, allTools, mergedOptions); - } - - return new Tools(matchedTools); - } catch (error) { - if (error instanceof SemanticSearchError) { - if (search === 'semantic') { - throw error; - } - - // Auto mode: silently fall back to local search - return this.localSearch(query, allTools, mergedOptions); - } - throw error; - } - } - - /** - * Search for action names without fetching tools. - * - * Useful when you need to inspect search results before fetching, - * or when building custom filtering logic. - * - * @param query - Natural language description of needed functionality - * @param options - Search options - * @returns List of SemanticSearchResult with action names, scores, and metadata - * - * @example - * ```typescript - * // Lightweight: inspect results before fetching - * const results = await toolset.searchActionNames('manage employees'); - * for (const r of results) { - * console.log(`${r.id}: ${r.similarityScore.toFixed(2)}`); - * } - * - * // Then fetch specific high-scoring actions - * const selected = results - * .filter(r => r.similarityScore > 0.7) - * .map(r => r.id); - * const tools = await toolset.fetchTools({ actions: selected }); - * ``` - */ - async searchActionNames( - query: string, - options?: SearchActionNamesOptions, - ): Promise { - if (this.searchConfig === null) { - throw new ToolSetConfigError( - 'Search is disabled. Initialize StackOneToolSet with a search config to enable.', - ); - } - - const effectiveTopK = options?.topK ?? this.searchConfig.topK; - const effectiveMinSimilarity = options?.minSimilarity ?? this.searchConfig.minSimilarity; - - // Resolve available connectors from account IDs - let availableConnectors: Set | undefined; - const effectiveAccountIds = options?.accountIds || this.accountIds; - if (effectiveAccountIds.length > 0) { - const allTools = await this.fetchTools({ accountIds: effectiveAccountIds }); - availableConnectors = allTools.getConnectors(); - if (availableConnectors.size === 0) { - return []; - } - } - - try { - const client = this.getSemanticClient(); - let allResults: SemanticSearchResult[] = []; - - if (availableConnectors) { - // Parallel per-connector search (only user's connectors) - let connectorsToSearch: Set; - if (options?.connector) { - const connectorLower = options.connector.toLowerCase(); - connectorsToSearch = availableConnectors.has(connectorLower) - ? new Set([connectorLower]) - : new Set(); - } else { - connectorsToSearch = availableConnectors; - } - - const searchPromises = [...connectorsToSearch].map(async (connector) => { - try { - const response = await client.search(query, { - connector, - topK: effectiveTopK, - minSimilarity: effectiveMinSimilarity, - }); - return response.results; - } catch { - return []; - } - }); - - const resultArrays = await Promise.all(searchPromises); - for (const results of resultArrays) { - allResults.push(...results); - } - } else { - // No account filtering — single global search - const response = await client.search(query, { - connector: options?.connector, - topK: effectiveTopK, - minSimilarity: effectiveMinSimilarity, - }); - allResults = response.results; - } - - // Sort by score — return raw results (consumers can normalize the composite ID if needed) - allResults.sort((a, b) => b.similarityScore - a.similarityScore); - - return effectiveTopK != null ? allResults.slice(0, effectiveTopK) : allResults; - } catch (error) { - if (error instanceof SemanticSearchError) { - return []; - } - throw error; - } - } - - /** - * Run local BM25+TF-IDF search over already-fetched tools. - */ - private async localSearch( - query: string, - allTools: Tools, - options?: Pick, - ): Promise { - const availableConnectors = allTools.getConnectors(); - if (availableConnectors.size === 0) { - return new Tools([]); - } - - if (!this.toolIndexCache || this.toolIndexCache.tools !== allTools) { - this.toolIndexCache = { tools: allTools, index: new ToolIndex(allTools.toArray()) }; - } - const index = this.toolIndexCache.index; - const results = await index.search(query, options?.topK ?? 5, options?.minSimilarity ?? 0.0); - const matchedNames = results.map((r) => r.name); - const toolMap = new Map(allTools.toArray().map((t) => [t.name, t])); - const filterConnectors = options?.connector - ? new Set([options.connector.toLowerCase()]) - : availableConnectors; - const matchedTools = matchedNames - .filter((name) => toolMap.has(name)) - .map((name) => toolMap.get(name)!) - .filter((tool) => tool.connector && filterConnectors.has(tool.connector)); - - return new Tools(options?.topK != null ? matchedTools.slice(0, options.topK) : matchedTools); - } /** * Fetch tools from MCP with optional filtering diff --git a/src/types.ts b/src/types.ts index 2b2ff738..133da3ed 100644 --- a/src/types.ts +++ b/src/types.ts @@ -205,25 +205,6 @@ export type AISDKToolResult = ToolSet & { /** * Options for toClaudeAgentSdk() method */ -/** - * Search configuration for the StackOneToolSet constructor. - * - * When provided as an object, sets default search options that flow through - * to `searchTools()`, `getSearchTool()`, and `searchActionNames()`. - * Per-call options override these defaults. - * - * When set to `null`, search is disabled entirely. - * When omitted (`undefined`), defaults to `{ method: 'auto' }`. - */ -export interface SearchConfig { - /** Search backend to use. Defaults to `'auto'`. */ - method?: 'auto' | 'semantic' | 'local'; - /** Maximum number of tools to return. */ - topK?: number; - /** Minimum similarity score threshold 0-1. */ - minSimilarity?: number; -} - export interface ClaudeAgentSdkOptions { /** * Name of the MCP server. Defaults to 'stackone-tools'. diff --git a/src/utils/normalize.test.ts b/src/utils/normalize.test.ts deleted file mode 100644 index 0b450442..00000000 --- a/src/utils/normalize.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { normalizeActionName } from './normalize'; - -describe('normalizeActionName', () => { - test('strips versioned API name to MCP format', () => { - expect(normalizeActionName('calendly_1.0.0_calendly_create_scheduling_link_global')).toBe( - 'calendly_create_scheduling_link', - ); - }); - - test('handles multi-digit version numbers', () => { - expect(normalizeActionName('bamboohr_2.10.3_bamboohr_list_employees_global')).toBe( - 'bamboohr_list_employees', - ); - }); - - test('returns input unchanged when no version pattern matches', () => { - expect(normalizeActionName('bamboohr_create_employee')).toBe('bamboohr_create_employee'); - }); - - test('returns input unchanged for empty string', () => { - expect(normalizeActionName('')).toBe(''); - }); - - test('returns input unchanged when missing _global suffix', () => { - expect(normalizeActionName('calendly_1.0.0_calendly_create_link')).toBe( - 'calendly_1.0.0_calendly_create_link', - ); - }); - - test('returns input unchanged for uppercase names', () => { - expect(normalizeActionName('Calendly_1.0.0_create_link_global')).toBe( - 'Calendly_1.0.0_create_link_global', - ); - }); - - test('handles connector with digits', () => { - expect(normalizeActionName('api2cart_1.0.0_api2cart_get_products_global')).toBe( - 'api2cart_get_products', - ); - }); -}); diff --git a/src/utils/normalize.ts b/src/utils/normalize.ts deleted file mode 100644 index 0eee3025..00000000 --- a/src/utils/normalize.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Action name normalization utilities. - * - * The semantic search API returns versioned action names like: - * 'calendly_1.0.0_calendly_create_scheduling_link_global' - * - * MCP tools use simplified names: - * 'calendly_create_scheduling_link' - * - * This module bridges the two formats. - */ - -const VERSIONED_ACTION_RE = /^[a-z][a-z0-9]*_\d+(?:\.\d+)+_(.+)_global$/; - -/** - * Convert semantic search API action name to MCP tool name. - * - * @param actionName - The raw action name from the API - * @returns The normalized MCP-compatible tool name - * - * @example - * ```typescript - * normalizeActionName('calendly_1.0.0_calendly_create_scheduling_link_global'); - * // => 'calendly_create_scheduling_link' - * - * normalizeActionName('bamboohr_create_employee'); - * // => 'bamboohr_create_employee' (unchanged) - * ``` - */ -export function normalizeActionName(actionName: string): string { - const match = VERSIONED_ACTION_RE.exec(actionName); - return match ? match[1] : actionName; -} diff --git a/src/utils/tfidf-index.test.ts b/src/utils/tfidf-index.test.ts deleted file mode 100644 index 0ca003a6..00000000 --- a/src/utils/tfidf-index.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { fc, test as fcTest } from '@fast-check/vitest'; -import { TfidfIndex } from './tfidf-index'; - -describe('TF-IDF Index - Core Functionality', () => { - test('ranks documents by cosine similarity with tf-idf weighting', () => { - const index = new TfidfIndex(); - index.build([ - { id: 'doc1', text: 'alpha beta' }, - { id: 'doc2', text: 'alpha alpha' }, - { id: 'doc3', text: 'beta gamma' }, - ]); - - const [best, second] = index.search('alpha'); - - expect(best?.id).toBe('doc2'); - expect(best?.score ?? 0).toBeCloseTo(1, 5); - expect(second?.id).toBe('doc1'); - expect(second?.score ?? 0).toBeGreaterThan(0); - expect(second?.score ?? 0).toBeLessThan(best?.score ?? 0); - }); - - test('drops stopwords and punctuation when tokenizing', () => { - const index = new TfidfIndex(); - index.build([ - { id: 'doc1', text: 'schedule onboarding meeting' }, - { id: 'doc2', text: 'escalate production incident' }, - ]); - - const [result] = index.search('the onboarding meeting!!!'); - - expect(result?.id).toBe('doc1'); - expect(result?.score ?? 0).toBeGreaterThan(0); - }); - - test('assigns higher IDF to rare terms', () => { - const index = new TfidfIndex(); - index.build([ - { id: 'doc1', text: 'common term appears everywhere' }, - { id: 'doc2', text: 'common term appears here' }, - { id: 'doc3', text: 'common term and rare word' }, - ]); - - const rareResults = index.search('rare'); - const commonResults = index.search('common'); - - expect(rareResults.length).toBeGreaterThan(0); - expect(commonResults.length).toBeGreaterThan(0); - expect(rareResults[0]?.score ?? 0).toBeGreaterThan(0); - }); -}); - -describe('TF-IDF Index - Tool Name Scenarios', () => { - test('handles tool names with underscores', () => { - const index = new TfidfIndex(); - index.build([ - { id: 'bamboohr_create_employee', text: 'bamboohr_create_employee create employee bamboohr' }, - { id: 'bamboohr_list_employees', text: 'bamboohr_list_employees list employees bamboohr' }, - { id: 'workday_create_candidate', text: 'workday_create_candidate create candidate workday' }, - ]); - - const results = index.search('bamboohr create employee'); - - expect(results.length).toBeGreaterThan(0); - const topIds = results.slice(0, 2).map((r) => r.id); - expect(topIds).toContain('bamboohr_create_employee'); - }); - - test('ranks by action type (create, list, etc)', () => { - const index = new TfidfIndex(); - index.build([ - { id: 'bamboohr_create_employee', text: 'create employee record' }, - { id: 'bamboohr_update_employee', text: 'update employee record' }, - { id: 'bamboohr_delete_employee', text: 'delete employee record' }, - { id: 'bamboohr_list_employees', text: 'list employee records' }, - ]); - - const results = index.search('create employee'); - - expect(results.length).toBeGreaterThan(0); - expect(results[0]?.id).toBe('bamboohr_create_employee'); - }); -}); - -/** - * Property-Based Tests for TfidfIndex - * - * These tests verify invariants that must hold for ANY valid input, - * replacing the following example-based tests: - * - * - Score Validation: scores like 0.7071, 0.5, 1.0 are always in [0, 1] - * - Edge Cases: empty query "" returns [], query with no matches returns [] - * - Case Sensitivity: "Alpha" and "ALPHA" and "alpha" return same results - * - Search Limits: search("term", 5) returns at most 5 results - */ -describe('TF-IDF Index - Property-Based Tests', () => { - const documentArbitrary = fc.record({ - id: fc.string({ minLength: 1, maxLength: 20 }).filter((s) => s.trim().length > 0), - text: fc.string({ minLength: 1, maxLength: 200 }), - }); - - const corpusArbitrary = fc.array(documentArbitrary, { minLength: 1, maxLength: 20 }); - - const queryArbitrary = fc - .array(fc.stringMatching(/^[a-zA-Z][a-zA-Z0-9]*$/), { minLength: 1, maxLength: 5 }) - .map((words) => words.join(' ')); - - // Example: search("alpha") on any corpus returns scores like 0.0, 0.5, 1.0 - never 1.5 or -0.1 - fcTest.prop([corpusArbitrary, queryArbitrary], { numRuns: 100 })( - 'scores are always within [0, 1] range', - (corpus, query) => { - const index = new TfidfIndex(); - index.build(corpus); - const results = index.search(query, 100); - - for (const result of results) { - expect(result.score).toBeGreaterThanOrEqual(0); - expect(result.score).toBeLessThanOrEqual(1); - } - }, - ); - - // Example: [{ score: 0.9 }, { score: 0.7 }, { score: 0.3 }] - always descending - fcTest.prop([corpusArbitrary, queryArbitrary], { numRuns: 100 })( - 'results are always sorted by score in descending order', - (corpus, query) => { - const index = new TfidfIndex(); - index.build(corpus); - const results = index.search(query, 100); - - for (let i = 0; i < results.length - 1; i++) { - expect(results[i]?.score ?? 0).toBeGreaterThanOrEqual(results[i + 1]?.score ?? 0); - } - }, - ); - - // Example: search("term", 3) with 10 matching docs returns only 3 results - fcTest.prop([corpusArbitrary, queryArbitrary, fc.integer({ min: 1, max: 50 })], { numRuns: 100 })( - 'search returns at most k results', - (corpus, query, k) => { - const index = new TfidfIndex(); - index.build(corpus); - const results = index.search(query, k); - - expect(results.length).toBeLessThanOrEqual(k); - }, - ); - - // Example: search("Alpha"), search("ALPHA"), search("alpha") all return identical results - fcTest.prop([corpusArbitrary, queryArbitrary], { numRuns: 100 })( - 'search is case-insensitive', - (corpus, query) => { - const index = new TfidfIndex(); - index.build(corpus); - - const lowerResults = index.search(query.toLowerCase()); - const upperResults = index.search(query.toUpperCase()); - - expect(lowerResults.length).toBe(upperResults.length); - for (let i = 0; i < lowerResults.length; i++) { - expect(lowerResults[i]?.id).toBe(upperResults[i]?.id); - expect(lowerResults[i]?.score).toBeCloseTo(upperResults[i]?.score ?? 0, 10); - } - }, - ); - - // Example: index.build([]) then search("anything") returns [] - fcTest.prop([queryArbitrary], { numRuns: 50 })('empty corpus returns empty results', (query) => { - const index = new TfidfIndex(); - index.build([]); - const results = index.search(query); - - expect(results).toHaveLength(0); - }); - - // Example: corpus has ids ["doc1", "doc2"], results only contain "doc1" or "doc2" - fcTest.prop([corpusArbitrary, queryArbitrary], { numRuns: 100 })( - 'result IDs are from the indexed corpus', - (corpus, query) => { - const index = new TfidfIndex(); - index.build(corpus); - const results = index.search(query, 100); - - const corpusIds = new Set(corpus.map((doc) => doc.id)); - for (const result of results) { - expect(corpusIds.has(result.id)).toBe(true); - } - }, - ); - - // Example: same corpus + same query always produces identical results - fcTest.prop([corpusArbitrary, queryArbitrary], { numRuns: 50 })( - 'search is deterministic', - (corpus, query) => { - const index1 = new TfidfIndex(); - const index2 = new TfidfIndex(); - - index1.build(corpus); - index2.build(corpus); - - const results1 = index1.search(query, 10); - const results2 = index2.search(query, 10); - - expect(results1).toEqual(results2); - }, - ); -}); diff --git a/src/utils/tfidf-index.ts b/src/utils/tfidf-index.ts deleted file mode 100644 index 9bd680ea..00000000 --- a/src/utils/tfidf-index.ts +++ /dev/null @@ -1,192 +0,0 @@ -/** - * Lightweight TF-IDF vector index for offline vector search. - * No external dependencies; tokenizes ASCII/latin text, lowercases, - * strips punctuation, removes a small stopword set, and builds a sparse index. - */ - -interface TfidfDocument { - id: string; - text: string; -} - -interface TfidfResult { - id: string; - score: number; // cosine similarity (0..1) -} - -const STOPWORDS = new Set([ - 'a', - 'an', - 'the', - 'and', - 'or', - 'but', - 'if', - 'then', - 'else', - 'for', - 'of', - 'in', - 'on', - 'to', - 'from', - 'by', - 'with', - 'as', - 'at', - 'is', - 'are', - 'was', - 'were', - 'be', - 'been', - 'it', - 'this', - 'that', - 'these', - 'those', - 'not', - 'no', - 'can', - 'could', - 'should', - 'would', - 'may', - 'might', - 'do', - 'does', - 'did', - 'have', - 'has', - 'had', - 'you', - 'your', -]); - -const tokenize = (text: string): string[] => { - return text - .toLowerCase() - .replace(/[^a-z0-9_\s]/g, ' ') - .split(/\s+/) - .filter((t) => t && !STOPWORDS.has(t)); -}; - -type SparseVec = Map; // termId -> weight - -export class TfidfIndex { - private vocab = new Map(); - private idf: number[] = []; - private docs: { id: string; vec: SparseVec; norm: number }[] = []; - - /** - * Build index from a corpus of documents - */ - build(corpus: TfidfDocument[]): void { - // vocab + df - const df = new Map(); - const docsTokens: string[][] = corpus.map((d) => tokenize(d.text)); - - // assign term ids - for (const tokens of docsTokens) { - for (const t of tokens) { - if (!this.vocab.has(t)) this.vocab.set(t, this.vocab.size); - } - } - - // compute df - for (const tokens of docsTokens) { - const seen = new Set(); - for (const t of tokens) { - const id = this.vocab.get(t); - if (id === undefined) continue; - if (!seen.has(id)) { - seen.add(id); - df.set(id, (df.get(id) || 0) + 1); - } - } - } - - // compute idf - const N = corpus.length; - this.idf = Array.from({ length: this.vocab.size }, (_, id) => { - const dfi = df.get(id) || 0; - // smoothed idf - return Math.log((N + 1) / (dfi + 1)) + 1; - }); - - // doc vectors - this.docs = corpus.map((d, i) => { - const docTokens = docsTokens[i] ?? []; - const tf = new Map(); - for (const t of docTokens) { - const id = this.vocab.get(t); - if (id === undefined) continue; - tf.set(id, (tf.get(id) || 0) + 1); - } - // build weighted vector - const vec: SparseVec = new Map(); - let normSq = 0; - tf.forEach((f, id) => { - const idf = this.idf[id]; - if (idf === undefined || docTokens.length === 0) return; - const w = (f / docTokens.length) * idf; - if (w > 0) { - vec.set(id, w); - normSq += w * w; - } - }); - const norm = Math.sqrt(normSq) || 1; - return { id: d.id, vec, norm }; - }); - } - - /** - * Search for documents similar to the query - * @param query - Search query - * @param k - Maximum number of results to return - * @returns Array of results sorted by score (descending) - */ - search(query: string, k = 10): TfidfResult[] { - const tokens = tokenize(query); - if (tokens.length === 0 || this.vocab.size === 0) return []; - - const tf = new Map(); - for (const t of tokens) { - const id = this.vocab.get(t); - if (id !== undefined) tf.set(id, (tf.get(id) || 0) + 1); - } - - if (tf.size === 0) return []; - - const qVec: SparseVec = new Map(); - let qNormSq = 0; - const total = tokens.length; - tf.forEach((f, id) => { - const idf = this.idf[id]; - if (idf === undefined) return; - const w = total === 0 ? 0 : (f / total) * idf; - if (w > 0) { - qVec.set(id, w); - qNormSq += w * w; - } - }); - const qNorm = Math.sqrt(qNormSq) || 1; - - // cosine similarity with sparse vectors - const scores: TfidfResult[] = []; - for (const d of this.docs) { - let dot = 0; - // iterate over smaller map - const [small, big] = qVec.size <= d.vec.size ? [qVec, d.vec] : [d.vec, qVec]; - small.forEach((w, id) => { - const v = big.get(id); - if (v !== undefined) dot += w * v; - }); - const sim = dot / (qNorm * d.norm); - if (sim > 0) scores.push({ id: d.id, score: Math.min(1, Math.max(0, sim)) }); - } - - scores.sort((a, b) => b.score - a.score); - return scores.slice(0, k); - } -} From 083b90ec497a70049ef459ed040cda6f9203061f Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 16 Sep 2026 16:53:06 +0100 Subject: [PATCH 002/151] fix!: remove search leftovers the typecheck never saw MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fc3752a deleted buildTools but left two callers, so getTools() and openai({ mode: 'search_and_execute' }) would have thrown "this.buildTools is not a function" at runtime. Both were meta-tool entry points with nothing behind them once search was removed, so both are gone. Also drops scripts/benchmark-search.ts, which benchmarked the removed search API, and an unused SearchTool import in toolsets.test.ts. None of this was caught because the typechecker was not running: vitest spawns tsc, the flake supplies typescript-go, and these commands were run outside `nix develop`. Vitest reported "Type Errors: no errors" while also printing "spawn tsc ENOENT" — so a typecheck that never ran looked like a clean one. `tsc --noEmit` finds all four the moment it can actually execute. Verified with a one-off typescript: typecheck clean, 255 tests pass. Co-Authored-By: Claude Opus 5 (1M context) --- scripts/benchmark-search.ts | 135 ------------------------------------ src/toolsets.test.ts | 1 - src/toolsets.ts | 41 ----------- 3 files changed, 177 deletions(-) delete mode 100644 scripts/benchmark-search.ts diff --git a/scripts/benchmark-search.ts b/scripts/benchmark-search.ts deleted file mode 100644 index 205bee17..00000000 --- a/scripts/benchmark-search.ts +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Benchmark: measure SDK search latency with caching. - * - * Runs fetchTools, local (BM25+TF-IDF) search, and semantic search N times, - * reports cold vs warm average latency and the speedup from caching. - * - * Prerequisites: - * - STACKONE_API_KEY environment variable - * - STACKONE_ACCOUNT_ID environment variable - * - * Run with: - * STACKONE_API_KEY=xxx STACKONE_ACCOUNT_ID=xxx npx tsx examples/benchmark-search.ts - * STACKONE_API_KEY=xxx STACKONE_ACCOUNT_ID=xxx npx tsx examples/benchmark-search.ts --iterations 50 - */ - -import process from 'node:process'; -import { StackOneToolSet } from '@stackone/ai'; - -const QUERIES = [ - 'list events', - 'cancel a meeting', - 'send a message', - 'get current user', - 'list employees', -]; - -function parseArgs(): number { - const idx = process.argv.indexOf('--iterations'); - const idxShort = process.argv.indexOf('-n'); - const pos = idx !== -1 ? idx : idxShort; - if (pos !== -1 && process.argv[pos + 1]) { - return Number.parseInt(process.argv[pos + 1], 10); - } - return 100; -} - -async function bench( - fn: () => Promise, - n: number, -): Promise<{ cold: number; warmAvg: number }> { - const times: number[] = []; - for (let i = 0; i < n; i++) { - const start = performance.now(); - await fn(); - times.push(performance.now() - start); - } - const cold = times[0]; - const warmTimes = times.slice(1); - const warmAvg = - warmTimes.length > 0 ? warmTimes.reduce((a, b) => a + b, 0) / warmTimes.length : cold; - return { cold, warmAvg }; -} - -function fmtMs(ms: number): string { - return `${ms.toFixed(1)}ms`.padStart(10); -} - -async function main(): Promise { - const iterations = parseArgs(); - - const apiKey = process.env.STACKONE_API_KEY; - const accountId = process.env.STACKONE_ACCOUNT_ID; - - if (!apiKey) { - console.error('Set STACKONE_API_KEY to run this benchmark.'); - process.exit(1); - } - if (!accountId) { - console.error('Set STACKONE_ACCOUNT_ID to run this benchmark.'); - process.exit(1); - } - - console.log( - `Benchmarking with account ${accountId.slice(0, 8)}..., ${iterations} iterations each\n`, - ); - - const ts = new StackOneToolSet({ - apiKey, - accountId, - search: { method: 'auto', topK: 5 }, - }); - - const results: Array<{ name: string; cold: number; warmAvg: number; speedup: number }> = []; - let queryIdx = 0; - const nextQuery = (): string => QUERIES[queryIdx++ % QUERIES.length]; - - // --- 1. fetchTools --- - console.log(`[1/3] fetchTools x${iterations} ...`); - ts.clearCatalogCache(); - const fetch = await bench(() => ts.fetchTools(), iterations); - const fetchSpeedup = fetch.cold / fetch.warmAvg; - results.push({ name: 'fetchTools', ...fetch, speedup: fetchSpeedup }); - console.log( - ` cold=${fmtMs(fetch.cold)} warm_avg=${fmtMs(fetch.warmAvg)} speedup=${fetchSpeedup.toFixed(0)}x`, - ); - - // --- 2. local search (BM25 + TF-IDF) --- - console.log(`[2/3] searchTools (local) x${iterations} ...`); - ts.clearCatalogCache(); - queryIdx = 0; - const local = await bench(() => ts.searchTools(nextQuery(), { search: 'local' }), iterations); - const localSpeedup = local.cold / local.warmAvg; - results.push({ name: 'search (local/BM25)', ...local, speedup: localSpeedup }); - console.log( - ` cold=${fmtMs(local.cold)} warm_avg=${fmtMs(local.warmAvg)} speedup=${localSpeedup.toFixed(0)}x`, - ); - - // --- 3. semantic search (auto) --- - console.log(`[3/3] searchTools (semantic/auto) x${iterations} ...`); - ts.clearCatalogCache(); - queryIdx = 0; - const semantic = await bench(() => ts.searchTools(nextQuery(), { search: 'auto' }), iterations); - const semanticSpeedup = semantic.cold / semantic.warmAvg; - results.push({ name: 'search (semantic)', ...semantic, speedup: semanticSpeedup }); - console.log( - ` cold=${fmtMs(semantic.cold)} warm_avg=${fmtMs(semantic.warmAvg)} speedup=${semanticSpeedup.toFixed(0)}x`, - ); - - // --- Summary --- - console.log('\n' + '='.repeat(65)); - console.log( - `${'Benchmark'.padEnd(22)} ${'Cold'.padStart(10)} ${'Warm (avg)'.padStart(10)} ${'Speedup'.padStart(10)}`, - ); - console.log('-'.repeat(65)); - for (const r of results) { - console.log( - `${r.name.padEnd(22)} ${fmtMs(r.cold)} ${fmtMs(r.warmAvg)} ${`${r.speedup.toFixed(0)}x`.padStart(10)}`, - ); - } - console.log('='.repeat(65)); - console.log(`\nWarm = average of ${iterations - 1} calls after the first (cold) call.`); - console.log('Speedup = cold / warm_avg — shows the benefit of caching.\n'); -} - -void main(); diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index e23016a4..cc96c4bb 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -12,7 +12,6 @@ import { type McpToolDefinition, createMcpApp, defaultMcpTools } from '../mocks/ import { server } from '../mocks/node'; import { TEST_BASE_URL } from '../mocks/constants'; import { - SearchTool, StackOneToolSet, ToolSetConfigError, __resetDefenderInfoLog, diff --git a/src/toolsets.ts b/src/toolsets.ts index ea8d90d0..0bca0c28 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -501,68 +501,27 @@ export class StackOneToolSet { } - /** - * Get tool_search + tool_execute for agent-driven discovery. - * - * Returns a Tools collection with two tools that let the LLM - * discover and execute tools on-demand. - * - * @param options - Options to scope tool discovery - * @returns Tools collection containing tool_search and tool_execute - */ - getTools(options?: { accountIds?: string[] }): Tools { - const accountIds = - options?.accountIds ?? - this.executeConfig?.accountIds ?? - (this.accountIds.length > 0 ? this.accountIds : undefined); - return this.buildTools(accountIds); - } /** * Get tools in OpenAI function calling format. * * @param options - Options - * @param options.mode - Tool mode. - * `undefined` (default): fetch all tools and convert to OpenAI format. - * `"search_and_execute"`: return two tools (tool_search + tool_execute) - * that let the LLM discover and execute tools on-demand. * @param options.accountIds - Account IDs to scope tools. Overrides the `execute` * config from the constructor. * @returns List of tool definitions in OpenAI function format. * * @example * ```typescript - * // All tools * const toolset = new StackOneToolSet(); * const tools = await toolset.openai(); - * - * // Search and execute for agent-driven discovery - * const toolset = new StackOneToolSet({ search: {} }); - * const tools = await toolset.openai({ mode: 'search_and_execute' }); * ``` */ async openai(options?: { - mode?: 'search_and_execute'; accountIds?: string[]; }): Promise> { const effectiveAccountIds = options?.accountIds ?? this.executeConfig?.accountIds; - if (options?.mode === 'search_and_execute') { - // Discover available connectors for dynamic descriptions - let connectors: string | undefined; - try { - const allTools = await this.fetchTools({ accountIds: effectiveAccountIds }); - const connectorSet = allTools.getConnectors(); - if (connectorSet.size > 0) { - connectors = Array.from(connectorSet).sort().join(', '); - } - } catch { - // Best-effort: if discovery fails, use generic descriptions - } - return this.buildTools(effectiveAccountIds, connectors).toOpenAI(); - } - const tools = await this.fetchTools({ accountIds: effectiveAccountIds }); return tools.toOpenAI(); } From fe737834517b1ab80e9fa65fe4e9b9ed89ebfa9c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 13:00:53 +0100 Subject: [PATCH 003/151] feat(tool): preserve root schema keywords in toJsonSchema pass-through --- src/tool.ts | 10 ++++++++-- src/types.ts | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/tool.ts b/src/tool.ts index 62912401..b79478ea 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -183,11 +183,17 @@ export class BaseTool { * This is framework-agnostic and can be used with any LLM that accepts JSON Schema */ toJsonSchema(): ObjectJSONSchema { - return { + const schema: Record = { + ...this.parameters, type: 'object', properties: this.parameters.properties, - required: this.parameters.required, }; + if (this.parameters.required && this.parameters.required.length > 0) { + schema.required = this.parameters.required; + } else { + delete schema.required; + } + return schema as unknown as ObjectJSONSchema; } /** diff --git a/src/types.ts b/src/types.ts index 133da3ed..ac020d93 100644 --- a/src/types.ts +++ b/src/types.ts @@ -159,7 +159,7 @@ export interface ToolExecution { /** * Schema definition for tool parameters */ -export interface ToolParameters { +export interface ToolParameters extends Record { type: string; properties: JsonSchemaProperties; // these are the params we will expose to the user/agent in the tool. These might be higher level params. required?: string[]; // list of required parameter names From 18c3003ec072162fd88bd65112e56d9664192598 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 13:02:32 +0100 Subject: [PATCH 004/151] style: run oxfmt on formatted files --- examples/README.md | 10 +++++----- src/toolsets.test.ts | 6 +----- src/toolsets.ts | 12 +----------- 3 files changed, 7 insertions(+), 21 deletions(-) diff --git a/examples/README.md b/examples/README.md index 8e7ffd18..cda0e7d0 100644 --- a/examples/README.md +++ b/examples/README.md @@ -76,9 +76,9 @@ Demonstrates the four ways to configure prompt-injection detection on a `StackOn ## Environment Variables -| Variable | Required | Used By | -| --------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------ | -| `STACKONE_API_KEY` | Yes | All examples | -| `STACKONE_ACCOUNT_ID` | Recommended | All examples (read automatically by `new StackOneToolSet()`) | +| Variable | Required | Used By | +| --------------------- | ---------------------------- | ----------------------------------------------------------------------------------- | +| `STACKONE_API_KEY` | Yes | All examples | +| `STACKONE_ACCOUNT_ID` | Recommended | All examples (read automatically by `new StackOneToolSet()`) | | `OPENAI_API_KEY` | For OpenAI / AI SDK examples | `openai-integration.ts`, `openai-responses-integration.ts`, `ai-sdk-integration.ts` | -| `ANTHROPIC_API_KEY` | For Anthropic examples | `anthropic-integration.ts`, `claude-agent-sdk-integration.ts` | +| `ANTHROPIC_API_KEY` | For Anthropic examples | `anthropic-integration.ts`, `claude-agent-sdk-integration.ts` | diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index cc96c4bb..e1be19d5 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -11,11 +11,7 @@ import { http, HttpResponse } from 'msw'; import { type McpToolDefinition, createMcpApp, defaultMcpTools } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { TEST_BASE_URL } from '../mocks/constants'; -import { - StackOneToolSet, - ToolSetConfigError, - __resetDefenderInfoLog, -} from './toolsets'; +import { StackOneToolSet, ToolSetConfigError, __resetDefenderInfoLog } from './toolsets'; describe('StackOneToolSet', () => { beforeEach(() => { diff --git a/src/toolsets.ts b/src/toolsets.ts index 0bca0c28..ceeeda48 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -477,8 +477,6 @@ export class StackOneToolSet { this.catalogCache.clear(); } - - /** * Extract the API key from authentication config. */ @@ -500,9 +498,6 @@ export class StackOneToolSet { return apiKey; } - - - /** * Get tools in OpenAI function calling format. * @@ -517,18 +512,13 @@ export class StackOneToolSet { * const tools = await toolset.openai(); * ``` */ - async openai(options?: { - accountIds?: string[]; - }): Promise> { + async openai(options?: { accountIds?: string[] }): Promise> { const effectiveAccountIds = options?.accountIds ?? this.executeConfig?.accountIds; const tools = await this.fetchTools({ accountIds: effectiveAccountIds }); return tools.toOpenAI(); } - - - /** * Fetch tools from MCP with optional filtering * @param options Optional filtering options for account IDs, providers, and actions From 2bb8dbff1c7e06757c8dadd8388536e6b5043c5d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 13:04:26 +0100 Subject: [PATCH 005/151] fix(toolsets): remove unused imports to pass oxlint --- src/toolsets.test.ts | 2 +- src/toolsets.ts | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index e1be19d5..28185d65 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -7,7 +7,7 @@ * - Account filtering * - Provider and action filtering */ -import { http, HttpResponse } from 'msw'; +import { http } from 'msw'; import { type McpToolDefinition, createMcpApp, defaultMcpTools } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { TEST_BASE_URL } from '../mocks/constants'; diff --git a/src/toolsets.ts b/src/toolsets.ts index ceeeda48..178a8fa2 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -1,6 +1,5 @@ import { defu } from 'defu'; import type { MergeExclusive, SimplifyDeep } from 'type-fest'; -import { z } from 'zod/v4'; import { DEFAULT_BASE_URL } from './consts'; import { createFeedbackTool } from './feedback'; import { type StackOneHeaders, normalizeHeaders, stackOneHeadersSchema } from './headers'; @@ -13,14 +12,12 @@ import type { ExecuteOptions, JsonObject, JsonSchemaProperties, - LocalExecuteConfig, RpcExecuteConfig, ToolParameters, } from './types'; import { DEFAULT_DEFENDER_CONFIG } from './types'; import type { BinaryDownloadResult } from './utils/binary-response'; import { StackOneError } from './utils/error-stackone'; -import { StackOneAPIError } from './utils/error-stackone-api'; /** * Param-style pinned on the /mcp tool-listing URL. The MCP schema and the RPC-execution From bdddc58bcc43ca311286d16866aee72207d2b490 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:22:10 +0100 Subject: [PATCH 006/151] refactor!: remove SDK-side defender configuration Defender is configured per project in the StackOne dashboard now, so the SDK no longer carries its own copy of the setting or sends one with each RPC call. Dropping it removes a second source of truth that could silently override what the dashboard shows. - Remove the `defender` constructor option, the `defenderMode` getter and the once-per-process override warning. - Stop sending `defender_config` in the `/actions/rpc` payload. - Remove the defender-config example and its tests, and the README section. BREAKING CHANGE: `DefenderConfig`, `DefenderMode` and `DEFAULT_DEFENDER_CONFIG` are no longer exported, the `defender` option of `StackOneToolSetConfig` and `StackOneToolSet#defenderMode` are removed, and RPC requests no longer carry `defender_config`. Configure Defender in the StackOne dashboard. --- README.md | 81 ---------- examples/README.md | 4 - examples/defender-config.ts | 182 ---------------------- mocks/handlers.stackone-rpc.ts | 23 --- src/index.ts | 4 - src/rpc-client.test.ts | 33 ---- src/rpc-client.ts | 3 - src/schema.ts | 11 -- src/toolsets.test.ts | 204 +------------------------ src/toolsets.ts | 148 ------------------ src/types.ts | 61 -------- tests/examples/defender-config.test.ts | 155 ------------------- 12 files changed, 1 insertion(+), 908 deletions(-) delete mode 100644 examples/defender-config.ts delete mode 100644 tests/examples/defender-config.test.ts diff --git a/README.md b/README.md index 747b8e7d..9aaf9d47 100644 --- a/README.md +++ b/README.md @@ -305,87 +305,6 @@ import { StackOneToolSet } from '@stackone/ai'; const toolset = new StackOneToolSet({ baseUrl: 'https://api.example-dev.com' }); ``` -### Defender - -The SDK includes built-in prompt injection protection via [StackOne Defender](https://www.npmjs.com/package/@stackone/defender). It runs on every tool call result before the content reaches your LLM, detecting and sanitizing injection attacks hidden in external data (emails, documents, CRM notes, etc.). - -**By default, the SDK defers to your project's dashboard defender setting.** Pass an explicit `defender` config to override the project setting per toolset. - -| `defender` option | Effective behavior | -| --------------------------------- | --------------------------------------------------------- | -| omitted _(default)_ | Project dashboard setting controls — SDK adds nothing | -| `{ useProjectSettings: true }` | Same as omitting; explicit, self-documenting form | -| `{ enabled, blockHighRisk, ... }` | SDK-level config wins, overrides the project setting | -| `null` | Defender forcibly disabled, overrides the project setting | - -When passing an explicit object, missing fields fall back to `DEFAULT_DEFENDER_CONFIG` (exported from `@stackone/ai`): `enabled: true`, `blockHighRisk: false`, both tiers on. - -#### Configuration modes - -```typescript -import { StackOneToolSet, DEFAULT_DEFENDER_CONFIG } from '@stackone/ai'; - -// Default — defer to project dashboard setting -const toolset = new StackOneToolSet({ apiKey: '...' }); - -// Same as default, explicit form -const toolset = new StackOneToolSet({ - apiKey: '...', - defender: { useProjectSettings: true }, -}); - -// Explicitly disabled — overrides any project setting -const toolset = new StackOneToolSet({ - apiKey: '...', - defender: null, -}); - -// Opt in with safe defaults, but block on HIGH/CRITICAL — overrides project setting -const toolset = new StackOneToolSet({ - apiKey: '...', - defender: { ...DEFAULT_DEFENDER_CONFIG, blockHighRisk: true }, -}); - -// Fully explicit SDK-level config -const toolset = new StackOneToolSet({ - apiKey: '...', - defender: { - enabled: true, - blockHighRisk: true, // throw on HIGH or CRITICAL risk - useTier1Classification: true, // pattern-based (regex, role markers) - useTier2Classification: true, // ML-based (ONNX model) - }, -}); -``` - -#### Inspecting and observing the resolved mode - -Use the `defenderMode` getter to check how a toolset will behave at runtime: - -```typescript -const toolset = new StackOneToolSet({ apiKey: '...', defender: null }); -toolset.defenderMode; // 'disabled' | 'explicit' | 'project' -``` - -When the SDK overrides the project dashboard (mode `disabled` or `explicit`), it emits a yellow `console.warn` line once per process per distinct override shape so the override is visible at runtime without spamming logs. Pass `NO_COLOR=1` to suppress color, or `FORCE_COLOR=1` to force it when piping output. The `project` mode is silent. - -#### Risk levels - -Defender assigns a risk level to each scanned result: - -| Level | Meaning | -| ---------- | --------------------------------------------------- | -| `low` | No threats detected | -| `medium` | Suspicious patterns detected, role markers stripped | -| `high` | Injection patterns found, content redacted | -| `critical` | Severe injection attempt with multiple indicators | - -When `blockHighRisk: false` (default), `high` and `critical` results are annotated and returned — the LLM sees the sanitized content. When `blockHighRisk: true`, those results are blocked entirely. - -[View full example](examples/defender-config.ts) - -For more detail on how the detection pipeline works, see the [`@stackone/defender`](https://www.npmjs.com/package/@stackone/defender) package. - ### Testing with dryRun You can use the `dryRun` option to return the api arguments from a tool call without making the actual api call: diff --git a/examples/README.md b/examples/README.md index cda0e7d0..77711543 100644 --- a/examples/README.md +++ b/examples/README.md @@ -70,10 +70,6 @@ Converts StackOne tools into an MCP server with `tools.toClaudeAgentSdk()` and p Walks through every way to configure API keys and account IDs: reading from environment variables, passing them explicitly to the constructor, setting multiple accounts with `setAccounts()`, overriding per-tool collection or per individual tool, and fetching tools for multiple accounts in one call. -### [`defender-config.ts`](./defender-config.ts) -- Defender Configuration - -Demonstrates the four ways to configure prompt-injection detection on a `StackOneToolSet`: omit (defer to project dashboard), `{ useProjectSettings: true }` (explicit form of the default), `null` (force off), and explicit config objects. Shows the `defenderMode` getter and the once-per-process warning the SDK emits when it overrides the dashboard. Sections 1–7 are construction-only; section 8 makes a live RPC call when `STACKONE_API_KEY` is set so you can inspect the `defenderMetadata` shape the backend returns. - ## Environment Variables | Variable | Required | Used By | diff --git a/examples/defender-config.ts b/examples/defender-config.ts deleted file mode 100644 index 506d7e38..00000000 --- a/examples/defender-config.ts +++ /dev/null @@ -1,182 +0,0 @@ -/** - * Defender configuration patterns. - * - * Sections 1–7 are construction-only: the four configuration modes, - * the `defenderMode` getter, the once-per-process override warning, - * and the runtime validation error. No API key required. - * - * Section 8 makes a live RPC call so you can see the defender - * annotations the backend returns. It's gated on `STACKONE_API_KEY` - * and skips with a friendly message if you don't have one set. - * - * Run with: - * pnpm run:example examples/defender-config.ts - * - * Or override the connector and tool for section 8: - * TOOL_NAME=calendly_get_current_user TOOL_BODY_JSON='{}' pnpm run:example examples/defender-config.ts - * TOOL_NAME=hibob_list_employees TOOL_BODY_JSON='{"page_size": 5}' pnpm run:example examples/defender-config.ts - * - * Live section env vars: - * STACKONE_API_KEY (required to run section 8; read from .env via run:example) - * STACKONE_ACCOUNT_ID (required for tool execution unless your key has a default account) - * TOOL_NAME (defaults to gmail_list_messages) - * TOOL_BODY_JSON (JSON body, defaults to `{}`) - */ - -import process from 'node:process'; -import type { JsonObject } from '@stackone/ai'; -import { DEFAULT_DEFENDER_CONFIG, StackOneToolSet, ToolSetConfigError } from '@stackone/ai'; - -const heading = (label: string): void => { - console.log(`\n=== ${label} ===`); -}; - -// --- 1. Default — defer to project dashboard --- -const defaultMode = (): void => { - heading('1. Default (omit defender) — defer to dashboard'); - const toolset = new StackOneToolSet({ apiKey: 'demo-key' }); - console.log(` defenderMode: ${toolset.defenderMode}`); - console.log(' SDK adds no defender_config to the RPC payload.'); -}; - -// --- 2. Explicit form of the default --- -const explicitProject = (): void => { - heading('2. defender: { useProjectSettings: true } — same as default'); - const toolset = new StackOneToolSet({ - apiKey: 'demo-key', - defender: { useProjectSettings: true }, - }); - console.log(` defenderMode: ${toolset.defenderMode}`); -}; - -// --- 3. Force off — overrides dashboard --- -const disabled = (): void => { - heading('3. defender: null — forcibly disabled (overrides dashboard)'); - const toolset = new StackOneToolSet({ apiKey: 'demo-key', defender: null }); - console.log(` defenderMode: ${toolset.defenderMode}`); - console.log(' SDK sends defender_config with all fields false.'); -}; - -// --- 4. Spread defaults + tweak one field --- -const explicitOptIn = (): void => { - heading('4. Spread DEFAULT_DEFENDER_CONFIG + override one field'); - const toolset = new StackOneToolSet({ - apiKey: 'demo-key', - defender: { ...DEFAULT_DEFENDER_CONFIG, blockHighRisk: true }, - }); - console.log(` defenderMode: ${toolset.defenderMode}`); -}; - -// --- 5. Repeat the same shape — dedupe should suppress the warning --- -const repeatedExplicit = (): void => { - heading('5. Repeat the same explicit shape — warning suppressed'); - const toolset = new StackOneToolSet({ - apiKey: 'demo-key', - defender: { ...DEFAULT_DEFENDER_CONFIG, blockHighRisk: true }, - }); - console.log(` defenderMode: ${toolset.defenderMode}`); -}; - -// --- 6. Different explicit shape — fresh warning fires --- -const differentExplicit = (): void => { - heading('6. Different explicit shape — fresh warning'); - const toolset = new StackOneToolSet({ - apiKey: 'demo-key', - defender: { - enabled: true, - blockHighRisk: false, - useTier1Classification: true, - useTier2Classification: false, - }, - }); - console.log(` defenderMode: ${toolset.defenderMode}`); -}; - -// --- 7. Runtime validation --- -const invalidCombo = (): void => { - heading('7. useProjectSettings: true + other fields → throws'); - try { - new StackOneToolSet({ - apiKey: 'demo-key', - // @ts-expect-error - intentionally testing invalid runtime input - defender: { useProjectSettings: true, enabled: true }, - }); - console.log(' (no throw — unexpected!)'); - } catch (err) { - if (err instanceof ToolSetConfigError) { - console.log(` caught ToolSetConfigError: ${err.message}`); - } else { - throw err; - } - } -}; - -// --- 8. Live tool call — inspect defender annotations in the real response --- -const liveCall = async (): Promise => { - heading('8. Live tool call — inspect defender annotations'); - - if (!process.env.STACKONE_API_KEY) { - console.log(' Skipping — set STACKONE_API_KEY to run this section.'); - console.log(' Optional: STACKONE_ACCOUNT_ID, TOOL_NAME, TOOL_BODY_JSON.'); - return; - } - - const toolName = process.env.TOOL_NAME ?? 'gmail_list_messages'; - let body: JsonObject; - try { - body = JSON.parse(process.env.TOOL_BODY_JSON ?? '{}') as JsonObject; - } catch (err) { - console.log(` Invalid TOOL_BODY_JSON: ${(err as Error).message}`); - return; - } - - const toolset = new StackOneToolSet({ - defender: { ...DEFAULT_DEFENDER_CONFIG, blockHighRisk: false }, - }); - - console.log(` Fetching tools and calling ${toolName}...`); - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === toolName); - if (!tool) { - console.log(` Tool "${toolName}" not in this account.`); - return; - } - - const result = await tool.execute({ body }); - - // The backend surfaces defender annotations alongside the tool data: - // - // { - // data: , - // defenderMetadata: { - // applied: boolean, // false if defender ran but did nothing - // result: { - // allowed: boolean, // false → backend blocked (with blockHighRisk: true) - // riskLevel: 'low' | 'medium' | 'high' | 'critical', - // fieldsSanitized: string[], - // patternsByField: Record, - // detections: unknown[], - // tier2SkipReason?: string, // only when Tier 2 didn't run (e.g. no strings) - // latencyMs: number, - // } - // } - // } - const metadata = (result as { defenderMetadata?: unknown }).defenderMetadata; - if (metadata) { - console.log(' defenderMetadata:', JSON.stringify(metadata, null, 2)); - } else { - console.log(' (no defenderMetadata in response — defender may not have run)'); - } -}; - -// --- Run all sections --- -defaultMode(); -explicitProject(); -disabled(); -explicitOptIn(); -repeatedExplicit(); -differentExplicit(); -invalidCombo(); -await liveCall(); - -console.log('\nDone — defender patterns demonstrated.'); diff --git a/mocks/handlers.stackone-rpc.ts b/mocks/handlers.stackone-rpc.ts index 3ed0bed6..5ff116ce 100644 --- a/mocks/handlers.stackone-rpc.ts +++ b/mocks/handlers.stackone-rpc.ts @@ -20,12 +20,6 @@ export const stackoneRpcHandlers = [ const body = (await request.json()) as { action?: string; body?: Record; - defender_config?: { - enabled?: boolean; - block_high_risk?: boolean; - use_tier1_classification?: boolean; - use_tier2_classification?: boolean; - }; headers?: Record; path?: Record; query?: Record; @@ -76,34 +70,17 @@ export const stackoneRpcHandlers = [ ); } - // Synthetic defender annotations - const defenderMetadata = body.defender_config - ? { - applied: body.defender_config.enabled !== false, - result: { - allowed: true, - riskLevel: 'low', - fieldsSanitized: [], - patternsByField: {}, - detections: [], - latencyMs: 0, - }, - } - : undefined; - // Default response for other actions — echo back received fields return HttpResponse.json({ data: { action: body.action, received: { body: body.body, - defender_config: body.defender_config, headers: body.headers, path: body.path, query: body.query, }, }, - ...(defenderMetadata ? { defenderMetadata } : {}), }); }), ]; diff --git a/src/index.ts b/src/index.ts index 3e63a72b..0fd0bbcf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,13 +19,9 @@ export { type StackOneToolSetConfig, } from './toolsets'; -export { DEFAULT_DEFENDER_CONFIG } from './types'; - export type { AISDKToolDefinition, AISDKToolResult, - DefenderConfig, - DefenderMode, ExecuteConfig, ExecuteOptions, JsonObject, diff --git a/src/rpc-client.test.ts b/src/rpc-client.test.ts index 08332e2b..77cc88f5 100644 --- a/src/rpc-client.test.ts +++ b/src/rpc-client.test.ts @@ -152,39 +152,6 @@ test('should send x-account-id as HTTP header', async () => { }); }); -test('should forward defender_config in request payload', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); - - const response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'custom_action', - defender_config: { enabled: true, block_high_risk: false }, - }), - ); - - expect(response.data).toMatchObject({ - received: { defender_config: { enabled: true, block_high_risk: false } }, - }); -}); - -test('should omit defender_config from payload when not provided', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); - - const response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'custom_action', - }), - ); - - expect((response.data as Record).received).not.toHaveProperty('defender_config'); -}); - /** * Binary file downloads over RPC * diff --git a/src/rpc-client.ts b/src/rpc-client.ts index 45f45a4f..f616d558 100644 --- a/src/rpc-client.ts +++ b/src/rpc-client.ts @@ -61,9 +61,6 @@ export class RpcClient { const requestBody = { action: validatedRequest.action, body: validatedRequest.body, - ...(validatedRequest.defender_config !== undefined && { - defender_config: validatedRequest.defender_config, - }), headers: validatedRequest.headers, path: validatedRequest.path, query: validatedRequest.query, diff --git a/src/schema.ts b/src/schema.ts index 345abfa8..4e9ccac2 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -1,16 +1,6 @@ import { z } from 'zod/v4-mini'; import { stackOneHeadersSchema } from './headers'; -/** - * Zod schema for nested defender configuration sent with each RPC request - */ -const defenderConfigRequestSchema = z.object({ - enabled: z.optional(z.boolean()), - block_high_risk: z.optional(z.boolean()), - use_tier1_classification: z.optional(z.boolean()), - use_tier2_classification: z.optional(z.boolean()), -}); - /** * Zod schema for RPC action request validation * @see https://docs.stackone.com/platform/api-reference/actions/make-an-rpc-call-to-an-action @@ -18,7 +8,6 @@ const defenderConfigRequestSchema = z.object({ export const rpcActionRequestSchema = z.object({ action: z.string(), body: z.optional(z.record(z.string(), z.unknown())), - defender_config: z.optional(defenderConfigRequestSchema), headers: z.optional(stackOneHeadersSchema), path: z.optional(z.record(z.string(), z.unknown())), query: z.optional(z.record(z.string(), z.unknown())), diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 28185d65..52121106 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -11,7 +11,7 @@ import { http } from 'msw'; import { type McpToolDefinition, createMcpApp, defaultMcpTools } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { TEST_BASE_URL } from '../mocks/constants'; -import { StackOneToolSet, ToolSetConfigError, __resetDefenderInfoLog } from './toolsets'; +import { StackOneToolSet, ToolSetConfigError } from './toolsets'; describe('StackOneToolSet', () => { beforeEach(() => { @@ -678,208 +678,6 @@ describe('StackOneToolSet', () => { }); }); - describe('defender config', () => { - it('should store defender config from constructor', () => { - const toolset = new StackOneToolSet({ - apiKey: 'test-key', - defender: { enabled: false }, - }); - - // @ts-expect-error - Accessing private property for testing - expect(toolset.defenderConfig).toEqual({ enabled: false }); - }); - - it('should normalize omitted defender to useProjectSettings: true', () => { - const toolset = new StackOneToolSet({ apiKey: 'test-key' }); - - // @ts-expect-error - Accessing private property for testing - expect(toolset.defenderConfig).toEqual({ useProjectSettings: true }); - }); - - it('should include defender_config in dryRun payload when defender.enabled is set', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - defender: { enabled: false }, - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody.defender_config.enabled).toBe(false); - }); - - it('should omit defender_config from dryRun payload when defender config is not set', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody).not.toHaveProperty('defender_config'); - }); - - it('should forward defender_config in live RPC call when defender.enabled is set', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - defender: { enabled: true }, - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute({ body: { name: 'test' } }); - - expect(result).toMatchObject({ - data: { received: { defender_config: { enabled: true } } }, - }); - }); - - it('should send defender_config with all fields false when defender is null', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - defender: null, - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody.defender_config).toEqual({ - enabled: false, - block_high_risk: false, - use_tier1_classification: false, - use_tier2_classification: false, - }); - }); - - it('should omit defender_config from payload when useProjectSettings is true', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - defender: { useProjectSettings: true }, - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody).not.toHaveProperty('defender_config'); - }); - - it('should throw ToolSetConfigError when useProjectSettings is combined with other defender options', () => { - expect( - () => - new StackOneToolSet({ - apiKey: 'test-key', - // @ts-expect-error - intentionally testing invalid runtime input - defender: { useProjectSettings: true, enabled: true }, - }), - ).toThrow(ToolSetConfigError); - }); - - describe('defenderMode getter', () => { - it('returns "project" when defender is omitted', () => { - const toolset = new StackOneToolSet({ apiKey: 'test-key' }); - expect(toolset.defenderMode).toBe('project'); - }); - - it('returns "project" when defender is { useProjectSettings: true }', () => { - const toolset = new StackOneToolSet({ - apiKey: 'test-key', - defender: { useProjectSettings: true }, - }); - expect(toolset.defenderMode).toBe('project'); - }); - - it('returns "disabled" when defender is null', () => { - const toolset = new StackOneToolSet({ apiKey: 'test-key', defender: null }); - expect(toolset.defenderMode).toBe('disabled'); - }); - - it('returns "explicit" when defender is an explicit config object', () => { - const toolset = new StackOneToolSet({ - apiKey: 'test-key', - defender: { useTier2Classification: false }, - }); - expect(toolset.defenderMode).toBe('explicit'); - }); - }); - - describe('override info log', () => { - beforeEach(() => { - __resetDefenderInfoLog(); - }); - - it('logs once for disabled mode and dedupes repeat constructions', () => { - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - new StackOneToolSet({ apiKey: 'test-key', defender: null }); - new StackOneToolSet({ apiKey: 'test-key', defender: null }); - const disabledCalls = warnSpy.mock.calls.filter((args) => - String(args[0]).includes('forcibly disabled'), - ); - expect(disabledCalls).toHaveLength(1); - warnSpy.mockRestore(); - }); - - it('logs once for an explicit config and dedupes the same shape', () => { - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - new StackOneToolSet({ - apiKey: 'test-key', - defender: { enabled: true, useTier1Classification: false, useTier2Classification: false }, - }); - new StackOneToolSet({ - apiKey: 'test-key', - defender: { enabled: true, useTier1Classification: false, useTier2Classification: false }, - }); - const explicitCalls = warnSpy.mock.calls.filter((args) => - String(args[0]).includes('configured via SDK'), - ); - expect(explicitCalls).toHaveLength(1); - expect(String(explicitCalls[0]?.[0])).toContain('useTier1Classification=false'); - warnSpy.mockRestore(); - }); - - it('does not log when defender is omitted or useProjectSettings', () => { - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - new StackOneToolSet({ apiKey: 'test-key' }); - new StackOneToolSet({ - apiKey: 'test-key', - defender: { useProjectSettings: true }, - }); - const defenderCalls = warnSpy.mock.calls.filter((args) => - String(args[0]).toLowerCase().includes('defender'), - ); - expect(defenderCalls).toHaveLength(0); - warnSpy.mockRestore(); - }); - }); - }); - describe('provider and action filtering', () => { it('filters tools by providers', async () => { const toolset = new StackOneToolSet({ diff --git a/src/toolsets.ts b/src/toolsets.ts index 178a8fa2..15d5f65c 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -7,15 +7,12 @@ import { createMCPClient } from './mcp-client'; import { type RpcActionResponse, RpcClient } from './rpc-client'; import { BaseTool, Tools } from './tool'; import type { - DefenderConfig, - DefenderMode, ExecuteOptions, JsonObject, JsonSchemaProperties, RpcExecuteConfig, ToolParameters, } from './types'; -import { DEFAULT_DEFENDER_CONFIG } from './types'; import type { BinaryDownloadResult } from './utils/binary-response'; import { StackOneError } from './utils/error-stackone'; @@ -168,15 +165,6 @@ interface StackOneToolSetBaseConfig extends BaseToolSetConfig { * Pass `{ accountIds: ['acc-1'] }` to scope tools to specific accounts. */ execute?: ExecuteToolsConfig; - /** - * Defender configuration. Controls prompt injection detection behavior for all tool calls. - * - * - Omit or pass `undefined` (default) → defer to the project dashboard setting - * - Pass `{ useProjectSettings: true }` → same as omitting; explicit form of the default - * - Pass `{ enabled, blockHighRisk, ... }` → explicit SDK-level config, overrides project settings - * - Pass `null` → defender explicitly disabled, overrides project settings - */ - defender?: DefenderConfig | null; } /** @@ -210,106 +198,6 @@ interface FetchToolsOptions { actions?: string[]; } -/** Wire-format defender config sent to the backend RPC action. */ -interface DefenderApiConfig { - enabled: boolean; - block_high_risk: boolean; - use_tier1_classification: boolean; - use_tier2_classification: boolean; -} - -/** Type guard: discriminate the `useProjectSettings: true` variant of DefenderConfig. */ -function usesProjectSettings(config: DefenderConfig): config is { useProjectSettings: true } { - return 'useProjectSettings' in config && config.useProjectSettings === true; -} - -/** - * Shapes already logged this process, keyed by mode + serialized wire payload. - * Ensures we surface one warning per distinct override shape, not per construction. - */ -const loggedDefenderShapes = new Set(); - -/** - * Test-only: clear the once-per-process dedupe cache for defender override warnings. - * @internal - */ -export function __resetDefenderInfoLog(): void { - loggedDefenderShapes.clear(); -} - -/** Wrap text in yellow ANSI, only when stderr is a TTY and color isn't suppressed. */ -function colorizeOverrideWarning(text: string): string { - if (process.env.NO_COLOR) return text; - if (!process.env.FORCE_COLOR && !process.stderr.isTTY) return text; - return `\x1b[33m${text}\x1b[0m`; -} - -/** - * Warn once when the SDK overrides the project dashboard's defender setting. - * Silent for `project` mode (no override) and for repeat constructions with the same shape. - */ -function logDefenderOverride( - config: DefenderConfig | null, - wireFields: { defender_config: DefenderApiConfig } | Record, -): void { - if (config === null) { - const key = 'disabled'; - if (loggedDefenderShapes.has(key)) return; - loggedDefenderShapes.add(key); - console.warn( - colorizeOverrideWarning( - 'Defender forcibly disabled via SDK config; project dashboard setting will be ignored.', - ), - ); - return; - } - if (usesProjectSettings(config)) return; - const key = `explicit:${JSON.stringify(wireFields)}`; - if (loggedDefenderShapes.has(key)) return; - loggedDefenderShapes.add(key); - const fields = (wireFields as { defender_config: DefenderApiConfig }).defender_config; - console.warn( - colorizeOverrideWarning( - `Defender configured via SDK (enabled=${fields.enabled}, blockHighRisk=${fields.block_high_risk}, useTier1Classification=${fields.use_tier1_classification}, useTier2Classification=${fields.use_tier2_classification}); project dashboard setting will be ignored.`, - ), - ); -} - -/** - * Map SDK DefenderConfig to the wire-format sent in the RPC body. - * - * - `null` → explicitly disabled (all fields false, overrides project setting) - * - `{ useProjectSettings: true }` → empty object (omitted from payload, project setting controls) - * - explicit object → wire format with missing fields filled from `DEFAULT_DEFENDER_CONFIG` - */ -function buildDefenderFields( - config: DefenderConfig | null, -): { defender_config: DefenderApiConfig } | Record { - if (config === null) { - return { - defender_config: { - enabled: false, - block_high_risk: false, - use_tier1_classification: false, - use_tier2_classification: false, - }, - }; - } - if (usesProjectSettings(config)) { - return {}; - } - return { - defender_config: { - enabled: config.enabled ?? DEFAULT_DEFENDER_CONFIG.enabled, - block_high_risk: config.blockHighRisk ?? DEFAULT_DEFENDER_CONFIG.blockHighRisk, - use_tier1_classification: - config.useTier1Classification ?? DEFAULT_DEFENDER_CONFIG.useTier1Classification, - use_tier2_classification: - config.useTier2Classification ?? DEFAULT_DEFENDER_CONFIG.useTier2Classification, - }, - }; -} - /** * Class for loading StackOne tools via MCP */ @@ -320,8 +208,6 @@ export class StackOneToolSet { private rpcClient?: RpcClient; private readonly timeout: number; private readonly executeConfig: ExecuteToolsConfig | undefined; - private readonly defenderConfig: DefenderConfig | null; - private readonly defenderFields: { defender_config: DefenderApiConfig } | Record; /** * Account ID for StackOne API @@ -382,25 +268,6 @@ export class StackOneToolSet { // Resolve search config: undefined/null → disabled, object → custom with defaults this.executeConfig = config?.execute; - // Resolve defender config: - // undefined → defer to project dashboard setting (normalized to { useProjectSettings: true }) - // null → explicitly disabled (overrides project setting) - // object → validate then store as-is - const defenderInput = config?.defender; - if ( - defenderInput != null && - typeof defenderInput === 'object' && - usesProjectSettings(defenderInput) && - Object.keys(defenderInput).length > 1 - ) { - throw new ToolSetConfigError( - 'Cannot combine useProjectSettings: true with explicit defender options. Use one or the other.', - ); - } - this.defenderConfig = - defenderInput === undefined ? { useProjectSettings: true } : defenderInput; - this.defenderFields = buildDefenderFields(this.defenderConfig); - logDefenderOverride(this.defenderConfig, this.defenderFields); // Set Authentication headers if provided if (this.authentication) { @@ -440,19 +307,6 @@ export class StackOneToolSet { private catalogCache: Map = new Map(); - /** - * Resolved defender behavior for this toolset. - * - * - `'project'` — SDK adds no `defender_config` to the RPC payload; the project dashboard controls. - * - `'disabled'` — SDK forces defender off (overrides the dashboard). - * - `'explicit'` — SDK sends an explicit `defender_config` (overrides the dashboard). - */ - get defenderMode(): DefenderMode { - if (this.defenderConfig === null) return 'disabled'; - if (usesProjectSettings(this.defenderConfig)) return 'project'; - return 'explicit'; - } - /** * Set account IDs for filtering tools * @param accountIds Array of account IDs to filter tools by @@ -750,7 +604,6 @@ export class StackOneToolSet { const requestPayload = { action: name, body: rpcBody, - ...this.defenderFields, headers: actionHeaders, path: pathParams ?? undefined, query: queryParams ?? undefined, @@ -768,7 +621,6 @@ export class StackOneToolSet { const response = await actionsClient.actions.rpcAction({ action: name, body: rpcBody, - ...this.defenderFields, headers: actionHeaders, path: pathParams ?? undefined, query: queryParams ?? undefined, diff --git a/src/types.ts b/src/types.ts index ac020d93..64215602 100644 --- a/src/types.ts +++ b/src/types.ts @@ -215,64 +215,3 @@ export interface ClaudeAgentSdkOptions { */ serverVersion?: string; } - -/** - * Defender configuration for controlling prompt injection detection behavior. - * Field names match the canonical `DefenderSettings` from `@stackone/core`. - * - * Four modes: - * - Omit `defender` entirely (default) — defer to whatever is configured in the project dashboard. - * The SDK sends no `defender_config` in the RPC payload, so the project setting controls behavior. - * - `{ useProjectSettings: true }` — same as omitting; provided as a self-documenting opt-in. - * No other fields may be set alongside this (TypeScript enforces it; a runtime error is also thrown). - * - An explicit config object — the SDK owns the defender settings and sends them with every - * RPC call, overriding any project-level config. - * - `null` — defender is explicitly disabled for all tool calls, overriding the project setting. - */ -export type DefenderConfig = - | { useProjectSettings: true } - | { - useProjectSettings?: false; - /** Whether to run defender at all. Default: `true`. */ - enabled?: boolean; - /** - * Whether to block tool execution when a HIGH risk score is detected. - * Default: `false` (scan and annotate, but do not block). - */ - blockHighRisk?: boolean; - /** Whether to enable tier 1 pattern-based (regex) detection. Default: `true`. */ - useTier1Classification?: boolean; - /** Whether to enable tier 2 ML-based detection. Default: `true`. */ - useTier2Classification?: boolean; - }; - -/** - * Reference values for a fully-enabled defender configuration with safe defaults - * (scan with both tiers, annotate but never block). - * - * Spread this into an explicit `defender` config to opt in with one tweak: - * ```ts - * defender: { ...DEFAULT_DEFENDER_CONFIG, blockHighRisk: true } - * ``` - * - * These values are also the per-field fallbacks applied when an explicit `defender` - * config object is passed with some fields omitted. - * - * Note: this is NOT applied when `defender` is omitted entirely — in that case the SDK - * defers to the project dashboard setting and sends no `defender_config` in the payload. - */ -export const DEFAULT_DEFENDER_CONFIG = { - enabled: true, - blockHighRisk: false, - useTier1Classification: true, - useTier2Classification: true, -} as const; - -/** - * Resolved defender behavior on a `StackOneToolSet`. - * - * - `'project'` — SDK adds no `defender_config` to the RPC payload; the project dashboard controls. - * - `'disabled'` — SDK forces defender off, overriding the dashboard. - * - `'explicit'` — SDK sends an explicit `defender_config`, overriding the dashboard. - */ -export type DefenderMode = 'project' | 'disabled' | 'explicit'; diff --git a/tests/examples/defender-config.test.ts b/tests/examples/defender-config.test.ts deleted file mode 100644 index 13368652..00000000 --- a/tests/examples/defender-config.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -/** - * E2E test for defender-config.ts example. - * - * Exercises the same defender configuration patterns the example - * demonstrates and asserts the resulting wire payloads via dryRun. - * Construction-time `defenderMode` and override-warning behavior is - * covered in `src/toolsets.test.ts`. - */ - -import { TEST_BASE_URL } from '../../mocks/constants'; -import { DEFAULT_DEFENDER_CONFIG, StackOneToolSet, ToolSetConfigError } from '../../src'; - -describe('defender-config example e2e', () => { - beforeEach(() => { - vi.stubEnv('STACKONE_API_KEY', 'test-key'); - // Silence override warnings so they don't pollute test output. - vi.spyOn(console, 'warn').mockImplementation(() => {}); - }); - - afterEach(() => { - vi.unstubAllEnvs(); - vi.restoreAllMocks(); - }); - - const fetchDummyTool = async (toolset: StackOneToolSet) => { - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'dummy_action tool should be defined in mocks'); - return tool; - }; - - it('omits defender_config when defender is not passed (mode 1)', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - accountId: 'test-account', - }); - expect(toolset.defenderMode).toBe('project'); - - const tool = await fetchDummyTool(toolset); - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody).not.toHaveProperty('defender_config'); - }); - - it('omits defender_config when defender is { useProjectSettings: true } (mode 2)', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - accountId: 'test-account', - defender: { useProjectSettings: true }, - }); - expect(toolset.defenderMode).toBe('project'); - - const tool = await fetchDummyTool(toolset); - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody).not.toHaveProperty('defender_config'); - }); - - it('sends all-false defender_config when defender is null (mode 3)', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - accountId: 'test-account', - defender: null, - }); - expect(toolset.defenderMode).toBe('disabled'); - - const tool = await fetchDummyTool(toolset); - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody.defender_config).toEqual({ - enabled: false, - block_high_risk: false, - use_tier1_classification: false, - use_tier2_classification: false, - }); - }); - - it('applies DEFAULT_DEFENDER_CONFIG fallbacks with explicit overrides (mode 4)', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - accountId: 'test-account', - defender: { ...DEFAULT_DEFENDER_CONFIG, blockHighRisk: true }, - }); - expect(toolset.defenderMode).toBe('explicit'); - - const tool = await fetchDummyTool(toolset); - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody.defender_config).toEqual({ - enabled: true, - block_high_risk: true, - use_tier1_classification: true, - use_tier2_classification: true, - }); - }); - - it('sends the exact explicit fields for a fully specified config (mode 6)', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - accountId: 'test-account', - defender: { - enabled: true, - blockHighRisk: false, - useTier1Classification: true, - useTier2Classification: false, - }, - }); - expect(toolset.defenderMode).toBe('explicit'); - - const tool = await fetchDummyTool(toolset); - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody.defender_config).toEqual({ - enabled: true, - block_high_risk: false, - use_tier1_classification: true, - use_tier2_classification: false, - }); - }); - - it('throws ToolSetConfigError when useProjectSettings is combined with other fields (mode 7)', () => { - expect( - () => - new StackOneToolSet({ - apiKey: 'demo-key', - // @ts-expect-error - intentionally testing invalid runtime input - defender: { useProjectSettings: true, enabled: true }, - }), - ).toThrow(ToolSetConfigError); - }); - - it('surfaces defenderMetadata alongside data in live RPC responses (mode 8)', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - accountId: 'test-account', - defender: { ...DEFAULT_DEFENDER_CONFIG, blockHighRisk: false }, - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'dummy_action tool should be defined in mocks'); - - const result = await tool.execute({ body: { name: 'test' } }); - const metadata = (result as { defenderMetadata?: Record }).defenderMetadata; - - expect(metadata).toBeDefined(); - assert(metadata, 'defenderMetadata should be defined'); - expect(metadata.applied).toBe(true); - expect(metadata.result).toMatchObject({ - allowed: true, - riskLevel: expect.stringMatching(/^(low|medium|high|critical)$/), - fieldsSanitized: expect.any(Array), - }); - }); -}); From ed777cdaf1a0e5043e02af66675d0d08122842f0 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:22:44 +0100 Subject: [PATCH 007/151] refactor!: remove the client-side feedback tool `fetchTools()` appended a `tool_feedback` tool that the SDK built itself and posted to `/ai/tool-feedback`. The server now serves a feedback tool of its own, `stackone_submit_feedback`, only when feedback is enabled for the project. A client-side stand-in reports success for feedback that goes nowhere when the project has it off, and it skewed every tool count by one. BREAKING CHANGE: `createFeedbackTool` is no longer exported and `fetchTools()` no longer appends a `tool_feedback` tool. Use the server-served `stackone_submit_feedback` tool (or the toolset's `submitFeedback()` method, added later in this series). --- README.md | 104 ---------- mocks/handlers.stackone-ai.ts | 11 -- src/feedback.test.ts | 301 ----------------------------- src/feedback.ts | 230 ---------------------- src/index.ts | 1 - src/toolsets.test.ts | 59 +++--- src/toolsets.ts | 9 +- tests/examples/fetch-tools.test.ts | 9 +- 8 files changed, 28 insertions(+), 696 deletions(-) delete mode 100644 src/feedback.test.ts delete mode 100644 src/feedback.ts diff --git a/README.md b/README.md index 9aaf9d47..b479dc79 100644 --- a/README.md +++ b/README.md @@ -371,110 +371,6 @@ The download result (typed `BinaryDownloadResult`) contains: > **Note:** `content` is a raw `Buffer`, not a `JsonValue`. `JSON.stringify` turns it into a `{ type: 'Buffer', data: [...] }` byte array (not the file, and potentially huge), so if you forward tool results to an LLM — or anything that re-serializes to JSON — strip or transform the `content` key first (for example, base64-encode it on the LLM-facing path). -### Feedback Collection Tool - -The StackOne AI SDK includes a built-in feedback collection tool (`tool_feedback`) that allows users to provide feedback on their experience with StackOne tools. This tool is automatically included when using `fetchTools()` and helps improve the SDK based on user input. - -#### How It Works - -The feedback tool: - -- **Requires explicit user consent** before submitting feedback -- **Collects user feedback** about their experience with StackOne tools -- **Tracks tool usage** by recording which tools were used -- **Submits to StackOne** via the `/ai/tool-feedback` endpoint -- **Uses the same API key** as other SDK operations for authentication - -#### Usage - -The feedback tool is automatically available when using `StackOneToolSet`: - -```typescript -import { StackOneToolSet } from '@stackone/ai'; - -const toolset = new StackOneToolSet(); -const tools = await toolset.fetchTools(); - -// The feedback tool is automatically included -const feedbackTool = tools.getTool('tool_feedback'); - -// Use with AI agents - they will ask for user consent first -const openAITools = tools.toOpenAI(); -// or -const aiSdkTools = await tools.toAISDK(); -``` - -#### Manual Usage - -You can also use the feedback tool directly: - -```typescript -// Get the feedback tool -const feedbackTool = tools.getTool('tool_feedback'); - -// Submit feedback (after getting user consent) -const result = await feedbackTool.execute({ - feedback: 'The tools worked great! Very easy to use.', - account_id: 'acc_123456', - tool_names: ['workday_list_workers', 'workday_create_time_off_request'], -}); -``` - -#### Multiple Account Support - -The feedback tool supports both single and multiple account IDs. When you provide an array of account IDs, the feedback will be sent to each account individually: - -```typescript -// Single account ID (string) -await feedbackTool.execute({ - feedback: 'The tools worked great! Very easy to use.', - account_id: 'acc_123456', - tool_names: ['workday_list_workers', 'workday_create_time_off_request'], -}); - -// Multiple account IDs (array) -await feedbackTool.execute({ - feedback: 'The tools worked great! Very easy to use.', - account_id: ['acc_123456', 'acc_789012'], - tool_names: ['workday_list_workers', 'workday_create_time_off_request'], -}); -``` - -**Response Format**: When using multiple account IDs, the tool returns a summary of all submissions: - -```typescript -{ - message: "Feedback sent to 2 account(s)", - total_accounts: 2, - successful: 2, - failed: 0, - results: [ - { - account_id: "acc_123456", - status: "success", - result: { message: "Feedback successfully stored", ... } - }, - { - account_id: "acc_789012", - status: "success", - result: { message: "Feedback successfully stored", ... } - } - ] -} -``` - -#### AI Agent Integration - -When AI agents use this tool, they will: - -1. **Ask for user consent**: "Are you ok with sending feedback to StackOne?" -2. **Collect feedback**: Get the user's verbatim feedback -3. **Track tool usage**: Record which tools were used in the session -4. **Submit to all accounts**: Send the same feedback to each account ID provided -5. **Report results**: Show which accounts received the feedback successfully - -The tool description includes clear instructions for AI agents to always ask for explicit user consent before submitting feedback. - ## Examples ### Running Examples diff --git a/mocks/handlers.stackone-ai.ts b/mocks/handlers.stackone-ai.ts index ca386773..06bc959b 100644 --- a/mocks/handlers.stackone-ai.ts +++ b/mocks/handlers.stackone-ai.ts @@ -20,17 +20,6 @@ export const stackoneAiHandlers = [ return HttpResponse.json({ error: 'Not found' }, { status: 404 }); }), - // StackOne AI tool feedback endpoint - http.post(`${TEST_BASE_URL}/ai/tool-feedback`, async ({ request }) => { - await request.json(); // Validate request body is JSON - return HttpResponse.json({ - message: 'Feedback successfully stored', - key: 'test-key.json', - submitted_at: new Date().toISOString(), - trace_id: 'test-trace-id', - }); - }), - // StackOne fetchTools endpoint for fetch-tools.ts example http.get(`${TEST_BASE_URL}/ai/tools`, () => { return HttpResponse.json({ diff --git a/src/feedback.test.ts b/src/feedback.test.ts deleted file mode 100644 index 54c4c351..00000000 --- a/src/feedback.test.ts +++ /dev/null @@ -1,301 +0,0 @@ -import { http, HttpResponse } from 'msw'; -import { server } from '../mocks/node'; -import { TEST_BASE_URL } from '../mocks/constants'; -import { createFeedbackTool } from './feedback'; -import { StackOneError } from './utils/error-stackone'; - -interface FeedbackResultItem { - account_id: string; - status: string; - result?: unknown; - error?: string; -} - -interface FeedbackResult { - message: string; - total_accounts: number; - successful: number; - failed: number; - results: FeedbackResultItem[]; -} - -describe('tool_feedback', () => { - describe('validation tests', () => { - it('test_missing_required_fields', async () => { - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - - // Test missing account_id - await expect( - tool.execute({ feedback: 'Great tools!', tool_names: ['test_tool'] }), - ).rejects.toBeInstanceOf(StackOneError); - - // Test missing tool_names - await expect( - tool.execute({ feedback: 'Great tools!', account_id: 'acc_123456' }), - ).rejects.toBeInstanceOf(StackOneError); - - // Test missing feedback - await expect( - tool.execute({ account_id: 'acc_123456', tool_names: ['test_tool'] }), - ).rejects.toBeInstanceOf(StackOneError); - }); - - it('test_empty_and_whitespace_validation', async () => { - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - - // Test empty feedback - await expect( - tool.execute({ feedback: '', account_id: 'acc_123456', tool_names: ['test_tool'] }), - ).rejects.toBeInstanceOf(StackOneError); - - // Test whitespace-only feedback - await expect( - tool.execute({ feedback: ' ', account_id: 'acc_123456', tool_names: ['test_tool'] }), - ).rejects.toBeInstanceOf(StackOneError); - - // Test empty account_id - await expect( - tool.execute({ feedback: 'Great tools!', account_id: '', tool_names: ['test_tool'] }), - ).rejects.toBeInstanceOf(StackOneError); - - // Test empty tool_names list - await expect( - tool.execute({ feedback: 'Great tools!', account_id: 'acc_123456', tool_names: [] }), - ).rejects.toBeInstanceOf(StackOneError); - - // Test tool_names with only whitespace - await expect( - tool.execute({ - feedback: 'Great tools!', - account_id: 'acc_123456', - tool_names: [' ', ' '], - }), - ).rejects.toBeInstanceOf(StackOneError); - }); - - it('test_multiple_account_ids_validation', async () => { - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - - // Test empty account ID list - await expect( - tool.execute({ - feedback: 'Great tools!', - account_id: [], - tool_names: ['test_tool'], - }), - ).rejects.toBeInstanceOf(StackOneError); - - // Test list with only empty strings - await expect( - tool.execute({ - feedback: 'Great tools!', - account_id: ['', ' '], - tool_names: ['test_tool'], - }), - ).rejects.toBeInstanceOf(StackOneError); - }); - - it('test_json_string_input', async () => { - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - const recordedRequests: Request[] = []; - const listener = ({ request }: { request: Request }) => { - recordedRequests.push(request); - }; - server.events.on('request:start', listener); - - // Test JSON string input - const jsonInput = JSON.stringify({ - feedback: 'Great tools!', - account_id: 'acc_123456', - tool_names: ['test_tool'], - }); - - const result = await tool.execute(jsonInput); - - expect(recordedRequests).toHaveLength(1); - expect(result).toMatchObject({ - message: 'Feedback sent to 1 account(s)', - total_accounts: 1, - successful: 1, - failed: 0, - }); - server.events.removeListener('request:start', listener); - }); - }); - - describe('execution tests', () => { - it('test_single_account_execution', async () => { - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - const recordedRequests: Request[] = []; - const listener = ({ request }: { request: Request }) => { - recordedRequests.push(request); - }; - server.events.on('request:start', listener); - - const result = await tool.execute({ - feedback: 'Great tools!', - account_id: 'acc_123456', - tool_names: ['data_export', 'analytics'], - }); - - expect(recordedRequests).toHaveLength(1); - expect(recordedRequests[0]?.url).toBe(`${TEST_BASE_URL}/ai/tool-feedback`); - expect(recordedRequests[0]?.method).toBe('POST'); - // TODO: Remove type assertion once createFeedbackTool returns properly typed result instead of JsonDict - const feedbackResult = result as unknown as FeedbackResult; - expect(feedbackResult).toMatchObject({ - message: 'Feedback sent to 1 account(s)', - total_accounts: 1, - successful: 1, - failed: 0, - }); - expect(feedbackResult.results[0]).toMatchObject({ - account_id: 'acc_123456', - status: 'success', - }); - expect(feedbackResult.results[0].result).toHaveProperty( - 'message', - 'Feedback successfully stored', - ); - server.events.removeListener('request:start', listener); - }); - - it('test_call_method_interface', async () => { - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - const recordedRequests: Request[] = []; - const listener = ({ request }: { request: Request }) => { - recordedRequests.push(request); - }; - server.events.on('request:start', listener); - - // Test using the tool directly (equivalent to .call() in Python) - const result = await tool.execute({ - feedback: 'Great tools!', - account_id: 'acc_123456', - tool_names: ['test_tool'], - }); - - expect(recordedRequests).toHaveLength(1); - expect(result).toMatchObject({ - message: 'Feedback sent to 1 account(s)', - total_accounts: 1, - successful: 1, - failed: 0, - }); - server.events.removeListener('request:start', listener); - }); - - it('test_api_error_handling', async () => { - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - - // Override the default handler to return an error - server.use( - http.post(`${TEST_BASE_URL}/ai/tool-feedback`, () => { - return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 }); - }), - ); - - await expect( - tool.execute({ - feedback: 'Great tools!', - account_id: 'acc_123456', - tool_names: ['test_tool'], - }), - ).rejects.toBeInstanceOf(StackOneError); - }); - - it('test_multiple_account_ids_execution', async () => { - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - - // Test all accounts succeed - const recordedRequests: Request[] = []; - const listener = ({ request }: { request: Request }) => { - recordedRequests.push(request); - }; - server.events.on('request:start', listener); - - const result = await tool.execute({ - feedback: 'Great tools!', - account_id: ['acc_123456', 'acc_789012', 'acc_345678'], - tool_names: ['test_tool'], - }); - - expect(recordedRequests).toHaveLength(3); - expect(result).toMatchObject({ - message: 'Feedback sent to 3 account(s)', - total_accounts: 3, - successful: 3, - failed: 0, - }); - server.events.removeListener('request:start', listener); - - // Test mixed success/error scenario - let callCount = 0; - server.use( - http.post(`${TEST_BASE_URL}/ai/tool-feedback`, () => { - callCount++; - if (callCount === 1) { - return HttpResponse.json({ message: 'Success' }); - } - return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 }); - }), - ); - - const mixedResult = await tool.execute({ - feedback: 'Great tools!', - account_id: ['acc_123456', 'acc_789012'], - tool_names: ['test_tool'], - }); - - expect(callCount).toBe(2); - // TODO: Remove type assertion once createFeedbackTool returns properly typed result instead of JsonDict - const mixedFeedbackResult = mixedResult as unknown as FeedbackResult; - expect(mixedFeedbackResult).toMatchObject({ - message: 'Feedback sent to 2 account(s)', - total_accounts: 2, - successful: 1, - failed: 1, - }); - - const successResult = mixedFeedbackResult.results.find((r) => r.account_id === 'acc_123456'); - const errorResult = mixedFeedbackResult.results.find((r) => r.account_id === 'acc_789012'); - - expect(successResult).toMatchObject({ - account_id: 'acc_123456', - status: 'success', - result: { message: 'Success' }, - }); - expect(errorResult).toMatchObject({ - account_id: 'acc_789012', - status: 'error', - error: '{"error":"Unauthorized"}', - }); - }); - - it('test_tool_integration', async () => { - // Test tool properties - const tool = createFeedbackTool(undefined, undefined, TEST_BASE_URL); - expect(tool.name).toBe('tool_feedback'); - expect(tool.description).toContain('Collects user feedback'); - expect(tool.parameters).toBeDefined(); - - // Test OpenAI function format conversion - const openaiFormat = tool.toOpenAI(); - expect(openaiFormat).toMatchObject({ - type: 'function', - function: { - name: 'tool_feedback', - description: expect.stringContaining('Collects user feedback'), - parameters: expect.objectContaining({ - type: 'object', - properties: expect.objectContaining({ - feedback: expect.any(Object), - account_id: expect.any(Object), - tool_names: expect.any(Object), - }), - }), - }, - }); - }); - }); -}); diff --git a/src/feedback.ts b/src/feedback.ts deleted file mode 100644 index 97b2b5ce..00000000 --- a/src/feedback.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { z } from 'zod/v4'; -import { DEFAULT_BASE_URL } from './consts'; -import { BaseTool } from './tool'; -import type { ExecuteConfig, ExecuteOptions, JsonObject, JsonValue, ToolParameters } from './types'; -import { StackOneError } from './utils/error-stackone'; - -interface FeedbackToolOptions { - baseUrl?: string; - apiKey?: string; - accountId?: string; -} - -const createNonEmptyTrimmedStringSchema = (fieldName: string) => - z - .string() - .transform((value) => value.trim()) - .refine((value) => value.length > 0, { - message: `${fieldName} must be a non-empty string.`, - }); - -const feedbackInputSchema = z.object({ - feedback: createNonEmptyTrimmedStringSchema('Feedback'), - account_id: z - .union([ - createNonEmptyTrimmedStringSchema('Account ID'), - z - .array(createNonEmptyTrimmedStringSchema('Account ID')) - .min(1, 'At least one account ID is required'), - ]) - .transform((value) => (Array.isArray(value) ? value : [value])), - tool_names: z - .array(z.string()) - .min(1, 'At least one tool name is required') - .transform((value) => value.map((item) => item.trim()).filter((item) => item.length > 0)) - .refine((value) => value.length > 0, { - message: 'Tool names must contain at least one non-empty string', - }), -}); - -export function createFeedbackTool( - apiKey?: string, - accountId?: string, - baseUrl = DEFAULT_BASE_URL, -): BaseTool { - const options: FeedbackToolOptions = { - apiKey, - accountId, - baseUrl, - }; - const name = 'tool_feedback' as const; - const description = - 'Collects user feedback on StackOne tool performance. First ask the user, "Are you ok with sending feedback to StackOne?" and mention that the LLM will take care of sending it. Call this tool only when the user explicitly answers yes.'; - const parameters = { - type: 'object', - properties: { - account_id: { - oneOf: [ - { - type: 'string', - description: 'Single account identifier (e.g., "acc_123456")', - }, - { - type: 'array', - items: { - type: 'string', - }, - description: 'Array of account identifiers (e.g., ["acc_123456", "acc_789012"])', - }, - ], - description: 'Account identifier(s) - can be a single string or array of strings', - }, - feedback: { - type: 'string', - description: 'Verbatim feedback from the user about their experience with StackOne tools.', - }, - tool_names: { - type: 'array', - items: { - type: 'string', - }, - description: 'Array of tool names being reviewed', - }, - }, - required: ['feedback', 'account_id', 'tool_names'], - } as const satisfies ToolParameters; - - const executeConfig = { - kind: 'http', - method: 'POST', - url: '/ai/tool-feedback', - bodyType: 'json', - params: [], - } as const satisfies ExecuteConfig; - - // Get API key from environment or options - const resolvedApiKey = options.apiKey || process.env.STACKONE_API_KEY; - - // Create authentication headers - const authHeaders: Record = {}; - if (resolvedApiKey) { - const authString = Buffer.from(`${resolvedApiKey}:`).toString('base64'); - authHeaders.Authorization = `Basic ${authString}`; - } - - const tool = new BaseTool(name, description, parameters, executeConfig, authHeaders); - const resolvedBaseUrl = options.baseUrl ?? DEFAULT_BASE_URL; - - tool.execute = async function ( - this: BaseTool, - inputParams?: JsonObject | string, - executeOptions?: ExecuteOptions, - ): Promise { - try { - const rawParams = - typeof inputParams === 'string' ? JSON.parse(inputParams) : inputParams || {}; - const parsedParams = feedbackInputSchema.parse(rawParams); - - const headers = { - Accept: 'application/json', - 'Content-Type': 'application/json', - ...this.getHeaders(), - }; - - // Handle dry run - show what would be sent to each account - if (executeOptions?.dryRun) { - const dryRunResults = parsedParams.account_id.map((accountId: string) => ({ - url: `${resolvedBaseUrl}${executeConfig.url}`, - method: executeConfig.method, - headers, - body: { - feedback: parsedParams.feedback, - account_id: accountId, - tool_names: parsedParams.tool_names, - }, - })); - - return { - multiple_requests: dryRunResults, - total_accounts: parsedParams.account_id.length, - } satisfies JsonObject; - } - - // Send feedback to each account individually - const results: Array<{ account_id: string; status: number; response: JsonValue }> = []; - const errors: Array<{ account_id: string; status?: number; error: string }> = []; - - for (const accountId of parsedParams.account_id) { - try { - const requestBody = { - feedback: parsedParams.feedback, - account_id: accountId, - tool_names: parsedParams.tool_names, - }; - - const response = await fetch(`${resolvedBaseUrl}${executeConfig.url}`, { - method: executeConfig.method satisfies 'POST', - headers, - body: JSON.stringify(requestBody), - }); - - const text = await response.text(); - let parsed: JsonValue; - try { - parsed = text ? (JSON.parse(text) satisfies JsonValue) : {}; - } catch { - parsed = { raw: text }; - } - - if (!response.ok) { - errors.push({ - account_id: accountId, - status: response.status, - error: - typeof parsed === 'object' && parsed !== null - ? JSON.stringify(parsed) - : String(parsed), - }); - } else { - results.push({ - account_id: accountId, - status: response.status, - response: parsed, - }); - } - } catch (error) { - errors.push({ - account_id: accountId, - error: error instanceof Error ? error.message : String(error), - }); - } - } - - // Return summary of all submissions in Python SDK format - const response = { - message: `Feedback sent to ${parsedParams.account_id.length} account(s)`, - total_accounts: parsedParams.account_id.length, - successful: results.length, - failed: errors.length, - results: [ - ...results.map((r) => ({ - account_id: r.account_id, - status: 'success', - result: r.response, - })), - ...errors.map((e) => ({ - account_id: e.account_id, - status: 'error', - error: e.error, - })), - ], - } satisfies JsonObject; - - // If all submissions failed, throw an error - if (errors.length > 0 && results.length === 0) { - throw new StackOneError( - `Failed to submit feedback to any account. Errors: ${JSON.stringify(errors)}`, - ); - } - - return response; - } catch (error) { - if (error instanceof StackOneError) { - throw error; - } - throw new StackOneError('Error executing tool', { cause: error }); - } - }; - - return tool; -} diff --git a/src/index.ts b/src/index.ts index 0fd0bbcf..112a5a19 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,7 +3,6 @@ */ export { BaseTool, StackOneTool, Tools } from './tool'; -export { createFeedbackTool } from './feedback'; export { isBinaryDownloadResult, type BinaryDownloadResult } from './utils/binary-response'; export { StackOneError } from './utils/error-stackone'; export { StackOneAPIError } from './utils/error-stackone-api'; diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 52121106..715a6803 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -233,8 +233,8 @@ describe('StackOneToolSet', () => { }); const tools = await toolset.fetchTools(); - // 1 dummy_action tool + 1 feedback tool - expect(tools.length).toBe(2); + // 1 dummy_action tool + expect(tools.length).toBe(1); const tool = tools.toArray().find((t) => t.name === 'dummy_action'); expect(tool).toBeDefined(); @@ -294,12 +294,11 @@ describe('StackOneToolSet', () => { }); const tools = await toolset.fetchTools(); - // 2 default tools + 1 feedback tool - expect(tools.length).toBe(3); + // 2 default tools + expect(tools.length).toBe(2); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('default_tool_1'); expect(toolNames).toContain('default_tool_2'); - expect(toolNames).toContain('tool_feedback'); }); it('uses x-account-id header when fetching tools with accountIds', async () => { @@ -310,12 +309,11 @@ describe('StackOneToolSet', () => { // Fetch tools for acc1 const tools = await toolset.fetchTools({ accountIds: ['acc1'] }); - // 2 acc1 tools + 1 feedback tool - expect(tools.length).toBe(3); + // 2 acc1 tools + expect(tools.length).toBe(2); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('acc1_tool_1'); expect(toolNames).toContain('acc1_tool_2'); - expect(toolNames).toContain('tool_feedback'); }); it('uses setAccounts when no accountIds provided in fetchTools', async () => { @@ -331,14 +329,13 @@ describe('StackOneToolSet', () => { const tools = await toolset.fetchTools(); // Should fetch tools for 2 accounts from setAccounts - // acc1 has 2 tools, acc2 has 2 tools, + 1 feedback tool = 5 - expect(tools.length).toBe(5); + // acc1 has 2 tools, acc2 has 2 tools + expect(tools.length).toBe(4); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('acc1_tool_1'); expect(toolNames).toContain('acc1_tool_2'); expect(toolNames).toContain('acc2_tool_1'); expect(toolNames).toContain('acc2_tool_2'); - expect(toolNames).toContain('tool_feedback'); }); it('uses accountIds from constructor when no accountIds provided in fetchTools', async () => { @@ -352,14 +349,13 @@ describe('StackOneToolSet', () => { const tools = await toolset.fetchTools(); // Should fetch tools for 2 accounts from constructor - // acc1 has 2 tools, acc2 has 2 tools, + 1 feedback tool = 5 - expect(tools.length).toBe(5); + // acc1 has 2 tools, acc2 has 2 tools + expect(tools.length).toBe(4); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('acc1_tool_1'); expect(toolNames).toContain('acc1_tool_2'); expect(toolNames).toContain('acc2_tool_1'); expect(toolNames).toContain('acc2_tool_2'); - expect(toolNames).toContain('tool_feedback'); }); it('setAccounts overrides constructor accountIds', async () => { @@ -376,14 +372,13 @@ describe('StackOneToolSet', () => { const tools = await toolset.fetchTools(); // Should fetch tools for acc2 and acc3 (not acc1) - // acc2 has 2 tools, acc3 has 1 tool, + 1 feedback tool = 4 - expect(tools.length).toBe(4); + // acc2 has 2 tools, acc3 has 1 tool + expect(tools.length).toBe(3); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).not.toContain('acc1_tool_1'); expect(toolNames).toContain('acc2_tool_1'); expect(toolNames).toContain('acc2_tool_2'); expect(toolNames).toContain('acc3_tool_1'); - expect(toolNames).toContain('tool_feedback'); }); it('overrides setAccounts when accountIds provided in fetchTools', async () => { @@ -398,11 +393,10 @@ describe('StackOneToolSet', () => { // Fetch with accountIds - should override setAccounts const tools = await toolset.fetchTools({ accountIds: ['acc3'] }); - // Should fetch tools only for acc3 (ignoring acc1, acc2) + 1 feedback tool - expect(tools.length).toBe(2); + // Should fetch tools only for acc3 (ignoring acc1, acc2) + expect(tools.length).toBe(1); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('acc3_tool_1'); - expect(toolNames).toContain('tool_feedback'); }); // Regression for issue #365: tools must carry the x-account-id of the @@ -689,15 +683,14 @@ describe('StackOneToolSet', () => { // Filter by providers const tools = await toolset.fetchTools({ providers: ['hibob', 'bamboohr'] }); - // 4 filtered tools + 1 feedback tool - expect(tools.length).toBe(5); + // 4 filtered tools + expect(tools.length).toBe(4); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('hibob_list_employees'); expect(toolNames).toContain('hibob_create_employees'); expect(toolNames).toContain('bamboohr_list_employees'); expect(toolNames).toContain('bamboohr_get_employee'); expect(toolNames).not.toContain('workday_list_employees'); - expect(toolNames).toContain('tool_feedback'); }); it('filters tools by actions with exact match', async () => { @@ -712,12 +705,11 @@ describe('StackOneToolSet', () => { actions: ['hibob_list_employees', 'hibob_create_employees'], }); - // 2 filtered tools + 1 feedback tool - expect(tools.length).toBe(3); + // 2 filtered tools + expect(tools.length).toBe(2); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('hibob_list_employees'); expect(toolNames).toContain('hibob_create_employees'); - expect(toolNames).toContain('tool_feedback'); }); it('filters tools by actions with glob pattern', async () => { @@ -730,15 +722,14 @@ describe('StackOneToolSet', () => { // Filter by glob pattern const tools = await toolset.fetchTools({ actions: ['*_list_employees'] }); - // 3 filtered tools + 1 feedback tool - expect(tools.length).toBe(4); + // 3 filtered tools + expect(tools.length).toBe(3); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('hibob_list_employees'); expect(toolNames).toContain('bamboohr_list_employees'); expect(toolNames).toContain('workday_list_employees'); expect(toolNames).not.toContain('hibob_create_employees'); expect(toolNames).not.toContain('bamboohr_get_employee'); - expect(toolNames).toContain('tool_feedback'); }); it('combines accountIds and actions filters', async () => { @@ -806,14 +797,13 @@ describe('StackOneToolSet', () => { actions: ['*_list_employees'], }); - // 2 filtered tools + 1 feedback tool - expect(tools.length).toBe(3); + // 2 filtered tools + expect(tools.length).toBe(2); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('hibob_list_employees'); expect(toolNames).toContain('bamboohr_list_employees'); expect(toolNames).not.toContain('hibob_create_employees'); expect(toolNames).not.toContain('bamboohr_get_employee'); - expect(toolNames).toContain('tool_feedback'); }); it('combines all filters: accountIds, providers, and actions', async () => { @@ -869,11 +859,10 @@ describe('StackOneToolSet', () => { actions: ['*_list_*'], }); - // Should only return hibob_list_employees (matches all filters) + 1 feedback tool - expect(tools.length).toBe(2); + // Should only return hibob_list_employees (matches all filters) + expect(tools.length).toBe(1); const toolNames = tools.toArray().map((t) => t.name); expect(toolNames).toContain('hibob_list_employees'); - expect(toolNames).toContain('tool_feedback'); }); }); diff --git a/src/toolsets.ts b/src/toolsets.ts index 15d5f65c..3183ee4d 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -1,7 +1,6 @@ import { defu } from 'defu'; import type { MergeExclusive, SimplifyDeep } from 'type-fest'; import { DEFAULT_BASE_URL } from './consts'; -import { createFeedbackTool } from './feedback'; import { type StackOneHeaders, normalizeHeaders, stackOneHeadersSchema } from './headers'; import { createMCPClient } from './mcp-client'; import { type RpcActionResponse, RpcClient } from './rpc-client'; @@ -411,12 +410,8 @@ export class StackOneToolSet { // Apply provider and action filters const filteredTools = this.filterTools(tools, options); - // Add feedback tool - const feedbackTool = createFeedbackTool(undefined, this.accountId, this.baseUrl); - const toolsWithFeedback = new Tools([...filteredTools.toArray(), feedbackTool]); - - this.catalogCache.set(cacheKey, toolsWithFeedback); - return toolsWithFeedback; + this.catalogCache.set(cacheKey, filteredTools); + return filteredTools; } /** diff --git a/tests/examples/fetch-tools.test.ts b/tests/examples/fetch-tools.test.ts index 37bb6f76..4f2fad5b 100644 --- a/tests/examples/fetch-tools.test.ts +++ b/tests/examples/fetch-tools.test.ts @@ -66,9 +66,7 @@ describe('fetch-tools example e2e', () => { }); expect(toolsByProviders.length).toBeGreaterThan(0); const providerToolNames = toolsByProviders.toArray().map((t) => t.name); - expect( - providerToolNames.every((name) => name.startsWith('bamboohr_') || name.startsWith('tool_')), - ).toBe(true); + expect(providerToolNames.every((name) => name.startsWith('bamboohr_'))).toBe(true); // Example 5: Filter by actions with exact match const toolsByActions = await toolset.fetchTools({ @@ -84,10 +82,7 @@ describe('fetch-tools example e2e', () => { accountIds: ['your-bamboohr-account-id'], actions: ['*_list_employees'], }); - const globToolNames = toolsByGlobPattern - .toArray() - .filter((t) => !t.name.startsWith('tool_')) - .map((t) => t.name); + const globToolNames = toolsByGlobPattern.toArray().map((t) => t.name); expect(globToolNames).toContain('bamboohr_list_employees'); // Execute a tool From e66ab64e2b80a54082ec2bbac8216be8cec0e22b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:25:08 +0100 Subject: [PATCH 008/151] fix(toolsets)!: stop model-supplied headers from switching tenant The RPC tool merged the envelope's headers OVER its own with `defu(extraHeaders, baseHeaders)`. Tool arguments are model-controlled, so a call carrying `headers_x-account-id` (or a nested `headers` object) replaced the account the tool was fetched for, both in the envelope and in the `x-account-id` HTTP header the API reads: a prompt injection could run any action against any tenant the API key reaches. - Filter model-supplied headers through an allowlist built from the served schema's own `headers_*` properties, compared trimmed and case-insensitively, and reject values carrying CR/LF or other control characters. - Apply the SDK's own headers after the merge, so `x-account-id` is always the tool's account. - Serve the mock catalog through a low-level MCP `Server`. `McpServer` expects a Zod shape and listed every JSON Schema as `properties: {}`, so the tests never saw a declared parameter. Regression tests cover the flat and nested injection paths and a declared header that must survive. BREAKING CHANGE: headers a tool call supplies are dropped unless the tool's served schema declares them as a `headers_` property. Undeclared headers were previously forwarded in the RPC envelope. --- mocks/mcp-server.ts | 32 ++++++++---------- src/headers.test.ts | 56 +++++++++++++++++++++++++++++++- src/headers.ts | 62 +++++++++++++++++++++++++++++++++++ src/toolsets.test.ts | 77 ++++++++++++++++++++++++++++++++++++++++++-- src/toolsets.ts | 18 ++++++++--- src/utils/logger.ts | 11 +++++++ 6 files changed, 229 insertions(+), 27 deletions(-) create mode 100644 src/utils/logger.ts diff --git a/mocks/mcp-server.ts b/mocks/mcp-server.ts index 24a53258..c65146ec 100644 --- a/mocks/mcp-server.ts +++ b/mocks/mcp-server.ts @@ -5,7 +5,8 @@ */ import type { Hono as HonoApp } from 'hono'; import { StreamableHTTPTransport } from '@hono/mcp'; -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; import { Hono } from 'hono'; import { basicAuth } from 'hono/basic-auth'; @@ -17,6 +18,7 @@ export interface McpToolDefinition { properties?: Record; required?: string[]; additionalProperties?: boolean; + [keyword: string]: unknown; }; } @@ -65,26 +67,18 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { const accountId = c.req.header('x-account-id') ?? 'default'; const tools = accountTools[accountId] ?? accountTools.default ?? []; - // Create a new MCP server instance per request - const mcp = new McpServer({ name: 'test-mcp-server', version: '1.0.0' }); + // A low-level Server rather than McpServer: McpServer.registerTool expects a Zod shape + // and lists a plain JSON Schema as `properties: {}`, so every tool used to reach the SDK + // with no parameters at all. The real endpoint serves each schema verbatim. + const mcp = new Server({ name: 'test-mcp-server', version: '1.0.0' }, { capabilities: { tools: {} } }); const transport = new StreamableHTTPTransport(); - for (const tool of tools) { - mcp.registerTool( - tool.name, - { - description: tool.description, - // MCP SDK expects Zod-like schema but accepts JSON Schema objects - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- MCP SDK type mismatch - inputSchema: tool.inputSchema as any, - }, - async ({ params }: { params: { arguments?: Record } }) => ({ - content: [], - structuredContent: params.arguments ?? {}, - _meta: undefined, - }), - ); - } + mcp.setRequestHandler(ListToolsRequestSchema, () => ({ + tools: tools.map((tool) => ({ ...tool, inputSchema: structuredClone(tool.inputSchema) })), + })); + mcp.setRequestHandler(CallToolRequestSchema, (request) => ({ + content: [{ type: 'text' as const, text: JSON.stringify(request.params.arguments ?? {}) }], + })); await mcp.connect(transport); return transport.handleRequest(c); diff --git a/src/headers.test.ts b/src/headers.test.ts index 3bb4f099..95f7f3cc 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -1,4 +1,4 @@ -import { normalizeHeaders } from './headers'; +import { declaredHeaderNames, normalizeHeaders, sanitiseHeaders } from './headers'; describe('normalizeHeaders', () => { it('returns empty object for undefined input', () => { @@ -67,3 +67,57 @@ describe('normalizeHeaders', () => { }); }); }); + +describe('sanitiseHeaders', () => { + const allowed = declaredHeaderNames(['headers_x-trace', 'query_limit', 'body_headers_x']); + + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('builds the allowlist from headers_* properties only, lower-cased', () => { + expect(declaredHeaderNames(['headers_X-Trace', 'query_limit', 'body_headers_x'])).toEqual( + new Set(['x-trace']), + ); + }); + + it('drops every header the served schema does not declare', () => { + expect( + sanitiseHeaders( + { + Authorization: 'Bearer stolen', + 'Proxy-Authorization': 'Basic stolen', + 'x-account-id': 'victim', + 'x-stackone-account-id': 'victim', + Cookie: 'session=x', + 'X-Api-Key': 'stolen', + }, + allowed, + ), + ).toEqual({}); + }); + + it.each([' x-trace', 'X-TRACE\t', 'X-Trace'])('matches %j case- and whitespace-insensitively', (name) => { + expect(sanitiseHeaders({ [name]: 'abc' }, allowed)).toEqual({ [name.trim()]: 'abc' }); + }); + + it.each(['a\r\nEvil: 1', 'trailing\n', 'bad\rvalue', 'nul\u0000byte', 'wide\u0100char'])( + 'drops a declared header whose value is %j', + (value) => { + expect(sanitiseHeaders({ 'X-Trace': value }, allowed)).toEqual({}); + }, + ); + + it('stringifies scalar values and skips nulls', () => { + expect(sanitiseHeaders({ 'x-trace': 42 }, allowed)).toEqual({ 'x-trace': '42' }); + expect(sanitiseHeaders({ 'x-trace': null }, allowed)).toEqual({}); + }); + + it('warns once per dropped header', () => { + sanitiseHeaders({ Authorization: 'x', 'X-Trace': 'bad\n' }, allowed); + expect(console.warn).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/headers.ts b/src/headers.ts index 76eec146..c79e9b7d 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -1,5 +1,6 @@ import { z } from 'zod/v4-mini'; import type { JsonObject } from './types'; +import { warn } from './utils/logger'; /** * Known StackOne API header keys that are forwarded as HTTP headers @@ -44,3 +45,64 @@ export function normalizeHeaders(headers: JsonObject | undefined): StackOneHeade } return stackOneHeadersSchema.parse(result); } + +/** An RFC 9110 header field name (`token`). */ +const HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/; + +/** + * A header field value: visible ASCII, space, tab and obs-text. Excludes CR and LF, so a value + * cannot smuggle a second header line. Anchored with `^…$` and no `m` flag, so a trailing + * newline cannot slip past the way it does under Python's `re.match(…$)`. + */ +const HEADER_VALUE_PATTERN = /^[\x20-\x7e\t\x80-\xff]*$/; + +const DECLARED_HEADER_PREFIX = 'headers_'; + +/** + * The header names a served tool schema declares, lower-cased. + * + * Under `param-style=flat_prefixed` a header parameter is served as a `headers_` + * property, so the schema itself is the allowlist. Nothing needs maintaining in the SDK: an + * action that starts declaring a header works without a release. + */ +export function declaredHeaderNames(propertyNames: Iterable): Set { + const allowed = new Set(); + for (const name of propertyNames) { + if (name.startsWith(DECLARED_HEADER_PREFIX)) { + allowed.add(name.slice(DECLARED_HEADER_PREFIX.length).toLowerCase()); + } + } + return allowed; +} + +/** + * Keep only the headers the served schema declared, and only with well-formed values. + * + * An allowlist, not a denylist. Tool arguments are model-controlled, so a prompt-injected call + * reaches this object directly — and a denylist has to enumerate every synonym of "credential" + * and "tenant selector" (`Proxy-Authorization`, `x-stackone-account-id`, `Cookie`, + * `X-Api-Key`, …) and is wrong the moment one is missed. + * + * Names are compared trimmed and case-insensitively: `" x-account-id "` and `"X-ACCOUNT-ID"` + * are the same header to any server. The value check runs only for a declared header, which + * is exactly where a model-supplied value needs it. + */ +export function sanitiseHeaders( + supplied: JsonObject | undefined, + allowed: ReadonlySet, +): Record { + const clean: Record = {}; + for (const [key, value] of Object.entries(normalizeHeaders(supplied))) { + const name = key.trim(); + if (!allowed.has(name.toLowerCase())) { + warn(`Dropping header "${name}" from a tool call: no served schema declares it`); + continue; + } + if (!HEADER_NAME_PATTERN.test(name) || !HEADER_VALUE_PATTERN.test(value)) { + warn(`Dropping malformed header "${name}" from a tool call`); + continue; + } + clean[name] = value; + } + return clean; +} diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 715a6803..4868509a 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -7,7 +7,7 @@ * - Account filtering * - Provider and action filtering */ -import { http } from 'msw'; +import { http, HttpResponse } from 'msw'; import { type McpToolDefinition, createMcpApp, defaultMcpTools } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { TEST_BASE_URL } from '../mocks/constants'; @@ -599,7 +599,8 @@ describe('StackOneToolSet', () => { expect(payload.path).toEqual({ id: '123' }); expect(payload.query).toEqual({ limit: 10 }); expect(payload.body).toEqual({ name: 'test' }); - expect((result.headers as Record)['x-custom']).toBe('value'); + // dummy_action declares no `headers_*` property, so the header is dropped. + expect(result.headers as Record).not.toHaveProperty('x-custom'); }); it('preserves fields named after Object.prototype members', async () => { @@ -672,6 +673,78 @@ describe('StackOneToolSet', () => { }); }); + describe('model-supplied headers', () => { + const serveTool = (inputSchema: McpToolDefinition['inputSchema']) => { + const app = createMcpApp({ + accountTools: { + 'tenant-a': [{ name: 'crm_list_contacts', description: 'List contacts', inputSchema }], + }, + }); + server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); + }; + const captureRpc = () => { + const seen: { accountHeader: string | null; body: Record }[] = []; + server.use( + http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { + seen.push({ + accountHeader: request.headers.get('x-account-id'), + body: (await request.json()) as Record, + }); + return HttpResponse.json({ data: {} }); + }), + ); + return seen; + }; + const fetchTool = async () => { + const toolset = new StackOneToolSet({ + baseUrl: TEST_BASE_URL, + apiKey: 'test-key', + accountId: 'tenant-a', + }); + const tool = (await toolset.fetchTools()).getTool('crm_list_contacts'); + assert(tool, 'tool should be listed'); + return tool; + }; + + // Regression: the envelope headers were merged OVER the tool's own headers, so a + // model-supplied x-account-id replaced the account the tool was fetched for — on the + // envelope and on the HTTP header the API actually reads. + it('cannot switch tenant with headers_x-account-id, even when the schema declares it', async () => { + serveTool({ + type: 'object', + properties: { 'headers_x-account-id': { type: 'string' }, query_limit: { type: 'number' } }, + }); + const seen = captureRpc(); + const tool = await fetchTool(); + + await tool.execute({ 'headers_x-account-id': 'tenant-b', query_limit: 1 }); + + expect(seen[0]?.accountHeader).toBe('tenant-a'); + expect((seen[0]?.body.headers as Record)['x-account-id']).toBe('tenant-a'); + }); + + it('cannot switch tenant with a nested headers object', async () => { + serveTool({ type: 'object', properties: { query_limit: { type: 'number' } } }); + const seen = captureRpc(); + const tool = await fetchTool(); + + await tool.execute({ headers: { 'X-Account-Id': 'tenant-b', Authorization: 'Bearer stolen' } }); + + expect(seen[0]?.accountHeader).toBe('tenant-a'); + expect(seen[0]?.body.headers).toEqual({ 'x-account-id': 'tenant-a' }); + }); + + it('forwards a header the served schema declares', async () => { + serveTool({ type: 'object', properties: { 'headers_x-trace': { type: 'string' } } }); + const seen = captureRpc(); + const tool = await fetchTool(); + + await tool.execute({ 'headers_x-trace': 'abc', 'headers_x-other': 'dropped' }); + + expect(seen[0]?.body.headers).toEqual({ 'x-trace': 'abc', 'x-account-id': 'tenant-a' }); + }); + }); + describe('provider and action filtering', () => { it('filters tools by providers', async () => { const toolset = new StackOneToolSet({ diff --git a/src/toolsets.ts b/src/toolsets.ts index 3183ee4d..f7f4c8b9 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -1,7 +1,11 @@ -import { defu } from 'defu'; import type { MergeExclusive, SimplifyDeep } from 'type-fest'; import { DEFAULT_BASE_URL } from './consts'; -import { type StackOneHeaders, normalizeHeaders, stackOneHeadersSchema } from './headers'; +import { + type StackOneHeaders, + declaredHeaderNames, + sanitiseHeaders, + stackOneHeadersSchema, +} from './headers'; import { createMCPClient } from './mcp-client'; import { type RpcActionResponse, RpcClient } from './rpc-client'; import { BaseTool, Tools } from './tool'; @@ -557,6 +561,8 @@ export class StackOneToolSet { properties: inputSchema?.properties as JsonSchemaProperties, } satisfies ToolParameters; + const declaredHeaders = declaredHeaderNames(Object.keys(toolParameters.properties ?? {})); + const tool = new BaseTool( name, description ?? '', @@ -589,9 +595,11 @@ export class StackOneToolSet { const envelope = this.splitEnvelopeParams(parsedParams); const pathParams = envelope.path; const queryParams = envelope.query; - const extraHeaders = normalizeHeaders(envelope.headers); - // defu merges extraHeaders into baseHeaders, both are already branded types - const actionHeaders = defu(extraHeaders, baseHeaders); + // Model-supplied headers are filtered to the ones the served schema declares, and + // the SDK's own headers are applied LAST. Merging the other way round let a tool + // call carry `headers_x-account-id` and switch the request to another tenant. + const allowedHeaders = sanitiseHeaders(envelope.headers, declaredHeaders); + const actionHeaders = stackOneHeadersSchema.parse({ ...allowedHeaders, ...baseHeaders }); const rpcBody: JsonObject = envelope.body; diff --git a/src/utils/logger.ts b/src/utils/logger.ts new file mode 100644 index 00000000..5c727f76 --- /dev/null +++ b/src/utils/logger.ts @@ -0,0 +1,11 @@ +/** + * The SDK's single diagnostic channel. + * + * Everything the SDK wants a developer to notice without failing the call — a dropped + * header, a skipped account, a clashing tool name — goes through here, so a host can + * silence or redirect it by stubbing `console.warn` in one place. + */ +export function warn(message: string): void { + // oxlint-disable-next-line no-console -- the one intentional console sink in the SDK + console.warn(`[@stackone/ai] ${message}`); +} From 527549d3ab6070cce81e82e1b094e609be72a46e Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:25:53 +0100 Subject: [PATCH 009/151] refactor!: root every SDK error at StackOneError `ToolSetError`, `ToolSetConfigError` and `ToolSetLoadError` extended `Error` directly, so `error instanceof StackOneError` missed the two errors a user is most likely to hit first: a missing API key and a catalog that will not load. They now extend `StackOneError`, alongside `StackOneAPIError`, and live in `src/utils/error-toolset.ts`. BREAKING CHANGE: `ToolSetError` (and so `ToolSetConfigError` and `ToolSetLoadError`) now extends `StackOneError`. Code that distinguished the two with `instanceof StackOneError` must check the toolset errors first. --- src/index.ts | 5 ++--- src/toolsets.test.ts | 3 ++- src/toolsets.ts | 31 +--------------------------- src/utils/error-toolset.test.ts | 27 +++++++++++++++++++++++++ src/utils/error-toolset.ts | 36 +++++++++++++++++++++++++++++++++ 5 files changed, 68 insertions(+), 34 deletions(-) create mode 100644 src/utils/error-toolset.test.ts create mode 100644 src/utils/error-toolset.ts diff --git a/src/index.ts b/src/index.ts index 112a5a19..498f8b25 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,11 +7,10 @@ export { isBinaryDownloadResult, type BinaryDownloadResult } from './utils/binar export { StackOneError } from './utils/error-stackone'; export { StackOneAPIError } from './utils/error-stackone-api'; +export { ToolSetConfigError, ToolSetError, ToolSetLoadError } from './utils/error-toolset'; + export { StackOneToolSet, - ToolSetConfigError, - ToolSetError, - ToolSetLoadError, type AuthenticationConfig, type BaseToolSetConfig, type ExecuteToolsConfig, diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 4868509a..d57e6a9a 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -11,7 +11,8 @@ import { http, HttpResponse } from 'msw'; import { type McpToolDefinition, createMcpApp, defaultMcpTools } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { TEST_BASE_URL } from '../mocks/constants'; -import { StackOneToolSet, ToolSetConfigError } from './toolsets'; +import { StackOneToolSet } from './toolsets'; +import { ToolSetConfigError } from './utils/error-toolset'; describe('StackOneToolSet', () => { beforeEach(() => { diff --git a/src/toolsets.ts b/src/toolsets.ts index f7f4c8b9..5f39b1b2 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -18,6 +18,7 @@ import type { } from './types'; import type { BinaryDownloadResult } from './utils/binary-response'; import { StackOneError } from './utils/error-stackone'; +import { ToolSetConfigError, ToolSetError } from './utils/error-toolset'; /** * Param-style pinned on the /mcp tool-listing URL. The MCP schema and the RPC-execution @@ -63,36 +64,6 @@ type ToolInputSchema = Awaited< ReturnType>['client']['listTools']> >['tools'][number]['inputSchema']; -/** - * Base exception for toolset errors - */ -export class ToolSetError extends Error { - constructor(message: string, options?: ErrorOptions) { - super(message, options); - this.name = 'ToolSetError'; - } -} - -/** - * Raised when there is an error in the toolset configuration - */ -export class ToolSetConfigError extends ToolSetError { - constructor(message: string, options?: ErrorOptions) { - super(message, options); - this.name = 'ToolSetConfigError'; - } -} - -/** - * Raised when there is an error loading tools - */ -export class ToolSetLoadError extends ToolSetError { - constructor(message: string, options?: ErrorOptions) { - super(message, options); - this.name = 'ToolSetLoadError'; - } -} - /** * Authentication configuration for toolsets */ diff --git a/src/utils/error-toolset.test.ts b/src/utils/error-toolset.test.ts new file mode 100644 index 00000000..d95372ae --- /dev/null +++ b/src/utils/error-toolset.test.ts @@ -0,0 +1,27 @@ +import { StackOneAPIError } from './error-stackone-api'; +import { StackOneError } from './error-stackone'; +import { ToolSetConfigError, ToolSetError, ToolSetLoadError } from './error-toolset'; + +describe('error hierarchy', () => { + // `instanceof StackOneError` must be a real catch-all. The toolset errors used to extend + // Error directly, so the obvious catch-all missed the two errors a user hits first. + it.each([ + ['ToolSetError', new ToolSetError('x')], + ['ToolSetConfigError', new ToolSetConfigError('x')], + ['ToolSetLoadError', new ToolSetLoadError('x')], + ['StackOneAPIError', new StackOneAPIError('x', 500, null)], + ])('%s is a StackOneError', (name, error) => { + expect(error).toBeInstanceOf(StackOneError); + expect(error.name).toBe(name); + }); + + it('keeps the toolset errors under ToolSetError', () => { + expect(new ToolSetConfigError('x')).toBeInstanceOf(ToolSetError); + expect(new ToolSetLoadError('x')).toBeInstanceOf(ToolSetError); + }); + + it('carries a cause', () => { + const cause = new Error('root'); + expect(new ToolSetLoadError('wrapped', { cause }).cause).toBe(cause); + }); +}); diff --git a/src/utils/error-toolset.ts b/src/utils/error-toolset.ts new file mode 100644 index 00000000..1f6922a4 --- /dev/null +++ b/src/utils/error-toolset.ts @@ -0,0 +1,36 @@ +import { StackOneError } from './error-stackone'; + +/** + * Base exception for toolset errors. + * + * A subclass of {@link StackOneError}, so `catch (e) { if (e instanceof StackOneError) … }` is a + * real catch-all for everything the SDK throws. The two used to be unrelated siblings, which + * meant the obvious catch-all silently missed the configuration and load errors — the ones a + * user is most likely to hit on their very first call. + */ +export class ToolSetError extends StackOneError { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = 'ToolSetError'; + } +} + +/** + * Raised when the toolset is configured, or called, with something it cannot use. + */ +export class ToolSetConfigError extends ToolSetError { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = 'ToolSetConfigError'; + } +} + +/** + * Raised when the tool catalog, or the accounts behind it, cannot be loaded. + */ +export class ToolSetLoadError extends ToolSetError { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = 'ToolSetLoadError'; + } +} From dd3d5e3854856daa33cfede21b51917b4c8f10e5 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:26:55 +0100 Subject: [PATCH 010/151] fix(download): reduce Content-Disposition filenames to a safe basename MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `fileName` on a download result came straight from the server's Content-Disposition, which whoever uploaded the file to the connected provider chooses. A caller that writes the download to `result.fileName` — the obvious thing to do — could be made to write `../../.ssh/authorized_keys` or `/etc/cron.d/x`, and the RFC 5987 branch percent-decoded, so `%2e%2e%2f` got through any filter applied earlier. Port the Python SDK's `_safe_basename`, applied last, after decoding: - treat `/`, `\` and `:` as separators (covers `C:evil.exe` and NTFS alternate data streams such as `report.pdf:payload`); - strip control and Unicode format characters (the U+202E extension spoof); - return null for an empty name, `.` or `..`; - cap at 255 UTF-8 bytes on a character boundary, keeping the extension. Parameters are now matched at a parameter boundary (`notfilename=` is ignored), and the extended form decodes with its declared charset (ISO-8859-1 included), falling back to UTF-8 for an unknown label, as the Python SDK does. The Python version leaves a name with no dot uncapped and does not treat `:` inside a name as a separator; both are handled here. --- src/utils/binary-response.test.ts | 63 +++++++++++++++- src/utils/binary-response.ts | 116 +++++++++++++++++++++++++----- 2 files changed, 158 insertions(+), 21 deletions(-) diff --git a/src/utils/binary-response.test.ts b/src/utils/binary-response.test.ts index de7cc3ce..7c3b29e8 100644 --- a/src/utils/binary-response.test.ts +++ b/src/utils/binary-response.test.ts @@ -1,4 +1,4 @@ -import { filenameFromContentDisposition, isJsonContentType } from './binary-response'; +import { filenameFromContentDisposition, isJsonContentType, safeBasename } from './binary-response'; /** * Unit tests for the Content-Type and Content-Disposition parsing helpers that drive the @@ -28,8 +28,14 @@ describe('filenameFromContentDisposition', () => { ['inline; filename="my report.docx"', 'my report.docx'], // RFC 5987 extended form is percent-decoded and takes precedence over the plain form. ['attachment; filename="fallback.txt"; filename*=UTF-8\'\'na%C3%AFve.txt', 'naïve.txt'], - // Malformed percent-encoding must not throw - fall back to the raw (undecoded) value. + // Malformed percent-encoding must not throw - the malformed escape stays literal. ["attachment; filename*=UTF-8''bad%ZZname", 'bad%ZZname'], + // Non-UTF-8 charset is honoured: 0xA3 is "£" in ISO-8859-1, not UTF-8. + ["attachment; filename*=ISO-8859-1'en'%A3%20rates.txt", '£ rates.txt'], + // Unknown charset label falls back to UTF-8 instead of throwing. + ["attachment; filename*=bogus-charset''%C2%A3.txt", '£.txt'], + // Non-conformant quoted extended value: surrounding quotes are stripped. + ['attachment; filename*="UTF-8\'\'na%C3%AFve.txt"', 'naïve.txt'], ['attachment', null], [null, null], ['', null], @@ -37,3 +43,56 @@ describe('filenameFromContentDisposition', () => { expect(filenameFromContentDisposition(input as string | null)).toBe(expected); }); }); + +/** + * The filename comes from a Content-Disposition that whoever uploaded the file chose, so it is + * attacker-controlled. Ported from the Python SDK's `_safe_basename` cases. + */ +describe('download filenames are safe to write', () => { + it.each([ + ['attachment; filename="../../.ssh/authorized_keys"', 'authorized_keys'], + ["attachment; filename*=UTF-8''%2e%2e%2f%2e%2e%2fetc%2fcron.d%2fx", 'x'], + ['attachment; filename="/etc/passwd"', 'passwd'], + ['attachment; filename="C:evil.exe"', 'evil.exe'], + ['attachment; filename="..\\\\..\\\\windows\\\\x.dll"', 'x.dll'], + ["attachment; filename*=UTF-8''..%5C..%5Cwindows%5Cx.dll", 'x.dll'], + ['attachment; filename="report.pdf:hidden.exe"', 'hidden.exe'], + ['attachment; filename="\u202egnp.exe"', 'gnp.exe'], + ['attachment; filename="line\u0000break\u0007.txt"', 'linebreak.txt'], + ['attachment; filename=".."', null], + ["attachment; filename*=UTF-8''%2e%2e", null], + ['attachment; filename=" "', null], + ['attachment; notfilename="decoy.txt"', null], + ['attachment; filename="report.pdf"', 'report.pdf'], + ])('%j -> %j', (header, expected) => { + expect(filenameFromContentDisposition(header)).toBe(expected); + }); + + const byteLength = (value: string) => new TextEncoder().encode(value).length; + + it('caps an overlong name at 255 bytes, keeping the extension', () => { + const name = filenameFromContentDisposition(`attachment; filename="${'a'.repeat(400)}.pdf"`); + expect(name?.endsWith('.pdf')).toBe(true); + expect(byteLength(name ?? '')).toBeLessThanOrEqual(255); + }); + + it('caps multi-byte names on a character boundary', () => { + const name = safeBasename(`${'é'.repeat(300)}.txt`); + expect(name?.endsWith('.txt')).toBe(true); + expect(byteLength(name ?? '')).toBeLessThanOrEqual(255); + expect(name).not.toContain('\uFFFD'); + }); + + it('caps an overlong name with no extension', () => { + expect(byteLength(safeBasename('b'.repeat(400)) ?? '')).toBe(255); + }); + + it('caps a name whose extension alone is overlong', () => { + expect(byteLength(safeBasename(`a.${'c'.repeat(400)}`) ?? '')).toBe(255); + }); + + it('passes null through', () => { + expect(safeBasename(null)).toBeNull(); + expect(safeBasename(undefined)).toBeNull(); + }); +}); diff --git a/src/utils/binary-response.ts b/src/utils/binary-response.ts index 432e67fc..7ef83286 100644 --- a/src/utils/binary-response.ts +++ b/src/utils/binary-response.ts @@ -36,35 +36,113 @@ export function isJsonContentType(contentType: string): boolean { return mediaType === 'application/json' || mediaType.endsWith('+json'); } +/** The longest filename, in UTF-8 bytes, that common filesystems (ext4, APFS, NTFS) accept. */ +const MAX_FILENAME_BYTES = 255; + +/** Control (Cc) and format (Cf) characters: log/header injection and bidi extension spoofing. */ +const CONTROL_OR_FORMAT_CHARS = /[\p{Cc}\p{Cf}]/gu; + +const utf8Encoder = new TextEncoder(); + +/** Truncate to at most `maxBytes` UTF-8 bytes without splitting a character. */ +function truncateUtf8(value: string, maxBytes: number): string { + let bytes = 0; + let end = 0; + for (const char of value) { + const size = utf8Encoder.encode(char).length; + if (bytes + size > maxBytes) { + break; + } + bytes += size; + end += char.length; + } + return value.slice(0, end); +} + +/** + * Reduce a server-supplied filename to a bare, writable basename, or `null` if nothing usable + * is left. + * + * The value comes from a remote `Content-Disposition`, which in practice is chosen by whoever + * uploaded the file to the connected provider — so it is attacker-controlled. Returned as-is it + * is an arbitrary-file-write primitive for any caller that does the obvious thing and passes it + * to `writeFile()`: `../../.ssh/authorized_keys` and `/etc/cron.d/x` both round-trip. The RFC + * 5987 branch percent-decodes, so a filter applied before this point would be bypassed anyway; + * sanitise last, here, once. + * + * - `/` and `\` are both path separators, whatever the host OS. + * - `:` is too: `C:evil.exe` writes to drive C:'s current directory on Windows, and + * `report.pdf:payload` writes an NTFS alternate data stream. + * - Control and Unicode format characters are removed — U+202E renders `\u202egnp.exe` as + * `…exe.png`, the classic extension spoof. + * - The result is capped at 255 UTF-8 bytes, keeping the extension when there is one. + */ +export function safeBasename(name: string | null | undefined): string | null { + if (name == null) { + return null; + } + const lastSegment = name.split(/[/\\:]/).at(-1) ?? ''; + const base = lastSegment.replace(CONTROL_OR_FORMAT_CHARS, '').trim(); + if (base === '' || base === '.' || base === '..') { + return null; + } + if (utf8Encoder.encode(base).length <= MAX_FILENAME_BYTES) { + return base; + } + const dot = base.lastIndexOf('.'); + const suffix = dot > 0 ? base.slice(dot) : ''; + const suffixBytes = utf8Encoder.encode(suffix).length; + // An extension that cannot fit alongside at least one character of stem is not worth + // keeping: truncate the whole name instead of emitting something still over the limit. + if (suffix === '' || suffixBytes >= MAX_FILENAME_BYTES) { + return truncateUtf8(base, MAX_FILENAME_BYTES); + } + return truncateUtf8(base.slice(0, dot), MAX_FILENAME_BYTES - suffixBytes) + suffix; +} + /** - * Extract the filename from a Content-Disposition header value, if present. + * Decode `%XX` escapes as bytes in `charset`, the way Python's `urllib.parse.unquote` does: + * malformed escapes stay literal, and bytes that do not decode become U+FFFD rather than + * throwing. An unknown charset label falls back to UTF-8. + */ +function percentDecode(encoded: string, charset: string): string { + let decoder: InstanceType; + try { + decoder = new TextDecoder(charset); + } catch { + decoder = new TextDecoder('utf-8'); + } + return encoded.replace(/(?:%[0-9A-Fa-f]{2})+/g, (run) => + decoder.decode(Uint8Array.from(run.slice(1).split('%'), (hex) => Number.parseInt(hex, 16))), + ); +} + +/** + * Extract the filename from a Content-Disposition header value, reduced to a safe basename. * * Handles both the plain `filename="example.pdf"` form and the RFC 5987 extended - * `filename*=UTF-8''example%20file.pdf` form (which is percent-decoded and takes precedence - * when present). Returns null when no filename is present. + * `filename*=UTF-8''example%20file.pdf` form, which takes precedence when present. The extended + * form is percent-decoded using its declared charset (RFC 5987 permits both `UTF-8` and + * `ISO-8859-1`). Parameters are matched at a parameter boundary, so `notfilename=` is ignored. + * Returns null when no usable filename is present — see {@link safeBasename}. */ -export function filenameFromContentDisposition(value: string | null): string | null { +export function filenameFromContentDisposition(value: string | null | undefined): string | null { if (!value) { return null; } - const extended = value.match(/filename\*\s*=\s*[^']*'[^']*'([^;]+)/i); - if (extended?.[1]) { - const encoded = extended[1].trim(); - try { - return decodeURIComponent(encoded); - } catch { - // Malformed percent-encoding: fall back to the raw value rather than throwing and - // breaking an otherwise-valid download over a bad Content-Disposition header. - return encoded; - } + const extended = value.match(/(?:^|;)\s*filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i); + if (extended) { + const charset = extended[1]?.trim() || 'utf-8'; + const encoded = (extended[2] ?? '').trim().replace(/^"+|"+$/g, ''); + return safeBasename(percentDecode(encoded, charset)); } - const quoted = value.match(/filename\s*=\s*"([^"]*)"/i); + const quoted = value.match(/(?:^|;)\s*filename\s*=\s*"([^"]*)"/i); if (quoted) { - return quoted[1]?.trim() || null; + return safeBasename(quoted[1]); } - const bare = value.match(/filename\s*=\s*([^;]+)/i); - if (bare?.[1]) { - return bare[1].trim().replace(/^"+|"+$/g, '') || null; + const bare = value.match(/(?:^|;)\s*filename\s*=\s*([^;]+)/i); + if (bare) { + return safeBasename((bare[1] ?? '').replace(/^"+|"+$/g, '')); } return null; } From 2eb93aaa9ba949c52f5526097668c2480ae25122 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:44:35 +0100 Subject: [PATCH 011/151] refactor!: rebuild the toolset on the served MCP catalog Port the Python SDK 3.0 toolset. Tools are listed from the MCP endpoint per account and executed over `/actions/rpc`, or over MCP `tools/call` for the tools with no action behind them. Schemas are passed through as served. Listing and accounts - An API key alone is enough: with no account configured, `fetchTools()` discovers the key's active accounts via `GET /accounts` (now public as `fetchAccounts()`). It used to send an unscoped request the API refuses. - Accounts are listed concurrently, at most 10 at a time, with `param-style=flat_prefixed` pinned and pagination followed. A failing account is skipped with a warning unless every account fails. - The cache holds listings, not tools: every call builds fresh tools on a deep copy of the schema, so one caller can no longer rescope or mutate another's. The key covers the account scope, mode, base URL and API key, and a generation guard stops an in-flight listing from repopulating the cache after `clearCatalogCache()`. Degraded listings are not cached. - `toolMode` / `fetchTools({ mode })` select `search_execute`, whose meta tools execute over `tools/call`. `stackone_submit_feedback` executes over `tools/call` in every mode and is returned once, however many accounts list it. - Provider filtering matches a full prefix (`browser_linkedin`), action globs follow `fnmatch`, and a name served by two accounts warns. Execution - RPC arguments are split into the envelope by their flat_prefixed location, decided once from the served schema: only when ALL declared keys are prefixed (otherwise a warning). A reserved container key given a scalar is rejected; prototype-named fields are plain data. - Headers are allowlisted from the served `headers_*` properties on both the RPC and MCP paths. `Authorization`, `x-account-id` and `User-Agent` are set by the SDK after every merge, including the `headers` option. - Every MCP call (listing and `tools/call`) and every RPC call honours `timeout`. MCP transport failures become `StackOneAPIError` with the HTTP status (e.g. 412 for a dead account); an `isError` result raises with the status from its payload. API errors lead with the server's own message and keep status and body. Schemas - `toJsonSchema()` is the served root verbatim (`$schema`, `$defs`, `title`, `additionalProperties`, `oneOf`, ...) with the served `required`. No internal marker is needed, so nothing named `nullable` is ever touched. - `toOpenAI()`, `toAnthropic()`, `toOpenAIResponses()`, `toAISDK()` and `toClaudeAgentSdkTool()` fold a top-level `oneOf`/`anyOf`/`allOf` (which OpenAI and Anthropic reject) into the root. Strict Responses and the AI SDK close the root with `additionalProperties: false`. Mocks refuse an unscoped `/mcp` or `/actions/rpc` request (400) and an unknown account (404), serve schemas verbatim, `GET /accounts`, the search/execute meta tools with a `session_id`, and optionally `stackone_submit_feedback`. `defu` and the `zod` peer are no longer used. BREAKING CHANGE: `RequestBuilder` and direct-HTTP execution are removed: `ExecuteConfig` no longer has an `http` kind, `ParameterLocation` is no longer exported, and `BaseTool#execute` throws unless overridden. `BaseTool` no longer takes a `headers` constructor argument and loses `getHeaders()`/`setHeaders()` and `connector`; `Tools#getConnectors()` is removed. `StackOneToolSetConfig` loses `authentication`, `strict` and `rpcClient`, and `AuthenticationConfig` and `BaseToolSetConfig` are no longer exported. The constructor throws `ToolSetConfigError` without an API key. `fetchTools()` returns fresh tool instances on every call (never the cached `Tools`), ordered by account id, and discovers accounts when none is configured. `ToolExecution` no longer carries `headers`. An RPC timeout is a `StackOneError` rather than a `StackOneAPIError` with status 0, and `StackOneAPIError` no longer appends `responseBody.message` to the message it is given. A `dryRun` result's `headers` are the HTTP request headers, without `Authorization`. --- mocks/handlers.example-api.ts | 59 - mocks/handlers.mcp.ts | 28 +- mocks/handlers.stackone-accounts.ts | 20 + mocks/handlers.stackone-ai.ts | 87 -- mocks/handlers.stackone-rpc.ts | 16 + mocks/handlers.ts | 6 +- mocks/mcp-server.ts | 194 ++- package.json | 6 +- pnpm-lock.yaml | 11 - pnpm-workspace.yaml | 2 - src/consts.ts | 27 +- src/envelope.test.ts | 91 ++ src/envelope.ts | 122 ++ src/headers.test.ts | 9 +- src/headers.ts | 66 +- src/index.ts | 7 +- src/mcp-client.test.ts | 308 ++++- src/mcp-client.ts | 270 ++++- src/requestBuilder.test.ts | 899 -------------- src/requestBuilder.ts | 397 ------ src/rpc-client.test.ts | 382 +++--- src/rpc-client.ts | 282 ++--- src/schema.test.ts | 130 ++ src/schema.ts | 139 ++- src/tool-optional-ai.test.ts | 16 +- src/tool.test-d.ts | 8 +- src/tool.test.ts | 1413 ++++++++-------------- src/tool.ts | 501 +++++--- src/toolsets.test.ts | 1662 +++++++++++--------------- src/toolsets.ts | 972 +++++++-------- src/types.ts | 101 +- src/utils/binary-response.ts | 6 +- src/utils/concurrency.ts | 26 + src/utils/error-stackone-api.test.ts | 46 +- src/utils/error-stackone-api.ts | 44 +- src/utils/serialize.ts | 21 + 36 files changed, 3742 insertions(+), 4632 deletions(-) delete mode 100644 mocks/handlers.example-api.ts create mode 100644 mocks/handlers.stackone-accounts.ts delete mode 100644 mocks/handlers.stackone-ai.ts create mode 100644 src/envelope.test.ts create mode 100644 src/envelope.ts delete mode 100644 src/requestBuilder.test.ts delete mode 100644 src/requestBuilder.ts create mode 100644 src/schema.test.ts create mode 100644 src/utils/concurrency.ts create mode 100644 src/utils/serialize.ts diff --git a/mocks/handlers.example-api.ts b/mocks/handlers.example-api.ts deleted file mode 100644 index 288dca0f..00000000 --- a/mocks/handlers.example-api.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { http, HttpResponse } from 'msw'; - -/** - * Example/Test API endpoint handlers - */ -export const exampleApiHandlers = [ - // Generic test endpoint for tool.spec.ts - http.get('https://api.example.com/test/:id', ({ params }) => { - if (params.id === 'invalid') { - return HttpResponse.json({ error: 'Invalid ID' }, { status: 400, statusText: 'Bad Request' }); - } - return HttpResponse.json({ - id: params.id, - name: 'Test', - }); - }), - - // Petstore API endpoint for openapi.spec.ts - http.get('https://petstore.swagger.io/v2/pet/:id', ({ params }) => { - return HttpResponse.json({ - id: params.id, - name: 'Fluffy', - status: 'available', - }); - }), - - // Meta tools test endpoints - http.post('https://api.example.com/hris/employees', async ({ request }) => { - const body = await request.json(); - return HttpResponse.json(body); - }), - - http.get('https://api.example.com/hris/employees', ({ request }) => { - const url = new URL(request.url); - const limit = url.searchParams.get('limit'); - return HttpResponse.json({ limit: limit ? Number(limit) : undefined }); - }), - - http.post('https://api.example.com/hris/time-off', async ({ request }) => { - const body = await request.json(); - return HttpResponse.json(body); - }), - - http.post('https://api.example.com/ats/candidates', async ({ request }) => { - const body = await request.json(); - return HttpResponse.json(body); - }), - - http.get('https://api.example.com/ats/candidates', ({ request }) => { - const url = new URL(request.url); - const status = url.searchParams.get('status'); - return HttpResponse.json({ status }); - }), - - http.post('https://api.example.com/crm/contacts', async ({ request }) => { - const body = await request.json(); - return HttpResponse.json(body); - }), -]; diff --git a/mocks/handlers.mcp.ts b/mocks/handlers.mcp.ts index 538db9db..ce139ae7 100644 --- a/mocks/handlers.mcp.ts +++ b/mocks/handlers.mcp.ts @@ -8,20 +8,20 @@ import { mixedProviderTools, } from './mcp-server'; -// Create MCP apps for testing -const defaultMcpApp = createMcpApp({ - accountTools: { - default: defaultMcpTools, - acc1: accountMcpTools.acc1, - acc2: accountMcpTools.acc2, - acc3: accountMcpTools.acc3, - 'test-account': accountMcpTools['test-account'], - mixed: mixedProviderTools, - // For examples testing - 'your-bamboohr-account-id': exampleBamboohrTools, - 'your-stackone-account-id': exampleBamboohrTools, - }, -}); +/** Every account the default mock knows. `/mcp` and `/actions/rpc` refuse any other with a 404. */ +export const mockAccountTools = { + default: defaultMcpTools, + acc1: accountMcpTools.acc1, + acc2: accountMcpTools.acc2, + acc3: accountMcpTools.acc3, + 'test-account': accountMcpTools['test-account'], + mixed: mixedProviderTools, + // For examples testing + 'your-bamboohr-account-id': exampleBamboohrTools, + 'your-stackone-account-id': exampleBamboohrTools, +}; + +const defaultMcpApp = createMcpApp({ accountTools: mockAccountTools }); /** * MCP Protocol endpoint handlers (delegated to Hono app) diff --git a/mocks/handlers.stackone-accounts.ts b/mocks/handlers.stackone-accounts.ts new file mode 100644 index 00000000..293cc2f9 --- /dev/null +++ b/mocks/handlers.stackone-accounts.ts @@ -0,0 +1,20 @@ +import { http, HttpResponse } from 'msw'; +import { TEST_BASE_URL } from './constants'; + +/** + * What `GET /accounts` serves: a bare list, with one account that is not active. An SDK that + * discovers accounts must filter on status, and one that fans out over every id is caught here. + */ +export const mockAccounts = [ + { id: 'default', provider: 'testprovider', status: 'active' }, + { id: 'dead', provider: 'brokenprovider', status: 'error' }, +]; + +export const stackoneAccountsHandlers = [ + http.get(`${TEST_BASE_URL}/accounts`, ({ request }) => { + if (!request.headers.get('Authorization')?.startsWith('Basic ')) { + return HttpResponse.json({ message: 'Unauthorized' }, { status: 401 }); + } + return HttpResponse.json(mockAccounts); + }), +]; diff --git a/mocks/handlers.stackone-ai.ts b/mocks/handlers.stackone-ai.ts deleted file mode 100644 index 06bc959b..00000000 --- a/mocks/handlers.stackone-ai.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { http, HttpResponse } from 'msw'; -import { TEST_BASE_URL } from './constants'; - -/** - * StackOne AI and Tools endpoint handlers - */ -export const stackoneAiHandlers = [ - // StackOne API spec endpoints - http.get(`${TEST_BASE_URL}/api/v1/:category/openapi.json`, ({ params }) => { - const { category } = params; - - if (category === 'hris') { - return HttpResponse.json({ - openapi: '3.0.0', - info: { title: 'HRIS API', version: '1.0.0' }, - paths: { '/employees': {} }, - }); - } - - return HttpResponse.json({ error: 'Not found' }, { status: 404 }); - }), - - // StackOne fetchTools endpoint for fetch-tools.ts example - http.get(`${TEST_BASE_URL}/ai/tools`, () => { - return HttpResponse.json({ - tools: [ - { - name: 'bamboohr_list_employees', - description: 'List all employees', - parameters: { - type: 'object', - properties: { - query: { - type: 'object', - properties: { limit: { type: 'number' } }, - }, - }, - }, - }, - { - name: 'bamboohr_get_employee', - description: 'Get employee by ID', - parameters: { - type: 'object', - properties: { id: { type: 'string' } }, - required: ['id'], - }, - }, - { - name: 'bamboohr_create_employee', - description: 'Create a new employee', - parameters: { - type: 'object', - properties: { name: { type: 'string' }, email: { type: 'string' } }, - }, - }, - ], - }); - }), - - // External OAS spec endpoint for openapi-toolset.ts example - http.get(`${TEST_BASE_URL}/oas/hris.json`, () => { - return HttpResponse.json({ - openapi: '3.0.0', - info: { title: 'StackOne HRIS API', version: '1.0.0' }, - servers: [{ url: TEST_BASE_URL }], - paths: { - '/hris/employees': { - get: { - operationId: 'bamboohr_list_employees', - summary: 'List employees', - parameters: [{ name: 'limit', in: 'query', schema: { type: 'integer' } }], - responses: { '200': { description: 'Success' } }, - }, - }, - '/hris/employees/{id}': { - get: { - operationId: 'bamboohr_get_employee', - summary: 'Get employee by ID', - parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], - responses: { '200': { description: 'Success' } }, - }, - }, - }, - }); - }), -]; diff --git a/mocks/handlers.stackone-rpc.ts b/mocks/handlers.stackone-rpc.ts index 5ff116ce..af462e27 100644 --- a/mocks/handlers.stackone-rpc.ts +++ b/mocks/handlers.stackone-rpc.ts @@ -1,5 +1,6 @@ import { http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from './constants'; +import { mockAccountTools } from './handlers.mcp'; /** * StackOne Actions RPC endpoint handlers @@ -17,6 +18,21 @@ export const stackoneRpcHandlers = [ ); } + // Execution is account-scoped too, exactly like /mcp: an unscoped request is refused, + // and so is an account the API has never heard of. + if (!accountIdHeader) { + return HttpResponse.json( + { error: 'Bad Request', message: 'Missing x-account-id header in request' }, + { status: 400 }, + ); + } + if (!Object.hasOwn(mockAccountTools, accountIdHeader)) { + return HttpResponse.json( + { error: 'Not Found', message: `Unknown account ${accountIdHeader}` }, + { status: 404 }, + ); + } + const body = (await request.json()) as { action?: string; body?: Record; diff --git a/mocks/handlers.ts b/mocks/handlers.ts index d1fc784c..addf4128 100644 --- a/mocks/handlers.ts +++ b/mocks/handlers.ts @@ -1,13 +1,11 @@ -import { exampleApiHandlers } from './handlers.example-api'; import { mcpHandlers } from './handlers.mcp'; import { openaiHandlers } from './handlers.openai'; -import { stackoneAiHandlers } from './handlers.stackone-ai'; +import { stackoneAccountsHandlers } from './handlers.stackone-accounts'; import { stackoneRpcHandlers } from './handlers.stackone-rpc'; export const handlers = [ ...openaiHandlers, + ...stackoneAccountsHandlers, ...stackoneRpcHandlers, - ...stackoneAiHandlers, - ...exampleApiHandlers, ...mcpHandlers, ]; diff --git a/mocks/mcp-server.ts b/mocks/mcp-server.ts index c65146ec..73803bc0 100644 --- a/mocks/mcp-server.ts +++ b/mocks/mcp-server.ts @@ -2,11 +2,18 @@ * Mock MCP server for testing using Hono's app.request() method. * This creates an MCP-compatible handler that can be used with MSW * without starting a real HTTP server. + * + * It refuses what the real endpoint refuses — an unscoped request, an unknown account — so a + * client bug that sends no account, or the wrong one, fails here instead of in production. */ import type { Hono as HonoApp } from 'hono'; import { StreamableHTTPTransport } from '@hono/mcp'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; -import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import { + CallToolRequestSchema, + type CallToolResult, + ListToolsRequestSchema, +} from '@modelcontextprotocol/sdk/types.js'; import { Hono } from 'hono'; import { basicAuth } from 'hono/basic-auth'; @@ -22,33 +29,132 @@ export interface McpToolDefinition { }; } +/** A `tools/call` exactly as it reached the server. */ +export interface RecordedToolCall { + accountId: string; + toolMode: string | undefined; + name: string; + arguments: Record; +} + export interface MockMcpServerOptions { - /** Tools available per account ID. Use 'default' for tools when no account header is provided. */ + /** Tools available per account ID. An account not listed here is refused with a 404. */ accountTools: Record; + /** + * Serve the global `stackone_submit_feedback` tool, in every tool mode, the way the real + * endpoint does when the org flag and project setting are on. Off models a project without + * it: the tool is simply absent, so the SDK has nothing to call. + */ + submitFeedback?: boolean; + /** Observe every `tools/call` as it arrived, before any schema parsing. */ + onToolCall?: (call: RecordedToolCall) => void; } +/** Mirrors the real `session_id` minted per search, so tests can assert it is carried through. */ +export const MOCK_SEARCH_SESSION_ID = 'mock-session-1'; + +/** The schema the real endpoint serves for its feedback tool, field for field. */ +const submitFeedbackTool = { + name: 'stackone_submit_feedback', + description: 'Records a structured verdict on how well the tools served this session.', + inputSchema: { + type: 'object', + properties: { + rating: { type: 'string', enum: ['positive', 'negative', 'neutral'] }, + feedback: { type: 'string' }, + tool_names: { type: 'array', items: { type: 'string' } }, + source: { type: 'string', enum: ['model', 'user', 'system'], default: 'model' }, + category: { + type: 'string', + enum: ['search', 'execute', 'defender', 'connection', 'general'], + }, + session_id: { type: 'string' }, + }, + required: ['rating', 'tool_names'], + }, +} as const satisfies McpToolDefinition; + +/** The two meta tools the real endpoint serves per connector under `tool-mode=search_execute`. */ +const metaTools = (accountId: string): McpToolDefinition[] => [ + { + name: `mock_${accountId}_search_actions`, + description: 'Search for available actions in natural language.', + inputSchema: { + type: 'object', + properties: { + query: { type: 'string' }, + top_k: { type: 'integer', minimum: 1, maximum: 50 }, + session_id: { type: 'string' }, + }, + required: ['query'], + }, + }, + { + name: `mock_${accountId}_execute_action`, + description: 'Execute an action by its action_id.', + inputSchema: { + type: 'object', + properties: { + action_id: { type: 'string' }, + path: { type: 'object' }, + query: { type: 'object' }, + body: { type: 'object' }, + headers: { type: 'object' }, + session_id: { type: 'string' }, + }, + required: ['action_id'], + }, + }, +]; + +const text = (payload: unknown, isError = false): CallToolResult => ({ + isError, + content: [{ type: 'text', text: JSON.stringify(payload) }], +}); + +const callMetaTool = (name: string, args: Record): CallToolResult | undefined => { + if (name.endsWith('_search_actions')) { + return text({ + session_id: MOCK_SEARCH_SESSION_ID, + actions: [ + { + action_id: 'mock_list_items', + description: 'List items', + similarity_score: 0.8, + example_request: { query: { page_size: 25 } }, + }, + ], + }); + } + if (name.endsWith('_execute_action')) { + // An unknown action must come back as isError — a normal response with the flag set — + // the way the real endpoint reports it. + if (args.action_id !== 'mock_list_items') { + return text({ error: `Unknown action ${String(args.action_id)}`, status_code: 404 }, true); + } + return text({ + data: { nodes: [] }, + echoed_query: args.query ?? null, + echoed_session_id: args.session_id ?? null, + }); + } + return undefined; +}; + /** - * Creates an MSW handler for mocking MCP protocol requests. - * Uses Hono's app.request() to handle requests without starting a server. + * Creates a Hono app speaking the MCP protocol at `/mcp`, for use from an MSW handler. * * @example * ```ts * import { server } from './mocks/node'; - * import { createMcpHandler, defaultMcpTools, accountMcpTools } from './mocks/mcp-server'; + * import { createMcpApp, accountMcpTools } from './mocks/mcp-server'; * - * // In your test setup - * server.use( - * createMcpHandler({ - * accountTools: { - * default: defaultMcpTools, - * 'account-1': accountMcpTools.acc1, - * }, - * }) - * ); + * const app = createMcpApp({ accountTools: { acc1: accountMcpTools.acc1 } }); + * server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); * ``` */ export function createMcpApp(options: MockMcpServerOptions): HonoApp { - const { accountTools } = options; + const { accountTools, submitFeedback = false, onToolCall } = options; // Create a Hono app that handles MCP protocol const app = new Hono(); @@ -63,23 +169,57 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { ); app.all('/mcp', async (c) => { - // Get account ID from header - const accountId = c.req.header('x-account-id') ?? 'default'; - const tools = accountTools[accountId] ?? accountTools.default ?? []; + // The real endpoint rejects a request with no account. Defaulting here made the mock more + // 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) { + return c.json( + { statusCode: 400, message: 'Missing x-account-id header or query parameter in request' }, + 400, + ); + } + // No fallback catalog either: serving one for an account that does not exist would hide + // any bug that sends a wrong, stale or mangled account id. + if (!Object.hasOwn(accountTools, accountId)) { + return c.json({ statusCode: 404, message: `Unknown account ${accountId}` }, 404); + } - // A low-level Server rather than McpServer: McpServer.registerTool expects a Zod shape - // and lists a plain JSON Schema as `properties: {}`, so every tool used to reach the SDK - // with no parameters at all. The real endpoint serves each schema verbatim. - const mcp = new Server({ name: 'test-mcp-server', version: '1.0.0' }, { capabilities: { tools: {} } }); - const transport = new StreamableHTTPTransport(); + const toolMode = c.req.query('tool-mode'); + const listed: McpToolDefinition[] = [ + ...(submitFeedback ? [submitFeedbackTool] : []), + ...(toolMode === 'search_execute' ? metaTools(accountId) : (accountTools[accountId] ?? [])), + ]; + // 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 + // verbatim, and so does this. + const mcp = new Server( + { name: 'test-mcp-server', version: '1.0.0' }, + { capabilities: { tools: {} } }, + ); mcp.setRequestHandler(ListToolsRequestSchema, () => ({ - tools: tools.map((tool) => ({ ...tool, inputSchema: structuredClone(tool.inputSchema) })), - })); - mcp.setRequestHandler(CallToolRequestSchema, (request) => ({ - content: [{ type: 'text' as const, text: JSON.stringify(request.params.arguments ?? {}) }], + tools: listed.map((tool) => ({ ...tool, inputSchema: structuredClone(tool.inputSchema) })), })); + mcp.setRequestHandler(CallToolRequestSchema, (request): CallToolResult => { + const { name } = request.params; + const args = request.params.arguments ?? {}; + onToolCall?.({ accountId, toolMode, name, arguments: structuredClone(args) }); + if (!listed.some((tool) => tool.name === name)) { + return text({ error: `Unknown tool ${name}`, status_code: 404 }, true); + } + if (name === submitFeedbackTool.name) { + return text({ + message: 'Feedback recorded', + submitted_at: new Date(0).toISOString(), + session_id: args.session_id ?? null, + }); + } + return callMetaTool(name, args) ?? text(args); + }); + + const transport = new StreamableHTTPTransport(); await mcp.connect(transport); return transport.handleRequest(c); }); diff --git a/package.json b/package.json index 7e5d25c6..ee0af930 100644 --- a/package.json +++ b/package.json @@ -62,8 +62,7 @@ "run:example": "tsx --env-file .env" }, "dependencies": { - "@modelcontextprotocol/sdk": "catalog:prod", - "defu": "catalog:prod" + "@modelcontextprotocol/sdk": "catalog:prod" }, "devDependencies": { "@fast-check/vitest": "catalog:dev", @@ -86,8 +85,7 @@ "@anthropic-ai/claude-agent-sdk": "catalog:peer", "@anthropic-ai/sdk": "catalog:peer", "ai": "catalog:peer", - "openai": "catalog:peer", - "zod": "catalog:peer" + "openai": "catalog:peer" }, "peerDependenciesMeta": { "@anthropic-ai/claude-agent-sdk": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8d177fca..e14e9a72 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -81,9 +81,6 @@ catalogs: '@modelcontextprotocol/sdk': specifier: ^1.24.3 version: 1.24.3 - defu: - specifier: ^6.1.4 - version: 6.1.4 importers: @@ -98,9 +95,6 @@ importers: '@modelcontextprotocol/sdk': specifier: catalog:prod version: 1.24.3(zod@4.3.5) - defu: - specifier: catalog:prod - version: 6.1.4 devDependencies: '@fast-check/vitest': specifier: catalog:dev @@ -1363,9 +1357,6 @@ packages: supports-color: optional: true - defu@6.1.4: - resolution: {integrity: sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==} - depd@2.0.0: resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} engines: {node: '>= 0.8'} @@ -3229,8 +3220,6 @@ snapshots: dependencies: ms: 2.1.3 - defu@6.1.4: {} - depd@2.0.0: {} dts-resolver@2.1.3(oxc-resolver@11.15.0): diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 6f602476..78e45457 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -31,10 +31,8 @@ catalogs: '@anthropic-ai/sdk': ^0.72.1 ai: '>=5.0.108 <8.0.0' openai: ^6.2.0 - zod: '>=3.25.0 <5' prod: '@modelcontextprotocol/sdk': ^1.24.3 - defu: ^6.1.4 enablePrePostScripts: true diff --git a/src/consts.ts b/src/consts.ts index 0353291b..a8989ca1 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -1,9 +1,32 @@ +import { version } from '../package.json'; + /** - * Package name used as User-Agent header + * Sent as the User-Agent on every request, versioned so each request is attributable to an + * exact SDK release. */ -export const USER_AGENT = 'stackone-ai-node'; +export const USER_AGENT = `stackone-ai-node/${version}`; /** * Default base URL for StackOne API */ export const DEFAULT_BASE_URL = 'https://api.stackone.com'; + +/** Request timeout applied to every HTTP and MCP call unless the toolset is given one. */ +export const DEFAULT_TIMEOUT_MS = 60_000; + +/** + * Param-style pinned on the /mcp tool-listing URL. The listed schema and the RPC envelope split + * (see `splitEnvelopeParams`) must agree on it, so it is pinned rather than following the server + * default — the server default is free to change without breaking the SDK. + */ +export const MCP_PARAM_STYLE = 'flat_prefixed'; + +/** + * The one global tool the MCP endpoint serves, in every tool mode, when feedback is enabled for + * the project. It is not an action: `/actions/rpc` has never heard of it, so it is only ever + * executed over MCP `tools/call`. + */ +export const SUBMIT_FEEDBACK_TOOL_NAME = 'stackone_submit_feedback'; + +/** Upper bound on how many accounts' catalogs (or connectors' searches) run at once. */ +export const MAX_CONCURRENCY = 10; diff --git a/src/envelope.test.ts b/src/envelope.test.ts new file mode 100644 index 00000000..3e1c09c8 --- /dev/null +++ b/src/envelope.test.ts @@ -0,0 +1,91 @@ +import { isFlatPrefixedSchema, splitEnvelopeParams } from './envelope'; + +const split = (params: Record, declared: string[] = []) => + splitEnvelopeParams(params as never, new Set(declared)); + +describe('splitEnvelopeParams', () => { + it('buckets flat_prefixed keys by their location prefix', () => { + expect( + split({ path_id: '123', query_limit: 10, 'headers_x-custom': 'value', body_name: 'test' }), + ).toEqual({ + path: { id: '123' }, + query: { limit: 10 }, + headers: { 'x-custom': 'value' }, + body: { name: 'test' }, + }); + }); + + it('accepts nested envelopes and sends unprefixed keys to the body', () => { + expect(split({ body: { nested: 'value' }, path: { id: '1' }, extra: 'x' })).toEqual({ + path: { id: '1' }, + query: {}, + headers: {}, + body: { nested: 'value', extra: 'x' }, + }); + }); + + // The prefix pattern alone cannot tell a path param from a body field that happens to start + // with "path_". The served schema settles it — decided once, from ALL of its keys. + describe('is decided once from the served schema', () => { + it('keeps prefix lookalikes in the body when any declared key is bare', () => { + const result = split({ path_to_file: '/tmp/x' }, ['path_to_file', 'name']); + expect(result.body).toEqual({ path_to_file: '/tmp/x' }); + expect(result.path).toEqual({}); + }); + + it('splits every match, declared or not, when every declared key is prefixed', () => { + const result = split({ path_id: '1', query_offset: 10 }, ['path_id', 'query_limit']); + expect(result.path).toEqual({ id: '1' }); + // Undeclared but prefixed: the model may be working from a newer schema than the + // cached listing. Routing it to the body would silently drop the argument. + expect(result.query).toEqual({ offset: 10 }); + }); + + it('trusts every match when there is no schema to consult', () => { + expect(split({ path_to_file: '/tmp/x' }).path).toEqual({ to_file: '/tmp/x' }); + expect(isFlatPrefixedSchema(new Set())).toBe(true); + }); + + it('is disabled by a single bare name', () => { + expect(isFlatPrefixedSchema(new Set(['path_id', 'name']))).toBe(false); + expect(isFlatPrefixedSchema(new Set(['path_id', 'body_name']))).toBe(true); + }); + }); + + it('treats a declared reserved word as a field, not a container', () => { + expect(split({ query: 'sales' }, ['query', 'id']).body).toEqual({ query: 'sales' }); + }); + + it.each([['not-an-object'], [5], [null], [['a']]])( + 'rejects a reserved container given %j rather than smuggling it into the body', + (value) => { + expect(() => split({ query: value })).toThrow(/envelope container and must be an object/); + }, + ); + + it('does not depend on the caller key order: flat beats nested beats bare', () => { + expect(split({ body_foo: 1, foo: 2 }).body).toEqual({ foo: 1 }); + expect(split({ foo: 2, body_foo: 1 }).body).toEqual({ foo: 1 }); + + expect(split({ body: { foo: 9 }, foo: 2 }).body).toEqual({ foo: 9 }); + expect(split({ foo: 2, body: { foo: 9 } }).body).toEqual({ foo: 9 }); + + expect(split({ path: { id: 'nested' }, path_id: 'flat' }).path).toEqual({ id: 'flat' }); + expect(split({ path_id: 'flat', path: { id: 'nested' } }).path).toEqual({ id: 'flat' }); + }); + + it('keeps fields named after Object.prototype members as plain data', () => { + const result = split( + JSON.parse( + '{"body_constructor":"x","path_toString":"y","query_valueOf":"z","body___proto__":"p","hasOwnProperty":"h"}', + ) as Record, + ); + + expect(JSON.stringify(result.body)).toBe( + '{"constructor":"x","__proto__":"p","hasOwnProperty":"h"}', + ); + expect(result.path).toEqual({ toString: 'y' }); + expect(result.query).toEqual({ valueOf: 'z' }); + expect(Object.getPrototypeOf(result.body)).toBe(Object.prototype); + }); +}); diff --git a/src/envelope.ts b/src/envelope.ts new file mode 100644 index 00000000..f903c3a3 --- /dev/null +++ b/src/envelope.ts @@ -0,0 +1,122 @@ +import { StackOneError } from './utils/error-stackone'; +import { warn } from './utils/logger'; +import type { JsonObject, JsonValue } from './types'; + +/** Matches a flat_prefixed envelope key: `_` (e.g. `path_id`, `query_limit`). */ +const FLAT_ENVELOPE_KEY_PATTERN = /^(path|query|body|headers)_(.+)$/; + +const ENVELOPE_LOCATIONS = ['path', 'query', 'headers', 'body'] as const; + +type EnvelopeLocation = (typeof ENVELOPE_LOCATIONS)[number]; + +/** The four buckets of an `/actions/rpc` request. */ +type Envelope = Record; + +const isEnvelopeLocation = (key: string): key is EnvelopeLocation => + (ENVELOPE_LOCATIONS as readonly string[]).includes(key); + +const isPlainObject = (value: unknown): value is JsonObject => + typeof value === 'object' && value !== null && !Array.isArray(value); + +/** + * Whether a tool's arguments should be read as flat_prefixed, decided ONCE from its served + * schema rather than per key. + * + * Under flat_prefixed every parameter is prefixed, so `path_to_file` means `path.to_file`; under + * a bare schema it is a body field that merely starts with "path_". ALL declared keys must be + * prefixed, not any: one bare name is proof the schema is not flat_prefixed, and `any` would be + * satisfied by the very key this exists to protect. No declared keys means no schema to + * consult, so every match is trusted — otherwise every path parameter would fall into the body. + */ +export function isFlatPrefixedSchema(declared: ReadonlySet): boolean { + return declared.size === 0 || [...declared].every((key) => FLAT_ENVELOPE_KEY_PATTERN.test(key)); +} + +/** + * Split tool arguments into the RPC envelope (path/query/headers/body). + * + * Tools are listed with `?param-style=flat_prefixed`, so keys arrive as `_` + * and the prefix carries the location. A bare object-valued `path`/`query`/`headers`/`body` key + * is still bucketed for clients holding a nested schema, and any other key falls through to the + * body. + * + * Precedence is a property of the KIND of key, never of the caller's key order: flat_prefixed + * beats nested beats bare. The Python SDK applies the same rules, so both send byte-identical + * wire bodies for the same call. + * + * Buckets are null-prototype objects, so fields named after `Object.prototype` members + * (`constructor`, `toString`, `__proto__`) are ordinary data rather than prototype lookups. + * + * @param params The model-supplied arguments. + * @param declared The served schema's property names. + * @param flatPrefixed The result of {@link isFlatPrefixedSchema} for `declared`. + * @throws StackOneError When a reserved container key carries a non-object value. + */ +export function splitEnvelopeParams( + params: JsonObject, + declared: ReadonlySet, + flatPrefixed: boolean = isFlatPrefixedSchema(declared), +): Envelope { + const buckets: Envelope = { + path: Object.create(null) as JsonObject, + query: Object.create(null) as JsonObject, + headers: Object.create(null) as JsonObject, + body: Object.create(null) as JsonObject, + }; + const setDefault = (bucket: JsonObject, field: string, value: JsonValue): void => { + if (!Object.hasOwn(bucket, field)) { + bucket[field] = value; + } + }; + + const nested: Array<[EnvelopeLocation, JsonObject]> = []; + const bare: Array<[string, JsonValue]> = []; + for (const [key, value] of Object.entries(params)) { + const match = flatPrefixed ? FLAT_ENVELOPE_KEY_PATTERN.exec(key) : null; + if (match) { + buckets[match[1] as EnvelopeLocation][match[2] as string] = value; + continue; + } + // A reserved word the schema declares as a property is a field, not a container — + // refusing it would reject a schema-valid call. + if (isEnvelopeLocation(key) && !declared.has(key)) { + // A container given a scalar is malformed input, not a body field. Putting it in the + // body would smuggle a field literally named `path` into the payload. + if (!isPlainObject(value)) { + throw new StackOneError( + `"${key}" is an envelope container and must be an object, got ${value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value}. Did you mean ${key}_?`, + ); + } + nested.push([key, value]); + continue; + } + bare.push([key, value]); + } + + for (const [location, value] of nested) { + for (const [field, fieldValue] of Object.entries(value)) { + setDefault(buckets[location], field, fieldValue); + } + } + for (const [key, value] of bare) { + setDefault(buckets.body, key, value); + } + + // Spread onto ordinary objects so downstream JSON and schema handling sees plain records. + return { + path: { ...buckets.path }, + query: { ...buckets.query }, + headers: { ...buckets.headers }, + body: { ...buckets.body }, + }; +} + +/** + * Warn, once, that a schema with bare names has flat-prefix detection disabled. Called by the + * tool the first time it splits arguments, rather than per call or per listing. + */ +export function warnBareSchema(toolName: string): void { + warn( + `Tool "${toolName}" has bare parameter names in its schema; flat-prefix detection is disabled and prefixed arguments may fall into the body.`, + ); +} diff --git a/src/headers.test.ts b/src/headers.test.ts index 95f7f3cc..ce27da28 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -100,9 +100,12 @@ describe('sanitiseHeaders', () => { ).toEqual({}); }); - it.each([' x-trace', 'X-TRACE\t', 'X-Trace'])('matches %j case- and whitespace-insensitively', (name) => { - expect(sanitiseHeaders({ [name]: 'abc' }, allowed)).toEqual({ [name.trim()]: 'abc' }); - }); + it.each([' x-trace', 'X-TRACE\t', 'X-Trace'])( + 'matches %j case- and whitespace-insensitively', + (name) => { + expect(sanitiseHeaders({ [name]: 'abc' }, allowed)).toEqual({ [name.trim()]: 'abc' }); + }, + ); it.each(['a\r\nEvil: 1', 'trailing\n', 'bad\rvalue', 'nul\u0000byte', 'wide\u0100char'])( 'drops a declared header whose value is %j', diff --git a/src/headers.ts b/src/headers.ts index c79e9b7d..d2a53db7 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -1,32 +1,64 @@ -import { z } from 'zod/v4-mini'; +import { USER_AGENT } from './consts'; import type { JsonObject } from './types'; import { warn } from './utils/logger'; /** - * Known StackOne API header keys that are forwarded as HTTP headers + * Header names the SDK owns. They are applied after every other header is merged, so neither a + * tool call nor a caller-supplied `headers` option can replace the credential or retarget the + * request at another account. */ -export const STACKONE_HEADER_KEYS = ['x-account-id'] as const; +const SDK_OWNED_HEADERS = ['authorization', 'x-account-id', 'user-agent'] as const; + +/** Whether a caller-supplied header name is one the SDK owns and will override. */ +export function isSdkOwnedHeader(name: string): boolean { + return (SDK_OWNED_HEADERS as readonly string[]).includes(name.trim().toLowerCase()); +} /** - * Zod schema for StackOne API headers (branded) - * These headers are forwarded as HTTP headers in API requests + * HTTP Basic credentials for an API key, as every StackOne endpoint expects them. */ -export const stackOneHeadersSchema = z.record(z.string(), z.string()).brand<'StackOneHeaders'>(); +function buildAuthHeader(apiKey: string): string { + return `Basic ${Buffer.from(`${apiKey}:`).toString('base64')}`; +} /** - * Branded type for StackOne API headers + * The HTTP headers for a request to StackOne: the caller's extra headers first, then the SDK's + * own, so `Authorization`, `x-account-id` and `User-Agent` are always the SDK's. + * + * Case variants of the owned names are removed before they are set — `fetch` joins + * `authorization` and `Authorization` into one comma-separated value rather than letting either + * win. With no `accountId`, no `x-account-id` is sent at all. */ -export type StackOneHeaders = z.infer; +export function buildRequestHeaders(options: { + apiKey: string; + accountId?: string; + extraHeaders?: Record; +}): Record { + const headers: Record = {}; + for (const [name, value] of Object.entries(options.extraHeaders ?? {})) { + if (!isSdkOwnedHeader(name)) { + headers[name] = value; + } + } + headers['User-Agent'] = USER_AGENT; + headers.Authorization = buildAuthHeader(options.apiKey); + if (options.accountId) { + headers['x-account-id'] = options.accountId; + } + return headers; +} /** - * Normalizes header values from JsonObject to StackOneHeaders (branded type) - * Converts numbers and booleans to strings, and serializes objects to JSON + * Normalizes header values from JsonObject to strings. + * Converts numbers and booleans to strings, serializes objects to JSON and skips nulls. * * @param headers - Headers object with JSON value types - * @returns Normalized headers with string values only (branded type) + * @returns Normalized headers with string values only */ -export function normalizeHeaders(headers: JsonObject | undefined): StackOneHeaders { - if (!headers) return stackOneHeadersSchema.parse({}); +export function normalizeHeaders(headers: JsonObject | undefined): Record { + if (!headers) { + return {}; + } const result: Record = {}; for (const [key, value] of Object.entries(headers)) { switch (true) { @@ -43,7 +75,7 @@ export function normalizeHeaders(headers: JsonObject | undefined): StackOneHeade break; } } - return stackOneHeadersSchema.parse(result); + return result; } /** An RFC 9110 header field name (`token`). */ @@ -84,7 +116,8 @@ export function declaredHeaderNames(propertyNames: Iterable): Set = {}; for (const [key, value] of Object.entries(normalizeHeaders(supplied))) { const name = key.trim(); - if (!allowed.has(name.toLowerCase())) { + // Owned names are refused even when declared: the SDK sets them itself, afterwards. + if (!allowed.has(name.toLowerCase()) || isSdkOwnedHeader(name)) { warn(`Dropping header "${name}" from a tool call: no served schema declares it`); continue; } diff --git a/src/index.ts b/src/index.ts index 498f8b25..f02bc706 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,14 +6,12 @@ export { BaseTool, StackOneTool, Tools } from './tool'; export { isBinaryDownloadResult, type BinaryDownloadResult } from './utils/binary-response'; export { StackOneError } from './utils/error-stackone'; export { StackOneAPIError } from './utils/error-stackone-api'; - export { ToolSetConfigError, ToolSetError, ToolSetLoadError } from './utils/error-toolset'; export { StackOneToolSet, - type AuthenticationConfig, - type BaseToolSetConfig, type ExecuteToolsConfig, + type FetchToolsOptions, type StackOneToolSetConfig, } from './toolsets'; @@ -24,6 +22,7 @@ export type { ExecuteOptions, JsonObject, JsonValue, - ParameterLocation, + StackOneAccount, ToolDefinition, + ToolMode, } from './types'; diff --git a/src/mcp-client.test.ts b/src/mcp-client.test.ts index 2519401e..026a8182 100644 --- a/src/mcp-client.test.ts +++ b/src/mcp-client.test.ts @@ -1,93 +1,269 @@ -/** - * MCP client factory tests. - * Tests the createMCPClient function for creating MCP protocol clients. - */ -import { Client } from '@modelcontextprotocol/sdk/client/index.js'; -import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; -import { version } from '../package.json'; +import { createServer, type Server as NetServer, type Socket } from 'node:net'; +import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { http, HttpResponse } from 'msw'; +import { TEST_BASE_URL } from '../mocks/constants'; +import { createMcpApp } from '../mocks/mcp-server'; import { server } from '../mocks/node'; -import { createMCPClient } from './mcp-client'; +import { USER_AGENT } from './consts'; +import { buildRequestHeaders } from './headers'; +import { callMcpTool, describeMcpFailure, listMcpTools, parseToolResult } from './mcp-client'; +import { StackOneAPIError } from './utils/error-stackone-api'; +import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; -test('createMCPClient creates client with required options', async () => { - const mcpClient = await createMCPClient({ - baseUrl: 'https://api.example.com/mcp', +const endpoint = `${TEST_BASE_URL}/mcp?param-style=flat_prefixed`; +const requestFor = (accountId?: string, timeout = 5_000) => ({ + endpoint, + headers: buildRequestHeaders({ apiKey: 'test-key', accountId }), + timeout, +}); + +describe('listMcpTools', () => { + it('lists every tool, following pagination', async () => { + const pages = [ + { tools: [{ name: 'tool_1', inputSchema: { type: 'object' } }], nextCursor: 'page-2' }, + { tools: [{ name: 'tool_2', inputSchema: { type: 'object' } }] }, + ]; + const cursors: unknown[] = []; + server.use( + http.post(`${TEST_BASE_URL}/mcp`, async ({ request }) => { + const message = (await request.json()) as { + id?: number; + method: string; + params?: { cursor?: string }; + }; + if (message.method === 'initialize') { + return HttpResponse.json({ + jsonrpc: '2.0', + id: message.id, + result: { + protocolVersion: '2025-06-18', + capabilities: { tools: {} }, + serverInfo: { name: 'paged', version: '1' }, + }, + }); + } + if (message.method === 'tools/list') { + cursors.push(message.params?.cursor); + const page = message.params?.cursor === 'page-2' ? pages[1] : pages[0]; + return HttpResponse.json({ jsonrpc: '2.0', id: message.id, result: page }); + } + return new HttpResponse(null, { status: 202 }); + }), + ); + + const tools = await listMcpTools(requestFor('acc1')); + + expect(tools.map((tool) => tool.name)).toEqual(['tool_1', 'tool_2']); + expect(cursors).toEqual([undefined, 'page-2']); }); - expect(mcpClient.client).toBeInstanceOf(Client); - expect(mcpClient.transport).toBeInstanceOf(StreamableHTTPClientTransport); - expect(typeof mcpClient[Symbol.asyncDispose]).toBe('function'); -}); + it('sends the credentials, the account and a version-bearing User-Agent', async () => { + const seen: Headers[] = []; + const app = createMcpApp({ accountTools: { acc1: [] } }); + server.use( + http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => { + seen.push(request.headers); + return app.fetch(request); + }), + ); + + await listMcpTools(requestFor('acc1')); + + expect(seen.length).toBeGreaterThan(0); + for (const headers of seen) { + expect(headers.get('x-account-id')).toBe('acc1'); + expect(headers.get('user-agent')).toBe(USER_AGENT); + expect(headers.get('authorization')).toMatch(/^Basic /); + } + }); + + it('surfaces an unscoped request as a 400 StackOneAPIError', async () => { + const error = (await listMcpTools(requestFor(undefined)).catch( + (caught: unknown) => caught, + )) as StackOneAPIError; -test('createMCPClient creates client with custom headers', async () => { - const mcpClient = await createMCPClient({ - baseUrl: 'https://api.example.com/mcp', - headers: { - Authorization: 'Bearer test-token', - 'x-custom-header': 'custom-value', - }, + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(400); + expect(error.message).toContain('x-account-id'); }); - expect(mcpClient.client).toBeInstanceOf(Client); - expect(mcpClient.transport).toBeInstanceOf(StreamableHTTPClientTransport); + // A dead account answers 412 with the reason in the body. The transport's own error buries + // the status in "Streamable HTTP error: Error POSTing to endpoint: …"; the caller needs it. + it('unwraps a transport HTTP failure into a StackOneAPIError with status and body', async () => { + server.use( + http.post(`${TEST_BASE_URL}/mcp`, () => + HttpResponse.json({ message: 're-link the account to resume' }, { status: 412 }), + ), + ); + + const error = (await listMcpTools(requestFor('acc1')).catch( + (caught: unknown) => caught, + )) as StackOneAPIError; + + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(412); + expect(error.responseBody).toEqual({ message: 're-link the account to resume' }); + expect(error.message).toBe( + `MCP request to ${endpoint} failed with 412 Precondition Failed: {"message":"re-link the account to resume"}`, + ); + }); }); -test('createMCPClient provides asyncDispose for cleanup', async () => { - const mcpClient = await createMCPClient({ - baseUrl: 'https://api.example.com/mcp', +describe('describeMcpFailure', () => { + it('passes SDK errors through untouched', () => { + const original = new ToolSetConfigError('already descriptive'); + expect(describeMcpFailure(original, endpoint, 1)).toBe(original); }); - // Spy on close methods - const clientCloseSpy = vi.spyOn(mcpClient.client, 'close').mockResolvedValue(undefined); - const transportCloseSpy = vi.spyOn(mcpClient.transport, 'close').mockResolvedValue(undefined); + it('reports the innermost cause, not the wrapper', () => { + const wrapped = new Error('outer', { cause: new TypeError('fetch failed: no route') }); + const error = describeMcpFailure(wrapped, endpoint, 1); + + expect(error).toBeInstanceOf(ToolSetLoadError); + expect(error.message).toBe( + `MCP request to ${endpoint} failed: TypeError: fetch failed: no route`, + ); + }); - // Call asyncDispose - await mcpClient[Symbol.asyncDispose](); + it('keeps a non-JSON body as text', () => { + const error = describeMcpFailure( + new StreamableHTTPError(503, 'Error POSTing to endpoint: upstream down'), + endpoint, + 1, + ) as StackOneAPIError; - expect(clientCloseSpy).toHaveBeenCalledOnce(); - expect(transportCloseSpy).toHaveBeenCalledOnce(); + expect(error.statusCode).toBe(503); + expect(error.responseBody).toBe('upstream down'); + }); }); -test('createMCPClient sends a version-bearing User-Agent on MCP requests', async () => { - const recordedRequests: Request[] = []; - const listener = ({ request }: { request: Request }) => { - recordedRequests.push(request); - }; - server.events.on('request:start', listener); +describe('parseToolResult', () => { + it('parses the text content as JSON', () => { + expect( + parseToolResult( + { content: [{ type: 'text', text: '{"actions":[{"action_id":"linear_list_comments"}]}' }] }, + 't', + ), + ).toEqual({ actions: [{ action_id: 'linear_list_comments' }] }); + }); + + it('wraps non-object and non-JSON text as { result }', () => { + expect(parseToolResult({ content: [{ type: 'text', text: '[1,2]' }] }, 't')).toEqual({ + result: [1, 2], + }); + expect(parseToolResult({ content: [{ type: 'text', text: 'plain' }] }, 't')).toEqual({ + result: 'plain', + }); + }); - await using mcpClient = await createMCPClient({ - baseUrl: 'http://localhost/mcp', - headers: { - Authorization: `Basic ${Buffer.from('test-key:').toString('base64')}`, - }, + it('falls back to structuredContent when there is no text', () => { + expect(parseToolResult({ content: [], structuredContent: { ok: true } }, 't')).toEqual({ + ok: true, + }); }); - await mcpClient.client.connect(mcpClient.transport); - await mcpClient.client.listTools(); + it('keeps non-text parts rather than dropping them', () => { + const image = { type: 'image', data: 'AAAA', mimeType: 'image/png' }; + expect(parseToolResult({ content: [{ type: 'text', text: '{"a":1}' }, image] }, 't')).toEqual({ + a: 1, + content_parts: [image], + }); + }); - server.events.removeListener('request:start', listener); + // A failed tools/call is an ordinary response with isError set. Returning its body as data + // would hand the caller an error as though it were a success. + it('raises on isError, with the status from the payload', () => { + let caught: unknown; + try { + parseToolResult( + { + isError: true, + content: [ + { type: 'text', text: '{"error":"Lambda execution failed","status_code":502}' }, + ], + }, + 'linear_execute_action', + ); + } catch (error) { + caught = error; + } - const mcpRequest = recordedRequests.find((request) => request.url.includes('/mcp')); - expect(mcpRequest?.headers.get('user-agent')).toBe(`stackone-ai-node/${version}`); + expect(caught).toBeInstanceOf(StackOneAPIError); + expect((caught as StackOneAPIError).message).toContain('Lambda execution failed'); + expect((caught as StackOneAPIError).statusCode).toBe(502); + }); + + it.each([ + [{ statusCode: 409 }, 409], + [{ error: { status_code: 429 } }, 429], + [{ data: { statusCode: 404 } }, 404], + [{ result: { status_code: 500 } }, 500], + [{ status_code: true }, 0], + [{ message: 'no status' }, 0], + ])('reads the status from %j', (payload, status) => { + expect(() => + parseToolResult( + { isError: true, content: [{ type: 'text', text: JSON.stringify(payload) }] }, + 't', + ), + ).toThrow(expect.objectContaining({ statusCode: status }) as Error); + }); }); -test('createMCPClient can connect and list tools from MCP server', async () => { - await using mcpClient = await createMCPClient({ - baseUrl: 'http://localhost/mcp', - headers: { - Authorization: `Basic ${Buffer.from('test-key:').toString('base64')}`, - 'x-account-id': 'test-account', - }, +describe('callMcpTool', () => { + it('calls the tool and returns its parsed result', async () => { + const app = createMcpApp({ accountTools: { acc1: [] }, submitFeedback: true }); + server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); + + const result = await callMcpTool(requestFor('acc1'), 'stackone_submit_feedback', { + rating: 'positive', + tool_names: ['x'], + session_id: 's-1', + }); + + expect(result).toMatchObject({ message: 'Feedback recorded', session_id: 's-1' }); }); +}); - await mcpClient.client.connect(mcpClient.transport); - const result = await mcpClient.client.listTools(); +describe('MCP timeouts', () => { + let silent: NetServer; + const sockets: Socket[] = []; + let port = 0; - expect(result.tools).toBeDefined(); - expect(Array.isArray(result.tools)).toBe(true); - expect(result.tools.length).toBeGreaterThan(0); + beforeAll(async () => { + // Accepts the connection and never answers. The MCP client's own defaults would hold this + // 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; + }); + afterAll(async () => { + for (const socket of sockets) { + socket.destroy(); + } + await new Promise((resolve) => silent.close(resolve)); + }); + + const silentRequest = () => ({ + endpoint: `http://127.0.0.1:${port}/mcp`, + headers: buildRequestHeaders({ apiKey: 'k', accountId: 'a' }), + timeout: 300, + }); + + it('bounds a listing by the timeout', async () => { + const started = Date.now(); + const error = await listMcpTools(silentRequest()).catch((caught: unknown) => caught); - const tool = result.tools[0]; - expect(tool.name).toBe('dummy_action'); - expect(tool.description).toBe('Dummy tool'); - expect(tool.inputSchema).toBeDefined(); + expect(error).toBeInstanceOf(ToolSetLoadError); + expect((error as Error).message).toMatch(/timed out after 300ms/); + expect(Date.now() - started).toBeLessThan(5_000); + }); + + it('bounds a tools/call by the timeout', async () => { + const started = Date.now(); + const error = await callMcpTool(silentRequest(), 'any', {}).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolSetLoadError); + expect(Date.now() - started).toBeLessThan(5_000); + }); }); diff --git a/src/mcp-client.ts b/src/mcp-client.ts index 3e9ca7cb..c0961d79 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -1,62 +1,242 @@ +import { STATUS_CODES } from 'node:http'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; -import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { + StreamableHTTPClientTransport, + StreamableHTTPError, +} from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; import { version } from '../package.json'; -import { USER_AGENT } from './consts'; +import type { JsonObject } from './types'; +import { StackOneAPIError } from './utils/error-stackone-api'; +import { StackOneError } from './utils/error-stackone'; +import { ToolSetLoadError } from './utils/error-toolset'; -interface MCPClientOptions { - baseUrl: string; - headers?: Record; +/** A tool exactly as the MCP server listed it. */ +export interface McpToolDefinition { + name: string; + description?: string; + inputSchema: Record; } -interface MCPClient { - /** underlying MCP client */ - client: Client; - - /** underlying transport */ - transport: StreamableHTTPClientTransport; +interface McpRequest { + endpoint: string; + /** The complete HTTP headers, credentials and account included. */ + headers: Record; + /** Deadline for the whole exchange, handshake included, in milliseconds. */ + timeout: number; +} - /** cleanup client and transport */ - [Symbol.asyncDispose](): Promise; +/** Raised by the overall deadline, so it can be told apart from a transport failure. */ +class McpDeadlineError extends Error { + constructor(timeout: number) { + super(`no response within ${timeout}ms`); + this.name = 'McpDeadlineError'; + } } +/** The prefix the transport puts in front of the server's response body. */ +const TRANSPORT_ERROR_PREFIX = /^Streamable HTTP error: Error POSTing to endpoint:\s*/; + +const parseBody = (text: string): unknown => { + if (!text) { + return null; + } + try { + return JSON.parse(text) as unknown; + } catch { + return text; + } +}; + /** - * Create a Model Context Protocol (MCP) client. + * Turn the MCP client's failure into something a caller can act on. * - * @example - * ```ts - * import { createMCPClient } from '@stackone/ai'; + * An HTTP error arrives as the transport's own error type, whose message buries the status in + * boilerplate. Unwrap it into a {@link StackOneAPIError} carrying the status and the response + * body — which is where the server explains itself: a dead account, for example, answers 412 + * with "re-link the account to resume". Anything else is reported by its innermost cause. + */ +export function describeMcpFailure(error: unknown, endpoint: string, timeout: number): Error { + if (error instanceof StackOneError) { + 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 }, + ); + } + if ( + error instanceof McpDeadlineError || + (error instanceof McpError && error.code === ErrorCode.RequestTimeout) + ) { + return new ToolSetLoadError(`MCP request to ${endpoint} timed out after ${timeout}ms`, { + cause: error, + }); + } + 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, + }); +} + +/** + * Open an MCP session, run `work` in it and close it, all within one deadline. * - * await using clients = await createMCPClient({ - * baseUrl: 'https://api.modelcontextprotocol.org', - * headers: { - * 'Authorization': 'Bearer YOUR_API_KEY', - * }, - * }); - * ``` + * The MCP client's own defaults are generous and apply per request, so a host that accepts the + * connection and never answers would hold a listing open far longer than the toolset's + * `timeout`. The whole exchange is bounded instead, and closing the client on expiry aborts the + * in-flight request. */ -export async function createMCPClient({ baseUrl, headers }: MCPClientOptions): Promise { - const transport = new StreamableHTTPClientTransport(new URL(baseUrl), { - requestInit: { - headers: { - // Version-bearing so /mcp requests are attributable to an exact SDK release. - // The transport sends no User-Agent of its own, and the plain USER_AGENT used on - // the other endpoints carries no version, which leaves tool listings anonymous. - 'User-Agent': `${USER_AGENT}/${version}`, - ...headers, - }, - }, +async function withMcpSession( + { endpoint, headers, timeout }: McpRequest, + work: (client: Client) => Promise, +): Promise { + const transport = new StreamableHTTPClientTransport(new URL(endpoint), { + requestInit: { headers }, }); + const client = new Client({ name: 'stackone-ai-node', version }); + let timer: ReturnType | undefined; + const deadline = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new McpDeadlineError(timeout)), timeout); + }); + try { + const session = (async () => { + await client.connect(transport, { timeout }); + return work(client); + })(); + return await Promise.race([session, deadline]); + } catch (error) { + throw describeMcpFailure(error, endpoint, timeout); + } finally { + clearTimeout(timer); + await client.close().catch(() => undefined); + } +} - const client = new Client({ - name: 'StackOne AI SDK', - version, +/** + * List every tool the MCP endpoint serves, following pagination. + */ +export async function listMcpTools(request: McpRequest): Promise { + return withMcpSession(request, async (client) => { + const collected: McpToolDefinition[] = []; + let cursor: string | undefined; + do { + const page = await client.listTools(cursor ? { cursor } : undefined, { + timeout: request.timeout, + }); + for (const tool of page.tools) { + collected.push({ + name: tool.name, + description: tool.description, + inputSchema: (tool.inputSchema ?? {}) as Record, + }); + } + cursor = page.nextCursor; + } while (cursor); + return collected; }); +} + +interface ContentPart { + type: string; + text?: unknown; +} - return { - client, - transport, - async [Symbol.asyncDispose]() { - await Promise.all([client.close(), transport.close()]); - }, - }; +/** + * Dig the HTTP status out of an MCP error payload. + * + * The transport succeeded, so there is no status on the response itself — but the payload + * carries one, and a caller cannot branch on 0. Both spellings and the wrapper keys the API + * uses are checked. + */ +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)) { + continue; + } + for (const key of ['status_code', 'statusCode']) { + const status = (candidate as JsonObject)[key]; + if (typeof status === 'number' && Number.isInteger(status)) { + return status; + } + } + } + return 0; +} + +/** + * Turn an MCP `tools/call` result into a plain object. + * + * Text parts are joined and parsed as JSON; a non-object is wrapped as `{ result }`. With no text + * at all, `structuredContent` is used. Parts that are not text (images, embedded resources) are + * kept under `content_parts` rather than silently dropped. + * + * @throws StackOneAPIError If the result carries `isError`. A failed tool call comes back as an + * ordinary response with that flag set, so without this check the error body would be handed + * to the caller as though it were a success. + */ +export function parseToolResult(result: Record, name: string): JsonObject { + 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; + } + + if (result.isError === true) { + throw new StackOneAPIError( + `Tool "${name}" failed: ${payload || JSON.stringify(parsed)}`, + statusOf(parsed), + parsed, + ); + } + + if (nonText.length > 0) { + parsed.content_parts = nonText as unknown as JsonObject[]; + } + return parsed; +} + +/** + * Invoke a tool over MCP `tools/call`. + */ +export async function callMcpTool( + request: McpRequest, + name: string, + args: JsonObject, +): Promise { + return withMcpSession(request, async (client) => { + const result = await client.callTool({ name, arguments: args }, undefined, { + timeout: request.timeout, + }); + return parseToolResult(result as Record, name); + }); } diff --git a/src/requestBuilder.test.ts b/src/requestBuilder.test.ts deleted file mode 100644 index 2e407710..00000000 --- a/src/requestBuilder.test.ts +++ /dev/null @@ -1,899 +0,0 @@ -import { fc, test as fcTest } from '@fast-check/vitest'; -import { http, HttpResponse } from 'msw'; -import { server } from '../mocks/node'; -import { type HttpExecuteConfig, type JsonObject, ParameterLocation } from './types'; -import { StackOneAPIError } from './utils/error-stackone-api'; -import { RequestBuilder } from './requestBuilder'; - -describe('RequestBuilder', () => { - let builder: RequestBuilder; - const recordRequests = () => { - const recordedRequests: Request[] = []; - const listener = ({ request }: { request: Request }) => { - recordedRequests.push(request); - }; - server.events.on('request:start', listener); - return recordedRequests; - }; - const mockConfig = { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/test/{pathParam}', - bodyType: 'json', - params: [ - { name: 'pathParam', location: ParameterLocation.PATH, type: 'string' }, - { name: 'queryParam', location: ParameterLocation.QUERY, type: 'string' }, - { name: 'headerParam', location: ParameterLocation.HEADER, type: 'string' }, - { name: 'bodyParam', location: ParameterLocation.BODY, type: 'string' }, - { name: 'defaultParam', location: ParameterLocation.BODY, type: 'string' }, - { name: 'filter', location: ParameterLocation.QUERY, type: 'object' }, - { name: 'proxy', location: ParameterLocation.QUERY, type: 'object' }, - { name: 'regularObject', location: ParameterLocation.QUERY, type: 'object' }, - { name: 'simple', location: ParameterLocation.QUERY, type: 'string' }, - { name: 'simpleString', location: ParameterLocation.QUERY, type: 'string' }, - { name: 'simpleNumber', location: ParameterLocation.QUERY, type: 'number' }, - { name: 'simpleBoolean', location: ParameterLocation.QUERY, type: 'boolean' }, - { name: 'complexObject', location: ParameterLocation.QUERY, type: 'object' }, - { name: 'deepFilter', location: ParameterLocation.QUERY, type: 'object' }, - { name: 'emptyFilter', location: ParameterLocation.QUERY, type: 'object' }, - ], - } satisfies HttpExecuteConfig; - - beforeEach(() => { - builder = new RequestBuilder(mockConfig, { 'Initial-Header': 'test' }); - server.use( - http.get('https://api.example.com/test/:pathParam', ({ params, request }) => { - const url = new URL(request.url); - const queryParam = url.searchParams.get('queryParam'); - - if (params.pathParam === 'invalid') { - return HttpResponse.json({ error: 'Not found' }, { status: 404 }); - } - - return HttpResponse.json({ - success: true, - pathParam: params.pathParam, - queryParam, - }); - }), - ); - }); - - afterEach(() => { - server.events.removeAllListeners('request:start'); - }); - - it('should initialize with headers from constructor', () => { - expect(builder.getHeaders()).toEqual({ 'Initial-Header': 'test' }); - }); - - it('should set and get headers', () => { - builder.setHeaders({ 'New-Header': 'value' }); - expect(builder.getHeaders()).toEqual({ - 'Initial-Header': 'test', - 'New-Header': 'value', - }); - }); - - it('should prepare headers', () => { - builder.setHeaders({ 'Custom-Header': 'value' }); - const headers = builder.prepareHeaders(); - - expect(headers).toEqual({ - 'User-Agent': 'stackone-ai-node', - 'Initial-Header': 'test', - 'Custom-Header': 'value', - }); - }); - - it('should prepare request parameters correctly', () => { - const params = { - pathParam: 'path-value', - queryParam: 'query-value', - headerParam: 'header-value', - bodyParam: 'body-value', - defaultParam: 'default-value', - }; - - const [url, bodyParams, queryParams] = builder.prepareRequestParams(params); - - expect(url).toBe('https://api.example.com/test/path-value'); - expect(queryParams).toEqual({ queryParam: 'query-value' }); - expect(bodyParams).toEqual({ - bodyParam: 'body-value', - defaultParam: 'default-value', - }); - expect(builder.getHeaders()).toEqual({ - 'Initial-Header': 'test', - headerParam: 'header-value', - }); - }); - - it('should build fetch options for JSON body type', () => { - const bodyParams = { test: 'value' }; - const options = builder.buildFetchOptions(bodyParams); - - expect(options.method).toBe('GET'); - expect(options.headers).toHaveProperty('Content-Type', 'application/json'); - expect(options.body).toBe(JSON.stringify(bodyParams)); - }); - - it('should build fetch options for form body type', () => { - const formBuilder = new RequestBuilder({ - ...mockConfig, - bodyType: 'form', - }); - - const bodyParams = { test: 'value' }; - const options = formBuilder.buildFetchOptions(bodyParams); - - expect(options.headers).toHaveProperty('Content-Type', 'application/x-www-form-urlencoded'); - expect(options.body).toBe('test=value'); - }); - - it('should build fetch options for multipart-form body type', () => { - const formBuilder = new RequestBuilder({ - ...mockConfig, - bodyType: 'multipart-form', - }); - - const bodyParams = { test: 'value' }; - const options = formBuilder.buildFetchOptions(bodyParams); - - expect(options.body).toBeInstanceOf(FormData); - }); - - it('should execute a request successfully', async () => { - const params = { - pathParam: 'path-value', - queryParam: 'query-value', - }; - - const recordedRequests = recordRequests(); - - const result = await builder.execute(params); - - expect(result).toEqual({ success: true, pathParam: 'path-value', queryParam: 'query-value' }); - expect(recordedRequests).toHaveLength(1); - expect(recordedRequests[0]?.url).toBe( - 'https://api.example.com/test/path-value?queryParam=query-value', - ); - }); - - it('should return request details on dry run', async () => { - const params = { pathParam: 'path-value' }; - - const recordedRequests = recordRequests(); - - const result = await builder.execute(params, { dryRun: true }); - - expect(result).toEqual({ - url: 'https://api.example.com/test/path-value', - method: 'GET', - headers: { - 'User-Agent': 'stackone-ai-node', - 'Initial-Header': 'test', - }, - body: null, - mappedParams: params, - }); - expect(recordedRequests).toHaveLength(0); - }); - - it('should throw StackOneAPIError when API request fails', async () => { - const params = { pathParam: 'invalid' }; - const recordedRequests = recordRequests(); - - await expect(builder.execute(params)).rejects.toThrow(StackOneAPIError); - expect(recordedRequests).toHaveLength(1); - expect(recordedRequests[0]?.url).toBe('https://api.example.com/test/invalid'); - }); - - it('should serialize deep object query parameters correctly', async () => { - const params = { - pathParam: 'test-value', - filter: { - updated_after: '2020-01-01T00:00:00.000Z', - job_id: '123', - nested: { - level2: 'value', - level3: { - deep: 'nested-value', - }, - }, - }, - proxy: { - custom_field: 'custom-value', - sort: 'first_name', - }, - simple: 'simple-value', - }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - // Check that deep object parameters are serialized correctly - expect(url.searchParams.get('filter[updated_after]')).toBe('2020-01-01T00:00:00.000Z'); - expect(url.searchParams.get('filter[job_id]')).toBe('123'); - expect(url.searchParams.get('filter[nested][level2]')).toBe('value'); - expect(url.searchParams.get('filter[nested][level3][deep]')).toBe('nested-value'); - expect(url.searchParams.get('proxy[custom_field]')).toBe('custom-value'); - expect(url.searchParams.get('proxy[sort]')).toBe('first_name'); - - // Check that simple parameters are still handled normally - expect(url.searchParams.get('simple')).toBe('simple-value'); - - // Ensure the original filter/proxy objects are not added as strings - expect(url.searchParams.get('filter')).toBeNull(); - expect(url.searchParams.get('proxy')).toBeNull(); - }); - - it('should handle null values in deep objects', async () => { - const params = { - pathParam: 'test-value', - filter: { - valid_field: 'value', - null_field: null, - empty_string: '', - zero: 0, - false_value: false, - }, - }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - // Check that valid values are included - expect(url.searchParams.get('filter[valid_field]')).toBe('value'); - expect(url.searchParams.get('filter[empty_string]')).toBe(''); - expect(url.searchParams.get('filter[zero]')).toBe('0'); - expect(url.searchParams.get('filter[false_value]')).toBe('false'); - - // Check that null values are excluded - expect(url.searchParams.get('filter[null_field]')).toBeNull(); - }); - - it('should apply deep object serialization to all object parameters', async () => { - const params = { - pathParam: 'test-value', - regularObject: { - nested: 'value', - deepNested: { - level2: 'deep-value', - }, - }, - }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - // All objects should now be serialized using deep object notation - expect(url.searchParams.get('regularObject[nested]')).toBe('value'); - expect(url.searchParams.get('regularObject[deepNested][level2]')).toBe('deep-value'); - - // The original object parameter should not be present as a string - expect(url.searchParams.get('regularObject')).toBeNull(); - }); - - it('should handle mixed parameter types with deep object serialization', async () => { - const params = { - pathParam: 'test-value', - simpleString: 'simple-value', - simpleNumber: 42, - simpleBoolean: true, - complexObject: { - nested: 'nested-value', - array: [1, 2, 3], // Arrays should be converted to string - nestedObject: { - deep: 'deep-value', - }, - }, - }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - // Primitive values should be handled normally - expect(url.searchParams.get('simpleString')).toBe('simple-value'); - expect(url.searchParams.get('simpleNumber')).toBe('42'); - expect(url.searchParams.get('simpleBoolean')).toBe('true'); - - // Complex object should use deep object serialization - expect(url.searchParams.get('complexObject[nested]')).toBe('nested-value'); - expect(url.searchParams.get('complexObject[array]')).toBe('[1,2,3]'); // Arrays become JSON strings - expect(url.searchParams.get('complexObject[nestedObject][deep]')).toBe('deep-value'); - - // Original complex object should not be present - expect(url.searchParams.get('complexObject')).toBeNull(); - }); - - describe('Security and Performance Improvements', () => { - it('should throw error when circular reference is detected', async () => { - // Test runtime behavior when circular reference is passed - // Note: This tests error handling for malformed input at runtime - const inner: Record = { b: 'test' }; - const circular: Record = { a: inner }; - inner.circular = circular; // Create circular reference - - const params = { - pathParam: 'test-value', - filter: circular, - } as unknown as JsonObject; // Cast to test runtime error handling - - await expect(builder.execute(params, { dryRun: true })).rejects.toThrow( - 'Circular reference detected in parameter object', - ); - }); - - it('should handle special types correctly at runtime', async () => { - // Test runtime behavior when non-JSON types are passed - // Note: Date and RegExp are not valid JsonValue types, but we test - // the serialiser's runtime handling of these edge cases - const testDate = new Date('2023-01-01T00:00:00.000Z'); - const testRegex = /test-pattern/gi; - - const params = { - pathParam: 'test-value', - filter: { - dateField: testDate, - regexField: testRegex, - nullField: null, - emptyString: '', - }, - } as unknown as JsonObject; // Cast to test runtime serialization - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - // Date should be serialized to ISO string - expect(url.searchParams.get('filter[dateField]')).toBe('2023-01-01T00:00:00.000Z'); - - // RegExp should be serialized to string representation - expect(url.searchParams.get('filter[regexField]')).toBe('/test-pattern/gi'); - - // Null should be filtered out - expect(url.searchParams.get('filter[nullField]')).toBeNull(); - - // Empty string should be preserved - expect(url.searchParams.get('filter[emptyString]')).toBe(''); - }); - - it('should throw error when trying to serialize functions at runtime', async () => { - // Test runtime error handling when functions are passed - const params = { - pathParam: 'test-value', - filter: { - validField: 'test', - functionField: () => 'test', // Functions should not be serializable - }, - } as unknown as JsonObject; // Cast to test runtime error handling - - await expect(builder.execute(params, { dryRun: true })).rejects.toThrow( - 'Functions cannot be serialized as parameters', - ); - }); - - it('should handle empty objects correctly', async () => { - const params = { - pathParam: 'test-value', - emptyFilter: {}, - filter: { - validField: 'test', - emptyNested: {}, - }, - }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - // Empty objects should not create any parameters - expect(url.searchParams.get('emptyFilter')).toBeNull(); - expect(url.searchParams.get('filter[emptyNested]')).toBeNull(); - - // Valid fields should still work - expect(url.searchParams.get('filter[validField]')).toBe('test'); - }); - - it('should handle arrays correctly within objects', async () => { - const params = { - pathParam: 'test-value', - filter: { - arrayField: [1, 2, 3], - stringArray: ['a', 'b', 'c'], - mixed: ['string', 42, true], - }, - }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - // Arrays should be converted to JSON strings - expect(url.searchParams.get('filter[arrayField]')).toBe('[1,2,3]'); - expect(url.searchParams.get('filter[stringArray]')).toBe('["a","b","c"]'); - expect(url.searchParams.get('filter[mixed]')).toBe('["string",42,true]'); - }); - - it('should handle nested objects with special types at runtime', async () => { - // Test runtime serialization of nested non-JSON types - const params = { - pathParam: 'test-value', - filter: { - nested: { - dateField: new Date('2023-01-01T00:00:00.000Z'), - level2: { - regexField: /test/, - stringField: 'normal-string', - }, - }, - }, - } as unknown as JsonObject; // Cast to test runtime serialization - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - expect(url.searchParams.get('filter[nested][dateField]')).toBe('2023-01-01T00:00:00.000Z'); - expect(url.searchParams.get('filter[nested][level2][regexField]')).toBe('/test/'); - expect(url.searchParams.get('filter[nested][level2][stringField]')).toBe('normal-string'); - }); - - it('should maintain performance with large objects', async () => { - // Create a moderately large object to test performance optimizations - const largeFilter: Record = {}; - for (let i = 0; i < 100; i++) { - largeFilter[`field_${i}`] = `value_${i}`; - if (i % 10 === 0) { - largeFilter[`nested_${i}`] = { - subField1: `sub_value_${i}_1`, - subField2: `sub_value_${i}_2`, - }; - } - } - - const params = { - pathParam: 'test-value', - filter: largeFilter, - } satisfies JsonObject; - - const startTime = performance.now(); - const result = await builder.execute(params, { dryRun: true }); - const endTime = performance.now(); - - // Should complete in reasonable time (less than 100ms for this size) - expect(endTime - startTime).toBeLessThan(100); - - const url = new URL(result.url as string); - - // Verify some parameters are correctly serialized - expect(url.searchParams.get('filter[field_0]')).toBe('value_0'); - expect(url.searchParams.get('filter[field_99]')).toBe('value_99'); - expect(url.searchParams.get('filter[nested_0][subField1]')).toBe('sub_value_0_1'); - }); - - it('should allow the same object in different branches after circular check', async () => { - const sharedObject = { shared: 'value' }; - const params = { - pathParam: 'test-value', - filter: { - branch1: { - shared: sharedObject, - }, - branch2: { - shared: sharedObject, // Same object reference in different branch - should be allowed - }, - }, - }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - // Both branches should be serialized correctly - expect(url.searchParams.get('filter[branch1][shared][shared]')).toBe('value'); - expect(url.searchParams.get('filter[branch2][shared][shared]')).toBe('value'); - }); - }); -}); - -/** - * Property-Based Tests for RequestBuilder - * - * These tests verify invariants that must hold for ANY valid input, - * replacing/supplementing example-based tests: - * - * Parameter Key Validation (replaces "should validate parameter keys and reject invalid characters"): - * - Valid: "user_id", "filter.name", "x-custom-field" => accepted - * - Invalid: "invalid key with spaces", "key@special!" => throws "Invalid parameter key" - * - * Value Serialization (supplements "should handle arrays correctly within objects" - kept for clarity): - * - { arrayField: [1, 2, 3] } => filter[arrayField]="[1,2,3]" - * - { stringArray: ["a", "b"] } => filter[stringArray]='["a","b"]' - * - * Deep Object Nesting (replaces "should throw error when recursion depth limit is exceeded"): - * - { nested: { nested: { value: "ok" } } } (depth 3) => accepted - * - { nested: { nested: { ... 12 levels ... } } } => throws "Maximum nesting depth (10) exceeded" - */ -describe('RequestBuilder - Property-Based Tests', () => { - const baseConfig = { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/test', - bodyType: 'json', - params: [{ name: 'filter', location: ParameterLocation.QUERY, type: 'object' }], - } satisfies HttpExecuteConfig; - - // Arbitrary for valid parameter keys (alphanumeric, underscore, dot, hyphen) - const validKeyArbitrary = fc.stringMatching(/^[a-zA-Z][a-zA-Z0-9_.-]{0,19}$/); - - // Arbitrary for invalid parameter keys (contains spaces or special chars) - const invalidKeyArbitrary = fc - .string({ minLength: 1, maxLength: 20 }) - .filter((s) => /[^a-zA-Z0-9_.-]/.test(s) && s.trim().length > 0); - - /** - * Parameter Key Validation - * - * Examples of valid keys: "user_id", "filter.name", "X-Custom-Header" - * Examples of invalid keys: "invalid key", "special@char", "has spaces" - */ - describe('Parameter Key Validation', () => { - // Example: { filter: { user_id: "123" } } => ?filter[user_id]=123 (no error) - fcTest.prop([validKeyArbitrary, fc.string()], { numRuns: 100 })( - 'accepts valid parameter keys', - async (key, value) => { - const builder = new RequestBuilder(baseConfig); - const params = { - filter: { [key]: value }, - }; - - // Should not throw for valid keys - const result = await builder.execute(params, { dryRun: true }); - expect(result.url).toBeDefined(); - }, - ); - - // Example: { filter: { "invalid key with spaces": "test" } } => throws Error - fcTest.prop([invalidKeyArbitrary, fc.string()], { numRuns: 100 })( - 'rejects invalid parameter keys', - async (key, value) => { - const builder = new RequestBuilder(baseConfig); - const params = { - filter: { [key]: value }, - }; - - await expect(builder.execute(params, { dryRun: true })).rejects.toThrow( - /Invalid parameter key/, - ); - }, - ); - }); - - /** - * Header Management - * - * Examples: - * - new RequestBuilder(config, { "Auth": "token" }).setHeaders({ "X-Api": "key" }) - * => getHeaders() returns { "Auth": "token", "X-Api": "key" } - * - prepareHeaders() always includes "User-Agent: stackone-ai-node" - */ - describe('Header Management', () => { - // Arbitrary for header key-value pairs - const headerArbitrary = fc.dictionary( - fc.stringMatching(/^[a-zA-Z][a-zA-Z0-9-]{0,29}$/), - fc.string({ minLength: 1, maxLength: 100 }), - { minKeys: 1, maxKeys: 5 }, - ); - - // Example: init with {"A": "1"}, setHeaders({"B": "2"}) => {"A": "1", "B": "2"} - fcTest.prop([headerArbitrary, headerArbitrary], { numRuns: 50 })( - 'setHeaders accumulates headers without losing existing ones', - (headers1, headers2) => { - const builder = new RequestBuilder(baseConfig, headers1); - builder.setHeaders(headers2); - - const result = builder.getHeaders(); - - // All headers from both sets should be present (with headers2 overriding duplicates) - for (const [key, value] of Object.entries(headers2)) { - expect(result[key]).toBe(value); - } - for (const [key, value] of Object.entries(headers1)) { - if (!(key in headers2)) { - expect(result[key]).toBe(value); - } - } - }, - ); - - // Example: prepareHeaders() => { "User-Agent": "stackone-ai-node", ...customHeaders } - fcTest.prop([headerArbitrary], { numRuns: 50 })( - 'prepareHeaders always includes User-Agent', - (headers) => { - const builder = new RequestBuilder(baseConfig, headers); - const prepared = builder.prepareHeaders(); - - expect(prepared['User-Agent']).toBe('stackone-ai-node'); - }, - ); - - // Example: const h = getHeaders(); h["X"] = "Y"; getHeaders()["X"] is still undefined - fcTest.prop([headerArbitrary], { numRuns: 50 })( - 'getHeaders returns a copy, not the original', - (headers) => { - const builder = new RequestBuilder(baseConfig, headers); - const retrieved = builder.getHeaders(); - - // Mutating the returned object should not affect internal state - retrieved['Mutated-Header'] = 'mutated'; - - expect(builder.getHeaders()['Mutated-Header']).toBeUndefined(); - }, - ); - }); - - /** - * Value Serialization - * - * Examples: - * - { key: "hello" } => ?filter[key]=hello - * - { key: 42 } => ?filter[key]=42 - * - { key: true } => ?filter[key]=true - * - { key: [1, 2, 3] } => ?filter[key]=[1,2,3] - * - { key: ["a", "b"] } => ?filter[key]=["a","b"] - */ - describe('Value Serialization', () => { - // Example: { filter: { key: "hello world" } } => ?filter[key]=hello%20world - fcTest.prop([fc.string()], { numRuns: 100 })( - 'string values serialize to themselves', - async (str) => { - const builder = new RequestBuilder(baseConfig); - const params = { filter: { key: str } }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - expect(url.searchParams.get('filter[key]')).toBe(str); - }, - ); - - // Example: { filter: { key: 42 } } => ?filter[key]=42 - fcTest.prop([fc.integer()], { numRuns: 100 })( - 'integer values serialize to string', - async (num) => { - const builder = new RequestBuilder(baseConfig); - const params = { filter: { key: num } }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - expect(url.searchParams.get('filter[key]')).toBe(String(num)); - }, - ); - - // Example: { filter: { key: true } } => ?filter[key]=true - fcTest.prop([fc.boolean()], { numRuns: 10 })( - 'boolean values serialize to string', - async (bool) => { - const builder = new RequestBuilder(baseConfig); - const params = { filter: { key: bool } }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - expect(url.searchParams.get('filter[key]')).toBe(String(bool)); - }, - ); - - // Example: { filter: { key: [1, 2, 3] } } => ?filter[key]=[1,2,3] - // Example: { filter: { key: ["a", "b"] } } => ?filter[key]=["a","b"] - fcTest.prop( - [fc.array(fc.oneof(fc.string(), fc.integer(), fc.boolean()), { minLength: 1, maxLength: 5 })], - { - numRuns: 50, - }, - )('arrays serialize to JSON string', async (arr) => { - const builder = new RequestBuilder(baseConfig); - const params = { filter: { key: arr } }; - - const result = await builder.execute(params, { dryRun: true }); - const url = new URL(result.url as string); - - expect(url.searchParams.get('filter[key]')).toBe(JSON.stringify(arr)); - }); - }); - - /** - * Deep Object Nesting - * - * Examples: - * - { nested: { value: "ok" } } (depth 2) => accepted - * - { a: { b: { c: { d: { e: { f: { g: { h: { i: { j: { k: "too deep" } } } } } } } } } } } - * (depth 11) => throws "Maximum nesting depth (10) exceeded" - */ - describe('Deep Object Nesting', () => { - // Example: depth 5 => { nested: { nested: { nested: { nested: { nested: { value: "test" } } } } } } - fcTest.prop([fc.integer({ min: 1, max: 9 })], { numRuns: 20 })( - 'accepts objects within depth limit', - async (depth) => { - const builder = new RequestBuilder(baseConfig); - const deepObject = {}; - let current: Record = deepObject; - for (let i = 0; i < depth; i++) { - current.nested = {}; - current = current.nested as Record; - } - current.value = 'test'; - - const params = { filter: deepObject } as JsonObject; - const result = await builder.execute(params, { dryRun: true }); - - expect(result.url).toBeDefined(); - }, - ); - - // Example: 12 levels of nesting => throws error - test('rejects objects exceeding depth limit of 10', async () => { - const builder = new RequestBuilder(baseConfig); - let deepObject: Record = { value: 'test' }; - for (let i = 0; i < 12; i++) { - deepObject = { nested: deepObject }; - } - - const params = { filter: deepObject } as JsonObject; - - await expect(builder.execute(params, { dryRun: true })).rejects.toThrow( - /Maximum nesting depth.*exceeded/, - ); - }); - }); - - /** - * Body Type Handling - * - * Examples: - * - bodyType: "json" => Content-Type: application/json, body: '{"test":"value"}' - * - bodyType: "form" => Content-Type: application/x-www-form-urlencoded, body: "test=value" - * - bodyType: "multipart-form" => body is FormData instance - */ - describe('Body Type Handling', () => { - const bodyTypes = ['json', 'form', 'multipart-form'] as const; - - // Example: buildFetchOptions({ test: "value" }) with bodyType "json" => valid options - fcTest.prop( - [ - fc.constantFrom(...bodyTypes), - fc.dictionary(fc.string(), fc.string(), { minKeys: 1, maxKeys: 3 }), - ], - { - numRuns: 30, - }, - )('all valid body types produce valid fetch options', (bodyType, bodyParams) => { - const config = { ...baseConfig, bodyType }; - const builder = new RequestBuilder(config); - - const options = builder.buildFetchOptions(bodyParams); - - expect(options.method).toBe('GET'); - expect(options.body).toBeDefined(); - }); - }); -}); - -/** - * Binary file downloads - * - * File-download actions (e.g. googledrive_unified_download_file) serve raw binary with - * the file's own MIME type and a Content-Disposition header - never JSON. The execute() - * path must branch on Content-Type and return the bytes plus metadata instead of forcing - * a JSON parse (which throws on binary bodies containing non-UTF8 bytes). - */ -describe('RequestBuilder - binary file downloads', () => { - const downloadConfig = { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/download/{id}', - bodyType: 'json', - params: [{ name: 'id', location: ParameterLocation.PATH, type: 'string' }], - } satisfies HttpExecuteConfig; - - it('returns raw bytes + metadata for a non-JSON (binary) response', async () => { - // Leading bytes of a real PDF; the 0xc4 byte is invalid UTF-8 and is exactly what - // makes an unconditional response.json() throw on a binary body. - const pdfBytes = new Uint8Array([ - 0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34, 0x0a, 0x25, 0xc4, 0xe5, 0xf2, 0xe5, 0xeb, - ]); - server.use( - http.get( - 'https://api.example.com/download/:id', - () => - new HttpResponse(pdfBytes, { - status: 200, - headers: { - 'content-type': 'application/pdf', - 'content-disposition': 'attachment; filename="download.pdf"', - }, - }), - ), - ); - - const builder = new RequestBuilder(downloadConfig); - const result = await builder.execute({ id: 'file-123' }); - - expect(result.content).toBeInstanceOf(Buffer); - expect((result.content as unknown as Buffer).equals(Buffer.from(pdfBytes))).toBe(true); - expect(result.contentType).toBe('application/pdf'); - expect(result.statusCode).toBe(200); - expect(result.fileName).toBe('download.pdf'); - expect((result.headers as Record)['content-type']).toBe('application/pdf'); - }); - - it('returns bytes with fileName null when there is no Content-Disposition', async () => { - const blob = new Uint8Array([0x00, 0x01, 0x02, 0xc4, 0xff, 0xfe]); - server.use( - http.get( - 'https://api.example.com/download/:id', - () => - new HttpResponse(blob, { - status: 200, - headers: { 'content-type': 'application/octet-stream' }, - }), - ), - ); - - const builder = new RequestBuilder(downloadConfig); - const result = await builder.execute({ id: 'blob' }); - - expect((result.content as unknown as Buffer).equals(Buffer.from(blob))).toBe(true); - expect(result.contentType).toBe('application/octet-stream'); - expect(result.fileName).toBeNull(); - }); - - it('still parses a normal JSON response into an object (no content wrapper)', async () => { - server.use( - http.get('https://api.example.com/download/:id', () => - HttpResponse.json({ id: '123', ok: true }), - ), - ); - - const builder = new RequestBuilder(downloadConfig); - const result = await builder.execute({ id: 'json' }); - - expect(result).toEqual({ id: '123', ok: true }); - expect(result.content).toBeUndefined(); - }); - - it('parses JSON when the Content-Type carries a charset parameter', async () => { - server.use( - http.get( - 'https://api.example.com/download/:id', - () => - new HttpResponse('{"ok":true}', { - status: 200, - headers: { 'content-type': 'application/json; charset=utf-8' }, - }), - ), - ); - - const builder = new RequestBuilder(downloadConfig); - const result = await builder.execute({ id: 'json-charset' }); - - expect(result).toEqual({ ok: true }); - }); - - it('treats a response with no Content-Type as opaque bytes, not JSON', async () => { - // JPEG magic bytes, no content-type. The SDK trusts Content-Type to choose JSON vs - // file, so an absent Content-Type returns raw bytes rather than risking a JSON decode. - const blob = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46]); - server.use( - http.get( - 'https://api.example.com/download/:id', - () => new HttpResponse(blob, { status: 200 }), - ), - ); - - const builder = new RequestBuilder(downloadConfig); - const result = await builder.execute({ id: 'no-ct' }); - - expect((result.content as unknown as Buffer).equals(Buffer.from(blob))).toBe(true); - expect(result.contentType).toBe('application/octet-stream'); - expect(result.fileName).toBeNull(); - }); -}); diff --git a/src/requestBuilder.ts b/src/requestBuilder.ts deleted file mode 100644 index a35896e2..00000000 --- a/src/requestBuilder.ts +++ /dev/null @@ -1,397 +0,0 @@ -import type { JsonValue } from 'type-fest'; -import { USER_AGENT } from './consts'; -import { - type ExecuteOptions, - type HttpBodyType, - type HttpExecuteConfig, - type JsonObject, - ParameterLocation, -} from './types'; -import { binaryDownloadFromResponse, isJsonContentType } from './utils/binary-response'; -import { StackOneAPIError } from './utils/error-stackone-api'; - -interface SerializationOptions { - maxDepth?: number; - strictValidation?: boolean; -} - -class ParameterSerializationError extends Error { - constructor(message: string, options?: ErrorOptions) { - super(message, options); - this.name = 'ParameterSerializationError'; - } -} - -/** - * Convert a JsonValue to a string representation suitable for URLs and form data. - * Objects and arrays are JSON-stringified, primitives are converted directly. - */ -function stringifyValue(value: JsonValue): string { - if (typeof value === 'string') { - return value; - } - if (typeof value === 'number' || typeof value === 'boolean') { - return String(value); - } - if (value === null) { - return ''; - } - // Arrays and objects - return JSON.stringify(value); -} - -/** - * Builds and executes HTTP requests for tools declared with kind:'http'. - */ -export class RequestBuilder { - private method: string; - private url: string; - private bodyType: HttpBodyType; - private params: HttpExecuteConfig['params']; - private headers: Record; - - constructor(config: HttpExecuteConfig, headers: Record = {}) { - this.method = config.method; - this.url = config.url; - this.bodyType = config.bodyType; - this.params = config.params; - this.headers = { ...headers }; - } - - /** - * Set headers for the request - */ - setHeaders(headers: Record): RequestBuilder { - this.headers = { ...this.headers, ...headers }; - return this; - } - - /** - * Get the current headers - */ - getHeaders(): Record { - return { ...this.headers }; - } - - /** - * Prepare headers for the API request - */ - prepareHeaders(): Record { - return { - 'User-Agent': USER_AGENT, - ...this.headers, - }; - } - - /** - * Prepare URL and parameters for the API request - */ - prepareRequestParams(params: JsonObject): [string, JsonObject, JsonObject] { - let url = this.url; - const bodyParams: JsonObject = {}; - const queryParams: JsonObject = {}; - - for (const [key, value] of Object.entries(params)) { - // Find the parameter configuration in the params array - const paramConfig = this.params.find((p) => p.name === key); - const paramLocation = paramConfig?.location; - - switch (paramLocation) { - case ParameterLocation.PATH: - // Replace path parameter in URL - url = url.replace(`{${key}}`, encodeURIComponent(stringifyValue(value))); - break; - case ParameterLocation.QUERY: - // Add to query parameters - queryParams[key] = value; - break; - case ParameterLocation.HEADER: - // Add to headers - this.headers[key] = stringifyValue(value); - break; - case ParameterLocation.BODY: - // Add to body parameters - bodyParams[key] = value; - break; - default: - paramLocation satisfies undefined; // exhaustive check - // Default to body parameters - bodyParams[key] = value; - break; - } - } - - return [url, bodyParams, queryParams]; - } - - /** - * Build the fetch options for the request - */ - buildFetchOptions(bodyParams: JsonObject): RequestInit { - const headers = this.prepareHeaders(); - const fetchOptions: RequestInit = { - method: this.method, - headers, - }; - - // Handle different body types - if (Object.keys(bodyParams).length > 0) { - switch (this.bodyType) { - case 'json': { - const headersRecord = fetchOptions.headers as Record; - fetchOptions.headers = { - ...headersRecord, - 'Content-Type': 'application/json', - }; - fetchOptions.body = JSON.stringify(bodyParams); - break; - } - case 'form': { - const headersRecord = fetchOptions.headers as Record; - fetchOptions.headers = { - ...headersRecord, - 'Content-Type': 'application/x-www-form-urlencoded', - }; - const formBody = new URLSearchParams(); - for (const [key, value] of Object.entries(bodyParams)) { - formBody.append(key, stringifyValue(value)); - } - fetchOptions.body = formBody.toString(); - break; - } - case 'multipart-form': { - // Handle file uploads - const formData = new FormData(); - for (const [key, value] of Object.entries(bodyParams)) { - formData.append(key, stringifyValue(value)); - } - fetchOptions.body = formData; - // Don't set Content-Type for FormData, it will be set automatically with the boundary - break; - } - default: { - this.bodyType satisfies never; - throw new Error(`Unsupported HTTP body type: ${String(this.bodyType)}`); - } - } - } - - return fetchOptions; - } - - /** - * Validates parameter keys to prevent injection attacks - */ - private validateParameterKey(key: string): void { - if (!/^[a-zA-Z0-9_.-]+$/.test(key)) { - throw new ParameterSerializationError(`Invalid parameter key: ${key}`); - } - } - - /** - * Safely serializes values to strings with special type handling - */ - private serializeValue(value: unknown): string { - if (value instanceof Date) { - return value.toISOString(); - } - if (value instanceof RegExp) { - return value.toString(); - } - if (typeof value === 'function') { - throw new ParameterSerializationError('Functions cannot be serialized as parameters'); - } - if (value == null) { - return ''; - } - if (typeof value === 'string') { - return value; - } - if (typeof value === 'number' || typeof value === 'boolean') { - return String(value); - } - // For objects and arrays, use JSON serialization - return JSON.stringify(value); - } - - /** - * Serialize an object into deep object query parameters with security protections - * Converts {filter: {updated_after: "2020-01-01", job_id: "123"}} - * to filter[updated_after]=2020-01-01&filter[job_id]=123 - */ - private serializeDeepObject( - obj: unknown, - prefix: string, - depth = 0, - visited = new WeakSet(), - options: SerializationOptions = {}, - ): [string, string][] { - const maxDepth = options.maxDepth ?? 10; - const strictValidation = options.strictValidation ?? true; - const params: [string, string][] = []; - - // Recursion depth protection - if (depth > maxDepth) { - throw new ParameterSerializationError( - `Maximum nesting depth (${maxDepth}) exceeded for parameter serialization`, - ); - } - - if (obj == null) { - return params; - } - - if (typeof obj === 'object' && !Array.isArray(obj)) { - // Circular reference protection - if (visited.has(obj)) { - throw new ParameterSerializationError('Circular reference detected in parameter object'); - } - visited.add(obj); - - try { - for (const [key, value] of Object.entries(obj as Record)) { - if (strictValidation) { - this.validateParameterKey(key); - } - - const nestedKey = `${prefix}[${key}]`; - if (value != null) { - if (this.shouldUseDeepObjectSerialization(key, value)) { - // Recursively handle nested objects - params.push( - ...this.serializeDeepObject(value, nestedKey, depth + 1, visited, options), - ); - } else { - params.push([nestedKey, this.serializeValue(value)]); - } - } - } - } finally { - // Remove from visited set to allow the same object in different branches - visited.delete(obj); - } - } else { - // For non-object values, use the prefix as-is - params.push([prefix, this.serializeValue(obj)]); - } - - return params; - } - - /** - * Check if a parameter should use deep object serialization - * Applies to all plain object parameters (excludes special types and arrays) - */ - private shouldUseDeepObjectSerialization(_key: string, value: unknown): boolean { - return ( - typeof value === 'object' && - value !== null && - !Array.isArray(value) && - !(value instanceof Date) && - !(value instanceof RegExp) && - typeof value !== 'function' - ); - } - - /** - * Builds all query parameters with optimized batching - */ - private buildQueryParameters(queryParams: JsonObject): [string, string][] { - const allParams: [string, string][] = []; - - for (const [key, value] of Object.entries(queryParams)) { - if (this.shouldUseDeepObjectSerialization(key, value)) { - // Use deep object serialization for complex parameters - allParams.push(...this.serializeDeepObject(value, key)); - } else { - // Use safe string conversion for primitive values - allParams.push([key, this.serializeValue(value)]); - } - } - - return allParams; - } - - /** - * Execute the request. - * - * For JSON responses, returns the parsed API response. - * - * For file downloads (any non-JSON Content-Type, e.g. a `*_unified_download_file` action), - * returns a description of the file: - * `{ content: Buffer, contentType: string, statusCode: number, headers: Record, - * fileName: string | null }`. Note `content` is a raw `Buffer`, not a `JsonValue`: it - * JSON-stringifies to a `{ type: 'Buffer', data: [...] }` byte array, so callers that - * re-serialize tool results (e.g. for an LLM) should strip or transform this key. - */ - async execute(params: JsonObject, options?: ExecuteOptions): Promise { - // Prepare request parameters - const [url, bodyParams, queryParams] = this.prepareRequestParams(params); - - // Prepare URL with query parameters using optimized batching - const urlWithQuery = new URL(url); - const serializedParams = this.buildQueryParameters(queryParams); - - // Batch append all parameters - for (const [paramKey, paramValue] of serializedParams) { - urlWithQuery.searchParams.append(paramKey, paramValue); - } - - // Build fetch options - const fetchOptions = this.buildFetchOptions(bodyParams); - - // If dryRun is true, return the request details instead of making the API call - if (options?.dryRun) { - // Convert headers to a plain object for JSON serialization - const headersObj = - fetchOptions.headers instanceof Headers - ? Object.fromEntries(fetchOptions.headers.entries()) - : Array.isArray(fetchOptions.headers) - ? Object.fromEntries(fetchOptions.headers) - : (fetchOptions.headers ?? {}); - - // Convert body to a JSON-serialisable value - const bodyValue = - fetchOptions.body instanceof FormData - ? '[FormData]' - : typeof fetchOptions.body === 'string' - ? fetchOptions.body - : null; - - return { - url: urlWithQuery.toString(), - method: this.method, - headers: headersObj, - body: bodyValue, - mappedParams: params, - } satisfies JsonObject; - } - - // Execute the request - const response = await fetch(urlWithQuery.toString(), fetchOptions); - - // Check if the response is OK - if (!response.ok) { - const responseBody = await response.json().catch(() => null); - throw new StackOneAPIError( - `API request failed with status ${response.status} for ${url}`, - response.status, - responseBody, - bodyParams, - ); - } - - // Branch on Content-Type: JSON bodies are parsed as before; any non-JSON body is a file - // download (raw binary served with the file's own MIME type and a Content-Disposition - // header) and must not be forced through response.json(), which throws on binary content. - const contentType = response.headers.get('content-type') ?? ''; - if (isJsonContentType(contentType)) { - return (await response.json()) as JsonObject; - } - - // Return the raw bytes plus metadata. `content` is a Buffer, which is not representable in - // type-fest's JsonValue (and JSON-stringifies to a byte array, not the file); the double-cast - // is the documented escape hatch for returning a non-JSON value from this JsonObject method. - return (await binaryDownloadFromResponse(response)) as unknown as JsonObject; - } -} diff --git a/src/rpc-client.test.ts b/src/rpc-client.test.ts index 77cc88f5..798516ea 100644 --- a/src/rpc-client.test.ts +++ b/src/rpc-client.test.ts @@ -1,169 +1,239 @@ +import { createServer, type Server as NetServer, type Socket } from 'node:net'; import { http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; import { server } from '../mocks/node'; -import { type RpcActionResponse, RpcClient } from './rpc-client'; -import { stackOneHeadersSchema } from './headers'; -import { type BinaryDownloadResult, isBinaryDownloadResult } from './utils/binary-response'; +import { USER_AGENT } from './consts'; +import { RpcClient } from './rpc-client'; +import { isBinaryDownloadResult } from './utils/binary-response'; import { StackOneAPIError } from './utils/error-stackone-api'; +import { StackOneError } from './utils/error-stackone'; -/** - * Narrow an rpcAction result to the JSON envelope, failing the test if the call returned a binary - * download instead. rpcAction returns `RpcActionResponse | BinaryDownloadResult`, so the JSON-path - * assertions below need the non-binary branch to stay type-safe. - */ -function expectJsonResponse(result: RpcActionResponse | BinaryDownloadResult): RpcActionResponse { - if (isBinaryDownloadResult(result)) { - throw new Error('expected a JSON RPC response, received a binary download'); - } - return result; -} - -test('should successfully execute an RPC action', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); +const newClient = (overrides: Partial[0]> = {}) => + new RpcClient({ baseUrl: TEST_BASE_URL, apiKey: 'test-api-key', timeout: 5_000, ...overrides }); - const response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'bamboohr_get_employee', - body: { fields: 'name,email' }, - path: { id: 'emp-123' }, +const request = (action: string, extra: Record = {}) => ({ + action, + body: {}, + headers: {}, + ...extra, +}); + +const captureRequests = () => { + const seen: Request[] = []; + server.use( + http.post(`${TEST_BASE_URL}/actions/rpc`, ({ request: incoming }) => { + seen.push(incoming.clone()); + return HttpResponse.json({ data: { ok: true } }); }), ); + return seen; +}; + +describe('RpcClient', () => { + it('posts the envelope to /actions/rpc with Basic auth, a versioned User-Agent and the account', async () => { + const seen = captureRequests(); - // Response matches server's ActionsRpcResponseApiModel structure - expect(response).toHaveProperty('data'); - expect(response.data).toMatchObject({ - id: 'emp-123', - name: 'Test Employee', + const result = await newClient().rpcAction( + request('crm_list_contacts', { query: { limit: 1 }, headers: { 'x-account-id': 'acc-1' } }), + 'acc-1', + ); + + expect(result).toEqual({ data: { ok: true } }); + const [sent] = seen; + assert(sent); + expect(sent.url).toBe(`${TEST_BASE_URL}/actions/rpc`); + expect(sent.headers.get('authorization')).toBe( + `Basic ${Buffer.from('test-api-key:').toString('base64')}`, + ); + expect(sent.headers.get('user-agent')).toBe(USER_AGENT); + expect(sent.headers.get('x-account-id')).toBe('acc-1'); + expect(await sent.json()).toEqual({ + action: 'crm_list_contacts', + body: {}, + headers: { 'x-account-id': 'acc-1' }, + query: { limit: 1 }, + }); }); -}); -test('should send correct payload structure', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, + // The account on the wire is the caller's argument, never a copy lifted out of the envelope: + // the envelope is model-supplied. + it('takes x-account-id from the tool, not from the envelope', async () => { + const seen = captureRequests(); + + await newClient().rpcAction( + request('crm_list_contacts', { headers: { 'x-account-id': 'victim' } }), + 'acc-1', + ); + + expect(seen[0]?.headers.get('x-account-id')).toBe('acc-1'); }); - const response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'custom_action', - body: { key: 'value' }, - headers: stackOneHeadersSchema.parse({ 'x-custom': 'header' }), - path: { id: '123' }, - query: { filter: 'active' }, - }), - ); + it('sends no x-account-id at all without an account, and the API refuses it', async () => { + const error = await newClient() + .rpcAction(request('dummy_action'), undefined) + .catch((caught: unknown) => caught); - // Response matches server's ActionsRpcResponseApiModel structure - expect(response.data).toMatchObject({ - action: 'custom_action', - received: { - body: { key: 'value' }, - headers: { 'x-custom': 'header' }, - path: { id: '123' }, - query: { filter: 'active' }, - }, + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(400); }); -}); -test('should handle list actions with array data', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, + it('refuses an account the API does not know', async () => { + const error = await newClient() + .rpcAction(request('dummy_action'), 'no-such-account') + .catch((caught: unknown) => caught); + + expect((error as StackOneAPIError).statusCode).toBe(404); }); - const response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'bamboohr_list_employees', - }), - ); + it('lets caller headers through beneath the SDK-owned ones', async () => { + const seen = captureRequests(); - // Response data can be an array (matches RpcActionResponseData union type) - expect(Array.isArray(response.data)).toBe(true); - expect(response.data).toMatchObject([ - { id: expect.any(String), name: expect.any(String) }, - { id: expect.any(String), name: expect.any(String) }, - ]); -}); + await newClient({ + headers: { 'X-Trace': 't-1', authorization: 'Bearer spoofed', 'X-Account-Id': 'other' }, + }).rpcAction(request('crm_list_contacts'), 'acc-1'); -test('should throw StackOneAPIError on server error', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, + const sent = seen[0]; + expect(sent?.headers.get('x-trace')).toBe('t-1'); + expect(sent?.headers.get('authorization')).toMatch(/^Basic /); + expect(sent?.headers.get('x-account-id')).toBe('acc-1'); }); - await expect( - client.actions.rpcAction({ - action: 'test_error_action', - }), - ).rejects.toThrow(StackOneAPIError); -}); + it('leads an API error with the server message and keeps status and body', async () => { + server.use( + http.post(`${TEST_BASE_URL}/actions/rpc`, () => + HttpResponse.json( + { message: 'path.id is missing', provider_errors: [{ status: 400 }] }, + { status: 400, statusText: 'Bad Request' }, + ), + ), + ); + + const error = (await newClient() + .rpcAction(request('crm_get_contact'), 'acc-1') + .catch((caught: unknown) => caught)) as StackOneAPIError; -test('should include request body in error for debugging', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.message).toBe('400 Bad Request: path.id is missing'); + expect(error.statusCode).toBe(400); + expect(error.responseBody).toEqual({ + message: 'path.id is missing', + provider_errors: [{ status: 400 }], + }); + expect(error.providerErrors).toEqual([{ status: 400 }]); }); - await expect( - client.actions.rpcAction({ - action: 'test_error_action', - body: { debug: 'data' }, - }), - ).rejects.toMatchObject({ - statusCode: 500, - requestBody: { action: 'test_error_action' }, + it('reports a non-JSON error body as text rather than throwing a SyntaxError', async () => { + server.use( + http.post( + `${TEST_BASE_URL}/actions/rpc`, + () => + new HttpResponse('502 Bad Gateway', { + status: 502, + statusText: 'Bad Gateway', + headers: { 'content-type': 'text/html' }, + }), + ), + ); + + const error = (await newClient() + .rpcAction(request('x'), 'acc-1') + .catch((caught: unknown) => caught)) as StackOneAPIError; + + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(502); + expect(error.responseBody).toBe('502 Bad Gateway'); + expect(error.message).toContain('502 Bad Gateway: '); }); -}); -test('should work with only action parameter', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, + it('blames the server, not the arguments, for malformed JSON', async () => { + server.use( + http.post( + `${TEST_BASE_URL}/actions/rpc`, + () => new HttpResponse('{not json', { headers: { 'content-type': 'application/json' } }), + ), + ); + + await expect(newClient().rpcAction(request('x'), 'acc-1')).rejects.toThrow( + /Server sent malformed JSON for "x"/, + ); }); - const response = await client.actions.rpcAction({ - action: 'simple_action', + it('wraps a non-object JSON response as { result }', async () => { + server.use(http.post(`${TEST_BASE_URL}/actions/rpc`, () => HttpResponse.json(['a', 'b']))); + + expect(await newClient().rpcAction(request('x'), 'acc-1')).toEqual({ result: ['a', 'b'] }); + }); + + it.each([204, 205])('returns { statusCode } for a bodyless %i', async (status) => { + server.use(http.post(`${TEST_BASE_URL}/actions/rpc`, () => new HttpResponse(null, { status }))); + + expect(await newClient().rpcAction(request('x'), 'acc-1')).toEqual({ statusCode: status }); + }); + + it('returns { statusCode } for an empty JSON body rather than a fake download', async () => { + server.use( + http.post( + `${TEST_BASE_URL}/actions/rpc`, + () => new HttpResponse('', { headers: { 'content-type': 'application/json' } }), + ), + ); + + expect(await newClient().rpcAction(request('x'), 'acc-1')).toEqual({ statusCode: 200 }); }); - // Response has data field (server returns { data: { action, received } }) - expect(response).toHaveProperty('data'); + it('reports arguments JSON cannot encode as an argument error', async () => { + await expect( + newClient().rpcAction(request('x', { body: { big: 1n as never } }), 'acc-1'), + ).rejects.toThrow(/could not be encoded as JSON/); + }); + + it('reports a network failure as a StackOneError', async () => { + server.use(http.post(`${TEST_BASE_URL}/actions/rpc`, () => HttpResponse.error())); + + const error = await newClient() + .rpcAction(request('x'), 'acc-1') + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneError); + expect((error as Error).message).toMatch(/^Request failed/); + }); }); -test('should send x-account-id as HTTP header', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, +describe('RpcClient timeout', () => { + let silent: NetServer; + const sockets: Socket[] = []; + let port = 0; + + beforeAll(async () => { + // Accepts the connection and never answers — the case a per-request default would hang on. + 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; + }); + afterAll(async () => { + for (const socket of sockets) { + socket.destroy(); + } + await new Promise((resolve) => silent.close(resolve)); }); - const response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'test_account_id_header', - headers: stackOneHeadersSchema.parse({ 'x-account-id': 'test-account-123' }), - }), - ); + it('gives up after the configured timeout', async () => { + const started = Date.now(); + const error = await newClient({ baseUrl: `http://127.0.0.1:${port}`, timeout: 300 }) + .rpcAction(request('x'), 'acc-1') + .catch((caught: unknown) => caught); - // Verify x-account-id is sent both as HTTP header and in request body - expect(response.data).toMatchObject({ - httpHeader: 'test-account-123', - bodyHeader: 'test-account-123', + expect(error).toBeInstanceOf(StackOneError); + expect((error as Error).message).toMatch(/timed out after 300ms/); + expect(Date.now() - started).toBeLessThan(5_000); }); }); /** - * Binary file downloads over RPC - * * File-download actions (e.g. googledrive_unified_download_file) are served over /actions/rpc - * as raw binary with the file's own MIME type and a Content-Disposition header - never the - * JSON {data,next} envelope. rpcAction must branch on Content-Type and return the bytes plus - * metadata instead of forcing a JSON parse (which throws on binary) or the envelope schema. + * as raw binary with the file's own MIME type and a Content-Disposition header - never JSON. */ describe('binary file downloads', () => { - const newClient = () => - new RpcClient({ serverURL: TEST_BASE_URL, security: { username: 'test-api-key' } }); - it('returns raw bytes + metadata for a non-JSON (binary) RPC response', async () => { // Leading bytes of a real PDF; the 0xc4 byte is invalid UTF-8 and is exactly what makes // an unconditional response.json() throw on a binary body. @@ -178,23 +248,22 @@ describe('binary file downloads', () => { status: 200, headers: { 'content-type': 'application/pdf', - 'content-disposition': 'attachment; filename="download.pdf"', + 'content-disposition': 'attachment; filename="../../download.pdf"', }, }), ), ); - const result = await newClient().actions.rpcAction({ - action: 'googledrive_unified_download_file', - path: { id: 'file-123' }, - query: { export_format: 'application/pdf' }, - }); + const result = await newClient().rpcAction( + request('googledrive_unified_download_file', { path: { id: 'file-123' } }), + 'acc-1', + ); - expect(isBinaryDownloadResult(result)).toBe(true); - if (!isBinaryDownloadResult(result)) throw new Error('expected a binary download result'); + assert(isBinaryDownloadResult(result), 'expected a binary download result'); expect(result.content.equals(Buffer.from(pdfBytes))).toBe(true); expect(result.contentType).toBe('application/pdf'); expect(result.statusCode).toBe(200); + // Reduced to a basename: the traversal never reaches the caller. expect(result.fileName).toBe('download.pdf'); expect(result.headers['content-type']).toBe('application/pdf'); }); @@ -204,31 +273,25 @@ describe('binary file downloads', () => { server.use( http.post( `${TEST_BASE_URL}/actions/rpc`, - () => - new HttpResponse(blob, { - status: 200, - headers: { 'content-type': 'application/octet-stream' }, - }), + () => new HttpResponse(blob, { headers: { 'content-type': 'application/octet-stream' } }), ), ); - const result = await newClient().actions.rpcAction({ action: 'some_unified_download_file' }); + const result = await newClient().rpcAction(request('some_unified_download_file'), 'acc-1'); - expect(isBinaryDownloadResult(result)).toBe(true); - if (!isBinaryDownloadResult(result)) throw new Error('expected a binary download result'); + assert(isBinaryDownloadResult(result), 'expected a binary download result'); expect(result.content.equals(Buffer.from(blob))).toBe(true); - expect(result.contentType).toBe('application/octet-stream'); expect(result.fileName).toBeNull(); }); - it('still parses a normal JSON envelope (regression)', async () => { - const result = await newClient().actions.rpcAction({ - action: 'bamboohr_get_employee', - path: { id: 'emp-123' }, - }); + it('treats a missing Content-Type as opaque bytes, not JSON', async () => { + const jpeg = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]); + server.use(http.post(`${TEST_BASE_URL}/actions/rpc`, () => new HttpResponse(jpeg))); - expect(isBinaryDownloadResult(result)).toBe(false); - expect(result).toHaveProperty('data'); + const result = await newClient().rpcAction(request('x'), 'acc-1'); + + assert(isBinaryDownloadResult(result), 'expected a binary download result'); + expect(result.contentType).toBe('application/octet-stream'); }); it('parses JSON when the Content-Type carries a charset parameter', async () => { @@ -237,34 +300,11 @@ describe('binary file downloads', () => { `${TEST_BASE_URL}/actions/rpc`, () => new HttpResponse('{"data":{"ok":true}}', { - status: 200, headers: { 'content-type': 'application/json; charset=utf-8' }, }), ), ); - const result = await newClient().actions.rpcAction({ action: 'custom_action' }); - - expect(isBinaryDownloadResult(result)).toBe(false); - expect(result).toMatchObject({ data: { ok: true } }); - }); - - it('throws StackOneAPIError (not SyntaxError) for a non-JSON error response', async () => { - // A gateway/proxy error often returns a non-JSON body (e.g. HTML). The content-type branch - // must not let response.json() throw a raw SyntaxError - surface a StackOneAPIError instead. - server.use( - http.post( - `${TEST_BASE_URL}/actions/rpc`, - () => - new HttpResponse('502 Bad Gateway', { - status: 502, - headers: { 'content-type': 'text/html' }, - }), - ), - ); - - await expect( - newClient().actions.rpcAction({ action: 'googledrive_unified_download_file' }), - ).rejects.toThrow(StackOneAPIError); + expect(await newClient().rpcAction(request('x'), 'acc-1')).toEqual({ data: { ok: true } }); }); }); diff --git a/src/rpc-client.ts b/src/rpc-client.ts index f616d558..9e8400b1 100644 --- a/src/rpc-client.ts +++ b/src/rpc-client.ts @@ -1,158 +1,174 @@ -import { DEFAULT_BASE_URL, USER_AGENT } from './consts'; -import { STACKONE_HEADER_KEYS } from './headers'; -import { - type RpcActionRequest, - type RpcActionResponse, - type RpcClientConfig, - rpcActionRequestSchema, - rpcActionResponseSchema, - rpcClientConfigSchema, -} from './schema'; +import { buildRequestHeaders } from './headers'; +import type { JsonObject } from './types'; import { type BinaryDownloadResult, binaryDownloadFromResponse, isJsonContentType, } from './utils/binary-response'; -import { StackOneAPIError } from './utils/error-stackone-api'; - -// Re-export types for consumers and to make types portable -export type { RpcActionResponse } from './schema'; +import { StackOneAPIError, describeApiFailure } from './utils/error-stackone-api'; +import { StackOneError } from './utils/error-stackone'; /** - * Custom RPC client for StackOne API. - * Replaces the @stackone/stackone-client-ts dependency. + * The `/actions/rpc` request body. * - * @see https://docs.stackone.com/platform/api-reference/actions/list-all-actions-metadata * @see https://docs.stackone.com/platform/api-reference/actions/make-an-rpc-call-to-an-action */ +export interface RpcActionRequest { + action: string; + body: JsonObject; + headers: Record; + path?: JsonObject; + query?: JsonObject; +} + +/** + * A bodyless success (`204`/`205`, or an empty JSON body). Not a file download: returning an + * empty `content` with a made-up content type would break any caller that re-serialises results. + */ +interface EmptyRpcResult { + statusCode: number; +} + +interface RpcClientConfig { + baseUrl: string; + apiKey: string; + /** Request timeout in milliseconds. */ + timeout: number; + /** Extra HTTP headers sent with every request, beneath the SDK's own. */ + headers?: Record; +} + +const readErrorBody = async (response: Response): Promise => { + const text = await response.text().catch(() => ''); + if (!text) { + return null; + } + try { + return JSON.parse(text) as unknown; + } catch { + return text; + } +}; + +/** + * Client for the StackOne actions RPC endpoint. + * + * The account a request runs against is the `x-account-id` HTTP header, set here from the tool's + * own account — never read out of the envelope, whose contents are model-supplied. + */ export class RpcClient { - private readonly baseUrl: string; - private readonly authHeader: string; - private readonly timeout: number; + readonly url: string; + readonly #apiKey: string; + readonly #timeout: number; + readonly #headers: Record; constructor(config: RpcClientConfig) { - const validatedConfig = rpcClientConfigSchema.parse(config); - this.baseUrl = validatedConfig.serverURL || DEFAULT_BASE_URL; - const username = validatedConfig.security.username; - const password = validatedConfig.security.password || ''; - this.authHeader = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`; - this.timeout = validatedConfig.timeout ?? 60_000; + this.url = `${config.baseUrl.replace(/\/+$/, '')}/actions/rpc`; + this.#apiKey = config.apiKey; + this.#timeout = config.timeout; + this.#headers = { ...config.headers }; } /** - * Actions namespace containing RPC methods + * The HTTP headers a request for `accountId` carries. */ - readonly actions: { - rpcAction: (request: RpcActionRequest) => Promise; - } = { - /** - * Execute an RPC action - * @param request The RPC action request - * @returns The RPC action response matching server's ActionsRpcResponseApiModel, or - for a - * file-download action served as raw binary - a {@link BinaryDownloadResult} of bytes + - * metadata. `content` is a raw `Buffer` (not a `JsonValue`); handle it before re-serializing. - */ - rpcAction: async ( - request: RpcActionRequest, - ): Promise => { - const validatedRequest = rpcActionRequestSchema.parse(request); - const url = `${this.baseUrl}/actions/rpc`; - - const requestBody = { - action: validatedRequest.action, - body: validatedRequest.body, - headers: validatedRequest.headers, - path: validatedRequest.path, - query: validatedRequest.query, - } satisfies RpcActionRequest; - - // Forward StackOne-specific headers as HTTP headers - const requestHeaders = validatedRequest.headers; - const forwardedHeaders: Record = {}; - if (requestHeaders) { - for (const key of STACKONE_HEADER_KEYS) { - const value = requestHeaders[key]; - if (value !== undefined) { - forwardedHeaders[key] = value; - } - } - } - const httpHeaders = { - 'Content-Type': 'application/json', - Authorization: this.authHeader, - 'User-Agent': USER_AGENT, - ...forwardedHeaders, - } satisfies Record; + requestHeaders(accountId: string | undefined): Record { + return { + 'Content-Type': 'application/json', + ...buildRequestHeaders({ apiKey: this.#apiKey, accountId, extraHeaders: this.#headers }), + }; + } - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.timeout); + /** + * Execute an RPC action. + * + * @returns The parsed JSON response (a non-object body is wrapped as `{ result }`); for a + * file-download action served as raw binary, a {@link BinaryDownloadResult}; for a bodyless + * success, `{ statusCode }`. + * @throws StackOneAPIError When the API answers with an error status, or with a JSON content + * type whose body is not JSON. + * @throws StackOneError When the request cannot be sent or times out. + */ + async rpcAction( + request: RpcActionRequest, + accountId: string | undefined, + ): Promise { + let body: string; + try { + body = JSON.stringify(request); + } catch (error) { + // A BigInt or a cycle: an argument problem, reported as one rather than escaping as a + // bare TypeError from inside fetch. + throw new StackOneError( + `Arguments for "${request.action}" could not be encoded as JSON: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } - let response: Response; - let responseBody: unknown; - try { - response = await fetch(url, { - method: 'POST', - headers: httpHeaders, - body: JSON.stringify(requestBody), - signal: controller.signal, + let response: Response; + try { + response = await fetch(this.url, { + method: 'POST', + headers: this.requestHeaders(accountId), + body, + signal: AbortSignal.timeout(this.#timeout), + }); + } catch (error) { + if ( + error instanceof Error && + (error.name === 'TimeoutError' || error.name === 'AbortError') + ) { + throw new StackOneError(`Request to ${this.url} timed out after ${this.#timeout}ms`, { + cause: error, }); - - // A non-JSON body is never the {data,next} envelope. A successful one is a file download - // (raw binary with the file's own MIME type + Content-Disposition) - e.g. a - // *_unified_download_file action - returned as bytes + metadata. A non-JSON error body - // (e.g. an HTML gateway error) is surfaced as a StackOneAPIError rather than letting - // response.json() throw a raw SyntaxError. JSON bodies fall through to the parse + - // envelope-validation path below. - const contentType = response.headers.get('content-type') ?? ''; - if (!isJsonContentType(contentType)) { - if (response.ok) { - return await binaryDownloadFromResponse(response); - } - const errorText = await response.text().catch(() => null); - throw new StackOneAPIError( - `RPC action failed for ${url}`, - response.status, - errorText || null, - requestBody, - ); - } - - responseBody = await response.json(); - } catch (error) { - if (error instanceof Error && error.name === 'AbortError') { - throw new StackOneAPIError( - `Request timed out after ${this.timeout}ms for ${url}`, - 0, - null, - requestBody, - ); - } - throw error; - } finally { - clearTimeout(timeoutId); } + throw new StackOneError( + `Request failed: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } - if (!response.ok) { - throw new StackOneAPIError( - `RPC action failed for ${url}`, - response.status, - responseBody, - requestBody, - ); - } + if (!response.ok) { + const errorBody = await readErrorBody(response); + throw new StackOneAPIError( + describeApiFailure(response.status, response.statusText, errorBody, this.url), + response.status, + errorBody, + request, + ); + } - const validation = rpcActionResponseSchema.safeParse(responseBody); + const contentType = response.headers.get('content-type') ?? ''; + if (response.status === 204 || response.status === 205) { + return { statusCode: response.status }; + } + if (!isJsonContentType(contentType)) { + // A non-JSON success is a file download (e.g. a *_download_file action): raw bytes + // with the file's own MIME type and a Content-Disposition. A zero-byte body with a + // download content type is an empty file, with a filename the caller still needs. + return binaryDownloadFromResponse(response); + } - if (!validation.success) { - throw new StackOneAPIError( - `Invalid RPC action response for ${url}`, - response.status, - responseBody, - requestBody, - ); - } - - return validation.data; - }, - }; + const text = await response.text(); + if (!text) { + return { statusCode: response.status }; + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch (error) { + // Not the caller's arguments — the server sent a JSON content type with a body that + // is not JSON. Blaming the arguments here sends people to debug the wrong end. + throw new StackOneAPIError( + `Server sent malformed JSON for "${request.action}": ${error instanceof Error ? error.message : String(error)}`, + response.status, + text.slice(0, 500), + request, + { cause: error }, + ); + } + return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) + ? (parsed as JsonObject) + : { result: parsed as JsonObject[string] }; + } } diff --git a/src/schema.test.ts b/src/schema.test.ts new file mode 100644 index 00000000..b63475fa --- /dev/null +++ b/src/schema.test.ts @@ -0,0 +1,130 @@ +import { foldRootComposition, toolParametersFromInputSchema } from './schema'; +import type { JSONSchema } from './types'; + +describe('toolParametersFromInputSchema', () => { + it('keeps every root keyword verbatim', () => { + const served = { + $schema: 'https://json-schema.org/draft/2020-12/schema', + title: 'Probe', + type: 'object', + additionalProperties: false, + $defs: { Money: { type: 'object', properties: { amount: { type: 'number' } } } }, + oneOf: [{ required: ['a'] }, { required: ['b'] }], + 'x-vendor': { anything: true }, + properties: { a: { type: 'string' }, b: { $ref: '#/$defs/Money' } }, + required: ['a'], + }; + + expect(toolParametersFromInputSchema(served)).toEqual(served); + }); + + it('copies rather than aliases the served schema', () => { + const served = { type: 'object', properties: { a: { type: 'object', properties: {} } } }; + const parameters = toolParametersFromInputSchema(served); + + const nested = parameters.properties.a?.properties; + assert(nested); + (nested as Record).injected = { type: 'string' }; + + expect(served.properties.a.properties).toEqual({}); + }); + + it('defaults a missing type and properties', () => { + expect(toolParametersFromInputSchema({})).toEqual({ type: 'object', properties: {} }); + expect(toolParametersFromInputSchema(undefined)).toEqual({ type: 'object', properties: {} }); + }); + + it.each([['a string'], [null], [[]], [[1, 2]]])( + 'drops a malformed required of %j', + (required) => { + expect( + toolParametersFromInputSchema({ type: 'object', properties: { a: {} }, required }), + ).not.toHaveProperty('required'); + }, + ); + + // The SDK needs no per-property marker: requiredness stays where the server put it, so a + // property literally named `nullable`, and a served `nullable` keyword, are both untouched. + it('never touches a property or keyword named nullable', () => { + const served = { + type: 'object', + properties: { + nullable: { type: 'object', properties: { name: { type: 'string' } }, nullable: false }, + other: { type: 'string', nullable: true }, + }, + required: ['nullable'], + }; + + expect(toolParametersFromInputSchema(served)).toEqual(served); + }); +}); + +describe('foldRootComposition', () => { + it('leaves a schema without root combinators untouched', () => { + const schema: JSONSchema = { type: 'object', properties: { a: { type: 'string' } } }; + expect(foldRootComposition(schema)).toBe(schema); + }); + + it('drops a root oneOf, keeping every branch property optional', () => { + const folded = foldRootComposition({ + type: 'object', + properties: { id: { type: 'string' } }, + oneOf: [ + { required: ['id'] }, + { properties: { email: { type: 'string', format: 'email' } }, required: ['email'] }, + ], + required: ['kind'], + }); + + expect(folded).toEqual({ + type: 'object', + properties: { id: { type: 'string' }, email: { type: 'string', format: 'email' } }, + required: ['kind'], + }); + }); + + it('merges an allOf into the root, required included, root definitions winning', () => { + expect( + foldRootComposition({ + type: 'object', + properties: { a: { type: 'string', description: 'root' } }, + allOf: [ + { properties: { a: { type: 'number' }, b: { type: 'number' } }, required: ['b'] }, + { required: ['a'] }, + ], + }), + ).toEqual({ + type: 'object', + properties: { a: { type: 'string', description: 'root' }, b: { type: 'number' } }, + required: ['b', 'a'], + }); + }); + + it('drops root anyOf, enum and not, and keeps everything else', () => { + expect( + foldRootComposition({ + $schema: 'https://json-schema.org/draft/2020-12/schema', + title: 'T', + $defs: { X: { type: 'string' } }, + additionalProperties: false, + properties: { x: { $ref: '#/$defs/X' } }, + anyOf: [{ required: ['x'] }], + enum: [{}], + not: { required: ['y'] }, + }), + ).toEqual({ + $schema: 'https://json-schema.org/draft/2020-12/schema', + title: 'T', + $defs: { X: { type: 'string' } }, + additionalProperties: false, + type: 'object', + properties: { x: { $ref: '#/$defs/X' } }, + }); + }); + + it('does not mutate its input', () => { + const schema: JSONSchema = { type: 'object', properties: {}, oneOf: [{ required: ['a'] }] }; + foldRootComposition(schema); + expect(schema.oneOf).toEqual([{ required: ['a'] }]); + }); +}); diff --git a/src/schema.ts b/src/schema.ts index 4e9ccac2..3fae0543 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -1,65 +1,112 @@ -import { z } from 'zod/v4-mini'; -import { stackOneHeadersSchema } from './headers'; - /** - * Zod schema for RPC action request validation - * @see https://docs.stackone.com/platform/api-reference/actions/make-an-rpc-call-to-an-action + * The served tool schema, and the few provider-specific adjustments made on the way to a model. + * + * The guiding property: the schema a model is shown is the schema the MCP server served. Nothing + * is invented and nothing is dropped, except where a provider's API would reject the request + * outright — and those adjustments are made on a copy, per adapter, never on the tool itself. */ -export const rpcActionRequestSchema = z.object({ - action: z.string(), - body: z.optional(z.record(z.string(), z.unknown())), - headers: z.optional(stackOneHeadersSchema), - path: z.optional(z.record(z.string(), z.unknown())), - query: z.optional(z.record(z.string(), z.unknown())), -}); +import type { JSONSchema, JsonSchemaProperties, ToolParameters } from './types'; + +const isPlainObject = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); /** - * RPC action request payload + * A deep copy of a JSON value. Schemas are shared between the catalog cache and every tool built + * from it, so anything handed to a caller must be a copy a caller cannot mutate back into the + * cache. */ -export type RpcActionRequest = z.infer; +export function cloneJson(value: T): T { + return structuredClone(value); +} /** - * Zod schema for RPC action response data + * The served `required` list, if it is one: an array of strings. A string or null `required` is + * malformed; treating it as a list would iterate characters or throw over one bad tool, so it is + * read as "nothing required". */ -const rpcActionResponseDataSchema = z.union([ - z.record(z.string(), z.unknown()), - z.array(z.record(z.string(), z.unknown())), - z.null(), -]); +function servedRequired(schema: Record): string[] | undefined { + const required = schema.required; + if (!Array.isArray(required)) { + return undefined; + } + const names = required.filter((name): name is string => typeof name === 'string'); + return names.length > 0 ? names : undefined; +} /** - * Zod schema for RPC action response validation - * - * The server returns a flexible JSON structure. Known fields: - * - `data`: The main response data (object, array, or null) - * - `next`: Pagination cursor for fetching next page + * Build a tool's parameters from the `inputSchema` the MCP server served. * - * Additional fields from the connector response are passed through. + * The root is kept verbatim — `$schema`, `$defs`, `title`, `additionalProperties`, `oneOf` and + * any keyword this SDK has never heard of — on a deep copy. `type` defaults to `object` when the + * server omits it, and `required` is the served list (dropped when empty or malformed). */ -export const rpcActionResponseSchema = z.looseObject({ - next: z.nullable(z.optional(z.string())), - data: z.optional(rpcActionResponseDataSchema), -}); +export function toolParametersFromInputSchema(inputSchema: unknown): ToolParameters { + const served = isPlainObject(inputSchema) ? cloneJson(inputSchema) : {}; + const { type, properties, required: _required, ...rest } = served; + const parameters: ToolParameters = { + ...rest, + type: typeof type === 'string' ? type : 'object', + properties: (isPlainObject(properties) ? properties : {}) as JsonSchemaProperties, + }; + const required = servedRequired(served); + if (required) { + parameters.required = required; + } + return parameters; +} /** - * RPC action response from the StackOne API - * Contains known fields (data, next) plus any additional fields from the connector + * Keywords the OpenAI and Anthropic tool APIs refuse at the root of a parameters schema. OpenAI + * rejects all five ("schema must be a JSON Schema of type object and not have + * oneOf/anyOf/allOf/enum/not at the top level"); Anthropic rejects the three combinators. */ -export type RpcActionResponse = z.infer; +const ROOT_KEYWORDS_PROVIDERS_REJECT = ['oneOf', 'anyOf', 'allOf', 'enum', 'not'] as const; /** - * Zod schema for RPC client configuration validation + * Make a lossless schema acceptable to a provider that requires a plain object at the root. + * + * Top-level combinators are folded into the root rather than silently lost where that is + * sound: every property any `allOf`/`oneOf`/`anyOf` branch declares becomes a root property + * (the root's own definition wins), and an `allOf` branch's `required` is merged in, since all + * of them must hold. A `oneOf`/`anyOf` branch's `required` is not — which alternative applies is + * exactly what the flat root cannot say — so those fields stay optional and the server's own + * validation decides. `enum` and `not` at the root cannot describe an object and are dropped. */ -export const rpcClientConfigSchema = z.object({ - serverURL: z.optional(z.string()), - security: z.object({ - username: z.string(), - password: z.optional(z.string()), - }), - timeout: z.optional(z.number()), -}); +export function foldRootComposition(schema: JSONSchema): JSONSchema { + if (!ROOT_KEYWORDS_PROVIDERS_REJECT.some((keyword) => keyword in schema)) { + return schema; + } + const folded: JSONSchema = { ...schema }; + const properties: JsonSchemaProperties = { ...folded.properties }; + const required = new Set(folded.required ?? []); -/** - * Configuration for the RPC client - */ -export type RpcClientConfig = z.infer; + 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)) { + properties[name] = definition; + } + } + if (keyword === 'allOf') { + for (const name of branch.required ?? []) { + required.add(name); + } + } + } + } + for (const keyword of ROOT_KEYWORDS_PROVIDERS_REJECT) { + delete folded[keyword]; + } + + folded.type = 'object'; + folded.properties = properties; + if (required.size > 0) { + folded.required = [...required]; + } else { + delete folded.required; + } + return folded; +} diff --git a/src/tool-optional-ai.test.ts b/src/tool-optional-ai.test.ts index 986d2499..59652658 100644 --- a/src/tool-optional-ai.test.ts +++ b/src/tool-optional-ai.test.ts @@ -2,25 +2,13 @@ import { existsSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { StackOneError } from './utils/error-stackone'; import { peerDependencies } from '../package.json'; -import { ParameterLocation, type ExecuteConfig, type ToolParameters } from './types'; +import type { ExecuteConfig, ToolParameters } from './types'; const builtToolEsm = new URL('../dist/src/tool.mjs', import.meta.url); const builtToolCjs = new URL('../dist/src/tool.cjs', import.meta.url); const distReady = existsSync(builtToolEsm) && existsSync(builtToolCjs); -const createExecuteConfig = (): ExecuteConfig => ({ - kind: 'http', - method: 'GET', - url: 'https://api.example.com/test/{id}', - bodyType: 'json', - params: [ - { - name: 'id', - location: ParameterLocation.PATH, - type: 'string', - }, - ], -}); +const createExecuteConfig = (): ExecuteConfig => ({ kind: 'local' }); const createParameters = (): ToolParameters => ({ type: 'object', diff --git a/src/tool.test-d.ts b/src/tool.test-d.ts index 730284be..ad58b8c6 100644 --- a/src/tool.test-d.ts +++ b/src/tool.test-d.ts @@ -12,13 +12,7 @@ const tool = new BaseTool( type: 'object', properties: { id: { type: 'string' } }, }, - { - kind: 'http', - method: 'GET', - url: 'https://example.com/test', - bodyType: 'json', - params: [], - }, + { kind: 'local' }, ); const tools = new Tools([tool]); diff --git a/src/tool.test.ts b/src/tool.test.ts index a979cd37..99724dc6 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -1,38 +1,15 @@ import { jsonSchema } from 'ai'; -import { BaseTool, StackOneTool, Tools } from './tool'; -import { - type AISDKToolResult, - type ExecuteConfig, - type JSONSchema, - ParameterLocation, - type ToolParameters, -} from './types'; +import { http, HttpResponse } from 'msw'; +import { TEST_BASE_URL } from '../mocks/constants'; +import { type RecordedToolCall, createMcpApp } from '../mocks/mcp-server'; +import { server } from '../mocks/node'; +import { RpcClient } from './rpc-client'; +import { toolParametersFromInputSchema } from './schema'; +import { BaseTool, StackOneMcpTool, StackOneRpcTool, StackOneTool, Tools } from './tool'; +import type { AISDKToolResult, JSONSchema, ToolParameters } from './types'; +import { isBinaryDownloadResult } from './utils/binary-response'; import { StackOneAPIError } from './utils/error-stackone-api'; - -// Create a mock tool for testing -const createMockTool = (headers?: Record): BaseTool => { - const name = 'test_tool'; - const description = 'Test tool'; - const parameters: ToolParameters = { - type: 'object', - properties: { id: { type: 'string', description: 'ID parameter' } }, - }; - const executeConfig: ExecuteConfig = { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/test/{id}', - bodyType: 'json', - params: [ - { - name: 'id', - location: ParameterLocation.PATH, - type: 'string', - }, - ], - }; - - return new BaseTool(name, description, parameters, executeConfig, headers); -}; +import { StackOneError } from './utils/error-stackone'; // Calls an AI SDK tool's `execute` through a plain signature rather than the // `ai` type. v5/v6 expect `ToolCallOptions`, v7 requires an extra `context` @@ -43,7 +20,7 @@ const executeAISDKTool = ( name: string, args: Record, ): Promise => { - const execute = tools[name].execute as unknown as ( + const execute = tools[name]?.execute as unknown as ( args: Record, options?: unknown, ) => Promise; @@ -51,991 +28,621 @@ const executeAISDKTool = ( return execute(args, { toolCallId: 'test-tool-call-id', messages: [] }); }; -describe('StackOneTool', () => { - it('should execute with parameters', async () => { - const tool = createMockTool(); - const result = await tool.execute({ id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); +/** The conformance suite's `rich-schema` fixture: every root keyword a server may send. */ +const richSchema = { + $schema: 'https://json-schema.org/draft/2020-12/schema', + title: 'Rich Schema Test', + type: 'object', + additionalProperties: false, + $defs: { + Money: { + type: 'object', + properties: { amount: { type: 'number' }, currency: { type: 'string' } }, + required: ['amount', 'currency'], + }, + }, + oneOf: [{ required: ['employee_id'] }, { required: ['identifier'] }], + properties: { + employee_id: { type: 'string', description: 'Employee id', pattern: '^emp_' }, + start_date: { type: 'string', format: 'date-time', description: 'Start date' }, + limit: { type: 'integer', minimum: 1, maximum: 100, default: 25 }, + status: { type: 'string', enum: ['active', 'terminated'] }, + address: { + type: 'object', + properties: { + line1: { type: 'string' }, + postcode: { type: 'string', pattern: '[A-Z]{2}[0-9]' }, + }, + required: ['line1'], + }, + identifier: { + description: 'Either an id or an email', + oneOf: [{ type: 'string' }, { type: 'integer' }], + }, + salary: { $ref: '#/$defs/Money' }, + nullable: { type: 'object', properties: { name: { type: 'string' } }, nullable: false }, + }, + required: ['start_date'], +} as const; + +const localTool = (name: string, schema: unknown, description = 'Test tool') => + new BaseTool(name, description, toolParametersFromInputSchema(schema), { kind: 'local' }); + +const simpleTool = () => + localTool('test_tool', { + type: 'object', + properties: { id: { type: 'string', description: 'ID' } }, }); - it('should execute with string arguments', async () => { - const tool = createMockTool(); - const result = await tool.execute('{"id":"123"}'); - - expect(result).toEqual({ id: '123', name: 'Test' }); +describe('BaseTool', () => { + it('cannot execute on its own', async () => { + await expect(simpleTool().execute({ id: '1' })).rejects.toThrow( + 'Tool "test_tool" has no executor', + ); }); - it('should handle API errors', async () => { - const tool = createMockTool(); - - await expect(tool.execute({ id: 'invalid' })).rejects.toSatisfy((error) => { - expect(error).toBeInstanceOf(StackOneAPIError); - const apiError = error as StackOneAPIError; - expect(apiError.statusCode).toBe(400); - expect(apiError.responseBody).toEqual({ error: 'Invalid ID' }); - return true; + describe('toJsonSchema', () => { + it('is the served schema, verbatim', () => { + expect(localTool('rich', richSchema).toJsonSchema()).toEqual(richSchema); }); - }); - - it('should convert to OpenAI Chat Completions API tool format', () => { - const tool = createMockTool(); - const openAIFormat = tool.toOpenAI(); - - expect(openAIFormat.type).toBe('function'); - expect(openAIFormat.function.name).toBe('test_tool'); - expect(openAIFormat.function.description).toBe('Test tool'); - expect(openAIFormat.function.parameters?.type).toBe('object'); - expect( - ( - openAIFormat.function.parameters as { - properties: { id: { type: string } }; - } - ).properties.id.type, - ).toBe('string'); - }); - - it('should convert to Anthropic tool format', () => { - const tool = createMockTool(); - const anthropicFormat = tool.toAnthropic(); - - expect(anthropicFormat.name).toBe('test_tool'); - expect(anthropicFormat.description).toBe('Test tool'); - expect(anthropicFormat.input_schema.type).toBe('object'); - const properties = anthropicFormat.input_schema.properties as Record; - expect(properties.id).toBeDefined(); - expect(properties.id.type).toBe('string'); - }); - - it('should convert to OpenAI Responses API tool format', () => { - const tool = createMockTool(); - const responsesFormat = tool.toOpenAIResponses(); - - expect(responsesFormat.type).toBe('function'); - expect(responsesFormat.name).toBe('test_tool'); - expect(responsesFormat.description).toBe('Test tool'); - expect(responsesFormat.strict).toBe(true); - expect(responsesFormat.parameters?.type).toBe('object'); - expect( - ( - responsesFormat.parameters as { - properties: { id: { type: string } }; - additionalProperties: boolean; - } - ).properties.id.type, - ).toBe('string'); - expect( - (responsesFormat.parameters as { additionalProperties: boolean }).additionalProperties, - ).toBe(false); - }); - - it('should convert to OpenAI Responses API tool format with strict disabled', () => { - const tool = createMockTool(); - const responsesFormat = tool.toOpenAIResponses({ strict: false }); - - expect(responsesFormat.type).toBe('function'); - expect(responsesFormat.name).toBe('test_tool'); - expect(responsesFormat.strict).toBe(false); - expect(responsesFormat.parameters).toBeDefined(); - expect( - (responsesFormat.parameters as { additionalProperties?: boolean }).additionalProperties, - ).toBeUndefined(); - }); - - it('should convert to AI SDK tool format', async () => { - const tool = createMockTool(); - - const aiSdkTool = await tool.toAISDK(); - - // Test the basic structure - expect(aiSdkTool).toBeDefined(); - expect(aiSdkTool.test_tool).toBeDefined(); - expect(typeof aiSdkTool.test_tool.execute).toBe('function'); - expect(aiSdkTool.test_tool.description).toBe('Test tool'); - expect(aiSdkTool.test_tool.inputSchema).toBeDefined(); - - // TODO: Remove ts-ignore once AISDKToolDefinition properly types inputSchema.jsonSchema - // @ts-ignore - jsonSchema is available on Schema wrapper from ai sdk - const schema = aiSdkTool.test_tool.inputSchema.jsonSchema; - expect(schema).toBeDefined(); - expect(schema.type).toBe('object'); - expect(schema.properties?.id).toBeDefined(); - expect(schema.properties?.id.type).toBe('string'); - }); - - it('should convert to Claude Agent SDK tool format', async () => { - const tool = createMockTool(); - - const claudeTool = await tool.toClaudeAgentSdkTool(); - - expect(claudeTool).toBeDefined(); - expect(claudeTool.name).toBe('test_tool'); - expect(claudeTool.description).toBe('Test tool'); - expect(claudeTool.inputSchema).toBeDefined(); - expect(typeof claudeTool.handler).toBe('function'); - - // Test the handler returns content in the expected format - const result = await claudeTool.handler({ id: 'test-123' }); - expect(result).toHaveProperty('content'); - expect(Array.isArray(result.content)).toBe(true); - expect(result.content[0]).toHaveProperty('type', 'text'); - expect(result.content[0]).toHaveProperty('text'); - }); - it('should include execution metadata by default in AI SDK conversion', async () => { - const tool = createMockTool(); + it('returns a copy a caller cannot mutate back into the tool', () => { + 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 = {}; - const aiSdkTool = await tool.toAISDK(); - const execution = aiSdkTool.test_tool.execution; - - expect(execution).toBeDefined(); - expect(execution?.config.kind).toBe('http'); - if (execution?.config.kind === 'http') { - expect(execution.config.method).toBe('GET'); - expect(execution.config.url).toBe('https://api.example.com/test/{id}'); - } - expect(execution?.headers).toEqual({}); - }); - - it('should allow disabling execution metadata exposure for AI SDK conversion', async () => { - const tool = createMockTool().setExposeExecutionMetadata(false); - - const aiSdkTool = await tool.toAISDK(); + expect(tool.toJsonSchema()).toEqual(richSchema); + }); - expect(aiSdkTool.test_tool.execution).toBeUndefined(); + it('omits an empty required list', () => { + expect( + localTool('t', { type: 'object', properties: {}, required: [] }).toJsonSchema(), + ).toEqual({ + type: 'object', + properties: {}, + }); + }); }); - it('should convert complex parameter types to zod schema', async () => { - const complexTool = new BaseTool( - 'complex_tool', - 'Complex tool', - { - type: 'object', - properties: { - stringParam: { type: 'string', description: 'A string parameter' }, - numberParam: { type: 'number', description: 'A number parameter' }, - booleanParam: { type: 'boolean', description: 'A boolean parameter' }, - arrayParam: { - type: 'array', - description: 'An array parameter', - items: { type: 'string' }, - }, - objectParam: { - type: 'object', - description: 'An object parameter', - properties: { nestedString: { type: 'string' } }, - }, + /** + * Every adapter must hand the model what the server served. The one exception is a top-level + * `oneOf`/`anyOf`/`allOf`, which the OpenAI and Anthropic tool APIs reject outright, so every + * provider-bound adapter folds it into the root. + */ + describe('root schema pass-through across every adapter', () => { + const tool = localTool('hris_rich_probe', richSchema, 'Rich probe'); + 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, + ], + [ + 'toOpenAIResponses (non-strict)', + async () => tool.toOpenAIResponses({ strict: false }).parameters as Record, + ], + [ + 'toAISDK', + async () => { + const aiTools = await tool.toAISDK({ executable: false }); + const aiTool = aiTools.hris_rich_probe; + assert(aiTool); + return (aiTool.inputSchema as { jsonSchema: Record }).jsonSchema; }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://example.com/complex', - bodyType: 'json', - params: [], + ], + [ + 'toClaudeAgentSdkTool', + async () => + ( + (await tool.toClaudeAgentSdkTool()).inputSchema as { + jsonSchema: Record; + } + ).jsonSchema, + ], + ]; + + it.each(adapters)( + '%s keeps $schema, $defs, $ref, title and every property', + async (_name, adapt) => { + const schema = await adapt(); + + expect(schema.$schema).toBe(richSchema.$schema); + expect(schema.title).toBe(richSchema.title); + expect(schema.$defs).toEqual(richSchema.$defs); + expect(schema.properties).toEqual(richSchema.properties); + expect(schema.required).toEqual(['start_date']); + expect(schema.type).toBe('object'); }, ); - const aiSdkTool = await complexTool.toAISDK(); - - // Check that the tool is defined - expect(aiSdkTool).toBeDefined(); - expect(aiSdkTool.complex_tool).toBeDefined(); + it.each(adapters)('%s drops the root oneOf the provider would reject', async (_name, adapt) => { + const schema = await adapt(); + + for (const keyword of ['oneOf', 'anyOf', 'allOf']) { + 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' }, + ]); + }); - // Check that inputSchema is defined - expect(aiSdkTool.complex_tool.inputSchema).toBeDefined(); + it.each(adapters)('%s is otherwise exactly the served root', async (_name, adapt) => { + expect(await adapt()).toEqual(providerRoot); + }); - // TODO: Remove ts-ignore once AISDKToolDefinition properly types inputSchema.jsonSchema - // @ts-ignore - jsonSchema is available on Schema wrapper from ai sdk - const schema = aiSdkTool.complex_tool.inputSchema.jsonSchema; - expect(schema).toBeDefined(); - expect(schema.type).toBe('object'); + it('preserves a served additionalProperties: true except where the adapter closes the root', async () => { + const open = localTool('open', { ...richSchema, additionalProperties: true }); + + expect(open.toJsonSchema().additionalProperties).toBe(true); + expect(open.toOpenAI().function.parameters?.additionalProperties).toBe(true); + expect(open.toAnthropic().input_schema.additionalProperties).toBe(true); + expect(open.toOpenAIResponses({ strict: false }).parameters?.additionalProperties).toBe(true); + // Strict Responses and the AI SDK close the root: documented, and pinned here. + 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); + }); - // Check that the properties are defined with correct types - expect(schema.properties).toBeDefined(); - expect(schema.properties?.stringParam.type).toBe('string'); - expect(schema.properties?.numberParam.type).toBe('number'); - expect(schema.properties?.booleanParam.type).toBe('boolean'); - expect(schema.properties?.arrayParam.type).toBe('array'); - expect(schema.properties?.objectParam.type).toBe('object'); + it('closes the root in strict mode without rewriting anything nested', () => { + const parameters = tool.toOpenAIResponses().parameters as JSONSchema; + expect(parameters.additionalProperties).toBe(false); + expect(parameters.properties?.address).toEqual(richSchema.properties.address); + }); }); - it('should execute AI SDK tool with parameters', async () => { - const tool = createMockTool(); - const aiSdkTool = await tool.toAISDK(); - - expect(aiSdkTool.test_tool.execute).toBeDefined(); - - const result = await executeAISDKTool(aiSdkTool, 'test_tool', { id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); + it('converts to the OpenAI Chat Completions shape', () => { + expect(simpleTool().toOpenAI()).toEqual({ + type: 'function', + function: { + name: 'test_tool', + description: 'Test tool', + parameters: { type: 'object', properties: { id: { type: 'string', description: 'ID' } } }, + }, + }); }); - it('should return error message as string when AI SDK tool execution fails', async () => { - const tool = createMockTool(); - const aiSdkTool = await tool.toAISDK(); - - expect(aiSdkTool.test_tool.execute).toBeDefined(); - - // 'invalid' id returns 400 error via MSW handler - const result = await executeAISDKTool(aiSdkTool, 'test_tool', { id: 'invalid' }); - expect(result).toMatch(/Error executing tool:/); + it('converts to the Anthropic shape', () => { + expect(simpleTool().toAnthropic()).toEqual({ + name: 'test_tool', + description: 'Test tool', + input_schema: { type: 'object', properties: { id: { type: 'string', description: 'ID' } } }, + }); }); - it('should set and get headers', () => { - const tool = createMockTool(); - - // Set headers - const headers = { 'X-Custom-Header': 'test-value' }; - tool.setHeaders(headers); + it('converts to the OpenAI Responses shape, strict by default', () => { + const strict = simpleTool().toOpenAIResponses(); + expect(strict).toMatchObject({ type: 'function', name: 'test_tool', strict: true }); - // Headers should include custom header - const updatedHeaders = tool.getHeaders(); - expect(updatedHeaders['X-Custom-Header']).toBe('test-value'); - - // Set additional headers - tool.setHeaders({ 'X-Another-Header': 'another-value' }); - - // Headers should include all headers - const finalHeaders = tool.getHeaders(); - expect(finalHeaders['X-Custom-Header']).toBe('test-value'); - expect(finalHeaders['X-Another-Header']).toBe('another-value'); + const lax = simpleTool().toOpenAIResponses({ strict: false }); + expect(lax.strict).toBe(false); + expect(lax.parameters).not.toHaveProperty('additionalProperties'); }); - it('should use basic authentication', async () => { - const headers = { - Authorization: `Basic ${Buffer.from('testuser:testpass').toString('base64')}`, - }; - const tool = createMockTool(headers); - - const result = await tool.execute({ id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); + 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(); }); - it('should use bearer authentication', async () => { - const headers = { - Authorization: 'Bearer test-token', - }; - const tool = createMockTool(headers); + it('returns an AI SDK execution error as a string rather than throwing', async () => { + const aiTools = await simpleTool().toAISDK(); + expect(await executeAISDKTool(aiTools, 'test_tool', { id: '1' })).toMatch( + /^Error executing tool: Tool "test_tool" has no executor/, + ); + }); - const result = await tool.execute({ id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); + it('exposes execution metadata only when asked', async () => { + const tool = simpleTool(); + expect((await tool.toAISDK()).test_tool?.execution).toEqual({ config: { kind: 'local' } }); + expect((await tool.toAISDK({ execution: false })).test_tool?.execution).toBeUndefined(); + tool.setExposeExecutionMetadata(false); + expect((await tool.toAISDK()).test_tool?.execution).toBeUndefined(); + expect((await tool.toAISDK({ executable: false })).test_tool?.execute).toBeUndefined(); }); - it('should use api-key authentication', async () => { - const apiKey = 'test-api-key'; - const headers = { - Authorization: `Bearer ${apiKey}`, - }; - const tool = createMockTool(headers); + it('serialises a Claude Agent SDK result for the model, bytes as base64', async () => { + const tool = simpleTool(); + tool.execute = async () => ({ content: Buffer.from('%PDF') as never, ok: true }); + const definition = await tool.toClaudeAgentSdkTool(); - const result = await tool.execute({ id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); + const result = await definition.handler({}); + + expect(JSON.parse(result.content[0]?.text ?? '')).toEqual({ + content: Buffer.from('%PDF').toString('base64'), + ok: true, + }); }); }); -describe('BaseTool - additional coverage', () => { - it('should throw error when execute is called on non-HTTP tool', async () => { - const rpcTool = new BaseTool( - 'rpc_tool', - 'RPC tool', - { type: 'object', properties: {} }, - { - kind: 'rpc', - method: 'test_method', - url: 'https://api.example.com/rpc', - payloadKeys: { action: 'action', body: 'body' }, - }, +describe('StackOneRpcTool', () => { + const client = new RpcClient({ baseUrl: TEST_BASE_URL, apiKey: 'test-key', timeout: 5_000 }); + const rpcTool = (properties: Record) => + new StackOneRpcTool({ + name: 'crm_update_contact', + description: 'Update a contact', + parameters: toolParametersFromInputSchema({ type: 'object', properties }), + client, + accountId: 'acc1', + }); + const flatProperties = { + path_id: { type: 'string' }, + query_expand: { type: 'string' }, + body_name: { type: 'string' }, + 'headers_x-trace': { type: 'string' }, + } satisfies Record; + + const captureRpc = ( + response: () => Response = () => HttpResponse.json({ data: { ok: true } }), + ) => { + const seen: Array<{ headers: Headers; body: Record }> = []; + server.use( + http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { + seen.push({ + headers: request.headers, + body: (await request.json()) as Record, + }); + return response(); + }), ); + return seen; + }; - await expect(rpcTool.execute({})).rejects.toThrow( - 'BaseTool.execute is only available for HTTP-backed tools', - ); - }); + it('sends the flat_prefixed arguments as the RPC envelope, scoped to its account', async () => { + const seen = captureRpc(); - it('should throw error for invalid parameter type', async () => { - const tool = createMockTool(); + const result = await rpcTool(flatProperties).execute({ + path_id: '7', + query_expand: 'owner', + body_name: 'Ada', + 'headers_x-trace': 't-1', + }); - // @ts-expect-error - intentionally passing invalid type - await expect(tool.execute(12345)).rejects.toThrow('Invalid parameters type'); + expect(result).toEqual({ data: { ok: true } }); + expect(seen[0]?.headers.get('x-account-id')).toBe('acc1'); + expect(seen[0]?.body).toEqual({ + action: 'crm_update_contact', + body: { name: 'Ada' }, + headers: { 'x-trace': 't-1', 'x-account-id': 'acc1' }, + path: { id: '7' }, + query: { expand: 'owner' }, + }); }); - it('should create execution metadata for RPC config in toAISDK', async () => { - const rpcTool = new BaseTool( - 'rpc_tool', - 'RPC tool', - { type: 'object', properties: {} }, - { - kind: 'rpc', - method: 'test_method', - url: 'https://api.example.com/rpc', - payloadKeys: { action: 'action', body: 'body', headers: 'headers' }, - }, - ); + it('accepts arguments as a JSON string', async () => { + const seen = captureRpc(); + await rpcTool(flatProperties).execute('{"path_id":"7"}'); + expect(seen[0]?.body.path).toEqual({ id: '7' }); + }); - const aiSdkTool = await rpcTool.toAISDK({ executable: false }); - const execution = aiSdkTool.rpc_tool.execution; - - expect(execution).toBeDefined(); - expect(execution?.config.kind).toBe('rpc'); - if (execution?.config.kind === 'rpc') { - expect(execution.config.method).toBe('test_method'); - expect(execution.config.url).toBe('https://api.example.com/rpc'); - expect(execution.config.payloadKeys).toEqual({ - action: 'action', - body: 'body', - headers: 'headers', - }); - } + it('omits empty path and query, but always sends body and headers', async () => { + const seen = captureRpc(); + await rpcTool(flatProperties).execute(); + expect(seen[0]?.body).toEqual({ + action: 'crm_update_contact', + body: {}, + headers: { 'x-account-id': 'acc1' }, + }); }); - it('should create execution metadata for local config in toAISDK', async () => { - const localTool = new BaseTool( - 'local_tool', - 'Local tool', - { type: 'object', properties: {} }, - { - kind: 'local', - identifier: 'local_test', - description: 'local://test', - }, - ); + it.each([ + ['Authorization', 'Bearer stolen'], + ['authorization', 'Bearer stolen'], + ['X-Account-Id', 'victim'], + [' x-account-id ', 'victim'], + ['Proxy-Authorization', 'Basic stolen'], + ['x-stackone-account-id', 'victim'], + ['Cookie', 'session=x'], + ])('drops a model-supplied %j header', async (name, value) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const seen = captureRpc(); - const aiSdkTool = await localTool.toAISDK({ executable: false }); - const execution = aiSdkTool.local_tool.execution; + await rpcTool(flatProperties).execute({ headers: { [name]: value } }); - expect(execution).toBeDefined(); - expect(execution?.config.kind).toBe('local'); - if (execution?.config.kind === 'local') { - expect(execution.config.identifier).toBe('local_test'); - expect(execution.config.description).toBe('local://test'); - } + expect(seen[0]?.body.headers).toEqual({ 'x-account-id': 'acc1' }); + expect(seen[0]?.headers.get('x-account-id')).toBe('acc1'); + expect(seen[0]?.headers.get('authorization')).toMatch(/^Basic /); + vi.restoreAllMocks(); }); - it('should allow providing custom execution metadata in toAISDK', async () => { - const tool = createMockTool(); - const customExecution = { - config: { - kind: 'http' as const, - method: 'POST' as const, - url: 'https://custom.example.com', - bodyType: 'json' as const, - params: [], - }, - headers: { 'X-Custom': 'value' }, - }; - - const aiSdkTool = await tool.toAISDK({ execution: customExecution }); - const execution = aiSdkTool.test_tool.execution; - - expect(execution).toBeDefined(); - expect(execution?.config.kind).toBe('http'); - if (execution?.config.kind === 'http') { - expect(execution.config.url).toBe('https://custom.example.com'); - } - expect(execution?.headers).toEqual({ 'X-Custom': 'value' }); + it('drops a declared header carrying CR/LF', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const seen = captureRpc(); + await rpcTool(flatProperties).execute({ 'headers_x-trace': 'a\r\nInjected: 1' }); + expect(seen[0]?.body.headers).toEqual({ 'x-account-id': 'acc1' }); + vi.restoreAllMocks(); }); - it('should return undefined execution when execution option is false', async () => { - const tool = createMockTool(); - - const aiSdkTool = await tool.toAISDK({ execution: false }); - expect(aiSdkTool.test_tool.execution).toBeUndefined(); - }); + it('routes a bare schema field that merely starts with path_ to the body, warning once', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const seen = captureRpc(); + const tool = rpcTool({ path_to_file: { type: 'string' }, name: { type: 'string' } }); - it('should return undefined execute when executable option is false', async () => { - const tool = createMockTool(); + await tool.execute({ path_to_file: '/tmp/x' }); + await tool.execute({ path_to_file: '/tmp/y' }); - const aiSdkTool = await tool.toAISDK({ executable: false }); - expect(aiSdkTool.test_tool.execute).toBeUndefined(); + expect(seen[0]?.body.body).toEqual({ path_to_file: '/tmp/x' }); + expect(seen[0]?.body).not.toHaveProperty('path'); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain('flat-prefix detection is disabled'); + vi.restoreAllMocks(); }); - it('should get headers from tool without requestBuilder', () => { - const rpcTool = new BaseTool( - 'rpc_tool', - 'RPC tool', - { type: 'object', properties: {} }, - { - kind: 'rpc', - method: 'test_method', - url: 'https://api.example.com/rpc', - payloadKeys: { action: 'action', body: 'body' }, - }, - { 'X-Custom': 'value' }, + it('rejects a reserved container given a scalar', async () => { + await expect(rpcTool(flatProperties).execute({ query: 'sales' })).rejects.toThrow( + /"query" is an envelope container/, ); - - expect(rpcTool.getHeaders()).toEqual({ 'X-Custom': 'value' }); }); - it('should set headers on tool without requestBuilder', () => { - const rpcTool = new BaseTool( - 'rpc_tool', - 'RPC tool', - { type: 'object', properties: {} }, - { - kind: 'rpc', - method: 'test_method', - url: 'https://api.example.com/rpc', - payloadKeys: { action: 'action', body: 'body' }, - }, - ); - - rpcTool.setHeaders({ 'X-New-Header': 'new-value' }); - expect(rpcTool.getHeaders()).toEqual({ 'X-New-Header': 'new-value' }); + it('describes the request without sending it on dryRun', async () => { + const seen = captureRpc(); + const result = await rpcTool(flatProperties).execute({ path_id: '7' }, { dryRun: true }); + + expect(seen).toHaveLength(0); + expect(result.url).toBe(`${TEST_BASE_URL}/actions/rpc`); + expect(result.method).toBe('POST'); + expect(result.headers).toMatchObject({ 'x-account-id': 'acc1' }); + expect(result.headers).not.toHaveProperty('Authorization'); + expect(JSON.parse(result.body as string)).toEqual({ + action: 'crm_update_contact', + body: {}, + headers: { 'x-account-id': 'acc1' }, + path: { id: '7' }, + }); + expect(result.mappedParams).toEqual({ path_id: '7' }); }); -}); -describe('Tools', () => { - it('should get tool by name', () => { - const tool = createMockTool(); - const tools = new Tools([tool]); + it.each([ + ['not valid json', /Invalid JSON in arguments/], + ['[1, 2, 3]', /must be a JSON object/], + ['null', /must be a JSON object/], + ])('rejects arguments %j', async (input, message) => { + await expect(rpcTool(flatProperties).execute(input)).rejects.toThrow(message); + }); - expect(tools.getTool('test_tool')).toBe(tool); - expect(tools.getTool('nonexistent')).toBeUndefined(); + it('rejects a non-object, non-string argument', async () => { + // @ts-expect-error - intentionally passing an invalid type + await expect(rpcTool(flatProperties).execute(12345)).rejects.toThrow(StackOneError); }); - it('should convert all tools to OpenAI format', () => { - const tool1 = new BaseTool( - 'tool1', - 'Tool 1', - { - type: 'object', - properties: { id: { type: 'string' } }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/test/{id}', - bodyType: 'json', - params: [ - { - name: 'id', - location: ParameterLocation.PATH, - type: 'string', - }, - ], - }, + it('reports arguments JSON cannot encode as an argument error', async () => { + await expect(rpcTool(flatProperties).execute({ body_name: 1n as never })).rejects.toThrow( + /could not be encoded as JSON/, ); + }); - const tool2 = new BaseTool( - 'tool2', - 'Tool 2', - { - type: 'object', - properties: { id: { type: 'string' } }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/test/{id}', - bodyType: 'json', - params: [ - { - name: 'id', - location: ParameterLocation.PATH, - type: 'string', - }, - ], - }, - { - authorization: 'Bearer test_key', - }, + it('surfaces an API rejection with its status, body and the server message', async () => { + captureRpc(() => + HttpResponse.json( + { message: 'path.id is missing' }, + { status: 400, statusText: 'Bad Request' }, + ), ); - const tools = new Tools([tool1, tool2]); - const openAITools = tools.toOpenAI(); + const error = (await rpcTool(flatProperties) + .execute({}) + .catch((caught: unknown) => caught)) as StackOneAPIError; - expect(openAITools).toBeInstanceOf(Array); - expect(openAITools.length).toBe(2); - expect(openAITools[0].type).toBe('function'); - expect(openAITools[0].function.name).toBe('tool1'); - expect(openAITools[1].function.name).toBe('tool2'); + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(400); + expect(error.message).toBe('400 Bad Request: path.id is missing'); }); - it('should convert all tools to Anthropic format', () => { - const tool1 = new BaseTool( - 'tool1', - 'Tool 1', - { - type: 'object', - properties: { id: { type: 'string' } }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/test/{id}', - bodyType: 'json', - params: [ - { - name: 'id', - location: ParameterLocation.PATH, - type: 'string', - }, - ], - }, - ); + it('is refused by the server when it has no account', async () => { + const tool = rpcTool({ foo: { type: 'string' } }).setAccountId(undefined); + const error = (await tool + .execute({ foo: 'bar' }) + .catch((caught: unknown) => caught)) as StackOneAPIError; - const tool2 = new BaseTool( - 'tool2', - 'Tool 2', - { - type: 'object', - properties: { name: { type: 'string' } }, - }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/test', - bodyType: 'json', - params: [ - { - name: 'name', - location: ParameterLocation.BODY, - type: 'string', + expect(error.statusCode).toBe(400); + }); + + it('returns a download with a safe file name', async () => { + captureRpc( + () => + new HttpResponse(new Uint8Array([1, 2, 3]), { + headers: { + 'content-type': 'application/pdf', + 'content-disposition': "attachment; filename*=UTF-8''%2e%2e%2fsecret.pdf", }, - ], - }, + }), ); - const tools = new Tools([tool1, tool2]); - const anthropicTools = tools.toAnthropic(); + const result = await rpcTool(flatProperties).execute({ path_id: 'f' }); - expect(anthropicTools).toBeInstanceOf(Array); - expect(anthropicTools.length).toBe(2); - expect(anthropicTools[0].name).toBe('tool1'); - expect(anthropicTools[0].description).toBe('Tool 1'); - expect(anthropicTools[0].input_schema.type).toBe('object'); - expect(anthropicTools[1].name).toBe('tool2'); - expect(anthropicTools[1].description).toBe('Tool 2'); + assert(isBinaryDownloadResult(result)); + expect(result.fileName).toBe('secret.pdf'); }); - it('should convert all tools to OpenAI Responses API tools', () => { - const tool1 = new StackOneTool( - 'tool1', - 'Tool 1', - { - type: 'object', - properties: { id: { type: 'string' } }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://api.example.com/test/{id}', - bodyType: 'json', - params: [], - }, - ); - const tool2 = new StackOneTool( - 'tool2', - 'Tool 2', - { - type: 'object', - properties: { name: { type: 'string' } }, - }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/test', - bodyType: 'json', - params: [], - }, - ); + it('can be rebound to another account', async () => { + const seen = captureRpc(); + const tool = rpcTool(flatProperties); - const tools = new Tools([tool1, tool2]); - const responsesTools = tools.toOpenAIResponses(); + tool.setAccountId('acc2'); + await tool.execute({}); - expect(responsesTools).toBeInstanceOf(Array); - expect(responsesTools.length).toBe(2); - expect(responsesTools[0].type).toBe('function'); - expect(responsesTools[0].name).toBe('tool1'); - expect(responsesTools[0].strict).toBe(true); - expect(responsesTools[1].name).toBe('tool2'); - expect(responsesTools[1].strict).toBe(true); + expect(tool.getAccountId()).toBe('acc2'); + expect(seen[0]?.headers.get('x-account-id')).toBe('acc2'); }); +}); - it('should convert all tools to OpenAI Responses API tools with strict disabled', () => { - const tool1 = createMockTool(); - const tools = new Tools([tool1]); - const responsesTools = tools.toOpenAIResponses({ strict: false }); +describe('StackOneMcpTool', () => { + const calls: RecordedToolCall[] = []; + beforeEach(() => { + calls.length = 0; + const app = createMcpApp({ + accountTools: { acc1: [] }, + onToolCall: (call) => calls.push(call), + }); + 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?param-style=flat_prefixed&tool-mode=search_execute`, + apiKey: 'test-key', + accountId: 'acc1', + timeout: 5_000, + }); - expect(responsesTools[0].strict).toBe(false); - }); + it('calls the tool over tools/call and returns the parsed result', async () => { + const result = await mcpTool().execute({ + action_id: 'mock_list_items', + query: { page_size: 2 }, + }); - it('should convert all tools to AI SDK tools', async () => { - const tool1 = createMockTool(); - const tool2 = new StackOneTool( - 'another_tool', - 'Another tool', - { - type: 'object', - properties: { name: { type: 'string' } }, - }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/test', - bodyType: 'json', - params: [ - { - name: 'name', - location: ParameterLocation.BODY, - type: 'string', - }, - ], - }, + expect(result).toMatchObject({ data: { nodes: [] }, echoed_query: { page_size: 2 } }); + expect(calls).toEqual([ { - authorization: 'Bearer test_key', + accountId: 'acc1', + toolMode: 'search_execute', + name: 'mock_acc1_execute_action', + arguments: { action_id: 'mock_list_items', query: { page_size: 2 } }, }, - ); - - const tools = new Tools([tool1, tool2]); - - const aiSdkTools = await tools.toAISDK(); - - expect(Object.keys(aiSdkTools).length).toBe(2); - expect(aiSdkTools.test_tool).toBeDefined(); - expect(aiSdkTools.another_tool).toBeDefined(); - expect(typeof aiSdkTools.test_tool.execute).toBe('function'); - expect(typeof aiSdkTools.another_tool.execute).toBe('function'); + ]); }); - it('should convert all tools to Claude Agent SDK MCP server', async () => { - const tool1 = createMockTool(); - const tool2 = new StackOneTool( - 'another_tool', - 'Another tool', - { - type: 'object', - properties: { name: { type: 'string' } }, - }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/test', - bodyType: 'json', - params: [ - { - name: 'name', - location: ParameterLocation.BODY, - type: 'string', - }, - ], - }, - { - authorization: 'Bearer test_key', + // The meta tools take a `headers` object the server unpacks, and these arguments are + // model-controlled. The meta tool's own schema declares no headers_*, so nothing survives. + it('drops every model-supplied header', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await mcpTool().execute({ + action_id: 'mock_list_items', + headers: { + Authorization: 'Bearer stolen', + 'Proxy-Authorization': 'Basic stolen', + 'x-account-id': 'victim-account', + 'x-stackone-account-id': 'victim-account', + Cookie: 'session=x', + 'X-Api-Key': 'stolen', }, - ); - - const tools = new Tools([tool1, tool2]); - - const mcpServer = await tools.toClaudeAgentSdk(); + }); - expect(mcpServer).toBeDefined(); - expect(mcpServer.type).toBe('sdk'); - expect(mcpServer.name).toBe('stackone-tools'); - expect(mcpServer.instance).toBeDefined(); + expect(calls[0]?.arguments.headers).toEqual({}); + vi.restoreAllMocks(); }); - it('should convert all tools to Claude Agent SDK MCP server with custom options', async () => { - const tool1 = createMockTool(); - const tools = new Tools([tool1]); - - const mcpServer = await tools.toClaudeAgentSdk({ - serverName: 'my-custom-server', - serverVersion: '2.0.0', + it('keeps a header its own schema declares', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + await mcpTool({ 'headers_x-trace': { type: 'string' } }).execute({ + action_id: 'mock_list_items', + headers: { 'X-Trace': 'abc', 'X-Other': 'no' }, }); - - expect(mcpServer).toBeDefined(); - expect(mcpServer.type).toBe('sdk'); - expect(mcpServer.name).toBe('my-custom-server'); - expect(mcpServer.instance).toBeDefined(); + expect(calls[0]?.arguments.headers).toEqual({ 'X-Trace': 'abc' }); + vi.restoreAllMocks(); }); - it('should be iterable', () => { - const tool1 = createMockTool(); - const tool2 = new StackOneTool( - 'another_tool', - 'Another tool', - { - type: 'object', - properties: { name: { type: 'string' } }, - }, - { - kind: 'http', - method: 'POST', - url: 'https://api.example.com/test', - bodyType: 'json', - params: [ - { - name: 'name', - location: ParameterLocation.BODY, - type: 'string', - }, - ], - }, - { - authorization: 'Bearer test_key', - }, - ); + it('raises when the result carries isError', async () => { + const error = (await mcpTool() + .execute({ action_id: 'mock_not_a_real_action' }) + .catch((caught: unknown) => caught)) as StackOneAPIError; - const tools = new Tools([tool1, tool2]); - - let count = 0; - for (const tool of tools) { - expect(tool).toBeDefined(); - expect(tool.name).toBeDefined(); - count++; - } + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.message).toContain('Unknown action mock_not_a_real_action'); + expect(error.statusCode).toBe(404); + }); - expect(count).toBe(2); + it('describes the call without sending it on dryRun', async () => { + const result = await mcpTool().execute({ action_id: 'a' }, { dryRun: true }); + expect(calls).toHaveLength(0); + expect(result).toMatchObject({ method: 'tools/call', arguments: { action_id: 'a' } }); }); }); -describe('BaseTool.connector', () => { - it('should extract connector prefix from tool name', () => { - const tool = new BaseTool( - 'bamboohr_list_employees', - 'List employees', - { type: 'object', properties: {} }, - { kind: 'http', method: 'GET', url: 'https://example.com', bodyType: 'json', params: [] }, - ); - expect(tool.connector).toBe('bamboohr'); +describe('Tools', () => { + const named = (name: string) => localTool(name, { type: 'object', properties: {} }); + + it('looks tools up by name, first match wins', () => { + const first = named('dup'); + const tools = new Tools([first, named('dup'), named('other')]); + + expect(tools.getTool('dup')).toBe(first); + expect(tools.getTool('missing')).toBeUndefined(); + expect(tools.length).toBe(3); }); - it('should return the name itself for single-segment names', () => { - const tool = new BaseTool( - 'bamboohr', - 'BambooHR', - { type: 'object', properties: {} }, - { kind: 'http', method: 'GET', url: 'https://example.com', bodyType: 'json', params: [] }, - ); - expect(tool.connector).toBe('bamboohr'); + it('does not alias the array it was built from', () => { + const list = [named('a')]; + const tools = new Tools(list); + list.push(named('b')); + expect(tools.length).toBe(1); }); - it('should return empty string for empty name', () => { - const tool = new BaseTool( - '', - 'Empty', - { type: 'object', properties: {} }, - { kind: 'http', method: 'GET', url: 'https://example.com', bodyType: 'json', params: [] }, - ); - expect(tool.connector).toBe(''); + it('filters, maps, iterates and copies', () => { + const tools = new Tools([named('a_x'), named('b_x')]); + + expect(tools.filter((tool) => tool.name.startsWith('a')).map((tool) => tool.name)).toEqual([ + 'a_x', + ]); + expect([...tools].map((tool) => tool.name)).toEqual(['a_x', 'b_x']); + const seen: string[] = []; + tools.forEach((tool) => seen.push(tool.name)); + expect(seen).toEqual(['a_x', 'b_x']); + expect(tools.toArray()).not.toBe(tools.toArray()); }); - it('should return lowercase connector', () => { - const tool = new BaseTool( - 'BambooHR_create_employee', - 'Create employee', + it('tells StackOne tools apart', () => { + const stackOneTool = new StackOneTool( + 's', + '', { type: 'object', properties: {} }, - { kind: 'http', method: 'POST', url: 'https://example.com', bodyType: 'json', params: [] }, + { kind: 'local' }, + 'acc', ); - expect(tool.connector).toBe('bamboohr'); - }); -}); + const tools = new Tools([named('plain'), stackOneTool]); -describe('Tools.getConnectors', () => { - it('should return unique connector names from tool names', () => { - const tools = new Tools([ - new BaseTool( - 'bamboohr_create_employee', - 'Create employee', - { type: 'object', properties: {} }, - { kind: 'http', method: 'POST', url: 'https://example.com', bodyType: 'json', params: [] }, - ), - new BaseTool( - 'bamboohr_list_employees', - 'List employees', - { type: 'object', properties: {} }, - { kind: 'http', method: 'GET', url: 'https://example.com', bodyType: 'json', params: [] }, - ), - new BaseTool( - 'hibob_create_employee', - 'Create employee', - { type: 'object', properties: {} }, - { kind: 'http', method: 'POST', url: 'https://example.com', bodyType: 'json', params: [] }, - ), - new BaseTool( - 'slack_send_message', - 'Send message', - { type: 'object', properties: {} }, - { kind: 'http', method: 'POST', url: 'https://example.com', bodyType: 'json', params: [] }, - ), - ]); - - const connectors = tools.getConnectors(); - expect(connectors).toEqual(new Set(['bamboohr', 'hibob', 'slack'])); + expect(tools.getStackOneTools()).toEqual([stackOneTool]); + expect(tools.getStackOneTool('s').getAccountId()).toBe('acc'); + expect(() => tools.getStackOneTool('plain')).toThrow(StackOneError); + expect(tools.isStackOneTool(stackOneTool)).toBe(true); }); - it('should return empty set for empty tools', () => { - const tools = new Tools([]); - expect(tools.getConnectors()).toEqual(new Set()); - }); + it('converts every tool with every adapter', async () => { + const tools = new Tools([named('a'), localTool('b', richSchema)]); - it('should return lowercase connector names', () => { - const tools = new Tools([ - new BaseTool( - 'BambooHR_create_employee', - 'Create employee', - { type: 'object', properties: {} }, - { kind: 'http', method: 'POST', url: 'https://example.com', bodyType: 'json', params: [] }, - ), + expect(tools.toJsonSchema().map((entry) => entry.parameters)).toEqual([ + { type: 'object', properties: {} }, + richSchema, ]); - - const connectors = tools.getConnectors(); - expect(connectors).toEqual(new Set(['bamboohr'])); + expect(tools.toOpenAI().map((tool) => tool.function.name)).toEqual(['a', 'b']); + expect(tools.toAnthropic().map((tool) => tool.name)).toEqual(['a', 'b']); + expect(tools.toOpenAIResponses({ strict: false }).map((tool) => tool.strict)).toEqual([ + false, + false, + ]); + expect(Object.keys(await tools.toAISDK())).toEqual(['a', 'b']); }); -}); -describe('Schema Validation', () => { - describe('Array Items in Schema', () => { - it('should preserve array items when provided', () => { - const tool = new StackOneTool( - 'test_tool', - 'Test tool', - { - type: 'object', - properties: { - arrayWithItems: { - type: 'array', - description: 'Array with items', - items: { type: 'number' }, - }, - }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://example.com/test', - bodyType: 'json', - params: [], - }, - { authorization: 'Bearer test_api_key' }, - ); - - const parameters = tool.toOpenAI().function.parameters; - const properties = parameters?.properties as Record; - - expect(properties.arrayWithItems.items).toBeDefined(); - expect((properties.arrayWithItems.items as JSONSchema).type).toBe('number'); + it('builds a Claude Agent SDK MCP server', async () => { + const mcpServer = await new Tools([named('a')]).toClaudeAgentSdk({ + serverName: 'custom', + serverVersion: '2.0.0', }); - it('should handle nested object structure', () => { - const tool = new StackOneTool( - 'test_tool', - 'Test tool', - { - type: 'object', - properties: { - nestedObject: { - type: 'object', - properties: { - nestedArray: { - type: 'array', - items: { type: 'string' }, - }, - }, - }, - }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://example.com/test', - bodyType: 'json', - params: [], - }, - { authorization: 'Bearer test_api_key' }, - ); - - const parameters = tool.toOpenAI().function.parameters; - expect(parameters).toBeDefined(); - const properties = parameters?.properties as Record; - const nestedObject = properties.nestedObject; - - expect(nestedObject.type).toBe('object'); - expect(nestedObject.properties).toBeDefined(); - }); + expect(mcpServer.type).toBe('sdk'); + expect(mcpServer.name).toBe('custom'); + expect(mcpServer.instance).toBeDefined(); }); +}); - describe('AI SDK Integration', () => { - it('should convert to AI SDK tool format with correct schema structure', async () => { - const tool = new StackOneTool( - 'test_tool', - 'Test tool with arrays', - { - type: 'object', - properties: { - arrayWithItems: { type: 'array', items: { type: 'string' } }, - }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://example.com/test', - bodyType: 'json', - params: [], - }, - { authorization: 'Bearer test_api_key' }, - ); - - const aiSdkTool = await tool.toAISDK(); - const toolObj = aiSdkTool[tool.name]; - - expect(toolObj).toBeDefined(); - expect(typeof toolObj.execute).toBe('function'); - // TODO: Remove ts-ignore once AISDKToolDefinition properly types inputSchema.jsonSchema - // @ts-ignore - jsonSchema is available on Schema wrapper from ai sdk - expect(toolObj.inputSchema.jsonSchema.type).toBe('object'); - - // @ts-ignore - jsonSchema is available on Schema wrapper from ai sdk - const arrayWithItems = toolObj.inputSchema.jsonSchema.properties?.arrayWithItems; - expect(arrayWithItems?.type).toBe('array'); - expect((arrayWithItems?.items as JSONSchema)?.type).toBe('string'); - }); - - it('should handle nested filter object for AI SDK', async () => { - const tool = new StackOneTool( - 'test_nested_arrays', - 'Test nested arrays', - { - type: 'object', - properties: { - filter: { - type: 'object', - properties: { - type_ids: { - type: 'array', - items: { type: 'string' }, - description: 'List of type IDs', - }, - status: { type: 'string' }, - }, - }, - }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://example.com/test', - bodyType: 'json', - params: [], - }, - { authorization: 'Bearer test_api_key' }, - ); - - const parameters = tool.toOpenAI().function.parameters; - expect(parameters).toBeDefined(); - const aiSchema = jsonSchema(parameters as JSONSchema); - expect(aiSchema).toBeDefined(); - - const aiSdkTool = await tool.toAISDK(); - // TODO: Remove ts-ignore once AISDKToolDefinition properly types inputSchema.jsonSchema - // @ts-ignore - jsonSchema is available on Schema wrapper from ai sdk - const filterProp = aiSdkTool[tool.name].inputSchema.jsonSchema.properties?.filter as - | (JSONSchema & { properties: Record }) - | undefined; - - expect(filterProp?.type).toBe('object'); - expect(filterProp?.properties.type_ids.type).toBe('array'); - expect(filterProp?.properties.type_ids.items).toBeDefined(); - }); +describe('ToolParameters typing', () => { + it('accepts a served schema as parameters', () => { + const parameters: ToolParameters = toolParametersFromInputSchema(richSchema); + expect(parameters.type).toBe('object'); }); }); diff --git a/src/tool.ts b/src/tool.ts index b79478ea..11c6d608 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -5,23 +5,26 @@ import type { ChatCompletionFunctionTool } from 'openai/resources/chat/completio import type { FunctionTool as OpenAIResponsesFunctionTool } from 'openai/resources/responses/responses'; import type { OverrideProperties } from 'type-fest'; import { peerDependencies } from '../package.json'; -import { RequestBuilder } from './requestBuilder'; +import { isFlatPrefixedSchema, splitEnvelopeParams, warnBareSchema } from './envelope'; +import { buildRequestHeaders, declaredHeaderNames, sanitiseHeaders } from './headers'; +import { callMcpTool } from './mcp-client'; +import type { RpcActionRequest, RpcClient } from './rpc-client'; +import { cloneJson, foldRootComposition } from './schema'; import type { AISDKToolDefinition, AISDKToolResult, ClaudeAgentSdkOptions, ExecuteConfig, ExecuteOptions, - HttpExecuteConfig, JsonObject, JSONSchema, - LocalExecuteConfig, + McpExecuteConfig, RpcExecuteConfig, ToolExecution, ToolParameters, } from './types'; - import { StackOneError } from './utils/error-stackone'; +import { serializeToolResult } from './utils/serialize'; import { tryImport } from './utils/try-import'; /** @@ -30,105 +33,34 @@ import { tryImport } from './utils/try-import'; */ type ObjectJSONSchema = OverrideProperties; +const isPlainObject = (value: unknown): value is JsonObject => + typeof value === 'object' && value !== null && !Array.isArray(value); + /** - * Base class for all tools. Provides common functionality for executing API calls - * and converting to various formats (OpenAI, AI SDK) + * Base class for all tools: a name, a description, the served parameter schema, and conversions + * to each framework's tool format. + * + * `BaseTool` itself cannot execute anything. The tools a {@link StackOneToolSet} returns are + * {@link StackOneTool}s that execute over the RPC endpoint or MCP `tools/call`; a hand-built + * tool must override {@link BaseTool.execute}. */ export class BaseTool { name: string; description: string; parameters: ToolParameters; executeConfig: ExecuteConfig; - protected requestBuilder?: RequestBuilder; #exposeExecutionMetadata = true; - #headers: Record; - - private createExecutionMetadata(): ToolExecution { - const config = (() => { - switch (this.executeConfig.kind) { - case 'http': - return { - kind: 'http', - method: this.executeConfig.method, - url: this.executeConfig.url, - bodyType: this.executeConfig.bodyType, - params: this.executeConfig.params.map((param) => ({ - ...param, - })), - } satisfies HttpExecuteConfig; - case 'rpc': - return { - kind: 'rpc', - method: this.executeConfig.method, - url: this.executeConfig.url, - payloadKeys: { ...this.executeConfig.payloadKeys }, - } satisfies RpcExecuteConfig; - case 'local': - return { - kind: 'local', - identifier: this.executeConfig.identifier, - description: this.executeConfig.description, - } satisfies LocalExecuteConfig; - default: - this.executeConfig satisfies never; - throw new StackOneError('Unsupported executeConfig kind'); - } - })(); - - return { - config, - headers: this.getHeaders(), - }; - } constructor( name: string, description: string, parameters: ToolParameters, executeConfig: ExecuteConfig, - headers?: Record, ) { this.name = name; this.description = description; this.parameters = parameters; this.executeConfig = executeConfig; - this.#headers = { ...headers }; - if (executeConfig.kind === 'http') { - this.requestBuilder = new RequestBuilder(executeConfig, this.#headers); - } - } - - /** - * Set headers for this tool - */ - setHeaders(headers: Record): BaseTool { - this.#headers = { ...this.#headers, ...headers }; - if (this.requestBuilder) { - this.requestBuilder.setHeaders(headers); - } - return this; - } - - /** - * Get the current headers - */ - getHeaders(): Record { - if (this.requestBuilder) { - const currentHeaders = this.requestBuilder.getHeaders(); - this.#headers = { ...currentHeaders }; - return currentHeaders; - } - return { ...this.#headers }; - } - - /** - * Extract connector/provider prefix from the tool name. - * - * Tool names follow the format `{connector}_{action}_{entity}`, - * e.g. `"bamboohr_list_employees"` → `"bamboohr"`. - */ - get connector(): string { - return this.name.split('_')[0]?.toLowerCase() ?? ''; } /** @@ -140,64 +72,60 @@ export class BaseTool { } /** - * Execute the tool with the provided parameters + * Execute the tool with the provided parameters. + * + * @throws StackOneError Always, on a `BaseTool`: override this to make a tool executable. */ - async execute(inputParams?: JsonObject | string, options?: ExecuteOptions): Promise { - try { - if (!this.requestBuilder || this.executeConfig.kind !== 'http') { - // Non-HTTP tools provide their own execute override (e.g. RPC, local tools). - throw new StackOneError( - 'BaseTool.execute is only available for HTTP-backed tools. Provide a custom execute implementation for non-HTTP tools.', - ); - } - // Validate params is either undefined, string, or object - if ( - inputParams !== undefined && - typeof inputParams !== 'string' && - typeof inputParams !== 'object' - ) { - throw new StackOneError( - `Invalid parameters type. Expected object or string, got ${typeof inputParams}. Parameters: ${JSON.stringify( - inputParams, - )}`, - ); - } - - // Convert string params to object - const params = typeof inputParams === 'string' ? JSON.parse(inputParams) : inputParams || {}; - - // Execute the request directly with parameters - return await this.requestBuilder.execute(params, options); - } catch (error) { - if (error instanceof StackOneError) { - throw error; - } - throw new StackOneError( - `Error executing tool: ${error instanceof Error ? error.message : String(error)}`, - ); - } + async execute( + _inputParams?: JsonObject | string, + _options?: ExecuteOptions, + ): Promise { + throw new StackOneError( + `Tool "${this.name}" has no executor. Override execute() to run a hand-built tool.`, + ); } /** - * Convert the tool parameters to a pure JSON Schema format - * This is framework-agnostic and can be used with any LLM that accepts JSON Schema + * The served parameter schema, verbatim, as a fresh deep copy. + * + * Lossless and framework-agnostic: every root keyword the server sent — `$schema`, `$defs`, + * `$ref`, `title`, `additionalProperties`, top-level `oneOf`/`anyOf`/`allOf` — and every + * nested constraint reaches the caller unchanged, with the served `required` list. Use this + * for any framework that accepts JSON Schema; the provider adapters below start from it. */ toJsonSchema(): ObjectJSONSchema { + const { required, ...rest } = cloneJson(this.parameters); const schema: Record = { - ...this.parameters, - type: 'object', - properties: this.parameters.properties, + ...rest, + type: rest.type || 'object', + properties: rest.properties ?? {}, }; - if (this.parameters.required && this.parameters.required.length > 0) { - schema.required = this.parameters.required; - } else { - delete schema.required; + if (Array.isArray(required) && required.length > 0) { + schema.required = required; } - return schema as unknown as ObjectJSONSchema; + return schema as ObjectJSONSchema; + } + + /** + * {@link toJsonSchema}, adjusted for providers that require a plain object at the root. + * + * The OpenAI and Anthropic tool APIs both reject a parameters schema with a top-level + * `oneOf`/`anyOf`/`allOf`; see {@link foldRootComposition} for how it is folded rather than + * lost. Everything else is passed through. + */ + #toProviderSchema(): ObjectJSONSchema { + return foldRootComposition(this.toJsonSchema()) as ObjectJSONSchema; + } + + #createExecutionMetadata(): ToolExecution { + return { config: cloneJson(this.executeConfig) }; } /** - * Convert the tool to OpenAI Chat Completions API format + * Convert the tool to OpenAI Chat Completions API format. + * + * The schema is {@link toJsonSchema} with any top-level `oneOf`/`anyOf`/`allOf`/`enum`/`not` + * folded into the root, which Chat Completions rejects. */ toOpenAI(): ChatCompletionFunctionTool { return { @@ -205,26 +133,39 @@ export class BaseTool { function: { name: this.name, description: this.description, - parameters: this.toJsonSchema(), + parameters: this.#toProviderSchema(), }, }; } /** - * Convert the tool to Anthropic format + * Convert the tool to Anthropic format. + * + * The schema is {@link toJsonSchema} with any top-level `oneOf`/`anyOf`/`allOf` folded into + * the root: the Messages API rejects `input_schema` with a combinator at the top level. + * * @see https://docs.anthropic.com/en/docs/build-with-claude/tool-use */ toAnthropic(): AnthropicTool { return { name: this.name, description: this.description, - input_schema: this.toJsonSchema(), + input_schema: this.#toProviderSchema(), }; } /** - * Convert the tool to OpenAI Responses API format + * Convert the tool to OpenAI Responses API format. + * + * With `strict` (the default) the root schema is closed with `additionalProperties: false`, + * replacing whatever the server served there. The SDK does not rewrite anything nested: + * OpenAI's strict mode additionally requires every property to be listed in `required` and + * every nested object to be closed, so a served schema with optional fields is rejected by + * OpenAI in strict mode. Pass `{ strict: false }` for those — the served schema then goes + * through unchanged apart from the top-level composition fold. + * * @see https://platform.openai.com/docs/api-reference/responses + * @see https://platform.openai.com/docs/guides/structured-outputs#supported-schemas */ toOpenAIResponses(options: { strict?: boolean } = {}): OpenAIResponsesFunctionTool { const { strict = true } = options; @@ -234,7 +175,7 @@ export class BaseTool { description: this.description, strict, parameters: { - ...this.toJsonSchema(), + ...this.#toProviderSchema(), ...(strict ? { additionalProperties: false } : {}), }, }; @@ -244,6 +185,9 @@ export class BaseTool { * Convert the tool to Claude Agent SDK format. * Returns a tool definition compatible with the Claude Agent SDK's tool() function. * + * The schema is the one {@link toAnthropic} uses. Results are handed back as JSON text, with + * file bytes base64-encoded. + * * @see https://docs.anthropic.com/en/docs/agents-and-tools/claude-agent-sdk */ async toClaudeAgentSdkTool(): Promise<{ @@ -258,7 +202,7 @@ export class BaseTool { 'ai', `npm install ai (requires ${peerDependencies.ai})`, ); - const inputSchema = ai.jsonSchema(this.toJsonSchema()); + const inputSchema = ai.jsonSchema(this.#toProviderSchema() as AISDKJSONSchema); const execute = this.execute.bind(this); return { @@ -268,14 +212,20 @@ export class BaseTool { handler: async (args: Record) => { const result = await execute(args as JsonObject); return { - content: [{ type: 'text' as const, text: JSON.stringify(result) }], + content: [{ type: 'text' as const, text: serializeToolResult(result) }], }; }, }; } /** - * Convert the tool to AI SDK format + * Convert the tool to AI SDK format. + * + * The schema is {@link toJsonSchema} with top-level composition folded (the AI SDK hands it + * to whichever provider you use, and OpenAI and Anthropic both reject it), and with the root + * closed by `additionalProperties: false`, replacing whatever the server served there. This + * matches what the AI SDK's OpenAI provider needs for strict structured outputs; nested + * objects are passed through as served. */ async toAISDK( options: { executable?: boolean; execution?: ToolExecution | false } = { @@ -283,9 +233,9 @@ export class BaseTool { }, ): Promise { const schema = { - ...this.toJsonSchema(), + ...this.#toProviderSchema(), additionalProperties: false, - } satisfies AISDKJSONSchema; + } as AISDKJSONSchema; /** AI SDK is optional dependency, import only when needed */ const ai = await tryImport( @@ -298,7 +248,7 @@ export class BaseTool { options.execution !== undefined ? options.execution : this.#exposeExecutionMetadata - ? this.createExecutionMetadata() + ? this.#createExecutionMetadata() : false; const toolDefinition = { @@ -326,23 +276,251 @@ export class BaseTool { } /** - * StackOne-specific tool class with additional functionality + * A tool served by StackOne, bound to the account it was listed for. */ export class StackOneTool extends BaseTool { + #accountId: string | undefined; + + constructor( + name: string, + description: string, + parameters: ToolParameters, + executeConfig: ExecuteConfig, + accountId?: string, + ) { + super(name, description, parameters, executeConfig); + this.#accountId = accountId; + } + /** - * Get the current account ID + * Get the account this tool executes against. */ getAccountId(): string | undefined { - return this.getHeaders()['x-account-id']; + return this.#accountId; } /** - * Set the account ID for this tool + * Rebind this tool to another account. The tools `fetchTools()` returns are built fresh per + * call, so this never affects another caller's tools. */ - setAccountId(accountId: string): StackOneTool { - this.setHeaders({ 'x-account-id': accountId }); + setAccountId(accountId: string | undefined): this { + this.#accountId = accountId; return this; } + + /** + * Parse tool arguments: a JSON string, an object, or nothing. + * + * @throws StackOneError If the arguments are not a JSON object. + */ + protected parseArguments(input: JsonObject | string | undefined): JsonObject { + if (input === undefined || input === null) { + return {}; + } + if (typeof input !== 'string' && typeof input !== 'object') { + throw new StackOneError( + `Invalid parameters type for "${this.name}". Expected object or string, got ${typeof input}.`, + ); + } + let parsed: unknown = input; + if (typeof input === 'string') { + try { + parsed = JSON.parse(input); + } catch (error) { + throw new StackOneError( + `Invalid JSON in arguments for "${this.name}": ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + } + if (!isPlainObject(parsed)) { + throw new StackOneError(`Tool arguments for "${this.name}" must be a JSON object`); + } + return { ...parsed }; + } +} + +/** + * A tool executed over the StackOne actions RPC endpoint — every per-action tool in the + * `individual` catalog. + * + * Arguments are split into the RPC envelope by their `flat_prefixed` location prefix, whether + * to trust that prefix being decided once from the served schema. Headers are filtered to the + * ones the schema declares, and the account is always the tool's own. + */ +export class StackOneRpcTool extends StackOneTool { + readonly #client: RpcClient; + readonly #declared: ReadonlySet; + readonly #flatPrefixed: boolean; + readonly #allowedHeaders: ReadonlySet; + #warnedBareSchema = false; + + constructor(options: { + name: string; + description: string; + parameters: ToolParameters; + client: RpcClient; + accountId?: string; + }) { + const executeConfig = { + kind: 'rpc', + method: 'POST', + url: options.client.url, + // Mirrors the StackOne RPC payload layout so metadata/debug stays in sync. + payloadKeys: { + action: 'action', + body: 'body', + headers: 'headers', + path: 'path', + query: 'query', + }, + } as const satisfies RpcExecuteConfig; + super(options.name, options.description, options.parameters, executeConfig, options.accountId); + this.setExposeExecutionMetadata(false); + this.#client = options.client; + this.#declared = new Set(Object.keys(options.parameters.properties)); + this.#flatPrefixed = isFlatPrefixedSchema(this.#declared); + this.#allowedHeaders = declaredHeaderNames(this.#declared); + } + + /** + * Build the `/actions/rpc` request for these arguments. + */ + #buildRequest(args: JsonObject): RpcActionRequest { + if (!this.#flatPrefixed && !this.#warnedBareSchema) { + this.#warnedBareSchema = true; + warnBareSchema(this.name); + } + const envelope = splitEnvelopeParams(args, this.#declared, this.#flatPrefixed); + const headers = sanitiseHeaders(envelope.headers, this.#allowedHeaders); + // Set last, so nothing a tool call supplies can retarget the request. + const accountId = this.getAccountId(); + if (accountId) { + headers['x-account-id'] = accountId; + } + return { + action: this.name, + body: envelope.body, + headers, + ...(Object.keys(envelope.path).length > 0 ? { path: envelope.path } : {}), + ...(Object.keys(envelope.query).length > 0 ? { query: envelope.query } : {}), + }; + } + + /** + * Execute the action. + * + * @returns The parsed JSON response. For a file download (any non-JSON Content-Type), a + * {@link BinaryDownloadResult} whose `content` is a raw `Buffer` — not JSON-serialisable, so + * handle it before re-serialising the result for a model. + * @throws StackOneAPIError If the API rejects the request; the message leads with the + * server's own explanation. + * @throws StackOneError If the arguments are malformed or the request cannot be sent. + */ + override async execute( + inputParams?: JsonObject | string, + options?: ExecuteOptions, + ): Promise { + try { + const args = this.parseArguments(inputParams); + const request = this.#buildRequest(args); + const accountId = this.getAccountId(); + + if (options?.dryRun) { + const { Authorization: _credential, ...headers } = this.#client.requestHeaders(accountId); + return { + url: this.#client.url, + method: 'POST', + headers, + body: JSON.stringify(request), + mappedParams: args, + }; + } + + return (await this.#client.rpcAction(request, accountId)) as unknown as JsonObject; + } catch (error) { + if (error instanceof StackOneError) { + throw error; + } + throw new StackOneError(`Error executing RPC action ${this.name}`, { cause: error }); + } + } +} + +/** + * A tool executed over MCP `tools/call` on the endpoint that listed it: the `search_execute` + * meta tools, and `stackone_submit_feedback` in every mode. They have no action behind them on + * `/actions/rpc`. + */ +export class StackOneMcpTool extends StackOneTool { + readonly #endpoint: string; + readonly #apiKey: string; + readonly #extraHeaders: Record; + readonly #timeout: number; + readonly #allowedHeaders: ReadonlySet; + + constructor(options: { + name: string; + description: string; + parameters: ToolParameters; + endpoint: string; + apiKey: string; + accountId?: string; + timeout: number; + extraHeaders?: Record; + }) { + const executeConfig = { + kind: 'mcp', + url: options.endpoint, + toolName: options.name, + } as const satisfies McpExecuteConfig; + super(options.name, options.description, options.parameters, executeConfig, options.accountId); + this.setExposeExecutionMetadata(false); + this.#endpoint = options.endpoint; + this.#apiKey = options.apiKey; + this.#extraHeaders = { ...options.extraHeaders }; + this.#timeout = options.timeout; + this.#allowedHeaders = declaredHeaderNames(Object.keys(options.parameters.properties)); + } + + /** + * Call the tool. + * + * A `headers` object in the arguments is filtered to what this tool's own schema declares + * under `headers_*` — for the meta tools that is nothing, so every model-supplied header is + * dropped: these arguments are model-controlled, and the envelope is unpacked server-side. + * + * @throws StackOneAPIError If the result carries `isError`, with the status from its payload, + * or the endpoint answers with an HTTP error. + * @throws ToolSetLoadError If the endpoint cannot be reached or does not answer in time. + */ + override async execute( + inputParams?: JsonObject | string, + options?: ExecuteOptions, + ): Promise { + const parsed = this.parseArguments(inputParams); + const args = isPlainObject(parsed.headers) + ? { ...parsed, headers: sanitiseHeaders(parsed.headers, this.#allowedHeaders) } + : parsed; + + if (options?.dryRun) { + return { url: this.#endpoint, method: 'tools/call', name: this.name, arguments: args }; + } + + return callMcpTool( + { + endpoint: this.#endpoint, + headers: buildRequestHeaders({ + apiKey: this.#apiKey, + accountId: this.getAccountId(), + extraHeaders: this.#extraHeaders, + }), + timeout: this.#timeout, + }, + this.name, + args, + ); + } } /** @@ -352,7 +530,7 @@ export class Tools implements Iterable { private tools: BaseTool[]; constructor(tools: BaseTool[]) { - this.tools = tools; + this.tools = [...tools]; } /** @@ -363,7 +541,7 @@ export class Tools implements Iterable { } /** - * Get a tool by name + * Get a tool by name. When two accounts serve the same name, this is the first one listed. */ getTool(name: string): BaseTool | undefined { return this.tools.find((tool) => tool.name === name); @@ -509,31 +687,6 @@ export class Tools implements Iterable { return new Tools(this.tools.filter(predicate)); } - /** - * Get unique connector names from all tools. - * - * Extracts the connector/provider prefix from each tool name - * (the first segment before `_`). - * - * @returns Set of connector names (lowercase) - * - * @example - * ```typescript - * const tools = await toolset.fetchTools(); - * const connectors = tools.getConnectors(); - * // Set { 'bamboohr', 'hibob', 'slack', ... } - * ``` - */ - getConnectors(): Set { - const connectors = new Set(); - for (const tool of this.tools) { - if (tool.connector) { - connectors.add(tool.connector); - } - } - return connectors; - } - /** * Iterator implementation */ diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index d57e6a9a..45534fc1 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -1,1073 +1,859 @@ /** - * StackOneToolSet tests - comprehensive test suite covering: - * - Initialization and configuration - * - Authentication (basic, bearer) - * - Glob and filter matching - * - MCP fetch integration - * - Account filtering - * - Provider and action filtering + * StackOneToolSet: configuration, account discovery, catalog listing and caching, filtering, + * 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 { http, HttpResponse } from 'msw'; -import { type McpToolDefinition, createMcpApp, defaultMcpTools } from '../mocks/mcp-server'; -import { server } from '../mocks/node'; import { TEST_BASE_URL } from '../mocks/constants'; +import { type McpToolDefinition, accountMcpTools, createMcpApp } from '../mocks/mcp-server'; +import { server } from '../mocks/node'; +import { type McpToolDefinition as ListedTool, listMcpTools } from './mcp-client'; +import { StackOneMcpTool, StackOneRpcTool, type StackOneTool } from './tool'; import { StackOneToolSet } from './toolsets'; -import { ToolSetConfigError } from './utils/error-toolset'; - -describe('StackOneToolSet', () => { - beforeEach(() => { - vi.stubEnv('STACKONE_API_KEY', 'test_key'); - }); - - afterEach(() => { - vi.unstubAllEnvs(); - }); - - describe('initialization', () => { - it('should initialize with API key from constructor', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); - - expect(toolset).toBeDefined(); - // @ts-expect-error - Accessing private property for testing - expect(toolset.authentication?.credentials?.username).toBe('custom_key'); - }); - - it('should initialize with API key from environment', () => { - const toolset = new StackOneToolSet(); - - expect(toolset).toBeDefined(); - // @ts-expect-error - Accessing private property for testing - expect(toolset.authentication?.credentials?.username).toBe('test_key'); - }); - - it('should initialize with custom values', () => { - const baseUrl = 'https://api.example.com'; - const headers = { 'X-Custom-Header': 'test' }; - - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - baseUrl, - headers, - }); - - // @ts-expect-error - Accessing private properties for testing - expect(toolset.baseUrl).toBe(baseUrl); - // @ts-expect-error - Accessing private properties for testing - expect(toolset.headers['X-Custom-Header']).toBe('test'); - }); +import { StackOneAPIError } from './utils/error-stackone-api'; +import { StackOneError } from './utils/error-stackone'; +import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; - it('should set API key in headers', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); +vi.mock('./mcp-client', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, listMcpTools: vi.fn(actual.listMcpTools) }; +}); - // @ts-expect-error - Accessing private property for testing - expect(toolset.headers.Authorization).toBe('Basic Y3VzdG9tX2tleTo='); - }); +const listMock = vi.mocked(listMcpTools); +const { listMcpTools: realListMcpTools } = + await vi.importActual('./mcp-client'); - it('should set account ID in headers if provided', () => { - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - accountId: 'test_account', - }); +type ListRequest = Parameters[0]; +const accountOf = (request: ListRequest): string | undefined => request.headers['x-account-id']; +const def = (name: string, inputSchema: Record = {}): ListedTool => ({ + name, + description: '', + inputSchema, +}); +/** Replace the MCP listing, as the Python suite monkeypatches `fetch_mcp_tools`. */ +const fakeListing = (listing: (request: ListRequest) => ListedTool[] | Promise) => { + listMock.mockImplementation(async (request) => listing(request)); +}; + +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); + +let warnSpy: ReturnType; +beforeEach(() => { + vi.stubEnv('STACKONE_ACCOUNT_ID', ''); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + listMock.mockReset(); + listMock.mockImplementation(realListMcpTools); +}); - // Verify account ID is stored in the headers - // @ts-expect-error - Accessing private property for testing - expect(toolset.headers['x-account-id']).toBe('test_account'); - }); +describe('configuration', () => { + it('requires an API key', () => { + vi.stubEnv('STACKONE_API_KEY', ''); + expect(() => new StackOneToolSet()).toThrow(ToolSetConfigError); + expect(() => new StackOneToolSet()).toThrow(/API key must be provided/); + }); - it('should allow setting account IDs via setAccounts', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); + it('reads the API key from STACKONE_API_KEY', async () => { + vi.stubEnv('STACKONE_API_KEY', 'test-key'); + const tools = await new StackOneToolSet({ + baseUrl: TEST_BASE_URL, + accountId: 'acc1', + }).fetchTools(); + expect(tools.length).toBe(2); + }); - const result = toolset.setAccounts(['account-1', 'account-2']); + it('reads the account from STACKONE_ACCOUNT_ID', async () => { + vi.stubEnv('STACKONE_ACCOUNT_ID', 'acc3'); + expect(names(await newToolSet().fetchTools())).toEqual(['acc3_tool_1']); + }); - // Should return this for chaining - expect(result).toBe(toolset); - // @ts-expect-error - Accessing private property for testing - expect(toolset.accountIds).toEqual(['account-1', 'account-2']); - }); + it('refuses both accountId and accountIds', () => { + expect(() => newToolSet({ accountId: 'a', accountIds: ['b'] } as never)).toThrow( + /Cannot provide both accountId and accountIds/, + ); + }); - it('should initialize with multiple account IDs from constructor', () => { - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - accountIds: ['account-1', 'account-2', 'account-3'], - }); + it.each([ + ['accountIds', () => newToolSet({ accountIds: 'acc1' as never })], + ['setAccounts', () => newToolSet().setAccounts('acc1' as never)], + ['fetchTools', () => newToolSet().fetchTools({ accountIds: 'acc1' as never })], + ])('refuses a string where %s expects a list', async (_name, act) => { + await expect(async () => act()).rejects.toThrow(/not a string. Did you mean \["acc1"\]\?/); + }); - // @ts-expect-error - Accessing private property for testing - expect(toolset.accountIds).toEqual(['account-1', 'account-2', 'account-3']); - }); + it('returns itself from setAccounts for chaining', () => { + const toolset = newToolSet(); + expect(toolset.setAccounts(['acc1'])).toBe(toolset); + }); - it('should initialize with empty accountIds array when not provided', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); + it('warns that it overrides SDK-owned headers passed in config', () => { + newToolSet({ headers: { Authorization: 'Bearer x', 'X-Trace': 't' } }); + expect(String(warnSpy.mock.calls[0]?.[0])).toContain('"Authorization"'); + }); +}); - // @ts-expect-error - Accessing private property for testing - expect(toolset.accountIds).toEqual([]); - }); +describe('account scope', () => { + it('lists the given accounts', async () => { + const tools = await newToolSet().fetchTools({ accountIds: ['acc1'] }); + expect(names(tools)).toEqual(['acc1_tool_1', 'acc1_tool_2']); + }); - it('should not allow both accountId and accountIds in constructor (type check)', () => { - // This test verifies the type system prevents using both accountId and accountIds - // The following would be a type error: - // new StackOneToolSet({ - // apiKey: 'custom_key', - // accountId: 'primary-account', - // accountIds: ['account-1', 'account-2'], - // }); - - // Valid: only accountId - const toolsetSingle = new StackOneToolSet({ - apiKey: 'custom_key', - accountId: 'primary-account', - }); - // @ts-expect-error - Accessing private property for testing - expect(toolsetSingle.headers['x-account-id']).toBe('primary-account'); - // @ts-expect-error - Accessing private property for testing - expect(toolsetSingle.accountIds).toEqual([]); - - // Valid: only accountIds - const toolsetMultiple = new StackOneToolSet({ - apiKey: 'custom_key', - accountIds: ['account-1', 'account-2'], - }); - // @ts-expect-error - Accessing private property for testing - expect(toolsetMultiple.headers['x-account-id']).toBeUndefined(); - // @ts-expect-error - Accessing private property for testing - expect(toolsetMultiple.accountIds).toEqual(['account-1', 'account-2']); - }); + it('lists every given account', async () => { + expect((await newToolSet().fetchTools({ accountIds: ['acc1', 'acc2', 'acc3'] })).length).toBe( + 5, + ); + }); - it('should throw error when both accountId and accountIds are provided at runtime', () => { - // Runtime validation for JavaScript users or when TypeScript is bypassed - expect(() => { - new StackOneToolSet({ - apiKey: 'custom_key', - accountId: 'primary-account', - accountIds: ['account-1', 'account-2'], - } as never); // Use 'as never' to bypass TypeScript for runtime test - }).toThrow(ToolSetConfigError); - expect(() => { - new StackOneToolSet({ - apiKey: 'custom_key', - accountId: 'primary-account', - accountIds: ['account-1', 'account-2'], - } as never); - }).toThrow(/Cannot provide both accountId and accountIds/); - }); + it('uses setAccounts, the constructor accountIds, execute.accountIds and accountId in turn', async () => { + expect(names(await newToolSet().setAccounts(['acc3']).fetchTools())).toEqual(['acc3_tool_1']); + expect(names(await newToolSet({ accountIds: ['acc3'] }).fetchTools())).toEqual(['acc3_tool_1']); + expect(names(await newToolSet({ execute: { accountIds: ['acc3'] } }).fetchTools())).toEqual([ + 'acc3_tool_1', + ]); + expect(names(await newToolSet({ accountId: 'acc3' }).fetchTools())).toEqual(['acc3_tool_1']); + }); - it('should set baseUrl from config', () => { - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - baseUrl: 'https://api.example.com', - }); + it('lets fetchTools override setAccounts without changing it', async () => { + const toolset = newToolSet().setAccounts(['acc1', 'acc2']); - // @ts-expect-error - Accessing private property for testing - expect(toolset.baseUrl).toBe('https://api.example.com'); - }); + expect(names(await toolset.fetchTools({ accountIds: ['acc3'] }))).toEqual(['acc3_tool_1']); + expect((await toolset.fetchTools()).length).toBe(4); }); - describe('authentication', () => { - it('should configure basic auth with API key from constructor', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); - - // @ts-expect-error - Accessing private property for testing - expect(toolset.authentication).toEqual({ - type: 'basic', - credentials: { - username: 'custom_key', - password: '', - }, - }); - }); + it('lets setAccounts override the constructor accounts', async () => { + const toolset = newToolSet({ accountIds: ['acc1'] }).setAccounts(['acc2', 'acc3']); + expect(names(await toolset.fetchTools())).toEqual([ + 'acc2_tool_1', + 'acc2_tool_2', + 'acc3_tool_1', + ]); + }); - it('should configure basic auth with API key from environment', () => { - const toolset = new StackOneToolSet(); + 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]); + } + }); - // @ts-expect-error - Accessing private property for testing - expect(toolset.authentication).toEqual({ - type: 'basic', - credentials: { - username: 'test_key', - password: '', - }, - }); - }); + it('keeps accounts apart when two fetchTools calls run concurrently', async () => { + const toolset = newToolSet(); + const [acc1, acc2] = await Promise.all([ + toolset.fetchTools({ accountIds: ['acc1'] }), + 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', + ]); + }); +}); - it('should throw ToolSetConfigError if no API key is provided and strict mode is enabled', () => { - vi.stubEnv('STACKONE_API_KEY', undefined); +/** + * An API key alone must work: /mcp requires an account, so the SDK finds one. The mock used to + * invent an account when the header was absent, so an SDK that never sent one still got a full + * catalog — these would all have passed against the SDK that shipped broken. + */ +describe('account discovery', () => { + it('lists the active accounts when none is configured', async () => { + const tools = await newToolSet().fetchTools(); - expect(() => { - new StackOneToolSet({ strict: true }); - }).toThrow(ToolSetConfigError); - }); + expect(names(tools)).toEqual(['default_tool_1', 'default_tool_2']); + expect(listMock.mock.calls.map(([request]) => accountOf(request))).toEqual(['default']); + }); - it('should not override custom headers with authentication', () => { - const customHeaders = { - 'Custom-Header': 'test-value', - Authorization: 'Bearer custom-token', - }; + it('exposes the linked accounts', async () => { + const accounts = await newToolSet().fetchAccounts(); - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - headers: customHeaders, - }); + expect(accounts.map((account) => account.id)).toEqual(['default', 'dead']); + expect(accounts.filter((account) => account.status === 'active').map((a) => a.id)).toEqual([ + 'default', + ]); + }); - // @ts-expect-error - Accessing private property for testing - expect(toolset.headers).toEqual(customHeaders); - }); + it('discovers once, until the cache is cleared', async () => { + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + requests += 1; + return HttpResponse.json([{ id: 'acc1', status: 'active' }]); + }), + ); + const toolset = newToolSet(); + + await toolset.fetchTools(); + await toolset.fetchTools({ providers: ['acc1'] }); + expect(requests).toBe(1); + + toolset.clearCatalogCache(); + await toolset.fetchTools(); + expect(requests).toBe(2); + }); - it('should combine authentication and account ID headers', () => { - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - accountId: 'test_account', - }); + it('accepts a { data: [...] } wrapper', async () => { + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json({ data: [{ id: 'acc3', status: 'active' }] }), + ), + ); + expect(names(await newToolSet().fetchTools())).toEqual(['acc3_tool_1']); + }); - const expectedAuthValue = `Basic ${Buffer.from('custom_key:').toString('base64')}`; - // @ts-expect-error - Accessing private property for testing - expect(toolset.headers.Authorization).toBe(expectedAuthValue); - // @ts-expect-error - Accessing private property for testing - expect(toolset.headers['x-account-id']).toBe('test_account'); - }); + it('explains a key with no linked accounts', async () => { + server.use(http.get(`${TEST_BASE_URL}/accounts`, () => HttpResponse.json([]))); + await expect(newToolSet().fetchTools()).rejects.toThrow( + new ToolSetConfigError( + 'This API key has no linked accounts. Link one in the StackOne dashboard, or pass accountId explicitly.', + ), + ); }); - describe('fetchTools (MCP integration)', () => { - it('creates tools from MCP catalog and wires RPC execution', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); + it('explains a key whose accounts are all inactive', async () => { + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json([{ id: 'x', provider: 'hibob', status: 'error' }]), + ), + ); + await expect(newToolSet().fetchTools()).rejects.toThrow( + /None of this API key's 1 linked accounts are active: hibob \(error\)/, + ); + }); - const tools = await toolset.fetchTools(); - // 1 dummy_action tool - expect(tools.length).toBe(1); + it('carries the status of a refused /accounts request', async () => { + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json({ message: 'bad key' }, { status: 401, statusText: 'Unauthorized' }), + ), + ); + const error = (await newToolSet() + .fetchAccounts() + .catch((caught: unknown) => caught)) as StackOneAPIError; + + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(401); + expect(error.message).toContain('401 Unauthorized: {"message":"bad key"}'); + }); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - expect(tool).toBeDefined(); - expect(tool?.name).toBe('dummy_action'); + it.each([ + [ + 'a non-list body', + HttpResponse.json({ results: [{ id: 'a' }] }), + /Unexpected \/accounts response shape: expected a list, got object/, + ], + [ + 'invalid JSON', + new HttpResponse('[{', { headers: { 'content-type': 'application/json' } }), + /Invalid JSON returned by/, + ], + [ + // `["\xff"]` is valid JSON only if the stray byte is silently replaced, so this + // fails unless the body is decoded strictly. + 'invalid UTF-8', + new HttpResponse(new Uint8Array([0x5b, 0x22, 0xff, 0x22, 0x5d])), + /Invalid JSON returned by/, + ], + ])('reports %s as a ToolSetLoadError', async (_name, response, message) => { + server.use(http.get(`${TEST_BASE_URL}/accounts`, () => response)); + const error = await newToolSet() + .fetchAccounts() + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolSetLoadError); + expect((error as Error).message).toMatch(message); + }); - const aiTools = await tool?.toAISDK({ executable: false }); - const aiToolDefinition = aiTools?.dummy_action; - expect(aiToolDefinition).toBeDefined(); - expect(aiToolDefinition?.description).toBe('Dummy tool'); - // @ts-expect-error - jsonSchema is available on Schema wrapper from ai sdk - expect(aiToolDefinition?.inputSchema.jsonSchema.properties).toBeDefined(); - expect(aiToolDefinition?.execution).toBeUndefined(); + it('reports an unreachable API as a ToolSetLoadError', async () => { + server.use(http.get(`${TEST_BASE_URL}/accounts`, () => HttpResponse.error())); + await expect(newToolSet().fetchAccounts()).rejects.toThrow( + new RegExp(`^Could not reach ${TEST_BASE_URL}/accounts`), + ); + }); +}); - const executableTool = (await tool?.toAISDK())?.dummy_action; - expect(executableTool?.execute).toBeDefined(); +/** The mock refuses what the real API refuses, so a bug here cannot stay green. */ +describe('server refusals', () => { + it('refuses an unscoped /mcp request (guards the mock itself)', async () => { + const response = await fetch(`${TEST_BASE_URL}/mcp`, { + method: 'POST', + headers: { Authorization: 'Basic dGVzdC1rZXk6', 'Content-Type': 'application/json' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }), }); + expect(response.status).toBe(400); + expect(await response.text()).toContain('x-account-id'); + }); - it('pins param-style=flat_prefixed on the MCP listing URL', async () => { - let requestedUrl = ''; - const mcpApp = createMcpApp({ accountTools: { default: defaultMcpTools } }); - server.use( - http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { - if (!requestedUrl) { - requestedUrl = request.url; - } - return mcpApp.fetch(request); - }), - ); - - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - await toolset.fetchTools(); + it('refuses an unknown account rather than serving a default catalog', async () => { + const error = (await newToolSet() + .fetchTools({ accountIds: ['no-such-account'] }) + .catch((caught: unknown) => caught)) as StackOneAPIError; - expect(requestedUrl).toBe(`${TEST_BASE_URL}/mcp?param-style=flat_prefixed`); - }); + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(404); }); - describe('account filtering', () => { - it('supports setAccounts() for chaining', () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); - - // Test chaining - const result = toolset.setAccounts(['acc1', 'acc2']); - expect(result).toBe(toolset); - }); + it('refuses execution without an account', async () => { + const tool = (await newToolSet().fetchTools({ accountIds: ['test-account'] })).getStackOneTool( + 'dummy_action', + ); + tool.setAccountId(undefined); - it('fetches tools without account filtering when no accountIds provided', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + const error = (await tool + .execute({ foo: 'bar' }) + .catch((caught: unknown) => caught)) as StackOneAPIError; + expect(error.statusCode).toBe(400); + }); +}); - const tools = await toolset.fetchTools(); - // 2 default tools - expect(tools.length).toBe(2); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('default_tool_1'); - expect(toolNames).toContain('default_tool_2'); - }); +describe('listing', () => { + it('pins param-style=flat_prefixed on the MCP listing URL', async () => { + fakeListing(() => []); + await newToolSet({ baseUrl: 'https://api.example.com/' }).fetchTools({ accountIds: ['acc1'] }); + expect(listMock.mock.calls[0]?.[0].endpoint).toBe( + 'https://api.example.com/mcp?param-style=flat_prefixed', + ); + }); - it('uses x-account-id header when fetching tools with accountIds', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + it('passes the timeout to every listing', async () => { + fakeListing(() => []); + await newToolSet({ timeout: 1234 }).fetchTools({ accountIds: ['a', 'b'] }); + expect(listMock.mock.calls.map(([request]) => request.timeout)).toEqual([1234, 1234]); + }); - // Fetch tools for acc1 - const tools = await toolset.fetchTools({ accountIds: ['acc1'] }); - // 2 acc1 tools - expect(tools.length).toBe(2); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('acc1_tool_1'); - expect(toolNames).toContain('acc1_tool_2'); + it('sends caller headers beneath the SDK-owned ones', async () => { + fakeListing(() => []); + await newToolSet({ headers: { 'X-Trace': 't', 'x-account-id': 'spoofed' } }).fetchTools({ + accountIds: ['acc1'], }); - - it('uses setAccounts when no accountIds provided in fetchTools', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); - - // Set accounts using setAccounts - toolset.setAccounts(['acc1', 'acc2']); - - // Fetch without accountIds - should use setAccounts - const tools = await toolset.fetchTools(); - - // Should fetch tools for 2 accounts from setAccounts - // acc1 has 2 tools, acc2 has 2 tools - expect(tools.length).toBe(4); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('acc1_tool_1'); - expect(toolNames).toContain('acc1_tool_2'); - expect(toolNames).toContain('acc2_tool_1'); - expect(toolNames).toContain('acc2_tool_2'); + expect(listMock.mock.calls[0]?.[0].headers).toMatchObject({ + 'X-Trace': 't', + 'x-account-id': 'acc1', }); + expect(listMock.mock.calls[0]?.[0].headers).not.toHaveProperty('X-Account-Id'); + }); - it('uses accountIds from constructor when no accountIds provided in fetchTools', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountIds: ['acc1', 'acc2'], - }); + it('builds each tool from its served definition', async () => { + const tool = (await newToolSet().fetchTools({ accountIds: ['test-account'] })).getTool( + 'dummy_action', + ); + expect(tool?.description).toBe('Dummy tool'); + expect(tool?.toJsonSchema()).toEqual(accountMcpTools['test-account'][0].inputSchema); + }); - // Fetch without accountIds - should use constructor accountIds - const tools = await toolset.fetchTools(); - - // Should fetch tools for 2 accounts from constructor - // acc1 has 2 tools, acc2 has 2 tools - expect(tools.length).toBe(4); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('acc1_tool_1'); - expect(toolNames).toContain('acc1_tool_2'); - expect(toolNames).toContain('acc2_tool_1'); - expect(toolNames).toContain('acc2_tool_2'); + it('runs accounts concurrently, bounded by the slowest', async () => { + fakeListing(async (request) => { + await new Promise((resolve) => setTimeout(resolve, 150)); + return [def(`tool_${accountOf(request)}`)]; }); - it('setAccounts overrides constructor accountIds', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountIds: ['acc1'], - }); - - // Override with setAccounts - toolset.setAccounts(['acc2', 'acc3']); + const started = performance.now(); + await newToolSet().fetchTools({ accountIds: ['a', 'b', 'c', 'd', 'e'] }); - // Fetch without accountIds - should use setAccounts, not constructor - const tools = await toolset.fetchTools(); + // Sequential would be 5 × 150ms; give CI generous headroom. + expect(performance.now() - started).toBeLessThan(450); + }); - // Should fetch tools for acc2 and acc3 (not acc1) - // acc2 has 2 tools, acc3 has 1 tool - expect(tools.length).toBe(3); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).not.toContain('acc1_tool_1'); - expect(toolNames).toContain('acc2_tool_1'); - expect(toolNames).toContain('acc2_tool_2'); - expect(toolNames).toContain('acc3_tool_1'); + it('keeps at most 10 listings in flight', async () => { + let inFlight = 0; + let peak = 0; + fakeListing(async (request) => { + inFlight += 1; + peak = Math.max(peak, inFlight); + await new Promise((resolve) => setTimeout(resolve, 20)); + inFlight -= 1; + return [def(`tool_${accountOf(request)}`)]; }); - it('overrides setAccounts when accountIds provided in fetchTools', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); - - // Set accounts using setAccounts - toolset.setAccounts(['acc1', 'acc2']); - - // Fetch with accountIds - should override setAccounts - const tools = await toolset.fetchTools({ accountIds: ['acc3'] }); - - // Should fetch tools only for acc3 (ignoring acc1, acc2) - expect(tools.length).toBe(1); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('acc3_tool_1'); + const tools = await newToolSet().fetchTools({ + accountIds: Array.from({ length: 25 }, (_, index) => `acc-${index}`), }); - // Regression for issue #365: tools must carry the x-account-id of the - // account they were fetched for, even when accounts are fetched - // concurrently. The prior implementation mutated this.headers around - // async boundaries, so concurrent fetches clobbered each other and - // tools were stamped with the wrong account. - it('stamps each tool with the x-account-id of its own account under intra-call concurrency', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + expect(tools.length).toBe(25); + expect(peak).toBe(10); + }); - const tools = await toolset.fetchTools({ accountIds: ['acc1', 'acc2', 'acc3'] }); + it('orders tools by account, whatever order listings complete in', async () => { + fakeListing(async (request) => { + const account = accountOf(request) ?? ''; + await new Promise((resolve) => setTimeout(resolve, account === 'a' ? 30 : 0)); + return [def(`tool_${account}`)]; + }); + expect(names(await newToolSet().fetchTools({ accountIds: ['c', 'a', 'b'] }))).toEqual([ + 'tool_a', + 'tool_b', + 'tool_c', + ]); + }); - for (const tool of tools.toArray()) { - if (tool.name.startsWith('acc1_')) { - expect(tool.getHeaders()['x-account-id']).toBe('acc1'); - } else if (tool.name.startsWith('acc2_')) { - expect(tool.getHeaders()['x-account-id']).toBe('acc2'); - } else if (tool.name.startsWith('acc3_')) { - expect(tool.getHeaders()['x-account-id']).toBe('acc3'); - } + it('keeps the healthy accounts when one fails, and says which failed', async () => { + fakeListing((request) => { + if (accountOf(request) === 'b') { + throw new Error('boom'); } + return [def(`tool_${accountOf(request)}`)]; }); - it('stamps tools correctly when two fetchTools calls run concurrently on the same instance', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); - - const [acc1Tools, acc2Tools] = await Promise.all([ - toolset.fetchTools({ accountIds: ['acc1'] }), - toolset.fetchTools({ accountIds: ['acc2'] }), - ]); + const tools = await newToolSet().fetchTools({ accountIds: ['a', 'b'] }); - for (const tool of acc1Tools.toArray()) { - if (tool.name.startsWith('acc')) { - expect(tool.getHeaders()['x-account-id']).toBe('acc1'); - } - } - for (const tool of acc2Tools.toArray()) { - if (tool.name.startsWith('acc')) { - expect(tool.getHeaders()['x-account-id']).toBe('acc2'); - } - } - }); + expect(names(tools)).toEqual(['tool_a']); + expect(String(warnSpy.mock.calls[0]?.[0])).toMatch( + /Skipping account that failed to list tools — b: boom/, + ); }); - describe('tool execution', () => { - it('should execute tool with dryRun option', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); - - expect(result.url).toBe(`${TEST_BASE_URL}/actions/rpc`); - expect(result.method).toBe('POST'); - expect(result.headers).toBeDefined(); - expect(result.body).toBeDefined(); - expect(result.mappedParams).toEqual({ body: { name: 'test' } }); - }); - - it('should execute tool with path, query, and headers params', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute( - { - body: { name: 'test' }, - path: { id: '123' }, - query: { limit: 10 }, - headers: { 'x-custom': 'value' }, - }, - { dryRun: true }, - ); - - expect(result.mappedParams).toEqual({ - body: { name: 'test' }, - path: { id: '123' }, - query: { limit: 10 }, - headers: { 'x-custom': 'value' }, - }); - }); - - it('should execute tool with string parameters', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute(JSON.stringify({ body: { name: 'test' } }), { - dryRun: true, - }); - - expect(result.mappedParams).toEqual({ body: { name: 'test' } }); + it('treats every account failing as a failure, not an empty catalog', async () => { + fakeListing((request) => { + throw new Error(`boom for ${accountOf(request)}`); }); + await expect(newToolSet().fetchTools({ accountIds: ['a', 'b'] })).rejects.toThrow( + 'No account returned tools. a: boom for a | b: boom for b', + ); + }); - it('should throw StackOneError for invalid parameter type', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - // @ts-expect-error - intentionally passing invalid type - await expect(tool.execute(12345)).rejects.toThrow('Invalid parameters type'); - }); - - it('should wrap non-StackOneError in execute', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - // Pass invalid JSON string to trigger JSON.parse error - await expect(tool.execute('not valid json')).rejects.toThrow('Error executing RPC action'); + it('does not cache a degraded listing', async () => { + let failB = true; + fakeListing((request) => { + if (accountOf(request) === 'b' && failB) { + throw new Error('boom'); + } + return [def(`tool_${accountOf(request)}`)]; }); + const toolset = newToolSet(); - it('should include extra params in rpcBody', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute( - { - body: { nested: 'value' }, - extraParam: 'extra-value', - anotherParam: 123, - }, - { dryRun: true }, - ); + expect((await toolset.fetchTools({ accountIds: ['a', 'b'] })).length).toBe(1); + failB = false; + expect((await toolset.fetchTools({ accountIds: ['a', 'b'] })).length).toBe(2); + }); - // The body should include both the nested body and extra params - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody.body).toEqual({ - nested: 'value', - extraParam: 'extra-value', - anotherParam: 123, - }); + it('passes an SDK error through without re-wrapping it', async () => { + fakeListing(() => { + throw new ToolSetConfigError('Original config error'); }); + await expect(newToolSet({ accountId: 'acc1' }).fetchTools()).rejects.toThrow( + new ToolSetConfigError('Original config error'), + ); + }); - it('routes flat_prefixed params into the RPC envelope', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); - - const result = await tool.execute( - { - path_id: '123', - query_limit: 10, - 'headers_x-custom': 'value', - body_name: 'test', - }, - { dryRun: true }, - ); - - const payload = JSON.parse(result.body as string); - expect(payload.path).toEqual({ id: '123' }); - expect(payload.query).toEqual({ limit: 10 }); - expect(payload.body).toEqual({ name: 'test' }); - // dummy_action declares no `headers_*` property, so the header is dropped. - expect(result.headers as Record).not.toHaveProperty('x-custom'); + it('wraps an unexpected error as a ToolSetLoadError', async () => { + fakeListing(() => [{ name: 'broken' } as ListedTool]); + listMock.mockImplementationOnce(() => { + throw new TypeError('unexpected'); }); + await expect(newToolSet({ accountId: 'acc1' }).fetchTools()).rejects.toThrow( + new ToolSetLoadError('Error fetching tools: unexpected'), + ); + }); +}); - it('preserves fields named after Object.prototype members', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); +describe('filtering', () => { + const mixed = () => newToolSet({ accountId: 'mixed' }); - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + it('filters by provider, case-insensitively', async () => { + expect(names(await mixed().fetchTools({ providers: ['HiBob', 'bamboohr'] }))).toEqual([ + 'hibob_list_employees', + 'hibob_create_employees', + 'bamboohr_list_employees', + 'bamboohr_get_employee', + ]); + }); - const result = await tool.execute( - { body_constructor: 'x', path_toString: 'y', query_valueOf: 'z' }, - { dryRun: true }, - ); + it('matches a provider as a full prefix, not the first token', async () => { + fakeListing(() => [def('browser_linkedin_search_people'), def('browser_open_page')]); + expect( + names( + await newToolSet({ accountId: 'acc1' }).fetchTools({ providers: ['browser_linkedin'] }), + ), + ).toEqual(['browser_linkedin_search_people']); + }); - const payload = JSON.parse(result.body as string); - expect(payload.body).toEqual({ constructor: 'x' }); - expect(payload.path).toEqual({ toString: 'y' }); - expect(payload.query).toEqual({ valueOf: 'z' }); - }); + it('filters by exact action name', async () => { + expect( + names( + await mixed().fetchTools({ actions: ['hibob_list_employees', 'hibob_create_employees'] }), + ), + ).toEqual(['hibob_list_employees', 'hibob_create_employees']); + }); - it('prefers an explicit flat key over a nested duplicate whatever the key order', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); + it.each([ + [ + ['*_list_employees'], + ['hibob_list_employees', 'bamboohr_list_employees', 'workday_list_employees'], + ], + [['hibob_*'], ['hibob_list_employees', 'hibob_create_employees']], + [['[hb]*_get_*'], ['bamboohr_get_employee']], + [['[!hb]*'], ['workday_list_employees']], + [['hibob_list_employee?'], ['hibob_list_employees']], + [['hibob.list*'], []], + ])('filters by glob %j', async (actions, expected) => { + expect(names(await mixed().fetchTools({ actions }))).toEqual(expected); + }); - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + it('combines accounts, providers and actions', async () => { + expect( + names(await newToolSet().fetchTools({ accountIds: ['acc1', 'acc2'], actions: ['*_tool_1'] })), + ).toEqual(['acc1_tool_1', 'acc2_tool_1']); + expect( + names(await mixed().fetchTools({ providers: ['hibob'], actions: ['*_list_*'] })), + ).toEqual(['hibob_list_employees']); + }); +}); - const nestedFirst = await tool.execute( - { path: { id: 'nested' }, path_id: 'flat' }, - { dryRun: true }, - ); - const flatFirst = await tool.execute( - { path_id: 'flat', path: { id: 'nested' } }, - { dryRun: true }, - ); +describe('catalog cache', () => { + const listingCount = () => listMock.mock.calls.length; - expect(JSON.parse(nestedFirst.body as string).path).toEqual({ id: 'flat' }); - expect(JSON.parse(flatFirst.body as string).path).toEqual({ id: 'flat' }); - }); + it('lists once for repeated calls', async () => { + const toolset = newToolSet({ accountId: 'acc1' }); + await toolset.fetchTools(); + await toolset.fetchTools(); + await toolset.fetchTools(); + expect(listingCount()).toBe(1); + }); - it('drops reserved envelope keys that do not carry an object', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); + it('keys on the account scope, not its order', async () => { + const toolset = newToolSet(); + await toolset.fetchTools({ accountIds: ['acc1'] }); + await toolset.fetchTools({ accountIds: ['acc2'] }); + await toolset.fetchTools({ accountIds: ['acc1'] }); + expect(listingCount()).toBe(2); - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + await toolset.fetchTools({ accountIds: ['acc1', 'acc2'] }); + await toolset.fetchTools({ accountIds: ['acc2', 'acc1', 'acc2'] }); + expect(listingCount()).toBe(4); + }); - const result = await tool.execute( - { body: 'oops', path: 5, real_field: 'kept' }, - { dryRun: true }, - ); + it('filters one cached listing without refetching', async () => { + const toolset = newToolSet({ accountId: 'mixed' }); + await toolset.fetchTools(); + await toolset.fetchTools({ providers: ['hibob'] }); + await toolset.fetchTools({ actions: ['*_list_*'] }); + expect(listingCount()).toBe(1); + }); - // `body`/`path` name an envelope, so a non-object value is dropped rather than - // leaked into the body payload under its reserved name. - const payload = JSON.parse(result.body as string); - expect(payload.body).toEqual({ real_field: 'kept' }); - expect(payload.path).toBeUndefined(); - }); + it('keys on the tool mode', async () => { + const toolset = newToolSet({ accountId: 'acc1' }); + await toolset.fetchTools(); + await toolset.fetchTools({ mode: 'search_execute' }); + await toolset.fetchTools({ mode: 'search_execute' }); + expect(listingCount()).toBe(2); }); - describe('model-supplied headers', () => { - const serveTool = (inputSchema: McpToolDefinition['inputSchema']) => { - const app = createMcpApp({ - accountTools: { - 'tenant-a': [{ name: 'crm_list_contacts', description: 'List contacts', inputSchema }], - }, - }); - server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); - }; - const captureRpc = () => { - const seen: { accountHeader: string | null; body: Record }[] = []; - server.use( - http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { - seen.push({ - accountHeader: request.headers.get('x-account-id'), - body: (await request.json()) as Record, - }); - return HttpResponse.json({ data: {} }); - }), - ); - return seen; - }; - const fetchTool = async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'tenant-a', - }); - const tool = (await toolset.fetchTools()).getTool('crm_list_contacts'); - assert(tool, 'tool should be listed'); - return tool; - }; - - // Regression: the envelope headers were merged OVER the tool's own headers, so a - // model-supplied x-account-id replaced the account the tool was fetched for — on the - // envelope and on the HTTP header the API actually reads. - it('cannot switch tenant with headers_x-account-id, even when the schema declares it', async () => { - serveTool({ - type: 'object', - properties: { 'headers_x-account-id': { type: 'string' }, query_limit: { type: 'number' } }, - }); - const seen = captureRpc(); - const tool = await fetchTool(); + it('is invalidated by clearCatalogCache and setAccounts', async () => { + const toolset = newToolSet({ accountIds: ['acc1'] }); + await toolset.fetchTools(); + toolset.clearCatalogCache(); + await toolset.fetchTools(); + expect(listingCount()).toBe(2); - await tool.execute({ 'headers_x-account-id': 'tenant-b', query_limit: 1 }); + toolset.setAccounts(['acc1']); + await toolset.fetchTools(); + expect(listingCount()).toBe(3); + }); - expect(seen[0]?.accountHeader).toBe('tenant-a'); - expect((seen[0]?.body.headers as Record)['x-account-id']).toBe('tenant-a'); + // A listing already in flight must not land after the clear that cancelled it — otherwise + // the stale catalog is written back and served for the life of the process. + it('is not repopulated by a listing that was in flight when it was cleared', async () => { + const toolset = newToolSet({ accountId: 'acc1' }); + fakeListing(() => { + toolset.clearCatalogCache(); + return [def('stale_tool')]; }); - it('cannot switch tenant with a nested headers object', async () => { - serveTool({ type: 'object', properties: { query_limit: { type: 'number' } } }); - const seen = captureRpc(); - const tool = await fetchTool(); - - await tool.execute({ headers: { 'X-Account-Id': 'tenant-b', Authorization: 'Bearer stolen' } }); + await toolset.fetchTools(); + fakeListing(() => [def('fresh_tool')]); - expect(seen[0]?.accountHeader).toBe('tenant-a'); - expect(seen[0]?.body.headers).toEqual({ 'x-account-id': 'tenant-a' }); - }); + expect(names(await toolset.fetchTools())).toEqual(['fresh_tool']); + }); - it('forwards a header the served schema declares', async () => { - serveTool({ type: 'object', properties: { 'headers_x-trace': { type: 'string' } } }); - const seen = captureRpc(); - const tool = await fetchTool(); + it('hands every caller fresh tools, so rebinding one never rescopes another', async () => { + const toolset = newToolSet({ accountId: 'acc1' }); + const first = (await toolset.fetchTools()).getStackOneTool('acc1_tool_1'); + first.setAccountId('someone-else'); - await tool.execute({ 'headers_x-trace': 'abc', 'headers_x-other': 'dropped' }); + const second = (await toolset.fetchTools()).getStackOneTool('acc1_tool_1'); - expect(seen[0]?.body.headers).toEqual({ 'x-trace': 'abc', 'x-account-id': 'tenant-a' }); - }); + expect(second).not.toBe(first); + expect(second.getAccountId()).toBe('acc1'); }); - describe('provider and action filtering', () => { - it('filters tools by providers', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - }); - - // Filter by providers - const tools = await toolset.fetchTools({ providers: ['hibob', 'bamboohr'] }); - - // 4 filtered tools - expect(tools.length).toBe(4); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('hibob_list_employees'); - expect(toolNames).toContain('hibob_create_employees'); - expect(toolNames).toContain('bamboohr_list_employees'); - expect(toolNames).toContain('bamboohr_get_employee'); - expect(toolNames).not.toContain('workday_list_employees'); - }); + it('does not share nested schema between callers', async () => { + fakeListing(() => [def('t', { properties: { body_x: { type: 'object', properties: {} } } })]); + const toolset = newToolSet({ accountId: 'acc1' }); - it('filters tools by actions with exact match', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - }); + const first = (await toolset.fetchTools()).getTool('t'); + const nested = first?.parameters.properties.body_x?.properties; + assert(nested); + (nested as Record).injected = { type: 'string' }; - // Filter by exact action names - const tools = await toolset.fetchTools({ - actions: ['hibob_list_employees', 'hibob_create_employees'], - }); + const second = (await toolset.fetchTools()).getTool('t'); + expect(second?.parameters.properties.body_x?.properties).toEqual({}); + }); +}); - // 2 filtered tools - expect(tools.length).toBe(2); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('hibob_list_employees'); - expect(toolNames).toContain('hibob_create_employees'); - }); +describe('tool mode', () => { + it('builds RPC tools by default', async () => { + fakeListing(() => [def('t')]); + expect((await newToolSet({ accountId: 'acc1' }).fetchTools()).getTool('t')).toBeInstanceOf( + StackOneRpcTool, + ); + }); - it('filters tools by actions with glob pattern', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - }); + it('builds MCP tools under search_execute, and requests it on the URL', async () => { + fakeListing(() => [def('t')]); + const tools = await newToolSet({ accountId: 'acc1', toolMode: 'search_execute' }).fetchTools(); - // Filter by glob pattern - const tools = await toolset.fetchTools({ actions: ['*_list_employees'] }); - - // 3 filtered tools - expect(tools.length).toBe(3); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('hibob_list_employees'); - expect(toolNames).toContain('bamboohr_list_employees'); - expect(toolNames).toContain('workday_list_employees'); - expect(toolNames).not.toContain('hibob_create_employees'); - expect(toolNames).not.toContain('bamboohr_get_employee'); - }); + expect(tools.getTool('t')).toBeInstanceOf(StackOneMcpTool); + expect(listMock.mock.calls[0]?.[0].endpoint).toBe( + `${TEST_BASE_URL}/mcp?param-style=flat_prefixed&tool-mode=search_execute`, + ); + }); - it('combines accountIds and actions filters', async () => { - const acc1Tools: McpToolDefinition[] = [ - { - name: 'hibob_list_employees', - description: 'HiBob List Employees', - inputSchema: { - type: 'object', - properties: { fields: { type: 'string' } }, - }, - }, - { - name: 'hibob_create_employees', - description: 'HiBob Create Employees', - inputSchema: { - type: 'object', - properties: { name: { type: 'string' } }, - required: ['name'], - }, - }, - ]; - - const acc2Tools: McpToolDefinition[] = [ - { - name: 'bamboohr_list_employees', - description: 'BambooHR List Employees', - inputSchema: { - type: 'object', - properties: { fields: { type: 'string' } }, - }, - }, - { - name: 'bamboohr_get_employee', - description: 'BambooHR Get Employee', - inputSchema: { - type: 'object', - properties: { id: { type: 'string' } }, - required: ['id'], - }, - }, - ]; + it('lets fetchTools override the configured mode, null meaning the server default', async () => { + fakeListing(() => [def('t')]); + const toolset = newToolSet({ accountId: 'acc1', toolMode: 'search_execute' }); + + expect((await toolset.fetchTools({ mode: null })).getTool('t')).toBeInstanceOf(StackOneRpcTool); + expect((await toolset.fetchTools({ mode: 'individual' })).getTool('t')).toBeInstanceOf( + StackOneRpcTool, + ); + expect(listMock.mock.calls.map(([request]) => request.endpoint.split('?')[1])).toEqual([ + 'param-style=flat_prefixed', + 'param-style=flat_prefixed&tool-mode=individual', + ]); + }); +}); - // Override the handler for this specific test - const testMcpApp = createMcpApp({ - accountTools: { - acc1: acc1Tools, - acc2: acc2Tools, - }, - }); - server.use( - http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { - return testMcpApp.fetch(request); - }), - ); +describe('duplicate tool names', () => { + it('warns when two accounts serve the same name', async () => { + fakeListing(() => [def('hibob_list_employees'), def('hibob_get_employee')]); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + const tools = await newToolSet().fetchTools({ accountIds: ['a', 'b'] }); - // Combine account and action filters - const tools = await toolset.fetchTools({ - accountIds: ['acc1', 'acc2'], - actions: ['*_list_employees'], - }); + expect(tools.length).toBe(4); + expect((tools.getTool('hibob_list_employees') as StackOneTool).getAccountId()).toBe('a'); + expect(String(warnSpy.mock.calls[0]?.[0])).toContain( + '2 tool name(s) are served by more than one account (hibob_get_employee, hibob_list_employees)', + ); + }); - // 2 filtered tools - expect(tools.length).toBe(2); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('hibob_list_employees'); - expect(toolNames).toContain('bamboohr_list_employees'); - expect(toolNames).not.toContain('hibob_create_employees'); - expect(toolNames).not.toContain('bamboohr_get_employee'); - }); + it('stays quiet when names are unique', async () => { + await newToolSet().fetchTools({ accountIds: ['acc1', 'acc2'] }); + expect(warnSpy).not.toHaveBeenCalled(); + }); +}); - it('combines all filters: accountIds, providers, and actions', async () => { - const acc1Tools: McpToolDefinition[] = [ - { - name: 'hibob_list_employees', - description: 'HiBob List Employees', - inputSchema: { - type: 'object', - properties: { fields: { type: 'string' } }, - }, - }, - { - name: 'hibob_create_employees', - description: 'HiBob Create Employees', - inputSchema: { - type: 'object', - properties: { name: { type: 'string' } }, - required: ['name'], - }, - }, - { - name: 'workday_list_employees', - description: 'Workday List Employees', - inputSchema: { - type: 'object', - properties: { fields: { type: 'string' } }, - }, - }, - ]; +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); + return HttpResponse.json({ data: {} }); + }), + ); + return rpcRequests; + }; + + it('appears once however many accounts list it, without a duplicate warning', async () => { + serveFeedback(true); + + const tools = await newToolSet({ accountIds: ['acc1', 'acc2'] }).fetchTools(); + + expect(names(tools).filter((name) => name === 'stackone_submit_feedback')).toHaveLength(1); + expect(warnSpy).not.toHaveBeenCalled(); + }); - // Override the handler for this specific test - const testMcpApp = createMcpApp({ - accountTools: { - acc1: acc1Tools, - }, - }); - server.use( - http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { - return testMcpApp.fetch(request); - }), + it.each([undefined, 'search_execute'] as const)( + 'is an MCP tool executed over tools/call in %s mode, never RPC', + async (toolMode) => { + const rpcRequests = serveFeedback(true); + const tool = (await newToolSet({ accountId: 'acc1', toolMode }).fetchTools()).getTool( + 'stackone_submit_feedback', ); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); - - // Combine all filters - const tools = await toolset.fetchTools({ - accountIds: ['acc1'], - providers: ['hibob'], - actions: ['*_list_*'], - }); + expect(tool).toBeInstanceOf(StackOneMcpTool); + expect( + await tool?.execute({ rating: 'positive', tool_names: ['acc1_tool_1'] }), + ).toMatchObject({ + message: 'Feedback recorded', + }); + expect(rpcRequests).toEqual([]); + }, + ); + + it('is absent when the server does not serve it — the SDK never invents one', async () => { + serveFeedback(false); + const tools = await newToolSet({ accountId: 'acc1' }).fetchTools(); + expect(tools.getTool('stackone_submit_feedback')).toBeUndefined(); + expect(tools.getTool('tool_feedback')).toBeUndefined(); + }); +}); - // Should only return hibob_list_employees (matches all filters) - expect(tools.length).toBe(1); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('hibob_list_employees'); - }); +describe('execution through fetched tools', () => { + it('executes an RPC tool against its account', async () => { + const tools = await newToolSet({ accountId: 'your-bamboohr-account-id' }).fetchTools(); + const result = await tools.getTool('bamboohr_get_employee')?.execute({ id: 'emp-123' }); + expect(result).toMatchObject({ data: { id: 'emp-123', name: 'Test Employee' } }); }); +}); - describe('catalog cache', () => { - const installMcpSpy = ( - accountTools: Record = { - acc1: [ - { - name: 'acc1_tool_1', - description: 'acc1 tool 1', - inputSchema: { type: 'object', properties: {} }, - }, - ], - acc2: [ - { - name: 'acc2_tool_1', - description: 'acc2 tool 1', - inputSchema: { type: 'object', properties: {} }, - }, - ], +describe('model-supplied headers', () => { + const serveTool = (inputSchema: McpToolDefinition['inputSchema']) => { + const app = createMcpApp({ + accountTools: { + 'tenant-a': [{ name: 'crm_list_contacts', description: 'List contacts', inputSchema }], }, - ) => { - const testMcpApp = createMcpApp({ accountTools }); - const counter = { count: 0 }; - server.use( - http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { - counter.count += 1; - return testMcpApp.fetch(request); - }), - ); - return counter; - }; - - it('memoizes fetchTools results across repeat calls', async () => { - const counter = installMcpSpy(); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); - - await toolset.fetchTools({ accountIds: ['acc1'] }); - const afterFirst = counter.count; - expect(afterFirst).toBeGreaterThan(0); - - await toolset.fetchTools({ accountIds: ['acc1'] }); - await toolset.fetchTools({ accountIds: ['acc1'] }); - expect(counter.count).toBe(afterFirst); }); + server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); + }; + const captureRpc = () => { + const seen: { accountHeader: string | null; body: Record }[] = []; + server.use( + http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { + seen.push({ + accountHeader: request.headers.get('x-account-id'), + body: (await request.json()) as Record, + }); + return HttpResponse.json({ data: {} }); + }), + ); + return seen; + }; + const fetchTool = async () => { + const tool = (await newToolSet({ accountId: 'tenant-a' }).fetchTools()).getTool( + 'crm_list_contacts', + ); + assert(tool, 'tool should be listed'); + return tool; + }; + + // Regression: the envelope headers were merged OVER the tool's own headers, so a + // model-supplied x-account-id replaced the account the tool was fetched for — on the + // envelope and on the HTTP header the API actually reads. + it('cannot switch tenant with headers_x-account-id, even when the schema declares it', async () => { + serveTool({ + type: 'object', + properties: { 'headers_x-account-id': { type: 'string' }, query_limit: { type: 'number' } }, + }); + const seen = captureRpc(); + const tool = await fetchTool(); + + await tool.execute({ 'headers_x-account-id': 'tenant-b', query_limit: 1 }); + + expect(seen[0]?.accountHeader).toBe('tenant-a'); + expect(seen[0]?.body.headers).toMatchObject({ 'x-account-id': 'tenant-a' }); + }); - it('uses separate cache entries for different account sets', async () => { - const counter = installMcpSpy(); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + it('cannot switch tenant with a nested headers object', async () => { + serveTool({ type: 'object', properties: { query_limit: { type: 'number' } } }); + const seen = captureRpc(); + const tool = await fetchTool(); - await toolset.fetchTools({ accountIds: ['acc1'] }); - const afterAcc1 = counter.count; + await tool.execute({ headers: { 'X-Account-Id': 'tenant-b', Authorization: 'Bearer stolen' } }); - await toolset.fetchTools({ accountIds: ['acc1'] }); - expect(counter.count).toBe(afterAcc1); + expect(seen[0]?.accountHeader).toBe('tenant-a'); + expect(seen[0]?.body.headers).toEqual({ 'x-account-id': 'tenant-a' }); + }); - await toolset.fetchTools({ accountIds: ['acc2'] }); - expect(counter.count).toBeGreaterThan(afterAcc1); - const afterAcc2 = counter.count; + it('forwards a header the served schema declares', async () => { + serveTool({ type: 'object', properties: { 'headers_x-trace': { type: 'string' } } }); + const seen = captureRpc(); + const tool = await fetchTool(); - await toolset.fetchTools({ accountIds: ['acc1'] }); - expect(counter.count).toBe(afterAcc2); - }); + await tool.execute({ 'headers_x-trace': 'abc', 'headers_x-other': 'dropped' }); - it('account-id ordering does not affect cache hits', async () => { - const counter = installMcpSpy(); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + expect(seen[0]?.body.headers).toEqual({ 'x-trace': 'abc', 'x-account-id': 'tenant-a' }); + }); +}); - await toolset.fetchTools({ accountIds: ['acc1', 'acc2'] }); - const afterFirst = counter.count; - expect(afterFirst).toBeGreaterThan(0); +describe('openai()', () => { + it('returns the catalog in OpenAI function format', async () => { + const tools = await newToolSet({ accountId: 'test-account' }).openai(); + + expect(tools).toEqual([ + { + type: 'function', + function: { + name: 'dummy_action', + description: 'Dummy tool', + parameters: accountMcpTools['test-account'][0].inputSchema, + }, + }, + ]); + }); - // Reordered list should hit the cache — no new MCP traffic. - await toolset.fetchTools({ accountIds: ['acc2', 'acc1'] }); - expect(counter.count).toBe(afterFirst); - }); + it('scopes to the given accounts', async () => { + const tools = await newToolSet({ accountId: 'test-account' }).openai({ accountIds: ['acc3'] }); + expect(tools.map((tool) => tool.function.name)).toEqual(['acc3_tool_1']); + }); +}); - it('clearCatalogCache forces a refetch', async () => { - const counter = installMcpSpy(); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); +describe('timeouts', () => { + let silent: NetServer; + const sockets: Socket[] = []; + let port = 0; - await toolset.fetchTools({ accountIds: ['acc1'] }); - const afterFirst = counter.count; + 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; + }); + afterAll(async () => { + for (const socket of sockets) { + socket.destroy(); + } + await new Promise((resolve) => silent.close(resolve)); + }); - toolset.clearCatalogCache(); - await toolset.fetchTools({ accountIds: ['acc1'] }); - expect(counter.count).toBeGreaterThan(afterFirst); + it('bounds a listing against a host that never answers', async () => { + const toolset = new StackOneToolSet({ + apiKey: 'k', + accountId: 'a', + baseUrl: `http://127.0.0.1:${port}`, + timeout: 300, }); + const started = Date.now(); + const error = await toolset.fetchTools().catch((caught: unknown) => caught); - it('setAccounts invalidates the cache', async () => { - const counter = installMcpSpy(); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountIds: ['acc1'], - }); - - await toolset.fetchTools(); - await toolset.fetchTools(); - const afterAcc1 = counter.count; + expect(error).toBeInstanceOf(ToolSetLoadError); + expect(Date.now() - started).toBeLessThan(5_000); + }); - toolset.setAccounts(['acc2']); - await toolset.fetchTools(); - expect(counter.count).toBeGreaterThan(afterAcc1); + it('bounds account discovery too', async () => { + const toolset = new StackOneToolSet({ + apiKey: 'k', + baseUrl: `http://127.0.0.1:${port}`, + timeout: 300, }); + await expect(toolset.fetchAccounts()).rejects.toThrow(ToolSetLoadError); + }); - it('reuses the same Tools instance on cache hit (identity)', async () => { - installMcpSpy(); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); - - const first = await toolset.fetchTools({ accountIds: ['acc1'] }); - const second = await toolset.fetchTools({ accountIds: ['acc1'] }); - - // Identity reuse means the toolIndex cache's reference-equality check - // in localSearch can hit across search calls. - expect(second).toBe(first); - }); + it('uses execute.timeout when no top-level timeout is given', async () => { + fakeListing(() => []); + await newToolSet({ accountId: 'acc1', execute: { timeout: 42 } }).fetchTools(); + expect(listMock.mock.calls[0]?.[0].timeout).toBe(42); }); }); + +it('is caught by `instanceof StackOneError`, whatever goes wrong', async () => { + vi.stubEnv('STACKONE_API_KEY', ''); + expect(() => new StackOneToolSet()).toThrow(StackOneError); + await expect(newToolSet().fetchTools({ accountIds: ['no-such-account'] })).rejects.toThrow( + StackOneError, + ); +}); diff --git a/src/toolsets.ts b/src/toolsets.ts index 5f39b1b2..36ed368f 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -1,93 +1,22 @@ import type { MergeExclusive, SimplifyDeep } from 'type-fest'; -import { DEFAULT_BASE_URL } from './consts'; import { - type StackOneHeaders, - declaredHeaderNames, - sanitiseHeaders, - stackOneHeadersSchema, -} from './headers'; -import { createMCPClient } from './mcp-client'; -import { type RpcActionResponse, RpcClient } from './rpc-client'; -import { BaseTool, Tools } from './tool'; -import type { - ExecuteOptions, - JsonObject, - JsonSchemaProperties, - RpcExecuteConfig, - ToolParameters, -} from './types'; -import type { BinaryDownloadResult } from './utils/binary-response'; + DEFAULT_BASE_URL, + DEFAULT_TIMEOUT_MS, + MAX_CONCURRENCY, + MCP_PARAM_STYLE, + SUBMIT_FEEDBACK_TOOL_NAME, +} from './consts'; +import { buildRequestHeaders, isSdkOwnedHeader } from './headers'; +import { type McpToolDefinition, listMcpTools } from './mcp-client'; +import { RpcClient } from './rpc-client'; +import { cloneJson, toolParametersFromInputSchema } from './schema'; +import { StackOneMcpTool, StackOneRpcTool, type StackOneTool, Tools } from './tool'; +import type { StackOneAccount, ToolMode } from './types'; +import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; -import { ToolSetConfigError, ToolSetError } from './utils/error-toolset'; - -/** - * Param-style pinned on the /mcp tool-listing URL. The MCP schema and the RPC-execution - * unwrap (splitEnvelopeParams) must agree on this, so it is pinned rather than following - * the server default — the server default is free to change without breaking the SDK. - */ -const MCP_PARAM_STYLE = 'flat_prefixed'; - -/** Matches a flat_prefixed envelope key: `_` (e.g. `path_id`, `query_limit`). */ -const FLAT_ENVELOPE_KEY_PATTERN = /^(path|query|body|headers)_(.+)$/; - -const ENVELOPE_LOCATIONS = ['path', 'query', 'headers', 'body'] as const; - -type EnvelopeLocation = (typeof ENVELOPE_LOCATIONS)[number]; - -const isEnvelopeLocation = (key: string): key is EnvelopeLocation => - (ENVELOPE_LOCATIONS as readonly string[]).includes(key); - -const isPlainObject = (value: unknown): value is Record => - typeof value === 'object' && value !== null && !Array.isArray(value); - -/** - * Converts an RPC action result to a JsonObject by flattening its top-level properties. - * - * RpcActionResponse uses z.passthrough() which preserves additional fields, making it - * structurally compatible with Record. A BinaryDownloadResult (file - * download) is flattened the same way - its `content` Buffer rides through under the value - * cast, so it is not a `JsonValue` (and JSON-stringifies to an unwieldy byte array); callers - * re-serializing for an LLM must handle that key. - */ -function rpcResponseToJsonObject(response: RpcActionResponse | BinaryDownloadResult): JsonObject { - // RpcActionResponse with passthrough() has the shape: - // { next?: string | null, data?: ..., [key: string]: unknown } - // We extract all properties into a plain object - const result: JsonObject = {}; - for (const [key, value] of Object.entries(response)) { - result[key] = value as JsonObject[string]; - } - return result; -} - -type ToolInputSchema = Awaited< - ReturnType>['client']['listTools']> ->['tools'][number]['inputSchema']; - -/** - * Authentication configuration for toolsets - */ -export interface AuthenticationConfig { - type: 'basic' | 'bearer'; - credentials?: { - username?: string; - password?: string; - token?: string; - }; - headers?: Record; -} - -/** - * Base configuration for all toolsets - */ -export interface BaseToolSetConfig { - baseUrl?: string; - authentication?: AuthenticationConfig; - headers?: Record; - rpcClient?: RpcClient; - /** Request timeout in milliseconds. Default: 60000 (60s). */ - timeout?: number; -} +import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; +import { settleWithConcurrency } from './utils/concurrency'; +import { warn } from './utils/logger'; /** * Configuration with a single account ID @@ -131,14 +60,32 @@ export interface ExecuteToolsConfig { /** * Base configuration for StackOne toolset (without account options) */ -interface StackOneToolSetBaseConfig extends BaseToolSetConfig { +interface StackOneToolSetBaseConfig { + /** API key. Defaults to the `STACKONE_API_KEY` environment variable. */ apiKey?: string; - strict?: boolean; + /** Defaults to `STACKONE_BASE_URL`, then `https://api.stackone.com`. */ + baseUrl?: string; + /** + * Extra HTTP headers sent with every request. `Authorization`, `x-account-id` and + * `User-Agent` are always the SDK's own and cannot be set here. + */ + headers?: Record; + /** + * Request timeout in milliseconds, applied to every MCP call (listing and `tools/call`), to + * RPC execution and to account discovery. Default: 60000 (60s). + */ + timeout?: number; /** * Execution configuration. Controls default account scoping for tool execution. * Pass `{ accountIds: ['acc-1'] }` to scope tools to specific accounts. */ execute?: ExecuteToolsConfig; + /** + * How the endpoint lists tools. `'search_execute'` returns two meta tools per connector + * instead of one tool per action, keeping the catalog small enough for a model's context. + * Defaults to the server's own default (`'individual'`). + */ + toolMode?: ToolMode; } /** @@ -150,16 +97,16 @@ export type StackOneToolSetConfig = StackOneToolSetBaseConfig & Partial + error instanceof Error ? error.message : String(error); + +/** + * Whether a tool belongs to one of the given providers (case-insensitive). + * + * Matched as a full prefix rather than on the first underscore-separated token: splitting on + * "_" reads `browser_linkedin_search_people` as provider `browser`, so asking for + * `browser_linkedin` returned nothing at all — silently, since an empty result is + * indistinguishable from a provider with no tools. + */ +function matchesProvider(toolName: string, providers: readonly string[]): boolean { + const lowered = toolName.toLowerCase(); + return providers.some((provider) => lowered.startsWith(`${provider.toLowerCase()}_`)); } /** - * Class for loading StackOne tools via MCP + * Whether a tool name matches a glob pattern, with the semantics of Python's `fnmatch`: `*` any + * run, `?` one character, `[seq]` / `[!seq]` a character class. Everything else is literal. + */ +function matchGlob(value: string, pattern: string): boolean { + let source = ''; + for (let index = 0; index < pattern.length; index++) { + const char = pattern[index] as string; + 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); + 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}]`; + index = end; + } + } else { + source += char.replace(/[.+^${}()|[\]\\/]/g, '\\$&'); + } + } + return new RegExp(`^${source}$`, 's').test(value); +} + +const assertAccountIdList = (accountIds: unknown, parameter: string): void => { + if (accountIds === undefined) { + return; + } + if (typeof accountIds === 'string') { + throw new ToolSetConfigError( + `${parameter} must be an array of account ids, not a string. Did you mean ["${accountIds}"]?`, + ); + } + if (!Array.isArray(accountIds) || accountIds.some((id) => typeof id !== 'string')) { + throw new ToolSetConfigError(`${parameter} must be an array of account id strings`); + } +}; + +/** + * The StackOne toolset: lists the served tool catalog and exposes it to agent frameworks. + * + * A thin client over the catalog. Tools are listed from the MCP endpoint, per account, and + * executed against the actions RPC endpoint (or over MCP `tools/call` for the tools that have no + * action behind them). Schemas are passed through as served, never rewritten, filtered or + * invented. + * + * An API key is enough: with no account configured, the toolset lists every active account + * linked to the key. */ export class StackOneToolSet { - private baseUrl?: string; - private authentication?: AuthenticationConfig; - private headers: Record; - private rpcClient?: RpcClient; - private readonly timeout: number; - private readonly executeConfig: ExecuteToolsConfig | undefined; + readonly #apiKey: string; + readonly #baseUrl: string; + readonly #headers: Record; + readonly #timeout: number; + readonly #toolMode: ToolMode | undefined; + readonly #accountId: string | undefined; + #accountIds: string[]; + readonly #rpcClient: RpcClient; /** - * Account ID for StackOne API + * The listing per account scope, not the Tools built from it. Tools are mutable + * (`setAccountId` rebinds one), so handing the same instances back on a cache hit let one + * caller silently rescope every later caller's tools. */ - private accountId?: string; - private accountIds: string[] = []; + readonly #catalogCache = new Map(); + #discoveredAccountIds: string[] | undefined; + /** + * Bumped by {@link clearCatalogCache}. A listing already in flight when the cache is cleared + * captured the generation it started under, and refuses to write back if it has moved — + * otherwise the stale catalog would land after the clear and be served for the life of the + * process, which is the one thing the clear exists to prevent. + */ + #cacheGeneration = 0; /** - * Initialize StackOne toolset with API key and optional account ID(s) - * @param config Configuration object containing API key and optional account ID(s) + * @throws ToolSetConfigError If no API key is given or found in `STACKONE_API_KEY`, or both + * `accountId` and `accountIds` are given. */ - constructor(config?: StackOneToolSetConfig) { - // Validate mutually exclusive account options - if (config?.accountId != null && config?.accountIds != null) { + 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.', ); } + assertAccountIdList(config.accountIds, 'accountIds'); + assertAccountIdList(config.execute?.accountIds, 'execute.accountIds'); - const apiKey = config?.apiKey || process.env.STACKONE_API_KEY; - - if (!apiKey && config?.strict) { + const apiKey = config.apiKey || process.env.STACKONE_API_KEY; + if (!apiKey) { throw new ToolSetConfigError( - 'No API key provided. Set STACKONE_API_KEY environment variable or pass apiKey in config.', + 'API key must be provided either through the apiKey option or the STACKONE_API_KEY environment variable', ); } - if (!apiKey) { - console.warn( - 'No API key provided. Set STACKONE_API_KEY environment variable or pass apiKey in config.', + 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. Use the apiKey and accountId options instead.`, ); } - const authentication: AuthenticationConfig = { - type: 'basic', - credentials: { - username: apiKey || '', - password: '', - }, - }; - - const accountId = config?.accountId || process.env.STACKONE_ACCOUNT_ID; - - const configHeaders = { - ...config?.headers, - ...(accountId ? { 'x-account-id': accountId } : {}), - }; - - // Initialize base properties - this.baseUrl = config?.baseUrl ?? process.env.STACKONE_BASE_URL ?? DEFAULT_BASE_URL; - this.authentication = authentication; - this.headers = configHeaders; - this.rpcClient = config?.rpcClient; - this.timeout = config?.timeout ?? config?.execute?.timeout ?? 60_000; - this.accountId = accountId; - this.accountIds = config?.accountIds ?? []; - - // Resolve search config: undefined/null → disabled, object → custom with defaults - this.executeConfig = config?.execute; - - - // Set Authentication headers if provided - if (this.authentication) { - // Only set auth headers if they don't already exist in custom headers - const needsAuthHeader = !('Authorization' in this.headers); - - if (needsAuthHeader) { - switch (this.authentication.type) { - case 'basic': - if (this.authentication.credentials?.username) { - const username = this.authentication.credentials.username; - const password = this.authentication.credentials.password || ''; - const authString = Buffer.from(`${username}:${password}`).toString('base64'); - this.headers.Authorization = `Basic ${authString}`; - } - break; - case 'bearer': - if (this.authentication.credentials?.token) { - this.headers.Authorization = `Bearer ${this.authentication.credentials.token}`; - } - break; - - default: - this.authentication.type satisfies never; - throw new ToolSetError( - `Unsupported authentication type: ${String(this.authentication.type)}`, - ); - } - } - - // Add any additional headers from authentication config, but don't override existing ones - if (this.authentication.headers) { - this.headers = { ...this.authentication.headers, ...this.headers }; - } - } + this.#apiKey = apiKey; + this.#baseUrl = 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.#toolMode = config.toolMode; + this.#accountId = config.accountId || process.env.STACKONE_ACCOUNT_ID || undefined; + this.#accountIds = [...(config.accountIds ?? config.execute?.accountIds ?? [])]; + this.#rpcClient = new RpcClient({ + baseUrl: this.#baseUrl, + apiKey: this.#apiKey, + timeout: this.#timeout, + headers: this.#headers, + }); } - private catalogCache: Map = new Map(); - /** * Set account IDs for filtering tools * @param accountIds Array of account IDs to filter tools by * @returns This toolset instance for chaining */ setAccounts(accountIds: string[]): this { - this.accountIds = accountIds; + assertAccountIdList(accountIds, 'accountIds'); + this.#accountIds = [...accountIds]; this.clearCatalogCache(); return this; } /** - * Invalidate cached tool catalog and local search index. + * Invalidate the cached tool catalog and discovered accounts. * - * Call when linked accounts change outside of {@link setAccounts} or when - * you need to force a fresh fetch from the StackOne MCP endpoint. + * Call when linked accounts change outside of {@link setAccounts} or when you need to force a + * fresh fetch from the StackOne MCP endpoint. A listing already in flight will not write its + * result back into the cache. */ clearCatalogCache(): void { - this.catalogCache.clear(); - } - - /** - * Extract the API key from authentication config. - */ - private getApiKey(): string { - const credentials = this.authentication?.credentials ?? {}; - const apiKeyFromAuth = - this.authentication?.type === 'basic' - ? credentials.username - : this.authentication?.type === 'bearer' - ? credentials.token - : credentials.username; - - const apiKey = apiKeyFromAuth || process.env.STACKONE_API_KEY; - if (!apiKey) { - throw new ToolSetConfigError( - 'API key is required for semantic search. Provide apiKey in config or set STACKONE_API_KEY environment variable.', - ); - } - return apiKey; + this.#cacheGeneration += 1; + this.#catalogCache.clear(); + this.#discoveredAccountIds = undefined; } /** * Get tools in OpenAI function calling format. * * @param options - Options - * @param options.accountIds - Account IDs to scope tools. Overrides the `execute` - * config from the constructor. + * @param options.accountIds - Account IDs to scope tools. Defaults to the toolset's accounts. * @returns List of tool definitions in OpenAI function format. * * @example @@ -338,359 +321,316 @@ export class StackOneToolSet { * ``` */ async openai(options?: { accountIds?: string[] }): Promise> { - const effectiveAccountIds = options?.accountIds ?? this.executeConfig?.accountIds; - - const tools = await this.fetchTools({ accountIds: effectiveAccountIds }); + const tools = await this.fetchTools({ accountIds: options?.accountIds }); return tools.toOpenAI(); } /** - * Fetch tools from MCP with optional filtering - * @param options Optional filtering options for account IDs, providers, and actions - * @returns Collection of tools matching the filter criteria + * List the accounts linked to this API key. + * + * Each entry carries at least `id`, `provider` and `status`. Only accounts with + * `status === 'active'` can serve tools. + * + * @throws StackOneAPIError If the API answers with an error status. + * @throws ToolSetLoadError If the API cannot be reached, or answers with something that is + * not a JSON list (including a body that is not valid UTF-8). */ - async fetchTools(options?: FetchToolsOptions): Promise { - // Use account IDs from options, or fall back to instance state - const effectiveAccountIds = options?.accountIds || this.accountIds; - - const cacheKey = JSON.stringify({ - accountIds: [...effectiveAccountIds].sort(), - providers: options?.providers?.length ? [...options.providers].sort() : null, - actions: options?.actions?.length ? [...options.actions].sort() : null, - }); - const cached = this.catalogCache.get(cacheKey); - if (cached) { - return cached; - } - - // Fetch tools (with account filtering if needed) - // Headers are threaded as parameters per request — never mutate this.headers, - // since concurrent callers would clobber each other's x-account-id. - let tools: Tools; - if (effectiveAccountIds.length > 0) { - const toolsPromises = effectiveAccountIds.map(async (accountId) => { - const requestHeaders = { ...this.headers, 'x-account-id': accountId }; - const accountTools = await this.fetchToolsFromMcp(requestHeaders); - return accountTools.toArray(); + async fetchAccounts(): Promise { + const url = `${this.#baseUrl.replace(/\/+$/, '')}/accounts`; + let response: Response; + try { + response = await fetch(url, { + headers: buildRequestHeaders({ apiKey: this.#apiKey, extraHeaders: this.#headers }), + signal: AbortSignal.timeout(this.#timeout), + }); + } catch (error) { + throw new ToolSetLoadError(`Could not reach ${url}: ${describeError(error)}`, { + cause: error, }); - - const toolArrays = await Promise.all(toolsPromises); - const allTools = toolArrays.flat(); - tools = new Tools(allTools); - } else { - // No account filtering - fetch all tools - tools = await this.fetchToolsFromMcp(this.headers); } - // Apply provider and action filters - const filteredTools = this.filterTools(tools, options); - - this.catalogCache.set(cacheKey, filteredTools); - return filteredTools; - } - - /** - * Fetch tool definitions from MCP using the given request headers. - * Headers are passed in (not read from this.headers) so concurrent callers - * can each scope their request to a different x-account-id safely. - */ - private async fetchToolsFromMcp(requestHeaders: Record): Promise { - if (!this.baseUrl) { - throw new ToolSetConfigError('baseUrl is required to fetch MCP tools'); + let bytes: ArrayBuffer; + try { + bytes = await response.arrayBuffer(); + } catch (error) { + throw new ToolSetLoadError( + `Could not read the response from ${url}: ${describeError(error)}`, + { + cause: error, + }, + ); } - await using clients = await createMCPClient({ - baseUrl: `${this.baseUrl}/mcp?param-style=${MCP_PARAM_STYLE}`, - headers: requestHeaders, - }); - - await clients.client.connect(clients.transport); - const listToolsResult = await clients.client.listTools(); - const actionsClient = this.getActionsClient(); - - const tools = listToolsResult.tools.map(({ name, description, inputSchema }) => { - return this.createRpcBackedTool({ - actionsClient, - name, - description, - inputSchema, - headers: requestHeaders, - }); - }); - - return new Tools(tools); - } + if (!response.ok) { + // Carry the status, so a caller can tell a 401 from a 429. + const text = new TextDecoder().decode(bytes).trim(); + throw new StackOneAPIError( + `Listing accounts at ${url} failed with ${response.status} ${response.statusText}: ${text}`, + response.status, + text, + ); + } - /** - * Filter tools by providers and actions - * @param tools Tools collection to filter - * @param options Filtering options - * @returns Filtered tools collection - */ - private filterTools(tools: Tools, options?: FetchToolsOptions): Tools { - let filteredTools = tools.toArray(); - - // Filter by providers if specified - if (options?.providers && options.providers.length > 0) { - const providerSet = new Set(options.providers.map((p) => p.toLowerCase())); - filteredTools = filteredTools.filter((tool) => { - return tool.connector && providerSet.has(tool.connector); + let body: unknown; + try { + body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch (error) { + throw new ToolSetLoadError(`Invalid JSON returned by ${url}: ${describeError(error)}`, { + cause: error, }); } - - // Filter by actions if specified (with glob support) - if (options?.actions && options.actions.length > 0) { - filteredTools = filteredTools.filter((tool) => - options.actions?.some((pattern) => this.matchGlob(tool.name, pattern)), + const accounts = + typeof body === 'object' && body !== null && !Array.isArray(body) && 'data' in body + ? (body as { data: unknown }).data + : body; + if (!Array.isArray(accounts)) { + throw new ToolSetLoadError( + `Unexpected /accounts response shape: expected a list, got ${accounts === null ? 'null' : typeof accounts}`, ); } - - return new Tools(filteredTools); + return accounts as StackOneAccount[]; } /** - * Check if a string matches a glob pattern - * @param str String to check - * @param pattern Glob pattern - * @returns True if the string matches the pattern + * The active accounts linked to this API key. + * + * The MCP endpoint requires an `x-account-id` on every request, so an API key on its own is + * not enough to list tools. Rather than make every caller supply one, ask the API which + * accounts the key has. + * + * For organisations with many linked accounts, discovery lists the catalog of every one of + * them: pass explicit `accountIds` to avoid the round trips and the context they cost. + * + * @throws ToolSetConfigError If the key has no accounts, or none are active. */ - private matchGlob(str: string, pattern: string): boolean { - // Convert glob pattern to regex - const regexPattern = pattern.replace(/\./g, '\\.').replace(/\*/g, '.*').replace(/\?/g, '.'); - - // Create regex with start and end anchors - const regex = new RegExp(`^${regexPattern}$`); - - // Test if the string matches the pattern - return regex.test(str); - } - - private getActionsClient(): RpcClient { - if (this.rpcClient) { - return this.rpcClient; + async #discoverAccountIds(): Promise { + if (this.#discoveredAccountIds) { + return this.#discoveredAccountIds; } - - const credentials = this.authentication?.credentials ?? {}; - const apiKeyFromAuth = - this.authentication?.type === 'basic' - ? credentials.username - : this.authentication?.type === 'bearer' - ? credentials.token - : credentials.username; - - const apiKey = apiKeyFromAuth || process.env.STACKONE_API_KEY; - const password = this.authentication?.type === 'basic' ? (credentials.password ?? '') : ''; - - if (!apiKey) { + const generation = this.#cacheGeneration; + const accounts = await this.fetchAccounts(); + const active = accounts + .filter( + (account) => account?.status === 'active' && typeof account.id === 'string' && account.id, + ) + .map((account) => account.id); + if (active.length === 0) { + if (accounts.length === 0) { + throw new ToolSetConfigError( + 'This API key has no linked accounts. Link one in the StackOne dashboard, or pass accountId explicitly.', + ); + } + const listed = accounts + .map((account) => `${String(account?.provider)} (${String(account?.status)})`) + .join(', '); throw new ToolSetConfigError( - 'StackOne API key is required to create an actions client. Provide rpcClient, configure authentication credentials, or set the STACKONE_API_KEY environment variable.', + `None of this API key's ${accounts.length} linked accounts are active: ${listed}. Re-link them in the StackOne dashboard, or pass accountId explicitly.`, ); } - - this.rpcClient = new RpcClient({ - serverURL: this.baseUrl, - security: { - username: apiKey, - password, - }, - timeout: this.timeout, - }); - - return this.rpcClient; + if (generation === this.#cacheGeneration) { + this.#discoveredAccountIds = active; + } + return active; } - private createRpcBackedTool({ - actionsClient, - name, - description, - inputSchema, - headers, - }: { - actionsClient: RpcClient; - name: string; - description?: string; - inputSchema: ToolInputSchema; - headers: Record; - }): BaseTool { - const executeConfig = { - kind: 'rpc', - method: 'POST', - url: `${this.baseUrl}/actions/rpc`, - payloadKeys: { - action: 'action', - body: 'body', - headers: 'headers', - path: 'path', - query: 'query', - }, - } as const satisfies RpcExecuteConfig; // Mirrors StackOne RPC payload layout so metadata/debug stays in sync. - - const toolParameters = { - ...inputSchema, - - // properties are not well typed in MCP spec - properties: inputSchema?.properties as JsonSchemaProperties, - } satisfies ToolParameters; - - const declaredHeaders = declaredHeaderNames(Object.keys(toolParameters.properties ?? {})); - - const tool = new BaseTool( - name, - description ?? '', - toolParameters, - executeConfig, - headers, - ).setExposeExecutionMetadata(false); - - tool.execute = async ( - inputParams?: JsonObject | string, - options?: ExecuteOptions, - ): Promise => { - try { - if ( - inputParams !== undefined && - typeof inputParams !== 'object' && - typeof inputParams !== 'string' - ) { - throw new StackOneError( - `Invalid parameters type. Expected object or string, got ${typeof inputParams}. Parameters: ${JSON.stringify(inputParams)}`, - ); - } - - const parsedParams = - typeof inputParams === 'string' ? JSON.parse(inputParams) : (inputParams ?? {}); - - const currentHeaders = tool.getHeaders(); - const baseHeaders = this.buildActionHeaders(currentHeaders); - - const envelope = this.splitEnvelopeParams(parsedParams); - const pathParams = envelope.path; - const queryParams = envelope.query; - // Model-supplied headers are filtered to the ones the served schema declares, and - // the SDK's own headers are applied LAST. Merging the other way round let a tool - // call carry `headers_x-account-id` and switch the request to another tenant. - const allowedHeaders = sanitiseHeaders(envelope.headers, declaredHeaders); - const actionHeaders = stackOneHeadersSchema.parse({ ...allowedHeaders, ...baseHeaders }); - - const rpcBody: JsonObject = envelope.body; - - if (options?.dryRun) { - const requestPayload = { - action: name, - body: rpcBody, - headers: actionHeaders, - path: pathParams ?? undefined, - query: queryParams ?? undefined, - }; - - return { - url: executeConfig.url, - method: executeConfig.method, - headers: actionHeaders, - body: JSON.stringify(requestPayload), - mappedParams: parsedParams, - } satisfies JsonObject; - } - - const response = await actionsClient.actions.rpcAction({ - action: name, - body: rpcBody, - headers: actionHeaders, - path: pathParams ?? undefined, - query: queryParams ?? undefined, - }); - - return rpcResponseToJsonObject(response); - } catch (error) { - if (error instanceof StackOneError) { - throw error; - } - throw new StackOneError(`Error executing RPC action ${name}`, { cause: error }); - } - }; - - return tool; + async #resolveAccountScope(accountIds: string[] | undefined): Promise { + assertAccountIdList(accountIds, 'accountIds'); + let scope = accountIds?.length ? accountIds : this.#accountIds; + if (scope.length === 0 && this.#accountId) { + scope = [this.#accountId]; + } + if (scope.length === 0) { + scope = await this.#discoverAccountIds(); + } + // 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(scope)].sort(); } - private buildActionHeaders(headers: Record): StackOneHeaders { - const sanitizedEntries = Object.entries(headers).filter( - ([key]) => key.toLowerCase() !== 'authorization', - ); + #endpoint(mode: ToolMode | undefined): string { + const endpoint = `${this.#baseUrl.replace(/\/+$/, '')}/mcp?param-style=${MCP_PARAM_STYLE}`; + return mode ? `${endpoint}&tool-mode=${mode}` : endpoint; + } - return stackOneHeadersSchema.parse( - Object.fromEntries(sanitizedEntries.map(([key, value]) => [key, String(value)])), - ); + /** + * Keyed on what was fetched, not on how it is filtered: providers and actions narrow the list + * in memory, so they must not force a refetch. The base URL and API key belong in it, so a + * catalog is never served for a host or key other than the one it was listed from. + */ + #cacheKey(scope: readonly string[], mode: ToolMode | undefined): string { + return JSON.stringify([scope, mode ?? null, this.#baseUrl, this.#apiKey]); } /** - * Splits LLM-supplied tool arguments into the RPC envelope (path/query/headers/body). + * List every scoped account's catalog, tolerating accounts that fail. * - * Tools are listed with `?param-style=flat_prefixed`, so keys arrive as `_` - * (for example `path_id`, `query_limit`). The prefix carries the parameter location, so the - * split needs no per-action schema. A bare object-valued `path`/`query`/`headers`/`body` key - * is still bucketed for clients holding a cached nested schema, and any other key falls - * through to the body. + * One unusable account must not cost the caller every other account's tools, so a failing + * account is skipped with a warning — unless every account fails, which is an error rather + * than an empty catalog. A degraded listing is not cached: the warning fires once, and every + * later call would otherwise serve the short list silently for the life of the process. */ - private splitEnvelopeParams(params: JsonObject): { - path?: JsonObject; - query?: JsonObject; - headers?: JsonObject; - body: JsonObject; - } { - // Null-prototype buckets so API fields named after Object.prototype members - // (`constructor`, `toString`, `__proto__`) are stored as ordinary own properties - // instead of colliding with the prototype chain and being dropped. - const buckets: Record = { - path: Object.create(null), - query: Object.create(null), - headers: Object.create(null), - body: Object.create(null), + async #listCatalog( + scope: readonly string[], + mode: ToolMode | undefined, + ): Promise { + const generation = this.#cacheGeneration; + const endpoint = this.#endpoint(mode); + const listAccount = async (accountId: string): Promise => { + const definitions = await listMcpTools({ + endpoint, + headers: buildRequestHeaders({ + apiKey: this.#apiKey, + accountId, + extraHeaders: this.#headers, + }), + timeout: this.#timeout, + }); + return definitions.map((definition) => ({ definition, accountId, endpoint })); }; - // Keeps whichever value reaches a field first, so the pass order below is what decides - // precedence rather than the order the caller happened to supply keys in. - const assignField = (bucket: JsonObject, field: string, value: unknown): void => { - if (!Object.hasOwn(bucket, field)) { - bucket[field] = value as JsonObject[string]; + const store = (listing: CatalogEntry[]): void => { + if (generation === this.#cacheGeneration) { + this.#catalogCache.set(this.#cacheKey(scope, mode), listing); } }; - const entries = Object.entries(params); + if (scope.length === 1) { + const listing = await listAccount(scope[0] as string); + store(listing); + return listing; + } - // First pass: explicit flat_prefixed keys. Applied before anything else so a prefixed - // key always wins over the same field carried in a nested envelope or as a bare key. - for (const [key, value] of entries) { - const match = key.match(FLAT_ENVELOPE_KEY_PATTERN); - if (match) { - assignField(buckets[match[1] as EnvelopeLocation], match[2], value); + const settled = await settleWithConcurrency(scope, MAX_CONCURRENCY, listAccount); + const listing: CatalogEntry[] = []; + const failures: string[] = []; + settled.forEach((outcome, index) => { + if (outcome.status === 'fulfilled') { + listing.push(...outcome.value); + } else { + failures.push(`${scope[index]}: ${describeError(outcome.reason)}`); } + }); + if (failures.length > 0 && listing.length === 0) { + throw new ToolSetLoadError(`No account returned tools. ${failures.join(' | ')}`); + } + for (const failure of failures) { + warn(`Skipping account that failed to list tools — ${failure}`); + } + if (failures.length === 0) { + store(listing); } + return listing; + } - // Second pass: nested envelopes from clients on a cached schema, then bare body fields. - for (const [key, value] of entries) { - if (FLAT_ENVELOPE_KEY_PATTERN.test(key)) { - continue; - } - if (isEnvelopeLocation(key)) { - // Reserved keys name an envelope, never a body field. A non-object value cannot - // be bucketed, so it is dropped rather than leaked into the body under its - // reserved name. - if (isPlainObject(value)) { - for (const [field, fieldValue] of Object.entries(value)) { - assignField(buckets[key], field, fieldValue); + /** + * Build an executable tool from a served catalog entry, on a deep copy of its schema. + * + * In `search_execute` mode the served tools are MCP meta tools with no action behind them on + * `/actions/rpc`, so they are executed over `tools/call`. `stackone_submit_feedback` goes over + * `tools/call` in every mode too. The server would also accept it on `/actions/rpc`, but it is + * served over MCP and is not a connector action, so it is called where it was listed. + */ + #createTool(entry: CatalogEntry, mode: ToolMode | undefined): StackOneTool { + const { definition, accountId, endpoint } = entry; + const parameters = toolParametersFromInputSchema(cloneJson(definition.inputSchema)); + const description = definition.description ?? ''; + if (mode === 'search_execute' || definition.name === SUBMIT_FEEDBACK_TOOL_NAME) { + return new StackOneMcpTool({ + name: definition.name, + description, + parameters, + endpoint, + apiKey: this.#apiKey, + accountId, + timeout: this.#timeout, + extraHeaders: this.#headers, + }); + } + return new StackOneRpcTool({ + name: definition.name, + description, + parameters, + client: this.#rpcClient, + accountId, + }); + } + + /** + * Fetch tools with optional filtering by account IDs, providers, and actions. + * + * The listing is cached per account scope and mode; filters are applied in memory, and every + * call builds fresh tool instances, so mutating one caller's tools never affects another's. + * + * `stackone_submit_feedback` is served once per account listing; it is returned once. + * + * @throws ToolSetConfigError If no account is configured and none can be discovered. + * @throws StackOneAPIError If the API refuses a listing (e.g. 412 for a dead account). + * @throws ToolSetLoadError If the catalog cannot be loaded. + */ + async fetchTools(options: FetchToolsOptions = {}): Promise { + try { + const mode = options.mode === undefined ? this.#toolMode : (options.mode ?? undefined); + const scope = await this.#resolveAccountScope(options.accountIds); + const listing = + this.#catalogCache.get(this.#cacheKey(scope, mode)) ?? + (await this.#listCatalog(scope, mode)); + + let seenFeedbackTool = false; + let tools = listing + .filter(({ definition }) => { + // Global rather than account-scoped, so every account's listing carries an + // identical copy. Keep the first. + if (definition.name !== SUBMIT_FEEDBACK_TOOL_NAME) { + return true; } - } - continue; + const first = !seenFeedbackTool; + seenFeedbackTool = true; + return first; + }) + .map((entry) => this.#createTool(entry, mode)); + + if (options.providers?.length) { + const providers = options.providers; + tools = tools.filter((tool) => matchesProvider(tool.name, providers)); } - assignField(buckets.body, key, value); + if (options.actions?.length) { + const actions = options.actions; + tools = tools.filter((tool) => actions.some((pattern) => matchGlob(tool.name, pattern))); + } + + warnOnDuplicateNames(tools); + return new Tools(tools); + } catch (error) { + // StackOneAPIError carries the HTTP status. Re-wrapping it would throw that away, so a + // caller could not tell a 401 from a 429. + if (error instanceof StackOneError) { + throw error; + } + throw new ToolSetLoadError(`Error fetching tools: ${describeError(error)}`, { + cause: error, + }); } + } +} - // Spread onto ordinary objects so downstream JSON and schema handling sees plain records. - return { - path: Object.keys(buckets.path).length > 0 ? { ...buckets.path } : undefined, - query: Object.keys(buckets.query).length > 0 ? { ...buckets.query } : undefined, - headers: Object.keys(buckets.headers).length > 0 ? { ...buckets.headers } : undefined, - body: { ...buckets.body }, - }; +/** + * Two accounts on one provider serve identically named tools, and `getTool()` returns whichever + * was listed first. OpenAI accepts duplicate function names without complaint, so nothing + * downstream surfaces it either — the only symptom would be an action running against an + * account the caller never chose. + */ +function warnOnDuplicateNames(tools: readonly StackOneTool[]): void { + const counts = new Map(); + 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(); + if (clashing.length > 0) { + warn( + `${clashing.length} tool name(s) are served by more than one account (${clashing.slice(0, 5).join(', ')}). getTool() will return the first one listed — pass accountIds to choose.`, + ); } } diff --git a/src/types.ts b/src/types.ts index 64215602..7f629b93 100644 --- a/src/types.ts +++ b/src/types.ts @@ -2,17 +2,11 @@ * Common type definitions for the StackOne SDK */ -import type { Tool } from 'ai'; -import type { ToolSet } from 'ai'; -import type { JsonObject, JsonValue, ValueOf } from 'type-fest'; +import type { Tool, ToolSet } from 'ai'; +import type { JsonObject, JsonValue } from 'type-fest'; export type { JsonObject, JsonValue }; -/** - * HTTP headers type - */ -type Headers = Record; - /** * JSON Schema type for defining tool input/output schemas as raw JSON Schema objects. * This allows tools to be defined without Zod when you have JSON Schema definitions available. @@ -71,45 +65,23 @@ export interface JSONSchema { export type JsonSchemaProperties = Record; /** - * JSON Schema type union - */ -type JsonSchemaType = JSONSchema['type']; - -/** - * Valid locations for parameters in requests + * How the MCP endpoint lists tools. + * + * `'individual'` (the server default) lists one tool per action — hundreds per account. + * `'search_execute'` lists two meta tools per connector instead: a `*_search_actions` that ranks + * actions for a natural-language query and an `*_execute_action` that runs one by id. The + * catalog stays small however many accounts are linked, which is what keeps it inside a model's + * context. */ -export const ParameterLocation = { - HEADER: 'header', - QUERY: 'query', - PATH: 'path', - BODY: 'body', -} as const satisfies Record; - -export type ParameterLocation = ValueOf; +export type ToolMode = 'individual' | 'search_execute'; /** - * Configuration for executing a tool against an API endpoint + * Executes over the StackOne actions RPC endpoint (`POST /actions/rpc`). Every per-action tool + * listed in `individual` mode is one of these. */ -interface HttpExecuteParameter { - name: string; - location: ParameterLocation; - type: JsonSchemaType; - derivedFrom?: string; // this is the name of the param that this one is derived from. -} - -export type HttpBodyType = 'json' | 'multipart-form' | 'form'; - -export interface HttpExecuteConfig { - kind: 'http'; - method: string; - url: string; - bodyType: HttpBodyType; - params: HttpExecuteParameter[]; // full list of params used to execute. Comes straight from the OpenAPI spec. -} - export interface RpcExecuteConfig { kind: 'rpc'; - method: string; + method: 'POST'; url: string; payloadKeys: { action: string; @@ -120,7 +92,21 @@ export interface RpcExecuteConfig { }; } -export interface LocalExecuteConfig { +/** + * Executes over MCP `tools/call` on the endpoint that listed it. The search/execute meta tools + * have no action behind them on `/actions/rpc`; `stackone_submit_feedback` is not a connector + * action either, so the SDK calls it here even though the server also accepts it over RPC. + */ +export interface McpExecuteConfig { + kind: 'mcp'; + url: string; + toolName: string; +} + +/** + * A tool whose `execute` is supplied by the caller rather than by the SDK. + */ +interface LocalExecuteConfig { kind: 'local'; identifier?: string; description?: string; @@ -129,15 +115,15 @@ export interface LocalExecuteConfig { /** * Discriminated union lets call sites branch on execution style without relying on nullable fields. */ -export type ExecuteConfig = HttpExecuteConfig | RpcExecuteConfig | LocalExecuteConfig; +export type ExecuteConfig = RpcExecuteConfig | McpExecuteConfig | LocalExecuteConfig; /** * Options for executing a tool */ export interface ExecuteOptions { /** - * If true, returns the request details instead of making the actual API call - * Useful for debugging and testing transformed parameters + * If true, returns the request the tool would send instead of sending it. Useful for + * checking how arguments are routed into the RPC envelope. */ dryRun?: boolean; } @@ -147,22 +133,21 @@ export interface ExecuteOptions { */ export interface ToolExecution { /** - * The raw execution configuration generated from the OpenAPI specification. + * How the tool is executed. */ config: ExecuteConfig; - /** - * The headers that will be sent when executing the tool. - */ - headers: Headers; } /** - * Schema definition for tool parameters + * Schema definition for tool parameters: the served `inputSchema`, verbatim. + * + * Every root keyword the server sends (`$schema`, `$defs`, `title`, `additionalProperties`, + * `oneOf`, …) is kept, so {@link BaseTool.toJsonSchema} can hand a model exactly what was served. */ export interface ToolParameters extends Record { type: string; - properties: JsonSchemaProperties; // these are the params we will expose to the user/agent in the tool. These might be higher level params. - required?: string[]; // list of required parameter names + properties: JsonSchemaProperties; + required?: string[]; } /** @@ -215,3 +200,13 @@ export interface ClaudeAgentSdkOptions { */ serverVersion?: string; } + +/** + * An account linked to the API key, as `GET /accounts` returns it. Only accounts whose `status` + * is `'active'` can serve tools. + */ +export type StackOneAccount = JsonObject & { + id: string; + provider?: string; + status?: string; +}; diff --git a/src/utils/binary-response.ts b/src/utils/binary-response.ts index 7ef83286..3edc17a2 100644 --- a/src/utils/binary-response.ts +++ b/src/utils/binary-response.ts @@ -2,9 +2,9 @@ * Shared handling for binary (file-download) HTTP responses. * * StackOne serves file downloads as raw binary with the file's own MIME type and a - * Content-Disposition header - never as the usual JSON envelope. Both the HTTP tool path - * (RequestBuilder) and the RPC tool path (RpcClient) must therefore decide JSON-vs-file by - * Content-Type and return the bytes plus metadata instead of forcing a JSON parse. + * Content-Disposition header - never as the usual JSON envelope. The RPC client must therefore + * decide JSON-vs-file by Content-Type and return the bytes plus metadata instead of forcing a + * JSON parse. */ /** diff --git a/src/utils/concurrency.ts b/src/utils/concurrency.ts new file mode 100644 index 00000000..4bbca28f --- /dev/null +++ b/src/utils/concurrency.ts @@ -0,0 +1,26 @@ +/** + * Run `work` over `items` with at most `limit` in flight, settling every one. + * + * Results come back in input order whatever order they complete in, so callers that merge them + * stay deterministic. + */ +export async function settleWithConcurrency( + items: readonly T[], + limit: number, + work: (item: T) => Promise, +): Promise[]> { + const results: PromiseSettledResult[] = Array.from({ length: items.length }); + let next = 0; + const worker = async (): Promise => { + while (next < items.length) { + const index = next++; + try { + results[index] = { status: 'fulfilled', value: await work(items[index] as T) }; + } catch (reason) { + results[index] = { status: 'rejected', reason }; + } + } + }; + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); + return results; +} diff --git a/src/utils/error-stackone-api.test.ts b/src/utils/error-stackone-api.test.ts index 437abd14..c526f91d 100644 --- a/src/utils/error-stackone-api.test.ts +++ b/src/utils/error-stackone-api.test.ts @@ -1,6 +1,6 @@ import { USER_AGENT } from '../consts'; import { TEST_BASE_URL } from '../../mocks/constants'; -import { StackOneAPIError } from './error-stackone-api'; +import { StackOneAPIError, describeApiFailure } from './error-stackone-api'; describe('StackOneAPIError', () => { it('should create an error with basic properties', () => { @@ -11,26 +11,11 @@ describe('StackOneAPIError', () => { expect(error.message).toBe('API failed'); }); - it('should append message from responseBody if present', () => { - const error = new StackOneAPIError('API failed', 400, { - message: 'Invalid request body', + it('keeps the message it is given rather than rewriting it', () => { + const error = new StackOneAPIError('400 Bad Request: path.id is missing', 400, { + message: 'path.id is missing', }); - expect(error.message).toBe('API failed: Invalid request body'); - }); - - it('should not append message if responseBody.message is not a string', () => { - const error = new StackOneAPIError('API failed', 400, { message: 123 }); - expect(error.message).toBe('API failed'); - }); - - it('should not append message if responseBody.message is empty', () => { - const error = new StackOneAPIError('API failed', 400, { message: '' }); - expect(error.message).toBe('API failed'); - }); - - it('should not append message if responseBody is null', () => { - const error = new StackOneAPIError('API failed', 400, null); - expect(error.message).toBe('API failed'); + expect(error.message).toBe('400 Bad Request: path.id is missing'); }); it('should extract provider errors from responseBody', () => { @@ -207,3 +192,24 @@ describe('StackOneAPIError', () => { expect(result).not.toContain('Provider Endpoint:'); }); }); + +describe('describeApiFailure', () => { + it.each([ + [{ message: 'path.id is missing', error: 'ignored' }, '400 Bad Request: path.id is missing'], + [{ error: 'Invalid ID' }, '400 Bad Request: Invalid ID'], + [{ detail: 'Nope' }, '400 Bad Request: Nope'], + [{ code: 7 }, '400 Bad Request: {"code":7}'], + [' plain text ', '400 Bad Request: plain text'], + [['a'], '400 Bad Request: ["a"]'], + [null, '400 Bad Request from https://api.example.com/x'], + ['', '400 Bad Request from https://api.example.com/x'], + ])('leads with the server explanation in %j', (body, expected) => { + expect(describeApiFailure(400, 'Bad Request', body, 'https://api.example.com/x')).toBe( + expected, + ); + }); + + it('caps a long text body', () => { + expect(describeApiFailure(500, '', 'x'.repeat(900), 'u')).toBe(`500: ${'x'.repeat(500)}`); + }); +}); diff --git a/src/utils/error-stackone-api.ts b/src/utils/error-stackone-api.ts index fba587ab..59eded17 100644 --- a/src/utils/error-stackone-api.ts +++ b/src/utils/error-stackone-api.ts @@ -2,7 +2,35 @@ import { USER_AGENT } from '../consts'; import { StackOneError } from './error-stackone'; /** - * Raised when the StackOne API returns an error + * Lead with the server's own explanation of what went wrong. + * + * A bare status ("400 Bad Request") never says which field was wrong, even though the answer is + * already in hand in the response body. This is the error a user hits on every bad tool call, so + * it is the one worth making actionable: `400 Bad Request: path.id is missing`. + */ +export function describeApiFailure( + status: number, + statusText: string, + body: unknown, + url: string, +): string { + let detail: string | undefined; + if (typeof body === 'object' && body !== null && !Array.isArray(body)) { + const record = body as Record; + const key = ['message', 'error', 'detail'].find((name) => typeof record[name] === 'string'); + detail = key ? (record[key] as string) : JSON.stringify(body); + } else if (typeof body === 'string' && body.trim()) { + detail = body.trim().slice(0, 500); + } else if (body != null && typeof body !== 'string') { + detail = JSON.stringify(body); + } + const heading = `${status} ${statusText}`.trim(); + return detail ? `${heading}: ${detail}` : `${heading} from ${url}`; +} + +/** + * Raised when the StackOne API returns an error. Carries the HTTP status and the response + * body, so a caller can branch on a 412 (a dead account) rather than parse the message. */ export class StackOneAPIError extends StackOneError { statusCode: number; @@ -17,19 +45,7 @@ export class StackOneAPIError extends StackOneError { requestBody?: unknown, options?: ErrorOptions, ) { - // Extract the error message from responseBody if it exists - let errorMessage = message; - if ( - responseBody && - typeof responseBody === 'object' && - 'message' in responseBody && - responseBody.message && - typeof responseBody.message === 'string' - ) { - errorMessage = `${message}: ${responseBody.message}`; - } - - super(errorMessage, options); + super(message, options); this.name = 'StackOneAPIError'; this.statusCode = statusCode; this.responseBody = responseBody; diff --git a/src/utils/serialize.ts b/src/utils/serialize.ts new file mode 100644 index 00000000..6554eac1 --- /dev/null +++ b/src/utils/serialize.ts @@ -0,0 +1,21 @@ +/** + * Serialise a tool result for a model. + * + * A file download carries its bytes as a `Buffer`, which `JSON.stringify` turns into a + * `{ type: 'Buffer', data: [...] }` byte array — not the file, and potentially enormous. Bytes are + * base64-encoded instead, and a `bigint` is written as its decimal string rather than throwing. + * The replacer reads the ORIGINAL value from its holder, because `JSON.stringify` has already + * called `Buffer#toJSON` by the time the replacer sees `value`. + */ +export function serializeToolResult(result: unknown): string { + return JSON.stringify(result, function replacer(this: unknown, key: string, value: unknown) { + const original = (this as Record)[key]; + if (original instanceof Uint8Array) { + return Buffer.from(original).toString('base64'); + } + if (typeof value === 'bigint') { + return value.toString(); + } + return value; + }); +} From 05bba0477bcac61999264451f6e4adeb5fa58950 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:48:26 +0100 Subject: [PATCH 012/151] feat: add search(), execute() and submitFeedback() with session ids The recommended surface: find an action in natural language, run it by id, and record how it went, without loading a tool catalog into a model's context. Ported from the Python SDK 3.0, plus the Node side of the feedback/session contract. - `search(query, { topK, accountIds })` queries every linked connector's `*_search_actions` meta tool (`tool-mode=search_execute`) concurrently and ranks the hits globally by `similarity_score`, rather than leaving them grouped by whichever connector answered first. `topK` is validated 1..50 before any round trip. A connector that fails is skipped with a warning unless all do. Every hit carries the `session_id` of the search that produced it, when the server issued one. - `execute(actionId, args?, { sessionId, accountIds })` routes to the longest connector whose name prefixes the action id, stripping the account id from the meta tool's name by identity (nanoid ids contain `_`). `session_id` is forwarded as a top-level argument only when given, and `action_id` is pinned last, so a model-supplied `action_id` in the arguments cannot swap the action. The `{ isError, result }` wrapper is unwrapped, and an `isError` result raises. - `submitFeedback({ rating, toolNames, feedback?, category?, sessionId?, source?, accountIds? })` finds the server-served `stackone_submit_feedback` in the catalog (any mode) and calls it over `tools/call` with snake_case arguments, omitting unset keys rather than sending null. When the server does not serve it, it raises `ToolSetLoadError`: feedback is not enabled for the project. --- src/consts.ts | 7 +- src/index.ts | 7 + src/toolsets.search-execute.test.ts | 497 ++++++++++++++++++++++++++++ src/toolsets.ts | 302 ++++++++++++++++- src/types.ts | 22 ++ 5 files changed, 832 insertions(+), 3 deletions(-) create mode 100644 src/toolsets.search-execute.test.ts diff --git a/src/consts.ts b/src/consts.ts index a8989ca1..9ca40281 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -23,10 +23,13 @@ export const MCP_PARAM_STYLE = 'flat_prefixed'; /** * The one global tool the MCP endpoint serves, in every tool mode, when feedback is enabled for - * the project. It is not an action: `/actions/rpc` has never heard of it, so it is only ever - * executed over MCP `tools/call`. + * the project. It is not a connector action; the server also accepts it on `/actions/rpc`, but + * the SDK executes it only over MCP `tools/call`, where it is served. */ export const SUBMIT_FEEDBACK_TOOL_NAME = 'stackone_submit_feedback'; /** Upper bound on how many accounts' catalogs (or connectors' searches) run at once. */ export const MAX_CONCURRENCY = 10; + +/** The `*_search_actions` meta tool's served schema caps `top_k` at 50. */ +export const MAX_TOP_K = 50; diff --git a/src/index.ts b/src/index.ts index f02bc706..807d2189 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,9 +10,12 @@ export { ToolSetConfigError, ToolSetError, ToolSetLoadError } from './utils/erro export { StackOneToolSet, + type ExecuteActionOptions, type ExecuteToolsConfig, type FetchToolsOptions, + type SearchOptions, type StackOneToolSetConfig, + type SubmitFeedbackOptions, } from './toolsets'; export type { @@ -20,8 +23,12 @@ export type { AISDKToolResult, ExecuteConfig, ExecuteOptions, + FeedbackCategory, + FeedbackRating, + FeedbackSource, JsonObject, JsonValue, + SearchResult, StackOneAccount, ToolDefinition, ToolMode, diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts new file mode 100644 index 00000000..07b28a4d --- /dev/null +++ b/src/toolsets.search-execute.test.ts @@ -0,0 +1,497 @@ +/** + * search(), execute() and submitFeedback(): the recommended surface, over the per-connector + * `*_search_actions` / `*_execute_action` meta tools and the server's `stackone_submit_feedback`. + */ +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 { server } from '../mocks/node'; +import { type McpToolDefinition, listMcpTools } from './mcp-client'; +import { StackOneMcpTool } from './tool'; +import { StackOneToolSet } from './toolsets'; +import type { JsonObject } from './types'; +import { StackOneAPIError } from './utils/error-stackone-api'; +import { StackOneError } from './utils/error-stackone'; +import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; + +vi.mock('./mcp-client', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, listMcpTools: vi.fn(actual.listMcpTools) }; +}); +const listMock = vi.mocked(listMcpTools); +const { listMcpTools: realListMcpTools } = + await vi.importActual('./mcp-client'); + +const newToolSet = (config: ConstructorParameters[0] = {}) => + new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); + +let warnSpy: ReturnType; +beforeEach(() => { + vi.stubEnv('STACKONE_ACCOUNT_ID', ''); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + listMock.mockReset(); + listMock.mockImplementation(realListMcpTools); +}); + +/** + * Serve meta tools with these names, each on the account its name embeds, and replace the + * tools/call with `respond` — as the Python suite monkeypatches `StackOneMcpTool.execute`. + */ +const fakeMetaTools = ( + names: string[], + respond: (tool: StackOneMcpTool, args: JsonObject) => JsonObject | Promise = () => ({ + data: {}, + }), +) => { + listMock.mockImplementation(async ({ headers }) => + names + .filter((name) => + name + .replace(/_(search_actions|execute_action)$/, '') + .endsWith(`_${headers['x-account-id']}`), + ) + .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); + }); + return calls; +}; + +/** Serve the real mock MCP app, recording every tools/call as it reached the wire. */ +const serveMock = ( + options: { + accountTools?: Parameters[0]['accountTools']; + submitFeedback?: boolean; + } = {}, +) => { + const calls: RecordedToolCall[] = []; + let rpcRequests = 0; + const app = createMcpApp({ + accountTools: options.accountTools ?? { default: [], acc1: accountMcpTools.acc1 }, + submitFeedback: options.submitFeedback, + onToolCall: (call) => calls.push(call), + }); + server.use( + http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request)), + http.post(`${TEST_BASE_URL}/actions/rpc`, () => { + rpcRequests += 1; + return HttpResponse.json({ data: {} }); + }), + ); + return { calls, rpcRequests: () => rpcRequests }; +}; + +describe('search()', () => { + it('finds actions with nothing but an API key', async () => { + serveMock(); + const actions = await newToolSet().search('list items'); + expect(actions.map((action) => action.action_id)).toEqual(['mock_list_items']); + }); + + it('asks the search_execute catalog, passing top_k through', async () => { + const { calls } = serveMock(); + + await newToolSet().search('list items', { topK: 7 }); + + expect(calls).toEqual([ + { + accountId: 'default', + toolMode: 'search_execute', + name: 'mock_default_search_actions', + arguments: { query: 'list items', top_k: 7 }, + }, + ]); + }); + + // Contract §4: each hit carries the session_id of the search that produced it. + it('copies the search session_id onto every hit', async () => { + serveMock(); + const [hit] = await newToolSet().search('list items'); + expect(hit?.session_id).toBe(MOCK_SEARCH_SESSION_ID); + }); + + it('omits session_id when the server issues none', async () => { + fakeMetaTools(['a_acc1_search_actions'], () => ({ + actions: [{ action_id: 'a_x' }], + session_id: '', + })); + const [hit] = await newToolSet({ accountId: 'acc1' }).search('x'); + expect(hit).toEqual({ action_id: 'a_x' }); + }); + + it('ranks results across connectors rather than concatenating them, tolerating bad scores', async () => { + const perConnector: Record = { + a_acc1_search_actions: [ + { action_id: 'a_low', similarity_score: 0.2 }, + { action_id: 'a_bad', similarity_score: '0.99' }, + ], + b_acc2_search_actions: [{ action_id: 'b_high', similarity_score: 0.9 }], + }; + fakeMetaTools(Object.keys(perConnector), (tool) => ({ + actions: perConnector[tool.name] ?? [], + session_id: `session-${tool.name}`, + })); + + const actions = await newToolSet({ accountIds: ['acc1', 'acc2'] }).search('x'); + + expect(actions.map((action) => action.action_id)).toEqual(['b_high', 'a_low', 'a_bad']); + // Each hit keeps the session of the connector search that found it. + expect(actions[0]?.session_id).toBe('session-b_acc2_search_actions'); + expect(actions[1]?.session_id).toBe('session-a_acc1_search_actions'); + }); + + it('keeps the connectors that answer when one fails', async () => { + fakeMetaTools(['a_acc1_search_actions', 'b_acc1_search_actions'], (tool) => { + if (tool.name.startsWith('b_')) { + throw new ToolSetLoadError('b is down'); + } + return { actions: [{ action_id: 'a_x', similarity_score: 1 }] }; + }); + + const actions = await newToolSet({ accountId: 'acc1' }).search('x'); + + expect(actions.map((action) => action.action_id)).toEqual(['a_x']); + expect(String(warnSpy.mock.calls[0]?.[0])).toContain( + 'Skipping connector that failed to search — b_acc1_search_actions: b is down', + ); + }); + + it('fails when every connector fails', async () => { + fakeMetaTools(['a_acc1_search_actions'], () => { + throw new Error('boom'); + }); + await expect(newToolSet({ accountId: 'acc1' }).search('x')).rejects.toThrow( + new ToolSetLoadError('No connector returned results. a_acc1_search_actions: boom'), + ); + }); + + it('returns nothing when no connector is linked', async () => { + fakeMetaTools([]); + expect(await newToolSet({ accountId: 'acc1' }).search('x')).toEqual([]); + }); + + it.each([0, -1, 51, 1000, 1.5, Number.NaN, '10', null, true])( + 'rejects topK=%j before any round trip', + async (topK) => { + await expect( + newToolSet({ accountId: 'acc1' }).search('x', { topK: topK as never }), + ).rejects.toThrow(/topK must be an integer between 1 and 50/); + expect(listMock).not.toHaveBeenCalled(); + }, + ); + + it.each([1, 50])('accepts topK=%i', async (topK) => { + fakeMetaTools([]); + await expect(newToolSet({ accountId: 'acc1' }).search('x', { topK })).resolves.toEqual([]); + }); + + it('uses the meta tools even when the toolset lists individual tools', async () => { + serveMock(); + const toolset = newToolSet({ accountId: 'acc1' }); + + await toolset.search('x'); + await toolset.fetchTools(); + + expect(listMock.mock.calls.map(([request]) => request.endpoint.split('?')[1])).toEqual([ + 'param-style=flat_prefixed&tool-mode=search_execute', + 'param-style=flat_prefixed', + ]); + }); +}); + +describe('execute()', () => { + it('runs a searched action', async () => { + serveMock(); + const toolset = newToolSet(); + const [hit] = await toolset.search('list items'); + + expect(await toolset.execute(hit?.action_id ?? '')).toMatchObject({ data: { nodes: [] } }); + }); + + it('passes the nested envelope through verbatim', async () => { + serveMock(); + const toolset = newToolSet(); + 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); + + expect(result.echoed_query).toEqual({ page_size: 25 }); + }); + + // Contract §5: session_id is forwarded as a top-level argument when given, never otherwise, + // and action_id stays pinned last. + it('forwards sessionId as a top-level session_id, action_id last', async () => { + const { calls } = serveMock(); + + await newToolSet().execute( + 'mock_list_items', + { query: { page_size: 1 } }, + { sessionId: MOCK_SEARCH_SESSION_ID }, + ); + + const [call] = calls; + expect(call?.name).toBe('mock_default_execute_action'); + expect(call?.arguments).toEqual({ + query: { page_size: 1 }, + session_id: MOCK_SEARCH_SESSION_ID, + action_id: 'mock_list_items', + }); + expect(Object.keys(call?.arguments ?? {}).at(-1)).toBe('action_id'); + }); + + it('sends no session_id when none is given', async () => { + const { calls } = serveMock(); + await newToolSet().execute('mock_list_items'); + expect(calls[0]?.arguments).toEqual({ action_id: 'mock_list_items' }); + }); + + it('lets sessionId win over a session_id in the arguments', async () => { + const { calls } = serveMock(); + await newToolSet().execute( + 'mock_list_items', + { session_id: 'model-supplied' }, + { sessionId: 'real' }, + ); + expect(calls[0]?.arguments.session_id).toBe('real'); + }); + + // A prompt-injected call must not be able to swap the action a host app pinned. + it('pins the caller’s action_id over one in the arguments', async () => { + const { calls } = serveMock(); + + await newToolSet().execute('mock_list_items', { action_id: 'mock_delete_everything' }); + + expect(calls[0]?.arguments).toEqual({ action_id: 'mock_list_items' }); + }); + + it('drops model-supplied credentials in the envelope', async () => { + const { calls } = serveMock(); + + await newToolSet().execute('mock_list_items', { + headers: { Authorization: 'Bearer stolen', 'x-account-id': 'victim' }, + }); + + expect(calls[0]?.arguments.headers).toEqual({}); + }); + + it('raises on an isError result rather than returning it as data', async () => { + serveMock(); + const error = (await newToolSet() + .execute('mock_not_a_real_action') + .catch((caught: unknown) => caught)) as StackOneAPIError; + + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.message).toContain('Unknown action mock_not_a_real_action'); + expect(error.statusCode).toBe(404); + }); + + it('unwraps the meta tool’s { isError, result } envelope', async () => { + fakeMetaTools(['linear_acc1_execute_action'], () => ({ + isError: false, + result: { data: { nodes: [1, 2] } }, + })); + expect(await newToolSet({ accountId: 'acc1' }).execute('linear_list_issues')).toEqual({ + data: { nodes: [1, 2] }, + }); + }); + + it('wraps a non-object meta tool result', async () => { + fakeMetaTools(['linear_acc1_execute_action'], () => ({ isError: false, result: [1] })); + expect(await newToolSet({ accountId: 'acc1' }).execute('linear_list_issues')).toEqual({ + result: [1], + }); + }); + + it('routes an account id containing underscores by identity', async () => { + const calls = fakeMetaTools(['linear_acc_1_execute_action']); + await newToolSet({ accountId: 'acc_1' }).execute('linear_list_issues'); + expect(calls[0]?.tool).toBe('linear_acc_1_execute_action'); + }); + + it('routes to the longest matching connector', async () => { + const calls = fakeMetaTools([ + 'browser_acc1_execute_action', + 'browser_linkedin_acc2_execute_action', + ]); + await newToolSet({ accountIds: ['acc1', 'acc2'] }).execute('browser_linkedin_search_people'); + expect(calls[0]?.tool).toBe('browser_linkedin_acc2_execute_action'); + }); + + it('warns when the same connector is linked twice, and uses the first', async () => { + const calls = fakeMetaTools(['linear_acc1_execute_action', 'linear_acc2_execute_action']); + + await newToolSet({ accountIds: ['acc2', 'acc1'] }).execute('linear_list_issues'); + + expect(calls[0]?.tool).toBe('linear_acc1_execute_action'); + expect(String(warnSpy.mock.calls[0]?.[0])).toContain( + '"linear_list_issues" matches 2 connectors (linear_acc1_execute_action, linear_acc2_execute_action)', + ); + }); + + it('matches the connector case-insensitively', async () => { + const calls = fakeMetaTools(['Linear_acc1_execute_action']); + await newToolSet({ accountId: 'acc1' }).execute('LINEAR_list_issues'); + expect(calls[0]?.tool).toBe('Linear_acc1_execute_action'); + }); + + it('explains an action no connector serves', async () => { + fakeMetaTools(['linear_acc1_execute_action']); + await expect(newToolSet({ accountId: 'acc1' }).execute('jira_list_issues')).rejects.toThrow( + new ToolSetLoadError( + 'No connector found for "jira_list_issues". Use search() to discover valid action ids.', + ), + ); + }); + + it.each([ + [ + 'an empty action id', + () => newToolSet({ accountId: 'acc1' }).execute(''), + /actionId must be a non-empty string/, + ], + [ + 'array arguments', + () => newToolSet({ accountId: 'acc1' }).execute('x_y', [1, 2] as never), + /arguments must be a JSON object, got array/, + ], + [ + 'a string sessionId that is empty', + () => newToolSet({ accountId: 'acc1' }).execute('x_y', {}, { sessionId: '' }), + /sessionId must be a non-empty string/, + ], + ])('rejects %s before any round trip', async (_name, act, message) => { + await expect(act()).rejects.toThrow(message); + await expect(act()).rejects.toBeInstanceOf(ToolSetConfigError); + expect(listMock).not.toHaveBeenCalled(); + }); +}); + +describe('submitFeedback()', () => { + // Contract §6: snake_case wire arguments, optional keys omitted rather than null. + it('calls stackone_submit_feedback over tools/call with snake_case arguments', async () => { + const { calls, rpcRequests } = serveMock({ submitFeedback: true }); + + const result = await newToolSet({ accountId: 'acc1' }).submitFeedback({ + rating: 'negative', + toolNames: ['mock_list_items'], + feedback: 'Needed two calls', + category: 'execute', + sessionId: MOCK_SEARCH_SESSION_ID, + source: 'user', + }); + + expect(result).toMatchObject({ + message: 'Feedback recorded', + session_id: MOCK_SEARCH_SESSION_ID, + }); + expect(calls).toEqual([ + { + accountId: 'acc1', + toolMode: undefined, + name: 'stackone_submit_feedback', + arguments: { + rating: 'negative', + tool_names: ['mock_list_items'], + feedback: 'Needed two calls', + category: 'execute', + session_id: MOCK_SEARCH_SESSION_ID, + source: 'user', + }, + }, + ]); + expect(rpcRequests()).toBe(0); + }); + + it('omits unset optional fields and defaults source to model', async () => { + const { calls } = serveMock({ submitFeedback: true }); + + await newToolSet({ accountId: 'acc1' }).submitFeedback({ + rating: 'positive', + toolNames: ['a'], + feedback: undefined, + sessionId: undefined, + }); + + expect(calls[0]?.arguments).toEqual({ rating: 'positive', tool_names: ['a'], source: 'model' }); + }); + + it('works from a search_execute toolset, once across accounts', async () => { + const { calls } = serveMock({ + accountTools: { acc1: [], acc2: [] }, + submitFeedback: true, + }); + + await newToolSet({ accountIds: ['acc1', 'acc2'], toolMode: 'search_execute' }).submitFeedback({ + rating: 'neutral', + toolNames: ['x'], + }); + + expect(calls.map((call) => call.name)).toEqual(['stackone_submit_feedback']); + }); + + it('explains that feedback is not enabled when the server does not serve the tool', async () => { + serveMock({ submitFeedback: false }); + const error = await newToolSet({ accountId: 'acc1' }) + .submitFeedback({ rating: 'positive', toolNames: ['a'] }) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolSetLoadError); + expect((error as Error).message).toBe( + 'The server did not serve stackone_submit_feedback: feedback is not enabled for this project.', + ); + }); + + it('refuses a string where toolNames expects a list', async () => { + await expect( + newToolSet({ accountId: 'acc1' }).submitFeedback({ + rating: 'positive', + toolNames: 'a' as never, + }), + ).rejects.toThrow( + /toolNames must be an array of tool names, not a string. Did you mean \["a"\]\?/, + ); + }); + + it('links search, execute and feedback with one session id', async () => { + const { calls } = serveMock({ submitFeedback: true }); + const toolset = newToolSet(); + + const [hit] = await toolset.search('list items'); + await toolset.execute(hit?.action_id ?? '', {}, { sessionId: hit?.session_id }); + await toolset.submitFeedback({ + rating: 'positive', + toolNames: [hit?.action_id ?? ''], + sessionId: hit?.session_id, + }); + + expect(calls.map((call) => [call.name, call.arguments.session_id])).toEqual([ + ['mock_default_search_actions', undefined], + ['mock_default_execute_action', MOCK_SEARCH_SESSION_ID], + ['stackone_submit_feedback', MOCK_SEARCH_SESSION_ID], + ]); + }); +}); + +it('keeps every search/execute error inside the StackOneError hierarchy', async () => { + await expect(newToolSet({ accountId: 'acc1' }).search('x', { topK: 0 })).rejects.toBeInstanceOf( + StackOneError, + ); + serveMock(); + await expect(newToolSet().execute('mock_nope')).rejects.toBeInstanceOf(StackOneError); +}); diff --git a/src/toolsets.ts b/src/toolsets.ts index 36ed368f..fa1b534b 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -3,6 +3,7 @@ import { DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, MAX_CONCURRENCY, + MAX_TOP_K, MCP_PARAM_STYLE, SUBMIT_FEEDBACK_TOOL_NAME, } from './consts'; @@ -11,7 +12,15 @@ import { type McpToolDefinition, listMcpTools } from './mcp-client'; import { RpcClient } from './rpc-client'; import { cloneJson, toolParametersFromInputSchema } from './schema'; import { StackOneMcpTool, StackOneRpcTool, type StackOneTool, Tools } from './tool'; -import type { StackOneAccount, ToolMode } from './types'; +import type { + FeedbackCategory, + FeedbackRating, + FeedbackSource, + JsonObject, + SearchResult, + StackOneAccount, + ToolMode, +} from './types'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; @@ -124,6 +133,49 @@ export interface FetchToolsOptions { mode?: ToolMode | null; } +/** + * Options for {@link StackOneToolSet.search}. + */ +export interface SearchOptions { + /** Maximum results per connector, 1–50. Default: 10. */ + topK?: number; + /** Restrict to these accounts. Defaults to the toolset's accounts, then every active one. */ + accountIds?: string[]; +} + +/** + * Options for {@link StackOneToolSet.execute}. + */ +export interface ExecuteActionOptions { + /** + * The `session_id` a {@link StackOneToolSet.search} hit carries. Passing it links this call to + * that search server-side. Sent only when given. + */ + sessionId?: string; + /** Restrict routing to these accounts. Defaults as for {@link StackOneToolSet.search}. */ + accountIds?: string[]; +} + +/** + * Options for {@link StackOneToolSet.submitFeedback}. + */ +export interface SubmitFeedbackOptions { + /** The verdict: `'positive'`, `'negative'` or `'neutral'`. */ + rating: FeedbackRating; + /** The tools or action ids the feedback is about. */ + toolNames: string[]; + /** An optional one-line reason. */ + feedback?: string; + /** What the feedback is about, e.g. `'search'` or `'execute'`. */ + category?: FeedbackCategory; + /** The session to attach the feedback to — the `session_id` of a search hit. */ + sessionId?: string; + /** Who produced the feedback. Default: `'model'`. */ + source?: FeedbackSource; + /** Accounts to list the tool through. Defaults as for {@link StackOneToolSet.fetchTools}. */ + accountIds?: string[]; +} + /** One served tool, with the account it was listed for. What the catalog cache holds. */ interface CatalogEntry { definition: McpToolDefinition; @@ -190,6 +242,32 @@ function matchGlob(value: string, pattern: string): boolean { return new RegExp(`^${source}$`, 's').test(value); } +const isPlainObject = (value: unknown): value is JsonObject => + typeof value === 'object' && value !== null && !Array.isArray(value); + +/** + * The connector a meta tool belongs to: its name minus the account id and the suffix. + * + * The account id is stripped by identity, not by splitting on the last underscore. Account ids + * are nanoid-shaped and nanoid's alphabet includes `_`, so splitting turned + * `mock_acc_1_execute_action` into connector `mock_acc` and made every action on that account + * unroutable — with an error blaming the caller's action id. + */ +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}`)) { + stem = stem.slice(0, -(account.length + 1)); + } + return stem.toLowerCase(); +} + +/** A search hit's score, or 0 for one without a numeric score, so it sorts last. */ +function scoreOf(action: SearchResult): number { + const score = action.similarity_score; + return typeof score === 'number' && !Number.isNaN(score) ? score : 0; +} + const assertAccountIdList = (accountIds: unknown, parameter: string): void => { if (accountIds === undefined) { return; @@ -611,6 +689,228 @@ export class StackOneToolSet { }); } } + + /** + * The server's per-connector meta tools, whatever this toolset's own mode. + * + * The mode is passed down rather than switched on the instance, so a concurrent + * `fetchTools()` can never read the switched mode and cache meta tools under the wrong key. + */ + async #metaTools(suffix: string, accountIds: string[] | undefined): Promise { + const tools = await this.fetchTools({ accountIds, mode: 'search_execute' }); + return tools.getStackOneTools().filter((tool) => tool.name.endsWith(suffix)); + } + + /** + * Find actions matching a natural-language query. + * + * Searches every linked connector and ranks the results together, so a catalog of hundreds of + * tools never has to fit in a model's context. A connector that fails to search is skipped + * with a warning, unless they all fail. + * + * @param query What you want to do, e.g. "list recent comments". + * @returns Actions carrying at least `action_id` and `description`, best first, each with the + * `session_id` of the search that found it when the server issued one. Pass it to + * {@link execute} and {@link submitFeedback} to link the calls. + * @throws ToolSetConfigError If `topK` is not an integer between 1 and 50. + * @throws ToolSetLoadError If every connector fails. + */ + 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}`); + } + + 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 that produced it. + const sessionId = found.session_id; + if (typeof sessionId !== 'string' || !sessionId) { + return actions; + } + return actions.map((action) => ({ ...action, session_id: sessionId })); + }; + + // 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); + const results: SearchResult[] = []; + const failures: string[] = []; + settled.forEach((outcome, index) => { + if (outcome.status === 'fulfilled') { + results.push(...outcome.value); + } else { + failures.push(`${tools[index]?.name}: ${describeError(outcome.reason)}`); + } + }); + if (failures.length > 0 && results.length === 0) { + throw new ToolSetLoadError(`No connector returned results. ${failures.join(' | ')}`); + } + for (const failure of failures) { + warn(`Skipping connector that failed to search — ${failure}`); + } + + // Concatenating per-connector results would leave them grouped by connector, so results[0] + // 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. + return results.sort((left, right) => scoreOf(right) - scoreOf(left)); + } + + /** + * Execute an action by id, as returned by {@link search}. + * + * Always runs through the connector's `*_execute_action` meta tool, so `args` is the nested + * envelope every action's `example_request` shows — `{ query: {...}, path: {...}, body: {...} }`. + * The flat, prefixed form belongs to `fetchTools()` tools, whose own served schema names the + * keys. The connector is the longest one whose name prefixes `actionId`, and `actionId` is + * pinned last, so a model-supplied `action_id` in `args` cannot replace it. + * + * @param actionId The action to run, e.g. `linear_list_issues`. + * @param args The action's arguments. + * @param options.sessionId The `session_id` a search hit carries, to link this call to it. + * @returns The action's result. + * @throws ToolSetConfigError If the arguments are malformed. + * @throws ToolSetLoadError If no linked connector serves the action. + * @throws StackOneAPIError If the action fails. + */ + 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 ${Array.isArray(args) ? 'array' : args === null ? 'null' : typeof args}`, + ); + } + const { sessionId } = options; + if (sessionId !== undefined && (typeof sessionId !== 'string' || !sessionId)) { + throw new ToolSetConfigError( + `sessionId must be a non-empty string, got ${JSON.stringify(sessionId)}`, + ); + } + + const suffix = '_execute_action'; + const lowered = actionId.toLowerCase(); + const matches = (await this.#metaTools(suffix, options.accountIds)).filter((tool) => + lowered.startsWith(`${connectorOf(tool, suffix)}_`), + ); + if (matches.length === 0) { + throw new ToolSetLoadError( + `No connector found for "${actionId}". Use search() to discover valid action ids.`, + ); + } + + // Longest connector wins: with both `browser` and `browser_linkedin` linked, the first + // 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); + const [tool] = finalists as [StackOneTool, ...StackOneTool[]]; + if (finalists.length > 1) { + // The same provider linked twice. Picking one silently would run the action against an + // account the caller never chose. + warn( + `"${actionId}" matches ${finalists.length} connectors (${finalists.map((t) => t.name).join(', ')}); using ${tool.name}. Pass accountIds to choose.`, + ); + } + + // action_id LAST, deleted first so it is last in key order too. Spreading the arguments + // over it would let a model-supplied "action_id" replace the action the caller pinned — the + // exact thing a host app pins it for. session_id only when given: the served schema makes + // it an optional string, so an absent key is valid and a null is not. + const callArguments: JsonObject = { ...args }; + delete callArguments.action_id; + if (sessionId !== undefined) { + delete callArguments.session_id; + callArguments.session_id = sessionId; + } + callArguments.action_id = actionId; + + const result = await tool.execute(callArguments); + // The meta tool wraps its payload as { isError, result }, but an isError response has + // already raised by this point — so the flag could only ever be false, and the wrapper would + // just make this return a different shape from tool.execute() for the same action. + const keys = Object.keys(result); + if (keys.length === 2 && keys.includes('isError') && keys.includes('result')) { + const inner = result.result; + return isPlainObject(inner) ? inner : { result: inner ?? null }; + } + return result; + } + + /** + * Record a verdict on how well the tools served this session, through the server's + * `stackone_submit_feedback` tool. + * + * The tool is found in the served catalog, never built here: the server serves it only when + * feedback is enabled for the project, and a client-side stand-in would report success for + * feedback that went nowhere. Unset optional fields are omitted, never sent as null. + * + * @example + * ```typescript + * const [hit] = await toolset.search('list recent comments'); + * await toolset.execute(hit.action_id, {}, { sessionId: hit.session_id }); + * await toolset.submitFeedback({ + * rating: 'positive', + * toolNames: [hit.action_id], + * sessionId: hit.session_id, + * }); + * ``` + * + * @throws ToolSetConfigError If `toolNames` is not a list. + * @throws ToolSetLoadError If feedback is not enabled for this project. + */ + async submitFeedback(options: SubmitFeedbackOptions): Promise { + const { rating, toolNames, feedback, category, sessionId, source = 'model' } = options; + if (typeof (toolNames as unknown) === 'string') { + throw new ToolSetConfigError( + `toolNames must be an array of tool names, not a string. Did you mean ["${String(toolNames)}"]?`, + ); + } + if (!Array.isArray(toolNames)) { + throw new ToolSetConfigError('toolNames must be an array of tool names'); + } + + const tool = (await this.fetchTools({ accountIds: options.accountIds })).getTool( + SUBMIT_FEEDBACK_TOOL_NAME, + ); + if (!tool) { + 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, source }; + for (const [key, value] of Object.entries(optional)) { + if (value !== undefined && value !== null) { + args[key] = value; + } + } + return tool.execute(args); + } } /** diff --git a/src/types.ts b/src/types.ts index 7f629b93..f04ad30a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -210,3 +210,25 @@ export type StackOneAccount = JsonObject & { provider?: string; status?: string; }; + +/** + * One action a `search()` found. Carries at least `action_id` and `description`, plus whatever + * else the server returns for it (`similarity_score`, `input_schema`, `example_request`, …). + */ +export type SearchResult = JsonObject & { + action_id: string; + /** + * The `session_id` of the search that produced this hit, when the server issued one. Pass it + * to `execute()` and `submitFeedback()` to link those calls to this search. + */ + session_id?: string; +}; + +/** The verdict `submitFeedback()` records. */ +export type FeedbackRating = 'positive' | 'negative' | 'neutral'; + +/** Who produced the feedback. */ +export type FeedbackSource = 'model' | 'user' | 'system'; + +/** What the feedback is about. */ +export type FeedbackCategory = 'search' | 'execute' | 'defender' | 'connection' | 'general'; From cf6501bf301d042d2559877ac427c990aeb6bf2d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:49:25 +0100 Subject: [PATCH 013/151] feat(tools): add executeOpenAIToolCalls() The counterpart to `toOpenAI()`, ported from the Python SDK's `execute_openai_tool_calls`: run a Chat Completions response's tool calls and get back the `tool` messages to send to the model, in order. A failed call does not throw. The error, and the server's response body when there is one, become the message content, so the model can read why and retry; an unknown tool or a non-function call is reported the same way. Errors that are not the SDK's still propagate. File bytes are base64-encoded rather than serialised as a byte array, as the Claude Agent SDK handler now does too. --- src/tool.test.ts | 124 ++++++++++++++++++++++++++++++++++++++++++++++- src/tool.ts | 87 ++++++++++++++++++++++++++++++++- 2 files changed, 209 insertions(+), 2 deletions(-) diff --git a/src/tool.test.ts b/src/tool.test.ts index 99724dc6..020a85de 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -6,7 +6,7 @@ import { server } from '../mocks/node'; import { RpcClient } from './rpc-client'; import { toolParametersFromInputSchema } from './schema'; import { BaseTool, StackOneMcpTool, StackOneRpcTool, StackOneTool, Tools } from './tool'; -import type { AISDKToolResult, JSONSchema, ToolParameters } from './types'; +import type { AISDKToolResult, JsonObject, JSONSchema, ToolParameters } from './types'; import { isBinaryDownloadResult } from './utils/binary-response'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; @@ -646,3 +646,125 @@ describe('ToolParameters typing', () => { expect(parameters.type).toBe('object'); }); }); + +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 }, + }); + + it('runs each call and pairs its result with the call id', async () => { + const { tools, seen } = toolsWith(async () => ({ data: { n: 1 } })); + + const messages = await tools.executeOpenAIToolCalls([ + call('linear_list_issues', '{"body_variables": {}}'), + ]); + + expect(messages).toEqual([ + { role: 'tool', tool_call_id: 'call_1', content: '{"data":{"n":1}}' }, + ]); + expect(seen).toEqual(['{"body_variables": {}}']); + }); + + it('keeps the order of several calls', async () => { + const { tools } = toolsWith(async (args) => ({ echoed: args as string })); + + const messages = await tools.executeOpenAIToolCalls([ + call('linear_list_issues', '{"a":1}', 'c1'), + call('linear_list_issues', '{"a":2}', 'c2'), + ]); + + expect(messages.map((message) => message.tool_call_id)).toEqual(['c1', 'c2']); + }); + + it('accepts plain objects without a type and with object arguments', async () => { + const { tools, seen } = toolsWith(async () => ({ ok: true })); + await tools.executeOpenAIToolCalls([ + { id: 'c', function: { name: 'linear_list_issues', arguments: { a: 1 } } }, + ]); + expect(seen).toEqual([{ a: 1 }]); + }); + + it('reports a failed call to the model instead of throwing, with the response body', async () => { + const { tools } = toolsWith(async () => { + throw new StackOneAPIError('400 Bad Request: path.id is missing', 400, { + message: 'path.id is missing', + }); + }); + + const [message] = await tools.executeOpenAIToolCalls([call('linear_list_issues')]); + + expect(JSON.parse(message?.content as string)).toEqual({ + error: '400 Bad Request: path.id is missing', + response_body: { message: 'path.id is missing' }, + }); + }); + + it('reports malformed arguments the same way', async () => { + const tool = new StackOneRpcTool({ + name: 'linear_list_issues', + description: '', + parameters: { type: 'object', properties: {} }, + client: new RpcClient({ baseUrl: TEST_BASE_URL, apiKey: 'k', timeout: 1_000 }), + accountId: 'acc1', + }); + 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/); + }); + + 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({ + error: 'Unknown tool "invented_tool"', + }); + }); + + it('reports a non-function tool call rather than throwing', async () => { + const { tools } = toolsWith(async () => ({})); + const [message] = await tools.executeOpenAIToolCalls([ + { id: 'c', type: 'custom', custom: { name: 'linear_list_issues', input: '' } }, + ]); + expect(JSON.parse(message?.content as string)).toEqual({ + error: 'Unsupported tool call type "custom"', + }); + }); + + it('serialises file bytes as base64 instead of a byte array', async () => { + 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({ + content: Buffer.from('%PDF-1.4').toString('base64'), + }); + }); + + it('rethrows an error that is not the SDK’s', async () => { + const { tools } = toolsWith(async () => { + throw new TypeError('programming error'); + }); + await expect(tools.executeOpenAIToolCalls([call('linear_list_issues')])).rejects.toThrow( + TypeError, + ); + }); + + it('returns no messages for no tool calls', async () => { + const { tools } = toolsWith(async () => ({})); + expect(await tools.executeOpenAIToolCalls(undefined)).toEqual([]); + expect(await tools.executeOpenAIToolCalls(null)).toEqual([]); + }); +}); diff --git a/src/tool.ts b/src/tool.ts index 11c6d608..b66302c4 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -1,7 +1,11 @@ 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 { ChatCompletionFunctionTool } from 'openai/resources/chat/completions'; +import type { + ChatCompletionFunctionTool, + ChatCompletionMessageToolCall, + ChatCompletionToolMessageParam, +} from 'openai/resources/chat/completions'; import type { FunctionTool as OpenAIResponsesFunctionTool } from 'openai/resources/responses/responses'; import type { OverrideProperties } from 'type-fest'; import { peerDependencies } from '../package.json'; @@ -23,6 +27,7 @@ import type { ToolExecution, ToolParameters, } from './types'; +import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { serializeToolResult } from './utils/serialize'; import { tryImport } from './utils/try-import'; @@ -523,6 +528,38 @@ export class StackOneMcpTool extends StackOneTool { } } +/** + * A Chat Completions tool call: the `openai` package's own object, or the same shape as a plain + * object (for example one read back from storage). + */ +type OpenAIToolCall = + | ChatCompletionMessageToolCall + | { + id: string; + type?: string; + function?: { name: string; arguments?: string | JsonObject | null }; + }; + +/** Pull the id, name and arguments out of a tool call, or say why it cannot be run. */ +function readOpenAIToolCall(call: OpenAIToolCall): { + id: string; + name: string; + args: string | JsonObject; + unsupported?: string; +} { + const id = String(call.id ?? ''); + if (!('function' in call) || !call.function) { + return { + id, + name: '', + args: {}, + unsupported: `Unsupported tool call type "${String(call.type)}"`, + }; + } + const { name, arguments: args } = call.function; + return { id, name: String(name), args: args || {} }; +} + /** * Collection of tools with utility methods */ @@ -591,6 +628,54 @@ export class Tools implements Iterable { return this.tools.map((tool) => tool.toOpenAI()); } + /** + * Run a Chat Completions response's tool calls and return the `tool` messages to send back. + * + * The counterpart to {@link toOpenAI}: that turns these tools into what OpenAI accepts, this + * turns what OpenAI returns back into messages for it. Append the assistant message first, + * then these, in order: + * + * ```typescript + * const message = response.choices[0].message; + * messages.push(message, ...(await tools.executeOpenAIToolCalls(message.tool_calls))); + * ``` + * + * A failed call does not throw. Its error — with the server's response body, when there is + * one — becomes the tool message's content, so the model can read why and retry. A call to a + * tool that is not in this collection is reported the same way. Calls run one at a time, in + * order. File bytes in a result are base64-encoded. + */ + async executeOpenAIToolCalls( + toolCalls: readonly OpenAIToolCall[] | null | undefined, + ): Promise { + 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 "${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 } : {}), + }; + } + } + messages.push({ role: 'tool', tool_call_id: id, content: serializeToolResult(result) }); + } + return messages; + } + /** * Convert all tools to Anthropic format * @see https://docs.anthropic.com/en/docs/build-with-claude/tool-use From 17c589c5488858c046855d25008e11b268aaaf92 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:52:34 +0100 Subject: [PATCH 014/151] docs: document search/execute, feedback and the pass-through schema - Add a search-and-execute example (accounts, ranked search, input schema, execute with the hit's session id, submitFeedback) and a test that runs the real example file against the mock API with nothing but an API key. - Complete the OpenAI example's tool-call loop with `executeOpenAIToolCalls()`, and show account discovery in the auth-management example. - README: lead with search/execute; document account discovery and `fetchAccounts()`, tool modes, feedback, what each adapter does to the served schema (including strict `additionalProperties: false`), the header allowlist, the error hierarchy, timeouts, safe download names and the new `dryRun` shape. Fix the `Tools#setAccountId` snippet, which never existed, and drop `zod` from the install line now it is not a peer. - Remove stale references left by the search removal: the Orama skill in CLAUDE.md and flake.nix, and `search-tools` in .env.example, which also now marks STACKONE_ACCOUNT_ID optional. --- .env.example | 4 +- CLAUDE.md | 7 +- README.md | 189 +++++++++++++++++----- examples/README.md | 12 +- examples/auth-management.ts | 19 ++- examples/openai-integration.ts | 43 +++-- examples/search-and-execute.ts | 90 +++++++++++ flake.nix | 1 - tests/examples/openai-integration.test.ts | 8 + tests/examples/search-and-execute.test.ts | 68 ++++++++ 10 files changed, 376 insertions(+), 65 deletions(-) create mode 100644 examples/search-and-execute.ts create mode 100644 tests/examples/search-and-execute.test.ts diff --git a/.env.example b/.env.example index ba48917c..5c5cac42 100644 --- a/.env.example +++ b/.env.example @@ -1,8 +1,10 @@ # Required for all examples STACKONE_API_KEY=your-stackone-api-key + +# Optional: without it, the SDK uses every active account linked to the API key STACKONE_ACCOUNT_ID=your-account-id -# Required for OpenAI examples (openai-integration, openai-responses-integration, search-tools) +# Required for OpenAI examples (openai-integration, openai-responses-integration, ai-sdk-integration) OPENAI_API_KEY=your-openai-api-key # Required for Anthropic examples (anthropic-integration, claude-agent-sdk-integration) diff --git a/CLAUDE.md b/CLAUDE.md index 060eaf49..014d16ab 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,7 +22,6 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Available Skills -| Skill | Usage | Description | -| --------------------- | --------------------------- | -------------------------------------------------- | -| **orama-integration** | N/A | Integrating with Orama search/indexing | -| **release-please** | `/release-please ` | Trigger a release-please PR for a specific version | +| Skill | Usage | Description | +| ------------------ | --------------------------- | -------------------------------------------------- | +| **release-please** | `/release-please ` | Trigger a release-please PR for a specific version | diff --git a/README.md b/README.md index b479dc79..76d9a3f8 100644 --- a/README.md +++ b/README.md @@ -8,37 +8,47 @@ ## StackOneToolSet -The StackOne AI SDK provides the `StackOneToolSet` class, which fetches tools dynamically from StackOne's MCP (Model Context Protocol) endpoint. This ensures you always have access to the latest tool definitions. +The StackOne AI SDK provides the `StackOneToolSet` class, a thin client over StackOne's MCP (Model Context Protocol) endpoint. It lists the tools your linked accounts serve and executes them, handing your model each tool's schema exactly as the server served it. + +It offers two ways in: + +- **`search()` and `execute()`** — find an action in natural language and run it by id. A catalog of hundreds of tools never has to fit in a model's context. This is the recommended way to start. +- **`fetchTools()`** — list the catalog as tools and hand them to your framework (OpenAI, Anthropic, the AI SDK, the Claude Agent SDK, …). ## Installation ```bash # Using npm -npm install @stackone/ai zod +npm install @stackone/ai # Using yarn -yarn add @stackone/ai zod +yarn add @stackone/ai # Using pnpm -pnpm add @stackone/ai zod +pnpm add @stackone/ai # Using bun -bun add @stackone/ai zod +bun add @stackone/ai ``` -> **Note:** `zod` is a peer dependency required for AI SDK integrations and internal schema validation. Version `>=3.25.0 <5` is supported. +Framework packages (`openai`, `@anthropic-ai/sdk`, `ai`, `@anthropic-ai/claude-agent-sdk`) are optional peer dependencies: install the ones you use. ## Usage ```typescript import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment +// Reads STACKONE_API_KEY from the environment. No account id needed. const toolset = new StackOneToolSet(); -const tools = await toolset.fetchTools(); -const employeeTool = tools.getTool('workday_list_workers'); -const employees = await employeeTool.execute(); +// Find an action, then run it by id +const [best] = await toolset.search('list recent comments', { topK: 3 }); +const result = await toolset.execute(best.action_id, { query: { limit: 5 } }); + +// Or list the catalog as tools for your framework +const tools = await toolset.fetchTools({ actions: ['*_list_*'] }); +const listTool = tools.getTool('workday_list_workers'); +const workers = await listTool?.execute(); ``` ### Authentication @@ -49,11 +59,21 @@ Set the `STACKONE_API_KEY` environment variable: export STACKONE_API_KEY= ``` -or load from a .env file using your preferred environment variable library. +or load from a .env file using your preferred environment variable library, or pass `apiKey` to the constructor. The constructor throws a `ToolSetConfigError` when neither is set. + +An API key alone is enough. With no account configured, the toolset asks `GET /accounts` which accounts the key is linked to and uses the active ones. `fetchAccounts()` returns that list: + +```typescript +for (const account of await toolset.fetchAccounts()) { + console.log(account.id, account.provider, account.status); +} +``` + +> If your organisation has many linked accounts, discovery lists the catalog of every one of them. Pass explicit `accountIds` to avoid the round trips and the model context they cost. ### Account IDs -StackOne uses account IDs to identify different integrations. You can specify the account ID at different levels: +StackOne uses account IDs to identify different integrations. You can specify the account ID at different levels (a per-call `accountIds` wins, then `setAccounts()`, then the constructor's `accountIds`, then `accountId` or `STACKONE_ACCOUNT_ID`, then discovery): ```typescript import { StackOneToolSet } from '@stackone/ai'; @@ -78,11 +98,14 @@ const workdayOnly = await multiAccountToolset.fetchTools({ actions: ['workday_*'], // Only Workday tools }); -// Set directly on a tool instance -tools.setAccountId('direct-account-id'); -const currentAccountId = tools.getAccountId(); // Get the current account ID +// Rebind a single tool to another account +const tool = tools.getStackOneTool('workday_list_workers'); +tool.setAccountId('direct-account-id'); +const currentAccountId = tool.getAccountId(); ``` +Every `fetchTools()` call returns fresh tool instances, so rebinding one never affects another caller's tools. When two accounts serve a tool with the same name, `getTool()` returns the first one listed, and the SDK warns. + ## Integrations The StackOneToolSet makes it super easy to use StackOne APIs as tools in your AI applications. @@ -101,24 +124,26 @@ import { StackOneToolSet } from '@stackone/ai'; // Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment const toolset = new StackOneToolSet(); -const tools = await toolset.fetchTools(); +const tools = await toolset.fetchTools({ actions: ['workday_*'] }); +const openai = new OpenAI(); -await openai.chat.completions.create({ +const messages: OpenAI.ChatCompletionMessageParam[] = [ + { role: 'system', content: 'You are a helpful HR assistant using Workday.' }, + { role: 'user', content: 'Create a time-off request for employee id cxIQ5764hj2' }, +]; +const response = await openai.chat.completions.create({ model: 'gpt-5.1', - messages: [ - { - role: 'system', - content: 'You are a helpful HR assistant using Workday.', - }, - { - role: 'user', - content: 'Create a time-off request for employee id cxIQ5764hj2', - }, - ], + messages, tools: tools.toOpenAI(), }); + +// Run the model's tool calls and send the results back +const message = response.choices[0].message; +messages.push(message, ...(await tools.executeOpenAIToolCalls(message.tool_calls))); ``` +`executeOpenAIToolCalls()` never throws for a failed call: the error, with the server's explanation, becomes the tool message, so the model can correct itself. + [View full example](examples/openai-integration.ts) @@ -259,6 +284,60 @@ for await (const message of result) { ## Features +### Search and execute + +`search()` asks every linked connector for actions matching a natural-language query and ranks the results together, best first. `execute()` runs one by id, through the connector that serves it. + +```typescript +const actions = await toolset.search('create a time-off request', { topK: 5 }); +for (const action of actions) { + console.log(action.similarity_score, action.action_id); +} + +const [best] = actions; +// `input_schema` describes what the action accepts; `example_request` shows the shape +const result = await toolset.execute(best.action_id, best.example_request, { + sessionId: best.session_id, +}); +``` + +- `execute()` takes the nested envelope an action's `example_request` shows: `{ path, query, body }`. (Tools from `fetchTools()` take the flat, prefixed arguments their own schema names, such as `path_id`.) +- The connector is the longest one whose name prefixes the action id, so `browser_linkedin_*` actions are not routed to `browser`. +- `action_id` is always the one you pass: an `action_id` inside `args` — for example, one a prompt-injected model put there — is ignored. +- Each hit carries the `session_id` of the search that found it, when the server issued one. Pass it back as `sessionId` to link the calls together. +- `topK` is 1–50 (default 10). A connector that fails to search is skipped with a warning, unless every connector fails. + +[View full example](examples/search-and-execute.ts) + +### Feedback + +When feedback is enabled for your project, the server serves a `stackone_submit_feedback` tool alongside the others, in every tool mode. A model can call it like any other tool, and `submitFeedback()` calls it for you: + +```typescript +await toolset.submitFeedback({ + rating: 'negative', // 'positive' | 'negative' | 'neutral' + toolNames: [best.action_id], + feedback: 'Needed two calls to find the right action', + category: 'search', // optional + sessionId: best.session_id, // optional: links the feedback to that search +}); +``` + +The SDK never builds a feedback tool itself: if the server does not serve it, `submitFeedback()` throws a `ToolSetLoadError` saying feedback is not enabled for the project. + +### Tool modes + +```typescript +// One tool per action (the server default) +const toolset = new StackOneToolSet(); + +// Two meta tools per connector instead: `*_search_actions` and `*_execute_action` +const compact = new StackOneToolSet({ toolMode: 'search_execute' }); +const metaTools = await compact.fetchTools(); +``` + +`search_execute` keeps the catalog small however many accounts are linked, which suits handing the tools to a model directly. A single call can override the mode with `fetchTools({ mode })`. + ### Filtering Tools with fetchTools() You can filter tools by account IDs, providers, and action patterns: @@ -272,7 +351,7 @@ const tools = await toolset.fetchTools({ accountIds: ['account-123', 'account-456'], }); -// Filter by providers +// Filter by providers (a full, case-insensitive prefix of the tool name) const tools = await toolset.fetchTools({ providers: ['hibob', 'workday'] }); // Filter by actions with exact match @@ -280,7 +359,7 @@ const tools = await toolset.fetchTools({ actions: ['hibob_list_employees', 'hibob_create_employees'], }); -// Filter by actions with glob patterns +// Filter by actions with glob patterns (`*`, `?`, `[seq]`, `[!seq]`) const tools = await toolset.fetchTools({ actions: ['*_list_employees'] }); // Combine multiple filters @@ -297,6 +376,38 @@ This is especially useful when you want to: - Focus on specific HR/CRM/ATS providers - Get only certain types of operations (e.g., all "list" operations) +The catalog is cached per account scope and mode, so changing a filter never refetches it. Call `clearCatalogCache()` after linking or unlinking accounts. + +### Tool schemas + +`tool.toJsonSchema()` is the schema the server served, verbatim — `$schema`, `$defs`, `$ref`, `title`, `additionalProperties`, top-level `oneOf`/`anyOf`/`allOf` and every nested constraint — with the served `required` list. It is a fresh copy each call. The framework adapters start from it and change only what the provider would otherwise reject: + +| Adapter | Adjustment | +| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `toJsonSchema()` | None: lossless. | +| `toOpenAI()`, `toAnthropic()`, `toClaudeAgentSdkTool()` | A top-level `oneOf`/`anyOf`/`allOf` is folded into the root: every branch's properties become root properties, and an `allOf` branch's `required` is merged in. OpenAI also rejects a top-level `enum`/`not`, so those are dropped. | +| `toOpenAIResponses()` | As above. With `strict` (the default) the root also gets `additionalProperties: false`. OpenAI's strict mode additionally requires every property to be `required` and every nested object closed, which the SDK does not rewrite, so pass `{ strict: false }` for schemas with optional fields. | +| `toAISDK()` | As `toOpenAI()`, plus `additionalProperties: false` on the root. | + +### Headers + +A tool call can only send the headers its served schema declares, as `headers_` properties; anything else a model supplies is dropped with a warning. `Authorization`, `x-account-id` and `User-Agent` are always the SDK's own, so no tool call — and no `headers` constructor option — can replace the credential or run a call against another account. + +```typescript +// Extra headers for every request (for example, tracing) +const toolset = new StackOneToolSet({ headers: { 'X-Request-Source': 'my-agent' } }); +``` + +### Errors and timeouts + +Everything the SDK throws is a `StackOneError`: + +- `StackOneAPIError` — the API refused a request. Carries `statusCode` and `responseBody`, and its message leads with the server's own explanation (`400 Bad Request: path.id is missing`). A failed MCP `tools/call` raises one too, with the status from its payload; a dead account surfaces as a `412`. +- `ToolSetConfigError` — the toolset was configured, or called, with something it cannot use. +- `ToolSetLoadError` — the catalog, or the accounts behind it, could not be loaded. + +`timeout` (milliseconds, default 60000) bounds every MCP listing and `tools/call`, every RPC call and account discovery. + ### Custom Base URL ```typescript @@ -319,25 +430,25 @@ const tools = await toolset.fetchTools(); const employeeTool = tools.getTool('workday_list_workers'); // Use dryRun to see the request details -const dryRunResult = await employeeTool.execute({ query: { limit: 5 } }, { dryRun: true }); +const dryRunResult = await employeeTool.execute({ query_limit: 5 }, { dryRun: true }); console.log(dryRunResult); // { // url: "https://api.stackone.com/actions/rpc", // method: "POST", // headers: { ... }, -// body: "...", -// mappedParams: { ... } +// body: '{"action":"workday_list_workers","body":{},"headers":{...},"query":{"limit":5}}', +// mappedParams: { query_limit: 5 } // } ``` The `dryRun` option returns an object containing: -- `url`: The full URL with query parameters +- `url`: The RPC endpoint - `method`: The HTTP method -- `headers`: The request headers -- `body`: The request body -- `mappedParams`: The parameters after mapping and derivation +- `headers`: The HTTP request headers, without `Authorization` +- `body`: The JSON request body: the arguments split into the RPC envelope +- `mappedParams`: The arguments as the tool received them ### File Downloads @@ -367,9 +478,11 @@ The download result (typed `BinaryDownloadResult`) contains: - `contentType`: `string` — the file's MIME type (e.g. `application/pdf`), or `application/octet-stream` - `statusCode`: `number` — HTTP status of the download response - `headers`: `Record` — the response headers -- `fileName`: `string | null` — filename from `Content-Disposition` (RFC 5987 `filename*` aware), or `null` +- `fileName`: `string | null` — filename from `Content-Disposition` (RFC 5987 `filename*` aware), reduced to a safe basename, or `null` + +The filename comes from whoever uploaded the file to the connected provider, so it is reduced to a bare basename before you see it: path components (`../`, `/`, `\`), drive letters and NTFS stream separators (`:`), control and Unicode format characters are removed, and it is capped at 255 bytes. It is `null` when nothing usable is left. -> **Note:** `content` is a raw `Buffer`, not a `JsonValue`. `JSON.stringify` turns it into a `{ type: 'Buffer', data: [...] }` byte array (not the file, and potentially huge), so if you forward tool results to an LLM — or anything that re-serializes to JSON — strip or transform the `content` key first (for example, base64-encode it on the LLM-facing path). +> **Note:** `content` is a raw `Buffer`, not a `JsonValue`. `JSON.stringify` turns it into a `{ type: 'Buffer', data: [...] }` byte array (not the file, and potentially huge), so if you forward tool results to an LLM — or anything that re-serializes to JSON — strip or transform the `content` key first. `executeOpenAIToolCalls()` and the Claude Agent SDK adapter base64-encode it for you. ## Examples diff --git a/examples/README.md b/examples/README.md index 77711543..f5755a13 100644 --- a/examples/README.md +++ b/examples/README.md @@ -16,7 +16,7 @@ Set your credentials using either approach: ```bash export STACKONE_API_KEY=your-stackone-api-key -export STACKONE_ACCOUNT_ID=your-account-id +export STACKONE_ACCOUNT_ID=your-account-id # optional: accounts are discovered otherwise export OPENAI_API_KEY=your-openai-api-key # for OpenAI/AI SDK examples export ANTHROPIC_API_KEY=your-anthropic-api-key # for Anthropic examples ``` @@ -46,9 +46,13 @@ pnpm test ## Examples Overview +### [`search-and-execute.ts`](./search-and-execute.ts) -- Search and Execute (recommended) + +Finds an action in natural language with `toolset.search()` and runs it with `toolset.execute()`, without loading a tool catalog into a model's context. Lists the linked accounts the API key reaches (no account id needed), prints the ranked matches and the best action's `input_schema`, executes it with the hit's `session_id`, and records feedback with `submitFeedback()` when the project has feedback enabled. + ### [`openai-integration.ts`](./openai-integration.ts) -- OpenAI Chat Completions API -Fetches StackOne tools, converts them with `tools.toOpenAI()`, and sends them to the OpenAI Chat Completions API. Demonstrates the basic tool-call flow: create a completion, inspect the returned tool calls, and log arguments. +Fetches StackOne tools, converts them with `tools.toOpenAI()`, and sends them to the OpenAI Chat Completions API. Demonstrates the full tool-call loop: create a completion, run the returned tool calls with `tools.executeOpenAIToolCalls()`, and send the results back for a final answer. ### [`openai-responses-integration.ts`](./openai-responses-integration.ts) -- OpenAI Responses API @@ -68,13 +72,13 @@ Converts StackOne tools into an MCP server with `tools.toClaudeAgentSdk()` and p ### [`auth-management.ts`](./auth-management.ts) -- Authentication Patterns -Walks through every way to configure API keys and account IDs: reading from environment variables, passing them explicitly to the constructor, setting multiple accounts with `setAccounts()`, overriding per-tool collection or per individual tool, and fetching tools for multiple accounts in one call. +Walks through every way to configure API keys and account IDs: reading from environment variables, passing them explicitly to the constructor, relying on account discovery with just an API key (`fetchAccounts()`), setting multiple accounts with `setAccounts()`, and overriding the account on an individual tool. ## Environment Variables | Variable | Required | Used By | | --------------------- | ---------------------------- | ----------------------------------------------------------------------------------- | | `STACKONE_API_KEY` | Yes | All examples | -| `STACKONE_ACCOUNT_ID` | Recommended | All examples (read automatically by `new StackOneToolSet()`) | +| `STACKONE_ACCOUNT_ID` | Optional | All examples (read automatically; without it, accounts are discovered from the key) | | `OPENAI_API_KEY` | For OpenAI / AI SDK examples | `openai-integration.ts`, `openai-responses-integration.ts`, `ai-sdk-integration.ts` | | `ANTHROPIC_API_KEY` | For Anthropic examples | `anthropic-integration.ts`, `claude-agent-sdk-integration.ts` | diff --git a/examples/auth-management.ts b/examples/auth-management.ts index dbb4f77f..7857fc6b 100644 --- a/examples/auth-management.ts +++ b/examples/auth-management.ts @@ -4,7 +4,9 @@ * Shows every way to configure API keys and account IDs with the Node SDK. * * Run with: - * STACKONE_API_KEY=xxx STACKONE_ACCOUNT_ID=xxx npx tsx examples/auth-management.ts + * STACKONE_API_KEY=xxx npx tsx examples/auth-management.ts + * + * STACKONE_ACCOUNT_ID is optional: without it, accounts are discovered from the API key. */ import process from 'node:process'; @@ -19,7 +21,7 @@ if (!process.env.STACKONE_API_KEY) { const apiKeyFromEnv = async (): Promise => { console.log('=== 1a. API Key from environment ===\n'); - // Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from env automatically + // Reads STACKONE_API_KEY (and STACKONE_ACCOUNT_ID, if set) from env automatically const toolset = new StackOneToolSet(); const tools = await toolset.fetchTools(); console.log(` Loaded ${tools.toOpenAI().length} tools using env API key\n`); @@ -33,6 +35,18 @@ const apiKeyExplicit = async (): Promise => { console.log(` Loaded ${tools.toOpenAI().length} tools using explicit API key\n`); }; +// --- 1c. API key alone: accounts are discovered --- +const apiKeyAlone = async (): Promise => { + console.log('=== 1c. API key alone ===\n'); + + // With no account configured, the toolset lists the key's active linked accounts itself. + const toolset = new StackOneToolSet({ apiKey: process.env.STACKONE_API_KEY }); + const accounts = await toolset.fetchAccounts(); + const active = accounts.filter((account) => account.status === 'active'); + console.log(` ${accounts.length} linked account(s), ${active.length} active`); + console.log(` Loaded ${(await toolset.fetchTools()).length} tools across them\n`); +}; + // --- 2. Account ID from environment --- const accountIdFromEnv = async (): Promise => { console.log('=== 2. Account ID from environment ===\n'); @@ -91,6 +105,7 @@ const perToolOverride = async (): Promise => { // --- Run all sections --- await apiKeyFromEnv(); await apiKeyExplicit(); +await apiKeyAlone(); await accountIdFromEnv(); await accountIdInConstructor(); await setAccountsGlobally(); diff --git a/examples/openai-integration.ts b/examples/openai-integration.ts index 4daa23e5..df81218b 100644 --- a/examples/openai-integration.ts +++ b/examples/openai-integration.ts @@ -31,33 +31,46 @@ const openaiIntegration = async (): Promise => { const openai = new OpenAI(); // Create a chat completion with tool calls + const messages: OpenAI.ChatCompletionMessageParam[] = [ + { + role: 'system', + content: 'You are a helpful assistant that can access HR information.', + }, + { + role: 'user', + content: 'List the first 5 employees', + }, + ]; const response = await openai.chat.completions.create({ model: 'gpt-5.1', - messages: [ - { - role: 'system', - content: 'You are a helpful assistant that can access HR information.', - }, - { - role: 'user', - content: 'List the first 5 employees', - }, - ], + messages, tools: openAITools, }); - console.log(`Model returned ${response.choices.length} choice(s)`); - - const choice = response.choices[0]; - const toolCalls = choice.message.tool_calls ?? []; + const message = response.choices[0]?.message; + const toolCalls = message?.tool_calls ?? []; console.log(`Tool calls made: ${toolCalls.length}`); + if (!message || toolCalls.length === 0) { + return; + } for (const toolCall of toolCalls) { - if ('function' in toolCall) { + if (toolCall.type === 'function') { console.log(` Tool: ${toolCall.function.name}`); console.log(` Arguments: ${toolCall.function.arguments}`); } } + + // 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. + messages.push(message, ...(await tools.executeOpenAIToolCalls(toolCalls))); + + const final = await openai.chat.completions.create({ + model: 'gpt-5.1', + messages, + tools: openAITools, + }); + console.log(`Answer: ${final.choices[0]?.message.content ?? ''}`); }; // Run the example diff --git a/examples/search-and-execute.ts b/examples/search-and-execute.ts new file mode 100644 index 00000000..9659e7d8 --- /dev/null +++ b/examples/search-and-execute.ts @@ -0,0 +1,90 @@ +/** + * Find an action in natural language and run it, without loading a tool catalog. + * + * This is the recommended way to use the SDK: search() asks every linked connector and returns + * ranked actions, so a catalog of hundreds of tools never has to fit in a model's context. + * + * Prerequisites: STACKONE_API_KEY and at least one active linked account. No account id is + * needed — the toolset discovers the ones your key can reach. + * + * Run with: + * STACKONE_API_KEY=xxx npx tsx examples/search-and-execute.ts + * + * Expected output: your linked accounts, the ranked actions matching the query, the input + * schema of the best one, and the result of executing it. + */ + +import process from 'node:process'; +import { StackOneError, StackOneToolSet, ToolSetError } from '@stackone/ai'; + +if (!process.env.STACKONE_API_KEY) { + console.error('STACKONE_API_KEY environment variable is required'); + process.exit(1); +} + +const searchAndExecute = async (): Promise => { + const toolset = new StackOneToolSet(); + + for (const account of await toolset.fetchAccounts()) { + console.log(`${account.id} ${account.provider ?? '?'} ${account.status ?? '?'}`); + } + + const actions = await toolset.search('list recent comments', { topK: 3 }); + const [best] = actions; + if (!best) { + 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) { + const score = typeof action.similarity_score === 'number' ? action.similarity_score : 0; + console.log(` ${score.toFixed(3)} ${action.action_id}`); + } + + // 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, + // so a guessed parameter looks like it worked. + console.log(`\ninput_schema for ${best.action_id}:`); + console.log(JSON.stringify(best.input_schema ?? {}, null, 2).slice(0, 600)); + + // Passing the hit's session_id links this call to the search that found it. + const result = await toolset.execute( + best.action_id, + { query: { limit: 2 } }, + { + sessionId: best.session_id, + }, + ); + console.log(`\nresult: ${JSON.stringify(result).slice(0, 300)}...`); + + // When feedback is enabled for your project, say how it went. + try { + await toolset.submitFeedback({ + rating: 'positive', + toolNames: [best.action_id], + category: 'search', + sessionId: best.session_id, + }); + console.log('\nFeedback recorded.'); + } catch (error) { + if (!(error instanceof ToolSetError)) { + throw error; + } + console.log(`\nFeedback skipped: ${error.message}`); + } +}; + +try { + await searchAndExecute(); +} catch (error) { + if (error instanceof ToolSetError) { + console.error(`Could not load tools from StackOne: ${error.message}`); + process.exit(1); + } + if (error instanceof StackOneError) { + console.error(`StackOne API error: ${error.message}`); + process.exit(1); + } + throw error; +} diff --git a/flake.nix b/flake.nix index 8ed401d1..933d1920 100644 --- a/flake.nix +++ b/flake.nix @@ -40,7 +40,6 @@ allowlist = agentLib.allowlistFor { inherit catalog sources; enable = [ - "orama-integration" "release-please" ]; }; diff --git a/tests/examples/openai-integration.test.ts b/tests/examples/openai-integration.test.ts index da5793fd..5bf1bfde 100644 --- a/tests/examples/openai-integration.test.ts +++ b/tests/examples/openai-integration.test.ts @@ -69,5 +69,13 @@ describe('openai-integration example e2e', () => { const args: unknown = JSON.parse(toolCall.function.arguments); assert(typeof args === 'object' && args !== null && 'id' in args); expect(args.id).toBe('c28xIQaWQ6MzM5MzczMDA2NzMzMzkwNzIwNA'); + + // Run the tool calls and turn them into the messages to send back + 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({ + data: { id: 'c28xIQaWQ6MzM5MzczMDA2NzMzMzkwNzIwNA', name: 'Test Employee' }, + }); }); }); diff --git a/tests/examples/search-and-execute.test.ts b/tests/examples/search-and-execute.test.ts new file mode 100644 index 00000000..179373f0 --- /dev/null +++ b/tests/examples/search-and-execute.test.ts @@ -0,0 +1,68 @@ +/** + * E2E test for search-and-execute.ts example + * + * Runs the real example file against the mock API: an API key and nothing else, so it has to + * discover the account, search, execute the best hit and try to record feedback. + */ + +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 { server } from '../../mocks/node'; +import { StackOneToolSet, ToolSetLoadError } from '../../src'; + +describe('search-and-execute example e2e', () => { + beforeEach(() => { + vi.stubEnv('STACKONE_API_KEY', 'test-key'); + vi.stubEnv('STACKONE_ACCOUNT_ID', ''); + vi.stubEnv('STACKONE_BASE_URL', TEST_BASE_URL); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + it('runs the example end to end', async () => { + const calls: RecordedToolCall[] = []; + const app = createMcpApp({ + accountTools: mockAccountTools, + submitFeedback: true, + onToolCall: (call) => calls.push(call), + }); + server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + + await import('../../examples/search-and-execute'); + + const printed = log.mock.calls.map((args) => String(args[0])).join('\n'); + expect(printed).toContain('default testprovider active'); + expect(printed).toContain('0.800 mock_list_items'); + expect(printed).toContain('Feedback recorded.'); + expect(calls.map((call) => [call.name, call.arguments.session_id])).toEqual([ + ['mock_default_search_actions', undefined], + ['mock_default_execute_action', MOCK_SEARCH_SESSION_ID], + ['stackone_submit_feedback', MOCK_SEARCH_SESSION_ID], + ]); + }); + + it('reports feedback as unavailable when the project has it off', async () => { + const toolset = new StackOneToolSet(); + + const [best] = await toolset.search('list recent comments', { topK: 3 }); + assert(best); + expect(await toolset.execute(best.action_id, {}, { sessionId: best.session_id })).toMatchObject( + { + data: { nodes: [] }, + }, + ); + await expect( + toolset.submitFeedback({ rating: 'positive', toolNames: [best.action_id] }), + ).rejects.toBeInstanceOf(ToolSetLoadError); + }); +}); From 9ec38c15241dfa5c18e4c9f6f0a773c0f6fc4097 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 14:54:02 +0100 Subject: [PATCH 015/151] ci: run the sdk-conformance suite against the built SDK Mirror the Python SDK's conformance gate. The suite drives the built `dist` against a mock of the Unified Cloud API and grades the wire contract both SDKs share: RPC envelopes, schema pass-through (strict), account discovery and search/execute over `tools/call`. - `check-secret` lets fork PRs and Dependabot, which cannot read CONFORMANCE_REPO_TOKEN, skip the gate; everything else must pass it and fails if the token is missing or expired. - `conformance` checks out StackOneHQ/sdk-conformance pinned to a full SHA, builds the SDK and runs `pnpm test:node -- --strict-schema` with NODE_SDK_DIST pointed at the built dist. - `ci-ok` aggregates every job into the one status check to require, so renaming a job or adding a matrix entry cannot silently drop a check. There was no aggregate job before. Actions are pinned to full SHAs with version comments, as elsewhere. --- .github/workflows/ci.yaml | 99 +++++++++++++++++++++++++++++++++++++++ knip.config.ts | 3 +- 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index bfeaf8c2..d750f201 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -116,6 +116,105 @@ jobs: - name: Run Tests run: pnpm exec vitest run --project root + # Enforces the wire contract shared with the Python SDK (StackOneHQ/sdk-conformance). + # StackOneHQ/sdk-conformance is private and requires CONFORMANCE_REPO_TOKEN. + # Fork PRs and Dependabot runs cannot access this secret and skip this gate; + # internal branches and PRs require the secret and fail if it is absent or expired. + check-secret: + runs-on: ubuntu-latest + outputs: + can-skip: ${{ steps.check.outputs.can-skip }} + steps: + - id: check + env: + TOKEN: ${{ secrets.CONFORMANCE_REPO_TOKEN }} + IS_FORK: ${{ github.event.pull_request.head.repo.fork == true }} + IS_DEPENDABOT: ${{ github.actor == 'dependabot[bot]' }} + run: | + if [ -z "$TOKEN" ] && { [ "$IS_FORK" = "true" ] || [ "$IS_DEPENDABOT" = "true" ]; }; then + echo "can-skip=true" >> "$GITHUB_OUTPUT" + else + echo "can-skip=false" >> "$GITHUB_OUTPUT" + fi + + conformance: + needs: check-secret + if: needs.check-secret.outputs.can-skip != 'true' + runs-on: ubuntu-latest + steps: + - name: Check conformance token is configured + env: + TOKEN: ${{ secrets.CONFORMANCE_REPO_TOKEN }} + run: | + if [ -z "$TOKEN" ]; then + echo "::error::CONFORMANCE_REPO_TOKEN is not set or has expired." + exit 1 + fi + + - name: Checkout SDK + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + path: sdk + + - name: Checkout conformance suite + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + repository: StackOneHQ/sdk-conformance + ref: cedc5658e9249d06bacc08a3fec2fe79db0dfe38 + token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} + path: sdk-conformance + persist-credentials: false + + - name: Setup pnpm + uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 + with: + version: 10.26.0 + package_json_file: sdk-conformance/package.json + + # 24, not 22: the SDK's devEngines pins Node ^24.11.0, and the suite runs on it too. + - name: Setup Node + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Install SDK dependencies + working-directory: sdk + run: pnpm install --frozen-lockfile + + # The runner imports the built dist, not src, so the harness grades the + # publishable artifact. It refuses a dist older than src. + - name: Build SDK + working-directory: sdk + run: pnpm run build + + - name: Install conformance dependencies + working-directory: sdk-conformance + run: pnpm install --frozen-lockfile + + - name: Run conformance suite + working-directory: sdk-conformance + env: + NODE_SDK_DIST: ${{ github.workspace }}/sdk/dist/index.mjs + run: pnpm test:node -- --strict-schema + + # Make this the one required status check. Individually required checks go + # missing when a job is renamed or a matrix entry is added, and nothing notices. + ci-ok: + if: always() + needs: [check-secret, gitleaks, lint, build-and-test, ai-peer-range, conformance] + runs-on: ubuntu-latest + steps: + - name: Require every job to have passed + run: | + if [ "${{ needs.gitleaks.result != 'success' || needs.lint.result != 'success' || needs.build-and-test.result != 'success' || needs.ai-peer-range.result != 'success' }}" = "true" ]; then + echo "::error::A required job did not pass (gitleaks: ${{ needs.gitleaks.result }}, lint: ${{ needs.lint.result }}, build-and-test: ${{ needs.build-and-test.result }}, ai-peer-range: ${{ needs.ai-peer-range.result }})" + exit 1 + fi + if [ "${{ needs.conformance.result != 'success' && needs.check-secret.outputs.can-skip != 'true' }}" = "true" ]; then + echo "::error::Conformance check did not pass (result: ${{ needs.conformance.result }})" + exit 1 + fi + coverage: runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' diff --git a/knip.config.ts b/knip.config.ts index 1c569c8b..e36e8b48 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -13,7 +13,8 @@ export default { }, }, ignore: ['**/*.test.ts', '**/*.spec.ts', '**/*.test-d.ts'], - ignoreBinaries: ['only-allow', 'oxfmt', 'oxlint', 'tsx'], + // `test:node` is a script of StackOneHQ/sdk-conformance, run from its checkout in CI. + ignoreBinaries: ['only-allow', 'oxfmt', 'oxlint', 'tsx', 'test:node'], ignoreDependencies: ['@typescript/native-preview'], rules: { optionalPeerDependencies: 'off', From cdb4b8e8af450f3bb12122b1933f227b2111f330 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 16:31:55 +0100 Subject: [PATCH 016/151] refactor!: execute every tool over MCP tools/call Per-action tools posted to /actions/rpc, so the SDK split each tool call into the RPC envelope itself and had to pin param-style so its split matched the listed schema. Every tool now executes over tools/call on the endpoint and account that listed it, and the server maps the arguments with its own reverse map. The only request outside MCP is GET /accounts for discovery. A tool returns the server's result exactly as the server wrote it. For an action tool, *_execute_action and feedback that is { isError: false, result, defenderMetadata?, policyMetadata? }, while search results are bare JSON. isError still raises StackOneAPIError. The unwrap that lived only in execute() is gone, so execute() and tool.execute() return the same shape for the same action. That unwrap also dropped defender metadata. The header allowlist reads a nested `headers` object as well as flat headers_* properties, because the served style is no longer pinned. BREAKING CHANGE: StackOneRpcTool, RpcExecuteConfig, BinaryDownloadResult and isBinaryDownloadResult are removed. Action results are the server's { isError, result, ... } object rather than the /actions/rpc body. A file action's `result` is the server's single-use { download_url, expires_at, file } instead of bytes, and the call raises StackOneAPIError with status 501 when no link can be issued. The /mcp URL no longer pins param-style=flat_prefixed. dryRun returns { url, method: 'tools/call', name, arguments }. --- mocks/handlers.mcp.ts | 2 +- mocks/handlers.stackone-rpc.ts | 102 ------ mocks/handlers.ts | 8 +- mocks/mcp-server.ts | 31 +- src/consts.ts | 10 +- src/envelope.test.ts | 91 ----- src/envelope.ts | 122 ------- src/headers.test.ts | 17 +- src/headers.ts | 19 +- src/index.ts | 1 - src/mcp-client.test.ts | 36 +- src/mcp-client.ts | 12 +- src/rpc-client.test.ts | 310 ------------------ src/rpc-client.ts | 174 ---------- src/tool.test.ts | 268 +++++++-------- src/tool.ts | 132 +------- src/toolsets.search-execute.test.ts | 32 +- src/toolsets.test.ts | 95 +++--- src/toolsets.ts | 75 ++--- src/types.ts | 27 +- src/utils/binary-response.test.ts | 98 ------ src/utils/binary-response.ts | 178 ---------- src/utils/serialize.ts | 2 +- .../claude-agent-sdk-integration.test.ts | 2 +- tests/examples/fetch-tools.test.ts | 8 +- tests/examples/openai-integration.test.ts | 8 +- tests/examples/search-and-execute.test.ts | 4 +- .../examples/tanstack-ai-integration.test.ts | 2 +- 28 files changed, 330 insertions(+), 1536 deletions(-) delete mode 100644 mocks/handlers.stackone-rpc.ts delete mode 100644 src/envelope.test.ts delete mode 100644 src/envelope.ts delete mode 100644 src/rpc-client.test.ts delete mode 100644 src/rpc-client.ts delete mode 100644 src/utils/binary-response.test.ts delete mode 100644 src/utils/binary-response.ts diff --git a/mocks/handlers.mcp.ts b/mocks/handlers.mcp.ts index ce139ae7..7ccf8b6f 100644 --- a/mocks/handlers.mcp.ts +++ b/mocks/handlers.mcp.ts @@ -8,7 +8,7 @@ import { mixedProviderTools, } from './mcp-server'; -/** Every account the default mock knows. `/mcp` and `/actions/rpc` refuse any other with a 404. */ +/** Every account the default mock knows. `/mcp` refuses any other with a 404. */ export const mockAccountTools = { default: defaultMcpTools, acc1: accountMcpTools.acc1, diff --git a/mocks/handlers.stackone-rpc.ts b/mocks/handlers.stackone-rpc.ts deleted file mode 100644 index af462e27..00000000 --- a/mocks/handlers.stackone-rpc.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { http, HttpResponse } from 'msw'; -import { TEST_BASE_URL } from './constants'; -import { mockAccountTools } from './handlers.mcp'; - -/** - * StackOne Actions RPC endpoint handlers - */ -export const stackoneRpcHandlers = [ - http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { - const authHeader = request.headers.get('Authorization'); - const accountIdHeader = request.headers.get('x-account-id'); - - // Check for authentication - if (!authHeader || !authHeader.startsWith('Basic ')) { - return HttpResponse.json( - { error: 'Unauthorized', message: 'Missing or invalid authorization header' }, - { status: 401 }, - ); - } - - // Execution is account-scoped too, exactly like /mcp: an unscoped request is refused, - // and so is an account the API has never heard of. - if (!accountIdHeader) { - return HttpResponse.json( - { error: 'Bad Request', message: 'Missing x-account-id header in request' }, - { status: 400 }, - ); - } - if (!Object.hasOwn(mockAccountTools, accountIdHeader)) { - return HttpResponse.json( - { error: 'Not Found', message: `Unknown account ${accountIdHeader}` }, - { status: 404 }, - ); - } - - const body = (await request.json()) as { - action?: string; - body?: Record; - headers?: Record; - path?: Record; - query?: Record; - }; - - // Validate action is provided - if (!body.action) { - return HttpResponse.json( - { error: 'Bad Request', message: 'Action is required' }, - { status: 400 }, - ); - } - - // Test action to verify x-account-id is sent as HTTP header - if (body.action === 'test_account_id_header') { - return HttpResponse.json({ - data: { - httpHeader: accountIdHeader, - bodyHeader: body.headers?.['x-account-id'], - }, - }); - } - - // Return mock response based on action - if (body.action === 'bamboohr_get_employee') { - return HttpResponse.json({ - data: { - id: body.path?.id || 'test-id', - name: 'Test Employee', - ...body.body, - }, - }); - } - - if (body.action === 'bamboohr_list_employees') { - return HttpResponse.json({ - data: [ - { id: '1', name: 'Employee 1' }, - { id: '2', name: 'Employee 2' }, - ], - }); - } - - if (body.action === 'test_error_action') { - return HttpResponse.json( - { error: 'Internal Server Error', message: 'Test error response' }, - { status: 500 }, - ); - } - - // Default response for other actions — echo back received fields - return HttpResponse.json({ - data: { - action: body.action, - received: { - body: body.body, - headers: body.headers, - path: body.path, - query: body.query, - }, - }, - }); - }), -]; diff --git a/mocks/handlers.ts b/mocks/handlers.ts index addf4128..43b6b4c0 100644 --- a/mocks/handlers.ts +++ b/mocks/handlers.ts @@ -1,11 +1,5 @@ import { mcpHandlers } from './handlers.mcp'; import { openaiHandlers } from './handlers.openai'; import { stackoneAccountsHandlers } from './handlers.stackone-accounts'; -import { stackoneRpcHandlers } from './handlers.stackone-rpc'; -export const handlers = [ - ...openaiHandlers, - ...stackoneAccountsHandlers, - ...stackoneRpcHandlers, - ...mcpHandlers, -]; +export const handlers = [...openaiHandlers, ...stackoneAccountsHandlers, ...mcpHandlers]; diff --git a/mocks/mcp-server.ts b/mocks/mcp-server.ts index 73803bc0..d02aa056 100644 --- a/mocks/mcp-server.ts +++ b/mocks/mcp-server.ts @@ -48,6 +48,8 @@ export interface MockMcpServerOptions { submitFeedback?: boolean; /** Observe every `tools/call` as it arrived, before any schema parsing. */ onToolCall?: (call: RecordedToolCall) => void; + /** Answer a `tools/call` for these tool names with this literal result, verbatim. */ + toolResults?: Record; } /** Mirrors the real `session_id` minted per search, so tests can assert it is carried through. */ @@ -112,6 +114,19 @@ const text = (payload: unknown, isError = false): CallToolResult => ({ content: [{ type: 'text', text: JSON.stringify(payload) }], }); +/** + * A success the way the real endpoint answers every action tool, `*_execute_action` and feedback: + * `{ isError: false, result }` in `structuredContent`, mirrored as a text part. + */ +const wrapped = (result: unknown): CallToolResult => { + const structuredContent = { isError: false, result }; + return { + isError: false, + content: [{ type: 'text', text: JSON.stringify(structuredContent) }], + structuredContent, + }; +}; + const callMetaTool = (name: string, args: Record): CallToolResult | undefined => { if (name.endsWith('_search_actions')) { return text({ @@ -132,7 +147,7 @@ const callMetaTool = (name: string, args: Record): CallToolResu if (args.action_id !== 'mock_list_items') { return text({ error: `Unknown action ${String(args.action_id)}`, status_code: 404 }, true); } - return text({ + return wrapped({ data: { nodes: [] }, echoed_query: args.query ?? null, echoed_session_id: args.session_id ?? null, @@ -154,7 +169,7 @@ const callMetaTool = (name: string, args: Record): CallToolResu * ``` */ export function createMcpApp(options: MockMcpServerOptions): HonoApp { - const { accountTools, submitFeedback = false, onToolCall } = options; + const { accountTools, submitFeedback = false, onToolCall, toolResults = {} } = options; // Create a Hono app that handles MCP protocol const app = new Hono(); @@ -209,14 +224,22 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { if (!listed.some((tool) => tool.name === name)) { return text({ error: `Unknown tool ${name}`, status_code: 404 }, true); } + const literal = toolResults[name]; + if (literal) { + return structuredClone(literal); + } if (name === submitFeedbackTool.name) { - return text({ + return wrapped({ message: 'Feedback recorded', submitted_at: new Date(0).toISOString(), session_id: args.session_id ?? null, }); } - return callMetaTool(name, args) ?? text(args); + // An action tool echoes what reached it, so a test can see the arguments and account. + return ( + callMetaTool(name, args) ?? + wrapped({ data: { action: name, account_id: accountId, arguments: args } }) + ); }); const transport = new StreamableHTTPTransport(); diff --git a/src/consts.ts b/src/consts.ts index 9ca40281..cfa2294c 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -14,17 +14,9 @@ export const DEFAULT_BASE_URL = 'https://api.stackone.com'; /** Request timeout applied to every HTTP and MCP call unless the toolset is given one. */ export const DEFAULT_TIMEOUT_MS = 60_000; -/** - * Param-style pinned on the /mcp tool-listing URL. The listed schema and the RPC envelope split - * (see `splitEnvelopeParams`) must agree on it, so it is pinned rather than following the server - * default — the server default is free to change without breaking the SDK. - */ -export const MCP_PARAM_STYLE = 'flat_prefixed'; - /** * The one global tool the MCP endpoint serves, in every tool mode, when feedback is enabled for - * the project. It is not a connector action; the server also accepts it on `/actions/rpc`, but - * the SDK executes it only over MCP `tools/call`, where it is served. + * the project. It is listed once however many accounts serve it. */ export const SUBMIT_FEEDBACK_TOOL_NAME = 'stackone_submit_feedback'; diff --git a/src/envelope.test.ts b/src/envelope.test.ts deleted file mode 100644 index 3e1c09c8..00000000 --- a/src/envelope.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { isFlatPrefixedSchema, splitEnvelopeParams } from './envelope'; - -const split = (params: Record, declared: string[] = []) => - splitEnvelopeParams(params as never, new Set(declared)); - -describe('splitEnvelopeParams', () => { - it('buckets flat_prefixed keys by their location prefix', () => { - expect( - split({ path_id: '123', query_limit: 10, 'headers_x-custom': 'value', body_name: 'test' }), - ).toEqual({ - path: { id: '123' }, - query: { limit: 10 }, - headers: { 'x-custom': 'value' }, - body: { name: 'test' }, - }); - }); - - it('accepts nested envelopes and sends unprefixed keys to the body', () => { - expect(split({ body: { nested: 'value' }, path: { id: '1' }, extra: 'x' })).toEqual({ - path: { id: '1' }, - query: {}, - headers: {}, - body: { nested: 'value', extra: 'x' }, - }); - }); - - // The prefix pattern alone cannot tell a path param from a body field that happens to start - // with "path_". The served schema settles it — decided once, from ALL of its keys. - describe('is decided once from the served schema', () => { - it('keeps prefix lookalikes in the body when any declared key is bare', () => { - const result = split({ path_to_file: '/tmp/x' }, ['path_to_file', 'name']); - expect(result.body).toEqual({ path_to_file: '/tmp/x' }); - expect(result.path).toEqual({}); - }); - - it('splits every match, declared or not, when every declared key is prefixed', () => { - const result = split({ path_id: '1', query_offset: 10 }, ['path_id', 'query_limit']); - expect(result.path).toEqual({ id: '1' }); - // Undeclared but prefixed: the model may be working from a newer schema than the - // cached listing. Routing it to the body would silently drop the argument. - expect(result.query).toEqual({ offset: 10 }); - }); - - it('trusts every match when there is no schema to consult', () => { - expect(split({ path_to_file: '/tmp/x' }).path).toEqual({ to_file: '/tmp/x' }); - expect(isFlatPrefixedSchema(new Set())).toBe(true); - }); - - it('is disabled by a single bare name', () => { - expect(isFlatPrefixedSchema(new Set(['path_id', 'name']))).toBe(false); - expect(isFlatPrefixedSchema(new Set(['path_id', 'body_name']))).toBe(true); - }); - }); - - it('treats a declared reserved word as a field, not a container', () => { - expect(split({ query: 'sales' }, ['query', 'id']).body).toEqual({ query: 'sales' }); - }); - - it.each([['not-an-object'], [5], [null], [['a']]])( - 'rejects a reserved container given %j rather than smuggling it into the body', - (value) => { - expect(() => split({ query: value })).toThrow(/envelope container and must be an object/); - }, - ); - - it('does not depend on the caller key order: flat beats nested beats bare', () => { - expect(split({ body_foo: 1, foo: 2 }).body).toEqual({ foo: 1 }); - expect(split({ foo: 2, body_foo: 1 }).body).toEqual({ foo: 1 }); - - expect(split({ body: { foo: 9 }, foo: 2 }).body).toEqual({ foo: 9 }); - expect(split({ foo: 2, body: { foo: 9 } }).body).toEqual({ foo: 9 }); - - expect(split({ path: { id: 'nested' }, path_id: 'flat' }).path).toEqual({ id: 'flat' }); - expect(split({ path_id: 'flat', path: { id: 'nested' } }).path).toEqual({ id: 'flat' }); - }); - - it('keeps fields named after Object.prototype members as plain data', () => { - const result = split( - JSON.parse( - '{"body_constructor":"x","path_toString":"y","query_valueOf":"z","body___proto__":"p","hasOwnProperty":"h"}', - ) as Record, - ); - - expect(JSON.stringify(result.body)).toBe( - '{"constructor":"x","__proto__":"p","hasOwnProperty":"h"}', - ); - expect(result.path).toEqual({ toString: 'y' }); - expect(result.query).toEqual({ valueOf: 'z' }); - expect(Object.getPrototypeOf(result.body)).toBe(Object.prototype); - }); -}); diff --git a/src/envelope.ts b/src/envelope.ts deleted file mode 100644 index f903c3a3..00000000 --- a/src/envelope.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { StackOneError } from './utils/error-stackone'; -import { warn } from './utils/logger'; -import type { JsonObject, JsonValue } from './types'; - -/** Matches a flat_prefixed envelope key: `_` (e.g. `path_id`, `query_limit`). */ -const FLAT_ENVELOPE_KEY_PATTERN = /^(path|query|body|headers)_(.+)$/; - -const ENVELOPE_LOCATIONS = ['path', 'query', 'headers', 'body'] as const; - -type EnvelopeLocation = (typeof ENVELOPE_LOCATIONS)[number]; - -/** The four buckets of an `/actions/rpc` request. */ -type Envelope = Record; - -const isEnvelopeLocation = (key: string): key is EnvelopeLocation => - (ENVELOPE_LOCATIONS as readonly string[]).includes(key); - -const isPlainObject = (value: unknown): value is JsonObject => - typeof value === 'object' && value !== null && !Array.isArray(value); - -/** - * Whether a tool's arguments should be read as flat_prefixed, decided ONCE from its served - * schema rather than per key. - * - * Under flat_prefixed every parameter is prefixed, so `path_to_file` means `path.to_file`; under - * a bare schema it is a body field that merely starts with "path_". ALL declared keys must be - * prefixed, not any: one bare name is proof the schema is not flat_prefixed, and `any` would be - * satisfied by the very key this exists to protect. No declared keys means no schema to - * consult, so every match is trusted — otherwise every path parameter would fall into the body. - */ -export function isFlatPrefixedSchema(declared: ReadonlySet): boolean { - return declared.size === 0 || [...declared].every((key) => FLAT_ENVELOPE_KEY_PATTERN.test(key)); -} - -/** - * Split tool arguments into the RPC envelope (path/query/headers/body). - * - * Tools are listed with `?param-style=flat_prefixed`, so keys arrive as `_` - * and the prefix carries the location. A bare object-valued `path`/`query`/`headers`/`body` key - * is still bucketed for clients holding a nested schema, and any other key falls through to the - * body. - * - * Precedence is a property of the KIND of key, never of the caller's key order: flat_prefixed - * beats nested beats bare. The Python SDK applies the same rules, so both send byte-identical - * wire bodies for the same call. - * - * Buckets are null-prototype objects, so fields named after `Object.prototype` members - * (`constructor`, `toString`, `__proto__`) are ordinary data rather than prototype lookups. - * - * @param params The model-supplied arguments. - * @param declared The served schema's property names. - * @param flatPrefixed The result of {@link isFlatPrefixedSchema} for `declared`. - * @throws StackOneError When a reserved container key carries a non-object value. - */ -export function splitEnvelopeParams( - params: JsonObject, - declared: ReadonlySet, - flatPrefixed: boolean = isFlatPrefixedSchema(declared), -): Envelope { - const buckets: Envelope = { - path: Object.create(null) as JsonObject, - query: Object.create(null) as JsonObject, - headers: Object.create(null) as JsonObject, - body: Object.create(null) as JsonObject, - }; - const setDefault = (bucket: JsonObject, field: string, value: JsonValue): void => { - if (!Object.hasOwn(bucket, field)) { - bucket[field] = value; - } - }; - - const nested: Array<[EnvelopeLocation, JsonObject]> = []; - const bare: Array<[string, JsonValue]> = []; - for (const [key, value] of Object.entries(params)) { - const match = flatPrefixed ? FLAT_ENVELOPE_KEY_PATTERN.exec(key) : null; - if (match) { - buckets[match[1] as EnvelopeLocation][match[2] as string] = value; - continue; - } - // A reserved word the schema declares as a property is a field, not a container — - // refusing it would reject a schema-valid call. - if (isEnvelopeLocation(key) && !declared.has(key)) { - // A container given a scalar is malformed input, not a body field. Putting it in the - // body would smuggle a field literally named `path` into the payload. - if (!isPlainObject(value)) { - throw new StackOneError( - `"${key}" is an envelope container and must be an object, got ${value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value}. Did you mean ${key}_?`, - ); - } - nested.push([key, value]); - continue; - } - bare.push([key, value]); - } - - for (const [location, value] of nested) { - for (const [field, fieldValue] of Object.entries(value)) { - setDefault(buckets[location], field, fieldValue); - } - } - for (const [key, value] of bare) { - setDefault(buckets.body, key, value); - } - - // Spread onto ordinary objects so downstream JSON and schema handling sees plain records. - return { - path: { ...buckets.path }, - query: { ...buckets.query }, - headers: { ...buckets.headers }, - body: { ...buckets.body }, - }; -} - -/** - * Warn, once, that a schema with bare names has flat-prefix detection disabled. Called by the - * tool the first time it splits arguments, rather than per call or per listing. - */ -export function warnBareSchema(toolName: string): void { - warn( - `Tool "${toolName}" has bare parameter names in its schema; flat-prefix detection is disabled and prefixed arguments may fall into the body.`, - ); -} diff --git a/src/headers.test.ts b/src/headers.test.ts index ce27da28..ca1684f0 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -69,7 +69,9 @@ describe('normalizeHeaders', () => { }); describe('sanitiseHeaders', () => { - const allowed = declaredHeaderNames(['headers_x-trace', 'query_limit', 'body_headers_x']); + const flat = (...names: string[]) => + Object.fromEntries(names.map((name) => [name, { type: 'string' }])); + const allowed = declaredHeaderNames(flat('headers_x-trace', 'query_limit', 'body_headers_x')); beforeEach(() => { vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -78,12 +80,21 @@ describe('sanitiseHeaders', () => { vi.restoreAllMocks(); }); - it('builds the allowlist from headers_* properties only, lower-cased', () => { - expect(declaredHeaderNames(['headers_X-Trace', 'query_limit', 'body_headers_x'])).toEqual( + it('builds the allowlist from flat headers_* properties only, lower-cased', () => { + expect(declaredHeaderNames(flat('headers_X-Trace', 'query_limit', 'body_headers_x'))).toEqual( new Set(['x-trace']), ); }); + it('builds the allowlist from a nested headers object, lower-cased', () => { + expect( + declaredHeaderNames({ + headers: { type: 'object', properties: { 'X-Trace': { type: 'string' } } }, + body: { type: 'object', properties: { 'x-other': { type: 'string' } } }, + }), + ).toEqual(new Set(['x-trace'])); + }); + it('drops every header the served schema does not declare', () => { expect( sanitiseHeaders( diff --git a/src/headers.ts b/src/headers.ts index d2a53db7..01ad1c3d 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -93,17 +93,26 @@ const DECLARED_HEADER_PREFIX = 'headers_'; /** * The header names a served tool schema declares, lower-cased. * - * Under `param-style=flat_prefixed` a header parameter is served as a `headers_` - * property, so the schema itself is the allowlist. Nothing needs maintaining in the SDK: an - * action that starts declaring a header works without a release. + * The schema itself is the allowlist, in whichever param-style the server served it: a flat + * `headers_` property, or a `` under a nested `headers` object. Nothing needs + * maintaining in the SDK: an action that starts declaring a header works without a release. */ -export function declaredHeaderNames(propertyNames: Iterable): Set { +export function declaredHeaderNames(properties: Record): Set { const allowed = new Set(); - for (const name of propertyNames) { + for (const name of Object.keys(properties)) { if (name.startsWith(DECLARED_HEADER_PREFIX)) { allowed.add(name.slice(DECLARED_HEADER_PREFIX.length).toLowerCase()); } } + const nested = properties.headers; + if (typeof nested === 'object' && nested !== null && !Array.isArray(nested)) { + const nestedProperties = (nested as { properties?: unknown }).properties; + if (typeof nestedProperties === 'object' && nestedProperties !== null) { + for (const name of Object.keys(nestedProperties)) { + allowed.add(name.toLowerCase()); + } + } + } return allowed; } diff --git a/src/index.ts b/src/index.ts index 807d2189..4449d906 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,7 +3,6 @@ */ export { BaseTool, StackOneTool, Tools } from './tool'; -export { isBinaryDownloadResult, type BinaryDownloadResult } from './utils/binary-response'; export { StackOneError } from './utils/error-stackone'; export { StackOneAPIError } from './utils/error-stackone-api'; export { ToolSetConfigError, ToolSetError, ToolSetLoadError } from './utils/error-toolset'; diff --git a/src/mcp-client.test.ts b/src/mcp-client.test.ts index 026a8182..8f9890e0 100644 --- a/src/mcp-client.test.ts +++ b/src/mcp-client.test.ts @@ -170,6 +170,37 @@ 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', () => { + const payload = { + isError: false, + result: { data: { id: 'e1' } }, + defenderMetadata: { applied: true }, + policyMetadata: { decision: 'allow' }, + }; + expect(parseToolResult(served(payload), 't')).toEqual(payload); + }); + + it('returns the same object when the wrapper is only in structuredContent', () => { + const payload = { isError: false, result: [1] }; + expect(parseToolResult({ content: [], structuredContent: payload }, 't')).toEqual(payload); + }); + + it('never writes content_parts into the caller’s structuredContent', () => { + const structuredContent = { ok: true }; + const image = { type: 'image', data: 'AAAA', mimeType: 'image/png' }; + parseToolResult({ content: [image], structuredContent }, 't'); + expect(structuredContent).toEqual({ ok: true }); + }); + }); + // A failed tools/call is an ordinary response with isError set. Returning its body as data // would hand the caller an error as though it were a success. it('raises on isError, with the status from the payload', () => { @@ -221,7 +252,10 @@ describe('callMcpTool', () => { session_id: 's-1', }); - expect(result).toMatchObject({ message: 'Feedback recorded', session_id: 's-1' }); + expect(result).toMatchObject({ + isError: false, + result: { message: 'Feedback recorded', session_id: 's-1' }, + }); }); }); diff --git a/src/mcp-client.ts b/src/mcp-client.ts index c0961d79..86062acc 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -179,8 +179,10 @@ function statusOf(parsed: JsonObject): number { * Turn an MCP `tools/call` result into a plain object. * * Text parts are joined and parsed as JSON; a non-object is wrapped as `{ result }`. With no text - * at all, `structuredContent` is used. Parts that are not text (images, embedded resources) are - * kept under `content_parts` rather than silently dropped. + * at all, `structuredContent` is used. Either way the result is returned as the server wrote it — + * for an action tool that is `{ isError: false, result, defenderMetadata?, policyMetadata? }`. + * Parts that are not text (images, embedded resources) are kept under `content_parts` rather than + * silently dropped. * * @throws StackOneAPIError If the result carries `isError`. A failed tool call comes back as an * ordinary response with that flag set, so without this check the error body would be handed @@ -219,10 +221,12 @@ 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) { - parsed.content_parts = nonText as unknown as JsonObject[]; + returned.content_parts = nonText as unknown as JsonObject[]; } - return parsed; + return returned; } /** diff --git a/src/rpc-client.test.ts b/src/rpc-client.test.ts deleted file mode 100644 index 798516ea..00000000 --- a/src/rpc-client.test.ts +++ /dev/null @@ -1,310 +0,0 @@ -import { createServer, type Server as NetServer, type Socket } from 'node:net'; -import { http, HttpResponse } from 'msw'; -import { TEST_BASE_URL } from '../mocks/constants'; -import { server } from '../mocks/node'; -import { USER_AGENT } from './consts'; -import { RpcClient } from './rpc-client'; -import { isBinaryDownloadResult } from './utils/binary-response'; -import { StackOneAPIError } from './utils/error-stackone-api'; -import { StackOneError } from './utils/error-stackone'; - -const newClient = (overrides: Partial[0]> = {}) => - new RpcClient({ baseUrl: TEST_BASE_URL, apiKey: 'test-api-key', timeout: 5_000, ...overrides }); - -const request = (action: string, extra: Record = {}) => ({ - action, - body: {}, - headers: {}, - ...extra, -}); - -const captureRequests = () => { - const seen: Request[] = []; - server.use( - http.post(`${TEST_BASE_URL}/actions/rpc`, ({ request: incoming }) => { - seen.push(incoming.clone()); - return HttpResponse.json({ data: { ok: true } }); - }), - ); - return seen; -}; - -describe('RpcClient', () => { - it('posts the envelope to /actions/rpc with Basic auth, a versioned User-Agent and the account', async () => { - const seen = captureRequests(); - - const result = await newClient().rpcAction( - request('crm_list_contacts', { query: { limit: 1 }, headers: { 'x-account-id': 'acc-1' } }), - 'acc-1', - ); - - expect(result).toEqual({ data: { ok: true } }); - const [sent] = seen; - assert(sent); - expect(sent.url).toBe(`${TEST_BASE_URL}/actions/rpc`); - expect(sent.headers.get('authorization')).toBe( - `Basic ${Buffer.from('test-api-key:').toString('base64')}`, - ); - expect(sent.headers.get('user-agent')).toBe(USER_AGENT); - expect(sent.headers.get('x-account-id')).toBe('acc-1'); - expect(await sent.json()).toEqual({ - action: 'crm_list_contacts', - body: {}, - headers: { 'x-account-id': 'acc-1' }, - query: { limit: 1 }, - }); - }); - - // The account on the wire is the caller's argument, never a copy lifted out of the envelope: - // the envelope is model-supplied. - it('takes x-account-id from the tool, not from the envelope', async () => { - const seen = captureRequests(); - - await newClient().rpcAction( - request('crm_list_contacts', { headers: { 'x-account-id': 'victim' } }), - 'acc-1', - ); - - expect(seen[0]?.headers.get('x-account-id')).toBe('acc-1'); - }); - - it('sends no x-account-id at all without an account, and the API refuses it', async () => { - const error = await newClient() - .rpcAction(request('dummy_action'), undefined) - .catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(400); - }); - - it('refuses an account the API does not know', async () => { - const error = await newClient() - .rpcAction(request('dummy_action'), 'no-such-account') - .catch((caught: unknown) => caught); - - expect((error as StackOneAPIError).statusCode).toBe(404); - }); - - it('lets caller headers through beneath the SDK-owned ones', async () => { - const seen = captureRequests(); - - await newClient({ - headers: { 'X-Trace': 't-1', authorization: 'Bearer spoofed', 'X-Account-Id': 'other' }, - }).rpcAction(request('crm_list_contacts'), 'acc-1'); - - const sent = seen[0]; - expect(sent?.headers.get('x-trace')).toBe('t-1'); - expect(sent?.headers.get('authorization')).toMatch(/^Basic /); - expect(sent?.headers.get('x-account-id')).toBe('acc-1'); - }); - - it('leads an API error with the server message and keeps status and body', async () => { - server.use( - http.post(`${TEST_BASE_URL}/actions/rpc`, () => - HttpResponse.json( - { message: 'path.id is missing', provider_errors: [{ status: 400 }] }, - { status: 400, statusText: 'Bad Request' }, - ), - ), - ); - - const error = (await newClient() - .rpcAction(request('crm_get_contact'), 'acc-1') - .catch((caught: unknown) => caught)) as StackOneAPIError; - - expect(error).toBeInstanceOf(StackOneAPIError); - expect(error.message).toBe('400 Bad Request: path.id is missing'); - expect(error.statusCode).toBe(400); - expect(error.responseBody).toEqual({ - message: 'path.id is missing', - provider_errors: [{ status: 400 }], - }); - expect(error.providerErrors).toEqual([{ status: 400 }]); - }); - - it('reports a non-JSON error body as text rather than throwing a SyntaxError', async () => { - server.use( - http.post( - `${TEST_BASE_URL}/actions/rpc`, - () => - new HttpResponse('502 Bad Gateway', { - status: 502, - statusText: 'Bad Gateway', - headers: { 'content-type': 'text/html' }, - }), - ), - ); - - const error = (await newClient() - .rpcAction(request('x'), 'acc-1') - .catch((caught: unknown) => caught)) as StackOneAPIError; - - expect(error).toBeInstanceOf(StackOneAPIError); - expect(error.statusCode).toBe(502); - expect(error.responseBody).toBe('502 Bad Gateway'); - expect(error.message).toContain('502 Bad Gateway: '); - }); - - it('blames the server, not the arguments, for malformed JSON', async () => { - server.use( - http.post( - `${TEST_BASE_URL}/actions/rpc`, - () => new HttpResponse('{not json', { headers: { 'content-type': 'application/json' } }), - ), - ); - - await expect(newClient().rpcAction(request('x'), 'acc-1')).rejects.toThrow( - /Server sent malformed JSON for "x"/, - ); - }); - - it('wraps a non-object JSON response as { result }', async () => { - server.use(http.post(`${TEST_BASE_URL}/actions/rpc`, () => HttpResponse.json(['a', 'b']))); - - expect(await newClient().rpcAction(request('x'), 'acc-1')).toEqual({ result: ['a', 'b'] }); - }); - - it.each([204, 205])('returns { statusCode } for a bodyless %i', async (status) => { - server.use(http.post(`${TEST_BASE_URL}/actions/rpc`, () => new HttpResponse(null, { status }))); - - expect(await newClient().rpcAction(request('x'), 'acc-1')).toEqual({ statusCode: status }); - }); - - it('returns { statusCode } for an empty JSON body rather than a fake download', async () => { - server.use( - http.post( - `${TEST_BASE_URL}/actions/rpc`, - () => new HttpResponse('', { headers: { 'content-type': 'application/json' } }), - ), - ); - - expect(await newClient().rpcAction(request('x'), 'acc-1')).toEqual({ statusCode: 200 }); - }); - - it('reports arguments JSON cannot encode as an argument error', async () => { - await expect( - newClient().rpcAction(request('x', { body: { big: 1n as never } }), 'acc-1'), - ).rejects.toThrow(/could not be encoded as JSON/); - }); - - it('reports a network failure as a StackOneError', async () => { - server.use(http.post(`${TEST_BASE_URL}/actions/rpc`, () => HttpResponse.error())); - - const error = await newClient() - .rpcAction(request('x'), 'acc-1') - .catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(StackOneError); - expect((error as Error).message).toMatch(/^Request failed/); - }); -}); - -describe('RpcClient timeout', () => { - let silent: NetServer; - const sockets: Socket[] = []; - let port = 0; - - beforeAll(async () => { - // Accepts the connection and never answers — the case a per-request default would hang on. - 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; - }); - afterAll(async () => { - for (const socket of sockets) { - socket.destroy(); - } - await new Promise((resolve) => silent.close(resolve)); - }); - - it('gives up after the configured timeout', async () => { - const started = Date.now(); - const error = await newClient({ baseUrl: `http://127.0.0.1:${port}`, timeout: 300 }) - .rpcAction(request('x'), 'acc-1') - .catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(StackOneError); - expect((error as Error).message).toMatch(/timed out after 300ms/); - expect(Date.now() - started).toBeLessThan(5_000); - }); -}); - -/** - * File-download actions (e.g. googledrive_unified_download_file) are served over /actions/rpc - * as raw binary with the file's own MIME type and a Content-Disposition header - never JSON. - */ -describe('binary file downloads', () => { - it('returns raw bytes + metadata for a non-JSON (binary) RPC response', async () => { - // Leading bytes of a real PDF; the 0xc4 byte is invalid UTF-8 and is exactly what makes - // an unconditional response.json() throw on a binary body. - const pdfBytes = new Uint8Array([ - 0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34, 0x0a, 0x25, 0xc4, 0xe5, 0xf2, 0xe5, 0xeb, - ]); - server.use( - http.post( - `${TEST_BASE_URL}/actions/rpc`, - () => - new HttpResponse(pdfBytes, { - status: 200, - headers: { - 'content-type': 'application/pdf', - 'content-disposition': 'attachment; filename="../../download.pdf"', - }, - }), - ), - ); - - const result = await newClient().rpcAction( - request('googledrive_unified_download_file', { path: { id: 'file-123' } }), - 'acc-1', - ); - - assert(isBinaryDownloadResult(result), 'expected a binary download result'); - expect(result.content.equals(Buffer.from(pdfBytes))).toBe(true); - expect(result.contentType).toBe('application/pdf'); - expect(result.statusCode).toBe(200); - // Reduced to a basename: the traversal never reaches the caller. - expect(result.fileName).toBe('download.pdf'); - expect(result.headers['content-type']).toBe('application/pdf'); - }); - - it('returns bytes with fileName null when there is no Content-Disposition', async () => { - const blob = new Uint8Array([0x00, 0x01, 0x02, 0xc4, 0xff, 0xfe]); - server.use( - http.post( - `${TEST_BASE_URL}/actions/rpc`, - () => new HttpResponse(blob, { headers: { 'content-type': 'application/octet-stream' } }), - ), - ); - - const result = await newClient().rpcAction(request('some_unified_download_file'), 'acc-1'); - - assert(isBinaryDownloadResult(result), 'expected a binary download result'); - expect(result.content.equals(Buffer.from(blob))).toBe(true); - expect(result.fileName).toBeNull(); - }); - - it('treats a missing Content-Type as opaque bytes, not JSON', async () => { - const jpeg = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]); - server.use(http.post(`${TEST_BASE_URL}/actions/rpc`, () => new HttpResponse(jpeg))); - - const result = await newClient().rpcAction(request('x'), 'acc-1'); - - assert(isBinaryDownloadResult(result), 'expected a binary download result'); - expect(result.contentType).toBe('application/octet-stream'); - }); - - it('parses JSON when the Content-Type carries a charset parameter', async () => { - server.use( - http.post( - `${TEST_BASE_URL}/actions/rpc`, - () => - new HttpResponse('{"data":{"ok":true}}', { - headers: { 'content-type': 'application/json; charset=utf-8' }, - }), - ), - ); - - expect(await newClient().rpcAction(request('x'), 'acc-1')).toEqual({ data: { ok: true } }); - }); -}); diff --git a/src/rpc-client.ts b/src/rpc-client.ts deleted file mode 100644 index 9e8400b1..00000000 --- a/src/rpc-client.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { buildRequestHeaders } from './headers'; -import type { JsonObject } from './types'; -import { - type BinaryDownloadResult, - binaryDownloadFromResponse, - isJsonContentType, -} from './utils/binary-response'; -import { StackOneAPIError, describeApiFailure } from './utils/error-stackone-api'; -import { StackOneError } from './utils/error-stackone'; - -/** - * The `/actions/rpc` request body. - * - * @see https://docs.stackone.com/platform/api-reference/actions/make-an-rpc-call-to-an-action - */ -export interface RpcActionRequest { - action: string; - body: JsonObject; - headers: Record; - path?: JsonObject; - query?: JsonObject; -} - -/** - * A bodyless success (`204`/`205`, or an empty JSON body). Not a file download: returning an - * empty `content` with a made-up content type would break any caller that re-serialises results. - */ -interface EmptyRpcResult { - statusCode: number; -} - -interface RpcClientConfig { - baseUrl: string; - apiKey: string; - /** Request timeout in milliseconds. */ - timeout: number; - /** Extra HTTP headers sent with every request, beneath the SDK's own. */ - headers?: Record; -} - -const readErrorBody = async (response: Response): Promise => { - const text = await response.text().catch(() => ''); - if (!text) { - return null; - } - try { - return JSON.parse(text) as unknown; - } catch { - return text; - } -}; - -/** - * Client for the StackOne actions RPC endpoint. - * - * The account a request runs against is the `x-account-id` HTTP header, set here from the tool's - * own account — never read out of the envelope, whose contents are model-supplied. - */ -export class RpcClient { - readonly url: string; - readonly #apiKey: string; - readonly #timeout: number; - readonly #headers: Record; - - constructor(config: RpcClientConfig) { - this.url = `${config.baseUrl.replace(/\/+$/, '')}/actions/rpc`; - this.#apiKey = config.apiKey; - this.#timeout = config.timeout; - this.#headers = { ...config.headers }; - } - - /** - * The HTTP headers a request for `accountId` carries. - */ - requestHeaders(accountId: string | undefined): Record { - return { - 'Content-Type': 'application/json', - ...buildRequestHeaders({ apiKey: this.#apiKey, accountId, extraHeaders: this.#headers }), - }; - } - - /** - * Execute an RPC action. - * - * @returns The parsed JSON response (a non-object body is wrapped as `{ result }`); for a - * file-download action served as raw binary, a {@link BinaryDownloadResult}; for a bodyless - * success, `{ statusCode }`. - * @throws StackOneAPIError When the API answers with an error status, or with a JSON content - * type whose body is not JSON. - * @throws StackOneError When the request cannot be sent or times out. - */ - async rpcAction( - request: RpcActionRequest, - accountId: string | undefined, - ): Promise { - let body: string; - try { - body = JSON.stringify(request); - } catch (error) { - // A BigInt or a cycle: an argument problem, reported as one rather than escaping as a - // bare TypeError from inside fetch. - throw new StackOneError( - `Arguments for "${request.action}" could not be encoded as JSON: ${error instanceof Error ? error.message : String(error)}`, - { cause: error }, - ); - } - - let response: Response; - try { - response = await fetch(this.url, { - method: 'POST', - headers: this.requestHeaders(accountId), - body, - signal: AbortSignal.timeout(this.#timeout), - }); - } catch (error) { - if ( - error instanceof Error && - (error.name === 'TimeoutError' || error.name === 'AbortError') - ) { - throw new StackOneError(`Request to ${this.url} timed out after ${this.#timeout}ms`, { - cause: error, - }); - } - throw new StackOneError( - `Request failed: ${error instanceof Error ? error.message : String(error)}`, - { cause: error }, - ); - } - - if (!response.ok) { - const errorBody = await readErrorBody(response); - throw new StackOneAPIError( - describeApiFailure(response.status, response.statusText, errorBody, this.url), - response.status, - errorBody, - request, - ); - } - - const contentType = response.headers.get('content-type') ?? ''; - if (response.status === 204 || response.status === 205) { - return { statusCode: response.status }; - } - if (!isJsonContentType(contentType)) { - // A non-JSON success is a file download (e.g. a *_download_file action): raw bytes - // with the file's own MIME type and a Content-Disposition. A zero-byte body with a - // download content type is an empty file, with a filename the caller still needs. - return binaryDownloadFromResponse(response); - } - - const text = await response.text(); - if (!text) { - return { statusCode: response.status }; - } - let parsed: unknown; - try { - parsed = JSON.parse(text); - } catch (error) { - // Not the caller's arguments — the server sent a JSON content type with a body that - // is not JSON. Blaming the arguments here sends people to debug the wrong end. - throw new StackOneAPIError( - `Server sent malformed JSON for "${request.action}": ${error instanceof Error ? error.message : String(error)}`, - response.status, - text.slice(0, 500), - request, - { cause: error }, - ); - } - return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) - ? (parsed as JsonObject) - : { result: parsed as JsonObject[string] }; - } -} diff --git a/src/tool.test.ts b/src/tool.test.ts index 020a85de..5e8d6dab 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -1,13 +1,12 @@ +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { jsonSchema } from 'ai'; -import { http, HttpResponse } from 'msw'; +import { http } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; import { type RecordedToolCall, createMcpApp } from '../mocks/mcp-server'; import { server } from '../mocks/node'; -import { RpcClient } from './rpc-client'; import { toolParametersFromInputSchema } from './schema'; -import { BaseTool, StackOneMcpTool, StackOneRpcTool, StackOneTool, Tools } from './tool'; +import { BaseTool, StackOneMcpTool, StackOneTool, Tools } from './tool'; import type { AISDKToolResult, JsonObject, JSONSchema, ToolParameters } from './types'; -import { isBinaryDownloadResult } from './utils/binary-response'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; @@ -266,74 +265,75 @@ describe('BaseTool', () => { }); }); -describe('StackOneRpcTool', () => { - const client = new RpcClient({ baseUrl: TEST_BASE_URL, apiKey: 'test-key', timeout: 5_000 }); - const rpcTool = (properties: Record) => - new StackOneRpcTool({ +describe('StackOneMcpTool as an action tool', () => { + const calls: RecordedToolCall[] = []; + const nestedProperties = { + path: { type: 'object', properties: { id: { type: 'string' } } }, + query: { type: 'object', properties: { expand: { type: 'string' } } }, + body: { type: 'object', properties: { name: { type: 'string' } } }, + headers: { type: 'object', properties: { 'x-trace': { type: 'string' } } }, + } satisfies Record; + const listed = { + name: 'crm_update_contact', + description: 'Update a contact', + inputSchema: { type: 'object' as const, properties: nestedProperties }, + }; + const serve = (toolResults: Record = {}) => { + const app = createMcpApp({ + accountTools: { acc1: [listed], acc2: [listed] }, + onToolCall: (call) => calls.push(call), + toolResults, + }); + server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); + }; + beforeEach(() => { + calls.length = 0; + serve(); + }); + + const actionTool = (properties: Record = nestedProperties) => + new StackOneMcpTool({ name: 'crm_update_contact', description: 'Update a contact', parameters: toolParametersFromInputSchema({ type: 'object', properties }), - client, + endpoint: `${TEST_BASE_URL}/mcp`, + apiKey: 'test-key', accountId: 'acc1', + timeout: 5_000, }); - const flatProperties = { - path_id: { type: 'string' }, - query_expand: { type: 'string' }, - body_name: { type: 'string' }, - 'headers_x-trace': { type: 'string' }, - } satisfies Record; - const captureRpc = ( - response: () => Response = () => HttpResponse.json({ data: { ok: true } }), - ) => { - const seen: Array<{ headers: Headers; body: Record }> = []; - server.use( - http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { - seen.push({ - headers: request.headers, - body: (await request.json()) as Record, - }); - return response(); - }), - ); - return seen; - }; + it('sends the arguments verbatim over tools/call, scoped to its account', async () => { + const args = { + path: { id: '7' }, + query: { expand: 'owner' }, + body: { name: 'Ada' }, + headers: { 'x-trace': 't-1' }, + }; - it('sends the flat_prefixed arguments as the RPC envelope, scoped to its account', async () => { - const seen = captureRpc(); + const result = await actionTool().execute(args); - const result = await rpcTool(flatProperties).execute({ - path_id: '7', - query_expand: 'owner', - body_name: 'Ada', - 'headers_x-trace': 't-1', + expect(calls).toEqual([ + { accountId: 'acc1', toolMode: undefined, name: 'crm_update_contact', arguments: args }, + ]); + // As the server wrote it: UCA's { isError: false, result } wrapper included. + expect(result).toEqual({ + isError: false, + result: { data: { action: 'crm_update_contact', account_id: 'acc1', arguments: args } }, }); + }); - expect(result).toEqual({ data: { ok: true } }); - expect(seen[0]?.headers.get('x-account-id')).toBe('acc1'); - expect(seen[0]?.body).toEqual({ - action: 'crm_update_contact', - body: { name: 'Ada' }, - headers: { 'x-trace': 't-1', 'x-account-id': 'acc1' }, - path: { id: '7' }, - query: { expand: 'owner' }, - }); + it('sends flat_prefixed arguments verbatim too', async () => { + const args = { path_id: '7', 'headers_x-trace': 't-1' }; + await actionTool({ + path_id: { type: 'string' }, + 'headers_x-trace': { type: 'string' }, + }).execute(args); + expect(calls[0]?.arguments).toEqual(args); }); it('accepts arguments as a JSON string', async () => { - const seen = captureRpc(); - await rpcTool(flatProperties).execute('{"path_id":"7"}'); - expect(seen[0]?.body.path).toEqual({ id: '7' }); - }); - - it('omits empty path and query, but always sends body and headers', async () => { - const seen = captureRpc(); - await rpcTool(flatProperties).execute(); - expect(seen[0]?.body).toEqual({ - action: 'crm_update_contact', - body: {}, - headers: { 'x-account-id': 'acc1' }, - }); + await actionTool().execute('{"path":{"id":"7"}}'); + expect(calls[0]?.arguments).toEqual({ path: { id: '7' } }); }); it.each([ @@ -346,134 +346,95 @@ describe('StackOneRpcTool', () => { ['Cookie', 'session=x'], ])('drops a model-supplied %j header', async (name, value) => { vi.spyOn(console, 'warn').mockImplementation(() => {}); - const seen = captureRpc(); - await rpcTool(flatProperties).execute({ headers: { [name]: value } }); + await actionTool().execute({ headers: { [name]: value } }); - expect(seen[0]?.body.headers).toEqual({ 'x-account-id': 'acc1' }); - expect(seen[0]?.headers.get('x-account-id')).toBe('acc1'); - expect(seen[0]?.headers.get('authorization')).toMatch(/^Basic /); + expect(calls[0]?.arguments.headers).toEqual({}); + expect(calls[0]?.accountId).toBe('acc1'); vi.restoreAllMocks(); }); - it('drops a declared header carrying CR/LF', async () => { + it('keeps a header a nested schema declares, and drops one carrying CR/LF', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}); - const seen = captureRpc(); - await rpcTool(flatProperties).execute({ 'headers_x-trace': 'a\r\nInjected: 1' }); - expect(seen[0]?.body.headers).toEqual({ 'x-account-id': 'acc1' }); - vi.restoreAllMocks(); - }); - - it('routes a bare schema field that merely starts with path_ to the body, warning once', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - const seen = captureRpc(); - const tool = rpcTool({ path_to_file: { type: 'string' }, name: { type: 'string' } }); - - await tool.execute({ path_to_file: '/tmp/x' }); - await tool.execute({ path_to_file: '/tmp/y' }); - - expect(seen[0]?.body.body).toEqual({ path_to_file: '/tmp/x' }); - expect(seen[0]?.body).not.toHaveProperty('path'); - expect(warn).toHaveBeenCalledTimes(1); - expect(String(warn.mock.calls[0]?.[0])).toContain('flat-prefix detection is disabled'); + 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' }); + expect(calls[1]?.arguments.headers).toEqual({}); vi.restoreAllMocks(); }); - it('rejects a reserved container given a scalar', async () => { - await expect(rpcTool(flatProperties).execute({ query: 'sales' })).rejects.toThrow( - /"query" is an envelope container/, - ); - }); - - it('describes the request without sending it on dryRun', async () => { - const seen = captureRpc(); - const result = await rpcTool(flatProperties).execute({ path_id: '7' }, { dryRun: true }); - - expect(seen).toHaveLength(0); - expect(result.url).toBe(`${TEST_BASE_URL}/actions/rpc`); - expect(result.method).toBe('POST'); - expect(result.headers).toMatchObject({ 'x-account-id': 'acc1' }); - expect(result.headers).not.toHaveProperty('Authorization'); - expect(JSON.parse(result.body as string)).toEqual({ - action: 'crm_update_contact', - body: {}, - headers: { 'x-account-id': 'acc1' }, - path: { id: '7' }, - }); - expect(result.mappedParams).toEqual({ path_id: '7' }); - }); - it.each([ ['not valid json', /Invalid JSON in arguments/], ['[1, 2, 3]', /must be a JSON object/], ['null', /must be a JSON object/], ])('rejects arguments %j', async (input, message) => { - await expect(rpcTool(flatProperties).execute(input)).rejects.toThrow(message); + await expect(actionTool().execute(input)).rejects.toThrow(message); }); it('rejects a non-object, non-string argument', async () => { // @ts-expect-error - intentionally passing an invalid type - await expect(rpcTool(flatProperties).execute(12345)).rejects.toThrow(StackOneError); - }); - - it('reports arguments JSON cannot encode as an argument error', async () => { - await expect(rpcTool(flatProperties).execute({ body_name: 1n as never })).rejects.toThrow( - /could not be encoded as JSON/, - ); + await expect(actionTool().execute(12345)).rejects.toThrow(StackOneError); }); - it('surfaces an API rejection with its status, body and the server message', async () => { - captureRpc(() => - HttpResponse.json( - { message: 'path.id is missing' }, - { status: 400, statusText: 'Bad Request' }, - ), - ); - - const error = (await rpcTool(flatProperties) + it('is refused by the server when it has no account', async () => { + const error = (await actionTool() + .setAccountId(undefined) .execute({}) .catch((caught: unknown) => caught)) as StackOneAPIError; expect(error).toBeInstanceOf(StackOneAPIError); expect(error.statusCode).toBe(400); - expect(error.message).toBe('400 Bad Request: path.id is missing'); }); - it('is refused by the server when it has no account', async () => { - const tool = rpcTool({ foo: { type: 'string' } }).setAccountId(undefined); - const error = (await tool - .execute({ foo: 'bar' }) - .catch((caught: unknown) => caught)) as StackOneAPIError; + it('returns a file action’s download link as the server sent it', async () => { + const link = { + download_url: `${TEST_BASE_URL}/actions/download/v1.eu.token`, + expires_at: '2026-09-29T12:05:00.000Z', + file: { name: 'report.pdf', content_type: 'application/pdf', content_length: 3 }, + }; + const structuredContent = { isError: false, result: link }; + serve({ + crm_update_contact: { + content: [{ type: 'text', text: JSON.stringify(structuredContent) }], + structuredContent, + }, + }); - expect(error.statusCode).toBe(400); + expect(await actionTool().execute({})).toEqual({ isError: false, result: link }); }); - it('returns a download with a safe file name', async () => { - captureRpc( - () => - new HttpResponse(new Uint8Array([1, 2, 3]), { - headers: { - 'content-type': 'application/pdf', - 'content-disposition': "attachment; filename*=UTF-8''%2e%2e%2fsecret.pdf", - }, - }), - ); + it('raises with status 501 when the server can issue no download link', async () => { + const structuredContent = { + isError: true, + result: { + error: 'This action returned a file, which cannot be delivered in a tool result', + status_code: 501, + }, + }; + serve({ + crm_update_contact: { + isError: true, + content: [{ type: 'text', text: JSON.stringify(structuredContent) }], + structuredContent, + }, + }); - const result = await rpcTool(flatProperties).execute({ path_id: 'f' }); + const error = (await actionTool() + .execute({}) + .catch((caught: unknown) => caught)) as StackOneAPIError; - assert(isBinaryDownloadResult(result)); - expect(result.fileName).toBe('secret.pdf'); + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(501); }); it('can be rebound to another account', async () => { - const seen = captureRpc(); - const tool = rpcTool(flatProperties); + const tool = actionTool(); tool.setAccountId('acc2'); await tool.execute({}); expect(tool.getAccountId()).toBe('acc2'); - expect(seen[0]?.headers.get('x-account-id')).toBe('acc2'); + expect(calls[0]?.accountId).toBe('acc2'); }); }); @@ -493,7 +454,7 @@ describe('StackOneMcpTool', () => { name: 'mock_acc1_execute_action', description: 'Execute', parameters: toolParametersFromInputSchema({ type: 'object', properties }), - endpoint: `${TEST_BASE_URL}/mcp?param-style=flat_prefixed&tool-mode=search_execute`, + endpoint: `${TEST_BASE_URL}/mcp?tool-mode=search_execute`, apiKey: 'test-key', accountId: 'acc1', timeout: 5_000, @@ -505,7 +466,10 @@ describe('StackOneMcpTool', () => { query: { page_size: 2 }, }); - expect(result).toMatchObject({ data: { nodes: [] }, echoed_query: { page_size: 2 } }); + expect(result).toMatchObject({ + isError: false, + result: { data: { nodes: [] }, echoed_query: { page_size: 2 } }, + }); expect(calls).toEqual([ { accountId: 'acc1', @@ -714,12 +678,14 @@ describe('Tools.executeOpenAIToolCalls', () => { }); it('reports malformed arguments the same way', async () => { - const tool = new StackOneRpcTool({ + const tool = new StackOneMcpTool({ name: 'linear_list_issues', description: '', parameters: { type: 'object', properties: {} }, - client: new RpcClient({ baseUrl: TEST_BASE_URL, apiKey: 'k', timeout: 1_000 }), + endpoint: `${TEST_BASE_URL}/mcp`, + apiKey: 'k', accountId: 'acc1', + timeout: 1_000, }); const [message] = await new Tools([tool]).executeOpenAIToolCalls([ call('linear_list_issues', '{not json'), diff --git a/src/tool.ts b/src/tool.ts index b66302c4..51192d81 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -9,10 +9,8 @@ import type { import type { FunctionTool as OpenAIResponsesFunctionTool } from 'openai/resources/responses/responses'; import type { OverrideProperties } from 'type-fest'; import { peerDependencies } from '../package.json'; -import { isFlatPrefixedSchema, splitEnvelopeParams, warnBareSchema } from './envelope'; import { buildRequestHeaders, declaredHeaderNames, sanitiseHeaders } from './headers'; import { callMcpTool } from './mcp-client'; -import type { RpcActionRequest, RpcClient } from './rpc-client'; import { cloneJson, foldRootComposition } from './schema'; import type { AISDKToolDefinition, @@ -23,7 +21,6 @@ import type { JsonObject, JSONSchema, McpExecuteConfig, - RpcExecuteConfig, ToolExecution, ToolParameters, } from './types'; @@ -45,9 +42,8 @@ const isPlainObject = (value: unknown): value is JsonObject => * Base class for all tools: a name, a description, the served parameter schema, and conversions * to each framework's tool format. * - * `BaseTool` itself cannot execute anything. The tools a {@link StackOneToolSet} returns are - * {@link StackOneTool}s that execute over the RPC endpoint or MCP `tools/call`; a hand-built - * tool must override {@link BaseTool.execute}. + * `BaseTool` itself cannot execute anything. The tools a {@link StackOneToolSet} returns execute + * over MCP `tools/call`; a hand-built tool must override {@link BaseTool.execute}. */ export class BaseTool { name: string; @@ -346,116 +342,9 @@ export class StackOneTool extends BaseTool { } /** - * A tool executed over the StackOne actions RPC endpoint — every per-action tool in the - * `individual` catalog. - * - * Arguments are split into the RPC envelope by their `flat_prefixed` location prefix, whether - * to trust that prefix being decided once from the served schema. Headers are filtered to the - * ones the schema declares, and the account is always the tool's own. - */ -export class StackOneRpcTool extends StackOneTool { - readonly #client: RpcClient; - readonly #declared: ReadonlySet; - readonly #flatPrefixed: boolean; - readonly #allowedHeaders: ReadonlySet; - #warnedBareSchema = false; - - constructor(options: { - name: string; - description: string; - parameters: ToolParameters; - client: RpcClient; - accountId?: string; - }) { - const executeConfig = { - kind: 'rpc', - method: 'POST', - url: options.client.url, - // Mirrors the StackOne RPC payload layout so metadata/debug stays in sync. - payloadKeys: { - action: 'action', - body: 'body', - headers: 'headers', - path: 'path', - query: 'query', - }, - } as const satisfies RpcExecuteConfig; - super(options.name, options.description, options.parameters, executeConfig, options.accountId); - this.setExposeExecutionMetadata(false); - this.#client = options.client; - this.#declared = new Set(Object.keys(options.parameters.properties)); - this.#flatPrefixed = isFlatPrefixedSchema(this.#declared); - this.#allowedHeaders = declaredHeaderNames(this.#declared); - } - - /** - * Build the `/actions/rpc` request for these arguments. - */ - #buildRequest(args: JsonObject): RpcActionRequest { - if (!this.#flatPrefixed && !this.#warnedBareSchema) { - this.#warnedBareSchema = true; - warnBareSchema(this.name); - } - const envelope = splitEnvelopeParams(args, this.#declared, this.#flatPrefixed); - const headers = sanitiseHeaders(envelope.headers, this.#allowedHeaders); - // Set last, so nothing a tool call supplies can retarget the request. - const accountId = this.getAccountId(); - if (accountId) { - headers['x-account-id'] = accountId; - } - return { - action: this.name, - body: envelope.body, - headers, - ...(Object.keys(envelope.path).length > 0 ? { path: envelope.path } : {}), - ...(Object.keys(envelope.query).length > 0 ? { query: envelope.query } : {}), - }; - } - - /** - * Execute the action. - * - * @returns The parsed JSON response. For a file download (any non-JSON Content-Type), a - * {@link BinaryDownloadResult} whose `content` is a raw `Buffer` — not JSON-serialisable, so - * handle it before re-serialising the result for a model. - * @throws StackOneAPIError If the API rejects the request; the message leads with the - * server's own explanation. - * @throws StackOneError If the arguments are malformed or the request cannot be sent. - */ - override async execute( - inputParams?: JsonObject | string, - options?: ExecuteOptions, - ): Promise { - try { - const args = this.parseArguments(inputParams); - const request = this.#buildRequest(args); - const accountId = this.getAccountId(); - - if (options?.dryRun) { - const { Authorization: _credential, ...headers } = this.#client.requestHeaders(accountId); - return { - url: this.#client.url, - method: 'POST', - headers, - body: JSON.stringify(request), - mappedParams: args, - }; - } - - return (await this.#client.rpcAction(request, accountId)) as unknown as JsonObject; - } catch (error) { - if (error instanceof StackOneError) { - throw error; - } - throw new StackOneError(`Error executing RPC action ${this.name}`, { cause: error }); - } - } -} - -/** - * A tool executed over MCP `tools/call` on the endpoint that listed it: the `search_execute` - * meta tools, and `stackone_submit_feedback` in every mode. They have no action behind them on - * `/actions/rpc`. + * A tool executed over MCP `tools/call`, on the endpoint and account that listed it. Every tool a + * {@link StackOneToolSet} returns is one: per-action tools, the `search_execute` meta tools, and + * `stackone_submit_feedback`. */ export class StackOneMcpTool extends StackOneTool { readonly #endpoint: string; @@ -485,16 +374,19 @@ export class StackOneMcpTool extends StackOneTool { this.#apiKey = options.apiKey; this.#extraHeaders = { ...options.extraHeaders }; this.#timeout = options.timeout; - this.#allowedHeaders = declaredHeaderNames(Object.keys(options.parameters.properties)); + this.#allowedHeaders = declaredHeaderNames(options.parameters.properties); } /** * Call the tool. * - * A `headers` object in the arguments is filtered to what this tool's own schema declares - * under `headers_*` — for the meta tools that is nothing, so every model-supplied header is - * dropped: these arguments are model-controlled, and the envelope is unpacked server-side. + * Arguments are sent as given; the server maps them onto the action. A `headers` object in + * them is filtered to the headers this tool's own schema declares — for the meta tools that is + * nothing, so every model-supplied header is dropped: these arguments are model-controlled. * + * @returns The result as the server wrote it: for an action tool, + * `{ isError: false, result, defenderMetadata?, policyMetadata? }`. A file action's `result` + * is the server's single-use `download_url`, not the file. * @throws StackOneAPIError If the result carries `isError`, with the status from its payload, * or the endpoint answers with an HTTP error. * @throws ToolSetLoadError If the endpoint cannot be reached or does not answer in time. diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 07b28a4d..51e285dd 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -208,8 +208,8 @@ describe('search()', () => { await toolset.fetchTools(); expect(listMock.mock.calls.map(([request]) => request.endpoint.split('?')[1])).toEqual([ - 'param-style=flat_prefixed&tool-mode=search_execute', - 'param-style=flat_prefixed', + 'tool-mode=search_execute', + undefined, ]); }); }); @@ -220,7 +220,10 @@ describe('execute()', () => { const toolset = newToolSet(); const [hit] = await toolset.search('list items'); - expect(await toolset.execute(hit?.action_id ?? '')).toMatchObject({ data: { nodes: [] } }); + expect(await toolset.execute(hit?.action_id ?? '')).toMatchObject({ + isError: false, + result: { data: { nodes: [] } }, + }); }); it('passes the nested envelope through verbatim', async () => { @@ -231,7 +234,7 @@ describe('execute()', () => { const result = await toolset.execute(hit?.action_id ?? '', hit?.example_request as JsonObject); - expect(result.echoed_query).toEqual({ page_size: 25 }); + expect((result.result as JsonObject).echoed_query).toEqual({ page_size: 25 }); }); // Contract §5: session_id is forwarded as a top-level argument when given, never otherwise, @@ -301,23 +304,6 @@ describe('execute()', () => { expect(error.statusCode).toBe(404); }); - it('unwraps the meta tool’s { isError, result } envelope', async () => { - fakeMetaTools(['linear_acc1_execute_action'], () => ({ - isError: false, - result: { data: { nodes: [1, 2] } }, - })); - expect(await newToolSet({ accountId: 'acc1' }).execute('linear_list_issues')).toEqual({ - data: { nodes: [1, 2] }, - }); - }); - - it('wraps a non-object meta tool result', async () => { - fakeMetaTools(['linear_acc1_execute_action'], () => ({ isError: false, result: [1] })); - expect(await newToolSet({ accountId: 'acc1' }).execute('linear_list_issues')).toEqual({ - result: [1], - }); - }); - it('routes an account id containing underscores by identity', async () => { const calls = fakeMetaTools(['linear_acc_1_execute_action']); await newToolSet({ accountId: 'acc_1' }).execute('linear_list_issues'); @@ -397,8 +383,8 @@ describe('submitFeedback()', () => { }); expect(result).toMatchObject({ - message: 'Feedback recorded', - session_id: MOCK_SEARCH_SESSION_ID, + isError: false, + result: { message: 'Feedback recorded', session_id: MOCK_SEARCH_SESSION_ID }, }); expect(calls).toEqual([ { diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 45534fc1..6512fb3c 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -6,10 +6,15 @@ import { createServer, type Server as NetServer, type Socket } from 'node:net'; import { http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; -import { type McpToolDefinition, accountMcpTools, createMcpApp } from '../mocks/mcp-server'; +import { + type McpToolDefinition, + type RecordedToolCall, + accountMcpTools, + createMcpApp, +} from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { type McpToolDefinition as ListedTool, listMcpTools } from './mcp-client'; -import { StackOneMcpTool, StackOneRpcTool, type StackOneTool } from './tool'; +import { StackOneMcpTool, type StackOneTool } from './tool'; import { StackOneToolSet } from './toolsets'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; @@ -317,12 +322,11 @@ describe('server refusals', () => { }); describe('listing', () => { - it('pins param-style=flat_prefixed on the MCP listing URL', async () => { + // 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 () => { fakeListing(() => []); await newToolSet({ baseUrl: 'https://api.example.com/' }).fetchTools({ accountIds: ['acc1'] }); - expect(listMock.mock.calls[0]?.[0].endpoint).toBe( - 'https://api.example.com/mcp?param-style=flat_prefixed', - ); + expect(listMock.mock.calls[0]?.[0].endpoint).toBe('https://api.example.com/mcp'); }); it('passes the timeout to every listing', async () => { @@ -601,10 +605,10 @@ describe('catalog cache', () => { }); describe('tool mode', () => { - it('builds RPC tools by default', async () => { + it('builds MCP tools by default', async () => { fakeListing(() => [def('t')]); expect((await newToolSet({ accountId: 'acc1' }).fetchTools()).getTool('t')).toBeInstanceOf( - StackOneRpcTool, + StackOneMcpTool, ); }); @@ -614,7 +618,7 @@ describe('tool mode', () => { expect(tools.getTool('t')).toBeInstanceOf(StackOneMcpTool); expect(listMock.mock.calls[0]?.[0].endpoint).toBe( - `${TEST_BASE_URL}/mcp?param-style=flat_prefixed&tool-mode=search_execute`, + `${TEST_BASE_URL}/mcp?tool-mode=search_execute`, ); }); @@ -622,13 +626,13 @@ describe('tool mode', () => { fakeListing(() => [def('t')]); const toolset = newToolSet({ accountId: 'acc1', toolMode: 'search_execute' }); - expect((await toolset.fetchTools({ mode: null })).getTool('t')).toBeInstanceOf(StackOneRpcTool); + expect((await toolset.fetchTools({ mode: null })).getTool('t')).toBeInstanceOf(StackOneMcpTool); expect((await toolset.fetchTools({ mode: 'individual' })).getTool('t')).toBeInstanceOf( - StackOneRpcTool, + StackOneMcpTool, ); expect(listMock.mock.calls.map(([request]) => request.endpoint.split('?')[1])).toEqual([ - 'param-style=flat_prefixed', - 'param-style=flat_prefixed&tool-mode=individual', + undefined, + 'tool-mode=individual', ]); }); }); @@ -689,9 +693,7 @@ describe('stackone_submit_feedback in the catalog', () => { expect(tool).toBeInstanceOf(StackOneMcpTool); expect( await tool?.execute({ rating: 'positive', tool_names: ['acc1_tool_1'] }), - ).toMatchObject({ - message: 'Feedback recorded', - }); + ).toMatchObject({ isError: false, result: { message: 'Feedback recorded' } }); expect(rpcRequests).toEqual([]); }, ); @@ -705,34 +707,33 @@ describe('stackone_submit_feedback in the catalog', () => { }); describe('execution through fetched tools', () => { - it('executes an RPC tool against its account', async () => { + it('executes an action tool over tools/call against its account', async () => { const tools = await newToolSet({ accountId: 'your-bamboohr-account-id' }).fetchTools(); const result = await tools.getTool('bamboohr_get_employee')?.execute({ id: 'emp-123' }); - expect(result).toMatchObject({ data: { id: 'emp-123', name: 'Test Employee' } }); + expect(result).toEqual({ + isError: false, + result: { + data: { + action: 'bamboohr_get_employee', + account_id: 'your-bamboohr-account-id', + arguments: { id: 'emp-123' }, + }, + }, + }); }); }); 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))); - }; - const captureRpc = () => { - const seen: { accountHeader: string | null; body: Record }[] = []; - server.use( - http.post(`${TEST_BASE_URL}/actions/rpc`, async ({ request }) => { - seen.push({ - accountHeader: request.headers.get('x-account-id'), - body: (await request.json()) as Record, - }); - return HttpResponse.json({ data: {} }); - }), - ); - return seen; + return calls; }; const fetchTool = async () => { const tool = (await newToolSet({ accountId: 'tenant-a' }).fetchTools()).getTool( @@ -742,42 +743,44 @@ describe('model-supplied headers', () => { return tool; }; - // Regression: the envelope headers were merged OVER the tool's own headers, so a - // model-supplied x-account-id replaced the account the tool was fetched for — on the - // envelope and on the HTTP header the API actually reads. + // 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; an argument is only ever an argument. it('cannot switch tenant with headers_x-account-id, even when the schema declares it', async () => { - serveTool({ + const calls = serveTool({ type: 'object', properties: { 'headers_x-account-id': { type: 'string' }, query_limit: { type: 'number' } }, }); - const seen = captureRpc(); const tool = await fetchTool(); await tool.execute({ 'headers_x-account-id': 'tenant-b', query_limit: 1 }); - expect(seen[0]?.accountHeader).toBe('tenant-a'); - expect(seen[0]?.body.headers).toMatchObject({ 'x-account-id': 'tenant-a' }); + expect(calls[0]?.accountId).toBe('tenant-a'); }); it('cannot switch tenant with a nested headers object', async () => { - serveTool({ type: 'object', properties: { query_limit: { type: 'number' } } }); - const seen = captureRpc(); + const calls = serveTool({ + type: 'object', + properties: { headers: { type: 'object', properties: {} } }, + }); const tool = await fetchTool(); await tool.execute({ headers: { 'X-Account-Id': 'tenant-b', Authorization: 'Bearer stolen' } }); - expect(seen[0]?.accountHeader).toBe('tenant-a'); - expect(seen[0]?.body.headers).toEqual({ 'x-account-id': 'tenant-a' }); + expect(calls[0]?.accountId).toBe('tenant-a'); + expect(calls[0]?.arguments.headers).toEqual({}); }); it('forwards a header the served schema declares', async () => { - serveTool({ type: 'object', properties: { 'headers_x-trace': { type: 'string' } } }); - const seen = captureRpc(); + const calls = serveTool({ + type: 'object', + properties: { headers: { type: 'object', properties: { 'x-trace': { type: 'string' } } } }, + }); const tool = await fetchTool(); - await tool.execute({ 'headers_x-trace': 'abc', 'headers_x-other': 'dropped' }); + await tool.execute({ headers: { 'x-trace': 'abc', 'x-other': 'dropped' } }); - expect(seen[0]?.body.headers).toEqual({ 'x-trace': 'abc', 'x-account-id': 'tenant-a' }); + expect(calls[0]?.arguments.headers).toEqual({ 'x-trace': 'abc' }); }); }); diff --git a/src/toolsets.ts b/src/toolsets.ts index fa1b534b..18d69455 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -4,14 +4,12 @@ import { DEFAULT_TIMEOUT_MS, MAX_CONCURRENCY, MAX_TOP_K, - MCP_PARAM_STYLE, SUBMIT_FEEDBACK_TOOL_NAME, } from './consts'; import { buildRequestHeaders, isSdkOwnedHeader } from './headers'; import { type McpToolDefinition, listMcpTools } from './mcp-client'; -import { RpcClient } from './rpc-client'; import { cloneJson, toolParametersFromInputSchema } from './schema'; -import { StackOneMcpTool, StackOneRpcTool, type StackOneTool, Tools } from './tool'; +import { StackOneMcpTool, type StackOneTool, Tools } from './tool'; import type { FeedbackCategory, FeedbackRating, @@ -80,8 +78,8 @@ interface StackOneToolSetBaseConfig { */ headers?: Record; /** - * Request timeout in milliseconds, applied to every MCP call (listing and `tools/call`), to - * RPC execution and to account discovery. Default: 60000 (60s). + * Request timeout in milliseconds, applied to every MCP call (listing and `tools/call`) and to + * account discovery. Default: 60000 (60s). */ timeout?: number; /** @@ -285,10 +283,9 @@ const assertAccountIdList = (accountIds: unknown, parameter: string): void => { /** * The StackOne toolset: lists the served tool catalog and exposes it to agent frameworks. * - * A thin client over the catalog. Tools are listed from the MCP endpoint, per account, and - * executed against the actions RPC endpoint (or over MCP `tools/call` for the tools that have no - * action behind them). Schemas are passed through as served, never rewritten, filtered or - * invented. + * A thin client over the MCP endpoint. Tools are listed from it, per account, and executed over + * its `tools/call`; the only other request is `GET /accounts`, to discover accounts. Schemas and + * arguments are passed through as served, never rewritten, filtered or invented. * * An API key is enough: with no account configured, the toolset lists every active account * linked to the key. @@ -301,7 +298,6 @@ export class StackOneToolSet { readonly #toolMode: ToolMode | undefined; readonly #accountId: string | undefined; #accountIds: string[]; - readonly #rpcClient: RpcClient; /** * The listing per account scope, not the Tools built from it. Tools are mutable @@ -352,12 +348,6 @@ export class StackOneToolSet { this.#toolMode = config.toolMode; this.#accountId = config.accountId || process.env.STACKONE_ACCOUNT_ID || undefined; this.#accountIds = [...(config.accountIds ?? config.execute?.accountIds ?? [])]; - this.#rpcClient = new RpcClient({ - baseUrl: this.#baseUrl, - apiKey: this.#apiKey, - timeout: this.#timeout, - headers: this.#headers, - }); } /** @@ -526,8 +516,8 @@ export class StackOneToolSet { } #endpoint(mode: ToolMode | undefined): string { - const endpoint = `${this.#baseUrl.replace(/\/+$/, '')}/mcp?param-style=${MCP_PARAM_STYLE}`; - return mode ? `${endpoint}&tool-mode=${mode}` : endpoint; + const endpoint = `${this.#baseUrl.replace(/\/+$/, '')}/mcp`; + return mode ? `${endpoint}?tool-mode=${mode}` : endpoint; } /** @@ -601,35 +591,21 @@ export class StackOneToolSet { } /** - * Build an executable tool from a served catalog entry, on a deep copy of its schema. - * - * In `search_execute` mode the served tools are MCP meta tools with no action behind them on - * `/actions/rpc`, so they are executed over `tools/call`. `stackone_submit_feedback` goes over - * `tools/call` in every mode too. The server would also accept it on `/actions/rpc`, but it is - * served over MCP and is not a connector action, so it is called where it was listed. + * Build an executable tool from a served catalog entry, on a deep copy of its schema. Every + * tool — per-action, meta or feedback — executes over `tools/call` on the endpoint and account + * that listed it. */ - #createTool(entry: CatalogEntry, mode: ToolMode | undefined): StackOneTool { + #createTool(entry: CatalogEntry): StackOneTool { const { definition, accountId, endpoint } = entry; - const parameters = toolParametersFromInputSchema(cloneJson(definition.inputSchema)); - const description = definition.description ?? ''; - if (mode === 'search_execute' || definition.name === SUBMIT_FEEDBACK_TOOL_NAME) { - return new StackOneMcpTool({ - name: definition.name, - description, - parameters, - endpoint, - apiKey: this.#apiKey, - accountId, - timeout: this.#timeout, - extraHeaders: this.#headers, - }); - } - return new StackOneRpcTool({ + return new StackOneMcpTool({ name: definition.name, - description, - parameters, - client: this.#rpcClient, + description: definition.description ?? '', + parameters: toolParametersFromInputSchema(cloneJson(definition.inputSchema)), + endpoint, + apiKey: this.#apiKey, accountId, + timeout: this.#timeout, + extraHeaders: this.#headers, }); } @@ -665,7 +641,7 @@ export class StackOneToolSet { seenFeedbackTool = true; return first; }) - .map((entry) => this.#createTool(entry, mode)); + .map((entry) => this.#createTool(entry)); if (options.providers?.length) { const providers = options.providers; @@ -848,16 +824,7 @@ export class StackOneToolSet { } callArguments.action_id = actionId; - const result = await tool.execute(callArguments); - // The meta tool wraps its payload as { isError, result }, but an isError response has - // already raised by this point — so the flag could only ever be false, and the wrapper would - // just make this return a different shape from tool.execute() for the same action. - const keys = Object.keys(result); - if (keys.length === 2 && keys.includes('isError') && keys.includes('result')) { - const inner = result.result; - return isPlainObject(inner) ? inner : { result: inner ?? null }; - } - return result; + return tool.execute(callArguments); } /** diff --git a/src/types.ts b/src/types.ts index f04ad30a..c4fbeed4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -76,26 +76,8 @@ export type JsonSchemaProperties = Record; export type ToolMode = 'individual' | 'search_execute'; /** - * Executes over the StackOne actions RPC endpoint (`POST /actions/rpc`). Every per-action tool - * listed in `individual` mode is one of these. - */ -export interface RpcExecuteConfig { - kind: 'rpc'; - method: 'POST'; - url: string; - payloadKeys: { - action: string; - body?: string; - headers?: string; - path?: string; - query?: string; - }; -} - -/** - * Executes over MCP `tools/call` on the endpoint that listed it. The search/execute meta tools - * have no action behind them on `/actions/rpc`; `stackone_submit_feedback` is not a connector - * action either, so the SDK calls it here even though the server also accepts it over RPC. + * Executes over MCP `tools/call`, on the endpoint that listed the tool. Every tool a toolset + * returns executes this way. */ export interface McpExecuteConfig { kind: 'mcp'; @@ -115,15 +97,14 @@ interface LocalExecuteConfig { /** * Discriminated union lets call sites branch on execution style without relying on nullable fields. */ -export type ExecuteConfig = RpcExecuteConfig | McpExecuteConfig | LocalExecuteConfig; +export type ExecuteConfig = McpExecuteConfig | LocalExecuteConfig; /** * Options for executing a tool */ export interface ExecuteOptions { /** - * If true, returns the request the tool would send instead of sending it. Useful for - * checking how arguments are routed into the RPC envelope. + * If true, returns the `tools/call` the tool would send instead of sending it. */ dryRun?: boolean; } diff --git a/src/utils/binary-response.test.ts b/src/utils/binary-response.test.ts deleted file mode 100644 index 7c3b29e8..00000000 --- a/src/utils/binary-response.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { filenameFromContentDisposition, isJsonContentType, safeBasename } from './binary-response'; - -/** - * Unit tests for the Content-Type and Content-Disposition parsing helpers that drive the - * JSON-vs-file decision and filename extraction shared by the HTTP and RPC tool paths. - */ -describe('isJsonContentType', () => { - it.each([ - ['application/json', true], - ['application/json; charset=utf-8', true], - ['APPLICATION/JSON', true], - ['application/problem+json', true], - ['application/vnd.api+json', true], - ['', false], - ['application/pdf', false], - ['application/octet-stream', false], - ['text/plain', false], - ['text/json-but-not-really', false], - ])('isJsonContentType(%j) === %s', (input, expected) => { - expect(isJsonContentType(input as string)).toBe(expected); - }); -}); - -describe('filenameFromContentDisposition', () => { - it.each([ - ['attachment; filename="download.pdf"', 'download.pdf'], - ['attachment; filename=download.pdf', 'download.pdf'], - ['inline; filename="my report.docx"', 'my report.docx'], - // RFC 5987 extended form is percent-decoded and takes precedence over the plain form. - ['attachment; filename="fallback.txt"; filename*=UTF-8\'\'na%C3%AFve.txt', 'naïve.txt'], - // Malformed percent-encoding must not throw - the malformed escape stays literal. - ["attachment; filename*=UTF-8''bad%ZZname", 'bad%ZZname'], - // Non-UTF-8 charset is honoured: 0xA3 is "£" in ISO-8859-1, not UTF-8. - ["attachment; filename*=ISO-8859-1'en'%A3%20rates.txt", '£ rates.txt'], - // Unknown charset label falls back to UTF-8 instead of throwing. - ["attachment; filename*=bogus-charset''%C2%A3.txt", '£.txt'], - // Non-conformant quoted extended value: surrounding quotes are stripped. - ['attachment; filename*="UTF-8\'\'na%C3%AFve.txt"', 'naïve.txt'], - ['attachment', null], - [null, null], - ['', null], - ])('filenameFromContentDisposition(%j) === %j', (input, expected) => { - expect(filenameFromContentDisposition(input as string | null)).toBe(expected); - }); -}); - -/** - * The filename comes from a Content-Disposition that whoever uploaded the file chose, so it is - * attacker-controlled. Ported from the Python SDK's `_safe_basename` cases. - */ -describe('download filenames are safe to write', () => { - it.each([ - ['attachment; filename="../../.ssh/authorized_keys"', 'authorized_keys'], - ["attachment; filename*=UTF-8''%2e%2e%2f%2e%2e%2fetc%2fcron.d%2fx", 'x'], - ['attachment; filename="/etc/passwd"', 'passwd'], - ['attachment; filename="C:evil.exe"', 'evil.exe'], - ['attachment; filename="..\\\\..\\\\windows\\\\x.dll"', 'x.dll'], - ["attachment; filename*=UTF-8''..%5C..%5Cwindows%5Cx.dll", 'x.dll'], - ['attachment; filename="report.pdf:hidden.exe"', 'hidden.exe'], - ['attachment; filename="\u202egnp.exe"', 'gnp.exe'], - ['attachment; filename="line\u0000break\u0007.txt"', 'linebreak.txt'], - ['attachment; filename=".."', null], - ["attachment; filename*=UTF-8''%2e%2e", null], - ['attachment; filename=" "', null], - ['attachment; notfilename="decoy.txt"', null], - ['attachment; filename="report.pdf"', 'report.pdf'], - ])('%j -> %j', (header, expected) => { - expect(filenameFromContentDisposition(header)).toBe(expected); - }); - - const byteLength = (value: string) => new TextEncoder().encode(value).length; - - it('caps an overlong name at 255 bytes, keeping the extension', () => { - const name = filenameFromContentDisposition(`attachment; filename="${'a'.repeat(400)}.pdf"`); - expect(name?.endsWith('.pdf')).toBe(true); - expect(byteLength(name ?? '')).toBeLessThanOrEqual(255); - }); - - it('caps multi-byte names on a character boundary', () => { - const name = safeBasename(`${'é'.repeat(300)}.txt`); - expect(name?.endsWith('.txt')).toBe(true); - expect(byteLength(name ?? '')).toBeLessThanOrEqual(255); - expect(name).not.toContain('\uFFFD'); - }); - - it('caps an overlong name with no extension', () => { - expect(byteLength(safeBasename('b'.repeat(400)) ?? '')).toBe(255); - }); - - it('caps a name whose extension alone is overlong', () => { - expect(byteLength(safeBasename(`a.${'c'.repeat(400)}`) ?? '')).toBe(255); - }); - - it('passes null through', () => { - expect(safeBasename(null)).toBeNull(); - expect(safeBasename(undefined)).toBeNull(); - }); -}); diff --git a/src/utils/binary-response.ts b/src/utils/binary-response.ts deleted file mode 100644 index 3edc17a2..00000000 --- a/src/utils/binary-response.ts +++ /dev/null @@ -1,178 +0,0 @@ -/** - * Shared handling for binary (file-download) HTTP responses. - * - * StackOne serves file downloads as raw binary with the file's own MIME type and a - * Content-Disposition header - never as the usual JSON envelope. The RPC client must therefore - * decide JSON-vs-file by Content-Type and return the bytes plus metadata instead of forcing a - * JSON parse. - */ - -/** - * Result of a non-JSON (file-download) response: the raw bytes plus metadata. - * - * Note: `content` is a raw `Buffer`, not a `JsonValue`. `JSON.stringify` turns a Buffer into a - * `{ type: 'Buffer', data: [...] }` byte array (not the file, and potentially huge), so callers - * that re-serialize tool results (e.g. for an LLM) should strip or transform this key. - */ -export interface BinaryDownloadResult { - content: Buffer; - contentType: string; - statusCode: number; - headers: Record; - fileName: string | null; -} - -/** - * Whether a response body should be parsed as JSON based on its Content-Type. - * - * Only genuine JSON media types are parsed (`application/json` and structured suffixes such - * as `application/problem+json`). Anything else - including a missing Content-Type - is treated - * as opaque content (a file download), so the raw bytes are returned instead of being - * force-decoded as UTF-8/JSON. This mirrors how the StackOne generated SDKs default unknown - * bodies to `application/octet-stream`. - */ -export function isJsonContentType(contentType: string): boolean { - const mediaType = contentType.split(';')[0]?.trim().toLowerCase() ?? ''; - return mediaType === 'application/json' || mediaType.endsWith('+json'); -} - -/** The longest filename, in UTF-8 bytes, that common filesystems (ext4, APFS, NTFS) accept. */ -const MAX_FILENAME_BYTES = 255; - -/** Control (Cc) and format (Cf) characters: log/header injection and bidi extension spoofing. */ -const CONTROL_OR_FORMAT_CHARS = /[\p{Cc}\p{Cf}]/gu; - -const utf8Encoder = new TextEncoder(); - -/** Truncate to at most `maxBytes` UTF-8 bytes without splitting a character. */ -function truncateUtf8(value: string, maxBytes: number): string { - let bytes = 0; - let end = 0; - for (const char of value) { - const size = utf8Encoder.encode(char).length; - if (bytes + size > maxBytes) { - break; - } - bytes += size; - end += char.length; - } - return value.slice(0, end); -} - -/** - * Reduce a server-supplied filename to a bare, writable basename, or `null` if nothing usable - * is left. - * - * The value comes from a remote `Content-Disposition`, which in practice is chosen by whoever - * uploaded the file to the connected provider — so it is attacker-controlled. Returned as-is it - * is an arbitrary-file-write primitive for any caller that does the obvious thing and passes it - * to `writeFile()`: `../../.ssh/authorized_keys` and `/etc/cron.d/x` both round-trip. The RFC - * 5987 branch percent-decodes, so a filter applied before this point would be bypassed anyway; - * sanitise last, here, once. - * - * - `/` and `\` are both path separators, whatever the host OS. - * - `:` is too: `C:evil.exe` writes to drive C:'s current directory on Windows, and - * `report.pdf:payload` writes an NTFS alternate data stream. - * - Control and Unicode format characters are removed — U+202E renders `\u202egnp.exe` as - * `…exe.png`, the classic extension spoof. - * - The result is capped at 255 UTF-8 bytes, keeping the extension when there is one. - */ -export function safeBasename(name: string | null | undefined): string | null { - if (name == null) { - return null; - } - const lastSegment = name.split(/[/\\:]/).at(-1) ?? ''; - const base = lastSegment.replace(CONTROL_OR_FORMAT_CHARS, '').trim(); - if (base === '' || base === '.' || base === '..') { - return null; - } - if (utf8Encoder.encode(base).length <= MAX_FILENAME_BYTES) { - return base; - } - const dot = base.lastIndexOf('.'); - const suffix = dot > 0 ? base.slice(dot) : ''; - const suffixBytes = utf8Encoder.encode(suffix).length; - // An extension that cannot fit alongside at least one character of stem is not worth - // keeping: truncate the whole name instead of emitting something still over the limit. - if (suffix === '' || suffixBytes >= MAX_FILENAME_BYTES) { - return truncateUtf8(base, MAX_FILENAME_BYTES); - } - return truncateUtf8(base.slice(0, dot), MAX_FILENAME_BYTES - suffixBytes) + suffix; -} - -/** - * Decode `%XX` escapes as bytes in `charset`, the way Python's `urllib.parse.unquote` does: - * malformed escapes stay literal, and bytes that do not decode become U+FFFD rather than - * throwing. An unknown charset label falls back to UTF-8. - */ -function percentDecode(encoded: string, charset: string): string { - let decoder: InstanceType; - try { - decoder = new TextDecoder(charset); - } catch { - decoder = new TextDecoder('utf-8'); - } - return encoded.replace(/(?:%[0-9A-Fa-f]{2})+/g, (run) => - decoder.decode(Uint8Array.from(run.slice(1).split('%'), (hex) => Number.parseInt(hex, 16))), - ); -} - -/** - * Extract the filename from a Content-Disposition header value, reduced to a safe basename. - * - * Handles both the plain `filename="example.pdf"` form and the RFC 5987 extended - * `filename*=UTF-8''example%20file.pdf` form, which takes precedence when present. The extended - * form is percent-decoded using its declared charset (RFC 5987 permits both `UTF-8` and - * `ISO-8859-1`). Parameters are matched at a parameter boundary, so `notfilename=` is ignored. - * Returns null when no usable filename is present — see {@link safeBasename}. - */ -export function filenameFromContentDisposition(value: string | null | undefined): string | null { - if (!value) { - return null; - } - const extended = value.match(/(?:^|;)\s*filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i); - if (extended) { - const charset = extended[1]?.trim() || 'utf-8'; - const encoded = (extended[2] ?? '').trim().replace(/^"+|"+$/g, ''); - return safeBasename(percentDecode(encoded, charset)); - } - const quoted = value.match(/(?:^|;)\s*filename\s*=\s*"([^"]*)"/i); - if (quoted) { - return safeBasename(quoted[1]); - } - const bare = value.match(/(?:^|;)\s*filename\s*=\s*([^;]+)/i); - if (bare) { - return safeBasename((bare[1] ?? '').replace(/^"+|"+$/g, '')); - } - return null; -} - -/** - * Read a non-JSON `Response` into a {@link BinaryDownloadResult} (bytes + metadata). - * - * Assumes the caller has already decided the body is non-JSON (see {@link isJsonContentType}); - * consumes the response body via `arrayBuffer()`. - */ -export async function binaryDownloadFromResponse( - response: Response, -): Promise { - const contentType = response.headers.get('content-type') ?? ''; - return { - content: Buffer.from(await response.arrayBuffer()), - contentType: contentType || 'application/octet-stream', - statusCode: response.status, - headers: Object.fromEntries(response.headers.entries()), - fileName: filenameFromContentDisposition(response.headers.get('content-disposition')), - }; -} - -/** - * Type guard for a {@link BinaryDownloadResult} - true when `content` carries raw bytes. - */ -export function isBinaryDownloadResult(value: unknown): value is BinaryDownloadResult { - return ( - typeof value === 'object' && - value !== null && - Buffer.isBuffer((value as { content?: unknown }).content) - ); -} diff --git a/src/utils/serialize.ts b/src/utils/serialize.ts index 6554eac1..0a856da8 100644 --- a/src/utils/serialize.ts +++ b/src/utils/serialize.ts @@ -1,7 +1,7 @@ /** * Serialise a tool result for a model. * - * A file download carries its bytes as a `Buffer`, which `JSON.stringify` turns into a + * A hand-built tool may return bytes as a `Buffer`, which `JSON.stringify` turns into a * `{ type: 'Buffer', data: [...] }` byte array — not the file, and potentially enormous. Bytes are * base64-encoded instead, and a `bigint` is written as its decimal string rather than throwing. * The replacer reads the ORIGINAL value from its holder, because `JSON.stringify` has already diff --git a/tests/examples/claude-agent-sdk-integration.test.ts b/tests/examples/claude-agent-sdk-integration.test.ts index 4bd5a38f..77c2ba3f 100644 --- a/tests/examples/claude-agent-sdk-integration.test.ts +++ b/tests/examples/claude-agent-sdk-integration.test.ts @@ -136,6 +136,6 @@ describe('claude-agent-sdk-integration example e2e', () => { const textContent = result.content[0]; assert(textContent?.type === 'text'); const data = JSON.parse(textContent.text) as unknown; - expect(data).toHaveProperty('data'); + expect(data).toMatchObject({ isError: false, result: { data: {} } }); }); }); diff --git a/tests/examples/fetch-tools.test.ts b/tests/examples/fetch-tools.test.ts index 4f2fad5b..ce0de301 100644 --- a/tests/examples/fetch-tools.test.ts +++ b/tests/examples/fetch-tools.test.ts @@ -92,7 +92,11 @@ describe('fetch-tools example e2e', () => { const result = await tool!.execute({ query: { limit: 5 }, }); - expect(result.data).toBeDefined(); - expect(Array.isArray(result.data)).toBe(true); + // 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 } }, + }); }); }); diff --git a/tests/examples/openai-integration.test.ts b/tests/examples/openai-integration.test.ts index 5bf1bfde..e8dd5d12 100644 --- a/tests/examples/openai-integration.test.ts +++ b/tests/examples/openai-integration.test.ts @@ -75,7 +75,13 @@ describe('openai-integration example e2e', () => { expect(toolMessages).toHaveLength(1); expect(toolMessages[0]).toMatchObject({ role: 'tool', tool_call_id: 'call_mock' }); expect(JSON.parse(toolMessages[0]?.content as string)).toMatchObject({ - data: { id: 'c28xIQaWQ6MzM5MzczMDA2NzMzMzkwNzIwNA', name: 'Test Employee' }, + isError: false, + result: { + data: { + action: 'bamboohr_get_employee', + arguments: { id: 'c28xIQaWQ6MzM5MzczMDA2NzMzMzkwNzIwNA' }, + }, + }, }); }); }); diff --git a/tests/examples/search-and-execute.test.ts b/tests/examples/search-and-execute.test.ts index 179373f0..612d14ce 100644 --- a/tests/examples/search-and-execute.test.ts +++ b/tests/examples/search-and-execute.test.ts @@ -57,9 +57,7 @@ describe('search-and-execute example e2e', () => { const [best] = await toolset.search('list recent comments', { topK: 3 }); assert(best); expect(await toolset.execute(best.action_id, {}, { sessionId: best.session_id })).toMatchObject( - { - data: { nodes: [] }, - }, + { isError: false, result: { data: { nodes: [] } } }, ); await expect( toolset.submitFeedback({ rating: 'positive', toolNames: [best.action_id] }), diff --git a/tests/examples/tanstack-ai-integration.test.ts b/tests/examples/tanstack-ai-integration.test.ts index 7c13e59d..4b82b77a 100644 --- a/tests/examples/tanstack-ai-integration.test.ts +++ b/tests/examples/tanstack-ai-integration.test.ts @@ -73,6 +73,6 @@ describe('tanstack-ai-integration example e2e', () => { }); expect(result).toBeDefined(); - expect(result).toHaveProperty('data'); + expect(result).toMatchObject({ isError: false, result: { data: {} } }); }); }); From 6d0f3b5ac7f37b0145bce0db26d9f6f5c5db5c4b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 16:31:55 +0100 Subject: [PATCH 017/151] docs: describe MCP-only execution, dryRun and download links The README described RPC execution, an RPC dryRun and byte downloads. It now shows the tools/call dryRun and the download link a file action returns, and says to reduce the provider-chosen filename before writing it. --- README.md | 65 +++++++++++++++++-------------------------------------- 1 file changed, 20 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 76d9a3f8..173758a9 100644 --- a/README.md +++ b/README.md @@ -406,7 +406,7 @@ Everything the SDK throws is a `StackOneError`: - `ToolSetConfigError` — the toolset was configured, or called, with something it cannot use. - `ToolSetLoadError` — the catalog, or the accounts behind it, could not be loaded. -`timeout` (milliseconds, default 60000) bounds every MCP listing and `tools/call`, every RPC call and account discovery. +`timeout` (milliseconds, default 60000) bounds every MCP listing and `tools/call`, and account discovery. ### Custom Base URL @@ -418,71 +418,46 @@ const toolset = new StackOneToolSet({ baseUrl: 'https://api.example-dev.com' }); ### Testing with dryRun -You can use the `dryRun` option to return the api arguments from a tool call without making the actual api call: +You can use the `dryRun` option to see the `tools/call` a tool would send, without sending it: ```typescript import { StackOneToolSet } from '@stackone/ai'; -// Initialize the toolset const toolset = new StackOneToolSet(); const tools = await toolset.fetchTools(); const employeeTool = tools.getTool('workday_list_workers'); -// Use dryRun to see the request details -const dryRunResult = await employeeTool.execute({ query_limit: 5 }, { dryRun: true }); +const dryRunResult = await employeeTool.execute({ query: { limit: 5 } }, { dryRun: true }); console.log(dryRunResult); // { -// url: "https://api.stackone.com/actions/rpc", -// method: "POST", -// headers: { ... }, -// body: '{"action":"workday_list_workers","body":{},"headers":{...},"query":{"limit":5}}', -// mappedParams: { query_limit: 5 } +// url: "https://api.stackone.com/mcp", +// method: "tools/call", +// name: "workday_list_workers", +// arguments: { query: { limit: 5 } } // } ``` -The `dryRun` option returns an object containing: - -- `url`: The RPC endpoint -- `method`: The HTTP method -- `headers`: The HTTP request headers, without `Authorization` -- `body`: The JSON request body: the arguments split into the RPC envelope -- `mappedParams`: The arguments as the tool received them - ### File Downloads -Actions that download a file (for example `googledrive_unified_download_file`, `documents_download_file`, or any `*_unified_download_file`) return raw bytes plus metadata instead of parsed JSON. The SDK decides from the response `Content-Type`: JSON media types (`application/json` and `+json` suffixes) are parsed as usual, and anything else is treated as a file download. - -Use the exported `isBinaryDownloadResult` type guard to narrow the result — no casts needed: +Every tool executes over MCP `tools/call`, and a tool returns the server's result exactly as the server wrote it: `{ isError: false, result, defenderMetadata?, policyMetadata? }`. A tool result cannot carry a file, so a file action (for example `googledrive_unified_download_file` or any `*_download_file`) returns a single-use link as its `result`: ```typescript -import { writeFileSync } from 'node:fs'; -import { isBinaryDownloadResult, StackOneToolSet } from '@stackone/ai'; - -const toolset = new StackOneToolSet(); -const tools = await toolset.fetchTools({ actions: ['googledrive_*'] }); -const download = tools.getTool('googledrive_unified_download_file'); - -const result = await download.execute({ id: 'file-id' }); - -if (isBinaryDownloadResult(result)) { - // result.content is a Buffer; result.fileName is string | null - writeFileSync(result.fileName ?? 'download.bin', result.content); -} +const response = await tools + .getTool('googledrive_unified_download_file') + ?.execute({ path: { id: 'file-id' } }); +// { +// isError: false, +// result: { +// download_url: "https://api.stackone.com/actions/download/v1.…", +// expires_at: "2026-09-29T12:05:00.000Z", +// file: { name: "report.pdf", content_type: "application/pdf", content_length: 48213 } +// } +// } ``` -The download result (typed `BinaryDownloadResult`) contains: - -- `content`: `Buffer` — the raw file bytes (not a `JsonValue`; see note) -- `contentType`: `string` — the file's MIME type (e.g. `application/pdf`), or `application/octet-stream` -- `statusCode`: `number` — HTTP status of the download response -- `headers`: `Record` — the response headers -- `fileName`: `string | null` — filename from `Content-Disposition` (RFC 5987 `filename*` aware), reduced to a safe basename, or `null` - -The filename comes from whoever uploaded the file to the connected provider, so it is reduced to a bare basename before you see it: path components (`../`, `/`, `\`), drive letters and NTFS stream separators (`:`), control and Unicode format characters are removed, and it is capped at 255 bytes. It is `null` when nothing usable is left. - -> **Note:** `content` is a raw `Buffer`, not a `JsonValue`. `JSON.stringify` turns it into a `{ type: 'Buffer', data: [...] }` byte array (not the file, and potentially huge), so if you forward tool results to an LLM — or anything that re-serializes to JSON — strip or transform the `content` key first. `executeOpenAIToolCalls()` and the Claude Agent SDK adapter base64-encode it for you. +`GET` the `download_url` for the bytes: it needs no credentials, works once, and expires after five minutes. The filename in `file.name` and in the download's `Content-Disposition` is chosen by whoever uploaded the file, so reduce it to a safe basename before writing it to disk. Where no link can be issued, the call raises a `StackOneAPIError` with status `501`. ## Examples From 7b14868fa1e97434d880c892fe850cd1c72ad655 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 16:56:16 +0100 Subject: [PATCH 018/151] ci: pin sdk-conformance to the MCP-only suite StackOneHQ/sdk-conformance#5 grades execution over tools/call, forbids /actions/rpc (invariant 13) and grades results as the server wrote them. The previous pin still graded /actions/rpc envelopes, which this SDK no longer sends. --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index d750f201..f65cd5f4 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: cedc5658e9249d06bacc08a3fec2fe79db0dfe38 + ref: 13a93bad6ac94b5627f44e8d0cdda23814cd0605 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From fd862c14ef6617e6b7b672557cfeaf4bba39611a Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 29 Sep 2026 17:01:33 +0100 Subject: [PATCH 019/151] test: keep the search-and-execute example out of the root typecheck The root project type-checks tests/, and the example's e2e test imported it by a literal path, so tsc followed it into examples/search-and-execute.ts. Its '@stackone/ai' import resolves only when the examples workspace is installed, which the ai-peer-range jobs skip, so they failed. The test now imports the example by a computed URL. Also formats src/toolsets.search-execute.test.ts the way CI's oxfmt 0.23.0 does. --- src/toolsets.search-execute.test.ts | 13 ++++++------- tests/examples/search-and-execute.test.ts | 6 +++++- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 51e285dd..7f100202 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -62,13 +62,12 @@ 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) { + calls.push({ tool: this.name, args: args as JsonObject }); + return respond(this, args as JsonObject); + }, + ); return calls; }; diff --git a/tests/examples/search-and-execute.test.ts b/tests/examples/search-and-execute.test.ts index 612d14ce..26f07a11 100644 --- a/tests/examples/search-and-execute.test.ts +++ b/tests/examples/search-and-execute.test.ts @@ -38,7 +38,11 @@ describe('search-and-execute example e2e', () => { server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); const log = vi.spyOn(console, 'log').mockImplementation(() => {}); - await import('../../examples/search-and-execute'); + // A computed specifier, so tsc does not follow it: the root project type-checks tests/, + // and the example imports '@stackone/ai', which resolves only when the examples + // workspace is installed — the ai-peer-range jobs install the root package alone. + const example = new URL('../../examples/search-and-execute.ts', import.meta.url).href; + await import(/* @vite-ignore */ example); const printed = log.mock.calls.map((args) => String(args[0])).join('\n'); expect(printed).toContain('default testprovider active'); From c4b9ba7bb0c6d1518f442906ebef82de09968b5f Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 20:59:34 +0100 Subject: [PATCH 020/151] test: type-check the search-and-execute example against source fd862c1 hid the example from the root typecheck by importing it through a computed URL, so tsc stopped checking it at all. Import it by its literal path again and map '@stackone/ai' to ./src/index.ts in the root tsconfig instead: the example now resolves the package to source whether or not the examples workspace is installed, which the ai-peer-range jobs skip. The three "'error' is of type 'unknown'" errors were fallout of the unresolved import, not defects in the example. The mapping only affects type resolution for files that import the package by name, which src never does, so the built dist and its published types are unchanged. --- tests/examples/search-and-execute.test.ts | 6 +----- tsconfig.json | 2 ++ 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/tests/examples/search-and-execute.test.ts b/tests/examples/search-and-execute.test.ts index 26f07a11..612d14ce 100644 --- a/tests/examples/search-and-execute.test.ts +++ b/tests/examples/search-and-execute.test.ts @@ -38,11 +38,7 @@ describe('search-and-execute example e2e', () => { server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); const log = vi.spyOn(console, 'log').mockImplementation(() => {}); - // A computed specifier, so tsc does not follow it: the root project type-checks tests/, - // and the example imports '@stackone/ai', which resolves only when the examples - // workspace is installed — the ai-peer-range jobs install the root package alone. - const example = new URL('../../examples/search-and-execute.ts', import.meta.url).href; - await import(/* @vite-ignore */ example); + await import('../../examples/search-and-execute'); const printed = log.mock.calls.map((args) => String(args[0])).join('\n'); expect(printed).toContain('default testprovider active'); diff --git a/tsconfig.json b/tsconfig.json index 27e16215..20f7d388 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,6 +22,8 @@ /* Other */ "forceConsistentCasingInFileNames": true, "lib": ["es2022"], + /* Examples imported by tests/examples resolve the package to source, installed or not */ + "paths": { "@stackone/ai": ["./src/index.ts"] }, "types": ["node", "vitest/globals", "vitest/importMeta"] }, "include": [ From 92aa49d4cb01dc154e624bdb07d1f5d673a495ca Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:03:02 +0100 Subject: [PATCH 021/151] fix(tools)!: forward only the header arguments a served schema declares A header argument is an entry of a top-level `headers` object, or a top-level `headers_` argument. Each is now forwarded only when the served schema declares it: `` under `properties.headers.properties`, or the `headers_` property itself. A `headers` property served as an object with no `properties` (as on every `*_execute_action`) declares any name, so `toolset.execute()` can now pass host-set headers such as `x-custom` through to the action. `Authorization`, `x-account-id` and `User-Agent` are never forwarded as header arguments, even when declared. Previously a `headers_` argument went to tools/call unfiltered, and a flat `headers_` declaration also let the nested `headers.` through. Every other argument goes to tools/call unchanged. Each dropped header argument now warns with the real reason, "not declared by the schema" or "set by the SDK", instead of claiming every drop was undeclared. The tenant-switch regression test now asserts the arguments tools/call received, not only the transport's x-account-id. BREAKING CHANGE: a `headers_` tool argument is dropped with a warning unless the served schema declares `headers_`, and is never forwarded for `authorization`, `x-account-id` or `user-agent`. A nested `headers.` is forwarded only when `properties.headers` declares it (or is an open object); a flat `headers_` declaration no longer admits it. --- README.md | 4 +- src/headers.test.ts | 129 +++++++++++++++++++---- src/headers.ts | 155 +++++++++++++++++++--------- src/tool.test.ts | 6 +- src/tool.ts | 23 +++-- src/toolsets.search-execute.test.ts | 12 +++ src/toolsets.test.ts | 65 +++++++++++- src/toolsets.ts | 4 + 8 files changed, 315 insertions(+), 83 deletions(-) diff --git a/README.md b/README.md index 173758a9..ad619954 100644 --- a/README.md +++ b/README.md @@ -391,7 +391,9 @@ The catalog is cached per account scope and mode, so changing a filter never ref ### Headers -A tool call can only send the headers its served schema declares, as `headers_` properties; anything else a model supplies is dropped with a warning. `Authorization`, `x-account-id` and `User-Agent` are always the SDK's own, so no tool call — and no `headers` constructor option — can replace the credential or run a call against another account. +A tool call's header arguments — the entries of a `headers` object argument, and `headers_` arguments — are forwarded only if the tool's served schema declares them: `` under `properties.headers.properties`, or a `headers_` property. A `headers` property served as an object with no `properties`, as on every `*_execute_action`, declares any name, so `toolset.execute(id, { headers: { 'x-custom': '…' } })` forwards it. Anything undeclared is dropped with a warning; every other argument is sent unchanged. + +`Authorization`, `x-account-id` and `User-Agent` are always the SDK's own: they are dropped from header arguments even when declared, and ignored with a warning in the `headers` constructor option, so nothing can replace the credential or run a call against another account. ```typescript // Extra headers for every request (for example, tracing) diff --git a/src/headers.test.ts b/src/headers.test.ts index ca1684f0..1e1b8ce4 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -1,4 +1,9 @@ -import { declaredHeaderNames, normalizeHeaders, sanitiseHeaders } from './headers'; +import { + declaredHeaders, + normalizeHeaders, + sanitiseHeaderArguments, + sanitiseHeaders, +} from './headers'; describe('normalizeHeaders', () => { it('returns empty object for undefined input', () => { @@ -68,31 +73,45 @@ describe('normalizeHeaders', () => { }); }); -describe('sanitiseHeaders', () => { - const flat = (...names: string[]) => - Object.fromEntries(names.map((name) => [name, { type: 'string' }])); - const allowed = declaredHeaderNames(flat('headers_x-trace', 'query_limit', 'body_headers_x')); +describe('declaredHeaders', () => { + it('reads flat headers_* properties exactly as served, and nothing else', () => { + expect( + declaredHeaders({ + 'headers_X-Trace': { type: 'string' }, + query_limit: { type: 'number' }, + body_headers_x: { type: 'string' }, + }), + ).toEqual({ nested: new Set(), flat: new Set(['headers_X-Trace']) }); + }); - beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); + it('reads the nested headers object, lower-cased', () => { + expect( + declaredHeaders({ + headers: { type: 'object', properties: { 'X-Trace': { type: 'string' } } }, + body: { type: 'object', properties: { 'x-other': { type: 'string' } } }, + }).nested, + ).toEqual(new Set(['x-trace'])); }); - afterEach(() => { - vi.restoreAllMocks(); + + it('treats a headers object schema with no properties as declaring every name', () => { + expect(declaredHeaders({ headers: { type: 'object' } }).nested).toBe('any'); }); - it('builds the allowlist from flat headers_* properties only, lower-cased', () => { - expect(declaredHeaderNames(flat('headers_X-Trace', 'query_limit', 'body_headers_x'))).toEqual( - new Set(['x-trace']), + it('treats empty properties as declaring nothing', () => { + expect(declaredHeaders({ headers: { type: 'object', properties: {} } }).nested).toEqual( + new Set(), ); }); +}); - it('builds the allowlist from a nested headers object, lower-cased', () => { - expect( - declaredHeaderNames({ - headers: { type: 'object', properties: { 'X-Trace': { type: 'string' } } }, - body: { type: 'object', properties: { 'x-other': { type: 'string' } } }, - }), - ).toEqual(new Set(['x-trace'])); +describe('sanitiseHeaders', () => { + const allowed = new Set(['x-trace']); + + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => { + vi.restoreAllMocks(); }); it('drops every header the served schema does not declare', () => { @@ -130,8 +149,74 @@ describe('sanitiseHeaders', () => { expect(sanitiseHeaders({ 'x-trace': null }, allowed)).toEqual({}); }); - it('warns once per dropped header', () => { - sanitiseHeaders({ Authorization: 'x', 'X-Trace': 'bad\n' }, allowed); - expect(console.warn).toHaveBeenCalledTimes(2); + it('forwards any name under an open schema, except the ones the SDK owns', () => { + expect( + sanitiseHeaders( + { 'x-custom': 'a', Authorization: 'x', 'X-Account-Id': 'b', 'user-agent': 'c' }, + 'any', + ), + ).toEqual({ 'x-custom': 'a' }); + }); + + it('says why each header was dropped', () => { + sanitiseHeaders({ Authorization: 'x', 'x-other': 'y', 'X-Trace': 'bad\n' }, allowed); + expect(vi.mocked(console.warn).mock.calls.map(([message]) => message)).toEqual([ + '[@stackone/ai] Dropping header "Authorization" from a tool call: set by the SDK', + '[@stackone/ai] Dropping header "x-other" from a tool call: not declared by the schema', + '[@stackone/ai] Dropping header "X-Trace" from a tool call: malformed', + ]); + }); +}); + +describe('sanitiseHeaderArguments', () => { + const declared = declaredHeaders({ + 'headers_x-trace': { type: 'string' }, + 'headers_x-account-id': { type: 'string' }, + headers: { type: 'object', properties: { 'x-nested': { type: 'string' } } }, + }); + + beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('forwards a declared headers_* argument with its value as given', () => { + expect(sanitiseHeaderArguments({ 'headers_x-trace': 7 }, declared)).toEqual({ + 'headers_x-trace': 7, + }); + }); + + it('drops an undeclared headers_* argument', () => { + expect(sanitiseHeaderArguments({ headers_foo: 'bar' }, declared)).toEqual({}); + expect(console.warn).toHaveBeenCalledWith( + '[@stackone/ai] Dropping header argument "headers_foo" from a tool call: not declared by the schema', + ); + }); + + it('drops an SDK-owned headers_* argument even when declared', () => { + expect(sanitiseHeaderArguments({ 'headers_x-account-id': 'victim' }, declared)).toEqual({}); + expect(console.warn).toHaveBeenCalledWith( + '[@stackone/ai] Dropping header argument "headers_x-account-id" from a tool call: set by the SDK', + ); + }); + + it('filters the nested headers object against its own declared names', () => { + expect( + sanitiseHeaderArguments({ headers: { 'x-nested': 'a', 'x-trace': 'b' } }, declared), + ).toEqual({ headers: { 'x-nested': 'a' } }); + }); + + it('passes every other argument through unchanged', () => { + const args = { + query_limit: 1, + body: { headers: { Authorization: 'kept' }, headers_x: 'kept' }, + path_id: 'x', + headers: 'not an object', + session_id: 's', + }; + expect(sanitiseHeaderArguments(args, declared)).toEqual(args); + expect(console.warn).not.toHaveBeenCalled(); }); }); diff --git a/src/headers.ts b/src/headers.ts index 01ad1c3d..8468e935 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -1,5 +1,5 @@ import { USER_AGENT } from './consts'; -import type { JsonObject } from './types'; +import type { JsonObject, JsonValue } from './types'; import { warn } from './utils/logger'; /** @@ -9,6 +9,9 @@ import { warn } from './utils/logger'; */ const SDK_OWNED_HEADERS = ['authorization', 'x-account-id', 'user-agent'] as const; +const isPlainObject = (value: unknown): value is JsonObject => + typeof value === 'object' && value !== null && !Array.isArray(value); + /** Whether a caller-supplied header name is one the SDK owns and will override. */ export function isSdkOwnedHeader(name: string): boolean { return (SDK_OWNED_HEADERS as readonly string[]).includes(name.trim().toLowerCase()); @@ -48,6 +51,20 @@ export function buildRequestHeaders(options: { return headers; } +/** A header value as a string: scalars stringified, objects serialised, null as absent. */ +function headerText(value: JsonValue | undefined): string | undefined { + switch (true) { + case value == null: + return undefined; + case typeof value === 'string': + return value; + case typeof value === 'number' || typeof value === 'boolean': + return String(value); + default: + return JSON.stringify(value); + } +} + /** * Normalizes header values from JsonObject to strings. * Converts numbers and booleans to strings, serializes objects to JSON and skips nulls. @@ -56,23 +73,11 @@ export function buildRequestHeaders(options: { * @returns Normalized headers with string values only */ export function normalizeHeaders(headers: JsonObject | undefined): Record { - if (!headers) { - return {}; - } const result: Record = {}; - for (const [key, value] of Object.entries(headers)) { - switch (true) { - case value == null: - continue; - case typeof value === 'string': - result[key] = value; - break; - case typeof value === 'number' || typeof value === 'boolean': - result[key] = String(value); - break; - default: - result[key] = JSON.stringify(value); - break; + for (const [key, value] of Object.entries(headers ?? {})) { + const text = headerText(value); + if (text !== undefined) { + result[key] = text; } } return result; @@ -88,36 +93,63 @@ const HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/; */ const HEADER_VALUE_PATTERN = /^[\x20-\x7e\t\x80-\xff]*$/; -const DECLARED_HEADER_PREFIX = 'headers_'; +const FLAT_HEADER_PREFIX = 'headers_'; /** - * The header names a served tool schema declares, lower-cased. + * The header arguments a served tool schema declares. * - * The schema itself is the allowlist, in whichever param-style the server served it: a flat - * `headers_` property, or a `` under a nested `headers` object. Nothing needs - * maintaining in the SDK: an action that starts declaring a header works without a release. + * The schema itself is the allowlist, in whichever param-style the server served it. Nothing + * needs maintaining in the SDK: an action that starts declaring a header works without a release. */ -export function declaredHeaderNames(properties: Record): Set { - const allowed = new Set(); - for (const name of Object.keys(properties)) { - if (name.startsWith(DECLARED_HEADER_PREFIX)) { - allowed.add(name.slice(DECLARED_HEADER_PREFIX.length).toLowerCase()); - } +export interface DeclaredHeaders { + /** + * Names declared under the nested `headers` object, lower-cased, or `'any'` when `headers` is + * an object schema with no `properties` — an open map, as on `*_execute_action`. + */ + nested: ReadonlySet | 'any'; + /** The top-level `headers_` properties, exactly as served. */ + flat: ReadonlySet; +} + +/** The header arguments a served tool schema's `properties` declare. */ +export function declaredHeaders(properties: Record): DeclaredHeaders { + const flat = new Set( + Object.keys(properties).filter((name) => name.startsWith(FLAT_HEADER_PREFIX)), + ); + const schema = properties.headers; + if (!isPlainObject(schema)) { + return { nested: new Set(), flat }; } - const nested = properties.headers; - if (typeof nested === 'object' && nested !== null && !Array.isArray(nested)) { - const nestedProperties = (nested as { properties?: unknown }).properties; - if (typeof nestedProperties === 'object' && nestedProperties !== null) { - for (const name of Object.keys(nestedProperties)) { - allowed.add(name.toLowerCase()); - } - } + if (!('properties' in schema)) { + return { nested: schema.type === 'object' ? 'any' : new Set(), flat }; + } + const nestedProperties = isPlainObject(schema.properties) ? schema.properties : {}; + return { nested: new Set(Object.keys(nestedProperties).map((name) => name.toLowerCase())), flat }; +} + +/** + * Why a header argument must not be forwarded, or `undefined` if it may be. + * + * `Authorization`, `x-account-id` and `User-Agent` are refused even when declared, because the + * SDK sets them itself. The value check runs only for a declared header, which is exactly where + * a model-supplied value needs it. + */ +function refuseHeader(name: string, value: string, declared: boolean): string | undefined { + if (isSdkOwnedHeader(name)) { + return 'set by the SDK'; + } + if (!declared) { + return 'not declared by the schema'; } - return allowed; + if (!HEADER_NAME_PATTERN.test(name) || !HEADER_VALUE_PATTERN.test(value)) { + return 'malformed'; + } + return undefined; } /** - * Keep only the headers the served schema declared, and only with well-formed values. + * Keep only the entries of a nested `headers` argument the served schema declared, and only with + * well-formed values. * * An allowlist, not a denylist. Tool arguments are model-controlled, so a prompt-injected call * reaches this object directly — and a denylist has to enumerate every synonym of "credential" @@ -125,27 +157,54 @@ export function declaredHeaderNames(properties: Record): Set, + allowed: ReadonlySet | 'any', ): Record { const clean: Record = {}; for (const [key, value] of Object.entries(normalizeHeaders(supplied))) { const name = key.trim(); - // Owned names are refused even when declared: the SDK sets them itself, afterwards. - if (!allowed.has(name.toLowerCase()) || isSdkOwnedHeader(name)) { - warn(`Dropping header "${name}" from a tool call: no served schema declares it`); + const declared = allowed === 'any' || allowed.has(name.toLowerCase()); + const reason = refuseHeader(name, value, declared); + if (reason) { + warn(`Dropping header "${name}" from a tool call: ${reason}`); + continue; + } + clean[name] = value; + } + return clean; +} + +/** + * Filter a tool call's header arguments to the ones its served schema declares. + * + * A header argument is an entry of a top-level `headers` object, or a top-level + * `headers_` argument. Every other argument is returned unchanged. A declared + * `headers_` keeps its value as given; nested entries are stringified. + */ +export function sanitiseHeaderArguments(args: JsonObject, declared: DeclaredHeaders): JsonObject { + const clean: JsonObject = {}; + for (const [key, value] of Object.entries(args)) { + if (key === 'headers' && isPlainObject(value)) { + clean.headers = sanitiseHeaders(value, declared.nested); continue; } - if (!HEADER_NAME_PATTERN.test(name) || !HEADER_VALUE_PATTERN.test(value)) { - warn(`Dropping malformed header "${name}" from a tool call`); + if (!key.startsWith(FLAT_HEADER_PREFIX)) { + clean[key] = value; continue; } - clean[name] = value; + 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 "${key}" from a tool call: ${reason}`); + continue; + } + clean[key] = value; } return clean; } diff --git a/src/tool.test.ts b/src/tool.test.ts index 5e8d6dab..9ebfa3ce 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -481,7 +481,7 @@ describe('StackOneMcpTool', () => { }); // The meta tools take a `headers` object the server unpacks, and these arguments are - // model-controlled. The meta tool's own schema declares no headers_*, so nothing survives. + // model-controlled. This schema declares no headers at all, so nothing survives. it('drops every model-supplied header', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}); @@ -503,7 +503,9 @@ describe('StackOneMcpTool', () => { it('keeps a header its own schema declares', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}); - await mcpTool({ 'headers_x-trace': { type: 'string' } }).execute({ + await mcpTool({ + headers: { type: 'object', properties: { 'x-trace': { type: 'string' } } }, + }).execute({ action_id: 'mock_list_items', headers: { 'X-Trace': 'abc', 'X-Other': 'no' }, }); diff --git a/src/tool.ts b/src/tool.ts index 51192d81..ab954bb0 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -9,7 +9,12 @@ import type { import type { FunctionTool as OpenAIResponsesFunctionTool } from 'openai/resources/responses/responses'; import type { OverrideProperties } from 'type-fest'; import { peerDependencies } from '../package.json'; -import { buildRequestHeaders, declaredHeaderNames, sanitiseHeaders } from './headers'; +import { + type DeclaredHeaders, + buildRequestHeaders, + declaredHeaders, + sanitiseHeaderArguments, +} from './headers'; import { callMcpTool } from './mcp-client'; import { cloneJson, foldRootComposition } from './schema'; import type { @@ -351,7 +356,7 @@ export class StackOneMcpTool extends StackOneTool { readonly #apiKey: string; readonly #extraHeaders: Record; readonly #timeout: number; - readonly #allowedHeaders: ReadonlySet; + readonly #declaredHeaders: DeclaredHeaders; constructor(options: { name: string; @@ -374,15 +379,17 @@ export class StackOneMcpTool extends StackOneTool { this.#apiKey = options.apiKey; this.#extraHeaders = { ...options.extraHeaders }; this.#timeout = options.timeout; - this.#allowedHeaders = declaredHeaderNames(options.parameters.properties); + this.#declaredHeaders = declaredHeaders(options.parameters.properties); } /** * Call the tool. * - * Arguments are sent as given; the server maps them onto the action. A `headers` object in - * them is filtered to the headers this tool's own schema declares — for the meta tools that is - * nothing, so every model-supplied header is dropped: these arguments are model-controlled. + * Arguments are sent as given; the server maps them onto the action. Header arguments — the + * entries of a `headers` object, and `headers_` arguments — are the exception: these + * arguments are model-controlled, so each is forwarded only if this tool's own schema declares + * it, and `Authorization`, `x-account-id` and `User-Agent` never are. A `headers` property + * served as an object with no `properties`, as on `*_execute_action`, declares every name. * * @returns The result as the server wrote it: for an action tool, * `{ isError: false, result, defenderMetadata?, policyMetadata? }`. A file action's `result` @@ -396,9 +403,7 @@ export class StackOneMcpTool extends StackOneTool { options?: ExecuteOptions, ): Promise { const parsed = this.parseArguments(inputParams); - const args = isPlainObject(parsed.headers) - ? { ...parsed, headers: sanitiseHeaders(parsed.headers, this.#allowedHeaders) } - : parsed; + const args = sanitiseHeaderArguments(parsed, this.#declaredHeaders); if (options?.dryRun) { return { url: this.#endpoint, method: 'tools/call', name: this.name, arguments: args }; diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 7f100202..b843c203 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -292,6 +292,18 @@ describe('execute()', () => { expect(calls[0]?.arguments.headers).toEqual({}); }); + // *_execute_action serves `headers` as an open object, so a host can pass any header the SDK + // does not own through to the action. + it('forwards host-set headers the SDK does not own', async () => { + const { calls } = serveMock(); + + await newToolSet().execute('mock_list_items', { + headers: { 'x-custom': 'yes', Authorization: 'Bearer stolen' }, + }); + + expect(calls[0]?.arguments.headers).toEqual({ 'x-custom': 'yes' }); + }); + it('raises on an isError result rather than returning it as data', async () => { serveMock(); const error = (await newToolSet() diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 6512fb3c..1c301c8d 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -745,7 +745,7 @@ 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; an argument is only ever an argument. + // the transport's x-account-id, which the SDK sets; the argument never reaches the server. it('cannot switch tenant with headers_x-account-id, even when the schema declares it', async () => { const calls = serveTool({ type: 'object', @@ -756,6 +756,7 @@ describe('model-supplied headers', () => { await tool.execute({ 'headers_x-account-id': 'tenant-b', query_limit: 1 }); expect(calls[0]?.accountId).toBe('tenant-a'); + expect(calls[0]?.arguments).toEqual({ query_limit: 1 }); }); it('cannot switch tenant with a nested headers object', async () => { @@ -771,6 +772,30 @@ describe('model-supplied headers', () => { expect(calls[0]?.arguments.headers).toEqual({}); }); + it('drops a headers_* argument the served schema does not declare', async () => { + const calls = serveTool({ type: 'object', properties: { query_limit: { type: 'number' } } }); + const tool = await fetchTool(); + + await tool.execute({ headers_foo: 'bar', query_limit: 1 }); + + expect(calls[0]?.arguments).toEqual({ query_limit: 1 }); + expect(String(warnSpy.mock.calls[0]?.[0])).toContain( + '"headers_foo" from a tool call: not declared by the schema', + ); + }); + + it('forwards a headers_* argument the served schema declares', async () => { + const calls = serveTool({ + type: 'object', + properties: { 'headers_x-trace': { type: 'string' }, query_limit: { type: 'number' } }, + }); + const tool = await fetchTool(); + + await tool.execute({ 'headers_x-trace': 'abc', query_limit: 1 }); + + expect(calls[0]?.arguments).toEqual({ 'headers_x-trace': 'abc', query_limit: 1 }); + }); + it('forwards a header the served schema declares', async () => { const calls = serveTool({ type: 'object', @@ -782,6 +807,44 @@ describe('model-supplied headers', () => { expect(calls[0]?.arguments.headers).toEqual({ 'x-trace': 'abc' }); }); + + it('forwards any header through an open headers object, except the ones the SDK owns', async () => { + const calls = serveTool({ type: 'object', properties: { headers: { type: 'object' } } }); + const tool = await fetchTool(); + + await tool.execute({ + headers: { 'x-custom': 'yes', Authorization: 'Bearer stolen', 'x-account-id': 'tenant-b' }, + }); + + expect(calls[0]?.accountId).toBe('tenant-a'); + expect(calls[0]?.arguments.headers).toEqual({ 'x-custom': 'yes' }); + expect(warnSpy.mock.calls.map((args: unknown[]) => String(args[0]))).toEqual([ + '[@stackone/ai] Dropping header "Authorization" from a tool call: set by the SDK', + '[@stackone/ai] Dropping header "x-account-id" from a tool call: set by the SDK', + ]); + }); + + it('sends every argument that is not a header argument unchanged', async () => { + const calls = serveTool({ + type: 'object', + properties: { + query_limit: { type: 'number' }, + path: { type: 'object' }, + body: { type: 'object' }, + }, + }); + const tool = await fetchTool(); + const args = { + query_limit: 1, + path: { id: 'c1' }, + body: { headers: { Authorization: 'kept' }, headers_x: 'kept' }, + x_account_id: 'kept', + }; + + await tool.execute(args); + + expect(calls[0]?.arguments).toEqual(args); + }); }); describe('openai()', () => { diff --git a/src/toolsets.ts b/src/toolsets.ts index 18d69455..9dddcbd9 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -758,6 +758,10 @@ export class StackOneToolSet { * keys. The connector is the longest one whose name prefixes `actionId`, and `actionId` is * pinned last, so a model-supplied `action_id` in `args` cannot replace it. * + * `args.headers` is forwarded to the action: `*_execute_action` serves `headers` as an open + * object, so any header name is declared — except `Authorization`, `x-account-id` and + * `User-Agent`, which the SDK sets itself and drops here with a warning. + * * @param actionId The action to run, e.g. `linear_list_issues`. * @param args The action's arguments. * @param options.sessionId The `session_id` a search hit carries, to link this call to it. From 10975c80e57f19bc3b227ae0604f5c68153de83e Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:04:13 +0100 Subject: [PATCH 022/151] fix(feedback): submit feedback with one tools/call on the first account submitFeedback() listed the catalog in the toolset's own mode across every scoped account. The feedback tool is global, so it now lists `tool-mode=search_execute` (two meta tools per connector rather than every action) on a single account and makes exactly one tools/call there. That account is the first in the order given, not the first by id: the first of the call's `accountIds`, else the toolset's, else the first active account `GET /accounts` lists. Account scoping keeps a separate, unsorted path for this; listing still sorts its scope for the cache key. --- README.md | 2 +- src/toolsets.search-execute.test.ts | 45 ++++++++++++++++++++++++++++- src/toolsets.ts | 31 ++++++++++++++++---- 3 files changed, 70 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index ad619954..d5b7ba5a 100644 --- a/README.md +++ b/README.md @@ -323,7 +323,7 @@ await toolset.submitFeedback({ }); ``` -The SDK never builds a feedback tool itself: if the server does not serve it, `submitFeedback()` throws a `ToolSetLoadError` saying feedback is not enabled for the project. +`submitFeedback()` makes exactly one call, on the first account: the first of its `accountIds` when given, otherwise the first the toolset is configured with or discovers. The SDK never builds a feedback tool itself: if the server does not serve it, `submitFeedback()` throws a `ToolSetLoadError` saying feedback is not enabled for the project. ### Tool modes diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index b843c203..f304eccb 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -400,7 +400,7 @@ describe('submitFeedback()', () => { expect(calls).toEqual([ { accountId: 'acc1', - toolMode: undefined, + toolMode: 'search_execute', name: 'stackone_submit_feedback', arguments: { rating: 'negative', @@ -442,6 +442,49 @@ describe('submitFeedback()', () => { expect(calls.map((call) => call.name)).toEqual(['stackone_submit_feedback']); }); + // The tool is global, so one call per account would record the same verdict once per account. + it('lists search_execute and calls once, on the first of the given accounts', async () => { + const { calls } = serveMock({ + accountTools: { acc1: [], acc2: [] }, + submitFeedback: true, + }); + + await newToolSet({ accountIds: ['acc1'] }).submitFeedback({ + rating: 'positive', + toolNames: ['x'], + accountIds: ['acc2', 'acc1'], + }); + + expect(listMock.mock.calls.map(([request]) => request.endpoint)).toEqual([ + `${TEST_BASE_URL}/mcp?tool-mode=search_execute`, + ]); + expect(calls.map((call) => [call.name, call.accountId, call.toolMode])).toEqual([ + ['stackone_submit_feedback', 'acc2', 'search_execute'], + ]); + }); + + it('calls on the first account GET /accounts lists, not the first by id', async () => { + const { calls } = serveMock({ + accountTools: { zeta: [], alpha: [] }, + submitFeedback: true, + }); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json([ + { id: 'gone', provider: 'p', status: 'error' }, + { id: 'zeta', provider: 'p', status: 'active' }, + { id: 'alpha', provider: 'p', status: 'active' }, + ]), + ), + ); + + await newToolSet().submitFeedback({ rating: 'positive', toolNames: ['x'] }); + + expect(calls.map((call) => [call.name, call.accountId])).toEqual([ + ['stackone_submit_feedback', 'zeta'], + ]); + }); + it('explains that feedback is not enabled when the server does not serve the tool', async () => { serveMock({ submitFeedback: false }); const error = await newToolSet({ accountId: 'acc1' }) diff --git a/src/toolsets.ts b/src/toolsets.ts index 9dddcbd9..d059b014 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -170,7 +170,10 @@ export interface SubmitFeedbackOptions { sessionId?: string; /** Who produced the feedback. Default: `'model'`. */ source?: FeedbackSource; - /** Accounts to list the tool through. Defaults as for {@link StackOneToolSet.fetchTools}. */ + /** + * The feedback is sent through the first of these accounts. Defaults as for + * {@link StackOneToolSet.fetchTools}, in the order given or discovered. + */ accountIds?: string[]; } @@ -501,7 +504,11 @@ export class StackOneToolSet { return active; } - async #resolveAccountScope(accountIds: string[] | undefined): Promise { + /** + * The accounts a call is scoped to, in the order they were given: the call's own, then the + * toolset's, then its single account, then every active account in `GET /accounts` order. + */ + async #accountsInOrder(accountIds: string[] | undefined): Promise { assertAccountIdList(accountIds, 'accountIds'); let scope = accountIds?.length ? accountIds : this.#accountIds; if (scope.length === 0 && this.#accountId) { @@ -510,9 +517,13 @@ export class StackOneToolSet { if (scope.length === 0) { scope = await this.#discoverAccountIds(); } + return scope; + } + + async #resolveAccountScope(accountIds: string[] | 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(scope)].sort(); + return [...new Set(await this.#accountsInOrder(accountIds))].sort(); } #endpoint(mode: ToolMode | undefined): string { @@ -839,6 +850,9 @@ export class StackOneToolSet { * feedback is enabled for the project, and a client-side stand-in would report success for * feedback that went nowhere. Unset optional fields are omitted, never sent as null. * + * Makes exactly one `tools/call`, on the first account: the first of `accountIds` when given, + * otherwise the toolset's first, otherwise the first active account `GET /accounts` lists. + * * @example * ```typescript * const [hit] = await toolset.search('list recent comments'); @@ -864,9 +878,14 @@ export class StackOneToolSet { throw new ToolSetConfigError('toolNames must be an array of tool names'); } - const tool = (await this.fetchTools({ accountIds: options.accountIds })).getTool( - SUBMIT_FEEDBACK_TOOL_NAME, - ); + // 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 first account, in the + // order given, is the one a caller can predict. search_execute lists two meta tools per + // connector where individual mode lists every action. + const [accountId] = await this.#accountsInOrder(options.accountIds); + const tool = ( + await this.fetchTools({ accountIds: accountId ? [accountId] : [], mode: 'search_execute' }) + ).getTool(SUBMIT_FEEDBACK_TOOL_NAME); if (!tool) { throw new ToolSetLoadError( `The server did not serve ${SUBMIT_FEEDBACK_TOOL_NAME}: feedback is not enabled for this project.`, From d44ec90d7bf5e03a15909c9dfb3d6dcd7c76ae8d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:04:35 +0100 Subject: [PATCH 023/151] test(toolsets): pin getTool() to the first listed duplicate Two accounts can serve the same tool name. The Tools unit test pins first-match-wins; this pins it end to end: the listing is ordered by account id whatever order the caller named them in, so the duplicate getTool() returns is predictable. --- src/toolsets.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 1c301c8d..df0c9e02 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -650,6 +650,20 @@ describe('duplicate tool names', () => { ); }); + // Listing order is by account id, whatever order the caller named them in, so which duplicate + // getTool() returns is predictable. + it('returns the first listed duplicate from getTool(), by account id', async () => { + fakeListing(() => [def('hibob_list_employees')]); + + const tools = await newToolSet().fetchTools({ accountIds: ['b', 'a'] }); + + expect(tools.toArray().map((tool) => (tool as StackOneTool).getAccountId())).toEqual([ + 'a', + 'b', + ]); + expect(tools.getTool('hibob_list_employees')).toBe(tools.toArray()[0]); + }); + it('stays quiet when names are unique', async () => { await newToolSet().fetchTools({ accountIds: ['acc1', 'acc2'] }); expect(warnSpy).not.toHaveBeenCalled(); From 406504d1fc7c69fc59cb063ee64ec88436ee2934 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:05:07 +0100 Subject: [PATCH 024/151] refactor(errors): remove the unused describeApiFailure() Nothing has called it since the RPC client went: tools/call failures build their message from the result's own text in mcp-client.ts. Drop it and its tests, and stop the README promising the "400 Bad Request: path.id is missing" message format it produced. --- README.md | 2 +- src/utils/error-stackone-api.test.ts | 23 +---------------------- src/utils/error-stackone-api.ts | 27 --------------------------- 3 files changed, 2 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index d5b7ba5a..c5462295 100644 --- a/README.md +++ b/README.md @@ -404,7 +404,7 @@ const toolset = new StackOneToolSet({ headers: { 'X-Request-Source': 'my-agent' Everything the SDK throws is a `StackOneError`: -- `StackOneAPIError` — the API refused a request. Carries `statusCode` and `responseBody`, and its message leads with the server's own explanation (`400 Bad Request: path.id is missing`). A failed MCP `tools/call` raises one too, with the status from its payload; a dead account surfaces as a `412`. +- `StackOneAPIError` — the API refused a request. Carries `statusCode` and `responseBody`, and its message carries the server's own explanation. A failed MCP `tools/call` raises one too, with the status from its payload and the result's text in the message (`Tool "hibob_get_employee" failed: …`); a dead account surfaces as a `412`. - `ToolSetConfigError` — the toolset was configured, or called, with something it cannot use. - `ToolSetLoadError` — the catalog, or the accounts behind it, could not be loaded. diff --git a/src/utils/error-stackone-api.test.ts b/src/utils/error-stackone-api.test.ts index c526f91d..64376493 100644 --- a/src/utils/error-stackone-api.test.ts +++ b/src/utils/error-stackone-api.test.ts @@ -1,6 +1,6 @@ import { USER_AGENT } from '../consts'; import { TEST_BASE_URL } from '../../mocks/constants'; -import { StackOneAPIError, describeApiFailure } from './error-stackone-api'; +import { StackOneAPIError } from './error-stackone-api'; describe('StackOneAPIError', () => { it('should create an error with basic properties', () => { @@ -192,24 +192,3 @@ describe('StackOneAPIError', () => { expect(result).not.toContain('Provider Endpoint:'); }); }); - -describe('describeApiFailure', () => { - it.each([ - [{ message: 'path.id is missing', error: 'ignored' }, '400 Bad Request: path.id is missing'], - [{ error: 'Invalid ID' }, '400 Bad Request: Invalid ID'], - [{ detail: 'Nope' }, '400 Bad Request: Nope'], - [{ code: 7 }, '400 Bad Request: {"code":7}'], - [' plain text ', '400 Bad Request: plain text'], - [['a'], '400 Bad Request: ["a"]'], - [null, '400 Bad Request from https://api.example.com/x'], - ['', '400 Bad Request from https://api.example.com/x'], - ])('leads with the server explanation in %j', (body, expected) => { - expect(describeApiFailure(400, 'Bad Request', body, 'https://api.example.com/x')).toBe( - expected, - ); - }); - - it('caps a long text body', () => { - expect(describeApiFailure(500, '', 'x'.repeat(900), 'u')).toBe(`500: ${'x'.repeat(500)}`); - }); -}); diff --git a/src/utils/error-stackone-api.ts b/src/utils/error-stackone-api.ts index 59eded17..343f5762 100644 --- a/src/utils/error-stackone-api.ts +++ b/src/utils/error-stackone-api.ts @@ -1,33 +1,6 @@ import { USER_AGENT } from '../consts'; import { StackOneError } from './error-stackone'; -/** - * Lead with the server's own explanation of what went wrong. - * - * A bare status ("400 Bad Request") never says which field was wrong, even though the answer is - * already in hand in the response body. This is the error a user hits on every bad tool call, so - * it is the one worth making actionable: `400 Bad Request: path.id is missing`. - */ -export function describeApiFailure( - status: number, - statusText: string, - body: unknown, - url: string, -): string { - let detail: string | undefined; - if (typeof body === 'object' && body !== null && !Array.isArray(body)) { - const record = body as Record; - const key = ['message', 'error', 'detail'].find((name) => typeof record[name] === 'string'); - detail = key ? (record[key] as string) : JSON.stringify(body); - } else if (typeof body === 'string' && body.trim()) { - detail = body.trim().slice(0, 500); - } else if (body != null && typeof body !== 'string') { - detail = JSON.stringify(body); - } - const heading = `${status} ${statusText}`.trim(); - return detail ? `${heading}: ${detail}` : `${heading} from ${url}`; -} - /** * Raised when the StackOne API returns an error. Carries the HTTP status and the response * body, so a caller can branch on a 412 (a dead account) rather than parse the message. From 37e2efea1cd4c6a9fbf5d1d989dbef7e3b3d16f8 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:05:44 +0100 Subject: [PATCH 025/151] fix(toolsets): share one in-flight account discovery between concurrent calls The discovered accounts were cached only once the request returned, so search() and fetchTools() started together on a fresh toolset each sent their own GET /accounts. Share the in-flight promise instead. A failed discovery is not kept, so the next call retries, and clearCatalogCache() drops an in-flight one as it already drops the result. --- src/toolsets.test.ts | 33 +++++++++++++++++++++++++++++++++ src/toolsets.ts | 16 ++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index df0c9e02..4622ec0d 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -207,6 +207,39 @@ describe('account discovery', () => { expect(requests).toBe(2); }); + it('shares one discovery between concurrent calls', async () => { + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + requests += 1; + return HttpResponse.json([{ id: 'acc1', status: 'active' }]); + }), + ); + fakeListing(() => []); + const toolset = newToolSet(); + + await Promise.all([toolset.search('x'), toolset.fetchTools(), toolset.fetchTools()]); + + expect(requests).toBe(1); + }); + + it('retries a discovery that failed', async () => { + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + requests += 1; + return requests === 1 + ? HttpResponse.json({ message: 'busy' }, { status: 503 }) + : HttpResponse.json([{ id: 'acc1', status: 'active' }]); + }), + ); + const toolset = newToolSet(); + + await expect(toolset.fetchTools()).rejects.toBeInstanceOf(StackOneAPIError); + expect(names(await toolset.fetchTools())).toEqual(['acc1_tool_1', 'acc1_tool_2']); + expect(requests).toBe(2); + }); + it('accepts a { data: [...] } wrapper', async () => { server.use( http.get(`${TEST_BASE_URL}/accounts`, () => diff --git a/src/toolsets.ts b/src/toolsets.ts index d059b014..3bca3364 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -309,6 +309,7 @@ export class StackOneToolSet { */ readonly #catalogCache = new Map(); #discoveredAccountIds: string[] | undefined; + #discovering: Promise | undefined; /** * Bumped by {@link clearCatalogCache}. A listing already in flight when the cache is cleared * captured the generation it started under, and refuses to write back if it has moved — @@ -376,6 +377,7 @@ export class StackOneToolSet { this.#cacheGeneration += 1; this.#catalogCache.clear(); this.#discoveredAccountIds = undefined; + this.#discovering = undefined; } /** @@ -478,6 +480,20 @@ export class StackOneToolSet { if (this.#discoveredAccountIds) { 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) { + const discovering = this.#fetchActiveAccountIds().finally(() => { + if (this.#discovering === discovering) { + this.#discovering = undefined; + } + }); + this.#discovering = discovering; + } + return this.#discovering; + } + + async #fetchActiveAccountIds(): Promise { const generation = this.#cacheGeneration; const accounts = await this.fetchAccounts(); const active = accounts From 7d65495406e1169c42309e64ddbbebcbc0857259 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:06:11 +0100 Subject: [PATCH 026/151] fix(tools): serialise a tool result of undefined as "null" JSON.stringify(undefined) returns undefined, not a string, so a hand-built tool that returned nothing produced a tool message with `content: undefined` from executeOpenAIToolCalls(), and an empty text part from the Claude Agent SDK adapter. Write "null" instead, which is what the Python SDK sends for None (`json.dumps(None)`). --- src/tool.test.ts | 6 ++++++ src/utils/serialize.ts | 28 ++++++++++++++++++---------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/tool.test.ts b/src/tool.test.ts index 9ebfa3ce..e617c78b 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -721,6 +721,12 @@ describe('Tools.executeOpenAIToolCalls', () => { }); }); + it('sends "null" for a tool that returns nothing, as the Python SDK does', async () => { + const { tools } = toolsWith(async () => undefined as never); + const [message] = await tools.executeOpenAIToolCalls([call('linear_list_issues')]); + expect(message?.content).toBe('null'); + }); + it('rethrows an error that is not the SDK’s', async () => { const { tools } = toolsWith(async () => { throw new TypeError('programming error'); diff --git a/src/utils/serialize.ts b/src/utils/serialize.ts index 0a856da8..ff8342a3 100644 --- a/src/utils/serialize.ts +++ b/src/utils/serialize.ts @@ -6,16 +6,24 @@ * base64-encoded instead, and a `bigint` is written as its decimal string rather than throwing. * The replacer reads the ORIGINAL value from its holder, because `JSON.stringify` has already * called `Buffer#toJSON` by the time the replacer sees `value`. + * + * A result `JSON.stringify` cannot represent — `undefined`, from a hand-built tool that returns + * nothing — is written as `"null"`, as the Python SDK's `json.dumps(None)` writes it, rather than + * becoming a message with no content at all. */ export function serializeToolResult(result: unknown): string { - return JSON.stringify(result, function replacer(this: unknown, key: string, value: unknown) { - const original = (this as Record)[key]; - if (original instanceof Uint8Array) { - return Buffer.from(original).toString('base64'); - } - if (typeof value === 'bigint') { - return value.toString(); - } - return value; - }); + const serialized: string | undefined = JSON.stringify( + result, + function replacer(this: unknown, key: string, value: unknown) { + const original = (this as Record)[key]; + if (original instanceof Uint8Array) { + return Buffer.from(original).toString('base64'); + } + if (typeof value === 'bigint') { + return value.toString(); + } + return value; + }, + ); + return serialized ?? 'null'; } From 3da22ecfdf03e427e9ef500e3df649d0d3781543 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:07:20 +0100 Subject: [PATCH 027/151] feat(types): declare the fields a search hit carries SearchResult typed only action_id and session_id, so reading a hit's score or schema needed a typeof guard, and passing `best.example_request` to execute() (as the README does) did not type-check. Declare `description`, `similarity_score`, `input_schema` and `example_request` as the per-connector `*_search_actions` tool serves them. All are optional: the server omits input_schema and example_request for an action with no inputs, and the SDK passes hits through without validating them. The example reads the score without narrowing. --- examples/search-and-execute.ts | 3 +-- src/toolsets.test-d.ts | 13 ++++++++++++- src/toolsets.ts | 2 +- src/types.ts | 15 +++++++++++++-- 4 files changed, 27 insertions(+), 6 deletions(-) diff --git a/examples/search-and-execute.ts b/examples/search-and-execute.ts index 9659e7d8..82878c9e 100644 --- a/examples/search-and-execute.ts +++ b/examples/search-and-execute.ts @@ -38,8 +38,7 @@ const searchAndExecute = async (): Promise => { console.log('\nRanked matches:'); for (const action of actions) { - const score = typeof action.similarity_score === 'number' ? action.similarity_score : 0; - console.log(` ${score.toFixed(3)} ${action.action_id}`); + console.log(` ${(action.similarity_score ?? 0).toFixed(3)} ${action.action_id}`); } // input_schema is how you find out what an action accepts. Build the call from it and from diff --git a/src/toolsets.test-d.ts b/src/toolsets.test-d.ts index 2a7642f0..eda2cdf7 100644 --- a/src/toolsets.test-d.ts +++ b/src/toolsets.test-d.ts @@ -1,5 +1,6 @@ import { expectTypeOf } from 'vitest'; -import type { StackOneToolSetConfig } from './toolsets'; +import type { StackOneToolSet, StackOneToolSetConfig } from './toolsets'; +import type { JsonObject, SearchResult } from './types'; // Valid configurations - only accountId test('StackOneToolSetConfig accepts only accountId', () => { @@ -42,3 +43,13 @@ test('accountId is typed as string | undefined', () => { test('accountIds is typed as string[] | undefined', () => { expectTypeOf().toEqualTypeOf(); }); + +// A search hit's served fields are typed, so a caller needs no narrowing to read them +test('SearchResult declares the fields the server serves', () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toExtend< + Parameters[1] + >(); +}); diff --git a/src/toolsets.ts b/src/toolsets.ts index 3bca3364..62d64dcb 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -712,7 +712,7 @@ export class StackOneToolSet { * with a warning, unless they all fail. * * @param query What you want to do, e.g. "list recent comments". - * @returns Actions carrying at least `action_id` and `description`, best first, each with the + * @returns Actions carrying at least `action_id`, best first, each with the * `session_id` of the search that found it when the server issued one. Pass it to * {@link execute} and {@link submitFeedback} to link the calls. * @throws ToolSetConfigError If `topK` is not an integer between 1 and 50. diff --git a/src/types.ts b/src/types.ts index c4fbeed4..eaa3ffea 100644 --- a/src/types.ts +++ b/src/types.ts @@ -193,11 +193,22 @@ export type StackOneAccount = JsonObject & { }; /** - * One action a `search()` found. Carries at least `action_id` and `description`, plus whatever - * else the server returns for it (`similarity_score`, `input_schema`, `example_request`, …). + * One action a `search()` found, as the server returned it: `action_id` always, the fields below + * when the server sent them, and anything else it adds. */ export type SearchResult = JsonObject & { action_id: string; + /** What the action does. */ + description?: string; + /** How well the action matched the query; results are ranked on it, highest first. */ + similarity_score?: number; + /** + * The JSON Schema of the arguments `execute()` takes for this action. The server omits it for + * an action that takes none. + */ + input_schema?: JsonObject; + /** A copy-and-edit `execute()` call for the action, served alongside `input_schema`. */ + example_request?: JsonObject; /** * The `session_id` of the search that produced this hit, when the server issued one. Pass it * to `execute()` and `submitFeedback()` to link those calls to this search. From 25812d11a6bd191ce79d1f205ff3c6d7312530bd Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:12:26 +0100 Subject: [PATCH 028/151] docs: add a 2.x to 3.0 migration guide Every breaking change since 2.10.0, each with the 2.x code and its 3.0 replacement: removed exports, constructor options, server-side search and execute, the result shape and download links, the header-argument allowlist, account discovery and ordering, submitFeedback(), the error hierarchy and StackOneAPIError messages, schema pass-through, and hand-built tools. Structured like the Python SDK's MIGRATION.md so the two read the same. Linked from the top of the README. --- MIGRATION.md | 299 +++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 3 + 2 files changed, 302 insertions(+) create mode 100644 MIGRATION.md diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 00000000..8ff131b8 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,299 @@ +# Migrating from 2.x to 3.0 + +3.0 is a thin client over StackOne's MCP endpoint. Every tool call goes over MCP `tools/call`, and the only other request the SDK makes is `GET /accounts`, to find your linked accounts. Search runs on the server. Anything MCP does not support has been removed rather than kept on a second transport. + +Work through the sections that apply to you. Each one gives the 2.x code and its 3.0 replacement. + +- [Installation](#installation) +- [Removed exports](#removed-exports) +- [Constructor options](#constructor-options) +- [Search and execute](#search-and-execute) +- [Results](#results) +- [Tool arguments and headers](#tool-arguments-and-headers) +- [Accounts](#accounts) +- [Feedback](#feedback) +- [Errors](#errors) +- [Schemas given to a model](#schemas-given-to-a-model) +- [Hand-built tools and `ExecuteConfig`](#hand-built-tools-and-executeconfig) + +## Installation + +`zod` is no longer a peer dependency, and `@orama/orama` and `defu` are no longer dependencies. Nothing else changes. + +```bash +# 2.x +npm install @stackone/ai zod + +# 3.0 +npm install @stackone/ai +``` + +## Removed exports + +These names are no longer exported from `@stackone/ai`: + +| Removed | Use instead | +| ------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- | +| `SearchTool`, `SearchMode`, `SearchConfig`, `SearchToolsOptions`, `SearchActionNamesOptions` | `toolset.search()`. See [Search and execute](#search-and-execute) | +| `SemanticSearchClient`, `SemanticSearchError`, `SemanticSearchOptions`, `SemanticSearchResponse`, `SemanticSearchResult` | `toolset.search()`, which returns `SearchResult` objects | +| `createFeedbackTool` | `toolset.submitFeedback()`. See [Feedback](#feedback) | +| `DefenderConfig`, `DefenderMode`, `DEFAULT_DEFENDER_CONFIG` | Defender settings in the StackOne dashboard. See [Constructor options](#constructor-options) | +| `BinaryDownloadResult`, `isBinaryDownloadResult` | The download link in the result. See [Results](#results) | +| `AuthenticationConfig`, `BaseToolSetConfig` | `StackOneToolSetConfig`, with `apiKey` | +| `ParameterLocation` | Nothing. The server maps arguments onto the request | + +`ToolSetError`, `ToolSetConfigError` and `ToolSetLoadError` are still exported from the package root. + +## Constructor options + +**An API key is required.** 2.x warned and carried on without one; 3.0 throws `ToolSetConfigError`. The `strict` option, which made 2.x throw, is gone. + +**`authentication`, `rpcClient`, `search`, `strict` and `defender` are removed.** Pass the key as `apiKey` (or set `STACKONE_API_KEY`), and configure Defender per project in the StackOne dashboard. The `defenderMode` getter is gone with the option. + +```typescript +// 2.x +const toolset = new StackOneToolSet({ + authentication: { type: 'basic', credentials: { username: apiKey } }, + search: { method: 'auto' }, + defender: { ...DEFAULT_DEFENDER_CONFIG, blockHighRisk: true }, +}); + +// 3.0 +const toolset = new StackOneToolSet({ apiKey }); +``` + +**`Authorization`, `x-account-id` and `User-Agent` in `headers` are ignored**, with a warning. The SDK always sets them itself, so a `headers` option can no longer replace the credential or point requests at another account. Use `apiKey` and `accountId` / `accountIds` instead. Any other header is still sent with every request. + +```typescript +// 2.x: this header replaced the Basic credential +new StackOneToolSet({ headers: { Authorization: `Bearer ${token}`, 'x-account-id': 'acc-1' } }); + +// 3.0 +new StackOneToolSet({ apiKey, accountId: 'acc-1' }); +``` + +## Search and execute + +Client-side search is gone: the local BM25/TF-IDF index, the semantic search client, the `search` constructor option, and the `tool_search` / `tool_execute` meta tools. The server's `*_search_actions` tool now does the search, and `toolset.execute()` runs an action by id through the server's `*_execute_action` tool. + +```typescript +// 2.x +const toolset = new StackOneToolSet({ search: { method: 'auto' } }); +const tools = await toolset.searchTools('list employees', { topK: 5 }); +const result = await tools.toArray()[0]?.execute({ query_page_size: 25 }); + +const names = await toolset.searchActionNames('time off requests', { topK: 5 }); + +// 3.0 +const toolset = new StackOneToolSet(); +const [hit] = await toolset.search('list employees', { topK: 5 }); // SearchResult[], best first +const result = await toolset.execute( + hit.action_id, + { query: { page_size: 25 } }, // the nested form hit.input_schema describes + { sessionId: hit.session_id }, +); +``` + +`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id`, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `execute()` raises rather than returning `{ error }`: `ToolSetLoadError` when no linked connector serves the action, `StackOneAPIError` when the action fails. + +To give a model the search and execute tools, set the tool mode on the toolset. `openai()` no longer takes `mode`. + +```typescript +// 2.x +const toolset = new StackOneToolSet({ search: {} }); +const openAITools = await toolset.openai({ mode: 'search_and_execute' }); + +// 3.0: two tools per connector, served by the server +const toolset = new StackOneToolSet({ toolMode: 'search_execute' }); +const tools = await toolset.fetchTools(); +const openAITools = tools.toOpenAI(); +// ...then run the model's tool calls and get the messages to send back: +messages.push(message, ...(await tools.executeOpenAIToolCalls(message.tool_calls))); +``` + +## Results + +**Every tool returns the server's result as the server wrote it.** For an action, that is `{ isError: false, result, defenderMetadata?, policyMetadata? }`. Search results are bare JSON. This applies to `tool.execute()` and `toolset.execute()` alike. + +```typescript +const tool = (await toolset.fetchTools()).getTool('hibob_list_employees'); + +// 2.x +const employees = (await tool.execute({})).data; + +// 3.0 +const employees = (await tool.execute({})).result.data; +``` + +A result with `isError` set raises `StackOneAPIError`, with the status from its payload in `statusCode` and the payload in `responseBody`. + +**File actions return a download link, not bytes.** The SDK does not follow the link. When no link can be issued, the call raises `StackOneAPIError` with `statusCode` 501. + +```typescript +// 2.x +const result = await download.execute({ id: 'file-id' }); +if (isBinaryDownloadResult(result)) { + writeFileSync(result.fileName ?? 'download.bin', result.content); +} + +// 3.0 +const { result: link } = await download.execute({ id: 'file-id' }); +// { download_url, expires_at, file: { name, content_type, content_length } } +const name = path.basename(link.file.name ?? 'download.bin'); // chosen by the provider: keep only the basename +writeFileSync(name, Buffer.from(await (await fetch(link.download_url)).arrayBuffer())); +``` + +**`dryRun` describes the `tools/call`**, not an HTTP request: + +```typescript +await tool.execute({ id: '1' }, { dryRun: true }); +// 2.x: { url: '.../actions/rpc', method: 'POST', headers, body, mappedParams } +// 3.0: { url: '.../mcp', method: 'tools/call', name: 'hibob_get_employee', arguments: { id: '1' } } +``` + +## Tool arguments and headers + +**Arguments are sent exactly as given**, as `tools/call` arguments. The SDK no longer splits flat `path_` / `query_` / `body_` keys into an `/actions/rpc` envelope; the server maps them itself. + +**`fetchTools()` tools have the server's own argument shape.** 2.x asked the server for the flat, prefixed style (`?param-style=flat_prefixed`). That request is gone, so the argument names are whatever the server serves for your project. Read them from `tool.parameters.properties` rather than hard-coding them: + +```typescript +// 2.x +await tool.execute({ body_variables: { first: 25 } }); + +// 3.0: use the keys the schema names, for example +console.log(tool.parameters.properties); +await tool.execute({ body: { variables: { first: 25 } } }); +``` + +**Header arguments are allowlisted.** A header argument is an entry of a `headers` object argument, or a top-level `headers_` argument. Each one is forwarded only if the tool's schema declares it in the same form: under `headers.properties`, or as a `headers_` property. An open `headers` object, with no `properties`, declares every name. `Authorization`, `x-account-id` and `User-Agent` are never forwarded, even when declared, because the SDK sets them itself. Anything dropped is logged as a warning. Every other argument is sent unchanged. + +`*_execute_action` serves an open `headers` object, so `toolset.execute()` passes your own headers on to the action, with the exception of those three: + +```typescript +await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' } }); +``` + +## Accounts + +**With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active account. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. + +**Listings are merged in sorted account order.** When two accounts serve the same tool name, `getTool()` returns the first one listed — now the one on the lowest account id, where 2.x followed the order you passed. A warning names the clashing tools. Pass `accountIds` to choose the account yourself. + +**`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. An account whose listing fails is skipped with a warning, unless every account fails. + +## Feedback + +The client-side `tool_feedback` tool and `createFeedbackTool()` have been removed, and `fetchTools()` no longer appends a feedback tool of its own. + +```typescript +// 2.x +const feedbackTool = (await toolset.fetchTools()).getTool('tool_feedback'); +await feedbackTool.execute({ + feedback: 'Worked well', + account_id: 'acc_123', + tool_names: ['workday_list_workers'], +}); + +// 3.0 +const [hit] = await toolset.search('list workers'); +await toolset.execute(hit.action_id, {}, { sessionId: hit.session_id }); +await toolset.submitFeedback({ + rating: 'positive', + toolNames: [hit.action_id], + feedback: 'Worked well', + sessionId: hit.session_id, +}); +``` + +When feedback is enabled for your project, the server also serves a `stackone_submit_feedback` tool. **`fetchTools()` and `openai()` include it**, once, however many accounts are linked. If you don't want a model to call it, filter it out: + +```typescript +const tools = (await toolset.fetchTools()).filter( + (tool) => tool.name !== 'stackone_submit_feedback', +); +``` + +`submitFeedback()` throws `ToolSetLoadError` when feedback is not enabled. + +## Errors + +**Every error the SDK throws is a `StackOneError`.** `ToolSetError`, `ToolSetConfigError` and `ToolSetLoadError` extended `Error` in 2.x; they now extend `StackOneError`, alongside `StackOneAPIError`. If you tell them apart with `instanceof`, check the toolset errors first: + +```typescript +try { + await toolset.fetchTools(); +} catch (error) { + if (error instanceof ToolSetError) { + // configuration or loading — test this first: it is also a StackOneError now + } else if (error instanceof StackOneError) { + // the API refused the request + } +} +``` + +**`StackOneAPIError` keeps the message it is given.** 2.x appended the response body's `message` to it (`Request failed: path.id is missing`). Read the server's explanation from `error.responseBody` instead; the SDK's own messages already include it. + +```typescript +// 2.x +new StackOneAPIError('Request failed', 400, { message: 'path.id is missing' }).message; +// 'Request failed: path.id is missing' + +// 3.0 +new StackOneAPIError('Request failed', 400, { message: 'path.id is missing' }).message; +// 'Request failed' +``` + +## Schemas given to a model + +**`toJsonSchema()` passes the served schema through**: root keywords such as `$schema`, `$defs`, `title` and `additionalProperties` reach the model as the server served them, and `required` is the served list, left out when it is missing or empty. `toOpenAI()`, `toAnthropic()`, `toOpenAIResponses()`, `toAISDK()` and `toClaudeAgentSdkTool()` fold a top-level `oneOf` / `anyOf` / `allOf`, which those APIs reject, into the root. + +## Hand-built tools and `ExecuteConfig` + +**`BaseTool` no longer makes HTTP requests.** Its `execute()` throws unless a subclass overrides it, `RequestBuilder` is gone, and `ExecuteConfig` is `{ kind: 'mcp', … }` or `{ kind: 'local', … }` — the `http` and `rpc` kinds are removed. Tools from `fetchTools()` execute over MCP. + +```typescript +// 2.x +const tool = new BaseTool( + 'get_employee', + 'Get an employee', + { type: 'object', properties: { id: { type: 'string' } } }, + { + kind: 'http', + method: 'GET', + url: 'https://api.example.com/employees/{id}', + bodyType: 'json', + params: [{ name: 'id', location: 'path', type: 'string' }], + }, + { Authorization: `Bearer ${token}` }, +); + +// 3.0 +class GetEmployee extends BaseTool { + override async execute(input?: JsonObject | string): Promise { + const { id } = typeof input === 'string' ? JSON.parse(input) : (input ?? {}); + const response = await fetch(`https://api.example.com/employees/${id}`, { + headers: { Authorization: `Bearer ${token}` }, + }); + return response.json(); + } +} +const tool = new GetEmployee( + 'get_employee', + 'Get an employee', + { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] }, + { kind: 'local' }, +); +``` + +**Tools no longer carry headers.** The `headers` constructor argument, `getHeaders()` and `setHeaders()` are removed from `BaseTool`, and `ToolExecution` — the `execution` metadata `toAISDK()` can attach — no longer has `headers`, so it cannot leak the credential. `StackOneTool`'s fifth constructor argument is now the account id; use `getAccountId()` / `setAccountId()` to read or rebind it. + +**`BaseTool#connector` and `Tools#getConnectors()` are removed.** Take the provider from the tool name, or filter with `fetchTools({ providers })`: + +```typescript +// 2.x +const connectors = tools.getConnectors(); + +// 3.0 +const connectors = new Set(tools.map((tool) => tool.name.split('_')[0])); +``` diff --git a/README.md b/README.md index c5462295..68b911b0 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,9 @@ +> **Upgrading from 2.x?** 3.0 has breaking changes. See the +> [migration guide](https://github.com/StackOneHQ/stackone-ai-node/blob/main/MIGRATION.md). + ## StackOneToolSet The StackOne AI SDK provides the `StackOneToolSet` class, a thin client over StackOne's MCP (Model Context Protocol) endpoint. It lists the tools your linked accounts serve and executes them, handing your model each tool's schema exactly as the server served it. From d0876f01a0538e2f2430770f699716c7495f7d3c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Wed, 30 Sep 2026 21:20:40 +0100 Subject: [PATCH 029/151] ci: pin sdk-conformance to 9b5605a --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index f65cd5f4..ad9437ee 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 13a93bad6ac94b5627f44e8d0cdda23814cd0605 + ref: 9b5605a520150c55724fdf9236871bc95e52b0cb token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 988e54c7cc397c627823b7f21a12a7eeeb33b71c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:42:11 +0100 Subject: [PATCH 030/151] fix(toolsets): reject an empty account id --- src/toolsets.search-execute.test.ts | 11 +++++++++++ src/toolsets.test.ts | 9 +++++++++ src/toolsets.ts | 15 ++++++++++----- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index f304eccb..6e89fa97 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -497,6 +497,17 @@ describe('submitFeedback()', () => { ); }); + it('refuses an empty account id rather than switch to another account', async () => { + const { calls } = serveMock({ submitFeedback: true }); + const error = await newToolSet({ accountId: 'acc1' }) + .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'); + expect(calls).toEqual([]); + }); + it('refuses a string where toolNames expects a list', async () => { await expect( newToolSet({ accountId: 'acc1' }).submitFeedback({ diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 4622ec0d..774dca19 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -93,6 +93,15 @@ describe('configuration', () => { await expect(async () => act()).rejects.toThrow(/not a string. Did you mean \["acc1"\]\?/); }); + it.each([ + ['accountIds', () => newToolSet({ accountIds: ['acc1', ''] })], + ['setAccounts', () => newToolSet().setAccounts([''])], + ['fetchTools', () => newToolSet().fetchTools({ accountIds: [''] })], + ])('refuses an empty account id in %s', async (_name, act) => { + await expect(async () => act()).rejects.toThrow(ToolSetConfigError); + await expect(async () => act()).rejects.toThrow(/must not contain an empty account id/); + }); + it('returns itself from setAccounts for chaining', () => { const toolset = newToolSet(); expect(toolset.setAccounts(['acc1'])).toBe(toolset); diff --git a/src/toolsets.ts b/src/toolsets.ts index 62d64dcb..e55a4040 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -281,6 +281,11 @@ const assertAccountIdList = (accountIds: unknown, parameter: string): void => { if (!Array.isArray(accountIds) || accountIds.some((id) => typeof id !== 'string')) { throw new ToolSetConfigError(`${parameter} must be an array of account id strings`); } + // An empty id would be sent with no x-account-id, so reject it rather than let the server + // answer for an account nobody chose. + if (accountIds.includes('')) { + throw new ToolSetConfigError(`${parameter} must not contain an empty account id`); + } }; /** @@ -880,7 +885,7 @@ export class StackOneToolSet { * }); * ``` * - * @throws ToolSetConfigError If `toolNames` is not a list. + * @throws ToolSetConfigError If `toolNames` is not a list, or `accountIds` holds an empty id. * @throws ToolSetLoadError If feedback is not enabled for this project. */ async submitFeedback(options: SubmitFeedbackOptions): Promise { @@ -898,10 +903,10 @@ export class StackOneToolSet { // feedback, and calling each would record it once per account. The first account, in the // order given, is the one a caller can predict. search_execute lists two meta tools per // connector where individual mode lists every action. - const [accountId] = await this.#accountsInOrder(options.accountIds); - const tool = ( - await this.fetchTools({ accountIds: accountId ? [accountId] : [], mode: 'search_execute' }) - ).getTool(SUBMIT_FEEDBACK_TOOL_NAME); + const accountIds = (await this.#accountsInOrder(options.accountIds)).slice(0, 1); + const tool = (await this.fetchTools({ accountIds, mode: 'search_execute' })).getTool( + SUBMIT_FEEDBACK_TOOL_NAME, + ); if (!tool) { throw new ToolSetLoadError( `The server did not serve ${SUBMIT_FEEDBACK_TOOL_NAME}: feedback is not enabled for this project.`, From c3c4c714616afb2387b6c6cb5f0a1d39ff6f7625 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:42:11 +0100 Subject: [PATCH 031/151] fix(headers): declare no names for a closed or untyped headers object --- MIGRATION.md | 2 +- README.md | 2 +- src/headers.test.ts | 23 +++++++++++++++++++++++ src/headers.ts | 7 +++++-- 4 files changed, 30 insertions(+), 4 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 8ff131b8..d3f1aea6 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -166,7 +166,7 @@ console.log(tool.parameters.properties); await tool.execute({ body: { variables: { first: 25 } } }); ``` -**Header arguments are allowlisted.** A header argument is an entry of a `headers` object argument, or a top-level `headers_` argument. Each one is forwarded only if the tool's schema declares it in the same form: under `headers.properties`, or as a `headers_` property. An open `headers` object, with no `properties`, declares every name. `Authorization`, `x-account-id` and `User-Agent` are never forwarded, even when declared, because the SDK sets them itself. Anything dropped is logged as a warning. Every other argument is sent unchanged. +**Header arguments are allowlisted.** A header argument is an entry of a `headers` object argument, or a top-level `headers_` argument. Each one is forwarded only if the tool's schema declares it in the same form: under `headers.properties`, or as a `headers_` property. An open `headers` object — `type: "object"`, no `properties`, and `additionalProperties` not `false` — declares every name; without `type: "object"`, or with `additionalProperties: false` and no `properties`, it declares none. `Authorization`, `x-account-id` and `User-Agent` are never forwarded, even when declared, because the SDK sets them itself. Anything dropped is logged as a warning. Every other argument is sent unchanged. `*_execute_action` serves an open `headers` object, so `toolset.execute()` passes your own headers on to the action, with the exception of those three: diff --git a/README.md b/README.md index 68b911b0..836a1876 100644 --- a/README.md +++ b/README.md @@ -394,7 +394,7 @@ The catalog is cached per account scope and mode, so changing a filter never ref ### Headers -A tool call's header arguments — the entries of a `headers` object argument, and `headers_` arguments — are forwarded only if the tool's served schema declares them: `` under `properties.headers.properties`, or a `headers_` property. A `headers` property served as an object with no `properties`, as on every `*_execute_action`, declares any name, so `toolset.execute(id, { headers: { 'x-custom': '…' } })` forwards it. Anything undeclared is dropped with a warning; every other argument is sent unchanged. +A tool call's header arguments — the entries of a `headers` object argument, and `headers_` arguments — are forwarded only if the tool's served schema declares them: `` under `properties.headers.properties`, or a `headers_` property. A `headers` property served as an open object — `type: "object"`, no `properties`, and `additionalProperties` not `false` — as on every `*_execute_action`, declares any name, so `toolset.execute(id, { headers: { 'x-custom': '…' } })` forwards it. Anything undeclared is dropped with a warning; every other argument is sent unchanged. `Authorization`, `x-account-id` and `User-Agent` are always the SDK's own: they are dropped from header arguments even when declared, and ignored with a warning in the `headers` constructor option, so nothing can replace the credential or run a call against another account. diff --git a/src/headers.test.ts b/src/headers.test.ts index 1e1b8ce4..da10da77 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -97,6 +97,29 @@ describe('declaredHeaders', () => { expect(declaredHeaders({ headers: { type: 'object' } }).nested).toBe('any'); }); + it('treats an open object schema with additionalProperties as declaring every name', () => { + expect( + declaredHeaders({ headers: { type: 'object', additionalProperties: true } }).nested, + ).toBe('any'); + expect( + declaredHeaders({ + headers: { type: 'object', additionalProperties: { type: 'string' } }, + }).nested, + ).toBe('any'); + }); + + it('treats additionalProperties: false with no properties as declaring nothing', () => { + expect( + declaredHeaders({ headers: { type: 'object', additionalProperties: false } }).nested, + ).toEqual(new Set()); + }); + + it('treats a headers schema without type: "object" as declaring nothing', () => { + expect(declaredHeaders({ headers: {} }).nested).toEqual(new Set()); + expect(declaredHeaders({ headers: { additionalProperties: true } }).nested).toEqual(new Set()); + expect(declaredHeaders({ headers: { type: 'string' } }).nested).toEqual(new Set()); + }); + it('treats empty properties as declaring nothing', () => { expect(declaredHeaders({ headers: { type: 'object', properties: {} } }).nested).toEqual( new Set(), diff --git a/src/headers.ts b/src/headers.ts index 8468e935..561246ac 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -104,7 +104,9 @@ const FLAT_HEADER_PREFIX = 'headers_'; export interface DeclaredHeaders { /** * Names declared under the nested `headers` object, lower-cased, or `'any'` when `headers` is - * an object schema with no `properties` — an open map, as on `*_execute_action`. + * an open map, as on `*_execute_action`: `type: "object"`, no `properties` key, and + * `additionalProperties` anything but `false`. A schema without `type: "object"`, or one that + * closes `additionalProperties` without listing `properties`, declares no names. */ nested: ReadonlySet | 'any'; /** The top-level `headers_` properties, exactly as served. */ @@ -121,7 +123,8 @@ export function declaredHeaders(properties: Record): DeclaredHe return { nested: new Set(), flat }; } if (!('properties' in schema)) { - return { nested: schema.type === 'object' ? 'any' : new Set(), flat }; + const open = schema.type === 'object' && schema.additionalProperties !== false; + return { nested: open ? 'any' : new Set(), flat }; } const nestedProperties = isPlainObject(schema.properties) ? schema.properties : {}; return { nested: new Set(Object.keys(nestedProperties).map((name) => name.toLowerCase())), flat }; From bb220e0313630ffffdda0e4d783550e56d634e4c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:42:11 +0100 Subject: [PATCH 032/151] fix(examples): print a non-numeric similarity score without throwing --- examples/search-and-execute.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/search-and-execute.ts b/examples/search-and-execute.ts index 82878c9e..0b074edd 100644 --- a/examples/search-and-execute.ts +++ b/examples/search-and-execute.ts @@ -38,7 +38,7 @@ const searchAndExecute = async (): Promise => { console.log('\nRanked matches:'); for (const action of actions) { - console.log(` ${(action.similarity_score ?? 0).toFixed(3)} ${action.action_id}`); + console.log(` ${Number(action.similarity_score ?? 0).toFixed(3)} ${action.action_id}`); } // input_schema is how you find out what an action accepts. Build the call from it and from From 7ec5d694012d87fe08c1802a862a215c26e22e19 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:42:11 +0100 Subject: [PATCH 033/151] ci: re-check the PR title when a draft is marked ready --- .github/workflows/check-title.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/check-title.yaml b/.github/workflows/check-title.yaml index 1801a55c..a322a4df 100644 --- a/.github/workflows/check-title.yaml +++ b/.github/workflows/check-title.yaml @@ -7,6 +7,7 @@ on: - reopened - edited - synchronize + - ready_for_review permissions: pull-requests: read From 1269d286d28655f2ffcbc424ecc96cb6641cb14d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:49:22 +0100 Subject: [PATCH 034/151] fix(tools): reject NaN and Infinity arguments instead of sending them as null --- src/tool.test.ts | 17 +++++++++++++++++ src/tool.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/tool.test.ts b/src/tool.test.ts index e617c78b..a0bf72d4 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -371,6 +371,23 @@ describe('StackOneMcpTool as an action tool', () => { await expect(actionTool().execute(input)).rejects.toThrow(message); }); + // JSON.stringify, and so the MCP client, would send each of these as null. + it.each([ + ['NaN at the top level', { amount: Number.NaN }], + ['Infinity nested in an object', { body: { name: 'Ada', score: Number.POSITIVE_INFINITY } }], + ['-Infinity nested in an array', { query: { ids: [1, Number.NEGATIVE_INFINITY] } }], + ])('rejects %s without calling the server', async (_name, args) => { + const error = await actionTool() + .execute(args as JsonObject) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneError); + expect((error as Error).message).toMatch( + /^Arguments for "crm_update_contact" could not be encoded as JSON: Out of range number values are not JSON compliant/, + ); + expect(calls).toEqual([]); + }); + it('rejects a non-object, non-string argument', async () => { // @ts-expect-error - intentionally passing an invalid type await expect(actionTool().execute(12345)).rejects.toThrow(StackOneError); diff --git a/src/tool.ts b/src/tool.ts index ab954bb0..9ec3cf1c 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -394,6 +394,7 @@ export class StackOneMcpTool extends StackOneTool { * @returns The result as the server wrote it: for an action tool, * `{ isError: false, result, defenderMetadata?, policyMetadata? }`. A file action's `result` * is the server's single-use `download_url`, not the file. + * @throws StackOneError If the arguments are not a JSON object or cannot be encoded as JSON. * @throws StackOneAPIError If the result carries `isError`, with the status from its payload, * or the endpoint answers with an HTTP error. * @throws ToolSetLoadError If the endpoint cannot be reached or does not answer in time. @@ -404,6 +405,7 @@ export class StackOneMcpTool extends StackOneTool { ): Promise { const parsed = this.parseArguments(inputParams); const args = sanitiseHeaderArguments(parsed, this.#declaredHeaders); + assertEncodable(this.name, args); if (options?.dryRun) { return { url: this.#endpoint, method: 'tools/call', name: this.name, arguments: args }; @@ -425,6 +427,31 @@ export class StackOneMcpTool extends StackOneTool { } } +/** + * Throw if `args` cannot be sent as JSON. NaN and Infinity are not JSON: `JSON.stringify`, and so + * the MCP client, would send them as null. A `bigint` or a cycle would otherwise fail deep inside + * the MCP client and surface as a transport error. Each is an argument problem. + * + * @throws StackOneError If any value, however deeply nested, cannot be encoded. + */ +function assertEncodable(toolName: string, args: JsonObject): void { + try { + JSON.stringify(args, (key, value: unknown) => { + if (typeof value === 'number' && !Number.isFinite(value)) { + throw new TypeError( + `Out of range number values are not JSON compliant: ${value}${key ? ` (at ${JSON.stringify(key)})` : ''}`, + ); + } + return value; + }); + } catch (error) { + throw new StackOneError( + `Arguments for "${toolName}" could not be encoded as JSON: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } +} + /** * A Chat Completions tool call: the `openai` package's own object, or the same shape as a plain * object (for example one read back from storage). From 111701e46c491acfb9462d41470ff2550a94f961 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:49:41 +0100 Subject: [PATCH 035/151] fix(toolsets): validate submitFeedback() sessionId as execute() does --- src/toolsets.search-execute.test.ts | 13 +++++++++++++ src/toolsets.ts | 8 +++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 6e89fa97..314834b7 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -519,6 +519,19 @@ describe('submitFeedback()', () => { ); }); + it.each([ + ['an empty string', ''], + ['a number', 42], + ])('rejects %s as sessionId, as execute() does, before any round trip', async (_name, bad) => { + const error = await newToolSet({ accountId: 'acc1' }) + .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/); + expect(listMock).not.toHaveBeenCalled(); + }); + it('links search, execute and feedback with one session id', async () => { const { calls } = serveMock({ submitFeedback: true }); const toolset = newToolSet(); diff --git a/src/toolsets.ts b/src/toolsets.ts index e55a4040..25c85bb2 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -885,7 +885,8 @@ export class StackOneToolSet { * }); * ``` * - * @throws ToolSetConfigError If `toolNames` is not a list, or `accountIds` holds an empty id. + * @throws ToolSetConfigError If `toolNames` is not a list, `sessionId` is empty or not a string, + * or `accountIds` holds an empty id. * @throws ToolSetLoadError If feedback is not enabled for this project. */ async submitFeedback(options: SubmitFeedbackOptions): Promise { @@ -898,6 +899,11 @@ export class StackOneToolSet { if (!Array.isArray(toolNames)) { throw new ToolSetConfigError('toolNames must be an array of tool names'); } + if (sessionId !== undefined && (typeof sessionId !== 'string' || !sessionId)) { + throw new ToolSetConfigError( + `sessionId must be a non-empty string, got ${JSON.stringify(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 first account, in the From 95c3cb3c3849df11b31dfae015fc230a1d1dd7a0 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:50:51 +0100 Subject: [PATCH 036/151] test: dispatch mock meta tools only in search_execute mode --- mocks/handlers.mcp.ts | 2 ++ mocks/mcp-server.ts | 13 ++++++++++++- src/toolsets.test.ts | 15 +++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/mocks/handlers.mcp.ts b/mocks/handlers.mcp.ts index 7ccf8b6f..d6a002e7 100644 --- a/mocks/handlers.mcp.ts +++ b/mocks/handlers.mcp.ts @@ -5,6 +5,7 @@ import { createMcpApp, defaultMcpTools, exampleBamboohrTools, + metaLookalikeTools, mixedProviderTools, } from './mcp-server'; @@ -16,6 +17,7 @@ export const mockAccountTools = { acc3: accountMcpTools.acc3, 'test-account': accountMcpTools['test-account'], mixed: mixedProviderTools, + lookalike: metaLookalikeTools, // For examples testing 'your-bamboohr-account-id': exampleBamboohrTools, 'your-stackone-account-id': exampleBamboohrTools, diff --git a/mocks/mcp-server.ts b/mocks/mcp-server.ts index d02aa056..0c679879 100644 --- a/mocks/mcp-server.ts +++ b/mocks/mcp-server.ts @@ -236,8 +236,10 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { }); } // 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 + // name ends in `_execute_action` is still an action. return ( - callMetaTool(name, args) ?? + (toolMode === 'search_execute' ? callMetaTool(name, args) : undefined) ?? wrapped({ data: { action: name, account_id: accountId, arguments: args } }) ); }); @@ -386,6 +388,15 @@ export const exampleBamboohrTools = [ }, ] as const satisfies McpToolDefinition[]; +/** A per-action tool whose name ends like a meta tool's, served in individual mode. */ +export const metaLookalikeTools = [ + { + name: 'lookalike_execute_action', + description: 'An action named like a meta tool', + inputSchema: { type: 'object', properties: { action_id: { type: 'string' } } }, + }, +] as const satisfies McpToolDefinition[]; + export const mixedProviderTools = [ { name: 'hibob_list_employees', diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 774dca19..2f94291a 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -777,6 +777,21 @@ describe('execution through fetched tools', () => { }, }); }); + + it('runs an action named like a meta tool as an action outside search_execute', async () => { + const tools = await newToolSet({ accountId: 'lookalike' }).fetchTools(); + const result = await tools.getTool('lookalike_execute_action')?.execute({ action_id: 'other' }); + expect(result).toEqual({ + isError: false, + result: { + data: { + action: 'lookalike_execute_action', + account_id: 'lookalike', + arguments: { action_id: 'other' }, + }, + }, + }); + }); }); describe('model-supplied headers', () => { From aefce4785596c721d09218e5670fe9c46a02db17 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:51:48 +0100 Subject: [PATCH 037/151] docs: match the README and migration guide to what the code does --- MIGRATION.md | 12 +++++++----- README.md | 2 ++ src/toolsets.ts | 1 + 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index d3f1aea6..a9c71bf3 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -87,6 +87,7 @@ const names = await toolset.searchActionNames('time off requests', { topK: 5 }); // 3.0 const toolset = new StackOneToolSet(); const [hit] = await toolset.search('list employees', { topK: 5 }); // SearchResult[], best first +if (!hit) throw new Error('No action matched'); const result = await toolset.execute( hit.action_id, { query: { page_size: 25 } }, // the nested form hit.input_schema describes @@ -94,7 +95,7 @@ const result = await toolset.execute( ); ``` -`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id`, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `execute()` raises rather than returning `{ error }`: `ToolSetLoadError` when no linked connector serves the action, `StackOneAPIError` when the action fails. +`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id`, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `execute()` raises rather than returning `{ error }`: `ToolSetConfigError` before any request when `actionId`, `args` or `sessionId` is malformed, `StackOneError` when the arguments cannot be encoded as JSON (NaN or Infinity, for example), `ToolSetLoadError` when no linked connector serves the action, and `StackOneAPIError` when the action fails, including when the server rejects the arguments. To give a model the search and execute tools, set the tool mode on the toolset. `openai()` no longer takes `mode`. @@ -153,7 +154,7 @@ await tool.execute({ id: '1' }, { dryRun: true }); ## Tool arguments and headers -**Arguments are sent exactly as given**, as `tools/call` arguments. The SDK no longer splits flat `path_` / `query_` / `body_` keys into an `/actions/rpc` envelope; the server maps them itself. +**Arguments are sent as given**, as `tools/call` arguments, except header arguments: each is forwarded only if the tool's schema declares it, and `Authorization`, `x-account-id` and `User-Agent` never are (see below). The SDK no longer splits flat `path_` / `query_` / `body_` keys into an `/actions/rpc` envelope; the server maps them itself. **`fetchTools()` tools have the server's own argument shape.** 2.x asked the server for the flat, prefixed style (`?param-style=flat_prefixed`). That request is gone, so the argument names are whatever the server serves for your project. Read them from `tool.parameters.properties` rather than hard-coding them: @@ -197,6 +198,7 @@ await feedbackTool.execute({ // 3.0 const [hit] = await toolset.search('list workers'); +if (!hit) throw new Error('No action matched'); await toolset.execute(hit.action_id, {}, { sessionId: hit.session_id }); await toolset.submitFeedback({ rating: 'positive', @@ -288,12 +290,12 @@ const tool = new GetEmployee( **Tools no longer carry headers.** The `headers` constructor argument, `getHeaders()` and `setHeaders()` are removed from `BaseTool`, and `ToolExecution` — the `execution` metadata `toAISDK()` can attach — no longer has `headers`, so it cannot leak the credential. `StackOneTool`'s fifth constructor argument is now the account id; use `getAccountId()` / `setAccountId()` to read or rebind it. -**`BaseTool#connector` and `Tools#getConnectors()` are removed.** Take the provider from the tool name, or filter with `fetchTools({ providers })`: +**`BaseTool#connector` and `Tools#getConnectors()` are removed.** Filter by provider with `fetchTools({ providers })`. A provider name can contain `_` (`browser_linkedin`), so do not split the tool name to find it: ```typescript // 2.x -const connectors = tools.getConnectors(); +const hibobTools = tools.toArray().filter((tool) => tool.connector === 'hibob'); // 3.0 -const connectors = new Set(tools.map((tool) => tool.name.split('_')[0])); +const hibobTools = await toolset.fetchTools({ providers: ['hibob'] }); ``` diff --git a/README.md b/README.md index 836a1876..fc286152 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ const toolset = new StackOneToolSet(); // Find an action, then run it by id const [best] = await toolset.search('list recent comments', { topK: 3 }); +if (!best) throw new Error('No action matched'); const result = await toolset.execute(best.action_id, { query: { limit: 5 } }); // Or list the catalog as tools for your framework @@ -298,6 +299,7 @@ for (const action of actions) { } const [best] = actions; +if (!best) throw new Error('No action matched'); // `input_schema` describes what the action accepts; `example_request` shows the shape const result = await toolset.execute(best.action_id, best.example_request, { sessionId: best.session_id, diff --git a/src/toolsets.ts b/src/toolsets.ts index 25c85bb2..16e26a4c 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -877,6 +877,7 @@ export class StackOneToolSet { * @example * ```typescript * const [hit] = await toolset.search('list recent comments'); + * if (!hit) throw new Error('No action matched'); * await toolset.execute(hit.action_id, {}, { sessionId: hit.session_id }); * await toolset.submitFeedback({ * rating: 'positive', From 64b3fe86f12ffb847c4cdffc3334861010533d0a Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 09:53:12 +0100 Subject: [PATCH 038/151] ci: pin sdk-conformance to 6a6991d --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ad9437ee..2380cf2c 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 9b5605a520150c55724fdf9236871bc95e52b0cb + ref: 6a6991dd2d65c211b55902e9243627f817c97543 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From f9532815c40f800dbd2b041c1c8dfc96a9a21892 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 10:01:18 +0100 Subject: [PATCH 039/151] fix(toolsets): reject an empty accountId instead of widening to every account --- src/toolsets.test.ts | 6 ++++++ src/toolsets.ts | 7 ++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 2f94291a..393ca965 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -102,6 +102,12 @@ describe('configuration', () => { await expect(async () => act()).rejects.toThrow(/must not contain an empty account id/); }); + it('refuses an empty accountId rather than widening to every account', () => { + expect(() => newToolSet({ accountId: '' })).toThrow( + new ToolSetConfigError('accountId must not be an empty string'), + ); + }); + it('returns itself from setAccounts for chaining', () => { const toolset = newToolSet(); expect(toolset.setAccounts(['acc1'])).toBe(toolset); diff --git a/src/toolsets.ts b/src/toolsets.ts index 16e26a4c..5fda0bf9 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -325,7 +325,7 @@ export class StackOneToolSet { /** * @throws ToolSetConfigError If no API key is given or found in `STACKONE_API_KEY`, or both - * `accountId` and `accountIds` are given. + * `accountId` and `accountIds` are given, or `accountId` is an empty string. */ constructor(config: StackOneToolSetConfig = {}) { if (config.accountId != null && config.accountIds != null) { @@ -333,6 +333,11 @@ export class StackOneToolSet { '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 all active accounts. + if (config.accountId === '') { + throw new ToolSetConfigError('accountId must not be an empty string'); + } assertAccountIdList(config.accountIds, 'accountIds'); assertAccountIdList(config.execute?.accountIds, 'execute.accountIds'); From faeed0b746f46312bb4d6bccbadd788e3c391530 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 10:59:18 +0100 Subject: [PATCH 040/151] refactor(toolsets): stop reading STACKONE_ACCOUNT_ID Match the Python SDK (stackone-ai-python#23): the account id must be passed as accountId/accountIds, and STACKONE_API_KEY stays the only credential read from the environment. In 3.0 an unset account means every active account, so an environment variable silently setting it changed a toolset's scope without the code saying so. The README and examples now read STACKONE_ACCOUNT_ID themselves and pass it as accountId; unset, it is undefined and the toolset discovers the key's accounts. MIGRATION.md shows the before and after. BREAKING CHANGE: STACKONE_ACCOUNT_ID is no longer read. Pass the account id as accountId or accountIds; without one, the toolset discovers every active account linked to the API key. --- .env.example | 3 ++- MIGRATION.md | 10 +++++++++ README.md | 26 +++++++++++------------ examples/README.md | 4 ++-- examples/ai-sdk-integration.ts | 5 +++-- examples/anthropic-integration.ts | 5 +++-- examples/auth-management.ts | 10 +++++---- examples/claude-agent-sdk-integration.ts | 5 +++-- examples/openai-integration.ts | 5 +++-- examples/openai-responses-integration.ts | 5 +++-- src/toolsets.search-execute.test.ts | 1 - src/toolsets.test.ts | 11 +++++++--- src/toolsets.ts | 8 +++++-- tests/examples/search-and-execute.test.ts | 1 - 14 files changed, 62 insertions(+), 37 deletions(-) diff --git a/.env.example b/.env.example index 5c5cac42..2c43b8c9 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,8 @@ # Required for all examples STACKONE_API_KEY=your-stackone-api-key -# Optional: without it, the SDK uses every active account linked to the API key +# Optional: the examples read this and pass it as accountId (the SDK itself never reads it). +# Without it, the SDK uses every active account linked to the API key STACKONE_ACCOUNT_ID=your-account-id # Required for OpenAI examples (openai-integration, openai-responses-integration, ai-sdk-integration) diff --git a/MIGRATION.md b/MIGRATION.md index a9c71bf3..26397a89 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -179,6 +179,16 @@ await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' **With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active account. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. +**`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: + +```typescript +// 2.x: STACKONE_ACCOUNT_ID picked up implicitly +const toolset = new StackOneToolSet(); + +// 3.0 +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); +``` + **Listings are merged in sorted account order.** When two accounts serve the same tool name, `getTool()` returns the first one listed — now the one on the lowest account id, where 2.x followed the order you passed. A warning names the clashing tools. Pass `accountIds` to choose the account yourself. **`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. An account whose listing fails is skipped with a warning, unless every account fails. diff --git a/README.md b/README.md index fc286152..0642f93b 100644 --- a/README.md +++ b/README.md @@ -77,13 +77,13 @@ for (const account of await toolset.fetchAccounts()) { ### Account IDs -StackOne uses account IDs to identify different integrations. You can specify the account ID at different levels (a per-call `accountIds` wins, then `setAccounts()`, then the constructor's `accountIds`, then `accountId` or `STACKONE_ACCOUNT_ID`, then discovery): +StackOne uses account IDs to identify different integrations. You can specify the account ID at different levels (a per-call `accountIds` wins, then `setAccounts()`, then the constructor's `accountIds`, then `accountId`, then discovery). The SDK never reads an account id from the environment, so an environment variable cannot silently change which accounts a toolset reaches. To keep yours in `STACKONE_ACCOUNT_ID`, read it yourself: ```typescript import { StackOneToolSet } from '@stackone/ai'; -// Simplest: set STACKONE_ACCOUNT_ID environment variable -const toolset = new StackOneToolSet(); +// Single account, read from your own environment variable. Unset means discovery +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); const tools = await toolset.fetchTools(); // Explicit single account @@ -125,8 +125,8 @@ npm install @stackone/ai openai # or: yarn/pnpm/bun add import { OpenAI } from 'openai'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment -const toolset = new StackOneToolSet(); +// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); const tools = await toolset.fetchTools({ actions: ['workday_*'] }); const openai = new OpenAI(); @@ -163,8 +163,8 @@ npm install @stackone/ai openai # or: yarn/pnpm/bun add import OpenAI from 'openai'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment -const toolset = new StackOneToolSet(); +// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); const tools = await toolset.fetchTools(); @@ -193,8 +193,8 @@ npm install @stackone/ai @anthropic-ai/sdk # or: yarn/pnpm/bun add import Anthropic from '@anthropic-ai/sdk'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment -const toolset = new StackOneToolSet(); +// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); const tools = await toolset.fetchTools(); @@ -232,8 +232,8 @@ import { openai } from '@ai-sdk/openai'; import { generateText, stepCountIs } from 'ai'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment -const toolset = new StackOneToolSet(); +// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); const tools = await toolset.fetchTools(); @@ -259,8 +259,8 @@ npm install @stackone/ai @anthropic-ai/claude-agent-sdk zod # or: yarn/pnpm/bun import { query } from '@anthropic-ai/claude-agent-sdk'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment -const toolset = new StackOneToolSet(); +// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); // Fetch tools and convert to Claude Agent SDK format const tools = await toolset.fetchTools(); diff --git a/examples/README.md b/examples/README.md index f5755a13..e1f1d0a2 100644 --- a/examples/README.md +++ b/examples/README.md @@ -16,7 +16,7 @@ Set your credentials using either approach: ```bash export STACKONE_API_KEY=your-stackone-api-key -export STACKONE_ACCOUNT_ID=your-account-id # optional: accounts are discovered otherwise +export STACKONE_ACCOUNT_ID=your-account-id # optional: the examples pass it as accountId export OPENAI_API_KEY=your-openai-api-key # for OpenAI/AI SDK examples export ANTHROPIC_API_KEY=your-anthropic-api-key # for Anthropic examples ``` @@ -79,6 +79,6 @@ Walks through every way to configure API keys and account IDs: reading from envi | Variable | Required | Used By | | --------------------- | ---------------------------- | ----------------------------------------------------------------------------------- | | `STACKONE_API_KEY` | Yes | All examples | -| `STACKONE_ACCOUNT_ID` | Optional | All examples (read automatically; without it, accounts are discovered from the key) | +| `STACKONE_ACCOUNT_ID` | Optional | Read by the examples and passed as `accountId`; without it, accounts are discovered | | `OPENAI_API_KEY` | For OpenAI / AI SDK examples | `openai-integration.ts`, `openai-responses-integration.ts`, `ai-sdk-integration.ts` | | `ANTHROPIC_API_KEY` | For Anthropic examples | `anthropic-integration.ts`, `claude-agent-sdk-integration.ts` | diff --git a/examples/ai-sdk-integration.ts b/examples/ai-sdk-integration.ts index 86f0209a..c5cb08d4 100644 --- a/examples/ai-sdk-integration.ts +++ b/examples/ai-sdk-integration.ts @@ -28,8 +28,9 @@ if (!process.env.OPENAI_API_KEY) { } const aiSdkIntegration = async (): Promise => { - // Initialize StackOne — reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from env - const toolset = new StackOneToolSet(); + // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; + // without one, the toolset uses every active account linked to the key + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); // Filter to specific tools to keep token usage manageable const tools = await toolset.fetchTools({ diff --git a/examples/anthropic-integration.ts b/examples/anthropic-integration.ts index b7be566e..cb0d327f 100644 --- a/examples/anthropic-integration.ts +++ b/examples/anthropic-integration.ts @@ -17,8 +17,9 @@ if (!process.env.ANTHROPIC_API_KEY) { } const anthropicIntegration = async (): Promise => { - // Initialize StackOne — reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from env - const toolset = new StackOneToolSet(); + // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; + // without one, the toolset uses every active account linked to the key + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); // Filter for any relevant tools const tools = await toolset.fetchTools({ diff --git a/examples/auth-management.ts b/examples/auth-management.ts index 7857fc6b..8e7804be 100644 --- a/examples/auth-management.ts +++ b/examples/auth-management.ts @@ -6,7 +6,8 @@ * Run with: * STACKONE_API_KEY=xxx npx tsx examples/auth-management.ts * - * STACKONE_ACCOUNT_ID is optional: without it, accounts are discovered from the API key. + * STACKONE_ACCOUNT_ID is optional, and only read by this example: the SDK never reads it. Without + * it, accounts are discovered from the API key. */ import process from 'node:process'; @@ -21,7 +22,7 @@ if (!process.env.STACKONE_API_KEY) { const apiKeyFromEnv = async (): Promise => { console.log('=== 1a. API Key from environment ===\n'); - // Reads STACKONE_API_KEY (and STACKONE_ACCOUNT_ID, if set) from env automatically + // Reads STACKONE_API_KEY from env automatically. No account is configured, so it discovers them const toolset = new StackOneToolSet(); const tools = await toolset.fetchTools(); console.log(` Loaded ${tools.toOpenAI().length} tools using env API key\n`); @@ -51,11 +52,12 @@ const apiKeyAlone = async (): Promise => { const accountIdFromEnv = async (): Promise => { console.log('=== 2. Account ID from environment ===\n'); - // The Node SDK reads STACKONE_ACCOUNT_ID from env automatically + // The SDK only reads the API key from env; read the account id yourself and pass it. + // Unset, it is undefined and the toolset discovers every active account instead. const accountId = process.env.STACKONE_ACCOUNT_ID; console.log(` STACKONE_ACCOUNT_ID is ${accountId ? 'set' : 'not set'}`); - const toolset = new StackOneToolSet(); + const toolset = new StackOneToolSet({ accountId }); const tools = await toolset.fetchTools(); console.log(` Loaded ${tools.toOpenAI().length} tools for account from env\n`); }; diff --git a/examples/claude-agent-sdk-integration.ts b/examples/claude-agent-sdk-integration.ts index 5012d8d7..1ebe6760 100644 --- a/examples/claude-agent-sdk-integration.ts +++ b/examples/claude-agent-sdk-integration.ts @@ -23,8 +23,9 @@ if (!process.env.ANTHROPIC_API_KEY) { } const claudeAgentSdkIntegration = async (): Promise => { - // Initialize StackOne — reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from env - const toolset = new StackOneToolSet(); + // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; + // without one, the toolset uses every active account linked to the key + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); // Fetch tools from StackOne and convert to Claude Agent SDK format const tools = await toolset.fetchTools(); diff --git a/examples/openai-integration.ts b/examples/openai-integration.ts index df81218b..c3587f07 100644 --- a/examples/openai-integration.ts +++ b/examples/openai-integration.ts @@ -17,8 +17,9 @@ if (!process.env.OPENAI_API_KEY) { } const openaiIntegration = async (): Promise => { - // Initialize StackOne — reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from env - const toolset = new StackOneToolSet(); + // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; + // without one, the toolset uses every active account linked to the key + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); // Filter to specific tools to stay within OpenAI's 128-tool limit const tools = await toolset.fetchTools({ diff --git a/examples/openai-responses-integration.ts b/examples/openai-responses-integration.ts index 0d55fe79..0af168a6 100644 --- a/examples/openai-responses-integration.ts +++ b/examples/openai-responses-integration.ts @@ -17,8 +17,9 @@ if (!process.env.OPENAI_API_KEY) { } const openaiResponsesIntegration = async (): Promise => { - // Initialize StackOne — reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from env - const toolset = new StackOneToolSet(); + // Initialize StackOne — reads STACKONE_API_KEY from env. The account id is passed explicitly; + // without one, the toolset uses every active account linked to the key + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); // Fetch tools via MCP const tools = await toolset.fetchTools({ diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 314834b7..1afb48c9 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -32,7 +32,6 @@ const newToolSet = (config: ConstructorParameters[0] = { let warnSpy: ReturnType; beforeEach(() => { - vi.stubEnv('STACKONE_ACCOUNT_ID', ''); warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 393ca965..5268b7f3 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -48,7 +48,6 @@ const names = (tools: { toArray(): Array<{ name: string }> }) => let warnSpy: ReturnType; beforeEach(() => { - vi.stubEnv('STACKONE_ACCOUNT_ID', ''); warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { @@ -74,9 +73,15 @@ describe('configuration', () => { expect(tools.length).toBe(2); }); - it('reads the account from STACKONE_ACCOUNT_ID', async () => { + it('ignores STACKONE_ACCOUNT_ID, so the environment cannot change the account scope', async () => { vi.stubEnv('STACKONE_ACCOUNT_ID', 'acc3'); - expect(names(await newToolSet().fetchTools())).toEqual(['acc3_tool_1']); + + expect(names(await newToolSet().fetchTools())).toEqual(['default_tool_1', 'default_tool_2']); + expect(names(await newToolSet({ accountId: 'acc1' }).fetchTools())).toEqual([ + 'acc1_tool_1', + 'acc1_tool_2', + ]); + expect(listMock.mock.calls.map(([request]) => accountOf(request))).toEqual(['default', 'acc1']); }); it('refuses both accountId and accountIds', () => { diff --git a/src/toolsets.ts b/src/toolsets.ts index 5fda0bf9..b1277ff2 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -31,7 +31,8 @@ import { warn } from './utils/logger'; interface SingleAccountConfig { /** * Single account ID for StackOne API operations - * Use this when working with a single account + * Use this when working with a single account. Never read from the environment: with no + * account configured, the toolset uses every active account linked to the API key. */ accountId: string; } @@ -324,6 +325,9 @@ export class StackOneToolSet { #cacheGeneration = 0; /** + * Falls back to `STACKONE_API_KEY` and `STACKONE_BASE_URL`, but never reads an account id from + * the environment: `accountId` / `accountIds` must be passed, or every active account is used. + * * @throws ToolSetConfigError If no API key is given or found in `STACKONE_API_KEY`, or both * `accountId` and `accountIds` are given, or `accountId` is an empty string. */ @@ -360,7 +364,7 @@ export class StackOneToolSet { this.#headers = { ...config.headers }; this.#timeout = config.timeout ?? config.execute?.timeout ?? DEFAULT_TIMEOUT_MS; this.#toolMode = config.toolMode; - this.#accountId = config.accountId || process.env.STACKONE_ACCOUNT_ID || undefined; + this.#accountId = config.accountId; this.#accountIds = [...(config.accountIds ?? config.execute?.accountIds ?? [])]; } diff --git a/tests/examples/search-and-execute.test.ts b/tests/examples/search-and-execute.test.ts index 612d14ce..ade5a5e7 100644 --- a/tests/examples/search-and-execute.test.ts +++ b/tests/examples/search-and-execute.test.ts @@ -19,7 +19,6 @@ import { StackOneToolSet, ToolSetLoadError } from '../../src'; describe('search-and-execute example e2e', () => { beforeEach(() => { vi.stubEnv('STACKONE_API_KEY', 'test-key'); - vi.stubEnv('STACKONE_ACCOUNT_ID', ''); vi.stubEnv('STACKONE_BASE_URL', TEST_BASE_URL); }); From 460f49524c02ddf4052d6ed855add89e9d06e1f6 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 11:30:51 +0100 Subject: [PATCH 041/151] feat: retry HTTP 429 responses and fail fan-outs on a persistent 429 Every request (GET /accounts and every MCP request, through the transport's fetch) is retried up to 3 times on 429, waiting for Retry-After (capped at 30s) or 1s/2s/4s with jitter. A 429 that outlasts the retries throws StackOneAPIError 429 and rejects a multi-account fetchTools() or search() instead of being skipped, and no further account is started. --- src/consts.ts | 9 ++ src/mcp-client.ts | 19 +++ src/rate-limit.test.ts | 266 ++++++++++++++++++++++++++++++++++ src/toolsets.ts | 42 +++++- src/utils/concurrency.test.ts | 39 +++++ src/utils/concurrency.ts | 11 +- src/utils/fetch-retry.test.ts | 207 ++++++++++++++++++++++++++ src/utils/fetch-retry.ts | 84 +++++++++++ 8 files changed, 668 insertions(+), 9 deletions(-) create mode 100644 src/rate-limit.test.ts create mode 100644 src/utils/concurrency.test.ts create mode 100644 src/utils/fetch-retry.test.ts create mode 100644 src/utils/fetch-retry.ts diff --git a/src/consts.ts b/src/consts.ts index cfa2294c..d9041cd7 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -25,3 +25,12 @@ export const MAX_CONCURRENCY = 10; /** The `*_search_actions` meta tool's served schema caps `top_k` at 50. */ export const MAX_TOP_K = 50; + +/** Retries after an HTTP 429, on top of the first attempt: four attempts in all. */ +export const RATE_LIMIT_MAX_RETRIES = 3; + +/** Backoff before retry 1 when the 429 carries no `Retry-After`; doubled for each retry after. */ +export const RATE_LIMIT_BASE_DELAY_MS = 1_000; + +/** Upper bound on a server-requested `Retry-After` wait. */ +export const RATE_LIMIT_MAX_DELAY_MS = 30_000; diff --git a/src/mcp-client.ts b/src/mcp-client.ts index 86062acc..f5d92d35 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -10,6 +10,7 @@ import type { JsonObject } from './types'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { ToolSetLoadError } from './utils/error-toolset'; +import { fetchWithRetry } from './utils/fetch-retry'; /** A tool exactly as the MCP server listed it. */ export interface McpToolDefinition { @@ -90,6 +91,21 @@ export function describeMcpFailure(error: unknown, endpoint: string, timeout: nu }); } +/** + * Whether an MCP request was still rate limited after its retries: an HTTP 429 from the endpoint. + * + * Unlike a dead account, this says nothing about one account and everything about the API key, + * so a fan-out must fail on it rather than skip the account and return a partial catalog. A + * `tools/call` result whose payload reports 429 is not this: the request itself was served. + */ +export function isRateLimitFailure(error: unknown): boolean { + return ( + error instanceof StackOneAPIError && + error.statusCode === 429 && + error.cause instanceof StreamableHTTPError + ); +} + /** * Open an MCP session, run `work` in it and close it, all within one deadline. * @@ -104,6 +120,9 @@ async function withMcpSession( ): Promise { const transport = new StreamableHTTPClientTransport(new URL(endpoint), { requestInit: { headers }, + // Every request the client sends, handshake included, so it never sees a 429 it could + // have waited out. + fetch: (url, init) => fetchWithRetry(url, init), }); const client = new Client({ name: 'stackone-ai-node', version }); let timer: ReturnType | undefined; diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts new file mode 100644 index 00000000..d095cd2b --- /dev/null +++ b/src/rate-limit.test.ts @@ -0,0 +1,266 @@ +/** + * HTTP 429 end to end: every request the toolset makes is retried, and a 429 that outlasts its + * retries fails the whole call rather than costing one account. The retry timing itself is + * covered in utils/fetch-retry.test.ts; here every 429 carries `Retry-After: 0`, so nothing waits. + */ +import { 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 { server } from '../mocks/node'; +import { StackOneToolSet } from './toolsets'; +import { StackOneAPIError } from './utils/error-stackone-api'; + +const newToolSet = (config: ConstructorParameters[0] = {}) => + new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); + +const RATE_LIMITED = { message: 'Too many requests' }; + +let warnSpy: ReturnType; +beforeEach(() => { + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +const warnings = (): string[] => warnSpy.mock.calls.map(([message]: unknown[]) => String(message)); +const retryWarnings = (): string[] => warnings().filter((message) => message.includes('(429)')); + +interface Throttle { + /** Answer 429 to the first `times` requests this matches. Default: every one. */ + times?: number; + method?: string; + accountId?: string; +} + +/** + * 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 + * that reached the app. + */ +const serveThrottled = (throttle: Throttle) => { + const attempts = { matched: 0 }; + const calls: RecordedToolCall[] = []; + const app = createMcpApp({ + accountTools: accountMcpTools, + onToolCall: (call) => calls.push(call), + }); + server.use( + http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { + const accountId = request.headers.get('x-account-id') ?? undefined; + 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); + if (matches && attempts.matched++ < (throttle.times ?? Number.POSITIVE_INFINITY)) { + return HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '0' } }); + } + return app.fetch(request); + }), + ); + return { attempts, calls }; +}; + +describe('a 429 that clears on retry', () => { + it('retries the MCP handshake', async () => { + const { attempts } = serveThrottled({ method: 'initialize', times: 1 }); + + const tools = await newToolSet().fetchTools({ accountIds: ['acc1'] }); + + expect(tools.length).toBe(accountMcpTools.acc1.length); + expect(attempts.matched).toBe(2); + }); + + it('retries a listing', async () => { + const { attempts } = serveThrottled({ method: 'tools/list', times: 1 }); + + const tools = await newToolSet().fetchTools({ accountIds: ['acc1'] }); + + expect(tools.length).toBe(accountMcpTools.acc1.length); + expect(attempts.matched).toBe(2); + expect(retryWarnings()).toEqual([ + expect.stringMatching( + new RegExp( + `^\\[@stackone/ai\\] Rate limited \\(429\\) by POST ${TEST_BASE_URL}/mcp; retrying in 0ms \\(attempt 2 of 4\\)$`, + ), + ), + ]); + }); + + it('retries a tools/call, which reaches the server once', async () => { + const { attempts, calls } = serveThrottled({ method: 'tools/call', times: 1 }); + const tool = (await newToolSet().fetchTools({ accountIds: ['acc1'] })).getTool('acc1_tool_1'); + + const result = await tool?.execute({ fields: 'name' }); + + expect(result).toMatchObject({ isError: false, result: { data: { action: 'acc1_tool_1' } } }); + expect(attempts.matched).toBe(2); + expect(calls).toHaveLength(1); + }); + + it('retries GET /accounts', async () => { + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + requests++ === 0 + ? HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '0' } }) + : HttpResponse.json(mockAccounts), + ), + ); + + expect(await newToolSet().fetchAccounts()).toEqual(mockAccounts); + expect(requests).toBe(2); + expect(retryWarnings()).toEqual([ + expect.stringContaining(`by GET ${TEST_BASE_URL}/accounts; retrying in 0ms (attempt 2 of 4)`), + ]); + }); +}); + +describe('a 429 that outlasts its retries', () => { + const expectRateLimited = (error: unknown) => { + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + expect((error as StackOneAPIError).responseBody).toEqual(RATE_LIMITED); + }; + + it('throws a 429 StackOneAPIError from GET /accounts after exactly 4 attempts', async () => { + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + requests++; + return HttpResponse.text('slow down', { status: 429, headers: { 'Retry-After': '0' } }); + }), + ); + + const error = await newToolSet() + .fetchAccounts() + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + expect((error as StackOneAPIError).responseBody).toBe('slow down'); + expect(requests).toBe(4); + expect(retryWarnings()).toHaveLength(3); + }); + + it('throws a 429 StackOneAPIError from a listing after exactly 4 attempts', async () => { + const { attempts } = serveThrottled({ method: 'tools/list' }); + + const error = await newToolSet() + .fetchTools({ accountIds: ['acc1'] }) + .catch((caught: unknown) => caught); + + expectRateLimited(error); + expect(attempts.matched).toBe(4); + expect(retryWarnings().map((message) => message.match(/attempt \d of 4/)?.[0])).toEqual([ + 'attempt 2 of 4', + 'attempt 3 of 4', + 'attempt 4 of 4', + ]); + }); + + it('throws a 429 StackOneAPIError from a tools/call after exactly 4 attempts', async () => { + const { attempts, calls } = serveThrottled({ method: 'tools/call' }); + const tool = (await newToolSet().fetchTools({ accountIds: ['acc1'] })).getTool('acc1_tool_1'); + + const error = await tool?.execute({ fields: 'name' }).catch((caught: unknown) => caught); + + expectRateLimited(error); + expect(attempts.matched).toBe(4); + expect(calls).toHaveLength(0); + }); + + it('fails a multi-account listing instead of returning the other accounts', async () => { + serveThrottled({ method: 'tools/list', accountId: 'acc2' }); + + const error = await newToolSet() + .fetchTools({ accountIds: ['acc1', 'acc2', 'dead'] }) + .catch((caught: unknown) => caught); + + expectRateLimited(error); + expect(warnings().filter((message) => message.includes('Skipping'))).toEqual([]); + }); + + it('still skips an account that fails any other way', async () => { + serveThrottled({ method: 'tools/list', times: 0 }); + + const tools = await newToolSet().fetchTools({ accountIds: ['acc1', 'dead'] }); + + expect(tools.length).toBe(accountMcpTools.acc1.length); + expect(warnings()).toEqual([ + expect.stringMatching(/Skipping account that failed to list tools — dead: .*412/), + ]); + }); + + it('fails account discovery, and the listing that needed it', async () => { + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '0' } }), + ), + ); + + const error = await newToolSet() + .fetchTools() + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + // GET /accounts keeps its error body as text. + expect((error as StackOneAPIError).responseBody).toBe(JSON.stringify(RATE_LIMITED)); + }); + + it('fails a search instead of skipping the throttled connector', async () => { + serveThrottled({ method: 'tools/call', accountId: 'acc2' }); + + const error = await newToolSet() + .search('list items', { accountIds: ['acc1', 'acc2'] }) + .catch((caught: unknown) => caught); + + expectRateLimited(error); + expect(warnings().filter((message) => message.includes('Skipping'))).toEqual([]); + }); +}); + +describe('other statuses', () => { + it.each([400, 500])('does not retry a %i', async (status) => { + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + requests++; + return HttpResponse.json({ message: 'no' }, { status, headers: { 'Retry-After': '0' } }); + }), + ); + + const error = await newToolSet() + .fetchAccounts() + .catch((caught: unknown) => caught); + + expect((error as StackOneAPIError).statusCode).toBe(status); + expect(requests).toBe(1); + expect(retryWarnings()).toEqual([]); + }); + + it('does not retry a 500 from the MCP endpoint', async () => { + let requests = 0; + server.use( + http.post(`${TEST_BASE_URL}/mcp`, () => { + requests++; + return HttpResponse.json({ message: 'down' }, { status: 500 }); + }), + ); + + const error = await newToolSet() + .fetchTools({ accountIds: ['acc1'] }) + .catch((caught: unknown) => caught); + + expect((error as StackOneAPIError).statusCode).toBe(500); + expect(requests).toBe(1); + }); +}); diff --git a/src/toolsets.ts b/src/toolsets.ts index b1277ff2..db34e933 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -7,7 +7,7 @@ import { SUBMIT_FEEDBACK_TOOL_NAME, } from './consts'; import { buildRequestHeaders, isSdkOwnedHeader } from './headers'; -import { type McpToolDefinition, listMcpTools } from './mcp-client'; +import { type McpToolDefinition, isRateLimitFailure, listMcpTools } from './mcp-client'; import { cloneJson, toolParametersFromInputSchema } from './schema'; import { StackOneMcpTool, type StackOneTool, Tools } from './tool'; import type { @@ -23,6 +23,7 @@ import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; import { settleWithConcurrency } from './utils/concurrency'; +import { fetchWithRetry } from './utils/fetch-retry'; import { warn } from './utils/logger'; /** @@ -418,7 +419,8 @@ export class StackOneToolSet { * Each entry carries at least `id`, `provider` and `status`. Only accounts with * `status === 'active'` can serve tools. * - * @throws StackOneAPIError If the API answers with an error status. + * @throws StackOneAPIError If the API answers with an error status, including a 429 that + * outlasted its retries. * @throws ToolSetLoadError If the API cannot be reached, or answers with something that is * not a JSON list (including a body that is not valid UTF-8). */ @@ -426,7 +428,7 @@ export class StackOneToolSet { const url = `${this.#baseUrl.replace(/\/+$/, '')}/accounts`; let response: Response; try { - response = await fetch(url, { + response = await fetchWithRetry(url, { headers: buildRequestHeaders({ apiKey: this.#apiKey, extraHeaders: this.#headers }), signal: AbortSignal.timeout(this.#timeout), }); @@ -575,8 +577,11 @@ export class StackOneToolSet { * * One unusable account must not cost the caller every other account's tools, so a failing * account is skipped with a warning — unless every account fails, which is an error rather - * than an empty catalog. A degraded listing is not cached: the warning fires once, and every - * later call would otherwise serve the short list silently for the life of the process. + * than an empty catalog. A 429 that outlasted its retries is not the account's fault but the + * key's, so it fails the whole listing instead: skipping it would hand back a catalog missing + * whichever accounts happened to be throttled. A degraded listing is not cached: the warning + * fires once, and every later call would otherwise serve the short list silently for the life + * of the process. */ async #listCatalog( scope: readonly string[], @@ -609,7 +614,12 @@ export class StackOneToolSet { return listing; } - const settled = await settleWithConcurrency(scope, MAX_CONCURRENCY, listAccount); + const settled = await settleWithConcurrency( + scope, + MAX_CONCURRENCY, + listAccount, + isRateLimitFailure, + ); const listing: CatalogEntry[] = []; const failures: string[] = []; settled.forEach((outcome, index) => { @@ -658,8 +668,14 @@ export class StackOneToolSet { * * `stackone_submit_feedback` is served once per account listing; it is returned once. * + * Rate limits: a request answered 429 is retried up to 3 times, after the server's + * `Retry-After` (capped at 30s) or a 1s/2s/4s backoff. One still rate limited after that fails + * the whole call: an account that fails any other way is skipped with a warning, but a 429 + * never yields a partial catalog. + * * @throws ToolSetConfigError If no account is configured and none can be discovered. - * @throws StackOneAPIError If the API refuses a listing (e.g. 412 for a dead account). + * @throws StackOneAPIError If the API refuses a listing (e.g. 412 for a dead account), or + * still answers 429 after the retries, on any account. * @throws ToolSetLoadError If the catalog cannot be loaded. */ async fetchTools(options: FetchToolsOptions = {}): Promise { @@ -725,11 +741,16 @@ export class StackOneToolSet { * tools never has to fit in a model's context. A connector that fails to search is skipped * with a warning, unless they all fail. * + * Rate limits: a request answered 429 is retried up to 3 times, after the server's + * `Retry-After` (capped at 30s) or a 1s/2s/4s backoff. One still rate limited after that fails + * the whole search rather than being skipped. + * * @param query What you want to do, e.g. "list recent comments". * @returns Actions carrying at least `action_id`, best first, each with the * `session_id` of the search that found it when the server issued one. Pass it to * {@link execute} and {@link submitFeedback} to link the calls. * @throws ToolSetConfigError If `topK` is not an integer between 1 and 50. + * @throws StackOneAPIError With status 429 if a request is still rate limited after retries. * @throws ToolSetLoadError If every connector fails. */ async search(query: string, options: SearchOptions = {}): Promise { @@ -767,7 +788,12 @@ export class StackOneToolSet { // 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); + const settled = await settleWithConcurrency( + tools, + MAX_CONCURRENCY, + searchOne, + isRateLimitFailure, + ); const results: SearchResult[] = []; const failures: string[] = []; settled.forEach((outcome, index) => { diff --git a/src/utils/concurrency.test.ts b/src/utils/concurrency.test.ts new file mode 100644 index 00000000..5df69d8c --- /dev/null +++ b/src/utils/concurrency.test.ts @@ -0,0 +1,39 @@ +import { settleWithConcurrency } from './concurrency'; + +describe('settleWithConcurrency', () => { + it('settles every item, in input order', async () => { + const settled = await settleWithConcurrency([1, 2, 3], 2, async (item) => { + if (item === 2) { + throw new Error('two'); + } + return item * 10; + }); + + expect(settled).toEqual([ + { status: 'fulfilled', value: 10 }, + { status: 'rejected', reason: new Error('two') }, + { status: 'fulfilled', value: 30 }, + ]); + }); + + it('rejects on a fatal failure and starts no further item', async () => { + const fatal = new Error('fatal'); + const started: number[] = []; + + const outcome = settleWithConcurrency( + [1, 2, 3, 4], + 1, + async (item) => { + started.push(item); + if (item === 2) { + throw fatal; + } + return item; + }, + (reason) => reason === fatal, + ); + + await expect(outcome).rejects.toBe(fatal); + expect(started).toEqual([1, 2]); + }); +}); diff --git a/src/utils/concurrency.ts b/src/utils/concurrency.ts index 4bbca28f..8c94805c 100644 --- a/src/utils/concurrency.ts +++ b/src/utils/concurrency.ts @@ -3,20 +3,29 @@ * * Results come back in input order whatever order they complete in, so callers that merge them * stay deterministic. + * + * A failure that `isFatal` accepts is not settled: it rejects the whole run as soon as it is + * seen, and no further item is started. Work already in flight finishes in the background. */ export async function settleWithConcurrency( items: readonly T[], limit: number, work: (item: T) => Promise, + isFatal: (reason: unknown) => boolean = () => false, ): Promise[]> { const results: PromiseSettledResult[] = Array.from({ length: items.length }); let next = 0; + let stopped = false; const worker = async (): Promise => { - while (next < items.length) { + while (!stopped && next < items.length) { const index = next++; try { results[index] = { status: 'fulfilled', value: await work(items[index] as T) }; } catch (reason) { + if (isFatal(reason)) { + stopped = true; + throw reason; + } results[index] = { status: 'rejected', reason }; } } diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts new file mode 100644 index 00000000..5bb41f1c --- /dev/null +++ b/src/utils/fetch-retry.test.ts @@ -0,0 +1,207 @@ +import { http, HttpResponse, type JsonBodyType } from 'msw'; +import { TEST_BASE_URL } from '../../mocks/constants'; +import { server } from '../../mocks/node'; +import { fetchWithRetry } from './fetch-retry'; + +const url = `${TEST_BASE_URL}/limited`; + +/** Answer each request with the next response, repeating the last. Returns the request count. */ +const respondWith = (...responses: Array<() => Response>) => { + const seen = { requests: 0 }; + server.use( + http.all(url, () => { + const respond = responses[Math.min(seen.requests, responses.length - 1)]; + seen.requests++; + return respond?.(); + }), + ); + return seen; +}; + +const limited = + (headers: Record = {}, body: JsonBodyType = { message: 'slow down' }) => + () => + HttpResponse.json(body, { status: 429, headers }); +const ok = () => HttpResponse.json({ ok: true }); + +/** Timing that records each requested wait instead of waiting. */ +const recordedTiming = (random = () => 0.5) => { + const delays: number[] = []; + return { + delays, + timing: { + sleep: async (ms: number) => { + delays.push(ms); + }, + random, + }, + }; +}; + +let warnSpy: ReturnType; +beforeEach(() => { + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('fetchWithRetry', () => { + it('retries a 429 and returns the success', async () => { + const seen = respondWith(limited({ 'Retry-After': '2' }), ok); + const { delays, timing } = recordedTiming(); + + const response = await fetchWithRetry(url, { method: 'POST', body: '{}' }, timing); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + expect(seen.requests).toBe(2); + expect(delays).toEqual([2000]); + expect(warnSpy.mock.calls.map(([message]: unknown[]) => message)).toEqual([ + `[@stackone/ai] Rate limited (429) by POST ${url}; retrying in 2000ms (attempt 2 of 4)`, + ]); + }); + + it('gives up after 4 attempts, returning the last 429 with its body', async () => { + const seen = respondWith( + limited({}, { message: 'first' }), + limited({}, { message: 'second' }), + limited({}, { message: 'third' }), + limited({}, { message: 'last' }), + ok, + ); + const { delays, timing } = recordedTiming(); + + const response = await fetchWithRetry(url, undefined, timing); + + expect(response.status).toBe(429); + expect(await response.json()).toEqual({ message: 'last' }); + expect(seen.requests).toBe(4); + expect(delays).toHaveLength(3); + expect(warnSpy).toHaveBeenCalledTimes(3); + }); + + it.each([400, 401, 412, 500, 503])('does not retry a %i', async (status) => { + const seen = respondWith( + () => HttpResponse.json({}, { status, headers: { 'Retry-After': '1' } }), + ok, + ); + const { delays, timing } = recordedTiming(); + + expect((await fetchWithRetry(url, undefined, timing)).status).toBe(status); + expect(seen.requests).toBe(1); + expect(delays).toEqual([]); + }); + + describe('Retry-After', () => { + it('waits the delta-seconds given', async () => { + respondWith(limited({ 'Retry-After': '7' }), ok); + const { delays, timing } = recordedTiming(); + + await fetchWithRetry(url, undefined, timing); + + expect(delays).toEqual([7000]); + }); + + it('waits until the HTTP-date given', async () => { + // HTTP-dates have whole-second precision, so the wait lands within a second below 10s. + const at = new Date(Date.now() + 10_000).toUTCString(); + respondWith(limited({ 'Retry-After': at }), ok); + const { delays, timing } = recordedTiming(); + + await fetchWithRetry(url, undefined, timing); + + expect(delays).toHaveLength(1); + expect(delays[0]).toBeGreaterThan(8_000); + expect(delays[0]).toBeLessThanOrEqual(10_000); + }); + + it('retries at once for an HTTP-date in the past', async () => { + respondWith(limited({ 'Retry-After': new Date(0).toUTCString() }), ok); + const { delays, timing } = recordedTiming(); + + expect((await fetchWithRetry(url, undefined, timing)).status).toBe(200); + expect(delays).toEqual([]); + }); + + it.each([ + ['delta-seconds', '120'], + ['an HTTP-date', new Date(Date.now() + 3_600_000).toUTCString()], + ])('caps %s at 30s', async (_kind, value) => { + respondWith(limited({ 'Retry-After': value }), ok); + const { delays, timing } = recordedTiming(); + + await fetchWithRetry(url, undefined, timing); + + expect(delays).toEqual([30_000]); + }); + + it('retries immediately on 0', async () => { + const seen = respondWith(limited({ 'Retry-After': '0' }), ok); + const { delays, timing } = recordedTiming(); + + expect((await fetchWithRetry(url, undefined, timing)).status).toBe(200); + expect(seen.requests).toBe(2); + expect(delays).toEqual([]); + expect(String(warnSpy.mock.calls[0]?.[0])).toContain('retrying in 0ms (attempt 2 of 4)'); + }); + + it('backs off as if absent when unreadable', async () => { + respondWith(limited({ 'Retry-After': 'soon' }), ok); + const { delays, timing } = recordedTiming(() => 0); + + await fetchWithRetry(url, undefined, timing); + + expect(delays).toEqual([500]); + }); + }); + + describe('without Retry-After', () => { + it('backs off 1s, 2s, 4s, scaled by jitter of at least 0.5', async () => { + respondWith(limited()); + const { delays, timing } = recordedTiming(() => 0); + + await fetchWithRetry(url, undefined, timing); + + expect(delays).toEqual([500, 1000, 2000]); + }); + + it('backs off 1s, 2s, 4s, scaled by jitter below 1.0', async () => { + respondWith(limited()); + const { delays, timing } = recordedTiming(() => 0.999_999); + + await fetchWithRetry(url, undefined, timing); + + expect(delays).toHaveLength(3); + [1000, 2000, 4000].forEach((ceiling, index) => { + expect(delays[index]).toBeGreaterThan(ceiling * 0.99); + expect(delays[index]).toBeLessThan(ceiling); + }); + }); + + it('keeps every jittered delay within [0.5, 1.0) of the base', async () => { + respondWith(limited()); + const { delays, timing } = recordedTiming(Math.random); + + await fetchWithRetry(url, undefined, timing); + + [1000, 2000, 4000].forEach((base, index) => { + expect(delays[index]).toBeGreaterThanOrEqual(base * 0.5); + expect(delays[index]).toBeLessThan(base); + }); + }); + }); + + it('waits for real by default, and gives up the wait when the signal aborts', async () => { + const seen = respondWith(limited({ 'Retry-After': '30' }), ok); + const controller = new AbortController(); + const reason = new Error('deadline'); + setTimeout(() => controller.abort(reason), 20); + + const started = performance.now(); + await expect(fetchWithRetry(url, { signal: controller.signal })).rejects.toBe(reason); + + expect(performance.now() - started).toBeLessThan(5_000); + expect(seen.requests).toBe(1); + }); +}); diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts new file mode 100644 index 00000000..8ec8d8dc --- /dev/null +++ b/src/utils/fetch-retry.ts @@ -0,0 +1,84 @@ +import { + RATE_LIMIT_BASE_DELAY_MS, + RATE_LIMIT_MAX_DELAY_MS, + RATE_LIMIT_MAX_RETRIES, +} from '../consts'; +import { warn } from './logger'; + +interface RetryTiming { + /** Wait `ms` milliseconds, rejecting with the signal's reason if it aborts first. */ + sleep: (ms: number, signal?: AbortSignal | null) => Promise; + /** A number in [0, 1), as `Math.random` returns. Drives the backoff jitter. */ + random: () => number; +} + +const sleep = (ms: number, signal?: AbortSignal | null): Promise => + new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + const onAbort = (): void => { + clearTimeout(timer); + reject(signal?.reason); + }; + const timer = setTimeout(() => { + signal?.removeEventListener('abort', onAbort); + resolve(); + }, ms); + signal?.addEventListener('abort', onAbort, { once: true }); + }); + +const defaultTiming: RetryTiming = { sleep, random: Math.random }; + +/** + * How long the server asked us to wait, in milliseconds: `Retry-After` as delta-seconds or an + * HTTP-date. Undefined when the header is absent or unreadable, so the caller backs off instead. + */ +function retryAfterMs(header: string | null): number | undefined { + const value = header?.trim(); + if (!value) { + return undefined; + } + if (/^\d+$/.test(value)) { + return Number(value) * 1000; + } + const date = Date.parse(value); + return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now()); +} + +/** + * `fetch`, retried on HTTP 429. + * + * A 429 means the server refused before doing anything, so even a `tools/call` is safe to send + * again. Each retry waits for the response's `Retry-After` (capped at 30s), or else 1s, 2s, 4s + * with jitter. Every other status, and the last 429, is handed back as it came: the caller turns + * it into a `StackOneAPIError` with the server's body. The waits run inside the caller's signal, + * so a timeout still bounds the whole exchange. + */ +export async function fetchWithRetry( + input: string | URL, + init?: RequestInit, + timing: RetryTiming = defaultTiming, +): Promise { + for (let retry = 1; ; retry++) { + const response = await fetch(input, init); + if (response.status !== 429 || retry > RATE_LIMIT_MAX_RETRIES) { + return response; + } + const requested = retryAfterMs(response.headers.get('retry-after')); + const delay = + requested === undefined + ? RATE_LIMIT_BASE_DELAY_MS * 2 ** (retry - 1) * (0.5 + timing.random() * 0.5) + : Math.min(requested, RATE_LIMIT_MAX_DELAY_MS); + // Discarded unread: only the final 429's body is reported. Not awaited, since a cancel can + // wait on a producer that never settles (MSW's, for one), and the retry need not wait. + void response.body?.cancel().catch(() => undefined); + warn( + `Rate limited (429) by ${init?.method ?? 'GET'} ${String(input)}; retrying in ${Math.round(delay)}ms (attempt ${retry + 1} of ${RATE_LIMIT_MAX_RETRIES + 1})`, + ); + if (delay > 0) { + await timing.sleep(delay, init?.signal); + } + } +} From fb2cadc11269ab92260eff965c8d8c357d5e1a1a Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 11:30:51 +0100 Subject: [PATCH 042/151] docs(readme): describe rate-limit retries --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 0642f93b..ffb1ef34 100644 --- a/README.md +++ b/README.md @@ -415,6 +415,10 @@ Everything the SDK throws is a `StackOneError`: `timeout` (milliseconds, default 60000) bounds every MCP listing and `tools/call`, and account discovery. +### Rate limits + +Every request the SDK makes (`GET /accounts` and every MCP request, `tools/call` included) is retried when the API answers `429 Too Many Requests`: up to 3 more times, waiting for the response's `Retry-After` (capped at 30s), or 1s, 2s, then 4s with jitter when there is none. Each retry logs a warning. A request still rate limited after that throws `StackOneAPIError` with `statusCode` `429`, and fails the whole `fetchTools()` or `search()` call: unlike a dead account, a rate-limited one is never skipped, so you never get a partial catalog. The retries' waits count towards `timeout`. + ### Custom Base URL ```typescript From 9f588c875918e58b3d6d1a76c82622659caeef90 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 11:39:15 +0100 Subject: [PATCH 043/151] fix(retry): read only digits or an HTTP-date as Retry-After Date.parse reads "1.5", "-1" and "2026-10-01" as dates, so an unreadable header became an immediate retry. Matches Python. --- src/utils/fetch-retry.test.ts | 17 +++++++++++------ src/utils/fetch-retry.ts | 5 +++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index 5bb41f1c..9cecc9e0 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -146,14 +146,19 @@ describe('fetchWithRetry', () => { expect(String(warnSpy.mock.calls[0]?.[0])).toContain('retrying in 0ms (attempt 2 of 4)'); }); - it('backs off as if absent when unreadable', async () => { - respondWith(limited({ 'Retry-After': 'soon' }), ok); - const { delays, timing } = recordedTiming(() => 0); + // Date.parse reads "1.5" and "2026-10-01" as dates, so only a value shaped like an + // HTTP-date may reach it. Python reads these the same way. + it.each(['soon', '1.5', '1.5e3', '-1', '2026-10-01'])( + 'backs off as if absent when unreadable (%s)', + async (value) => { + respondWith(limited({ 'Retry-After': value }), ok); + const { delays, timing } = recordedTiming(() => 0); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, timing); - expect(delays).toEqual([500]); - }); + expect(delays).toEqual([500]); + }, + ); }); describe('without Retry-After', () => { diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index 8ec8d8dc..ccd87c6d 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -43,6 +43,11 @@ function retryAfterMs(header: string | null): number | undefined { if (/^\d+$/.test(value)) { return Number(value) * 1000; } + // An HTTP-date always starts with a day name. Date.parse alone reads "1.5" as a day in + // 2001, which would turn an unreadable header into an immediate retry. + if (!/^[A-Za-z]/.test(value)) { + return undefined; + } const date = Date.parse(value); return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now()); } From dc9a75535e62242d117687d7176af043bdbe5c37 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 11:39:27 +0100 Subject: [PATCH 044/151] ci: pin sdk-conformance to 9d5efab --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 2380cf2c..f3b8f10e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 6a6991dd2d65c211b55902e9243627f817c97543 + ref: 9d5efab9b6c6fa736e1885e784604d9e05fad7b4 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 05fa4fde9bcb37a625a4641612d4631b9087cc38 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 11:49:06 +0100 Subject: [PATCH 045/151] fix(retry): read Retry-After as a date only when it starts with a weekday Date.parse accepts "March 1, 2027"; all three HTTP-date forms start with a weekday. Matches Python. --- src/utils/fetch-retry.test.ts | 23 ++++++++++++++--------- src/utils/fetch-retry.ts | 7 ++++--- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index 9cecc9e0..5faf6664 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -148,17 +148,22 @@ describe('fetchWithRetry', () => { // Date.parse reads "1.5" and "2026-10-01" as dates, so only a value shaped like an // HTTP-date may reach it. Python reads these the same way. - it.each(['soon', '1.5', '1.5e3', '-1', '2026-10-01'])( - 'backs off as if absent when unreadable (%s)', - async (value) => { - respondWith(limited({ 'Retry-After': value }), ok); - const { delays, timing } = recordedTiming(() => 0); + it.each([ + 'soon', + '1.5', + '1.5e3', + '-1', + '2026-10-01', + 'March 1, 2027', + 'X, 21 Oct 2015 07:28:00 GMT', + ])('backs off as if absent when unreadable (%s)', async (value) => { + respondWith(limited({ 'Retry-After': value }), ok); + const { delays, timing } = recordedTiming(() => 0); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, timing); - expect(delays).toEqual([500]); - }, - ); + expect(delays).toEqual([500]); + }); }); describe('without Retry-After', () => { diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index ccd87c6d..061162f7 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -43,9 +43,10 @@ function retryAfterMs(header: string | null): number | undefined { if (/^\d+$/.test(value)) { return Number(value) * 1000; } - // An HTTP-date always starts with a day name. Date.parse alone reads "1.5" as a day in - // 2001, which would turn an unreadable header into an immediate retry. - if (!/^[A-Za-z]/.test(value)) { + // All three HTTP-date forms start with a weekday ("Sun,", "Sunday,", "Sun "). Date.parse + // alone reads "1.5" or "March 1, 2027" as dates, so anything else falls back to the + // backoff, as in Python. + if (!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[, ]/.test(value)) { return undefined; } const date = Date.parse(value); From 6639d19585cd5d90957c19ed733e1968dbbc3e37 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 14:34:21 +0100 Subject: [PATCH 046/151] fix(retry): return the 429 when a retry's wait would outlast the timeout Waiting anyway let the timeout fire, so a rate-limited account was skipped as timed out and fetchTools() returned a partial catalog, and GET /accounts raised ToolSetLoadError instead of the 429. The deadline is the call's timeout: the MCP session's for listings and tools/call, measured from the first attempt for GET /accounts. --- README.md | 2 +- src/mcp-client.ts | 7 +-- src/rate-limit.test.ts | 92 ++++++++++++++++++++++++++++++++--- src/toolsets.ts | 23 +++++---- src/utils/fetch-retry.test.ts | 90 +++++++++++++++++++++++++++++----- src/utils/fetch-retry.ts | 33 +++++++++++-- 6 files changed, 210 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index ffb1ef34..fea7fb00 100644 --- a/README.md +++ b/README.md @@ -417,7 +417,7 @@ Everything the SDK throws is a `StackOneError`: ### Rate limits -Every request the SDK makes (`GET /accounts` and every MCP request, `tools/call` included) is retried when the API answers `429 Too Many Requests`: up to 3 more times, waiting for the response's `Retry-After` (capped at 30s), or 1s, 2s, then 4s with jitter when there is none. Each retry logs a warning. A request still rate limited after that throws `StackOneAPIError` with `statusCode` `429`, and fails the whole `fetchTools()` or `search()` call: unlike a dead account, a rate-limited one is never skipped, so you never get a partial catalog. The retries' waits count towards `timeout`. +Every request the SDK makes (`GET /accounts` and every MCP request, `tools/call` included) is retried when the API answers `429 Too Many Requests`: up to 3 more times, waiting for the response's `Retry-After` (capped at 30s), or 1s, 2s, then 4s with jitter when there is none. Each retry logs a warning. A request still rate limited after that throws `StackOneAPIError` with `statusCode` `429`, and fails the whole `fetchTools()` or `search()` call: unlike a dead account, a rate-limited one is never skipped, so you never get a partial catalog. The retries' waits count towards `timeout`, and a wait that would outlast it is not started: the 429 is thrown at once, so a rate limit never turns into a timeout. ### Custom Base URL diff --git a/src/mcp-client.ts b/src/mcp-client.ts index f5d92d35..790ad992 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -10,7 +10,7 @@ import type { JsonObject } from './types'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { ToolSetLoadError } from './utils/error-toolset'; -import { fetchWithRetry } from './utils/fetch-retry'; +import { fetchWithRetry, retryTiming } from './utils/fetch-retry'; /** A tool exactly as the MCP server listed it. */ export interface McpToolDefinition { @@ -118,11 +118,12 @@ async function withMcpSession( { endpoint, headers, timeout }: McpRequest, work: (client: Client) => Promise, ): Promise { + const expiresAt = retryTiming.now() + timeout; const transport = new StreamableHTTPClientTransport(new URL(endpoint), { requestInit: { headers }, // Every request the client sends, handshake included, so it never sees a 429 it could - // have waited out. - fetch: (url, init) => fetchWithRetry(url, init), + // have waited out — but never one that would outlast the session's deadline. + fetch: (url, init) => fetchWithRetry(url, init, { deadline: expiresAt }), }); const client = new Client({ name: 'stackone-ai-node', version }); let timer: ReturnType | undefined; diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts index d095cd2b..1f8bb24c 100644 --- a/src/rate-limit.test.ts +++ b/src/rate-limit.test.ts @@ -10,6 +10,7 @@ import { type RecordedToolCall, accountMcpTools, createMcpApp } from '../mocks/m import { server } from '../mocks/node'; import { StackOneToolSet } from './toolsets'; import { StackOneAPIError } from './utils/error-stackone-api'; +import { retryTiming } from './utils/fetch-retry'; const newToolSet = (config: ConstructorParameters[0] = {}) => new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); @@ -32,6 +33,8 @@ interface Throttle { times?: number; method?: string; accountId?: string; + /** The `Retry-After` each 429 carries. Default: `'0'`. */ + retryAfter?: string; } /** @@ -60,7 +63,10 @@ const serveThrottled = (throttle: Throttle) => { (throttle.method === undefined || message?.method === throttle.method) && (throttle.accountId === undefined || accountId === throttle.accountId); if (matches && attempts.matched++ < (throttle.times ?? Number.POSITIVE_INFINITY)) { - return HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '0' } }); + return HttpResponse.json(RATE_LIMITED, { + status: 429, + headers: { 'Retry-After': throttle.retryAfter ?? '0' }, + }); } return app.fetch(request); }), @@ -68,6 +74,12 @@ const serveThrottled = (throttle: Throttle) => { return { attempts, calls }; }; +const expectRateLimited = (error: unknown) => { + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + expect((error as StackOneAPIError).responseBody).toEqual(RATE_LIMITED); +}; + describe('a 429 that clears on retry', () => { it('retries the MCP handshake', async () => { const { attempts } = serveThrottled({ method: 'initialize', times: 1 }); @@ -124,12 +136,6 @@ describe('a 429 that clears on retry', () => { }); describe('a 429 that outlasts its retries', () => { - const expectRateLimited = (error: unknown) => { - expect(error).toBeInstanceOf(StackOneAPIError); - expect((error as StackOneAPIError).statusCode).toBe(429); - expect((error as StackOneAPIError).responseBody).toEqual(RATE_LIMITED); - }; - it('throws a 429 StackOneAPIError from GET /accounts after exactly 4 attempts', async () => { let requests = 0; server.use( @@ -228,6 +234,78 @@ 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; + }; + + 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' }); + + const error = await newToolSet({ timeout: 3_000 }) + .fetchTools({ accountIds: ['acc1', 'acc2'] }) + .catch((caught: unknown) => caught); + + expectRateLimited(error); + // One 2s wait fits in 3s; the second would end at 4s, so the 429 is returned instead. + expect(waits).toEqual([2_000]); + expect(attempts.matched).toBe(2); + expect(warnings().filter((message) => message.includes('Skipping'))).toEqual([]); + }); + + it('throws the 429 from GET /accounts without waiting', async () => { + const waits = fakeClock(); + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + requests++; + return HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '3' } }); + }), + ); + + const error = await newToolSet({ timeout: 1_000 }) + .fetchAccounts() + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + expect(requests).toBe(1); + expect(waits).toEqual([]); + expect(retryWarnings()).toEqual([]); + }); + + it('measures the GET /accounts deadline from the first attempt', async () => { + const waits = fakeClock(); + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + requests++; + return HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '1' } }); + }), + ); + + const error = await newToolSet({ timeout: 2_500 }) + .fetchAccounts() + .catch((caught: unknown) => caught); + + expect((error as StackOneAPIError).statusCode).toBe(429); + expect(waits).toEqual([1_000, 1_000]); + expect(requests).toBe(3); + }); +}); + describe('other statuses', () => { it.each([400, 500])('does not retry a %i', async (status) => { let requests = 0; diff --git a/src/toolsets.ts b/src/toolsets.ts index db34e933..aac17a09 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -23,7 +23,7 @@ import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; import { settleWithConcurrency } from './utils/concurrency'; -import { fetchWithRetry } from './utils/fetch-retry'; +import { fetchWithRetry, retryTiming } from './utils/fetch-retry'; import { warn } from './utils/logger'; /** @@ -428,10 +428,14 @@ export class StackOneToolSet { const url = `${this.#baseUrl.replace(/\/+$/, '')}/accounts`; let response: Response; try { - response = await fetchWithRetry(url, { - headers: buildRequestHeaders({ apiKey: this.#apiKey, extraHeaders: this.#headers }), - signal: AbortSignal.timeout(this.#timeout), - }); + response = await fetchWithRetry( + url, + { + headers: buildRequestHeaders({ apiKey: this.#apiKey, extraHeaders: this.#headers }), + signal: AbortSignal.timeout(this.#timeout), + }, + { deadline: retryTiming.now() + this.#timeout }, + ); } catch (error) { throw new ToolSetLoadError(`Could not reach ${url}: ${describeError(error)}`, { cause: error, @@ -669,8 +673,8 @@ export class StackOneToolSet { * `stackone_submit_feedback` is served once per account listing; it is returned once. * * Rate limits: a request answered 429 is retried up to 3 times, after the server's - * `Retry-After` (capped at 30s) or a 1s/2s/4s backoff. One still rate limited after that fails - * the whole call: an account that fails any other way is skipped with a warning, but a 429 + * `Retry-After` (capped at 30s) or a 1s/2s/4s backoff, unless that wait would outlast the + * `timeout`. One still rate limited after that fails the whole call: an account that fails any other way is skipped with a warning, but a 429 * never yields a partial catalog. * * @throws ToolSetConfigError If no account is configured and none can be discovered. @@ -742,8 +746,9 @@ export class StackOneToolSet { * with a warning, unless they all fail. * * Rate limits: a request answered 429 is retried up to 3 times, after the server's - * `Retry-After` (capped at 30s) or a 1s/2s/4s backoff. One still rate limited after that fails - * the whole search rather than being skipped. + * `Retry-After` (capped at 30s) or a 1s/2s/4s backoff, unless that wait would outlast the + * `timeout`. One still rate limited after that fails the whole search rather than being + * skipped. * * @param query What you want to do, e.g. "list recent comments". * @returns Actions carrying at least `action_id`, best first, each with the diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index 5faf6664..df8cff08 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -24,16 +24,19 @@ const limited = HttpResponse.json(body, { status: 429, headers }); const ok = () => HttpResponse.json({ ok: true }); -/** Timing that records each requested wait instead of waiting. */ +/** Timing that records each requested wait instead of waiting, advancing a fake clock by it. */ const recordedTiming = (random = () => 0.5) => { const delays: number[] = []; + const clock = { now: 0 }; return { delays, timing: { sleep: async (ms: number) => { delays.push(ms); + clock.now += ms; }, random, + now: () => clock.now, }, }; }; @@ -51,7 +54,7 @@ describe('fetchWithRetry', () => { const seen = respondWith(limited({ 'Retry-After': '2' }), ok); const { delays, timing } = recordedTiming(); - const response = await fetchWithRetry(url, { method: 'POST', body: '{}' }, timing); + const response = await fetchWithRetry(url, { method: 'POST', body: '{}' }, { timing }); expect(response.status).toBe(200); expect(await response.json()).toEqual({ ok: true }); @@ -72,7 +75,7 @@ describe('fetchWithRetry', () => { ); const { delays, timing } = recordedTiming(); - const response = await fetchWithRetry(url, undefined, timing); + const response = await fetchWithRetry(url, undefined, { timing }); expect(response.status).toBe(429); expect(await response.json()).toEqual({ message: 'last' }); @@ -88,7 +91,7 @@ describe('fetchWithRetry', () => { ); const { delays, timing } = recordedTiming(); - expect((await fetchWithRetry(url, undefined, timing)).status).toBe(status); + expect((await fetchWithRetry(url, undefined, { timing })).status).toBe(status); expect(seen.requests).toBe(1); expect(delays).toEqual([]); }); @@ -98,7 +101,7 @@ describe('fetchWithRetry', () => { respondWith(limited({ 'Retry-After': '7' }), ok); const { delays, timing } = recordedTiming(); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, { timing }); expect(delays).toEqual([7000]); }); @@ -109,7 +112,7 @@ describe('fetchWithRetry', () => { respondWith(limited({ 'Retry-After': at }), ok); const { delays, timing } = recordedTiming(); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, { timing }); expect(delays).toHaveLength(1); expect(delays[0]).toBeGreaterThan(8_000); @@ -120,7 +123,7 @@ describe('fetchWithRetry', () => { respondWith(limited({ 'Retry-After': new Date(0).toUTCString() }), ok); const { delays, timing } = recordedTiming(); - expect((await fetchWithRetry(url, undefined, timing)).status).toBe(200); + expect((await fetchWithRetry(url, undefined, { timing })).status).toBe(200); expect(delays).toEqual([]); }); @@ -131,7 +134,7 @@ describe('fetchWithRetry', () => { respondWith(limited({ 'Retry-After': value }), ok); const { delays, timing } = recordedTiming(); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, { timing }); expect(delays).toEqual([30_000]); }); @@ -140,7 +143,7 @@ describe('fetchWithRetry', () => { const seen = respondWith(limited({ 'Retry-After': '0' }), ok); const { delays, timing } = recordedTiming(); - expect((await fetchWithRetry(url, undefined, timing)).status).toBe(200); + expect((await fetchWithRetry(url, undefined, { timing })).status).toBe(200); expect(seen.requests).toBe(2); expect(delays).toEqual([]); expect(String(warnSpy.mock.calls[0]?.[0])).toContain('retrying in 0ms (attempt 2 of 4)'); @@ -160,7 +163,7 @@ describe('fetchWithRetry', () => { respondWith(limited({ 'Retry-After': value }), ok); const { delays, timing } = recordedTiming(() => 0); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, { timing }); expect(delays).toEqual([500]); }); @@ -171,7 +174,7 @@ describe('fetchWithRetry', () => { respondWith(limited()); const { delays, timing } = recordedTiming(() => 0); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, { timing }); expect(delays).toEqual([500, 1000, 2000]); }); @@ -180,7 +183,7 @@ describe('fetchWithRetry', () => { respondWith(limited()); const { delays, timing } = recordedTiming(() => 0.999_999); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, { timing }); expect(delays).toHaveLength(3); [1000, 2000, 4000].forEach((ceiling, index) => { @@ -193,7 +196,7 @@ describe('fetchWithRetry', () => { respondWith(limited()); const { delays, timing } = recordedTiming(Math.random); - await fetchWithRetry(url, undefined, timing); + await fetchWithRetry(url, undefined, { timing }); [1000, 2000, 4000].forEach((base, index) => { expect(delays[index]).toBeGreaterThanOrEqual(base * 0.5); @@ -202,6 +205,67 @@ describe('fetchWithRetry', () => { }); }); + describe('with a deadline', () => { + it('returns the 429 at once when Retry-After would outlast the deadline', async () => { + const seen = respondWith(limited({ 'Retry-After': '3' }, { message: 'too long' }), ok); + const { delays, timing } = recordedTiming(); + + const response = await fetchWithRetry(url, undefined, { deadline: 1_000, timing }); + + expect(response.status).toBe(429); + expect(await response.json()).toEqual({ message: 'too long' }); + expect(seen.requests).toBe(1); + expect(delays).toEqual([]); + expect(warnSpy).not.toHaveBeenCalled(); + }); + + it('counts every earlier wait against the deadline', async () => { + const seen = respondWith(limited({ 'Retry-After': '2' })); + const { delays, timing } = recordedTiming(); + + // Waiting 2s ends at 2s, inside 3s; the next 2s wait would end at 4s, so it is not started. + const response = await fetchWithRetry(url, undefined, { deadline: 3_000, timing }); + + expect(response.status).toBe(429); + expect(seen.requests).toBe(2); + expect(delays).toEqual([2_000]); + }); + + it('applies to the jittered backoff too', async () => { + const seen = respondWith(limited()); + const { delays, timing } = recordedTiming(() => 0); + + // 500ms, then 1000ms fit in 2s; the 2000ms after them would end at 3.5s. + const response = await fetchWithRetry(url, undefined, { deadline: 2_000, timing }); + + expect(response.status).toBe(429); + expect(seen.requests).toBe(3); + expect(delays).toEqual([500, 1_000]); + }); + + it('does not retry a wait that would end exactly at the deadline', async () => { + const seen = respondWith(limited({ 'Retry-After': '1' }), ok); + const { delays, timing } = recordedTiming(); + + const response = await fetchWithRetry(url, undefined, { deadline: 1_000, timing }); + + expect(response.status).toBe(429); + expect(seen.requests).toBe(1); + expect(delays).toEqual([]); + }); + + it('retries a wait that ends before the deadline', async () => { + const seen = respondWith(limited({ 'Retry-After': '1' }), ok); + const { delays, timing } = recordedTiming(); + + const response = await fetchWithRetry(url, undefined, { deadline: 1_001, timing }); + + expect(response.status).toBe(200); + expect(seen.requests).toBe(2); + expect(delays).toEqual([1_000]); + }); + }); + it('waits for real by default, and gives up the wait when the signal aborts', async () => { const seen = respondWith(limited({ 'Retry-After': '30' }), ok); const controller = new AbortController(); diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index 061162f7..ca35d651 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -10,6 +10,17 @@ interface RetryTiming { sleep: (ms: number, signal?: AbortSignal | null) => Promise; /** A number in [0, 1), as `Math.random` returns. Drives the backoff jitter. */ random: () => number; + /** The current time in milliseconds, on the clock a `deadline` is measured on. */ + now: () => number; +} + +interface RetryOptions { + /** + * When the caller's timeout expires, as a {@link RetryTiming.now} time. A retry whose wait + * would not end before it is not attempted: the 429 is returned instead. + */ + deadline?: number; + timing?: RetryTiming; } const sleep = (ms: number, signal?: AbortSignal | null): Promise => @@ -29,7 +40,15 @@ const sleep = (ms: number, signal?: AbortSignal | null): Promise => signal?.addEventListener('abort', onAbort, { once: true }); }); -const defaultTiming: RetryTiming = { sleep, random: Math.random }; +/** + * The timing every retry uses unless given its own. Shared and mutable so tests can replace + * the clock and the waits of a whole toolset call, deadline included. + */ +export const retryTiming: RetryTiming = { + sleep, + random: () => Math.random(), + now: () => performance.now(), +}; /** * How long the server asked us to wait, in milliseconds: `Retry-After` as delta-seconds or an @@ -59,13 +78,16 @@ function retryAfterMs(header: string | null): number | undefined { * A 429 means the server refused before doing anything, so even a `tools/call` is safe to send * again. Each retry waits for the response's `Retry-After` (capped at 30s), or else 1s, 2s, 4s * with jitter. Every other status, and the last 429, is handed back as it came: the caller turns - * it into a `StackOneAPIError` with the server's body. The waits run inside the caller's signal, - * so a timeout still bounds the whole exchange. + * it into a `StackOneAPIError` with the server's body. + * + * A wait that would not end before `deadline` is not started: the 429 is handed back at once. + * 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. */ export async function fetchWithRetry( input: string | URL, init?: RequestInit, - timing: RetryTiming = defaultTiming, + { deadline, timing = retryTiming }: RetryOptions = {}, ): Promise { for (let retry = 1; ; retry++) { const response = await fetch(input, init); @@ -77,6 +99,9 @@ export async function fetchWithRetry( requested === undefined ? RATE_LIMIT_BASE_DELAY_MS * 2 ** (retry - 1) * (0.5 + timing.random() * 0.5) : Math.min(requested, RATE_LIMIT_MAX_DELAY_MS); + if (deadline !== undefined && timing.now() + delay >= deadline) { + return response; + } // Discarded unread: only the final 429's body is reported. Not awaited, since a cancel can // wait on a producer that never settles (MSW's, for one), and the retry need not wait. void response.body?.cancel().catch(() => undefined); From 98254a74f8d42c18f8bd116b5ec34a3b351d6d2d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 14:39:26 +0100 Subject: [PATCH 047/151] test(mock): record each tools/call from the raw request body The server's schema parsing rebuilds the arguments and drops a __proto__ key, so a call recorded after it was not the call that was sent. --- mocks/mcp-server.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/mocks/mcp-server.ts b/mocks/mcp-server.ts index 0c679879..7ecdf633 100644 --- a/mocks/mcp-server.ts +++ b/mocks/mcp-server.ts @@ -219,7 +219,6 @@ export function createMcpApp(options: MockMcpServerOptions): HonoApp { mcp.setRequestHandler(CallToolRequestSchema, (request): CallToolResult => { const { name } = request.params; const args = request.params.arguments ?? {}; - onToolCall?.({ accountId, toolMode, name, arguments: structuredClone(args) }); if (!listed.some((tool) => tool.name === name)) { return text({ error: `Unknown tool ${name}`, status_code: 404 }, true); @@ -244,6 +243,21 @@ 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 ?? {} }); + } + } + } + const transport = new StreamableHTTPTransport(); await mcp.connect(transport); return transport.handleRequest(c); From 609e3fcf57602965855ad97c89e2b9eaa35b925e Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 14:39:26 +0100 Subject: [PATCH 048/151] fix(headers): keep a tool argument or header named __proto__ Assigning to clean[key] with the key __proto__ sets the prototype instead, so {"__proto__":"p","constructor":"c","q":1} went out without __proto__. Python sends all three. Every copy in headers.ts now defines its entries as own properties. --- src/headers.test.ts | 40 +++++++++++++++++++++++++++++ src/headers.ts | 23 +++++++++++++---- src/tool.test.ts | 12 +++++++++ src/toolsets.search-execute.test.ts | 18 +++++++++++++ 4 files changed, 88 insertions(+), 5 deletions(-) diff --git a/src/headers.test.ts b/src/headers.test.ts index da10da77..612bbcb1 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -1,9 +1,11 @@ import { + buildRequestHeaders, declaredHeaders, normalizeHeaders, sanitiseHeaderArguments, sanitiseHeaders, } from './headers'; +import type { JsonObject } from './types'; describe('normalizeHeaders', () => { it('returns empty object for undefined input', () => { @@ -243,3 +245,41 @@ describe('sanitiseHeaderArguments', () => { expect(console.warn).not.toHaveBeenCalled(); }); }); + +// 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(), + flat: new Set(), + }); + expect(Object.entries(clean)).toEqual([ + ['__proto__', 'p'], + ['constructor', 'c'], + ['q', 1], + ]); + expect(JSON.stringify(clean)).toBe('{"__proto__":"p","constructor":"c","q":1}'); + }); + + it('is kept by normalizeHeaders and an open sanitiseHeaders', () => { + expect(Object.entries(normalizeHeaders(withProto('"x":1')))).toEqual([ + ['__proto__', 'p'], + ['x', '1'], + ]); + expect(Object.entries(sanitiseHeaders(withProto('"x":"1"'), 'any'))).toEqual([ + ['__proto__', 'p'], + ['x', '1'], + ]); + }); + + it('is kept by buildRequestHeaders', () => { + const headers = buildRequestHeaders({ + apiKey: 'k', + extraHeaders: JSON.parse('{"__proto__":"p"}') as Record, + }); + 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 561246ac..56788f77 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -12,6 +12,19 @@ const SDK_OWNED_HEADERS = ['authorization', 'x-account-id', 'user-agent'] as con const isPlainObject = (value: unknown): value is JsonObject => typeof value === 'object' && value !== null && !Array.isArray(value); +/** + * Set `key` on `target` as an own, enumerable property. Plain assignment with the key + * `__proto__` replaces the prototype instead, so the entry would vanish from the request. + */ +function setEntry(target: Record, key: string, value: T): void { + Object.defineProperty(target, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }); +} + /** Whether a caller-supplied header name is one the SDK owns and will override. */ export function isSdkOwnedHeader(name: string): boolean { return (SDK_OWNED_HEADERS as readonly string[]).includes(name.trim().toLowerCase()); @@ -40,7 +53,7 @@ export function buildRequestHeaders(options: { const headers: Record = {}; for (const [name, value] of Object.entries(options.extraHeaders ?? {})) { if (!isSdkOwnedHeader(name)) { - headers[name] = value; + setEntry(headers, name, value); } } headers['User-Agent'] = USER_AGENT; @@ -77,7 +90,7 @@ export function normalizeHeaders(headers: JsonObject | undefined): Record { }); }); + // `clean[key] = value` with the key `__proto__` sets the prototype, so the argument vanished + // from the request. Python sends it. + it('sends an argument named __proto__ like any other', async () => { + await actionTool().execute('{"__proto__":"p","constructor":"c","q":1}'); + + expect(Object.entries(calls[0]?.arguments ?? {})).toEqual([ + ['__proto__', 'p'], + ['constructor', 'c'], + ['q', 1], + ]); + }); + it('sends flat_prefixed arguments verbatim too', async () => { const args = { path_id: '7', 'headers_x-trace': 't-1' }; await actionTool({ diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 1afb48c9..77e728a8 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -256,6 +256,24 @@ describe('execute()', () => { expect(Object.keys(call?.arguments ?? {}).at(-1)).toBe('action_id'); }); + it('keeps an argument named __proto__ while pinning action_id and session_id', async () => { + const { calls } = serveMock(); + + await newToolSet().execute( + 'mock_list_items', + JSON.parse('{"__proto__":"p","constructor":"c","action_id":"other","q":1}') as JsonObject, + { sessionId: 'real' }, + ); + + expect(Object.entries(calls[0]?.arguments ?? {})).toEqual([ + ['__proto__', 'p'], + ['constructor', 'c'], + ['q', 1], + ['session_id', 'real'], + ['action_id', 'mock_list_items'], + ]); + }); + it('sends no session_id when none is given', async () => { const { calls } = serveMock(); await newToolSet().execute('mock_list_items'); From a8ea52fd5164d343d6bb9e46269b6a0a911c713e Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 14:44:34 +0100 Subject: [PATCH 049/151] feat(types): type execute() and submitFeedback() results as ActionResult ActionResult is the server's { isError: false, result, defenderMetadata?, policyMetadata? } wrapper, with any key it adds kept. A type only: results are returned unchanged. tool.execute() keeps JsonObject, since a *_search_actions tool returns bare JSON and dryRun the call it would send. The migration guide's result snippets now type-check. --- MIGRATION.md | 18 ++++++++++++++---- src/index.ts | 1 + src/tool.ts | 6 ++++-- src/toolsets.test-d.ts | 17 ++++++++++++++++- src/toolsets.ts | 12 +++++++----- src/types.ts | 18 ++++++++++++++++++ 6 files changed, 60 insertions(+), 12 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 26397a89..db79ded2 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -114,16 +114,22 @@ messages.push(message, ...(await tools.executeOpenAIToolCalls(message.tool_calls ## Results -**Every tool returns the server's result as the server wrote it.** For an action, that is `{ isError: false, result, defenderMetadata?, policyMetadata? }`. Search results are bare JSON. This applies to `tool.execute()` and `toolset.execute()` alike. +**Every tool returns the server's result as the server wrote it.** For an action, that is `{ isError: false, result, defenderMetadata?, policyMetadata? }`, exported as the `ActionResult` type. Search results are bare JSON. This applies to `tool.execute()` and `toolset.execute()` alike. + +`toolset.execute()` and `submitFeedback()` are typed as returning `ActionResult`. `tool.execute()` still returns `JsonObject`, because a tool can be a `*_search_actions` meta tool or a `dryRun`: on an action tool, assert `ActionResult`. Either way `result` is the action's own JSON, typed `JsonValue`, so narrow it to read inside it. ```typescript +import type { ActionResult, JsonObject } from '@stackone/ai'; + const tool = (await toolset.fetchTools()).getTool('hibob_list_employees'); +if (!tool) throw new Error('hibob_list_employees is not served'); // 2.x const employees = (await tool.execute({})).data; // 3.0 -const employees = (await tool.execute({})).result.data; +const { result } = (await tool.execute({})) as ActionResult; +const employees = (result as JsonObject).data; ``` A result with `isError` set raises `StackOneAPIError`, with the status from its payload in `statusCode` and the payload in `responseBody`. @@ -138,8 +144,12 @@ if (isBinaryDownloadResult(result)) { } // 3.0 -const { result: link } = await download.execute({ id: 'file-id' }); -// { download_url, expires_at, file: { name, content_type, content_length } } +const { result } = (await download.execute({ id: 'file-id' })) as ActionResult; +const link = result as { + download_url: string; + expires_at: string; + file: { name?: string; content_type?: string; content_length?: number }; +}; const name = path.basename(link.file.name ?? 'download.bin'); // chosen by the provider: keep only the basename writeFileSync(name, Buffer.from(await (await fetch(link.download_url)).arrayBuffer())); ``` diff --git a/src/index.ts b/src/index.ts index 4449d906..b76f5fc3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,7 @@ export { } from './toolsets'; export type { + ActionResult, AISDKToolDefinition, AISDKToolResult, ExecuteConfig, diff --git a/src/tool.ts b/src/tool.ts index 9ec3cf1c..7e2d1de0 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -391,9 +391,11 @@ export class StackOneMcpTool extends StackOneTool { * it, and `Authorization`, `x-account-id` and `User-Agent` never are. A `headers` property * served as an object with no `properties`, as on `*_execute_action`, declares every name. * - * @returns The result as the server wrote it: for an action tool, + * @returns The result as the server wrote it: for an action tool, an `ActionResult`, * `{ isError: false, result, defenderMetadata?, policyMetadata? }`. A file action's `result` - * is the server's single-use `download_url`, not the file. + * is the server's single-use `download_url`, not the file. Typed `JsonObject` rather than + * `ActionResult`, since a `*_search_actions` meta tool returns bare JSON and `dryRun` the + * call it would send: assert `ActionResult` on an action tool. * @throws StackOneError If the arguments are not a JSON object or cannot be encoded as JSON. * @throws StackOneAPIError If the result carries `isError`, with the status from its payload, * or the endpoint answers with an HTTP error. diff --git a/src/toolsets.test-d.ts b/src/toolsets.test-d.ts index eda2cdf7..4028f5fc 100644 --- a/src/toolsets.test-d.ts +++ b/src/toolsets.test-d.ts @@ -1,6 +1,6 @@ import { expectTypeOf } from 'vitest'; import type { StackOneToolSet, StackOneToolSetConfig } from './toolsets'; -import type { JsonObject, SearchResult } from './types'; +import type { ActionResult, JsonObject, JsonValue, SearchResult } from './types'; // Valid configurations - only accountId test('StackOneToolSetConfig accepts only accountId', () => { @@ -53,3 +53,18 @@ test('SearchResult declares the fields the server serves', () => { Parameters[1] >(); }); + +// An action's result is the server's wrapper, typed so `result` needs no cast to reach +test('execute() and submitFeedback() return an ActionResult', () => { + expectTypeOf>().toEqualTypeOf>(); + expectTypeOf>().toEqualTypeOf< + Promise + >(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + // Keys the server adds are kept, and a result is still a JsonObject. + expectTypeOf<{ isError: false; result: null; extra: true }>().toExtend(); + expectTypeOf().toExtend(); +}); diff --git a/src/toolsets.ts b/src/toolsets.ts index aac17a09..3ab5aa75 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -11,6 +11,7 @@ import { type McpToolDefinition, isRateLimitFailure, listMcpTools } from './mcp- import { cloneJson, toolParametersFromInputSchema } from './schema'; import { StackOneMcpTool, type StackOneTool, Tools } from './tool'; import type { + ActionResult, FeedbackCategory, FeedbackRating, FeedbackSource, @@ -837,7 +838,7 @@ export class StackOneToolSet { * @param actionId The action to run, e.g. `linear_list_issues`. * @param args The action's arguments. * @param options.sessionId The `session_id` a search hit carries, to link this call to it. - * @returns The action's result. + * @returns The action's result as the server wrote it: `{ isError: false, result, … }`. * @throws ToolSetConfigError If the arguments are malformed. * @throws ToolSetLoadError If no linked connector serves the action. * @throws StackOneAPIError If the action fails. @@ -846,7 +847,7 @@ export class StackOneToolSet { actionId: string, args?: JsonObject, options: ExecuteActionOptions = {}, - ): Promise { + ): Promise { if (typeof actionId !== 'string' || !actionId) { throw new ToolSetConfigError( `actionId must be a non-empty string, got ${JSON.stringify(actionId) ?? String(actionId)}`, @@ -900,7 +901,8 @@ export class StackOneToolSet { } callArguments.action_id = actionId; - return tool.execute(callArguments); + // `*_execute_action` answers with the action's result wrapper; see ActionResult. + return (await tool.execute(callArguments)) as ActionResult; } /** @@ -930,7 +932,7 @@ export class StackOneToolSet { * or `accountIds` holds an empty id. * @throws ToolSetLoadError If feedback is not enabled for this project. */ - async submitFeedback(options: SubmitFeedbackOptions): Promise { + async submitFeedback(options: SubmitFeedbackOptions): Promise { const { rating, toolNames, feedback, category, sessionId, source = 'model' } = options; if (typeof (toolNames as unknown) === 'string') { throw new ToolSetConfigError( @@ -967,7 +969,7 @@ export class StackOneToolSet { args[key] = value; } } - return tool.execute(args); + return (await tool.execute(args)) as ActionResult; } } diff --git a/src/types.ts b/src/types.ts index eaa3ffea..3a174d9e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -216,6 +216,24 @@ export type SearchResult = JsonObject & { session_id?: string; }; +/** + * What an action returns: the server's own wrapper, as it wrote it. `toolset.execute()` and + * `submitFeedback()` return one; so does `tool.execute()` on an action tool. + * + * A type for what the server sends, not a check: the SDK returns the result unchanged. A result + * with `isError` set never reaches the caller, since it raises `StackOneAPIError` instead. Any + * key the server adds beyond these is kept. + */ +export type ActionResult = JsonObject & { + isError: false; + /** The action's output. A file action's is `{ download_url, expires_at, file }`. */ + result: JsonValue; + /** What StackOne Defender checked, when it ran on this call. */ + defenderMetadata?: JsonObject; + /** The policy decision for this call, when a policy applied. */ + policyMetadata?: JsonObject; +}; + /** The verdict `submitFeedback()` records. */ export type FeedbackRating = 'positive' | 'negative' | 'neutral'; From b80451ec853641bd85f643ab499cb67aa57e1739 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 14:46:50 +0100 Subject: [PATCH 050/151] docs: describe fetchTools() arguments and empty account ids as they now work execute()'s docstring and the README still described the removed flat, prefixed param style; they now use the wording Python adopted. The migration guide warns that an empty accountId throws, including a set but empty STACKONE_ACCOUNT_ID, and the README's dryRun snippet checks getTool(). --- MIGRATION.md | 6 ++++-- README.md | 4 ++-- src/toolsets.ts | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index db79ded2..005f2a53 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -195,10 +195,12 @@ await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' // 2.x: STACKONE_ACCOUNT_ID picked up implicitly const toolset = new StackOneToolSet(); -// 3.0 -const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); +// 3.0: `|| undefined`, so a variable that is set but empty means "discover", not an error +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); ``` +**An empty account id throws.** `accountId: ''`, or an empty string in `accountIds`, `execute.accountIds`, `setAccounts()` or a call's `accountIds`, now throws `ToolSetConfigError`. In 2.x an empty `accountId` fell back to `STACKONE_ACCOUNT_ID` or discovery; in 3.0 that would silently widen the toolset to every active account. So `accountId: process.env.STACKONE_ACCOUNT_ID` throws when the variable is set but empty (`STACKONE_ACCOUNT_ID=` in a `.env` file, for example): pass `process.env.STACKONE_ACCOUNT_ID || undefined`, as above. + **Listings are merged in sorted account order.** When two accounts serve the same tool name, `getTool()` returns the first one listed — now the one on the lowest account id, where 2.x followed the order you passed. A warning names the clashing tools. Pass `accountIds` to choose the account yourself. **`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. An account whose listing fails is skipped with a warning, unless every account fails. diff --git a/README.md b/README.md index fea7fb00..e9b79e73 100644 --- a/README.md +++ b/README.md @@ -306,7 +306,7 @@ const result = await toolset.execute(best.action_id, best.example_request, { }); ``` -- `execute()` takes the nested envelope an action's `example_request` shows: `{ path, query, body }`. (Tools from `fetchTools()` take the flat, prefixed arguments their own schema names, such as `path_id`.) +- `execute()` takes the nested envelope an action's `example_request` shows: `{ path, query, body }`. (A `fetchTools()` tool takes the keys its own served schema names instead: read them from `tool.parameters.properties`.) - The connector is the longest one whose name prefixes the action id, so `browser_linkedin_*` actions are not routed to `browser`. - `action_id` is always the one you pass: an `action_id` inside `args` — for example, one a prompt-injected model put there — is ignored. - Each hit carries the `session_id` of the search that found it, when the server issued one. Pass it back as `sessionId` to link the calls together. @@ -439,7 +439,7 @@ const toolset = new StackOneToolSet(); const tools = await toolset.fetchTools(); const employeeTool = tools.getTool('workday_list_workers'); -const dryRunResult = await employeeTool.execute({ query: { limit: 5 } }, { dryRun: true }); +const dryRunResult = await employeeTool?.execute({ query: { limit: 5 } }, { dryRun: true }); console.log(dryRunResult); // { diff --git a/src/toolsets.ts b/src/toolsets.ts index 3ab5aa75..84e35d59 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -827,8 +827,9 @@ export class StackOneToolSet { * * Always runs through the connector's `*_execute_action` meta tool, so `args` is the nested * envelope every action's `example_request` shows — `{ query: {...}, path: {...}, body: {...} }`. - * The flat, prefixed form belongs to `fetchTools()` tools, whose own served schema names the - * keys. The connector is the longest one whose name prefixes `actionId`, and `actionId` is + * A `fetchTools()` tool takes the keys its own served schema names instead; routing by whether + * an id happened to be in the catalog would make the argument shape depend on something the + * caller cannot see. The connector is the longest one whose name prefixes `actionId`, and `actionId` is * pinned last, so a model-supplied `action_id` in `args` cannot replace it. * * `args.headers` is forwarded to the action: `*_execute_action` serves `headers` as an open From 45917f1be133640d16e2bd95f5ede8ce5321272a Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 15:02:01 +0100 Subject: [PATCH 051/151] fix(schema): keep a schema property named __proto__ when folding root combinators Plain assignment set the prototype, so the model never saw the field. setEntry moves to a shared util. --- src/headers.ts | 14 +------------- src/schema.test.ts | 9 +++++++++ src/schema.ts | 3 ++- src/utils/set-entry.ts | 12 ++++++++++++ 4 files changed, 24 insertions(+), 14 deletions(-) create mode 100644 src/utils/set-entry.ts diff --git a/src/headers.ts b/src/headers.ts index 56788f77..50e8e851 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -1,6 +1,7 @@ import { USER_AGENT } from './consts'; import type { JsonObject, JsonValue } from './types'; import { warn } from './utils/logger'; +import { setEntry } from './utils/set-entry'; /** * Header names the SDK owns. They are applied after every other header is merged, so neither a @@ -12,19 +13,6 @@ const SDK_OWNED_HEADERS = ['authorization', 'x-account-id', 'user-agent'] as con const isPlainObject = (value: unknown): value is JsonObject => typeof value === 'object' && value !== null && !Array.isArray(value); -/** - * Set `key` on `target` as an own, enumerable property. Plain assignment with the key - * `__proto__` replaces the prototype instead, so the entry would vanish from the request. - */ -function setEntry(target: Record, key: string, value: T): void { - Object.defineProperty(target, key, { - value, - enumerable: true, - writable: true, - configurable: true, - }); -} - /** Whether a caller-supplied header name is one the SDK owns and will override. */ export function isSdkOwnedHeader(name: string): boolean { return (SDK_OWNED_HEADERS as readonly string[]).includes(name.trim().toLowerCase()); diff --git a/src/schema.test.ts b/src/schema.test.ts index b63475fa..9ba138b1 100644 --- a/src/schema.test.ts +++ b/src/schema.test.ts @@ -60,6 +60,15 @@ describe('toolParametersFromInputSchema', () => { }); describe('foldRootComposition', () => { + it('keeps a branch property named __proto__', () => { + const schema = 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); + }); + it('leaves a schema without root combinators untouched', () => { const schema: JSONSchema = { type: 'object', properties: { a: { type: 'string' } } }; expect(foldRootComposition(schema)).toBe(schema); diff --git a/src/schema.ts b/src/schema.ts index 3fae0543..d0b61f60 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -6,6 +6,7 @@ * outright — and those adjustments are made on a copy, per adapter, never on the tool itself. */ import type { JSONSchema, JsonSchemaProperties, ToolParameters } from './types'; +import { setEntry } from './utils/set-entry'; const isPlainObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); @@ -87,7 +88,7 @@ export function foldRootComposition(schema: JSONSchema): JSONSchema { } for (const [name, definition] of Object.entries(branch.properties ?? {})) { if (!Object.hasOwn(properties, name)) { - properties[name] = definition; + setEntry(properties, name, definition); } } if (keyword === 'allOf') { diff --git a/src/utils/set-entry.ts b/src/utils/set-entry.ts new file mode 100644 index 00000000..125b6899 --- /dev/null +++ b/src/utils/set-entry.ts @@ -0,0 +1,12 @@ +/** + * Set `key` on `target` as an own, enumerable property. Plain assignment with the key + * `__proto__` replaces the prototype instead, so the entry would vanish from the request. + */ +export function setEntry(target: Record, key: string, value: T): void { + Object.defineProperty(target, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }); +} From b1427f78025935be54054c35976bb65a8467a71a Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 15:12:35 +0100 Subject: [PATCH 052/151] fix(headers): drop non-object header arguments that aren't declared as ordinary fields A top-level headers argument that isn't a plain object is now dropped with a warning unless the served schema declares headers as a non-object field, in which case it is an ordinary argument sent as given. A declared flat headers_ argument whose value is an array or object is dropped too; only a string, number or boolean can be a header value. --- MIGRATION.md | 2 ++ README.md | 2 ++ src/headers.test.ts | 61 +++++++++++++++++++++++++++++++++++++++++++-- src/headers.ts | 38 ++++++++++++++++++++++++---- 4 files changed, 96 insertions(+), 7 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 005f2a53..83818953 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -179,6 +179,8 @@ await tool.execute({ body: { variables: { first: 25 } } }); **Header arguments are allowlisted.** A header argument is an entry of a `headers` object argument, or a top-level `headers_` argument. Each one is forwarded only if the tool's schema declares it in the same form: under `headers.properties`, or as a `headers_` property. An open `headers` object — `type: "object"`, no `properties`, and `additionalProperties` not `false` — declares every name; without `type: "object"`, or with `additionalProperties: false` and no `properties`, it declares none. `Authorization`, `x-account-id` and `User-Agent` are never forwarded, even when declared, because the SDK sets them itself. Anything dropped is logged as a warning. Every other argument is sent unchanged. +A top-level `headers` argument that isn't a plain object is dropped with a warning, unless the schema declares `headers` itself as a non-object field, in which case it's an ordinary argument that happens to be named `headers` and is sent as given. A `headers_` argument is dropped with a warning when its value is an array or object. + `*_execute_action` serves an open `headers` object, so `toolset.execute()` passes your own headers on to the action, with the exception of those three: ```typescript diff --git a/README.md b/README.md index e9b79e73..c2beeacc 100644 --- a/README.md +++ b/README.md @@ -398,6 +398,8 @@ The catalog is cached per account scope and mode, so changing a filter never ref A tool call's header arguments — the entries of a `headers` object argument, and `headers_` arguments — are forwarded only if the tool's served schema declares them: `` under `properties.headers.properties`, or a `headers_` property. A `headers` property served as an open object — `type: "object"`, no `properties`, and `additionalProperties` not `false` — as on every `*_execute_action`, declares any name, so `toolset.execute(id, { headers: { 'x-custom': '…' } })` forwards it. Anything undeclared is dropped with a warning; every other argument is sent unchanged. +A top-level `headers` argument that isn't a plain object is dropped with a warning, unless the served schema declares `headers` itself as a non-object field (for example `type: "string"`), in which case it's an ordinary argument that happens to be named `headers` and is sent as given. A `headers_` argument is dropped with a warning when its value is an array or object — only a string, number or boolean can be a header value. + `Authorization`, `x-account-id` and `User-Agent` are always the SDK's own: they are dropped from header arguments even when declared, and ignored with a warning in the `headers` constructor option, so nothing can replace the credential or run a call against another account. ```typescript diff --git a/src/headers.test.ts b/src/headers.test.ts index 612bbcb1..f4907101 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -83,7 +83,11 @@ describe('declaredHeaders', () => { query_limit: { type: 'number' }, body_headers_x: { type: 'string' }, }), - ).toEqual({ nested: new Set(), flat: new Set(['headers_X-Trace']) }); + ).toEqual({ + nested: new Set(), + flat: new Set(['headers_X-Trace']), + ordinaryHeadersField: false, + }); }); it('reads the nested headers object, lower-cased', () => { @@ -238,12 +242,64 @@ describe('sanitiseHeaderArguments', () => { query_limit: 1, body: { headers: { Authorization: 'kept' }, headers_x: 'kept' }, path_id: 'x', - headers: 'not an object', session_id: 's', }; expect(sanitiseHeaderArguments(args, declared)).toEqual(args); expect(console.warn).not.toHaveBeenCalled(); }); + + it('drops a string headers argument when headers is declared as an object', () => { + expect(sanitiseHeaderArguments({ headers: 'not an object' }, declared)).toEqual({}); + expect(console.warn).toHaveBeenCalledWith( + '[@stackone/ai] Dropping header argument "headers" from a tool call: not an object', + ); + }); + + it('drops an array headers argument when headers is declared as an object', () => { + expect(sanitiseHeaderArguments({ headers: [['x-account-id', 'B']] }, declared)).toEqual({}); + expect(console.warn).toHaveBeenCalledWith( + '[@stackone/ai] Dropping header argument "headers" from a tool call: not an object', + ); + }); + + it('drops a non-object headers argument when no headers property is declared at all', () => { + const noHeadersSchema = declaredHeaders({ 'headers_x-trace': { type: 'string' } }); + expect(sanitiseHeaderArguments({ headers: 'x-account-id: B' }, noHeadersSchema)).toEqual({}); + expect(console.warn).toHaveBeenCalledWith( + '[@stackone/ai] Dropping header argument "headers" from a tool call: not an object', + ); + }); + + it('forwards a string headers argument unchanged when headers is declared as a string field', () => { + const stringHeadersSchema = declaredHeaders({ headers: { type: 'string' } }); + expect(sanitiseHeaderArguments({ headers: 'x-account-id: B' }, stringHeadersSchema)).toEqual({ + headers: 'x-account-id: B', + }); + expect(console.warn).not.toHaveBeenCalled(); + }); + + it('drops an array value on a declared flat headers_ argument', () => { + expect( + sanitiseHeaderArguments({ 'headers_x-trace': ['a\r\nx-account-id: B'] }, declared), + ).toEqual({}); + expect(console.warn).toHaveBeenCalledWith( + '[@stackone/ai] Dropping header argument "headers_x-trace" from a tool call: not a string, number or boolean', + ); + }); + + it('drops an object value on a declared flat headers_ argument', () => { + expect(sanitiseHeaderArguments({ 'headers_x-trace': { nested: 'value' } }, declared)).toEqual( + {}, + ); + expect(console.warn).toHaveBeenCalledWith( + '[@stackone/ai] Dropping header argument "headers_x-trace" from a tool call: not a string, number or boolean', + ); + }); + + it('still drops a null flat headers_ argument silently', () => { + expect(sanitiseHeaderArguments({ 'headers_x-trace': null }, declared)).toEqual({}); + expect(console.warn).not.toHaveBeenCalled(); + }); }); // Assigning to `__proto__` sets the prototype, so each of these once dropped the entry. @@ -254,6 +310,7 @@ describe('an entry named __proto__', () => { const clean = sanitiseHeaderArguments(withProto('"constructor":"c","q":1'), { nested: new Set(), flat: new Set(), + ordinaryHeadersField: false, }); expect(Object.entries(clean)).toEqual([ ['__proto__', 'p'], diff --git a/src/headers.ts b/src/headers.ts index 50e8e851..d37271db 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -112,6 +112,13 @@ export interface DeclaredHeaders { nested: ReadonlySet | 'any'; /** The top-level `headers_` properties, exactly as served. */ flat: ReadonlySet; + /** + * Whether the served schema declares a top-level `headers` property as something other than an + * object — an ordinary field that happens to be named `headers`, not a header container. A + * schema with no `headers` property, or one typed `"object"`, is not ordinary: a non-object + * value sent for it is dropped rather than forwarded. + */ + ordinaryHeadersField: boolean; } /** The header arguments a served tool schema's `properties` declare. */ @@ -120,15 +127,21 @@ export function declaredHeaders(properties: Record): DeclaredHe Object.keys(properties).filter((name) => name.startsWith(FLAT_HEADER_PREFIX)), ); const schema = properties.headers; + const ordinaryHeadersField = + isPlainObject(schema) && typeof schema.type === 'string' && schema.type !== 'object'; if (!isPlainObject(schema)) { - return { nested: new Set(), flat }; + return { nested: new Set(), flat, ordinaryHeadersField }; } if (!('properties' in schema)) { const open = schema.type === 'object' && schema.additionalProperties !== false; - return { nested: open ? 'any' : new Set(), flat }; + return { nested: open ? 'any' : new Set(), flat, ordinaryHeadersField }; } const nestedProperties = isPlainObject(schema.properties) ? schema.properties : {}; - return { nested: new Set(Object.keys(nestedProperties).map((name) => name.toLowerCase())), flat }; + return { + nested: new Set(Object.keys(nestedProperties).map((name) => name.toLowerCase())), + flat, + ordinaryHeadersField, + }; } /** @@ -187,18 +200,33 @@ export function sanitiseHeaders( * A header argument is an entry of a top-level `headers` object, or a top-level * `headers_` argument. Every other argument is returned unchanged. A declared * `headers_` keeps its value as given; nested entries are stringified. + * + * A top-level `headers` argument that isn't a plain object is forwarded unchanged when the + * schema declares `headers` as something other than an object (it's an ordinary field that + * happens to be named `headers`), and dropped otherwise. A flat `headers_` whose value is + * an array or object is dropped too — only a string, number or boolean can be a header value. */ export function sanitiseHeaderArguments(args: JsonObject, declared: DeclaredHeaders): JsonObject { const clean: JsonObject = {}; for (const [key, value] of Object.entries(args)) { - if (key === 'headers' && isPlainObject(value)) { - clean.headers = sanitiseHeaders(value, declared.nested); + if (key === 'headers') { + if (isPlainObject(value)) { + clean.headers = sanitiseHeaders(value, declared.nested); + } else if (declared.ordinaryHeadersField) { + setEntry(clean, key, value); + } else { + warn('Dropping header argument "headers" from a tool call: not an object'); + } continue; } if (!key.startsWith(FLAT_HEADER_PREFIX)) { setEntry(clean, key, value); continue; } + if (isPlainObject(value) || Array.isArray(value)) { + warn(`Dropping header argument "${key}" from a tool call: not a string, number or boolean`); + continue; + } const text = headerText(value); if (text === undefined) { continue; From 04bcd7f8aceca65a05be744d7bf565a74b5415b2 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 15:22:49 +0100 Subject: [PATCH 053/151] ci: pin sdk-conformance to 67103ca --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index f3b8f10e..83ef8e48 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 9d5efab9b6c6fa736e1885e784604d9e05fad7b4 + ref: 67103caab5ec1b547fa9919375ee48dd04e44b75 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From dcd9c8a0600a1711e67c17789c98fa6e336403e0 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 15:39:43 +0100 Subject: [PATCH 054/151] fix(headers): treat array-typed headers field without object as ordinary --- src/headers.test.ts | 35 +++++++++++++++++++++++++++++++++++ src/headers.ts | 12 ++++++++---- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/headers.test.ts b/src/headers.test.ts index f4907101..8535be4e 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -126,6 +126,18 @@ describe('declaredHeaders', () => { expect(declaredHeaders({ headers: { type: 'string' } }).nested).toEqual(new Set()); }); + it('treats an array type without "object" as an ordinary headers field', () => { + expect(declaredHeaders({ headers: { type: ['string', 'null'] } }).ordinaryHeadersField).toBe( + true, + ); + }); + + it('treats an array type that includes "object" as a header container', () => { + expect(declaredHeaders({ headers: { type: ['object', 'null'] } }).ordinaryHeadersField).toBe( + false, + ); + }); + it('treats empty properties as declaring nothing', () => { expect(declaredHeaders({ headers: { type: 'object', properties: {} } }).nested).toEqual( new Set(), @@ -278,6 +290,29 @@ describe('sanitiseHeaderArguments', () => { expect(console.warn).not.toHaveBeenCalled(); }); + it('forwards a string headers argument unchanged when headers is declared as ["string", "null"]', () => { + const nullableStringHeadersSchema = declaredHeaders({ headers: { type: ['string', 'null'] } }); + expect( + sanitiseHeaderArguments({ headers: 'x-account-id: B' }, nullableStringHeadersSchema), + ).toEqual({ headers: 'x-account-id: B' }); + expect(console.warn).not.toHaveBeenCalled(); + }); + + it('sanitises an object headers argument, and drops a string one, when headers is declared as ["object", "null"]', () => { + const nullableObjectHeadersSchema = declaredHeaders({ + headers: { type: ['object', 'null'], properties: { 'x-trace': { type: 'string' } } }, + }); + expect( + sanitiseHeaderArguments({ headers: { 'x-trace': 'abc' } }, nullableObjectHeadersSchema), + ).toEqual({ headers: { 'x-trace': 'abc' } }); + expect( + sanitiseHeaderArguments({ headers: 'x-account-id: B' }, nullableObjectHeadersSchema), + ).toEqual({}); + expect(console.warn).toHaveBeenCalledWith( + '[@stackone/ai] Dropping header argument "headers" from a tool call: not an object', + ); + }); + it('drops an array value on a declared flat headers_ argument', () => { expect( sanitiseHeaderArguments({ 'headers_x-trace': ['a\r\nx-account-id: B'] }, declared), diff --git a/src/headers.ts b/src/headers.ts index d37271db..9a2f7e10 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -114,9 +114,11 @@ export interface DeclaredHeaders { flat: ReadonlySet; /** * Whether the served schema declares a top-level `headers` property as something other than an - * object — an ordinary field that happens to be named `headers`, not a header container. A - * schema with no `headers` property, or one typed `"object"`, is not ordinary: a non-object - * value sent for it is dropped rather than forwarded. + * object — an ordinary field that happens to be named `headers`, not a header container. True + * when `type` is a non-`"object"` string, or an array of types that doesn't include `"object"` + * (e.g. `["string", "null"]`). A schema with no `headers` property, or one whose `type` is or + * includes `"object"`, is not ordinary: a non-object value sent for it is dropped rather than + * forwarded. */ ordinaryHeadersField: boolean; } @@ -128,7 +130,9 @@ export function declaredHeaders(properties: Record): DeclaredHe ); const schema = properties.headers; const ordinaryHeadersField = - isPlainObject(schema) && typeof schema.type === 'string' && schema.type !== 'object'; + isPlainObject(schema) && + ((typeof schema.type === 'string' && schema.type !== 'object') || + (Array.isArray(schema.type) && schema.type.length > 0 && !schema.type.includes('object'))); if (!isPlainObject(schema)) { return { nested: new Set(), flat, ordinaryHeadersField }; } From ba73216b7d48854b26a3071668e2bc789b662c41 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 16:39:49 +0100 Subject: [PATCH 055/151] feat(errors): add ToolArgumentsError A new StackOneError subclass for a tool's arguments being unusable: not JSON, not an object, or not encodable. Not thrown anywhere yet. --- src/index.ts | 1 + src/utils/error-tool-arguments.test.ts | 20 ++++++++++++++++++++ src/utils/error-tool-arguments.ts | 15 +++++++++++++++ src/utils/error-toolset.test.ts | 2 ++ 4 files changed, 38 insertions(+) create mode 100644 src/utils/error-tool-arguments.test.ts create mode 100644 src/utils/error-tool-arguments.ts diff --git a/src/index.ts b/src/index.ts index b76f5fc3..333a67a5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,7 @@ export { BaseTool, StackOneTool, Tools } from './tool'; export { StackOneError } from './utils/error-stackone'; export { StackOneAPIError } from './utils/error-stackone-api'; +export { ToolArgumentsError } from './utils/error-tool-arguments'; export { ToolSetConfigError, ToolSetError, ToolSetLoadError } from './utils/error-toolset'; export { diff --git a/src/utils/error-tool-arguments.test.ts b/src/utils/error-tool-arguments.test.ts new file mode 100644 index 00000000..0dc7a050 --- /dev/null +++ b/src/utils/error-tool-arguments.test.ts @@ -0,0 +1,20 @@ +import { StackOneError } from './error-stackone'; +import { ToolArgumentsError } from './error-tool-arguments'; + +describe('ToolArgumentsError', () => { + it('should create an error with the correct name', () => { + const error = new ToolArgumentsError('Test error'); + expect(error.name).toBe('ToolArgumentsError'); + expect(error.message).toBe('Test error'); + }); + + it('is a StackOneError', () => { + expect(new ToolArgumentsError('x')).toBeInstanceOf(StackOneError); + }); + + it('should support error cause via options', () => { + const cause = new Error('Original error'); + const error = new ToolArgumentsError('Wrapped error', { cause }); + expect(error.cause).toBe(cause); + }); +}); diff --git a/src/utils/error-tool-arguments.ts b/src/utils/error-tool-arguments.ts new file mode 100644 index 00000000..096a1982 --- /dev/null +++ b/src/utils/error-tool-arguments.ts @@ -0,0 +1,15 @@ +import { StackOneError } from './error-stackone'; + +/** + * Raised when a tool's arguments are unusable: not JSON, not an object, or not encodable as + * JSON. + * + * A subclass of {@link StackOneError}, so `catch (e) { if (e instanceof StackOneError) … }` + * still catches it. Thrown before any request is made. + */ +export class ToolArgumentsError extends StackOneError { + constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = 'ToolArgumentsError'; + } +} diff --git a/src/utils/error-toolset.test.ts b/src/utils/error-toolset.test.ts index d95372ae..f531c78e 100644 --- a/src/utils/error-toolset.test.ts +++ b/src/utils/error-toolset.test.ts @@ -1,5 +1,6 @@ import { StackOneAPIError } from './error-stackone-api'; import { StackOneError } from './error-stackone'; +import { ToolArgumentsError } from './error-tool-arguments'; import { ToolSetConfigError, ToolSetError, ToolSetLoadError } from './error-toolset'; describe('error hierarchy', () => { @@ -10,6 +11,7 @@ describe('error hierarchy', () => { ['ToolSetConfigError', new ToolSetConfigError('x')], ['ToolSetLoadError', new ToolSetLoadError('x')], ['StackOneAPIError', new StackOneAPIError('x', 500, null)], + ['ToolArgumentsError', new ToolArgumentsError('x')], ])('%s is a StackOneError', (name, error) => { expect(error).toBeInstanceOf(StackOneError); expect(error.name).toBe(name); From b6de5a0f7f5e8683b48a72e4095f4b272b5e92ec Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 16:40:06 +0100 Subject: [PATCH 056/151] fix(tool): throw ToolArgumentsError for malformed or unencodable arguments Match Python: tool.execute() now throws ToolArgumentsError instead of a plain StackOneError when arguments are invalid JSON, not an object, or cannot be encoded as JSON - including values JSON.stringify previously converted silently (Date, Map, Set, RegExp) or dropped (functions, symbols), bigint, typed arrays and buffers, undefined inside an array, and circular references. The bad value's path is named in the message. --- MIGRATION.md | 8 ++- README.md | 1 + src/tool.test.ts | 73 +++++++++++++++++++++++- src/tool.ts | 145 +++++++++++++++++++++++++++++++++++++++-------- 4 files changed, 201 insertions(+), 26 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 83818953..a94dd4d6 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -95,7 +95,7 @@ const result = await toolset.execute( ); ``` -`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id`, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `execute()` raises rather than returning `{ error }`: `ToolSetConfigError` before any request when `actionId`, `args` or `sessionId` is malformed, `StackOneError` when the arguments cannot be encoded as JSON (NaN or Infinity, for example), `ToolSetLoadError` when no linked connector serves the action, and `StackOneAPIError` when the action fails, including when the server rejects the arguments. +`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id`, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `execute()` raises rather than returning `{ error }`: `ToolSetConfigError` before any request when `actionId`, `args` or `sessionId` is malformed, `ToolArgumentsError` when the arguments cannot be encoded as JSON (NaN or Infinity, a `Date`, a circular reference, for example), `ToolSetLoadError` when no linked connector serves the action, and `StackOneAPIError` when the action fails, including when the server rejects the arguments. To give a model the search and execute tools, set the tool mode on the toolset. `openai()` no longer takes `mode`. @@ -166,6 +166,10 @@ await tool.execute({ id: '1' }, { dryRun: true }); **Arguments are sent as given**, as `tools/call` arguments, except header arguments: each is forwarded only if the tool's schema declares it, and `Authorization`, `x-account-id` and `User-Agent` never are (see below). The SDK no longer splits flat `path_` / `query_` / `body_` keys into an `/actions/rpc` envelope; the server maps them itself. +**Arguments must be JSON values.** `null`, booleans, finite numbers, strings, arrays and plain objects are accepted; a `NaN` or `Infinity`, a `bigint`, a `Date`, `Map`, `Set` or `RegExp`, a function, a symbol, a class instance, a typed array or buffer, or a circular reference, anywhere in the arguments, throws `ToolArgumentsError` naming the path. 2.x let some of these through `JSON.stringify` silently converted (a `Date` to a string, a `Map` to `{}`), which sent the model a value it never supplied. An object property set to `undefined` is still treated as absent; `undefined` inside an array now throws, where 2.x sent it as `null`. + +**Integers above 2^53 are not sent exactly.** JavaScript has already rounded them by the time an argument reaches the SDK, where Python's arbitrary-precision integers reach the server exactly. + **`fetchTools()` tools have the server's own argument shape.** 2.x asked the server for the flat, prefixed style (`?param-style=flat_prefixed`). That request is gone, so the argument names are whatever the server serves for your project. Read them from `tool.parameters.properties` rather than hard-coding them: ```typescript @@ -244,7 +248,7 @@ const tools = (await toolset.fetchTools()).filter( ## Errors -**Every error the SDK throws is a `StackOneError`.** `ToolSetError`, `ToolSetConfigError` and `ToolSetLoadError` extended `Error` in 2.x; they now extend `StackOneError`, alongside `StackOneAPIError`. If you tell them apart with `instanceof`, check the toolset errors first: +**Every error the SDK throws is a `StackOneError`.** `ToolSetError`, `ToolSetConfigError` and `ToolSetLoadError` extended `Error` in 2.x; they now extend `StackOneError`, alongside `StackOneAPIError` and the new `ToolArgumentsError` (thrown when a tool's arguments are not a JSON object, or cannot be encoded as JSON — see [Tool arguments and headers](#tool-arguments-and-headers)). If you tell them apart with `instanceof`, check the toolset errors first: ```typescript try { diff --git a/README.md b/README.md index c2beeacc..a5067476 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,7 @@ const toolset = new StackOneToolSet({ headers: { 'X-Request-Source': 'my-agent' Everything the SDK throws is a `StackOneError`: - `StackOneAPIError` — the API refused a request. Carries `statusCode` and `responseBody`, and its message carries the server's own explanation. A failed MCP `tools/call` raises one too, with the status from its payload and the result's text in the message (`Tool "hibob_get_employee" failed: …`); a dead account surfaces as a `412`. +- `ToolArgumentsError` — a tool's arguments are unusable: not a JSON object, or not encodable as JSON (a `NaN`, a `bigint`, a `Date`, a circular reference, …). Thrown by `tool.execute()` before any request is made. - `ToolSetConfigError` — the toolset was configured, or called, with something it cannot use. - `ToolSetLoadError` — the catalog, or the accounts behind it, could not be loaded. diff --git a/src/tool.test.ts b/src/tool.test.ts index 16440ee2..8f8bd51c 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -9,6 +9,7 @@ import { BaseTool, StackOneMcpTool, StackOneTool, Tools } from './tool'; import type { AISDKToolResult, JsonObject, JSONSchema, ToolParameters } from './types'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; +import { ToolArgumentsError } from './utils/error-tool-arguments'; // Calls an AI SDK tool's `execute` through a plain signature rather than the // `ai` type. v5/v6 expect `ToolCallOptions`, v7 requires an extra `context` @@ -402,7 +403,77 @@ describe('StackOneMcpTool as an action tool', () => { it('rejects a non-object, non-string argument', async () => { // @ts-expect-error - intentionally passing an invalid type - await expect(actionTool().execute(12345)).rejects.toThrow(StackOneError); + await expect(actionTool().execute(12345)).rejects.toThrow(ToolArgumentsError); + }); + + it.each([ + ['a Date', new Date()], + ['a Map', new Map()], + ['a Set', new Set()], + ])('rejects %s as the whole arguments object', async (_name, value) => { + const error = await actionTool() + // @ts-expect-error - intentionally passing a non-plain object + .execute(value) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as Error).message).toMatch(/must be a JSON object/); + expect(calls).toEqual([]); + }); + + // JSON.stringify would silently convert each of these (a Date to a string, a Map or Set to + // `{}`) rather than refuse it, which would send the model a value it never supplied. + it.each([ + ['a Date', { when: new Date() }, 'a Date'], + ['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 symbol', { tag: Symbol('x') }, 'a symbol'], + ['a bigint', { amount: 10n }, 'a bigint'], + ['a Uint8Array', { bytes: new Uint8Array([1]) }, 'binary data'], + ['a class instance', { contact: new StackOneError('x') }, 'an instance of'], + ])( + 'rejects %s nested in the arguments, without calling the server', + async (_name, args, hint) => { + const error = await actionTool() + .execute(args as unknown as JsonObject) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as Error).message).toContain( + `Arguments for "crm_update_contact" could not be encoded as JSON: ${hint}`, + ); + expect(calls).toEqual([]); + }, + ); + + it('rejects undefined inside an array', async () => { + const error = await actionTool() + .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/); + expect(calls).toEqual([]); + }); + + it('rejects a circular reference', async () => { + const body: JsonObject = { name: 'Ada' }; + body.self = body; + + const error = await actionTool() + .execute({ body }) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as Error).message).toMatch(/circular reference/); + expect(calls).toEqual([]); + }); + + it('drops an object property set to undefined, rather than rejecting it', async () => { + 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 () => { diff --git a/src/tool.ts b/src/tool.ts index 7e2d1de0..9bd57998 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -31,6 +31,7 @@ import type { } from './types'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; +import { ToolArgumentsError } from './utils/error-tool-arguments'; import { serializeToolResult } from './utils/serialize'; import { tryImport } from './utils/try-import'; @@ -40,8 +41,21 @@ import { tryImport } from './utils/try-import'; */ type ObjectJSONSchema = OverrideProperties; -const isPlainObject = (value: unknown): value is JsonObject => - typeof value === 'object' && value !== null && !Array.isArray(value); +/** + * A JSON object: a non-null, non-array value whose prototype is `Object.prototype` or `null`. + * + * `typeof value === 'object' && !Array.isArray(value)` alone also accepts a `Date`, `Map`, + * `Set`, `RegExp` or class instance — none of which are JSON objects, and some of which + * `JSON.stringify` would otherwise convert silently (a `Date` to a string, a `Map` to `{}`) + * rather than refuse. + */ +const isPlainObject = (value: unknown): value is JsonObject => { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return false; + } + const prototype: unknown = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +}; /** * Base class for all tools: a name, a description, the served parameter schema, and conversions @@ -317,14 +331,14 @@ export class StackOneTool extends BaseTool { /** * Parse tool arguments: a JSON string, an object, or nothing. * - * @throws StackOneError If the arguments are not a JSON object. + * @throws ToolArgumentsError If the arguments are not a JSON object. */ protected parseArguments(input: JsonObject | string | undefined): JsonObject { if (input === undefined || input === null) { return {}; } if (typeof input !== 'string' && typeof input !== 'object') { - throw new StackOneError( + throw new ToolArgumentsError( `Invalid parameters type for "${this.name}". Expected object or string, got ${typeof input}.`, ); } @@ -333,14 +347,14 @@ export class StackOneTool extends BaseTool { try { parsed = JSON.parse(input); } catch (error) { - throw new StackOneError( + throw new ToolArgumentsError( `Invalid JSON in arguments for "${this.name}": ${error instanceof Error ? error.message : String(error)}`, { cause: error }, ); } } if (!isPlainObject(parsed)) { - throw new StackOneError(`Tool arguments for "${this.name}" must be a JSON object`); + throw new ToolArgumentsError(`Tool arguments for "${this.name}" must be a JSON object`); } return { ...parsed }; } @@ -396,7 +410,8 @@ export class StackOneMcpTool extends StackOneTool { * is the server's single-use `download_url`, not the file. Typed `JsonObject` rather than * `ActionResult`, since a `*_search_actions` meta tool returns bare JSON and `dryRun` the * call it would send: assert `ActionResult` on an action tool. - * @throws StackOneError If the arguments are not a JSON object or cannot be encoded as JSON. + * @throws ToolArgumentsError If the arguments are not a JSON object or cannot be encoded as + * JSON. * @throws StackOneAPIError If the result carries `isError`, with the status from its payload, * or the endpoint answers with an HTTP error. * @throws ToolSetLoadError If the endpoint cannot be reached or does not answer in time. @@ -430,27 +445,111 @@ export class StackOneMcpTool extends StackOneTool { } /** - * Throw if `args` cannot be sent as JSON. NaN and Infinity are not JSON: `JSON.stringify`, and so - * the MCP client, would send them as null. A `bigint` or a cycle would otherwise fail deep inside - * the MCP client and surface as a transport error. Each is an argument problem. + * 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'; + } + if (value instanceof RegExp) { + return 'a RegExp'; + } + if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) { + return 'binary data'; + } + return `an instance of ${(value as object).constructor?.name ?? typeof value}`; +} + +/** + * Walk `value`, throwing if it, or anything nested inside it, is not a JSON value. + * + * Only `null`, booleans, finite numbers, strings, arrays and plain objects are JSON values. + * `JSON.stringify` quietly converts some of what this refuses — a `Date` to a string, a `Map` + * or `Set` to `{}` — rather than refuse it, which would silently send the model a value it + * never supplied. `undefined` is dropped, as `JSON.stringify` drops it from an object, but is + * refused inside an array, where `JSON.stringify` would send it as `null`. * - * @throws StackOneError If any value, however deeply nested, cannot be encoded. + * @throws ToolArgumentsError If `value` is not a JSON value. */ -function assertEncodable(toolName: string, args: JsonObject): void { - try { - JSON.stringify(args, (key, value: unknown) => { - if (typeof value === 'number' && !Number.isFinite(value)) { - throw new TypeError( - `Out of range number values are not JSON compliant: ${value}${key ? ` (at ${JSON.stringify(key)})` : ''}`, +function assertJsonValue(value: unknown, path: string, toolName: string, seen: Set): void { + if (value === null || typeof value === 'boolean' || typeof value === 'string') { + return; + } + if (typeof value === 'number') { + if (!Number.isFinite(value)) { + throw new ToolArgumentsError( + `Arguments for "${toolName}" could not be encoded as JSON: Out of range number values are not JSON compliant: ${value} (at ${JSON.stringify(path)})`, + ); + } + return; + } + if (Array.isArray(value)) { + if (seen.has(value)) { + throw new ToolArgumentsError( + `Arguments for "${toolName}" could not be encoded as JSON: circular reference (at ${JSON.stringify(path)})`, + ); + } + seen.add(value); + value.forEach((item, index) => { + const itemPath = `${path}[${index}]`; + if (item === undefined) { + throw new ToolArgumentsError( + `Arguments for "${toolName}" could not be encoded as JSON: undefined is not a JSON value (at ${JSON.stringify(itemPath)})`, ); } - return value; + assertJsonValue(item, itemPath, toolName, seen); }); - } catch (error) { - throw new StackOneError( - `Arguments for "${toolName}" could not be encoded as JSON: ${error instanceof Error ? error.message : String(error)}`, - { cause: error }, - ); + seen.delete(value); + return; + } + if (isPlainObject(value)) { + if (seen.has(value)) { + throw new ToolArgumentsError( + `Arguments for "${toolName}" could not be encoded as JSON: 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; + } + assertJsonValue(entry, `${path}.${key}`, toolName, seen); + } + seen.delete(value); + return; + } + throw new ToolArgumentsError( + `Arguments for "${toolName}" could not be encoded as JSON: ${describeUnencodableType(value)} is not a JSON value (at ${JSON.stringify(path)})`, + ); +} + +/** + * Throw if `args` cannot be sent as JSON: see {@link assertJsonValue}. + * + * @throws ToolArgumentsError If any value, however deeply nested, is not a JSON value. + */ +function assertEncodable(toolName: string, args: JsonObject): void { + for (const [key, value] of Object.entries(args)) { + if (value === undefined) { + continue; + } + assertJsonValue(value, key, toolName, new Set()); } } From 486e052b1ff6329dec40ddd336d8f59443d1c614 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 16:40:18 +0100 Subject: [PATCH 057/151] fix(toolset): treat a null sessionId as not given Match Python's None: execute() and submitFeedback() now treat sessionId: null the same as sessionId being unset, so no session_id is sent. Other invalid values ('', non-strings) still throw ToolSetConfigError. --- src/toolsets.search-execute.test.ts | 25 +++++++++++++++++++++++++ src/toolsets.ts | 17 ++++++++++------- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 77e728a8..c42f5196 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -280,6 +280,13 @@ describe('execute()', () => { expect(calls[0]?.arguments).toEqual({ action_id: 'mock_list_items' }); }); + // `null` means "not given", matching Python's `None`, rather than being sent as a literal null. + it('treats a null sessionId as not given', async () => { + const { calls } = serveMock(); + await newToolSet().execute('mock_list_items', {}, { sessionId: null }); + expect(calls[0]?.arguments).toEqual({ action_id: 'mock_list_items' }); + }); + it('lets sessionId win over a session_id in the arguments', async () => { const { calls } = serveMock(); await newToolSet().execute( @@ -389,6 +396,11 @@ describe('execute()', () => { () => newToolSet({ accountId: 'acc1' }).execute('x_y', {}, { sessionId: '' }), /sessionId must be a non-empty string/, ], + [ + 'a numeric sessionId', + () => newToolSet({ accountId: 'acc1' }).execute('x_y', {}, { sessionId: 42 as never }), + /sessionId must be a non-empty string/, + ], ])('rejects %s before any round trip', async (_name, act, message) => { await expect(act()).rejects.toThrow(message); await expect(act()).rejects.toBeInstanceOf(ToolSetConfigError); @@ -445,6 +457,19 @@ describe('submitFeedback()', () => { expect(calls[0]?.arguments).toEqual({ rating: 'positive', tool_names: ['a'], source: 'model' }); }); + // `null` means "not given", matching Python's `None`, rather than being sent as a literal null. + it('treats a null sessionId as not given', async () => { + const { calls } = serveMock({ submitFeedback: true }); + + await newToolSet({ accountId: 'acc1' }).submitFeedback({ + rating: 'positive', + toolNames: ['a'], + sessionId: null, + }); + + expect(calls[0]?.arguments).toEqual({ rating: 'positive', tool_names: ['a'], source: 'model' }); + }); + it('works from a search_execute toolset, once across accounts', async () => { const { calls } = serveMock({ accountTools: { acc1: [], acc2: [] }, diff --git a/src/toolsets.ts b/src/toolsets.ts index 84e35d59..d4944884 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -150,9 +150,9 @@ export interface SearchOptions { export interface ExecuteActionOptions { /** * The `session_id` a {@link StackOneToolSet.search} hit carries. Passing it links this call to - * that search server-side. Sent only when given. + * that search server-side. Sent only when given; `null` behaves the same as leaving it unset. */ - sessionId?: string; + sessionId?: string | null; /** Restrict routing to these accounts. Defaults as for {@link StackOneToolSet.search}. */ accountIds?: string[]; } @@ -169,8 +169,11 @@ export interface SubmitFeedbackOptions { feedback?: string; /** What the feedback is about, e.g. `'search'` or `'execute'`. */ category?: FeedbackCategory; - /** The session to attach the feedback to — the `session_id` of a search hit. */ - sessionId?: string; + /** + * The session to attach the feedback to — the `session_id` of a search hit. `null` behaves + * the same as leaving it unset. + */ + sessionId?: string | null; /** Who produced the feedback. Default: `'model'`. */ source?: FeedbackSource; /** @@ -860,7 +863,7 @@ export class StackOneToolSet { ); } const { sessionId } = options; - if (sessionId !== undefined && (typeof sessionId !== 'string' || !sessionId)) { + if (sessionId != null && (typeof sessionId !== 'string' || !sessionId)) { throw new ToolSetConfigError( `sessionId must be a non-empty string, got ${JSON.stringify(sessionId)}`, ); @@ -896,7 +899,7 @@ export class StackOneToolSet { // it an optional string, so an absent key is valid and a null is not. const callArguments: JsonObject = { ...args }; delete callArguments.action_id; - if (sessionId !== undefined) { + if (sessionId != null) { delete callArguments.session_id; callArguments.session_id = sessionId; } @@ -943,7 +946,7 @@ export class StackOneToolSet { if (!Array.isArray(toolNames)) { throw new ToolSetConfigError('toolNames must be an array of tool names'); } - if (sessionId !== undefined && (typeof sessionId !== 'string' || !sessionId)) { + if (sessionId != null && (typeof sessionId !== 'string' || !sessionId)) { throw new ToolSetConfigError( `sessionId must be a non-empty string, got ${JSON.stringify(sessionId)}`, ); From 2be2c5fce20a825dada569ea27efa692da0d40d2 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Thu, 1 Oct 2026 16:48:12 +0100 Subject: [PATCH 058/151] fix(toolsets): treat an empty baseUrl or STACKONE_BASE_URL as unset, as Python does With ??, an empty value was used verbatim and every request went to a hostless URL. --- src/toolsets.test.ts | 25 +++++++++++++++++++++++++ src/toolsets.ts | 7 +++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 5268b7f3..d3930797 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -382,6 +382,31 @@ describe('listing', () => { expect(listMock.mock.calls[0]?.[0].endpoint).toBe('https://api.example.com/mcp'); }); + it.each([ + [ + 'the baseUrl option', + { baseUrl: 'https://option.example.com' }, + 'https://env.example.com', + 'https://option.example.com/mcp', + ], + ['STACKONE_BASE_URL', {}, 'https://env.example.com', 'https://env.example.com/mcp'], + ['the default', {}, undefined, 'https://api.stackone.com/mcp'], + [ + 'STACKONE_BASE_URL when baseUrl is empty', + { baseUrl: '' }, + 'https://env.example.com', + 'https://env.example.com/mcp', + ], + ['the default when both are empty', { baseUrl: '' }, '', 'https://api.stackone.com/mcp'], + ])('lists from %s', async (_name, config, env, endpoint) => { + fakeListing(() => []); + vi.stubEnv('STACKONE_BASE_URL', env); + await new StackOneToolSet({ apiKey: 'test-key', ...config }).fetchTools({ + accountIds: ['acc1'], + }); + expect(listMock.mock.calls[0]?.[0].endpoint).toBe(endpoint); + }); + it('passes the timeout to every listing', async () => { fakeListing(() => []); await newToolSet({ timeout: 1234 }).fetchTools({ accountIds: ['a', 'b'] }); diff --git a/src/toolsets.ts b/src/toolsets.ts index d4944884..188b4895 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -73,7 +73,10 @@ export interface ExecuteToolsConfig { interface StackOneToolSetBaseConfig { /** API key. Defaults to the `STACKONE_API_KEY` environment variable. */ apiKey?: string; - /** Defaults to `STACKONE_BASE_URL`, then `https://api.stackone.com`. */ + /** + * Defaults to `STACKONE_BASE_URL`, then `https://api.stackone.com`. An empty value counts as + * unset, as in Python, so an empty variable falls through rather than producing hostless URLs. + */ baseUrl?: string; /** * Extra HTTP headers sent with every request. `Authorization`, `x-account-id` and @@ -365,7 +368,7 @@ export class StackOneToolSet { } this.#apiKey = apiKey; - this.#baseUrl = config.baseUrl ?? process.env.STACKONE_BASE_URL ?? DEFAULT_BASE_URL; + this.#baseUrl = 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.#toolMode = config.toolMode; From 4de520f15be6bac6560ff87b5dc10dbf8040ceb4 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 09:44:43 +0100 Subject: [PATCH 059/151] fix(retry): read a Retry-After date strictly, as an RFC 9110 HTTP-date in GMT Date.parse read asctime and zone-less dates in the host's local time, rolled 30 February over to 2 March, and read five-digit years. Parse the three HTTP-date forms exactly, as Python does: GMT always, real calendar dates only, a leap second allowed, and RFC 850's two-digit year placed by RFC 9110's 50-year rule against now. The delay and the deadline decision move into their own functions. --- src/utils/fetch-retry.test.ts | 50 ++++++++++++- src/utils/fetch-retry.ts | 135 ++++++++++++++++++++++++++++++---- 2 files changed, 168 insertions(+), 17 deletions(-) diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index df8cff08..143b7f87 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -1,7 +1,7 @@ import { http, HttpResponse, type JsonBodyType } from 'msw'; import { TEST_BASE_URL } from '../../mocks/constants'; import { server } from '../../mocks/node'; -import { fetchWithRetry } from './fetch-retry'; +import { fetchWithRetry, retryAfterMs } from './fetch-retry'; const url = `${TEST_BASE_URL}/limited`; @@ -169,6 +169,54 @@ describe('fetchWithRetry', () => { }); }); + describe('retryAfterMs', () => { + const now = Date.parse('2026-10-01T12:00:00Z'); + + // Each form is GMT, whatever the host's time zone: Date.parse read asctime and a + // zone-less IMF date as local time. + it.each([ + ['IMF-fixdate', 'Thu, 01 Oct 2026 12:00:30 GMT', 30_000], + ['asctime', 'Thu Oct 1 12:00:45 2026', 45_000], + ['RFC 850', 'Thursday, 01-Oct-26 12:01:00 GMT', 60_000], + ['a leap second', 'Thu, 01 Oct 2026 12:00:60 GMT', 60_000], + ['a mismatched weekday', 'Mon, 01 Oct 2026 12:00:10 GMT', 10_000], + ])('reads %s', (_form, value, expected) => { + expect(retryAfterMs(value, now)).toBe(expected); + }); + + // RFC 9110 §5.6.7: a two-digit year more than 50 years ahead is in the previous century. + it.each([ + ['60', 'Friday, 01-Oct-60 12:00:00 GMT', '2060-10-01T12:00:00Z'], + ['75', 'Tuesday, 31-Dec-75 23:59:59 GMT', '2075-12-31T23:59:59Z'], + ['76', 'Thursday, 01-Oct-76 12:00:00 GMT', '1976-10-01T12:00:00Z'], + ])('reads the RFC 850 year %s against now', (_year, value, expected) => { + expect(retryAfterMs(value, Date.parse('2026-01-01T00:00:00Z'))).toBe( + Math.max(0, Date.parse(expected) - Date.parse('2026-01-01T00:00:00Z')), + ); + }); + + it.each([ + ['a missing zone', 'Thu, 01 Oct 2026 12:00:30'], + ['trailing text', 'Thu, 01 Oct 2026 12:00:30 GMT garbage'], + ['30 February', 'Mon, 30 Feb 2026 12:00:00 GMT'], + ['29 February in a common year', 'Sun, 29 Feb 2026 12:00:00 GMT'], + ['a five-digit year', 'Fri, 01 Oct 10000 12:00:00 GMT'], + ['year 0', 'Sat, 01 Jan 0000 12:00:00 GMT'], + ['a numeric zone', 'Thu, 01 Oct 2026 13:00:30 +0100'], + ['a two-digit IMF year', 'Thu, 01 Oct 26 12:00:30 GMT'], + ['second 61', 'Thu, 01 Oct 2026 12:00:61 GMT'], + ['a lower-case weekday', 'thu, 01 Oct 2026 12:00:30 GMT'], + ])('refuses %s', (_problem, value) => { + expect(retryAfterMs(value, now)).toBeUndefined(); + }); + + it('reads 29 February in a leap year', () => { + expect(retryAfterMs('Tue, 29 Feb 2028 00:00:00 GMT', now)).toBe( + Date.parse('2028-02-29T00:00:00Z') - now, + ); + }); + }); + describe('without Retry-After', () => { it('backs off 1s, 2s, 4s, scaled by jitter of at least 0.5', async () => { respondWith(limited()); diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index ca35d651..1723b342 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -50,11 +50,97 @@ export const retryTiming: RetryTiming = { now: () => performance.now(), }; +// The three HTTP-date forms of RFC 9110 §5.6.7, exactly: case-sensitive, single spaces, GMT only. +const WEEKDAY = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)'; +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +const MONTH = `(?${MONTHS.join('|')})`; +const TIME = '(?\\d{2}):(?\\d{2}):(?\\d{2})'; + +/** `Sun, 06 Nov 1994 08:49:37 GMT`: RFC 9110's preferred form. */ +const IMF_FIXDATE = new RegExp(`^${WEEKDAY}, (?\\d{2}) ${MONTH} (?\\d{4}) ${TIME} GMT$`); +/** `Sunday, 06-Nov-94 08:49:37 GMT`: obsolete, with a two-digit year. */ +const RFC850_DATE = new RegExp( + `^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?\\d{2})-${MONTH}-(?\\d{2}) ${TIME} GMT$`, +); +/** `Sun Nov 6 08:49:37 1994`: obsolete, C's asctime(), always GMT. */ +const ASCTIME_DATE = new RegExp( + `^${WEEKDAY} ${MONTH} (? \\d|\\d{2}) ${TIME} (?\\d{4})$`, +); + +const isLeapYear = (year: number): boolean => + (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + +const daysInMonth = (year: number, month: number): number => + [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] ?? 0; + +/** A UTC time as milliseconds since the epoch. `setUTCFullYear`, as `Date.UTC` reads 0–99 as 19xx. */ +function utcTime( + year: number, + month: number, + day: number, + h: number, + m: number, + s: number, +): number { + const date = new Date(0); + date.setUTCFullYear(year, month, day); + date.setUTCHours(h, m, s, 0); + return date.getTime(); +} + +/** `time` moved by whole years; 29 February lands on the 28th in a common year. */ +function addYears(time: number, years: number): number { + const date = new Date(time); + const year = date.getUTCFullYear() + years; + const day = Math.min(date.getUTCDate(), daysInMonth(year, date.getUTCMonth())); + date.setUTCFullYear(year, date.getUTCMonth(), day); + return date.getTime(); +} + +/** + * Read an RFC 9110 HTTP-date as a time in milliseconds, or undefined if it is not one. + * + * Strict, unlike `Date.parse`, which reads a zone-less date in the host's local time, rolls + * 30 February over to 2 March and accepts trailing text. All three forms are always GMT. The + * weekday must be present but need not match the date, which is what the date means. + */ +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) { + return undefined; + } + const thisYear = new Date(now).getUTCFullYear(); + const year = Number(fields.year) + (rfc850 ? thisYear - (thisYear % 100) : 0); + 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) { + 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 when; +} + /** * How long the server asked us to wait, in milliseconds: `Retry-After` as delta-seconds or an - * HTTP-date. Undefined when the header is absent or unreadable, so the caller backs off instead. + * HTTP-date, read against `now` (milliseconds since the epoch). Undefined when the header is + * absent or unreadable, so the caller backs off instead. Not capped: the caller caps it. */ -function retryAfterMs(header: string | null): number | undefined { +export function retryAfterMs(header: string | null, now: number = Date.now()): number | undefined { const value = header?.trim(); if (!value) { return undefined; @@ -62,16 +148,33 @@ function retryAfterMs(header: string | null): number | undefined { if (/^\d+$/.test(value)) { return Number(value) * 1000; } - // All three HTTP-date forms start with a weekday ("Sun,", "Sunday,", "Sun "). Date.parse - // alone reads "1.5" or "March 1, 2027" as dates, so anything else falls back to the - // backoff, as in Python. - if (!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[, ]/.test(value)) { - return undefined; - } - const date = Date.parse(value); - return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now()); + const date = parseHttpDate(value, now); + return date === undefined ? undefined : Math.max(0, date - now); } +/** + * How long to wait, in milliseconds, before retry number `retry` (1-based) of a 429: its + * `Retry-After` when readable, else 1s, 2s, 4s jittered by `random()` into [50%, 100%); capped + * at 30s either way. + */ +function rateLimitDelayMs( + retry: number, + retryAfter: number | undefined, + random: () => number, +): number { + const delay = retryAfter ?? RATE_LIMIT_BASE_DELAY_MS * 2 ** (retry - 1) * (0.5 + random() * 0.5); + return Math.min(delay, RATE_LIMIT_MAX_DELAY_MS); +} + +/** + * Whether a retry's wait ends before the deadline, `remaining` milliseconds away. An equal wait + * does not: the caller's timeout would fire as the retry starts. + */ +const waitsForRetry = (delay: number, remaining: number): boolean => delay < remaining; + +/** Seconds rounded half up to two decimals and written as a number: `0`, `0.75`, `1.5`. */ +const formatSeconds = (ms: number): string => String(Math.floor((ms / 1000) * 100 + 0.5) / 100); + /** * `fetch`, retried on HTTP 429. * @@ -94,12 +197,12 @@ export async function fetchWithRetry( if (response.status !== 429 || retry > RATE_LIMIT_MAX_RETRIES) { return response; } - const requested = retryAfterMs(response.headers.get('retry-after')); - const delay = - requested === undefined - ? RATE_LIMIT_BASE_DELAY_MS * 2 ** (retry - 1) * (0.5 + timing.random() * 0.5) - : Math.min(requested, RATE_LIMIT_MAX_DELAY_MS); - if (deadline !== undefined && timing.now() + delay >= deadline) { + const delay = rateLimitDelayMs( + retry, + retryAfterMs(response.headers.get('retry-after')), + timing.random, + ); + if (deadline !== undefined && !waitsForRetry(delay, deadline - timing.now())) { return response; } // Discarded unread: only the final 429's body is reported. Not awaited, since a cancel can From 56f8e2a841945f5a347aa2a3ad5a186feb117789 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 09:44:43 +0100 Subject: [PATCH 060/151] fix(headers): open a headers schema typed ["object", "null"], and treat type [] as ordinary A type list that includes "object" is an object type: with no properties, the schema is open and declares every name, as with type "object". An empty type list includes no object type, so headers is an ordinary field and its value is forwarded. Both as in Python. --- src/headers.test.ts | 17 +++++++++++++++++ src/headers.ts | 21 +++++++++++---------- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/src/headers.test.ts b/src/headers.test.ts index 8535be4e..98bd902f 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -290,6 +290,23 @@ describe('sanitiseHeaderArguments', () => { expect(console.warn).not.toHaveBeenCalled(); }); + it('opens headers declared as ["object", "null"] with no properties', () => { + const nullableObjectSchema = declaredHeaders({ headers: { type: ['object', 'null'] } }); + expect(nullableObjectSchema.nested).toBe('any'); + expect(sanitiseHeaderArguments({ headers: { 'x-custom': 'a' } }, nullableObjectSchema)).toEqual( + { headers: { 'x-custom': 'a' } }, + ); + expect(console.warn).not.toHaveBeenCalled(); + }); + + it('forwards a string headers argument unchanged when headers is typed []', () => { + const emptyTypeSchema = declaredHeaders({ headers: { type: [] } }); + expect(sanitiseHeaderArguments({ headers: 'abc' }, emptyTypeSchema)).toEqual({ + headers: 'abc', + }); + expect(console.warn).not.toHaveBeenCalled(); + }); + it('forwards a string headers argument unchanged when headers is declared as ["string", "null"]', () => { const nullableStringHeadersSchema = declaredHeaders({ headers: { type: ['string', 'null'] } }); expect( diff --git a/src/headers.ts b/src/headers.ts index 9a2f7e10..aa86fcd9 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -105,9 +105,10 @@ const FLAT_HEADER_PREFIX = 'headers_'; export interface DeclaredHeaders { /** * Names declared under the nested `headers` object, lower-cased, or `'any'` when `headers` is - * an open map, as on `*_execute_action`: `type: "object"`, no `properties` key, and - * `additionalProperties` anything but `false`. A schema without `type: "object"`, or one that - * closes `additionalProperties` without listing `properties`, declares no names. + * an open map, as on `*_execute_action`: `type: "object"` (or a type list that includes + * `"object"`, such as `["object", "null"]`), no `properties` key, and `additionalProperties` + * anything but `false`. A schema not typed as an object, or one that closes + * `additionalProperties` without listing `properties`, declares no names. */ nested: ReadonlySet | 'any'; /** The top-level `headers_` properties, exactly as served. */ @@ -116,7 +117,7 @@ export interface DeclaredHeaders { * Whether the served schema declares a top-level `headers` property as something other than an * object — an ordinary field that happens to be named `headers`, not a header container. True * when `type` is a non-`"object"` string, or an array of types that doesn't include `"object"` - * (e.g. `["string", "null"]`). A schema with no `headers` property, or one whose `type` is or + * (e.g. `["string", "null"]`, or `[]`). A schema with no `headers` property, or one whose `type` is or * includes `"object"`, is not ordinary: a non-object value sent for it is dropped rather than * forwarded. */ @@ -129,15 +130,15 @@ export function declaredHeaders(properties: Record): DeclaredHe Object.keys(properties).filter((name) => name.startsWith(FLAT_HEADER_PREFIX)), ); const schema = properties.headers; - const ordinaryHeadersField = - isPlainObject(schema) && - ((typeof schema.type === 'string' && schema.type !== 'object') || - (Array.isArray(schema.type) && schema.type.length > 0 && !schema.type.includes('object'))); if (!isPlainObject(schema)) { - return { nested: new Set(), flat, ordinaryHeadersField }; + 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; if (!('properties' in schema)) { - const open = schema.type === 'object' && schema.additionalProperties !== false; + const open = objectTyped && schema.additionalProperties !== false; return { nested: open ? 'any' : new Set(), flat, ordinaryHeadersField }; } const nestedProperties = isPlainObject(schema.properties) ? schema.properties : {}; From bb21398780ae873744d1daffbd6847f8f6e125c7 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 09:45:02 +0100 Subject: [PATCH 061/151] fix(tool): refuse a lone surrogate in tool arguments A string or key holding half a surrogate pair, which a model emits when a token boundary splits an emoji, is not Unicode text and cannot be sent as UTF-8. JSON.stringify escaped it and sent it; it is now a ToolArgumentsError, as in Python. A non-finite number is reported as "NaN is not a JSON number", the wording shared with Python. JSON text holding NaN or Infinity is invalid JSON, which the tests now pin. --- src/tool.test.ts | 58 +++++++++++++++++++++++++++++++++++++++----- src/tool.ts | 63 ++++++++++++++++++++++++++++++++++++------------ 2 files changed, 100 insertions(+), 21 deletions(-) diff --git a/src/tool.test.ts b/src/tool.test.ts index 8f8bd51c..0f1397ff 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -386,17 +386,25 @@ describe('StackOneMcpTool as an action tool', () => { // JSON.stringify, and so the MCP client, would send each of these as null. it.each([ - ['NaN at the top level', { amount: Number.NaN }], - ['Infinity nested in an object', { body: { name: 'Ada', score: Number.POSITIVE_INFINITY } }], - ['-Infinity nested in an array', { query: { ids: [1, Number.NEGATIVE_INFINITY] } }], - ])('rejects %s without calling the server', async (_name, args) => { + ['NaN at the top level', { amount: Number.NaN }, 'NaN'], + [ + 'Infinity nested in an object', + { body: { name: 'Ada', score: Number.POSITIVE_INFINITY } }, + 'Infinity', + ], + [ + '-Infinity nested in an array', + { query: { ids: [1, Number.NEGATIVE_INFINITY] } }, + '-Infinity', + ], + ])('rejects %s without calling the server', async (_name, args, value) => { const error = await actionTool() .execute(args as JsonObject) .catch((caught: unknown) => caught); expect(error).toBeInstanceOf(StackOneError); - expect((error as Error).message).toMatch( - /^Arguments for "crm_update_contact" could not be encoded as JSON: Out of range number values are not JSON compliant/, + expect((error as Error).message).toBe( + `Arguments for "crm_update_contact" could not be encoded as JSON: ${value} is not a JSON number`, ); expect(calls).toEqual([]); }); @@ -448,6 +456,44 @@ describe('StackOneMcpTool as an action tool', () => { }, ); + // What a model emits when a token boundary splits an emoji: not Unicode text, so not UTF-8. + it.each([ + ['a lone high surrogate in a value', { name: 'Ada\uD83D' }], + ['a lone low surrogate nested in an array', { query: { ids: ['\uDE00x'] } }], + ['a lone surrogate in a key', { body: { '\uD800': 'x' } }], + ['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) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as 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([]); + }); + + it('accepts a surrogate pair', async () => { + await actionTool().execute({ name: 'Ada \uD83D\uDE00' }); + expect(calls).toHaveLength(1); + }); + + it.each([['{"a": NaN}'], ['NaN'], ['{"a": Infinity}']])( + 'rejects the JSON text %s as invalid JSON', + async (text) => { + const error = await actionTool() + .execute(text) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as 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() .execute({ query: { ids: [1, undefined, 3] } } as unknown as JsonObject) diff --git a/src/tool.ts b/src/tool.ts index 9bd57998..00943535 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -475,6 +475,19 @@ function describeUnencodableType(value: unknown): string { return `an instance of ${(value as object).constructor?.name ?? typeof value}`; } +/** A ToolArgumentsError for arguments that cannot be encoded as JSON. */ +const unencodable = (toolName: string, detail: string): ToolArgumentsError => + new ToolArgumentsError( + `Arguments for ${JSON.stringify(toolName)} could not be encoded as JSON: ${detail}`, + ); + +/** + * A UTF-16 surrogate without its other half: what a model emits when a token boundary splits an + * emoji. `JSON.stringify` escapes it as `\ud800` rather than refusing it, but it is not Unicode + * text, so it cannot be encoded as UTF-8 — Python refuses it, and so does this. + */ +const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?): void { - if (value === null || typeof value === 'boolean' || typeof value === 'string') { + if (value === null || typeof value === 'boolean') { + 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)})`, + ); + } return; } if (typeof value === 'number') { if (!Number.isFinite(value)) { - throw new ToolArgumentsError( - `Arguments for "${toolName}" could not be encoded as JSON: Out of range number values are not JSON compliant: ${value} (at ${JSON.stringify(path)})`, - ); + throw unencodable(toolName, `${value} is not a JSON number`); } return; } if (Array.isArray(value)) { if (seen.has(value)) { - throw new ToolArgumentsError( - `Arguments for "${toolName}" could not be encoded as JSON: circular reference (at ${JSON.stringify(path)})`, - ); + throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); } seen.add(value); value.forEach((item, index) => { const itemPath = `${path}[${index}]`; if (item === undefined) { - throw new ToolArgumentsError( - `Arguments for "${toolName}" could not be encoded as JSON: undefined is not a JSON value (at ${JSON.stringify(itemPath)})`, + throw unencodable( + toolName, + `undefined is not a JSON value (at ${JSON.stringify(itemPath)})`, ); } assertJsonValue(item, itemPath, toolName, seen); @@ -519,9 +539,7 @@ function assertJsonValue(value: unknown, path: string, toolName: string, seen: S } if (isPlainObject(value)) { if (seen.has(value)) { - throw new ToolArgumentsError( - `Arguments for "${toolName}" could not be encoded as JSON: circular reference (at ${JSON.stringify(path)})`, - ); + throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); } seen.add(value); for (const [key, entry] of Object.entries(value)) { @@ -529,16 +547,30 @@ function assertJsonValue(value: unknown, path: string, toolName: string, seen: S if (entry === undefined) { continue; } + assertJsonKey(key, path, toolName); assertJsonValue(entry, `${path}.${key}`, toolName, seen); } seen.delete(value); return; } - throw new ToolArgumentsError( - `Arguments for "${toolName}" could not be encoded as JSON: ${describeUnencodableType(value)} is not a JSON value (at ${JSON.stringify(path)})`, + throw unencodable( + toolName, + `${describeUnencodableType(value)} is not a JSON value (at ${JSON.stringify(path)})`, ); } +/** + * Throw if an object key holds a lone surrogate. `path` is where the object is, if anywhere. + * + * @throws ToolArgumentsError If the key is not Unicode text. + */ +function assertJsonKey(key: string, path: string | undefined, toolName: string): void { + if (LONE_SURROGATE.test(key)) { + const where = path === undefined ? '' : ` (in ${JSON.stringify(path)})`; + throw unencodable(toolName, `a key holding a lone surrogate is not Unicode text${where}`); + } +} + /** * Throw if `args` cannot be sent as JSON: see {@link assertJsonValue}. * @@ -549,6 +581,7 @@ function assertEncodable(toolName: string, args: JsonObject): void { if (value === undefined) { continue; } + assertJsonKey(key, undefined, toolName); assertJsonValue(value, key, toolName, new Set()); } } From 259d0c998796601da0f8dd8336f8dc14fe408a1c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 09:45:02 +0100 Subject: [PATCH 062/151] fix(toolsets): treat accountIds: null as not given In the constructor, setAccounts, fetchTools, search, execute and submitFeedback, as Python treats account_ids=None. Any other non-list is still refused. --- src/toolsets.search-execute.test.ts | 15 ++++++++ src/toolsets.test-d.ts | 6 ++-- src/toolsets.ts | 56 ++++++++++++++++++----------- 3 files changed, 54 insertions(+), 23 deletions(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index c42f5196..5acb223c 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -539,6 +539,21 @@ describe('submitFeedback()', () => { ); }); + it('treats accountIds: null as not given in search, execute and submitFeedback', async () => { + const { calls } = serveMock({ submitFeedback: true }); + const toolset = newToolSet({ accountId: 'acc1' }); + + await toolset.search('list items', { accountIds: null }); + await toolset.execute('mock_list_items', {}, { accountIds: null }); + await toolset.submitFeedback({ rating: 'positive', toolNames: ['a'], accountIds: null }); + + expect(calls.map((call) => [call.name, call.accountId])).toEqual([ + ['mock_acc1_search_actions', 'acc1'], + ['mock_acc1_execute_action', 'acc1'], + ['stackone_submit_feedback', 'acc1'], + ]); + }); + it('refuses an empty account id rather than switch to another account', async () => { const { calls } = serveMock({ submitFeedback: true }); const error = await newToolSet({ accountId: 'acc1' }) diff --git a/src/toolsets.test-d.ts b/src/toolsets.test-d.ts index 4028f5fc..7e0b1b57 100644 --- a/src/toolsets.test-d.ts +++ b/src/toolsets.test-d.ts @@ -39,9 +39,9 @@ test('accountId is typed as string | undefined', () => { expectTypeOf().toEqualTypeOf(); }); -// Verify accountIds can be string[] or undefined -test('accountIds is typed as string[] | undefined', () => { - expectTypeOf().toEqualTypeOf(); +// Verify accountIds can be string[], null or undefined +test('accountIds is typed as string[] | null | undefined', () => { + expectTypeOf().toEqualTypeOf(); }); // A search hit's served fields are typed, so a caller needs no narrowing to read them diff --git a/src/toolsets.ts b/src/toolsets.ts index 188b4895..35862eb8 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -45,10 +45,11 @@ interface SingleAccountConfig { interface MultipleAccountsConfig { /** * Array of account IDs for filtering tools across multiple accounts - * When provided, tools will be fetched for all specified accounts + * When provided, tools will be fetched for all specified accounts. `null` is the same as + * leaving it unset. * @example ['account-1', 'account-2'] */ - accountIds: string[]; + accountIds: string[] | null; } /** @@ -61,8 +62,8 @@ type AccountConfig = SimplifyDeep + value === null ? 'null' : Array.isArray(value) ? 'array' : typeof 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 === undefined) { + if (accountIds == null) { return; } if (typeof accountIds === 'string') { @@ -378,12 +391,12 @@ export class StackOneToolSet { /** * Set account IDs for filtering tools - * @param accountIds Array of account IDs to filter tools by + * @param accountIds Array of account IDs to filter tools by. `null` clears them, as `[]` does. * @returns This toolset instance for chaining */ - setAccounts(accountIds: string[]): this { + setAccounts(accountIds: string[] | null): this { assertAccountIdList(accountIds, 'accountIds'); - this.#accountIds = [...accountIds]; + this.#accountIds = [...(accountIds ?? [])]; this.clearCatalogCache(); return this; } @@ -415,7 +428,7 @@ export class StackOneToolSet { * const tools = await toolset.openai(); * ``` */ - async openai(options?: { accountIds?: string[] }): Promise> { + async openai(options?: { accountIds?: string[] | null }): Promise> { const tools = await this.fetchTools({ accountIds: options?.accountIds }); return tools.toOpenAI(); } @@ -551,7 +564,7 @@ export class StackOneToolSet { * The accounts a call is scoped to, in the order they were given: the call's own, then the * toolset's, then its single account, then every active account in `GET /accounts` order. */ - async #accountsInOrder(accountIds: string[] | undefined): Promise { + async #accountsInOrder(accountIds: string[] | null | undefined): Promise { assertAccountIdList(accountIds, 'accountIds'); let scope = accountIds?.length ? accountIds : this.#accountIds; if (scope.length === 0 && this.#accountId) { @@ -563,7 +576,7 @@ export class StackOneToolSet { return scope; } - async #resolveAccountScope(accountIds: string[] | undefined): Promise { + 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(); @@ -740,7 +753,10 @@ export class StackOneToolSet { * The mode is passed down rather than switched on the instance, so a concurrent * `fetchTools()` can never read the switched mode and cache meta tools under the wrong key. */ - async #metaTools(suffix: string, accountIds: string[] | undefined): Promise { + async #metaTools( + suffix: string, + accountIds: string[] | null | undefined, + ): Promise { const tools = await this.fetchTools({ accountIds, mode: 'search_execute' }); return tools.getStackOneTools().filter((tool) => tool.name.endsWith(suffix)); } From 222b6688061c02f59060d763cfc505a70793a926 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 09:45:16 +0100 Subject: [PATCH 063/151] fix: align error and warning messages with the Python SDK Adopt the canonical wording of sdk-conformance's vectors/messages.json: names and ids written as JSON, "list" rather than "array", language-neutral advice in place of method and parameter names, JSON type names, the MCP timeout in seconds, and the 429 retry warning numbering the attempt that failed, with its delay in seconds. A non-object argument value that is not a string now gets the same message as any other. --- src/headers.ts | 10 ++++---- src/mcp-client.test.ts | 4 +++- src/mcp-client.ts | 5 ++-- src/rate-limit.test.ts | 6 ++--- src/tool.test.ts | 8 +++++-- src/tool.ts | 15 +++++------- src/toolsets.search-execute.test.ts | 8 ++++--- src/toolsets.test.ts | 36 ++++++++++++++++++++++++----- src/toolsets.ts | 26 ++++++++++----------- src/utils/fetch-retry.test.ts | 9 ++++---- src/utils/fetch-retry.ts | 2 +- 11 files changed, 80 insertions(+), 49 deletions(-) diff --git a/src/headers.ts b/src/headers.ts index aa86fcd9..a1033269 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -191,7 +191,7 @@ export function sanitiseHeaders( const declared = allowed === 'any' || allowed.has(name.toLowerCase()); const reason = refuseHeader(name, value, declared); if (reason) { - warn(`Dropping header "${name}" from a tool call: ${reason}`); + warn(`Dropping header ${JSON.stringify(name)} from a tool call: ${reason}`); continue; } setEntry(clean, name, value); @@ -220,7 +220,7 @@ export function sanitiseHeaderArguments(args: JsonObject, declared: DeclaredHead } else if (declared.ordinaryHeadersField) { setEntry(clean, key, value); } else { - warn('Dropping header argument "headers" from a tool call: not an object'); + warn(`Dropping header argument ${JSON.stringify(key)} from a tool call: not an object`); } continue; } @@ -229,7 +229,9 @@ export function sanitiseHeaderArguments(args: JsonObject, declared: DeclaredHead continue; } if (isPlainObject(value) || Array.isArray(value)) { - warn(`Dropping header argument "${key}" from a tool call: not a string, number or boolean`); + warn( + `Dropping header argument ${JSON.stringify(key)} from a tool call: not a string, number or boolean`, + ); continue; } const text = headerText(value); @@ -238,7 +240,7 @@ export function sanitiseHeaderArguments(args: JsonObject, declared: DeclaredHead } const reason = refuseHeader(key.slice(FLAT_HEADER_PREFIX.length), text, declared.flat.has(key)); if (reason) { - warn(`Dropping header argument "${key}" from a tool call: ${reason}`); + warn(`Dropping header argument ${JSON.stringify(key)} from a tool call: ${reason}`); continue; } setEntry(clean, key, value); diff --git a/src/mcp-client.test.ts b/src/mcp-client.test.ts index 8f9890e0..6508b562 100644 --- a/src/mcp-client.test.ts +++ b/src/mcp-client.test.ts @@ -289,7 +289,9 @@ describe('MCP timeouts', () => { const error = await listMcpTools(silentRequest()).catch((caught: unknown) => caught); expect(error).toBeInstanceOf(ToolSetLoadError); - expect((error as Error).message).toMatch(/timed out after 300ms/); + expect((error as 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 790ad992..8cea71c3 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -77,7 +77,8 @@ export function describeMcpFailure(error: unknown, endpoint: string, timeout: nu error instanceof McpDeadlineError || (error instanceof McpError && error.code === ErrorCode.RequestTimeout) ) { - return new ToolSetLoadError(`MCP request to ${endpoint} timed out after ${timeout}ms`, { + // In seconds, written as a number (0.5s, 60s), as the Python SDK writes it. + return new ToolSetLoadError(`MCP request to ${endpoint} timed out after ${timeout / 1000}s`, { cause: error, }); } @@ -235,7 +236,7 @@ export function parseToolResult(result: Record, name: string): if (result.isError === true) { throw new StackOneAPIError( - `Tool "${name}" failed: ${payload || JSON.stringify(parsed)}`, + `Tool ${JSON.stringify(name)} failed: ${payload || JSON.stringify(parsed)}`, statusOf(parsed), parsed, ); diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts index 1f8bb24c..0af3c0cc 100644 --- a/src/rate-limit.test.ts +++ b/src/rate-limit.test.ts @@ -100,7 +100,7 @@ describe('a 429 that clears on retry', () => { expect(retryWarnings()).toEqual([ expect.stringMatching( new RegExp( - `^\\[@stackone/ai\\] Rate limited \\(429\\) by POST ${TEST_BASE_URL}/mcp; retrying in 0ms \\(attempt 2 of 4\\)$`, + `^\\[@stackone/ai\\] POST ${TEST_BASE_URL}/mcp was rate limited \\(429\\) on attempt 1 of 4; retrying in 0s$`, ), ), ]); @@ -130,7 +130,7 @@ describe('a 429 that clears on retry', () => { expect(await newToolSet().fetchAccounts()).toEqual(mockAccounts); expect(requests).toBe(2); expect(retryWarnings()).toEqual([ - expect.stringContaining(`by GET ${TEST_BASE_URL}/accounts; retrying in 0ms (attempt 2 of 4)`), + `[@stackone/ai] GET ${TEST_BASE_URL}/accounts was rate limited (429) on attempt 1 of 4; retrying in 0s`, ]); }); }); @@ -166,9 +166,9 @@ describe('a 429 that outlasts its retries', () => { expectRateLimited(error); expect(attempts.matched).toBe(4); expect(retryWarnings().map((message) => message.match(/attempt \d of 4/)?.[0])).toEqual([ + 'attempt 1 of 4', 'attempt 2 of 4', 'attempt 3 of 4', - 'attempt 4 of 4', ]); }); diff --git a/src/tool.test.ts b/src/tool.test.ts index 0f1397ff..5d0c91a5 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -77,7 +77,9 @@ const simpleTool = () => describe('BaseTool', () => { it('cannot execute on its own', async () => { await expect(simpleTool().execute({ id: '1' })).rejects.toThrow( - 'Tool "test_tool" has no executor', + new StackOneError( + 'Tool "test_tool" has no executor. Override execute() to run a hand-built tool.', + ), ); }); @@ -411,7 +413,9 @@ describe('StackOneMcpTool as an action tool', () => { it('rejects a non-object, non-string argument', async () => { // @ts-expect-error - intentionally passing an invalid type - await expect(actionTool().execute(12345)).rejects.toThrow(ToolArgumentsError); + await expect(actionTool().execute(12345)).rejects.toThrow( + new ToolArgumentsError('Tool arguments for "crm_update_contact" must be a JSON object'), + ); }); it.each([ diff --git a/src/tool.ts b/src/tool.ts index 00943535..04773cb3 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -101,7 +101,7 @@ export class BaseTool { _options?: ExecuteOptions, ): Promise { throw new StackOneError( - `Tool "${this.name}" has no executor. Override execute() to run a hand-built tool.`, + `Tool ${JSON.stringify(this.name)} has no executor. Override execute() to run a hand-built tool.`, ); } @@ -337,24 +337,21 @@ export class StackOneTool extends BaseTool { if (input === undefined || input === null) { return {}; } - if (typeof input !== 'string' && typeof input !== 'object') { - throw new ToolArgumentsError( - `Invalid parameters type for "${this.name}". Expected object or string, got ${typeof input}.`, - ); - } let parsed: unknown = input; if (typeof input === 'string') { try { parsed = JSON.parse(input); } catch (error) { throw new ToolArgumentsError( - `Invalid JSON in arguments for "${this.name}": ${error instanceof Error ? error.message : String(error)}`, + `Invalid JSON in arguments for ${JSON.stringify(this.name)}: ${error instanceof Error ? error.message : String(error)}`, { cause: error }, ); } } if (!isPlainObject(parsed)) { - throw new ToolArgumentsError(`Tool arguments for "${this.name}" must be a JSON object`); + throw new ToolArgumentsError( + `Tool arguments for ${JSON.stringify(this.name)} must be a JSON object`, + ); } return { ...parsed }; } @@ -714,7 +711,7 @@ export class Tools implements Iterable { if (unsupported) { result = { error: unsupported }; } else if (!tool) { - result = { error: `Unknown tool "${name}"` }; + result = { error: `Unknown tool ${JSON.stringify(name)}` }; } else { try { result = await tool.execute(args); diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 5acb223c..04c6e959 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -360,8 +360,8 @@ describe('execute()', () => { await newToolSet({ accountIds: ['acc2', 'acc1'] }).execute('linear_list_issues'); expect(calls[0]?.tool).toBe('linear_acc1_execute_action'); - expect(String(warnSpy.mock.calls[0]?.[0])).toContain( - '"linear_list_issues" matches 2 connectors (linear_acc1_execute_action, linear_acc2_execute_action)', + expect(String(warnSpy.mock.calls[0]?.[0])).toBe( + '[@stackone/ai] "linear_list_issues" matches 2 connectors (linear_acc1_execute_action, linear_acc2_execute_action); using linear_acc1_execute_action. Pass account ids to choose.', ); }); @@ -572,7 +572,9 @@ describe('submitFeedback()', () => { toolNames: 'a' as never, }), ).rejects.toThrow( - /toolNames must be an array of tool names, not a string. Did you mean \["a"\]\?/, + new ToolSetConfigError( + 'toolNames must be a list of tool names, not a string. Did you mean ["a"]?', + ), ); }); diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index d3930797..452481d2 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -61,7 +61,9 @@ describe('configuration', () => { it('requires an API key', () => { vi.stubEnv('STACKONE_API_KEY', ''); expect(() => new StackOneToolSet()).toThrow(ToolSetConfigError); - expect(() => new StackOneToolSet()).toThrow(/API key must be provided/); + expect(() => new StackOneToolSet()).toThrow( + 'An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable', + ); }); it('reads the API key from STACKONE_API_KEY', async () => { @@ -95,7 +97,29 @@ describe('configuration', () => { ['setAccounts', () => newToolSet().setAccounts('acc1' as never)], ['fetchTools', () => newToolSet().fetchTools({ accountIds: 'acc1' as never })], ])('refuses a string where %s expects a list', async (_name, act) => { - await expect(async () => act()).rejects.toThrow(/not a string. Did you mean \["acc1"\]\?/); + await expect(async () => act()).rejects.toThrow( + new ToolSetConfigError( + 'accountIds must be a list of account ids, not a string. Did you mean ["acc1"]?', + ), + ); + }); + + it.each([ + ['accountIds', () => newToolSet({ accountIds: [1] as never })], + ['setAccounts', () => newToolSet().setAccounts({ id: 'acc1' } as never)], + ['fetchTools', () => newToolSet().fetchTools({ accountIds: 5 as never })], + ])('refuses a non-list or non-string ids in %s', async (_name, act) => { + await expect(async () => act()).rejects.toThrow( + new ToolSetConfigError('accountIds must be a list of account id strings'), + ); + }); + + it('treats accountIds: null as not given', async () => { + const toolset = newToolSet({ accountIds: null }); + expect(names(await toolset.setAccounts(null).fetchTools({ accountIds: null }))).toEqual([ + 'default_tool_1', + 'default_tool_2', + ]); }); it.each([ @@ -273,7 +297,7 @@ describe('account discovery', () => { server.use(http.get(`${TEST_BASE_URL}/accounts`, () => HttpResponse.json([]))); await expect(newToolSet().fetchTools()).rejects.toThrow( new ToolSetConfigError( - 'This API key has no linked accounts. Link one in the StackOne dashboard, or pass accountId explicitly.', + 'This API key has no linked accounts. Link one in the StackOne dashboard, or pass an account id explicitly.', ), ); }); @@ -308,7 +332,7 @@ describe('account discovery', () => { [ 'a non-list body', HttpResponse.json({ results: [{ id: 'a' }] }), - /Unexpected \/accounts response shape: expected a list, got object/, + /^Unexpected \/accounts response shape: expected a list, got object$/, ], [ 'invalid JSON', @@ -723,8 +747,8 @@ describe('duplicate tool names', () => { expect(tools.length).toBe(4); expect((tools.getTool('hibob_list_employees') as StackOneTool).getAccountId()).toBe('a'); - expect(String(warnSpy.mock.calls[0]?.[0])).toContain( - '2 tool name(s) are served by more than one account (hibob_get_employee, hibob_list_employees)', + 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). Looking a tool up by name returns the first one listed — pass account ids to choose.', ); }); diff --git a/src/toolsets.ts b/src/toolsets.ts index 35862eb8..a78397e9 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -297,11 +297,11 @@ const assertAccountIdList = (accountIds: unknown, parameter: string): void => { } if (typeof accountIds === 'string') { throw new ToolSetConfigError( - `${parameter} must be an array of account ids, not a string. Did you mean ["${accountIds}"]?`, + `${parameter} must be a list of account ids, not a string. Did you mean [${JSON.stringify(accountIds)}]?`, ); } if (!Array.isArray(accountIds) || accountIds.some((id) => typeof id !== 'string')) { - throw new ToolSetConfigError(`${parameter} must be an array of account id strings`); + throw new ToolSetConfigError(`${parameter} must be a list of account id strings`); } // An empty id would be sent with no x-account-id, so reject it rather than let the server // answer for an account nobody chose. @@ -369,7 +369,7 @@ export class StackOneToolSet { const apiKey = config.apiKey || process.env.STACKONE_API_KEY; if (!apiKey) { throw new ToolSetConfigError( - 'API key must be provided either through the apiKey option or the STACKONE_API_KEY environment variable', + 'An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable', ); } @@ -478,7 +478,7 @@ export class StackOneToolSet { // Carry the status, so a caller can tell a 401 from a 429. const text = new TextDecoder().decode(bytes).trim(); throw new StackOneAPIError( - `Listing accounts at ${url} failed with ${response.status} ${response.statusText}: ${text}`, + `${`Listing accounts at ${url} failed with ${response.status} ${response.statusText}`.trimEnd()}: ${text}`, response.status, text, ); @@ -498,7 +498,7 @@ export class StackOneToolSet { : body; if (!Array.isArray(accounts)) { throw new ToolSetLoadError( - `Unexpected /accounts response shape: expected a list, got ${accounts === null ? 'null' : typeof accounts}`, + `Unexpected /accounts response shape: expected a list, got ${jsonType(accounts)}`, ); } return accounts as StackOneAccount[]; @@ -544,14 +544,14 @@ export class StackOneToolSet { if (active.length === 0) { if (accounts.length === 0) { throw new ToolSetConfigError( - 'This API key has no linked accounts. Link one in the StackOne dashboard, or pass accountId explicitly.', + 'This API key has no linked accounts. Link one in the StackOne dashboard, or pass an account id explicitly.', ); } const listed = accounts .map((account) => `${String(account?.provider)} (${String(account?.status)})`) .join(', '); throw new ToolSetConfigError( - `None of this API key's ${accounts.length} linked accounts are active: ${listed}. Re-link them in the StackOne dashboard, or pass accountId explicitly.`, + `None of this API key's ${accounts.length} linked accounts are active: ${listed}. Re-link them in the StackOne dashboard, or pass an account id explicitly.`, ); } if (generation === this.#cacheGeneration) { @@ -877,9 +877,7 @@ export class StackOneToolSet { ); } if (args !== undefined && !isPlainObject(args)) { - throw new ToolSetConfigError( - `arguments must be a JSON object, got ${Array.isArray(args) ? 'array' : args === null ? 'null' : typeof args}`, - ); + throw new ToolSetConfigError(`arguments must be a JSON object, got ${jsonType(args)}`); } const { sessionId } = options; if (sessionId != null && (typeof sessionId !== 'string' || !sessionId)) { @@ -895,7 +893,7 @@ export class StackOneToolSet { ); if (matches.length === 0) { throw new ToolSetLoadError( - `No connector found for "${actionId}". Use search() to discover valid action ids.`, + `No connector found for ${JSON.stringify(actionId)}. Use search() to discover valid action ids.`, ); } @@ -908,7 +906,7 @@ export class StackOneToolSet { // The same provider linked twice. Picking one silently would run the action against an // account the caller never chose. warn( - `"${actionId}" matches ${finalists.length} connectors (${finalists.map((t) => t.name).join(', ')}); using ${tool.name}. Pass accountIds to choose.`, + `${JSON.stringify(actionId)} matches ${finalists.length} connectors (${finalists.map((t) => t.name).join(', ')}); using ${tool.name}. Pass account ids to choose.`, ); } @@ -959,7 +957,7 @@ export class StackOneToolSet { const { rating, toolNames, feedback, category, sessionId, source = 'model' } = options; if (typeof (toolNames as unknown) === 'string') { throw new ToolSetConfigError( - `toolNames must be an array of tool names, not a string. Did you mean ["${String(toolNames)}"]?`, + `toolNames must be a list of tool names, not a string. Did you mean [${JSON.stringify(toolNames)}]?`, ); } if (!Array.isArray(toolNames)) { @@ -1013,7 +1011,7 @@ function warnOnDuplicateNames(tools: readonly StackOneTool[]): void { .sort(); if (clashing.length > 0) { warn( - `${clashing.length} tool name(s) are served by more than one account (${clashing.slice(0, 5).join(', ')}). getTool() will return the first one listed — pass accountIds to choose.`, + `${clashing.length} tool name(s) are served by more than one account (${clashing.slice(0, 5).join(', ')}). Looking a tool up by name returns the first one listed — pass account ids to choose.`, ); } } diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index 143b7f87..fbe64953 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -61,7 +61,7 @@ describe('fetchWithRetry', () => { expect(seen.requests).toBe(2); expect(delays).toEqual([2000]); expect(warnSpy.mock.calls.map(([message]: unknown[]) => message)).toEqual([ - `[@stackone/ai] Rate limited (429) by POST ${url}; retrying in 2000ms (attempt 2 of 4)`, + `[@stackone/ai] POST ${url} was rate limited (429) on attempt 1 of 4; retrying in 2s`, ]); }); @@ -146,11 +146,12 @@ describe('fetchWithRetry', () => { expect((await fetchWithRetry(url, undefined, { timing })).status).toBe(200); expect(seen.requests).toBe(2); expect(delays).toEqual([]); - expect(String(warnSpy.mock.calls[0]?.[0])).toContain('retrying in 0ms (attempt 2 of 4)'); + expect(String(warnSpy.mock.calls[0]?.[0])).toBe( + `[@stackone/ai] GET ${url} was rate limited (429) on attempt 1 of 4; retrying in 0s`, + ); }); - // Date.parse reads "1.5" and "2026-10-01" as dates, so only a value shaped like an - // HTTP-date may reach it. Python reads these the same way. + // Only the three RFC 9110 HTTP-date forms are dates. Python reads these the same way. it.each([ 'soon', '1.5', diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index 1723b342..e9252d8f 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -209,7 +209,7 @@ export async function fetchWithRetry( // wait on a producer that never settles (MSW's, for one), and the retry need not wait. void response.body?.cancel().catch(() => undefined); warn( - `Rate limited (429) by ${init?.method ?? 'GET'} ${String(input)}; retrying in ${Math.round(delay)}ms (attempt ${retry + 1} of ${RATE_LIMIT_MAX_RETRIES + 1})`, + `${init?.method ?? 'GET'} ${String(input)} was rate limited (429) on attempt ${retry} of ${RATE_LIMIT_MAX_RETRIES + 1}; retrying in ${formatSeconds(delay)}s`, ); if (delay > 0) { await timing.sleep(delay, init?.signal); From ccf23184cb28d8e88ab602f657270395055d9bf6 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:09:42 +0100 Subject: [PATCH 064/151] feat(retry): warn when a 429 is not retried because the wait would pass the deadline The shared rate-limit-deadline warning, which Python already emits. Before, a 429 handed back early for its deadline was silent: the caller saw the error, but not that a retry had been passed up, or why. --- src/rate-limit.test.ts | 4 +++- src/utils/fetch-retry.test.ts | 4 +++- src/utils/fetch-retry.ts | 8 +++++--- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts index 0af3c0cc..aec8593c 100644 --- a/src/rate-limit.test.ts +++ b/src/rate-limit.test.ts @@ -283,7 +283,9 @@ describe('a 429 whose wait would outlast the timeout', () => { expect((error as StackOneAPIError).statusCode).toBe(429); expect(requests).toBe(1); expect(waits).toEqual([]); - expect(retryWarnings()).toEqual([]); + expect(retryWarnings()).toEqual([ + `[@stackone/ai] GET ${TEST_BASE_URL}/accounts was rate limited (429) on attempt 1 of 4; not retrying, because waiting 3s would pass the deadline`, + ]); }); it('measures the GET /accounts deadline from the first attempt', async () => { diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index fbe64953..bd180a51 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -265,7 +265,9 @@ describe('fetchWithRetry', () => { expect(await response.json()).toEqual({ message: 'too long' }); expect(seen.requests).toBe(1); expect(delays).toEqual([]); - expect(warnSpy).not.toHaveBeenCalled(); + expect(warnSpy.mock.calls.map(([message]: unknown[]) => message)).toEqual([ + `[@stackone/ai] GET ${url} was rate limited (429) on attempt 1 of 4; not retrying, because waiting 3s would pass the deadline`, + ]); }); it('counts every earlier wait against the deadline', async () => { diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index e9252d8f..b99a4e55 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -202,15 +202,17 @@ export async function fetchWithRetry( retryAfterMs(response.headers.get('retry-after')), timing.random, ); + const limited = `${init?.method ?? 'GET'} ${String(input)} was rate limited (429) on attempt ${retry} of ${RATE_LIMIT_MAX_RETRIES + 1}`; if (deadline !== undefined && !waitsForRetry(delay, deadline - timing.now())) { + warn( + `${limited}; not retrying, because waiting ${formatSeconds(delay)}s would pass the deadline`, + ); return response; } // Discarded unread: only the final 429's body is reported. Not awaited, since a cancel can // wait on a producer that never settles (MSW's, for one), and the retry need not wait. void response.body?.cancel().catch(() => undefined); - warn( - `${init?.method ?? 'GET'} ${String(input)} was rate limited (429) on attempt ${retry} of ${RATE_LIMIT_MAX_RETRIES + 1}; retrying in ${formatSeconds(delay)}s`, - ); + warn(`${limited}; retrying in ${formatSeconds(delay)}s`); if (delay > 0) { await timing.sleep(delay, init?.signal); } From 3ce3c0d32b404bd7cb7bc6cedbea45d990280cf2 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:09:42 +0100 Subject: [PATCH 065/151] fix(retry): read a Retry-After date as the shared vectors do An IMF-fixdate with no zone is GMT, a numeric offset is honoured, and a two-digit year is placed by the same 50-year rule as RFC 850's. Trailing text, impossible dates and five-digit years are still unreadable. The unit tests keep only the calendar edges the vectors leave out. --- src/utils/fetch-retry.test.ts | 62 +++++++++-------------------------- src/utils/fetch-retry.ts | 33 +++++++++++++------ 2 files changed, 39 insertions(+), 56 deletions(-) diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index bd180a51..3d28876a 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -151,71 +151,41 @@ describe('fetchWithRetry', () => { ); }); - // Only the three RFC 9110 HTTP-date forms are dates. Python reads these the same way. - it.each([ - 'soon', - '1.5', - '1.5e3', - '-1', - '2026-10-01', - 'March 1, 2027', - 'X, 21 Oct 2015 07:28:00 GMT', - ])('backs off as if absent when unreadable (%s)', async (value) => { - respondWith(limited({ 'Retry-After': value }), ok); - const { delays, timing } = recordedTiming(() => 0); + it.each(['soon', 'March 1, 2027'])( + 'backs off as if absent when unreadable (%s)', + async (value) => { + respondWith(limited({ 'Retry-After': value }), ok); + const { delays, timing } = recordedTiming(() => 0); - await fetchWithRetry(url, undefined, { timing }); + await fetchWithRetry(url, undefined, { timing }); - expect(delays).toEqual([500]); - }); + expect(delays).toEqual([500]); + }, + ); }); + // The shared vectors (src/vectors.test.ts) grade the forms, years and refusals; these are + // the calendar edges they leave out. describe('retryAfterMs', () => { const now = Date.parse('2026-10-01T12:00:00Z'); - // Each form is GMT, whatever the host's time zone: Date.parse read asctime and a - // zone-less IMF date as local time. - it.each([ - ['IMF-fixdate', 'Thu, 01 Oct 2026 12:00:30 GMT', 30_000], - ['asctime', 'Thu Oct 1 12:00:45 2026', 45_000], - ['RFC 850', 'Thursday, 01-Oct-26 12:01:00 GMT', 60_000], - ['a leap second', 'Thu, 01 Oct 2026 12:00:60 GMT', 60_000], - ['a mismatched weekday', 'Mon, 01 Oct 2026 12:00:10 GMT', 10_000], - ])('reads %s', (_form, value, expected) => { - expect(retryAfterMs(value, now)).toBe(expected); + it('reads a leap second as the start of the next minute', () => { + expect(retryAfterMs('Thu, 01 Oct 2026 12:00:60 GMT', now)).toBe(60_000); }); - // RFC 9110 §5.6.7: a two-digit year more than 50 years ahead is in the previous century. - it.each([ - ['60', 'Friday, 01-Oct-60 12:00:00 GMT', '2060-10-01T12:00:00Z'], - ['75', 'Tuesday, 31-Dec-75 23:59:59 GMT', '2075-12-31T23:59:59Z'], - ['76', 'Thursday, 01-Oct-76 12:00:00 GMT', '1976-10-01T12:00:00Z'], - ])('reads the RFC 850 year %s against now', (_year, value, expected) => { - expect(retryAfterMs(value, Date.parse('2026-01-01T00:00:00Z'))).toBe( - Math.max(0, Date.parse(expected) - Date.parse('2026-01-01T00:00:00Z')), + it('reads 29 February in a leap year', () => { + expect(retryAfterMs('Tue, 29 Feb 2028 00:00:00 GMT', now)).toBe( + Date.parse('2028-02-29T00:00:00Z') - now, ); }); it.each([ - ['a missing zone', 'Thu, 01 Oct 2026 12:00:30'], - ['trailing text', 'Thu, 01 Oct 2026 12:00:30 GMT garbage'], - ['30 February', 'Mon, 30 Feb 2026 12:00:00 GMT'], ['29 February in a common year', 'Sun, 29 Feb 2026 12:00:00 GMT'], - ['a five-digit year', 'Fri, 01 Oct 10000 12:00:00 GMT'], ['year 0', 'Sat, 01 Jan 0000 12:00:00 GMT'], - ['a numeric zone', 'Thu, 01 Oct 2026 13:00:30 +0100'], - ['a two-digit IMF year', 'Thu, 01 Oct 26 12:00:30 GMT'], ['second 61', 'Thu, 01 Oct 2026 12:00:61 GMT'], - ['a lower-case weekday', 'thu, 01 Oct 2026 12:00:30 GMT'], ])('refuses %s', (_problem, value) => { expect(retryAfterMs(value, now)).toBeUndefined(); }); - - it('reads 29 February in a leap year', () => { - expect(retryAfterMs('Tue, 29 Feb 2028 00:00:00 GMT', now)).toBe( - Date.parse('2028-02-29T00:00:00Z') - now, - ); - }); }); describe('without Retry-After', () => { diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index b99a4e55..d04a09ab 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -50,14 +50,20 @@ export const retryTiming: RetryTiming = { now: () => performance.now(), }; -// The three HTTP-date forms of RFC 9110 §5.6.7, exactly: case-sensitive, single spaces, GMT only. +// The three HTTP-date forms of RFC 9110 §5.6.7: case-sensitive, single spaces, nothing after. const WEEKDAY = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)'; const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const MONTH = `(?${MONTHS.join('|')})`; const TIME = '(?\\d{2}):(?\\d{2}):(?\\d{2})'; -/** `Sun, 06 Nov 1994 08:49:37 GMT`: RFC 9110's preferred form. */ -const IMF_FIXDATE = new RegExp(`^${WEEKDAY}, (?\\d{2}) ${MONTH} (?\\d{4}) ${TIME} GMT$`); +/** + * `Sun, 06 Nov 1994 08:49:37 GMT`: RFC 9110's preferred form. As the shared vectors read it, a + * two-digit year is read as RFC 850's is, and the zone may be left out (GMT) or written as an + * offset (`+0100`). + */ +const IMF_FIXDATE = new RegExp( + `^${WEEKDAY}, (?\\d{2}) ${MONTH} (?\\d{4}|\\d{2}) ${TIME}(?: (?GMT|[+-]\\d{4}))?$`, +); /** `Sunday, 06-Nov-94 08:49:37 GMT`: obsolete, with a two-digit year. */ const RFC850_DATE = new RegExp( `^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?\\d{2})-${MONTH}-(?\\d{2}) ${TIME} GMT$`, @@ -101,17 +107,19 @@ function addYears(time: number, years: number): number { * Read an RFC 9110 HTTP-date as a time in milliseconds, or undefined if it is not one. * * Strict, unlike `Date.parse`, which reads a zone-less date in the host's local time, rolls - * 30 February over to 2 March and accepts trailing text. All three forms are always GMT. The - * weekday must be present but need not match the date, which is what the date means. + * 30 February over to 2 March, reads five-digit years and accepts trailing text. A date with no + * zone is GMT. The weekday must be present but need not match the date, which is what the date + * means. */ 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) { + const fields = (RFC850_DATE.exec(value) ?? IMF_FIXDATE.exec(value) ?? ASCTIME_DATE.exec(value)) + ?.groups; + if (!fields?.year) { return undefined; } + const twoDigitYear = fields.year.length === 2; const thisYear = new Date(now).getUTCFullYear(); - const year = Number(fields.year) + (rfc850 ? thisYear - (thisYear % 100) : 0); + const year = Number(fields.year) + (twoDigitYear ? thisYear - (thisYear % 100) : 0); const month = MONTHS.indexOf(fields.month ?? ''); const d = Number(fields.day); const h = Number(fields.hour); @@ -122,7 +130,7 @@ function parseHttpDate(value: string, now: number): number | undefined { return undefined; } let when = utcTime(year, month, d, h, m, s); - if (rfc850) { + if (twoDigitYear) { // 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); @@ -132,6 +140,11 @@ function parseHttpDate(value: string, now: number): number | undefined { when = addYears(when, 100); } } + const offset = /^([+-])(\d{2})(\d{2})$/.exec(fields.zone ?? ''); + if (offset) { + const minutes = Number(offset[2]) * 60 + Number(offset[3]); + when -= (offset[1] === '-' ? -1 : 1) * minutes * 60_000; + } return when; } From cc19db06c0e784380d29b284cc92f4718400f82f Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:10:03 +0100 Subject: [PATCH 066/151] test: run the shared sdk-conformance vectors against the SDK tests/vectors is vendored byte for byte from StackOneHQ/sdk-conformance b8c2871 by scripts/sync-vectors.sh, and src/vectors.test.ts runs every case of every file: Retry-After with an injected now, the backoff and the deadline decision, header values, names and arguments with their warnings, argument encoding, account ids, and every shared message through the code that emits it. Unit tests the vectors now cover are removed. retry-after.json's rfc850-year-70 expects 1970, which its own rfc850-year-60, -76 and -77 contradict; it runs as an expected failure until the vector is fixed. --- .oxfmtrc.jsonc | 3 +- scripts/sync-vectors.sh | 22 + src/headers.test.ts | 229 +-- src/tool.test.ts | 29 +- src/toolsets.test.ts | 18 - src/utils/fetch-retry.ts | 4 +- src/vectors.test.ts | 909 +++++++++++ tests/vectors/README.md | 141 ++ tests/vectors/account-ids.json | 198 +++ tests/vectors/argument-encoding.json | 249 +++ tests/vectors/backoff.json | 241 +++ tests/vectors/header-arguments.json | 1366 +++++++++++++++++ tests/vectors/header-names.json | 383 +++++ tests/vectors/header-values.json | 307 ++++ tests/vectors/messages.json | 1021 ++++++++++++ tests/vectors/retry-after.json | 318 ++++ tests/vectors/schema/account-ids.schema.json | 124 ++ .../schema/argument-encoding.schema.json | 140 ++ tests/vectors/schema/backoff.schema.json | 183 +++ .../schema/header-arguments.schema.json | 143 ++ tests/vectors/schema/header-names.schema.json | 109 ++ .../vectors/schema/header-values.schema.json | 133 ++ tests/vectors/schema/messages.schema.json | 203 +++ tests/vectors/schema/retry-after.schema.json | 128 ++ 24 files changed, 6326 insertions(+), 275 deletions(-) create mode 100755 scripts/sync-vectors.sh create mode 100644 src/vectors.test.ts create mode 100644 tests/vectors/README.md create mode 100644 tests/vectors/account-ids.json create mode 100644 tests/vectors/argument-encoding.json create mode 100644 tests/vectors/backoff.json create mode 100644 tests/vectors/header-arguments.json create mode 100644 tests/vectors/header-names.json create mode 100644 tests/vectors/header-values.json create mode 100644 tests/vectors/messages.json create mode 100644 tests/vectors/retry-after.json create mode 100644 tests/vectors/schema/account-ids.schema.json create mode 100644 tests/vectors/schema/argument-encoding.schema.json create mode 100644 tests/vectors/schema/backoff.schema.json create mode 100644 tests/vectors/schema/header-arguments.schema.json create mode 100644 tests/vectors/schema/header-names.schema.json create mode 100644 tests/vectors/schema/header-values.schema.json create mode 100644 tests/vectors/schema/messages.schema.json create mode 100644 tests/vectors/schema/retry-after.schema.json diff --git a/.oxfmtrc.jsonc b/.oxfmtrc.jsonc index b5da1175..d6112824 100644 --- a/.oxfmtrc.jsonc +++ b/.oxfmtrc.jsonc @@ -3,5 +3,6 @@ "useTabs": true, "semi": true, "singleQuote": true, - "ignorePatterns": [".claude/settings.local.json", "CHANGELOG.md"], + // tests/vectors is vendored byte for byte from sdk-conformance: CI diffs it against the source. + "ignorePatterns": [".claude/settings.local.json", "CHANGELOG.md", "tests/vectors/**"], } diff --git a/scripts/sync-vectors.sh b/scripts/sync-vectors.sh new file mode 100755 index 00000000..2ff1cc08 --- /dev/null +++ b/scripts/sync-vectors.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Copy the shared test vectors from a StackOneHQ/sdk-conformance checkout into tests/vectors/, +# byte for byte. Check the checkout out at the commit CI pins (the conformance job in +# .github/workflows/ci.yaml), which fails if the two differ. +# +# Usage: scripts/sync-vectors.sh +set -euo pipefail + +if [ "$#" -ne 1 ]; then + echo "usage: $0 " >&2 + exit 2 +fi +source_dir="$1/vectors" +if [ ! -d "$source_dir" ]; then + echo "$source_dir does not exist" >&2 + exit 1 +fi +target_dir="$(cd "$(dirname "$0")/.." && pwd)/tests/vectors" + +rm -rf "$target_dir" +cp -R "$source_dir" "$target_dir" +echo "Copied $source_dir to $target_dir" diff --git a/src/headers.test.ts b/src/headers.test.ts index 98bd902f..49f06a08 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -75,6 +75,8 @@ describe('normalizeHeaders', () => { }); }); +// The shared vectors (src/vectors.test.ts) grade which headers each served schema declares, +// and what sanitiseHeaderArguments forwards and warns; these test the pieces directly. describe('declaredHeaders', () => { it('reads flat headers_* properties exactly as served, and nothing else', () => { expect( @@ -98,51 +100,6 @@ describe('declaredHeaders', () => { }).nested, ).toEqual(new Set(['x-trace'])); }); - - it('treats a headers object schema with no properties as declaring every name', () => { - expect(declaredHeaders({ headers: { type: 'object' } }).nested).toBe('any'); - }); - - it('treats an open object schema with additionalProperties as declaring every name', () => { - expect( - declaredHeaders({ headers: { type: 'object', additionalProperties: true } }).nested, - ).toBe('any'); - expect( - declaredHeaders({ - headers: { type: 'object', additionalProperties: { type: 'string' } }, - }).nested, - ).toBe('any'); - }); - - it('treats additionalProperties: false with no properties as declaring nothing', () => { - expect( - declaredHeaders({ headers: { type: 'object', additionalProperties: false } }).nested, - ).toEqual(new Set()); - }); - - it('treats a headers schema without type: "object" as declaring nothing', () => { - expect(declaredHeaders({ headers: {} }).nested).toEqual(new Set()); - expect(declaredHeaders({ headers: { additionalProperties: true } }).nested).toEqual(new Set()); - expect(declaredHeaders({ headers: { type: 'string' } }).nested).toEqual(new Set()); - }); - - it('treats an array type without "object" as an ordinary headers field', () => { - expect(declaredHeaders({ headers: { type: ['string', 'null'] } }).ordinaryHeadersField).toBe( - true, - ); - }); - - it('treats an array type that includes "object" as a header container', () => { - expect(declaredHeaders({ headers: { type: ['object', 'null'] } }).ordinaryHeadersField).toBe( - false, - ); - }); - - it('treats empty properties as declaring nothing', () => { - expect(declaredHeaders({ headers: { type: 'object', properties: {} } }).nested).toEqual( - new Set(), - ); - }); }); describe('sanitiseHeaders', () => { @@ -170,188 +127,6 @@ describe('sanitiseHeaders', () => { ), ).toEqual({}); }); - - it.each([' x-trace', 'X-TRACE\t', 'X-Trace'])( - 'matches %j case- and whitespace-insensitively', - (name) => { - expect(sanitiseHeaders({ [name]: 'abc' }, allowed)).toEqual({ [name.trim()]: 'abc' }); - }, - ); - - it.each(['a\r\nEvil: 1', 'trailing\n', 'bad\rvalue', 'nul\u0000byte', 'wide\u0100char'])( - 'drops a declared header whose value is %j', - (value) => { - expect(sanitiseHeaders({ 'X-Trace': value }, allowed)).toEqual({}); - }, - ); - - it('stringifies scalar values and skips nulls', () => { - expect(sanitiseHeaders({ 'x-trace': 42 }, allowed)).toEqual({ 'x-trace': '42' }); - expect(sanitiseHeaders({ 'x-trace': null }, allowed)).toEqual({}); - }); - - it('forwards any name under an open schema, except the ones the SDK owns', () => { - expect( - sanitiseHeaders( - { 'x-custom': 'a', Authorization: 'x', 'X-Account-Id': 'b', 'user-agent': 'c' }, - 'any', - ), - ).toEqual({ 'x-custom': 'a' }); - }); - - it('says why each header was dropped', () => { - sanitiseHeaders({ Authorization: 'x', 'x-other': 'y', 'X-Trace': 'bad\n' }, allowed); - expect(vi.mocked(console.warn).mock.calls.map(([message]) => message)).toEqual([ - '[@stackone/ai] Dropping header "Authorization" from a tool call: set by the SDK', - '[@stackone/ai] Dropping header "x-other" from a tool call: not declared by the schema', - '[@stackone/ai] Dropping header "X-Trace" from a tool call: malformed', - ]); - }); -}); - -describe('sanitiseHeaderArguments', () => { - const declared = declaredHeaders({ - 'headers_x-trace': { type: 'string' }, - 'headers_x-account-id': { type: 'string' }, - headers: { type: 'object', properties: { 'x-nested': { type: 'string' } } }, - }); - - beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); - }); - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('forwards a declared headers_* argument with its value as given', () => { - expect(sanitiseHeaderArguments({ 'headers_x-trace': 7 }, declared)).toEqual({ - 'headers_x-trace': 7, - }); - }); - - it('drops an undeclared headers_* argument', () => { - expect(sanitiseHeaderArguments({ headers_foo: 'bar' }, declared)).toEqual({}); - expect(console.warn).toHaveBeenCalledWith( - '[@stackone/ai] Dropping header argument "headers_foo" from a tool call: not declared by the schema', - ); - }); - - it('drops an SDK-owned headers_* argument even when declared', () => { - expect(sanitiseHeaderArguments({ 'headers_x-account-id': 'victim' }, declared)).toEqual({}); - expect(console.warn).toHaveBeenCalledWith( - '[@stackone/ai] Dropping header argument "headers_x-account-id" from a tool call: set by the SDK', - ); - }); - - it('filters the nested headers object against its own declared names', () => { - expect( - sanitiseHeaderArguments({ headers: { 'x-nested': 'a', 'x-trace': 'b' } }, declared), - ).toEqual({ headers: { 'x-nested': 'a' } }); - }); - - it('passes every other argument through unchanged', () => { - const args = { - query_limit: 1, - body: { headers: { Authorization: 'kept' }, headers_x: 'kept' }, - path_id: 'x', - session_id: 's', - }; - expect(sanitiseHeaderArguments(args, declared)).toEqual(args); - expect(console.warn).not.toHaveBeenCalled(); - }); - - it('drops a string headers argument when headers is declared as an object', () => { - expect(sanitiseHeaderArguments({ headers: 'not an object' }, declared)).toEqual({}); - expect(console.warn).toHaveBeenCalledWith( - '[@stackone/ai] Dropping header argument "headers" from a tool call: not an object', - ); - }); - - it('drops an array headers argument when headers is declared as an object', () => { - expect(sanitiseHeaderArguments({ headers: [['x-account-id', 'B']] }, declared)).toEqual({}); - expect(console.warn).toHaveBeenCalledWith( - '[@stackone/ai] Dropping header argument "headers" from a tool call: not an object', - ); - }); - - it('drops a non-object headers argument when no headers property is declared at all', () => { - const noHeadersSchema = declaredHeaders({ 'headers_x-trace': { type: 'string' } }); - expect(sanitiseHeaderArguments({ headers: 'x-account-id: B' }, noHeadersSchema)).toEqual({}); - expect(console.warn).toHaveBeenCalledWith( - '[@stackone/ai] Dropping header argument "headers" from a tool call: not an object', - ); - }); - - it('forwards a string headers argument unchanged when headers is declared as a string field', () => { - const stringHeadersSchema = declaredHeaders({ headers: { type: 'string' } }); - expect(sanitiseHeaderArguments({ headers: 'x-account-id: B' }, stringHeadersSchema)).toEqual({ - headers: 'x-account-id: B', - }); - expect(console.warn).not.toHaveBeenCalled(); - }); - - it('opens headers declared as ["object", "null"] with no properties', () => { - const nullableObjectSchema = declaredHeaders({ headers: { type: ['object', 'null'] } }); - expect(nullableObjectSchema.nested).toBe('any'); - expect(sanitiseHeaderArguments({ headers: { 'x-custom': 'a' } }, nullableObjectSchema)).toEqual( - { headers: { 'x-custom': 'a' } }, - ); - expect(console.warn).not.toHaveBeenCalled(); - }); - - it('forwards a string headers argument unchanged when headers is typed []', () => { - const emptyTypeSchema = declaredHeaders({ headers: { type: [] } }); - expect(sanitiseHeaderArguments({ headers: 'abc' }, emptyTypeSchema)).toEqual({ - headers: 'abc', - }); - expect(console.warn).not.toHaveBeenCalled(); - }); - - it('forwards a string headers argument unchanged when headers is declared as ["string", "null"]', () => { - const nullableStringHeadersSchema = declaredHeaders({ headers: { type: ['string', 'null'] } }); - expect( - sanitiseHeaderArguments({ headers: 'x-account-id: B' }, nullableStringHeadersSchema), - ).toEqual({ headers: 'x-account-id: B' }); - expect(console.warn).not.toHaveBeenCalled(); - }); - - it('sanitises an object headers argument, and drops a string one, when headers is declared as ["object", "null"]', () => { - const nullableObjectHeadersSchema = declaredHeaders({ - headers: { type: ['object', 'null'], properties: { 'x-trace': { type: 'string' } } }, - }); - expect( - sanitiseHeaderArguments({ headers: { 'x-trace': 'abc' } }, nullableObjectHeadersSchema), - ).toEqual({ headers: { 'x-trace': 'abc' } }); - expect( - sanitiseHeaderArguments({ headers: 'x-account-id: B' }, nullableObjectHeadersSchema), - ).toEqual({}); - expect(console.warn).toHaveBeenCalledWith( - '[@stackone/ai] Dropping header argument "headers" from a tool call: not an object', - ); - }); - - it('drops an array value on a declared flat headers_ argument', () => { - expect( - sanitiseHeaderArguments({ 'headers_x-trace': ['a\r\nx-account-id: B'] }, declared), - ).toEqual({}); - expect(console.warn).toHaveBeenCalledWith( - '[@stackone/ai] Dropping header argument "headers_x-trace" from a tool call: not a string, number or boolean', - ); - }); - - it('drops an object value on a declared flat headers_ argument', () => { - expect(sanitiseHeaderArguments({ 'headers_x-trace': { nested: 'value' } }, declared)).toEqual( - {}, - ); - expect(console.warn).toHaveBeenCalledWith( - '[@stackone/ai] Dropping header argument "headers_x-trace" from a tool call: not a string, number or boolean', - ); - }); - - it('still drops a null flat headers_ argument silently', () => { - expect(sanitiseHeaderArguments({ 'headers_x-trace': null }, declared)).toEqual({}); - expect(console.warn).not.toHaveBeenCalled(); - }); }); // Assigning to `__proto__` sets the prototype, so each of these once dropped the entry. diff --git a/src/tool.test.ts b/src/tool.test.ts index 5d0c91a5..2fb026f3 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -386,31 +386,6 @@ describe('StackOneMcpTool as an action tool', () => { await expect(actionTool().execute(input)).rejects.toThrow(message); }); - // JSON.stringify, and so the MCP client, would send each of these as null. - it.each([ - ['NaN at the top level', { amount: Number.NaN }, 'NaN'], - [ - 'Infinity nested in an object', - { body: { name: 'Ada', score: Number.POSITIVE_INFINITY } }, - 'Infinity', - ], - [ - '-Infinity nested in an array', - { query: { ids: [1, Number.NEGATIVE_INFINITY] } }, - '-Infinity', - ], - ])('rejects %s without calling the server', async (_name, args, value) => { - const error = await actionTool() - .execute(args as JsonObject) - .catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(StackOneError); - expect((error as Error).message).toBe( - `Arguments for "crm_update_contact" could not be encoded as JSON: ${value} is not a JSON number`, - ); - expect(calls).toEqual([]); - }); - it('rejects a non-object, non-string argument', async () => { // @ts-expect-error - intentionally passing an invalid type await expect(actionTool().execute(12345)).rejects.toThrow( @@ -462,7 +437,6 @@ describe('StackOneMcpTool as an action tool', () => { // What a model emits when a token boundary splits an emoji: not Unicode text, so not UTF-8. it.each([ - ['a lone high surrogate in a value', { name: 'Ada\uD83D' }], ['a lone low surrogate nested in an array', { query: { ids: ['\uDE00x'] } }], ['a lone surrogate in a key', { body: { '\uD800': 'x' } }], ['a lone surrogate in a top-level key', { '\uDFFF': 'x' }], @@ -483,7 +457,8 @@ describe('StackOneMcpTool as an action tool', () => { expect(calls).toHaveLength(1); }); - it.each([['{"a": NaN}'], ['NaN'], ['{"a": Infinity}']])( + // NaN alone, and in an object, are in the shared vectors. + it.each([['{"a": Infinity}'], ['[-Infinity]']])( 'rejects the JSON text %s as invalid JSON', async (text) => { const error = await actionTool() diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 452481d2..666f7395 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -104,24 +104,6 @@ describe('configuration', () => { ); }); - it.each([ - ['accountIds', () => newToolSet({ accountIds: [1] as never })], - ['setAccounts', () => newToolSet().setAccounts({ id: 'acc1' } as never)], - ['fetchTools', () => newToolSet().fetchTools({ accountIds: 5 as never })], - ])('refuses a non-list or non-string ids in %s', async (_name, act) => { - await expect(async () => act()).rejects.toThrow( - new ToolSetConfigError('accountIds must be a list of account id strings'), - ); - }); - - it('treats accountIds: null as not given', async () => { - const toolset = newToolSet({ accountIds: null }); - expect(names(await toolset.setAccounts(null).fetchTools({ accountIds: null }))).toEqual([ - 'default_tool_1', - 'default_tool_2', - ]); - }); - it.each([ ['accountIds', () => newToolSet({ accountIds: ['acc1', ''] })], ['setAccounts', () => newToolSet().setAccounts([''])], diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index d04a09ab..8a5cb6c8 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -170,7 +170,7 @@ export function retryAfterMs(header: string | null, now: number = Date.now()): n * `Retry-After` when readable, else 1s, 2s, 4s jittered by `random()` into [50%, 100%); capped * at 30s either way. */ -function rateLimitDelayMs( +export function rateLimitDelayMs( retry: number, retryAfter: number | undefined, random: () => number, @@ -183,7 +183,7 @@ function rateLimitDelayMs( * Whether a retry's wait ends before the deadline, `remaining` milliseconds away. An equal wait * does not: the caller's timeout would fire as the retry starts. */ -const waitsForRetry = (delay: number, remaining: number): boolean => delay < remaining; +export const waitsForRetry = (delay: number, remaining: number): boolean => delay < remaining; /** Seconds rounded half up to two decimals and written as a number: `0`, `0.75`, `1.5`. */ const formatSeconds = (ms: number): string => String(Math.floor((ms / 1000) * 100 + 0.5) / 100); diff --git a/src/vectors.test.ts b/src/vectors.test.ts new file mode 100644 index 00000000..c757e3e4 --- /dev/null +++ b/src/vectors.test.ts @@ -0,0 +1,909 @@ +/** + * The shared vectors of StackOneHQ/sdk-conformance, vendored byte for byte in tests/vectors/ + * (scripts/sync-vectors.sh), run against the SDK's own code. The Python SDK runs the same files. + * `unresolved` cases are not graded; every other case must pass. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; +import { http, HttpResponse } from 'msw'; +import { TEST_BASE_URL } from '../mocks/constants'; +import { server } from '../mocks/node'; +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 { fetchWithRetry, rateLimitDelayMs, retryAfterMs, waitsForRetry } from './utils/fetch-retry'; + +vi.mock('./mcp-client', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, listMcpTools: vi.fn(actual.listMcpTools) }; +}); +const listMock = vi.mocked(listMcpTools); +const { listMcpTools: realListMcpTools } = + await vi.importActual('./mcp-client'); + +const VECTORS = join(import.meta.dirname, '..', 'tests', 'vectors'); + +/** Replace every `{"$number": "NaN" | "Infinity" | "-Infinity"}` with the number it names. */ +const decodeNumbers = (value: unknown): unknown => { + if (Array.isArray(value)) { + 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 value; +}; + +interface VectorFile { + version: number; + cases: Case[]; + unresolved?: unknown[]; +} + +/** A vector file, its NaN markers decoded. */ +function loadFile(name: string): File { + return decodeNumbers(JSON.parse(readFileSync(join(VECTORS, name), 'utf8'))) as File; +} +const load = (name: string): VectorFile => loadFile>(name); + +/** Seconds are compared with a relative tolerance of 1e-9 (README, "Reading the values"). */ +const expectSeconds = (actual: number | null, expected: number | null): void => { + if (expected === null || actual === null || !Number.isFinite(expected)) { + expect(actual).toBe(expected); + return; + } + expect(Math.abs(actual - expected)).toBeLessThanOrEqual(Math.abs(expected) * 1e-9); +}; + +// --------------------------------------------------------------------------------------------- +// messages.json: rendering, shared by every file whose cases produce messages. + +interface Placeholder { + format: 'text' | 'json' | 'integer' | 'seconds' | 'seconds-2dp' | 'json-type' | 'reason'; +} +interface Message { + id: string; + kind: 'error' | 'warning' | 'tool-result'; + error?: { node: string }; + template: string; + placeholders: Record; +} + +const messages = loadFile<{ + version: number; + reasons: Record; + messages: Message[]; +}>('messages.json'); +const messageById = new Map(messages.messages.map((message) => [message.id, message])); + +const jsonType = (value: unknown): string => + value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value; + +const formatValue = (value: unknown, format: Placeholder['format']): string => { + switch (format) { + case 'json': + return JSON.stringify(value); + case 'seconds': + return String(value); + case 'seconds-2dp': + return String(Math.floor((value as number) * 100 + 0.5) / 100); + case 'json-type': + return jsonType(value); + case 'reason': { + const text = messages.reasons[value as string]; + if (text === undefined) { + throw new Error(`No reason text for ${String(value)}`); + } + return text; + } + default: + return String(value); + } +}; + +/** A message's template, rendered with these values. */ +const render = (id: string, values: Record = {}): string => { + const message = messageById.get(id); + if (!message) { + 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)) { + throw new Error(`No value for {${name}} in ${id}`); + } + return formatValue(values[name], placeholder.format); + }); +}; + +/** 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) { + throw new Error(`messages.json has no message ${id}`); + } + const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const source = message.template + .split(/(\{\w+\})/) + .map((part) => { + const name = /^\{(\w+)\}$/.exec(part)?.[1]; + if (name === undefined) { + return escape(part); + } + const placeholder = message.placeholders[name]; + return name in values && placeholder + ? escape(formatValue(values[name], placeholder.format)) + : '.*'; + }) + .join(''); + return new RegExp(`^${source}$`, 's'); +}; + +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(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); + listMock.mockReset(); + listMock.mockImplementation(realListMcpTools); +}); + +/** A tool with this served input schema, whose calls are dry runs: nothing is sent. */ +const toolWith = (inputSchema: Record, name = 'vector_tool') => + new StackOneMcpTool({ + name, + description: '', + parameters: toolParametersFromInputSchema(inputSchema as never), + endpoint: `${TEST_BASE_URL}/mcp`, + apiKey: 'test-key', + accountId: 'acc-1', + timeout: 5_000, + }); + +const sentArguments = async ( + inputSchema: Record, + args: unknown, +): Promise => { + const call = await toolWith(inputSchema).execute(args as JsonObject, { dryRun: true }); + return call.arguments as JsonObject; +}; + +const OPEN_HEADERS = { type: 'object', properties: { headers: { type: 'object' } } }; + +// --------------------------------------------------------------------------------------------- + +describe('retry-after.json', () => { + const file = load<{ + id: string; + header: string | null; + now: string; + expected_seconds: number | null; + }>('retry-after.json'); + + it('is the version these tests were written for', () => { + expect(file.version).toBe(1); + }); + + /** + * Cases these tests cannot pass, each with why. Run with `it.fails`, so a fixed vector fails + * here until it is taken off the list. + */ + const CONTRADICTED: Record = { + // 01-Oct-70 is 44 years ahead of `now`, not more than 50, so RFC 9110 §5.6.7 — and this + // file's own rfc850-year-60, -76 and -77 — put it in 2070, not 1970. + 'rfc850-year-70': 'contradicts rfc850-year-60/76/77', + }; + + it.each(file.cases.filter(({ id }) => !(id in CONTRADICTED)))( + '$id', + ({ header, now, expected_seconds }) => { + const ms = retryAfterMs(header, Date.parse(now)); + expectSeconds(ms === undefined ? null : ms / 1000, expected_seconds); + }, + ); + + it.fails.each(file.cases.filter(({ id }) => id in CONTRADICTED))( + '$id (contradicted by the vectors themselves)', + ({ header, now, expected_seconds }) => { + const ms = retryAfterMs(header, Date.parse(now)); + expectSeconds(ms === undefined ? null : ms / 1000, expected_seconds); + }, + ); +}); + +describe('backoff.json', () => { + const file = loadFile< + VectorFile<{ + id: string; + retry: number; + random: number; + retry_after_seconds: number | null; + expected_delay_seconds: number; + }> & { + deadline_cases: Array<{ + id: string; + delay_seconds: number; + remaining_seconds: number; + expected: 'wait' | 'return-429'; + }>; + } + >('backoff.json'); + + it('is the version these tests were written for', () => { + expect(file.version).toBe(1); + }); + + it.each(file.cases)('$id', ({ retry, random, retry_after_seconds, expected_delay_seconds }) => { + const delay = rateLimitDelayMs( + retry, + retry_after_seconds === null ? undefined : retry_after_seconds * 1000, + () => random, + ); + expectSeconds(delay / 1000, expected_delay_seconds); + }); + + it.each(file.deadline_cases)('$id', ({ delay_seconds, remaining_seconds, expected }) => { + const waits = waitsForRetry(delay_seconds * 1000, remaining_seconds * 1000); + expect(waits ? 'wait' : 'return-429').toBe(expected); + }); +}); + +describe('header-values.json', () => { + const file = load<{ id: string; value: unknown; expected: string | { dropped: true } }>( + 'header-values.json', + ); + + it('is the version these tests were written for', () => { + expect(file.version).toBe(1); + }); + + 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 }); + } else { + expect(headers).toEqual({}); + } + }); +}); + +describe('header-names.json', () => { + const file = load<{ + id: string; + name: string; + expected: { forwarded: string } | { dropped: string }; + }>('header-names.json'); + + it('is the version these tests were written for', () => { + expect(file.version).toBe(1); + }); + + 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(warnings()).toEqual([]); + } else { + expect(sent.headers).toEqual({}); + expect(warnings()).toEqual([ + PREFIX + render('header-dropped', { header: name.trim(), reason: expected.dropped }), + ]); + } + }); +}); + +describe('header-arguments.json', () => { + const file = load<{ + id: string; + schema: Record; + arguments: JsonObject; + expected_arguments: JsonObject; + expected_warnings: Array<{ argument: string; header?: string; reason: string }>; + }>('header-arguments.json'); + + it('is the version these tests were written for', () => { + expect(file.version).toBe(1); + }); + + it.each(file.cases)( + '$id', + async ({ schema, arguments: args, expected_arguments, expected_warnings }) => { + const sent = await sentArguments(schema, args); + // Key order too: arguments are forwarded in the order the model gave them. + expect(JSON.stringify(sent)).toBe(JSON.stringify(expected_arguments)); + expect(warnings()).toEqual( + expected_warnings.map( + ({ argument, header, reason }) => + PREFIX + + (header === undefined + ? render('header-argument-dropped', { argument, reason }) + : render('header-dropped', { header, reason })), + ), + ); + }, + ); +}); + +describe('argument-encoding.json', () => { + const file = load<{ + id: string; + arguments?: unknown; + arguments_json?: string; + expected: 'ok' | { error: string; reason: string }; + }>('argument-encoding.json'); + + const TOOL = 'vector_tool'; + const messageFor = (reason: string, input: unknown): RegExp => { + switch (reason) { + case 'not-finite': + return pattern('arguments-not-finite', { tool: TOOL }); + case 'invalid-json': { + let detail = ''; + try { + JSON.parse(input as string); + } catch (error) { + detail = (error as Error).message; + } + return pattern('arguments-invalid-json', { tool: TOOL, detail }); + } + case 'not-an-object': + return pattern('arguments-not-an-object', { tool: TOOL }); + case 'unencodable': + return pattern('arguments-not-encodable', { tool: TOOL }); + default: + throw new Error(`Unknown reason ${reason}`); + } + }; + + it('is the version these tests were written for', () => { + expect(file.version).toBe(1); + }); + + 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) + .execute(input as JsonObject, { dryRun: true }) + .then( + (call) => ({ ok: call }), + (error: unknown) => ({ error: error as Error }), + ); + if (testCase.expected === 'ok') { + expect(outcome).toHaveProperty('ok'); + return; + } + expect('error' in outcome && outcome.error.name).toBe(testCase.expected.error); + expect('error' in outcome && outcome.error.message).toMatch( + messageFor(testCase.expected.reason, input), + ); + }); +}); + +describe('account-ids.json', () => { + const file = load<{ + id: string; + parameter: 'account_ids' | 'account_id'; + value: unknown; + 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 } })], + ['setAccounts()', async (value) => newToolSet().setAccounts(value as string[])], + ['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); + }); + + describe.each(file.cases)('$id', ({ parameter, value, expected }) => { + const takers: Array<[string, (value: unknown) => Promise]> = + parameter === 'account_id' + ? [['the constructor', async (id) => newToolSet({ accountId: id })]] + : listTakers; + + it.each(takers)('in %s', async (_where, take) => { + listMock.mockResolvedValue([]); + const outcome = await outcomeOf(() => take(value)); + if (expected === 'ok') { + expect(outcome).toBe('ok'); + } else { + expect(outcome).toBeInstanceOf(Error); + expect((outcome as Error).name).toBe(expected.error.node); + } + if (expected !== 'ok' || parameter === 'account_id') { + expect(listMock).not.toHaveBeenCalled(); + } + }); + }); +}); + +// --------------------------------------------------------------------------------------------- +// 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 }) => + names + .filter((name) => + name + .replace(/_(search_actions|execute_action)$/, '') + .endsWith(`_${headers['x-account-id']}`), + ) + .map((name) => ({ name, description: '', inputSchema: {} })), + ); +}; + +/** 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); + }, + ); +}; + +const errorOf = (act: () => unknown): Promise => + Promise.resolve() + .then(act) + .then( + () => { + throw new Error('expected an error'); + }, + (error: unknown) => error as Error, + ); + +type Emitted = { error: Error } | { warnings: string[] } | { toolResult: string }; + +/** + * How to make the SDK emit each message, and the values it should be rendered with. A value + * left out is a placeholder whose text is not the SDK's to choose (a parser's message). + */ +const emitters: Record< + string, + () => Promise<{ emitted: Emitted; values: Record }> +> = { + 'header-dropped': async () => { + await sentArguments(OPEN_HEADERS, { headers: { Authorization: 'x' } }); + return { + emitted: { warnings: warnings() }, + values: { header: 'Authorization', reason: 'set-by-sdk' }, + }; + }, + 'header-argument-dropped': async () => { + await sentArguments(OPEN_HEADERS, { headers: 'abc' }); + return { + emitted: { warnings: warnings() }, + values: { argument: 'headers', reason: 'not-an-object' }, + }; + }, + 'rate-limit-retry': async () => { + const url = `${TEST_BASE_URL}/limited`; + let requests = 0; + server.use( + http.post(url, () => + requests++ === 0 + ? HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '2' } }) + : HttpResponse.json({}), + ), + ); + await fetchWithRetry( + url, + { method: 'POST' }, + { timing: { sleep: async () => {}, random: () => 0.5, now: () => 0 } }, + ); + return { + emitted: { warnings: warnings() }, + values: { method: 'POST', url, attempt: 1, max_attempts: 4, delay: 2 }, + }; + }, + 'rate-limit-deadline': async () => { + const url = `${TEST_BASE_URL}/limited`; + server.use( + http.post(url, () => HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '3' } })), + ); + await fetchWithRetry( + url, + { method: 'POST' }, + { + deadline: 1_000, + timing: { sleep: async () => {}, random: () => 0.5, now: () => 0 }, + }, + ); + return { + emitted: { warnings: warnings() }, + values: { method: 'POST', url, attempt: 1, max_attempts: 4, delay: 3 }, + }; + }, + 'skip-account': async () => { + listMock.mockImplementation(async ({ headers }) => { + if (headers['x-account-id'] === 'acc-2') { + throw new Error('boom'); + } + return [{ name: 't_acc-1', description: '', inputSchema: {} }]; + }); + await newToolSet().fetchTools({ accountIds: ['acc-1', 'acc-2'] }); + return { emitted: { warnings: warnings() }, values: { account_id: 'acc-2', error: 'boom' } }; + }, + 'skip-connector': async () => { + listByAccount(['a_acc-1_search_actions', 'b_acc-1_search_actions']); + respondToCalls((tool) => { + if (tool.name.startsWith('b_')) { + throw new Error('boom'); + } + return { actions: [{ action_id: 'a_x' }] }; + }); + await newToolSet({ accountId: 'acc-1' }).search('q'); + return { + emitted: { warnings: warnings() }, + values: { tool: 'b_acc-1_search_actions', error: 'boom' }, + }; + }, + 'duplicate-tool-names': async () => { + listMock.mockResolvedValue([{ name: 'dup', description: '', inputSchema: {} }]); + await newToolSet().fetchTools({ accountIds: ['acc-1', 'acc-2'] }); + return { emitted: { warnings: warnings() }, values: { count: 1, names: 'dup' } }; + }, + 'ambiguous-connector': async () => { + listByAccount(['linear_acc1_execute_action', 'linear_acc2_execute_action']); + respondToCalls(() => ({ data: {} })); + await newToolSet({ accountIds: ['acc1', 'acc2'] }).execute('linear_list_issues'); + return { + emitted: { warnings: warnings() }, + values: { + action_id: 'linear_list_issues', + count: 2, + tools: 'linear_acc1_execute_action, linear_acc2_execute_action', + tool: 'linear_acc1_execute_action', + }, + }; + }, + 'mcp-timeout': async () => { + const endpoint = `${TEST_BASE_URL}/mcp`; + return { + emitted: { + error: describeMcpFailure( + new McpError(ErrorCode.RequestTimeout, 'timed out'), + endpoint, + 1_500, + ), + }, + values: { endpoint, timeout: 1.5 }, + }; + }, + 'mcp-http-failure': async () => { + const endpoint = `${TEST_BASE_URL}/mcp`; + server.use( + http.post(endpoint, () => HttpResponse.json({ message: 're-link' }, { status: 412 })), + ); + const error = await errorOf(() => + realListMcpTools({ endpoint, headers: { 'x-account-id': 'acc-1' }, timeout: 5_000 }), + ); + return { + emitted: { error }, + values: { + endpoint, + status: 412, + reason_phrase: 'Precondition Failed', + body: '{"message":"re-link"}', + }, + }; + }, + 'mcp-failure': async () => { + const endpoint = `${TEST_BASE_URL}/mcp`; + const error = describeMcpFailure( + new Error('fetch failed', { cause: new TypeError('connection refused') }), + endpoint, + 5_000, + ); + return { + emitted: { error }, + values: { endpoint, error_type: 'TypeError', error_message: 'connection refused' }, + }; + }, + 'accounts-http-failure': async () => { + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json({ message: 'bad key' }, { status: 401 }), + ), + ); + return { + emitted: { error: await errorOf(() => newToolSet().fetchAccounts()) }, + values: { + url: `${TEST_BASE_URL}/accounts`, + status: 401, + reason_phrase: 'Unauthorized', + body: '{"message":"bad key"}', + }, + }; + }, + 'accounts-unreachable': async () => { + server.use(http.get(`${TEST_BASE_URL}/accounts`, () => HttpResponse.error())); + return { + emitted: { error: await errorOf(() => newToolSet().fetchAccounts()) }, + values: { url: `${TEST_BASE_URL}/accounts` }, + }; + }, + 'accounts-invalid-json': async () => { + server.use( + http.get( + `${TEST_BASE_URL}/accounts`, + () => new HttpResponse('[{', { headers: { 'content-type': 'application/json' } }), + ), + ); + return { + emitted: { error: await errorOf(() => newToolSet().fetchAccounts()) }, + values: { url: `${TEST_BASE_URL}/accounts` }, + }; + }, + 'accounts-unexpected-shape': async () => { + server.use(http.get(`${TEST_BASE_URL}/accounts`, () => HttpResponse.json('acc-1'))); + return { + emitted: { error: await errorOf(() => newToolSet().fetchAccounts()) }, + values: { json_type: 'acc-1' }, + }; + }, + 'no-linked-accounts': async () => { + server.use(http.get(`${TEST_BASE_URL}/accounts`, () => HttpResponse.json([]))); + return { emitted: { error: await errorOf(() => newToolSet().fetchTools()) }, values: {} }; + }, + 'no-active-accounts': async () => { + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json([{ id: 'dead', provider: 'hibob', status: 'error' }]), + ), + ); + return { + emitted: { error: await errorOf(() => newToolSet().fetchTools()) }, + values: { count: 1, accounts: 'hibob (error)' }, + }; + }, + 'no-account-returned-tools': async () => { + listMock.mockImplementation(async ({ headers }) => { + throw new Error(`down ${headers['x-account-id']}`); + }); + return { + emitted: { + error: await errorOf(() => newToolSet().fetchTools({ accountIds: ['acc-1', 'acc-2'] })), + }, + values: { failures: 'acc-1: down acc-1 | acc-2: down acc-2' }, + }; + }, + 'no-connector-returned-results': async () => { + listByAccount(['a_acc-1_search_actions', 'b_acc-1_search_actions']); + respondToCalls((tool) => { + throw new Error(`down ${tool.name}`); + }); + return { + emitted: { error: await errorOf(() => newToolSet({ accountId: 'acc-1' }).search('q')) }, + values: { + failures: + 'a_acc-1_search_actions: down a_acc-1_search_actions | b_acc-1_search_actions: down b_acc-1_search_actions', + }, + }; + }, + 'fetch-tools-failed': async () => { + listMock.mockRejectedValue(new Error('boom')); + return { + emitted: { error: await errorOf(() => newToolSet({ accountId: 'acc-1' }).fetchTools()) }, + values: { detail: 'boom' }, + }; + }, + 'missing-api-key': async () => { + vi.stubEnv('STACKONE_API_KEY', ''); + try { + return { emitted: { error: await errorOf(() => new StackOneToolSet()) }, values: {} }; + } finally { + vi.unstubAllEnvs(); + } + }, + 'empty-account-id': async () => ({ + emitted: { error: await errorOf(() => newToolSet({ accountId: '' })) }, + values: { parameter: 'accountId' }, + }), + 'account-ids-not-a-list': async () => ({ + emitted: { error: await errorOf(() => newToolSet({ accountIds: 'acc-1' })) }, + values: { parameter: 'accountIds', value: 'acc-1' }, + }), + 'account-ids-not-strings': async () => ({ + emitted: { error: await errorOf(() => newToolSet({ accountIds: [1] })) }, + values: { parameter: 'accountIds' }, + }), + 'account-ids-empty-id': async () => ({ + emitted: { error: await errorOf(() => newToolSet({ accountIds: [''] })) }, + values: { parameter: 'accountIds' }, + }), + 'invalid-session-id': async () => ({ + emitted: { + error: await errorOf(() => + newToolSet({ accountId: 'acc-1' }).execute('x_y', {}, { sessionId: '' }), + ), + }, + values: { parameter: 'sessionId', value: '' }, + }), + 'invalid-action-id': async () => ({ + emitted: { error: await errorOf(() => newToolSet({ accountId: 'acc-1' }).execute('')) }, + values: { parameter: 'actionId', value: '' }, + }), + 'execute-arguments-not-an-object': async () => ({ + emitted: { + error: await errorOf(() => newToolSet({ accountId: 'acc-1' }).execute('x_y', [1] as never)), + }, + values: { json_type: [1] }, + }), + 'top-k-out-of-range': async () => ({ + emitted: { + error: await errorOf(() => newToolSet({ accountId: 'acc-1' }).search('q', { topK: 51 })), + }, + values: { parameter: 'topK', max: 50, value: 51 }, + }), + 'tool-names-not-a-list': async () => ({ + emitted: { + error: await errorOf(() => + newToolSet({ accountId: 'acc-1' }).submitFeedback({ + rating: 'positive', + toolNames: 'a' as never, + }), + ), + }, + values: { parameter: 'toolNames', value: 'a' }, + }), + 'feedback-not-enabled': async () => { + listMock.mockResolvedValue([]); + return { + emitted: { + error: await errorOf(() => + newToolSet({ accountId: 'acc-1' }).submitFeedback({ + rating: 'positive', + toolNames: ['a'], + }), + ), + }, + values: {}, + }; + }, + 'no-connector-for-action': async () => { + listByAccount(['linear_acc1_execute_action']); + return { + emitted: { + error: await errorOf(() => newToolSet({ accountId: 'acc1' }).execute('jira_list_issues')), + }, + values: { action_id: 'jira_list_issues' }, + }; + }, + 'arguments-not-finite': async () => ({ + emitted: { + error: await errorOf(() => + toolWith({ type: 'object', properties: {} }).execute({ a: Number.NaN }), + ), + }, + values: { tool: 'vector_tool', value: 'NaN' }, + }), + 'arguments-not-encodable': async () => { + const args: JsonObject = {}; + args.self = args; + return { + emitted: { + error: await errorOf(() => toolWith({ type: 'object', properties: {} }).execute(args)), + }, + values: { tool: 'vector_tool' }, + }; + }, + 'arguments-invalid-json': async () => { + let detail = ''; + try { + JSON.parse('{'); + } catch (error) { + detail = (error as Error).message; + } + return { + emitted: { + error: await errorOf(() => toolWith({ type: 'object', properties: {} }).execute('{')), + }, + values: { tool: 'vector_tool', detail }, + }; + }, + 'arguments-not-an-object': async () => ({ + emitted: { + error: await errorOf(() => toolWith({ type: 'object', properties: {} }).execute(5 as never)), + }, + values: { tool: 'vector_tool' }, + }), + 'tool-call-failed': async () => ({ + emitted: { + error: await errorOf(() => + parseToolResult({ isError: true, content: [{ type: 'text', text: 'boom' }] }, 'a_b'), + ), + }, + values: { tool: 'a_b', detail: 'boom' }, + }), + 'no-executor': async () => ({ + emitted: { + error: await errorOf(() => + new BaseTool('hand_built', '', { type: 'object', properties: {} }, { + kind: 'local', + } as never).execute({}), + ), + }, + values: { tool: 'hand_built' }, + }), + 'unknown-tool': async () => { + const [message] = await new Tools([]).executeOpenAIToolCalls([ + { id: 'c', type: 'function', function: { name: 'invented', arguments: '{}' } }, + ]); + return { + emitted: { toolResult: JSON.parse(message?.content as string).error }, + values: { name: 'invented' }, + }; + }, +}; + +describe('messages.json', () => { + it('is the version these tests were written for', () => { + expect(messages.version).toBe(1); + }); + + it('has an emitter for every shared message', () => { + expect(Object.keys(emitters).sort()).toEqual( + messages.messages.map((message) => message.id).sort(), + ); + }); + + it.each(messages.messages)('$id', async ({ id, kind, error: errorClass }) => { + const emit = emitters[id]; + if (!emit) { + throw new Error(`No emitter for ${id}`); + } + const { emitted, values } = await emit(); + const expected = pattern(id, values); + if (kind === 'warning') { + expect('warnings' in emitted && emitted.warnings).toEqual([ + expect.stringMatching( + new RegExp(`^${PREFIX.replace(/[[\]]/g, '\\$&')}${expected.source.slice(1)}`, 's'), + ), + ]); + } 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); + } + }); +}); diff --git a/tests/vectors/README.md b/tests/vectors/README.md new file mode 100644 index 00000000..d95eb24f --- /dev/null +++ b/tests/vectors/README.md @@ -0,0 +1,141 @@ +# Shared test vectors + +Unit-test data both SDKs load, so the Python and Node unit tests check the same inputs against +the same expected outputs. The harness in this repo grades an SDK end to end, over the wire; +these grade the pure functions underneath: reading a `Retry-After`, the backoff, header +filtering, argument encoding and account-id validation. They also fix the canonical wording of +every message the two SDKs share. + +Every expected value was taken from both SDKs' behaviour at the time it was written, and only +where they agreed. Where they disagreed, the contract has since settled which is right, and the +case is in that file's `cases` array with the agreed value — a `description` on the case says what +changes. A case that is settled but still not identical across SDKs for a reason outside the rule +(for example, a JSON parser has already rounded a value before the rule ever sees it) is in a +`known_differences` array instead, not graded. A file keeps an `unresolved` array for a case the +SDKs disagree on today and the contract does not yet settle; none is open right now. + +| File | Input → expected | +|---|---| +| `retry-after.json` | a `Retry-After` value and `now` → seconds before the cap, or `null` when absent or unreadable | +| `backoff.json` | retry number, injected random value, `Retry-After` → the delay; and a delay against the time left → `wait` or `return-429` | +| `header-values.json` | a nested header value → the string forwarded, or `{"dropped": true}` | +| `header-names.json` | a nested header name → `{"forwarded": ""}` or `{"dropped": ""}` | +| `header-arguments.json` | a served `inputSchema` and the model's arguments → the arguments sent, and the warnings as `{argument, header?, reason}` | +| `argument-encoding.json` | a tool's arguments → `ok`, or `{"error": "ToolArgumentsError", "reason"}` | +| `account-ids.json` | an account-id argument → `ok`, or each language's config error class | +| `messages.json` | the canonical template of every shared warning and error, with each SDK's current text beside it | + +`schema/` holds a JSON Schema (draft 2020-12) for each file. Each file names its schema in +`$schema`. + +## File shape + +```jsonc +{ + "$schema": "./schema/.schema.json", + "description": "what the vectors are, and the context each case runs in", + "version": 1, + // any constants the cases share: max_delay_seconds, constants, reasons, error_classes + "cases": [{ "id": "…", "description": "…", /* inputs */ "expected…": … }], + // present only while a case is open: + "unresolved": [{ "id": "…", "description": "…", /* inputs */ "python": …, "node": … }], + // present only where a settled case still differs for a reason outside the rule: + "known_differences": [{ "id": "…", "description": "…", /* inputs */ "python": …, "node": … }] +} +``` + +- **`id`** is unique within a file and does not change: a test names its cases by it. +- **`version`** is bumped when an existing case's meaning or expected value changes. Adding a case + does not bump it. +- **`unresolved`** cases are not graded. Each one says what the two SDKs do differently. Once the + contract settles it, the case moves to `cases` with the agreed value, and the SDK that changes + fixes its code in the same release. A file only has this array while it has an open case. +- **`known_differences`** cases are not graded either. Each one is settled — the contract has + chosen the expected behaviour, and it is in `cases` — but the two SDKs still produce different + values for a reason outside the rule being tested, so there is nothing to converge on. + +## Reading the values + +- **Numbers JSON cannot hold.** `{"$number": "NaN"}`, `{"$number": "Infinity"}` and + `{"$number": "-Infinity"}` stand for the non-finite floats. Decode them before use: walk the + value, and replace every object whose only key is `$number` with the float it names. +- **Seconds** are compared with a relative tolerance of 1e-9. The Node SDK works in milliseconds, + and converting back can leave a last-bit difference: 99999999999999999999 s round-trips as + 99999999999999980000. +- **`now` and `random` are injected.** `retry-after.json` gives each case its `now` in RFC 3339. + `backoff.json` gives the uniform value in [0, 1) that the jitter is built from: Node's + `Math.random()`, and in Python the value `random.uniform(0.5, 1.0)` scales (`0.5 + 0.5 * r`). An + SDK whose clock or random source is not yet injectable has to make it injectable to load these. +- **Warnings** in `header-arguments.json` are listed in argument order, which both SDKs follow. A + warning's `reason` is a code. `messages.json` turns a code into text (`reasons`) and fills it + into a template, so the wording is checked once there and not in every case. +- **Error classes** are given by name. `account-ids.json` gives both, because the spelling differs: + `ToolsetConfigError` in Python, `ToolSetConfigError` in Node. + +## `messages.json` + +Each message has an `id`, a `template` with named placeholders (`{endpoint}`, `{attempt}`, …), a +`format` for each placeholder, and the text each SDK emits today (`python`, `node`). `matches` +says whether that text is already the canonical one, and `notes` explain the differences. Render +a template by replacing each placeholder with its value written in the placeholder's format: + +| Format | Written as | +|---|---| +| `text` | the value as is | +| `json` | compact JSON: `JSON.stringify(v)` / `json.dumps(v, ensure_ascii=False, separators=(",", ":"))`, so a string comes out in double quotes | +| `integer` | decimal digits | +| `seconds` | a number of seconds, as JavaScript's `String(n)` writes it: `1`, `0.5`, never `1.0` | +| `seconds-2dp` | rounded half up to two decimals (`Math.floor(x * 100 + 0.5) / 100`), then as `seconds` | +| `json-type` | the value's JSON type: `object`, `array`, `string`, `number`, `boolean`, `null` | +| `reason` | the text `reasons` gives for the code | + +A prefix that a language adds stays outside the template: Node's `[@stackone/ai] ` on every +`console.warn`, and Python's logger name. The harness checks the same templates end to end: a +scenario's `expect.warnings` and `expect.error.message` must render one, or the run refuses to +start. + +`unshared` lists messages only one SDK emits. They are recorded so they are not forgotten. They +have no canonical form yet. + +## How an SDK consumes them + +An SDK vendors a copy of this directory. Its unit tests load the vendored copy and never fetch +these files over the network. The vendored copy is pinned to a commit of this repo: the one the +SDK's CI already uses to check out the conformance suite. + +1. Copy `vectors/` into the SDK, for example to `tests/conformance_vectors/` (Python) or + `src/__fixtures__/conformance-vectors/` (Node), from the commit you pin. +2. Add a test per file that iterates `cases` and checks each `id`. Skip `unresolved` and + `known_differences`. Check `version` too, so that a bump fails the test until someone has read + what changed. +3. In CI, check out this repo at the pinned commit, as the conformance job already does, and fail + unless the vendored copy is **byte-identical** to it: + + ```yaml + - name: Vendored vectors match the pinned sdk-conformance + run: diff -r sdk/tests/conformance_vectors sdk-conformance/vectors + ``` + + An edit to the copy fails CI, and so does a pin that moved without a re-copy. Neither SDK can + drift from the data the other one tests against. + +To update, bump the pin, re-copy, and fix whatever the new vectors fail. + +```python +# Python (pytest) +VECTORS = Path(__file__).parent / "conformance_vectors" +retry_after = json.loads((VECTORS / "retry-after.json").read_text()) + +@pytest.mark.parametrize("case", retry_after["cases"], ids=lambda case: case["id"]) +def test_retry_after(case): + ... +``` + +```typescript +// Node (vitest) +import retryAfter from './__fixtures__/conformance-vectors/retry-after.json'; + +describe.each(retryAfter.cases)('Retry-After $id', (testCase) => { + it('reads as the agreed seconds', () => { /* … */ }); +}); +``` diff --git a/tests/vectors/account-ids.json b/tests/vectors/account-ids.json new file mode 100644 index 00000000..37959056 --- /dev/null +++ b/tests/vectors/account-ids.json @@ -0,0 +1,198 @@ +{ + "$schema": "./schema/account-ids.schema.json", + "description": "Which account ids a toolset accepts. `parameter: \"account_ids\"` is the per-call list (fetch_tools(account_ids=…) / fetchTools({accountIds})), checked by the same validator as set_accounts/setAccounts and the constructor's execute.account_ids; `parameter: \"account_id\"` is the constructor's single id. A refusal raises the language's own config error class, before any request.", + "version": 1, + "error_classes": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "cases": [ + { + "id": "list", + "description": "a list of ids", + "parameter": "account_ids", + "value": ["acc-1", "acc-2"], + "expected": "ok" + }, + { + "id": "duplicates", + "description": "duplicates are allowed (the scope is deduplicated)", + "parameter": "account_ids", + "value": ["acc-1", "acc-1"], + "expected": "ok" + }, + { + "id": "whitespace-id", + "description": "a whitespace id is not empty, so it is accepted", + "parameter": "account_ids", + "value": [" "], + "expected": "ok" + }, + { + "id": "empty-list", + "description": "an empty list means not given: the toolset's own accounts, then discovery", + "parameter": "account_ids", + "value": [], + "expected": "ok" + }, + { + "id": "empty-string-id", + "description": "an empty id would be sent with no x-account-id", + "parameter": "account_ids", + "value": [""], + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "empty-among-valid", + "description": "one empty id among valid ones", + "parameter": "account_ids", + "value": ["acc-1", ""], + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "bare-string", + "description": "a bare string is refused, not iterated as characters", + "parameter": "account_ids", + "value": "acc-1", + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "bare-empty-string", + "description": "a bare empty string is refused as a string", + "parameter": "account_ids", + "value": "", + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "number-id", + "description": "a non-string id", + "parameter": "account_ids", + "value": [1], + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "null-id", + "description": "a null id", + "parameter": "account_ids", + "value": [null], + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "object-id", + "description": "an object id", + "parameter": "account_ids", + "value": [ + { + "id": "acc-1" + } + ], + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "nested-list", + "description": "a list id", + "parameter": "account_ids", + "value": [["acc-1"]], + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "single", + "description": "a single account id", + "parameter": "account_id", + "value": "acc-1", + "expected": "ok" + }, + { + "id": "single-empty", + "description": "an empty single account id is usually an unset variable: refused rather than widened to every account", + "parameter": "account_id", + "value": "", + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "single-whitespace", + "description": "a whitespace single account id is not empty", + "parameter": "account_id", + "value": " ", + "expected": "ok" + }, + { + "id": "null", + "description": "account_ids=None / accountIds: null means not given, the same as omitting it: the toolset's own accounts, then discovery. In both SDKs.", + "parameter": "account_ids", + "value": null, + "expected": "ok" + }, + { + "id": "not-a-list-number", + "description": "a number is refused in both: it is not a list of account id strings (account-ids-not-strings).", + "parameter": "account_ids", + "value": 5, + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + }, + { + "id": "not-a-list-object", + "description": "an object is refused in both: it is not a list of account id strings (account-ids-not-strings), not iterated for its keys.", + "parameter": "account_ids", + "value": { + "id": "acc-1" + }, + "expected": { + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + } + } + } + ] +} diff --git a/tests/vectors/argument-encoding.json b/tests/vectors/argument-encoding.json new file mode 100644 index 00000000..53f23892 --- /dev/null +++ b/tests/vectors/argument-encoding.json @@ -0,0 +1,249 @@ +{ + "$schema": "./schema/argument-encoding.schema.json", + "description": "Whether a tool's arguments can be sent: `ok`, or a ToolArgumentsError raised before any request with the given reason. `arguments` is the value handed to the tool's execute; `arguments_json` is JSON text handed instead. `{\"$number\": \"NaN\"}`, \"Infinity\" and \"-Infinity\" stand for the non-finite numbers JSON cannot hold. The tool's schema declares no header arguments, so header filtering plays no part.", + "version": 1, + "reasons": ["not-finite", "invalid-json", "not-an-object", "unencodable"], + "cases": [ + { + "id": "empty-object", + "description": "no arguments", + "arguments": {}, + "expected": "ok" + }, + { + "id": "nested-empty", + "description": "empty containers", + "arguments": { + "a": {}, + "b": [] + }, + "expected": "ok" + }, + { + "id": "scalars", + "description": "every JSON scalar", + "arguments": { + "s": "x", + "n": 1, + "f": 1.5, + "t": true, + "z": null + }, + "expected": "ok" + }, + { + "id": "deep-nesting", + "description": "deep nesting", + "arguments": { + "a": { + "b": { + "c": { + "d": { + "e": [ + [ + [ + { + "f": 1 + } + ] + ] + ] + } + } + } + } + }, + "expected": "ok" + }, + { + "id": "proto-key-nested", + "description": "a __proto__ key one level down is an ordinary key", + "arguments": { + "body": { + "__proto__": { + "polluted": true + } + } + }, + "expected": "ok" + }, + { + "id": "proto-key-top", + "description": "a top-level __proto__ key is an ordinary key to the SDK (the server's MCP stack drops it, see invariant 3)", + "arguments": { + "__proto__": { + "polluted": true + } + }, + "expected": "ok" + }, + { + "id": "constructor-key", + "description": "builtin-named keys are ordinary keys", + "arguments": { + "constructor": "x", + "toString": 1, + "valueOf": {} + }, + "expected": "ok" + }, + { + "id": "nan-top", + "description": "NaN is not JSON", + "arguments": { + "a": { + "$number": "NaN" + } + }, + "expected": { + "error": "ToolArgumentsError", + "reason": "not-finite" + } + }, + { + "id": "infinity-nested", + "description": "Infinity, however deep, is not JSON", + "arguments": { + "body": { + "limit": { + "$number": "Infinity" + } + } + }, + "expected": { + "error": "ToolArgumentsError", + "reason": "not-finite" + } + }, + { + "id": "neg-infinity-in-array", + "description": "-Infinity inside an array is not JSON", + "arguments": { + "a": [ + 1, + { + "$number": "-Infinity" + } + ] + }, + "expected": { + "error": "ToolArgumentsError", + "reason": "not-finite" + } + }, + { + "id": "big-int", + "description": "an integer above 2^53 is still encodable", + "arguments": { + "a": 12345678901234567890 + }, + "expected": "ok" + }, + { + "id": "non-ascii", + "description": "non-ASCII and astral characters are encodable", + "arguments": { + "a": "é€🙂" + }, + "expected": "ok" + }, + { + "id": "json-text-object", + "description": "arguments given as JSON text", + "arguments_json": "{\"a\":1}", + "expected": "ok" + }, + { + "id": "json-text-invalid", + "description": "JSON text that does not parse", + "arguments_json": "{", + "expected": { + "error": "ToolArgumentsError", + "reason": "invalid-json" + } + }, + { + "id": "json-text-array", + "description": "JSON text that is an array", + "arguments_json": "[1]", + "expected": { + "error": "ToolArgumentsError", + "reason": "not-an-object" + } + }, + { + "id": "json-text-string", + "description": "JSON text that is a string", + "arguments_json": "\"x\"", + "expected": { + "error": "ToolArgumentsError", + "reason": "not-an-object" + } + }, + { + "id": "json-text-overflow", + "description": "1e400 parses as Infinity in both languages, which is not JSON", + "arguments_json": "{\"a\": 1e400}", + "expected": { + "error": "ToolArgumentsError", + "reason": "not-finite" + } + }, + { + "id": "json-text-empty", + "description": "empty JSON text does not parse", + "arguments_json": "", + "expected": { + "error": "ToolArgumentsError", + "reason": "invalid-json" + } + }, + { + "id": "not-object-array", + "description": "an array is not an arguments object", + "arguments": [1, 2], + "expected": { + "error": "ToolArgumentsError", + "reason": "not-an-object" + } + }, + { + "id": "not-object-number", + "description": "a number is not an arguments object", + "arguments": 5, + "expected": { + "error": "ToolArgumentsError", + "reason": "not-an-object" + } + }, + { + "id": "lone-surrogate", + "description": "a lone UTF-16 surrogate (what a model emits when a token boundary splits an emoji), anywhere in the arguments, cannot be encoded: it is refused in both SDKs rather than sent as an escaped \\ud800.", + "arguments": { + "a": "\ud800" + }, + "expected": { + "error": "ToolArgumentsError", + "reason": "unencodable" + } + }, + { + "id": "json-text-nan-literal", + "description": "JSON text containing a bare NaN is invalid JSON in both SDKs, even though a lenient parser could read it as a number.", + "arguments_json": "{\"a\": NaN}", + "expected": { + "error": "ToolArgumentsError", + "reason": "invalid-json" + } + }, + { + "id": "json-text-bare-nan", + "description": "the JSON text NaN alone is invalid JSON in both SDKs.", + "arguments_json": "NaN", + "expected": { + "error": "ToolArgumentsError", + "reason": "invalid-json" + } + } + ] +} diff --git a/tests/vectors/backoff.json b/tests/vectors/backoff.json new file mode 100644 index 00000000..bbb33387 --- /dev/null +++ b/tests/vectors/backoff.json @@ -0,0 +1,241 @@ +{ + "$schema": "./schema/backoff.schema.json", + "description": "The delay before a retry of a 429, and whether the deadline allows it. Before retry `retry` (1-based), the delay is `retry_after_seconds` when the 429 carried a readable Retry-After, else `backoff_seconds[retry - 1] * (jitter.min + (jitter.max - jitter.min) * random)`; either way capped at `max_delay_seconds`. `random` is the injected uniform value in [0, 1) — Node's Math.random(), and in Python the value random.uniform(0.5, 1.0) is built from. Deadline cases take the delay after the cap.", + "version": 1, + "constants": { + "max_retries": 3, + "max_attempts": 4, + "backoff_seconds": [1, 2, 4], + "jitter": { + "min": 0.5, + "max": 1, + "max_exclusive": true + }, + "max_delay_seconds": 30 + }, + "cases": [ + { + "id": "backoff-retry-1-random-0", + "description": "no Retry-After: backoff 1s x jitter 0.5", + "retry": 1, + "random": 0, + "retry_after_seconds": null, + "expected_delay_seconds": 0.5 + }, + { + "id": "backoff-retry-1-random-0.25", + "description": "no Retry-After: backoff 1s x jitter 0.625", + "retry": 1, + "random": 0.25, + "retry_after_seconds": null, + "expected_delay_seconds": 0.625 + }, + { + "id": "backoff-retry-1-random-0.5", + "description": "no Retry-After: backoff 1s x jitter 0.75", + "retry": 1, + "random": 0.5, + "retry_after_seconds": null, + "expected_delay_seconds": 0.75 + }, + { + "id": "backoff-retry-1-random-0.9375", + "description": "no Retry-After: backoff 1s x jitter 0.96875", + "retry": 1, + "random": 0.9375, + "retry_after_seconds": null, + "expected_delay_seconds": 0.96875 + }, + { + "id": "backoff-retry-2-random-0", + "description": "no Retry-After: backoff 2s x jitter 0.5", + "retry": 2, + "random": 0, + "retry_after_seconds": null, + "expected_delay_seconds": 1 + }, + { + "id": "backoff-retry-2-random-0.25", + "description": "no Retry-After: backoff 2s x jitter 0.625", + "retry": 2, + "random": 0.25, + "retry_after_seconds": null, + "expected_delay_seconds": 1.25 + }, + { + "id": "backoff-retry-2-random-0.5", + "description": "no Retry-After: backoff 2s x jitter 0.75", + "retry": 2, + "random": 0.5, + "retry_after_seconds": null, + "expected_delay_seconds": 1.5 + }, + { + "id": "backoff-retry-2-random-0.9375", + "description": "no Retry-After: backoff 2s x jitter 0.96875", + "retry": 2, + "random": 0.9375, + "retry_after_seconds": null, + "expected_delay_seconds": 1.9375 + }, + { + "id": "backoff-retry-3-random-0", + "description": "no Retry-After: backoff 4s x jitter 0.5", + "retry": 3, + "random": 0, + "retry_after_seconds": null, + "expected_delay_seconds": 2 + }, + { + "id": "backoff-retry-3-random-0.25", + "description": "no Retry-After: backoff 4s x jitter 0.625", + "retry": 3, + "random": 0.25, + "retry_after_seconds": null, + "expected_delay_seconds": 2.5 + }, + { + "id": "backoff-retry-3-random-0.5", + "description": "no Retry-After: backoff 4s x jitter 0.75", + "retry": 3, + "random": 0.5, + "retry_after_seconds": null, + "expected_delay_seconds": 3 + }, + { + "id": "backoff-retry-3-random-0.9375", + "description": "no Retry-After: backoff 4s x jitter 0.96875", + "retry": 3, + "random": 0.9375, + "retry_after_seconds": null, + "expected_delay_seconds": 3.875 + }, + { + "id": "retry-after-0", + "description": "Retry-After 0s is honoured as given", + "retry": 1, + "random": 0.5, + "retry_after_seconds": 0, + "expected_delay_seconds": 0 + }, + { + "id": "retry-after-5", + "description": "Retry-After 5s is honoured as given", + "retry": 1, + "random": 0.5, + "retry_after_seconds": 5, + "expected_delay_seconds": 5 + }, + { + "id": "retry-after-30", + "description": "Retry-After 30s is honoured as given", + "retry": 1, + "random": 0.5, + "retry_after_seconds": 30, + "expected_delay_seconds": 30 + }, + { + "id": "retry-after-31", + "description": "Retry-After 31s is capped at 30s", + "retry": 1, + "random": 0.5, + "retry_after_seconds": 31, + "expected_delay_seconds": 30 + }, + { + "id": "retry-after-3600", + "description": "Retry-After 3600s is capped at 30s", + "retry": 1, + "random": 0.5, + "retry_after_seconds": 3600, + "expected_delay_seconds": 30 + }, + { + "id": "retry-after-on-retry-3", + "description": "Retry-After 7s is honoured as given", + "retry": 3, + "random": 0, + "retry_after_seconds": 7, + "expected_delay_seconds": 7 + } + ], + "deadline_cases": [ + { + "id": "delay-5-remaining-10", + "description": "a 5s wait with 10s left: the wait is less than the time left", + "delay_seconds": 5, + "remaining_seconds": 10, + "expected": "wait" + }, + { + "id": "delay-10-remaining-10", + "description": "a 10s wait with 10s left: the wait is equal to the time left — the boundary: an equal wait does not finish before the deadline", + "delay_seconds": 10, + "remaining_seconds": 10, + "expected": "return-429" + }, + { + "id": "delay-10-remaining-5", + "description": "a 10s wait with 5s left: the wait is more than the time left", + "delay_seconds": 10, + "remaining_seconds": 5, + "expected": "return-429" + }, + { + "id": "delay-0-remaining-0", + "description": "a 0s wait with 0s left: the wait is equal to the time left — the boundary: an equal wait does not finish before the deadline", + "delay_seconds": 0, + "remaining_seconds": 0, + "expected": "return-429" + }, + { + "id": "delay-0-remaining-1", + "description": "a 0s wait with 1s left: the wait is less than the time left", + "delay_seconds": 0, + "remaining_seconds": 1, + "expected": "wait" + }, + { + "id": "delay-1-remaining-1", + "description": "a 1s wait with 1s left: the wait is equal to the time left — the boundary: an equal wait does not finish before the deadline", + "delay_seconds": 1, + "remaining_seconds": 1, + "expected": "return-429" + }, + { + "id": "delay-2-remaining-1", + "description": "a 2s wait with 1s left: the wait is more than the time left", + "delay_seconds": 2, + "remaining_seconds": 1, + "expected": "return-429" + }, + { + "id": "delay-10-remaining-2", + "description": "a 10s wait with 2s left: the wait is more than the time left", + "delay_seconds": 10, + "remaining_seconds": 2, + "expected": "return-429" + }, + { + "id": "delay-0-remaining--1", + "description": "a 0s wait with -1s left: the wait is more than the time left", + "delay_seconds": 0, + "remaining_seconds": -1, + "expected": "return-429" + }, + { + "id": "delay-30-remaining-30.5", + "description": "a 30s wait with 30.5s left: the wait is less than the time left", + "delay_seconds": 30, + "remaining_seconds": 30.5, + "expected": "wait" + }, + { + "id": "delay-29-remaining-29.001", + "description": "a 29s wait with 29.001s left: the wait is less than the time left", + "delay_seconds": 29, + "remaining_seconds": 29.001, + "expected": "wait" + } + ] +} diff --git a/tests/vectors/header-arguments.json b/tests/vectors/header-arguments.json new file mode 100644 index 00000000..7331afb7 --- /dev/null +++ b/tests/vectors/header-arguments.json @@ -0,0 +1,1366 @@ +{ + "$schema": "./schema/header-arguments.schema.json", + "description": "Invariant 4 as data: a tool's served inputSchema, the model's arguments, the arguments that reach tools/call, and the warnings the SDK emits, in argument order. A warning is {argument, header?, reason}: `argument` is the top-level key (`headers` or `headers_`); `header` is the trimmed nested name, for an entry of a `headers` object. `reason` is one of `reasons`; messages.json renders it.", + "version": 1, + "reasons": ["set-by-sdk", "not-declared", "malformed", "not-an-object", "not-a-scalar"], + "cases": [ + { + "id": "open-forwards-every-name", + "description": "an open headers object (type object, no properties, additionalProperties not false) declares every name", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object" + } + } + }, + "arguments": { + "headers": { + "x-custom": "a", + "X-Other": "b" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a", + "X-Other": "b" + } + }, + "expected_warnings": [] + }, + { + "id": "open-drops-sdk-owned", + "description": "an open object still never forwards an SDK-owned name", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object" + } + } + }, + "arguments": { + "headers": { + "Authorization": "Bearer x", + "x-account-id": "victim", + "User-Agent": "evil/0", + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "Authorization", + "reason": "set-by-sdk" + }, + { + "argument": "headers", + "header": "x-account-id", + "reason": "set-by-sdk" + }, + { + "argument": "headers", + "header": "User-Agent", + "reason": "set-by-sdk" + } + ] + }, + { + "id": "open-additional-properties-true", + "description": "additionalProperties: true is open", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "additionalProperties": true + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [] + }, + { + "id": "open-additional-properties-schema", + "description": "additionalProperties as a schema is open", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [] + }, + { + "id": "closed-declares-nothing", + "description": "a closed object (additionalProperties: false, no properties) declares no names; headers is sent empty", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "additionalProperties": false + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": {} + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-custom", + "reason": "not-declared" + } + ] + }, + { + "id": "closed-with-properties", + "description": "a closed object with properties declares exactly those", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "additionalProperties": false, + "properties": { + "x-custom": { + "type": "string" + } + } + } + } + }, + "arguments": { + "headers": { + "x-custom": "a", + "x-other": "b" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-other", + "reason": "not-declared" + } + ] + }, + { + "id": "declared-nested", + "description": "declared names are forwarded; an undeclared one is not; a declared SDK-owned one is not; a non-header argument is untouched", + "schema": { + "type": "object", + "properties": { + "path": { + "type": "object" + }, + "headers": { + "type": "object", + "properties": { + "x-custom": { + "type": "string" + }, + "Authorization": { + "type": "string" + } + } + } + } + }, + "arguments": { + "path": { + "id": "emp_1" + }, + "headers": { + "x-custom": "a", + "x-other": "b", + "authorization": "Bearer x" + } + }, + "expected_arguments": { + "path": { + "id": "emp_1" + }, + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-other", + "reason": "not-declared" + }, + { + "argument": "headers", + "header": "authorization", + "reason": "set-by-sdk" + } + ] + }, + { + "id": "declared-nested-case-insensitive", + "description": "nested names are declared case-insensitively, and forwarded as supplied", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "properties": { + "X-Custom": { + "type": "string" + } + } + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [] + }, + { + "id": "declared-nested-trimmed", + "description": "a nested name is trimmed before it is looked up and forwarded", + "schema": { + "type": "object", + "properties": { + "path": { + "type": "object" + }, + "headers": { + "type": "object", + "properties": { + "x-custom": { + "type": "string" + }, + "Authorization": { + "type": "string" + } + } + } + } + }, + "arguments": { + "headers": { + " x-custom\t": "a" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [] + }, + { + "id": "declared-nested-null-value", + "description": "a null nested value is dropped silently", + "schema": { + "type": "object", + "properties": { + "path": { + "type": "object" + }, + "headers": { + "type": "object", + "properties": { + "x-custom": { + "type": "string" + }, + "Authorization": { + "type": "string" + } + } + } + } + }, + "arguments": { + "headers": { + "x-custom": null + } + }, + "expected_arguments": { + "headers": {} + }, + "expected_warnings": [] + }, + { + "id": "declared-nested-scalar-value", + "description": "a nested scalar is forwarded as its text (see header-values.json)", + "schema": { + "type": "object", + "properties": { + "path": { + "type": "object" + }, + "headers": { + "type": "object", + "properties": { + "x-custom": { + "type": "string" + }, + "Authorization": { + "type": "string" + } + } + } + } + }, + "arguments": { + "headers": { + "x-custom": 1 + } + }, + "expected_arguments": { + "headers": { + "x-custom": "1" + } + }, + "expected_warnings": [] + }, + { + "id": "nested-empty-object", + "description": "an empty headers object is forwarded empty", + "schema": { + "type": "object", + "properties": { + "path": { + "type": "object" + }, + "headers": { + "type": "object", + "properties": { + "x-custom": { + "type": "string" + }, + "Authorization": { + "type": "string" + } + } + } + } + }, + "arguments": { + "headers": {} + }, + "expected_arguments": { + "headers": {} + }, + "expected_warnings": [] + }, + { + "id": "properties-not-an-object", + "description": "a properties keyword that is not an object declares nothing", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "properties": [] + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": {} + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-custom", + "reason": "not-declared" + } + ] + }, + { + "id": "untyped-declares-nothing", + "description": "an untyped headers schema with no properties declares nothing", + "schema": { + "type": "object", + "properties": { + "headers": {} + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": {} + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-custom", + "reason": "not-declared" + } + ] + }, + { + "id": "untyped-with-properties", + "description": "an untyped headers schema with properties declares those", + "schema": { + "type": "object", + "properties": { + "headers": { + "properties": { + "x-custom": {} + } + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [] + }, + { + "id": "untyped-non-object-dropped", + "description": "an untyped headers schema is not an ordinary field: a non-object value is dropped", + "schema": { + "type": "object", + "properties": { + "headers": {} + } + }, + "arguments": { + "headers": "abc" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers", + "reason": "not-an-object" + } + ] + }, + { + "id": "object-or-null-with-properties", + "description": "[\"object\",\"null\"] with properties declares those", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": ["object", "null"], + "properties": { + "x-custom": {} + } + } + } + }, + "arguments": { + "headers": { + "x-custom": "a", + "x-other": "b" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-other", + "reason": "not-declared" + } + ] + }, + { + "id": "object-or-null-non-object-dropped", + "description": "[\"object\",\"null\"] is still a header container: a non-object value is dropped", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": ["object", "null"] + } + } + }, + "arguments": { + "headers": "abc" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers", + "reason": "not-an-object" + } + ] + }, + { + "id": "string-typed-is-ordinary", + "description": "a headers property typed string is an ordinary field: its value is forwarded unchanged", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "string" + } + } + }, + "arguments": { + "headers": "abc" + }, + "expected_arguments": { + "headers": "abc" + }, + "expected_warnings": [] + }, + { + "id": "string-typed-array-value-is-ordinary", + "description": "an ordinary field's value is forwarded whatever its type", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "string" + } + } + }, + "arguments": { + "headers": ["a"] + }, + "expected_arguments": { + "headers": ["a"] + }, + "expected_warnings": [] + }, + { + "id": "string-or-null-is-ordinary", + "description": "[\"string\",\"null\"] is an ordinary field", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": ["string", "null"] + } + } + }, + "arguments": { + "headers": "abc" + }, + "expected_arguments": { + "headers": "abc" + }, + "expected_warnings": [] + }, + { + "id": "array-typed-is-ordinary", + "description": "a headers property typed array is an ordinary field", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "array" + } + } + }, + "arguments": { + "headers": [["x-account-id", "B"]] + }, + "expected_arguments": { + "headers": [["x-account-id", "B"]] + }, + "expected_warnings": [] + }, + { + "id": "string-typed-object-value-still-filtered", + "description": "the ordinary-field exception covers non-object values only: an object is still filtered, and declares nothing", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "string" + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": {} + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-custom", + "reason": "not-declared" + } + ] + }, + { + "id": "no-headers-schema-object", + "description": "with no headers property served, a nested headers object declares nothing", + "schema": { + "type": "object", + "properties": { + "path_id": {} + } + }, + "arguments": { + "path_id": "e", + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "path_id": "e", + "headers": {} + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-custom", + "reason": "not-declared" + } + ] + }, + { + "id": "no-headers-schema-non-object", + "description": "with no headers property served, a non-object headers value is dropped", + "schema": { + "type": "object", + "properties": { + "path_id": {} + } + }, + "arguments": { + "path_id": "e", + "headers": "abc" + }, + "expected_arguments": { + "path_id": "e" + }, + "expected_warnings": [ + { + "argument": "headers", + "reason": "not-an-object" + } + ] + }, + { + "id": "non-object-string", + "description": "a non-object headers argument is dropped entirely, not sent as {}", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object" + } + } + }, + "arguments": { + "headers": "x-account-id: B" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers", + "reason": "not-an-object" + } + ] + }, + { + "id": "non-object-array", + "description": "an array of pairs is not an object: dropped", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object" + } + } + }, + "arguments": { + "headers": [["x-account-id", "B"]] + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers", + "reason": "not-an-object" + } + ] + }, + { + "id": "non-object-number", + "description": "a number is not an object: dropped", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object" + } + } + }, + "arguments": { + "headers": 5 + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers", + "reason": "not-an-object" + } + ] + }, + { + "id": "non-object-boolean", + "description": "a boolean is not an object: dropped", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object" + } + } + }, + "arguments": { + "headers": true + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers", + "reason": "not-an-object" + } + ] + }, + { + "id": "non-object-null", + "description": "null is not an object: dropped, with a warning", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object" + } + } + }, + "arguments": { + "headers": null + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers", + "reason": "not-an-object" + } + ] + }, + { + "id": "flat-exact-match", + "description": "a flat headers_ is declared only by the identical top-level property, and forwarded as given", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "path_id": "e", + "headers_x-custom": "abc" + }, + "expected_arguments": { + "path_id": "e", + "headers_x-custom": "abc" + }, + "expected_warnings": [] + }, + { + "id": "flat-case-mismatch", + "description": "flat names are matched exactly, not case-insensitively", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_X-Custom": "abc" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_X-Custom", + "reason": "not-declared" + } + ] + }, + { + "id": "flat-undeclared", + "description": "an undeclared flat header is dropped", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-other": "abc" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_x-other", + "reason": "not-declared" + } + ] + }, + { + "id": "flat-number-as-given", + "description": "a flat number is forwarded as a number, not stringified", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-custom": 7 + }, + "expected_arguments": { + "headers_x-custom": 7 + }, + "expected_warnings": [] + }, + { + "id": "flat-float-as-given", + "description": "a flat float is forwarded as given", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-custom": 1.5 + }, + "expected_arguments": { + "headers_x-custom": 1.5 + }, + "expected_warnings": [] + }, + { + "id": "flat-boolean-as-given", + "description": "a flat boolean is forwarded as given", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-custom": true + }, + "expected_arguments": { + "headers_x-custom": true + }, + "expected_warnings": [] + }, + { + "id": "flat-empty-string", + "description": "an empty flat string is a valid value", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-custom": "" + }, + "expected_arguments": { + "headers_x-custom": "" + }, + "expected_warnings": [] + }, + { + "id": "flat-array-dropped", + "description": "a flat array is dropped, CRLF and all", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-custom": ["a\r\nx-account-id: B"] + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_x-custom", + "reason": "not-a-scalar" + } + ] + }, + { + "id": "flat-object-dropped", + "description": "a flat object is dropped", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-custom": { + "k": 1 + } + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_x-custom", + "reason": "not-a-scalar" + } + ] + }, + { + "id": "flat-array-undeclared-dropped", + "description": "the value check comes first: an undeclared flat array is reported as not-a-scalar", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-other": ["a"] + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_x-other", + "reason": "not-a-scalar" + } + ] + }, + { + "id": "flat-null-dropped-silently", + "description": "a flat null is dropped silently, declared or not", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-custom": null, + "headers_x-other": null + }, + "expected_arguments": {}, + "expected_warnings": [] + }, + { + "id": "flat-owned-declared", + "description": "a declared flat SDK-owned header is never forwarded", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_authorization": "Bearer x" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_authorization", + "reason": "set-by-sdk" + } + ] + }, + { + "id": "flat-owned-undeclared", + "description": "an owned name is reported as set-by-sdk before declaration is checked, whatever its case or surrounding space", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_X-Account-Id": "victim", + "headers_ user-agent": "evil/0" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_X-Account-Id", + "reason": "set-by-sdk" + }, + { + "argument": "headers_ user-agent", + "reason": "set-by-sdk" + } + ] + }, + { + "id": "flat-malformed-value", + "description": "a declared flat header with CRLF in its value is malformed", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "headers_x-custom": "a\r\nb" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_x-custom", + "reason": "malformed" + } + ] + }, + { + "id": "flat-malformed-name", + "description": "a declared flat header whose name is not a token is malformed", + "schema": { + "type": "object", + "properties": { + "headers_x custom": { + "type": "string" + } + } + }, + "arguments": { + "headers_x custom": "a" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_x custom", + "reason": "malformed" + } + ] + }, + { + "id": "flat-empty-name", + "description": "a declared headers_ with an empty name is malformed", + "schema": { + "type": "object", + "properties": { + "headers_": { + "type": "string" + } + } + }, + "arguments": { + "headers_": "a" + }, + "expected_arguments": {}, + "expected_warnings": [ + { + "argument": "headers_", + "reason": "malformed" + } + ] + }, + { + "id": "non-header-arguments-untouched", + "description": "only `headers` and the `headers_` prefix are header arguments: Headers, header_x, headers-x and a headers key inside body are not", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-custom": { + "type": "string" + }, + "headers_authorization": { + "type": "string" + } + } + }, + "arguments": { + "path_id": "e", + "body": { + "headers": { + "authorization": "x" + } + }, + "Headers": { + "authorization": "x" + }, + "header_x": "a", + "headers-x": "b", + "x_headers_y": 1 + }, + "expected_arguments": { + "path_id": "e", + "body": { + "headers": { + "authorization": "x" + } + }, + "Headers": { + "authorization": "x" + }, + "header_x": "a", + "headers-x": "b", + "x_headers_y": 1 + }, + "expected_warnings": [] + }, + { + "id": "flat-and-nested-together", + "description": "nested and flat header arguments are filtered independently", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "properties": { + "x-custom": {} + } + }, + "headers_x-custom": {} + } + }, + "arguments": { + "headers": { + "x-custom": "a" + }, + "headers_x-custom": "b", + "headers_x-other": "c" + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + }, + "headers_x-custom": "b" + }, + "expected_warnings": [ + { + "argument": "headers_x-other", + "reason": "not-declared" + } + ] + }, + { + "id": "object-or-null-open", + "description": "headers typed [\"object\",\"null\"] with no properties (and additionalProperties not false) is OPEN, the same as `type: \"object\"`: a type list containing \"object\" declares every name, so x-custom is forwarded.", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": ["object", "null"] + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [] + }, + { + "id": "empty-type-list", + "description": "headers typed [] (an empty list) is an ORDINARY field: the list does not contain \"object\", so headers is not a header container and the string is forwarded unchanged, with no header filtering.", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": [] + } + } + }, + "arguments": { + "headers": "abc" + }, + "expected_arguments": { + "headers": "abc" + }, + "expected_warnings": [] + } + ] +} diff --git a/tests/vectors/header-names.json b/tests/vectors/header-names.json new file mode 100644 index 00000000..4048cf55 --- /dev/null +++ b/tests/vectors/header-names.json @@ -0,0 +1,383 @@ +{ + "$schema": "./schema/header-names.schema.json", + "description": "How a nested header name — an entry of a top-level `headers` object argument whose served schema is open (`{\"type\": \"object\"}`), with the value \"v\" — is treated. The name is trimmed of what JavaScript's String.prototype.trim() strips, then refused if it is SDK-owned (authorization, x-account-id, user-agent, case-insensitively), then if it is not an RFC 9110 token. A forwarded name is the trimmed one.", + "version": 1, + "cases": [ + { + "id": "plain", + "description": "a plain token", + "name": "x-custom", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "mixed-case", + "description": "case is kept as supplied", + "name": "X-Custom", + "expected": { + "forwarded": "X-Custom" + } + }, + { + "id": "token-chars", + "description": "every RFC 9110 tchar", + "name": "x_c.u!s#t$o%m&'*+^`|~", + "expected": { + "forwarded": "x_c.u!s#t$o%m&'*+^`|~" + } + }, + { + "id": "leading-space", + "description": "leading space is trimmed", + "name": " x-custom", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "trailing-space", + "description": "trailing space is trimmed", + "name": "x-custom ", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "tab", + "description": "tabs are trimmed", + "name": "\tx-custom\t", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "newline-ends", + "description": "CR and LF at the ends are trimmed", + "name": "\nx-custom\r\n", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "vt-ff", + "description": "vertical tab and form feed are trimmed", + "name": "\u000bx-custom\f", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "nbsp", + "description": "U+00A0 NO-BREAK SPACE is JavaScript whitespace: trimmed", + "name": "\u00a0x-custom\u00a0", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "bom", + "description": "U+FEFF BYTE ORDER MARK is JavaScript whitespace: trimmed", + "name": "\ufeffx-custom", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "ogham", + "description": "U+1680 OGHAM SPACE MARK is trimmed", + "name": "\u1680x-custom", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "en-quad", + "description": "U+2000 EN QUAD is trimmed", + "name": "\u2000x-custom", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "hair-space", + "description": "U+200A HAIR SPACE is trimmed", + "name": "x-custom\u200a", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "line-separator", + "description": "U+2028 LINE SEPARATOR is a JavaScript line terminator: trimmed", + "name": "\u2028x-custom\u2029", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "narrow-nbsp", + "description": "U+202F NARROW NO-BREAK SPACE is trimmed", + "name": "\u202fx-custom", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "math-space", + "description": "U+205F MEDIUM MATHEMATICAL SPACE is trimmed", + "name": "\u205fx-custom", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "ideographic-space", + "description": "U+3000 IDEOGRAPHIC SPACE is trimmed", + "name": "\u3000x-custom", + "expected": { + "forwarded": "x-custom" + } + }, + { + "id": "fs", + "description": "U+001C is not JavaScript whitespace (Python's str.strip() would strip it): kept, so malformed", + "name": "\u001cx-custom", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "gs", + "description": "U+001D is not trimmed: malformed", + "name": "x-custom\u001d", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "rs", + "description": "U+001E is not trimmed: malformed", + "name": "\u001ex-custom", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "us", + "description": "U+001F is not trimmed: malformed", + "name": "x-custom\u001f", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "nel", + "description": "U+0085 NEXT LINE is not JavaScript whitespace (str.strip() would strip it): malformed", + "name": "\u0085x-custom", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "zwsp", + "description": "U+200B ZERO WIDTH SPACE is not whitespace: malformed", + "name": "\u200bx-custom", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "non-ascii", + "description": "a non-ASCII letter is not a tchar", + "name": "x-cüstom", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "non-ascii-cjk", + "description": "a CJK character is not a tchar", + "name": "x-頭", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "inner-space", + "description": "a space inside the name is not trimmed: malformed", + "name": "x custom", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "colon", + "description": "a colon is not a tchar", + "name": "x-custom:", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "empty", + "description": "an empty name is malformed", + "name": "", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "whitespace-only", + "description": "whitespace only trims to empty: malformed", + "name": " ", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "owned-authorization", + "description": "SDK-owned", + "name": "authorization", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-upper", + "description": "SDK-owned, compared case-insensitively", + "name": "AUTHORIZATION", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-mixed", + "description": "SDK-owned, as usually written", + "name": "Authorization", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-account", + "description": "SDK-owned tenant selector", + "name": "X-Account-Id", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-ua", + "description": "SDK-owned client identity", + "name": "User-Agent", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-padded", + "description": "SDK-owned once trimmed", + "name": " authorization ", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-tab", + "description": "SDK-owned once trimmed", + "name": "\tx-account-id", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-nbsp", + "description": "SDK-owned once U+00A0 is trimmed", + "name": "\u00a0User-Agent", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-bom", + "description": "SDK-owned once the BOM is trimmed", + "name": "\ufeffauthorization", + "expected": { + "dropped": "set-by-sdk" + } + }, + { + "id": "owned-us-suffix", + "description": "U+001F is not trimmed, so this is not the owned name: it is malformed", + "name": "authorization\u001f", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "owned-nel", + "description": "U+0085 is not trimmed, so this is not the owned name: it is malformed", + "name": "\u0085x-account-id", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "owned-dotted-i", + "description": "U+0130 lower-cases to i + U+0307, not i: not owned, and malformed", + "name": "AUTHORİZATION", + "expected": { + "dropped": "malformed" + } + }, + { + "id": "not-owned-similar", + "description": "a name that merely starts with an owned one is not owned", + "name": "x-account-id-2", + "expected": { + "forwarded": "x-account-id-2" + } + }, + { + "id": "proxy-authorization", + "description": "only the three names are owned; others are declared by the open schema", + "name": "Proxy-Authorization", + "expected": { + "forwarded": "Proxy-Authorization" + } + }, + { + "id": "proto-name", + "description": "__proto__ is an ordinary header name", + "name": "__proto__", + "expected": { + "forwarded": "__proto__" + } + }, + { + "id": "constructor-name", + "description": "constructor is an ordinary header name", + "name": "constructor", + "expected": { + "forwarded": "constructor" + } + }, + { + "id": "upper-case", + "description": "upper case kept as supplied", + "name": "X-CUSTOM", + "expected": { + "forwarded": "X-CUSTOM" + } + }, + { + "id": "owned-long-s", + "description": "U+017F LATIN SMALL LETTER LONG S. The SDK-owned check lowercases ASCII only, so uſer-agent is never folded to user-agent: it is not owned, and ſ is not a tchar, so it is malformed.", + "name": "uſer-agent", + "expected": { + "dropped": "malformed" + } + } + ] +} diff --git a/tests/vectors/header-values.json b/tests/vectors/header-values.json new file mode 100644 index 00000000..58722b9e --- /dev/null +++ b/tests/vectors/header-values.json @@ -0,0 +1,307 @@ +{ + "$schema": "./schema/header-values.schema.json", + "description": "How a nested header value — an entry of a top-level `headers` object argument whose served schema is open (`{\"type\": \"object\"}`), under the declared name `x-probe` — reaches the wire: the string forwarded, or dropped. Values are JSON; `{\"$number\": \"NaN\"}`, `\"Infinity\"` and `\"-Infinity\"` stand for the non-finite numbers JSON cannot hold.", + "version": 1, + "cases": [ + { + "id": "string", + "description": "a string is forwarded as is", + "value": "abc", + "expected": "abc" + }, + { + "id": "empty-string", + "description": "an empty string is a valid header value", + "value": "", + "expected": "" + }, + { + "id": "string-with-space", + "description": "a space is allowed", + "value": "a b", + "expected": "a b" + }, + { + "id": "string-with-tab", + "description": "a tab is allowed", + "value": "a\tb", + "expected": "a\tb" + }, + { + "id": "latin1", + "description": "obs-text (U+0080-U+00FF) is allowed", + "value": "café", + "expected": "café" + }, + { + "id": "non-latin1", + "description": "a character above U+00FF is malformed", + "value": "€", + "expected": { + "dropped": true + } + }, + { + "id": "emoji", + "description": "an astral character is malformed", + "value": "🙂", + "expected": { + "dropped": true + } + }, + { + "id": "crlf", + "description": "CRLF would smuggle a second header line: malformed", + "value": "a\r\nx-account-id: B", + "expected": { + "dropped": true + } + }, + { + "id": "lf-trailing", + "description": "a trailing LF is malformed (a `$` anchor must not let it through)", + "value": "abc\n", + "expected": { + "dropped": true + } + }, + { + "id": "cr", + "description": "a bare CR is malformed", + "value": "a\rb", + "expected": { + "dropped": true + } + }, + { + "id": "nul", + "description": "NUL is malformed", + "value": "a\u0000b", + "expected": { + "dropped": true + } + }, + { + "id": "del", + "description": "DEL (0x7f) is malformed", + "value": "a\u007fb", + "expected": { + "dropped": true + } + }, + { + "id": "true", + "description": "a boolean as its literal text", + "value": true, + "expected": "true" + }, + { + "id": "false", + "description": "a boolean as its literal text", + "value": false, + "expected": "false" + }, + { + "id": "zero", + "description": "zero", + "value": 0, + "expected": "0" + }, + { + "id": "int", + "description": "an integer", + "value": 7, + "expected": "7" + }, + { + "id": "negative-int", + "description": "a negative integer", + "value": -3, + "expected": "-3" + }, + { + "id": "float-integral", + "description": "an integral float is written as JavaScript writes it: 1, not 1.0", + "value": 1, + "expected": "1" + }, + { + "id": "float", + "description": "a float", + "value": 1.5, + "expected": "1.5" + }, + { + "id": "negative-float", + "description": "a negative float", + "value": -0.5, + "expected": "-0.5" + }, + { + "id": "negative-zero", + "description": "negative zero is written 0", + "value": 0, + "expected": "0" + }, + { + "id": "exp-small", + "description": "below 1e-6, exponent notation, written as JavaScript does", + "value": 1e-7, + "expected": "1e-7" + }, + { + "id": "exp-boundary-small", + "description": "1e-6 is still written in full", + "value": 1e-6, + "expected": "0.000001" + }, + { + "id": "exp-large", + "description": "from 1e21, exponent notation with an explicit +", + "value": 1e21, + "expected": "1e+21" + }, + { + "id": "exp-boundary-large", + "description": "1e20 is still written in full", + "value": 1e20, + "expected": "100000000000000000000" + }, + { + "id": "exp-large-fraction", + "description": "a large exponent with a fraction", + "value": 1.5e300, + "expected": "1.5e+300" + }, + { + "id": "float-repr", + "description": "the shortest representation that round-trips", + "value": 0.30000000000000004, + "expected": "0.30000000000000004" + }, + { + "id": "safe-int", + "description": "the largest integer both languages hold exactly", + "value": 9007199254740991, + "expected": "9007199254740991" + }, + { + "id": "nan", + "description": "NaN as its text (a JSON argument cannot hold it; see argument-encoding.json for what else happens)", + "value": { + "$number": "NaN" + }, + "expected": "NaN" + }, + { + "id": "infinity", + "description": "Infinity as its text", + "value": { + "$number": "Infinity" + }, + "expected": "Infinity" + }, + { + "id": "neg-infinity", + "description": "-Infinity as its text", + "value": { + "$number": "-Infinity" + }, + "expected": "-Infinity" + }, + { + "id": "object", + "description": "an object as compact JSON", + "value": { + "k": 1 + }, + "expected": "{\"k\":1}" + }, + { + "id": "object-nested", + "description": "nested values as compact JSON, numbers as JavaScript writes them", + "value": { + "a": { + "b": [1, 2, true, null] + } + }, + "expected": "{\"a\":{\"b\":[1,2,true,null]}}" + }, + { + "id": "object-float", + "description": "floats inside JSON as JavaScript writes them", + "value": { + "x": 1, + "y": 1e21 + }, + "expected": "{\"x\":1,\"y\":1e+21}" + }, + { + "id": "object-non-ascii", + "description": "non-ASCII stays unescaped in the JSON text, and is valid obs-text", + "value": { + "k": "é" + }, + "expected": "{\"k\":\"é\"}" + }, + { + "id": "object-euro", + "description": "non-ASCII above U+00FF stays unescaped, so the JSON text is malformed as a header", + "value": { + "k": "€" + }, + "expected": { + "dropped": true + } + }, + { + "id": "object-escapes", + "description": "JSON escapes for quote, backslash and newline keep the text on one line", + "value": { + "k": "a\"b\\c\nd" + }, + "expected": "{\"k\":\"a\\\"b\\\\c\\nd\"}" + }, + { + "id": "object-empty", + "description": "an empty object", + "value": {}, + "expected": "{}" + }, + { + "id": "array", + "description": "an array as compact JSON", + "value": ["a", "b"], + "expected": "[\"a\",\"b\"]" + }, + { + "id": "array-empty", + "description": "an empty array", + "value": [], + "expected": "[]" + }, + { + "id": "array-mixed", + "description": "mixed array values as compact JSON", + "value": [true, 1.5, null, "x"], + "expected": "[true,1.5,null,\"x\"]" + }, + { + "id": "null", + "description": "null is dropped silently, with no warning", + "value": null, + "expected": { + "dropped": true + } + } + ], + "known_differences": [ + { + "id": "big-int", + "description": "an integer above 2^53. Not graded: by the time this value reaches header filtering, the SDK's own JSON parser has already rounded it, so what is forwarded is an artifact of each language's JSON number type, not a choice the header-value rule makes. Python's JSON parser keeps every digit; Node's JSON numbers are doubles, so JSON.parse already rounds it before this code ever sees it.", + "value": 12345678901234567890, + "python": "12345678901234567890", + "node": "12345678901234567000" + } + ] +} diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json new file mode 100644 index 00000000..cbdf3a5d --- /dev/null +++ b/tests/vectors/messages.json @@ -0,0 +1,1021 @@ +{ + "$schema": "./schema/messages.schema.json", + "description": "The canonical wording of every user-facing warning and error message both SDKs emit. `template` is the canonical text; `python` and `node` are each SDK's text today, written with the same placeholders (and `|` between variants), so an SDK can see what changes. A prefix the language adds — Node's `[@stackone/ai] `, Python's logger name — is outside the template. An error's class is in `error`. `matches` says whether an SDK's text is already the canonical one, reading a value written raw between double quotes as its JSON text — the same for every ordinary value; the notes say where not.", + "version": 1, + "prefixes": { + "node": "Every warning goes through console.warn, prefixed `[@stackone/ai] ` — outside the template.", + "python": "Every warning is a WARNING record on a `stackone.*` logger; its getMessage() is the template, rendered." + }, + "formats": { + "text": "Inserted as is.", + "json": "Compact JSON text: JSON.stringify(value), json.dumps(value, ensure_ascii=False, separators=(\",\", \":\")). A string comes out in double quotes.", + "integer": "Decimal digits.", + "seconds": "A number of seconds as JavaScript's String(number) writes it: 1, 0.5, 1.25 — never 1.0, never padded, never exponent form for values in [1e-6, 1e21).", + "seconds-2dp": "The seconds rounded half up to two decimals, Math.floor(x * 100 + 0.5) / 100, then written as `seconds`: 0, 0.75, 1.5.", + "json-type": "The JSON type of the value: object, array, string, number, boolean or null.", + "reason": "The text for a header reason code, from `reasons`." + }, + "reasons": { + "set-by-sdk": "set by the SDK", + "not-declared": "not declared by the schema", + "malformed": "malformed", + "not-an-object": "not an object", + "not-a-scalar": "not a string, number or boolean" + }, + "messages": [ + { + "id": "header-dropped", + "kind": "warning", + "template": "Dropping header {header} from a tool call: {reason}", + "placeholders": { + "header": { + "format": "json", + "description": "the nested header name, trimmed" + }, + "reason": { + "format": "reason", + "description": "set-by-sdk, not-declared or malformed" + } + }, + "python": "Dropping header {header!r} from a tool call: it is {reason} | Dropping malformed header {header!r} from a tool call", + "node": "Dropping header \"{header}\" from a tool call: {reason}", + "matches": { + "python": false, + "node": true + }, + "notes": "Python quotes with repr ('x'), prefixes the reason with \"it is\", and words malformed differently. Node writes the name raw between double quotes; the canonical form JSON-escapes it, which only differs for a name holding a quote, a backslash or a control character." + }, + { + "id": "header-argument-dropped", + "kind": "warning", + "template": "Dropping header argument {argument} from a tool call: {reason}", + "placeholders": { + "argument": { + "format": "json", + "description": "the top-level argument: headers, or headers_ as supplied" + }, + "reason": { + "format": "reason", + "description": "any reason code" + } + }, + "python": "Dropping header argument {argument!r} from a tool call: it is {reason} | … : not a string, number or boolean | … 'headers' … : not an object | Dropping malformed header argument {argument!r} from a tool call", + "node": "Dropping header argument \"{argument}\" from a tool call: {reason}", + "matches": { + "python": false, + "node": true + }, + "notes": "As header-dropped. Python's not-a-scalar and not-an-object texts already match; its set-by-sdk and not-declared add \"it is\"." + }, + { + "id": "rate-limit-retry", + "kind": "warning", + "template": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; retrying in {delay}s", + "placeholders": { + "method": { + "format": "text", + "description": "the HTTP method" + }, + "url": { + "format": "text", + "description": "the request URL" + }, + "attempt": { + "format": "integer", + "description": "the attempt that was answered 429, 1-based" + }, + "max_attempts": { + "format": "integer", + "description": "4" + }, + "delay": { + "format": "seconds-2dp", + "description": "the wait before the next attempt" + } + }, + "python": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; retrying in {delay:.2f}s", + "node": "Rate limited (429) by {method} {url}; retrying in {delay_ms}ms (attempt {attempt + 1} of {max_attempts})", + "matches": { + "python": false, + "node": false + }, + "notes": "Python's sentence is the clearer one: it names the attempt that failed. Node numbers the attempt about to be made, so the two count one apart. Python pads the delay to two decimals (0.00s); the canonical form writes it as a number (0s, 0.75s)." + }, + { + "id": "rate-limit-deadline", + "kind": "warning", + "template": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; not retrying, because waiting {delay}s would pass the deadline", + "placeholders": { + "method": { + "format": "text", + "description": "the HTTP method" + }, + "url": { + "format": "text", + "description": "the request URL" + }, + "attempt": { + "format": "integer", + "description": "the attempt that was answered 429, 1-based" + }, + "max_attempts": { + "format": "integer", + "description": "4" + }, + "delay": { + "format": "seconds-2dp", + "description": "the wait before the next attempt that would pass the deadline" + } + }, + "python": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; not retrying, because waiting {delay:.2f}s would outlast the request's deadline ({remaining:.2f}s left)", + "node": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; not retrying, because waiting {delay}s would pass the deadline", + "matches": { + "python": false, + "node": true + }, + "notes": "Both SDKs now emit this, in the style of rate-limit-retry: when the next wait would not finish before the call's deadline, the SDK raises the 429 it already has instead of sleeping. Python's sentence also names how much of the deadline is left ({remaining:.2f}s); the canonical form drops it, as rate-limit-retry drops Python's two-decimal padding." + }, + { + "id": "skip-account", + "kind": "warning", + "template": "Skipping account that failed to list tools — {account_id}: {error}", + "placeholders": { + "account_id": { + "format": "text", + "description": "the account's id" + }, + "error": { + "format": "text", + "description": "the failure's own message" + } + }, + "python": "Skipping account that failed to list tools — {account_id}: {error}", + "node": "Skipping account that failed to list tools — {account_id}: {error}", + "matches": { + "python": true, + "node": true + }, + "notes": "Identical; the error part is whichever message the failure carries, so it matches only where that message does." + }, + { + "id": "skip-connector", + "kind": "warning", + "template": "Skipping connector that failed to search — {tool}: {error}", + "placeholders": { + "tool": { + "format": "text", + "description": "the *_search_actions tool's name" + }, + "error": { + "format": "text", + "description": "the failure's own message" + } + }, + "python": "Skipping connector that failed to search — {tool}: {error}", + "node": "Skipping connector that failed to search — {tool}: {error}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "duplicate-tool-names", + "kind": "warning", + "template": "{count} tool name(s) are served by more than one account ({names}). Looking a tool up by name returns the first one listed — pass account ids to choose.", + "placeholders": { + "count": { + "format": "integer", + "description": "how many names clash" + }, + "names": { + "format": "text", + "description": "up to five of them, sorted, joined by \", \"" + } + }, + "python": "{count} tool name(s) are served by more than one account ({names}). get_tool() will return the first one listed — pass account_ids to choose.", + "node": "{count} tool name(s) are served by more than one account ({names}). getTool() will return the first one listed — pass accountIds to choose.", + "matches": { + "python": false, + "node": false + }, + "notes": "Language-neutral wording in place of each SDK's method and parameter names." + }, + { + "id": "ambiguous-connector", + "kind": "warning", + "template": "{action_id} matches {count} connectors ({tools}); using {tool}. Pass account ids to choose.", + "placeholders": { + "action_id": { + "format": "json", + "description": "the action id" + }, + "count": { + "format": "integer", + "description": "how many connectors match" + }, + "tools": { + "format": "text", + "description": "the matching *_execute_action tools, joined by \", \"" + }, + "tool": { + "format": "text", + "description": "the one used" + } + }, + "python": "{action_id!r} matches {count} connectors ({tools}); using {tool}. Pass account_ids to choose.", + "node": "\"{action_id}\" matches {count} connectors ({tools}); using {tool}. Pass accountIds to choose.", + "matches": { + "python": false, + "node": false + } + }, + { + "id": "mcp-timeout", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "MCP request to {endpoint} timed out after {timeout}s", + "placeholders": { + "endpoint": { + "format": "text", + "description": "the MCP endpoint URL, with its ?tool-mode query when it has one" + }, + "timeout": { + "format": "seconds", + "description": "the toolset's timeout" + } + }, + "python": "MCP request to {endpoint} timed out after {timeout:g}s", + "node": "MCP request to {endpoint} timed out after {timeout_ms}ms", + "matches": { + "python": false, + "node": false + }, + "notes": "Seconds, written as a number: 1s, 0.5s, 60s. Python's :g agrees for ordinary values but switches to exponent form below 1e-4 (1e-05s); Node gives milliseconds." + }, + { + "id": "mcp-http-failure", + "kind": "error", + "error": { + "python": "StackOneAPIError", + "node": "StackOneAPIError" + }, + "template": "MCP request to {endpoint} failed with {status} {reason_phrase}: {body}", + "placeholders": { + "endpoint": { + "format": "text", + "description": "the MCP endpoint URL, with its ?tool-mode query when it has one" + }, + "status": { + "format": "integer", + "description": "the HTTP status" + }, + "reason_phrase": { + "format": "text", + "description": "the status's reason phrase" + }, + "body": { + "format": "text", + "description": "the response body, trimmed; with an empty body the \": {body}\" suffix is omitted" + } + }, + "python": "MCP request to {endpoint} failed with {status} {reason_phrase}: {body}", + "node": "MCP request to {endpoint} failed with {status} {reason_phrase}: {body}", + "matches": { + "python": true, + "node": true + }, + "notes": "Identical for every status with a reason phrase. For one without, Node trims the trailing space and Python keeps it; the canonical form trims it." + }, + { + "id": "mcp-failure", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "MCP request to {endpoint} failed: {error_type}: {error_message}", + "placeholders": { + "endpoint": { + "format": "text", + "description": "the MCP endpoint URL, with its ?tool-mode query when it has one" + }, + "error_type": { + "format": "text", + "description": "the innermost cause's class name, which is the language's own" + }, + "error_message": { + "format": "text", + "description": "its message" + } + }, + "python": "MCP request to {endpoint} failed: {error_type}: {error_message}", + "node": "MCP request to {endpoint} failed: {error_type}: {error_message}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "accounts-http-failure", + "kind": "error", + "error": { + "python": "StackOneAPIError", + "node": "StackOneAPIError" + }, + "template": "Listing accounts at {url} failed with {status} {reason_phrase}: {body}", + "placeholders": { + "url": { + "format": "text", + "description": "the /accounts URL" + }, + "status": { + "format": "integer", + "description": "the HTTP status" + }, + "reason_phrase": { + "format": "text", + "description": "the reason phrase" + }, + "body": { + "format": "text", + "description": "the response body, trimmed" + } + }, + "python": "Listing accounts at {url} failed with {status} {reason_phrase}: {body}", + "node": "Listing accounts at {url} failed with {status} {reason_phrase}: {body}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "accounts-unreachable", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "Could not reach {url}: {detail}", + "placeholders": { + "url": { + "format": "text", + "description": "the /accounts URL" + }, + "detail": { + "format": "text", + "description": "the transport's own message" + } + }, + "python": "Could not reach {url}: {detail}", + "node": "Could not reach {url}: {detail}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "accounts-invalid-json", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "Invalid JSON returned by {url}: {detail}", + "placeholders": { + "url": { + "format": "text", + "description": "the /accounts URL" + }, + "detail": { + "format": "text", + "description": "the parser's own message" + } + }, + "python": "Invalid JSON returned by {url}: {detail}", + "node": "Invalid JSON returned by {url}: {detail}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "accounts-unexpected-shape", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "Unexpected /accounts response shape: expected a list, got {json_type}", + "placeholders": { + "json_type": { + "format": "json-type", + "description": "object, string, number, boolean or null" + } + }, + "python": "Unexpected /accounts response shape: expected a list, got {type(accounts).__name__}", + "node": "Unexpected /accounts response shape: expected a list, got {typeof accounts}", + "matches": { + "python": false, + "node": false + }, + "notes": "Python gives its own type name (dict, str, NoneType); Node gives typeof (object, string) and null. The canonical form names the JSON type." + }, + { + "id": "no-linked-accounts", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "This API key has no linked accounts. Link one in the StackOne dashboard, or pass an account id explicitly.", + "placeholders": {}, + "python": "This API key has no linked accounts. Link one in the StackOne dashboard, or pass account_id explicitly.", + "node": "This API key has no linked accounts. Link one in the StackOne dashboard, or pass accountId explicitly.", + "matches": { + "python": false, + "node": false + } + }, + { + "id": "no-active-accounts", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "None of this API key's {count} linked accounts are active: {accounts}. Re-link them in the StackOne dashboard, or pass an account id explicitly.", + "placeholders": { + "count": { + "format": "integer", + "description": "how many accounts are linked" + }, + "accounts": { + "format": "text", + "description": "each as \"{provider} ({status})\", joined by \", \"" + } + }, + "python": "None of this API key's {count} linked accounts are active: {accounts}. Re-link them in the StackOne dashboard, or pass account_id explicitly.", + "node": "None of this API key's {count} linked accounts are active: {accounts}. Re-link them in the StackOne dashboard, or pass accountId explicitly.", + "matches": { + "python": false, + "node": false + }, + "notes": "A missing provider or status is written None by Python and undefined by Node; neither is canonical yet." + }, + { + "id": "no-account-returned-tools", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "No account returned tools. {failures}", + "placeholders": { + "failures": { + "format": "text", + "description": "each as \"{account_id}: {error}\", joined by \" | \"" + } + }, + "python": "No account returned tools. {failures}", + "node": "No account returned tools. {failures}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "no-connector-returned-results", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "No connector returned results. {failures}", + "placeholders": { + "failures": { + "format": "text", + "description": "each as \"{tool}: {error}\", joined by \" | \"" + } + }, + "python": "No connector returned results. {failures}", + "node": "No connector returned results. {failures}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "fetch-tools-failed", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "Error fetching tools: {detail}", + "placeholders": { + "detail": { + "format": "text", + "description": "the unexpected failure's message" + } + }, + "python": "Error fetching tools: {detail}", + "node": "Error fetching tools: {detail}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "missing-api-key", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable", + "placeholders": {}, + "python": "API key must be provided either through api_key parameter or STACKONE_API_KEY environment variable", + "node": "API key must be provided either through the apiKey option or the STACKONE_API_KEY environment variable", + "matches": { + "python": false, + "node": false + } + }, + { + "id": "empty-account-id", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{parameter} must not be an empty string", + "placeholders": { + "parameter": { + "format": "text", + "description": "account_id / accountId" + } + }, + "python": "{parameter} must not be an empty string", + "node": "{parameter} must not be an empty string", + "matches": { + "python": true, + "node": true + }, + "notes": "The same once the parameter is named in each SDK's spelling." + }, + { + "id": "account-ids-not-a-list", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{parameter} must be a list of account ids, not a string. Did you mean [{value}]?", + "placeholders": { + "parameter": { + "format": "text", + "description": "the parameter's name in the SDK's own spelling: account_ids / accountIds" + }, + "value": { + "format": "json", + "description": "the string given" + } + }, + "python": "{parameter} must be a list of account ids, not a string. Did you mean [{value!r}]?", + "node": "{parameter} must be an array of account ids, not a string. Did you mean [\"{value}\"]?", + "matches": { + "python": false, + "node": false + }, + "notes": "\"list\", not \"array\": the language-neutral word. The suggestion is JSON, so it reads the same in both." + }, + { + "id": "account-ids-not-strings", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{parameter} must be a list of account id strings", + "placeholders": { + "parameter": { + "format": "text", + "description": "the parameter's name in the SDK's own spelling: account_ids / accountIds" + } + }, + "python": "{parameter} must be a list of account id strings, got {ids!r}", + "node": "{parameter} must be an array of account id strings", + "matches": { + "python": false, + "node": false + }, + "notes": "Python appends the list it was given, as a Python repr; dropped, since not every value it could hold is JSON." + }, + { + "id": "account-ids-empty-id", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{parameter} must not contain an empty account id", + "placeholders": { + "parameter": { + "format": "text", + "description": "the parameter's name in the SDK's own spelling: account_ids / accountIds" + } + }, + "python": "{parameter} must not contain an empty account id", + "node": "{parameter} must not contain an empty account id", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "invalid-session-id", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{parameter} must be a non-empty string, got {value}", + "placeholders": { + "parameter": { + "format": "text", + "description": "session_id / sessionId" + }, + "value": { + "format": "json", + "description": "the value given" + } + }, + "python": "{parameter} must be a non-empty string, got {value!r}", + "node": "{parameter} must be a non-empty string, got {value}", + "matches": { + "python": false, + "node": true + }, + "notes": "Node already writes the value as JSON; Python as a repr ('' rather than \"\"). Once null means \"not given\" (scenario execute-null-session-id), null no longer raises this." + }, + { + "id": "invalid-action-id", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{parameter} must be a non-empty string, got {value}", + "placeholders": { + "parameter": { + "format": "text", + "description": "action_id / actionId" + }, + "value": { + "format": "json", + "description": "the value given" + } + }, + "python": "{parameter} must be a non-empty string, got {value!r}", + "node": "{parameter} must be a non-empty string, got {value}", + "matches": { + "python": false, + "node": true + } + }, + { + "id": "execute-arguments-not-an-object", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "arguments must be a JSON object, got {json_type}", + "placeholders": { + "json_type": { + "format": "json-type", + "description": "array, string, number, boolean or null" + } + }, + "python": "arguments must be a JSON object, got {type(arguments).__name__}", + "node": "arguments must be a JSON object, got {json_type}", + "matches": { + "python": false, + "node": true + }, + "notes": "Python gives its own type name (list, str); Node already names the JSON type (array, string, null) — no object reaches this message." + }, + { + "id": "top-k-out-of-range", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{parameter} must be an integer between 1 and {max}, got {value}", + "placeholders": { + "parameter": { + "format": "text", + "description": "top_k / topK" + }, + "max": { + "format": "integer", + "description": "50" + }, + "value": { + "format": "json", + "description": "the value given" + } + }, + "python": "{parameter} must be an integer between 1 and {max}, got {top_k!r}", + "node": "{parameter} must be an integer between 1 and {max}, got {value}", + "matches": { + "python": false, + "node": true + } + }, + { + "id": "tool-names-not-a-list", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{parameter} must be a list of tool names, not a string. Did you mean [{value}]?", + "placeholders": { + "parameter": { + "format": "text", + "description": "tool_names / toolNames" + }, + "value": { + "format": "json", + "description": "the string given" + } + }, + "python": "{parameter} must be a list of tool names, not a string. Did you mean [{value!r}]?", + "node": "{parameter} must be an array of tool names, not a string. Did you mean [\"{value}\"]?", + "matches": { + "python": false, + "node": false + } + }, + { + "id": "feedback-not-enabled", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "The server did not serve stackone_submit_feedback: feedback is not enabled for this project.", + "placeholders": {}, + "python": "The server did not serve stackone_submit_feedback: feedback is not enabled for this project.", + "node": "The server did not serve stackone_submit_feedback: feedback is not enabled for this project.", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "no-connector-for-action", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "No connector found for {action_id}. Use search() to discover valid action ids.", + "placeholders": { + "action_id": { + "format": "json", + "description": "the action id" + } + }, + "python": "No connector found for \"{action_id}\". Use search() to discover valid action ids.", + "node": "No connector found for \"{action_id}\". Use search() to discover valid action ids.", + "matches": { + "python": true, + "node": true + }, + "notes": "Both write the id raw between double quotes, which is its JSON text for any ordinary id." + }, + { + "id": "arguments-not-finite", + "kind": "error", + "error": { + "python": "ToolArgumentsError", + "node": "ToolArgumentsError" + }, + "template": "Arguments for {tool} could not be encoded as JSON: {value} is not a JSON number", + "placeholders": { + "tool": { + "format": "json", + "description": "the tool's name" + }, + "value": { + "format": "text", + "description": "NaN, Infinity or -Infinity" + } + }, + "python": "Arguments for {tool!r} could not be encoded as JSON: Out of range float values are not JSON compliant: {nan | inf | -inf}", + "node": "Arguments for \"{tool}\" could not be encoded as JSON: Out of range number values are not JSON compliant: {value} (at \"{key}\")", + "matches": { + "python": false, + "node": false + }, + "notes": "Both pass on their JSON encoder's wording. The canonical form names the value in JavaScript's spelling and leaves out the location, which Python's encoder does not report." + }, + { + "id": "arguments-not-encodable", + "kind": "error", + "error": { + "python": "ToolArgumentsError", + "node": "ToolArgumentsError" + }, + "template": "Arguments for {tool} could not be encoded as JSON: {detail}", + "placeholders": { + "tool": { + "format": "json", + "description": "the tool's name" + }, + "detail": { + "format": "text", + "description": "the SDK's own explanation: a circular reference, a non-JSON type, …" + } + }, + "python": "Arguments for {tool!r} could not be encoded as JSON: {detail}", + "node": "Arguments for \"{tool}\" could not be encoded as JSON: {detail}", + "matches": { + "python": false, + "node": true + }, + "notes": "For every reason but a non-finite number, which has its own message above." + }, + { + "id": "arguments-invalid-json", + "kind": "error", + "error": { + "python": "ToolArgumentsError", + "node": "ToolArgumentsError" + }, + "template": "Invalid JSON in arguments for {tool}: {detail}", + "placeholders": { + "tool": { + "format": "json", + "description": "the tool's name" + }, + "detail": { + "format": "text", + "description": "the JSON parser's own message" + } + }, + "python": "Invalid JSON in arguments for {tool!r}: {detail}", + "node": "Invalid JSON in arguments for \"{tool}\": {detail}", + "matches": { + "python": false, + "node": true + } + }, + { + "id": "arguments-not-an-object", + "kind": "error", + "error": { + "python": "ToolArgumentsError", + "node": "ToolArgumentsError" + }, + "template": "Tool arguments for {tool} must be a JSON object", + "placeholders": { + "tool": { + "format": "json", + "description": "the tool's name" + } + }, + "python": "Tool arguments must be a JSON object", + "node": "Tool arguments for \"{tool}\" must be a JSON object | Invalid parameters type for \"{tool}\". Expected object or string, got {typeof}.", + "matches": { + "python": false, + "node": false + }, + "notes": "Node's clearer form, naming the tool. Node has a second message for a value that is neither an object nor a string; the canonical form uses this one for both." + }, + { + "id": "tool-call-failed", + "kind": "error", + "error": { + "python": "StackOneAPIError", + "node": "StackOneAPIError" + }, + "template": "Tool {tool} failed: {detail}", + "placeholders": { + "tool": { + "format": "json", + "description": "the tool's name" + }, + "detail": { + "format": "text", + "description": "the result's text, or its structured content as compact JSON" + } + }, + "python": "Tool \"{tool}\" failed: {detail}", + "node": "Tool \"{tool}\" failed: {detail}", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "no-executor", + "kind": "error", + "error": { + "python": "StackOneError", + "node": "StackOneError" + }, + "template": "Tool {tool} has no executor. Override execute() to run a hand-built tool.", + "placeholders": { + "tool": { + "format": "json", + "description": "the tool's name" + } + }, + "python": "Tool \"{tool}\" has no executor. Override execute() to run a hand-built tool.", + "node": "Tool \"{tool}\" has no executor. Override execute() to run a hand-built tool.", + "matches": { + "python": true, + "node": true + } + }, + { + "id": "unknown-tool", + "kind": "tool-result", + "template": "Unknown tool {name}", + "placeholders": { + "name": { + "format": "json", + "description": "the tool call's function name" + } + }, + "python": "Unknown tool {name!r}", + "node": "Unknown tool \"{name}\"", + "matches": { + "python": false, + "node": true + }, + "notes": "Not raised: the `error` of the tool message execute_openai_tool_calls / executeOpenAIToolCalls returns for a call to a tool not in the collection." + } + ], + "unshared": [ + { + "sdk": "python", + "kind": "error", + "text": "Cannot provide both positional and keyword arguments", + "notes": "call() only; Node has no call()." + }, + { + "sdk": "python", + "kind": "error", + "text": "Only one positional argument is allowed" + }, + { + "sdk": "python", + "kind": "error", + "text": "Tool \"{tool}\" has no API key to authenticate with." + }, + { + "sdk": "node", + "kind": "warning", + "text": "Ignoring headers {names}: the SDK sets them itself. Use the apiKey and accountId options instead.", + "notes": "Python's toolset takes no extra headers." + }, + { + "sdk": "node", + "kind": "error", + "text": "Cannot provide both accountId and accountIds. Use accountId for a single account or accountIds for multiple accounts." + }, + { + "sdk": "node", + "kind": "error", + "text": "query must be a string, got {typeof}" + }, + { + "sdk": "node", + "kind": "error", + "text": "toolNames must be an array of tool names" + }, + { + "sdk": "node", + "kind": "error", + "text": "Could not read the response from {url}: {detail}" + }, + { + "sdk": "node", + "kind": "tool-result", + "text": "Unsupported tool call type \"{type}\"" + }, + { + "sdk": "node", + "kind": "error", + "text": "Tool {name} is not a StackOne tool" + } + ] +} diff --git a/tests/vectors/retry-after.json b/tests/vectors/retry-after.json new file mode 100644 index 00000000..f4b426f0 --- /dev/null +++ b/tests/vectors/retry-after.json @@ -0,0 +1,318 @@ +{ + "$schema": "./schema/retry-after.schema.json", + "description": "How a Retry-After header value reads as seconds from `now`: delta-seconds or an HTTP-date. `expected_seconds` is the RAW value, before the cap: null when the header is absent or unreadable (the caller falls back to its own backoff), 0 for a date in the past. The cap (`max_delay_seconds`) is applied afterwards by the caller, and graded in backoff.json.", + "version": 1, + "max_delay_seconds": 30, + "cases": [ + { + "id": "delta", + "description": "delta-seconds", + "header": "5", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 5 + }, + { + "id": "zero", + "description": "zero delta-seconds: retry at once", + "header": "0", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 0 + }, + { + "id": "leading-zeros", + "description": "delta-seconds with leading zeros", + "header": "005", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 5 + }, + { + "id": "large", + "description": "20 digits: read as a number, not refused; the cap is applied separately, so this is the raw value", + "header": "99999999999999999999", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 100000000000000000000 + }, + { + "id": "huge", + "description": "309 digits overflow to infinity in both languages; the cap then makes it 30s", + "header": "999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": { + "$number": "Infinity" + } + }, + { + "id": "cap-boundary", + "description": "above the cap: recorded raw, the cap is applied separately", + "header": "31", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 31 + }, + { + "id": "imf", + "description": "IMF-fixdate (RFC 9110's preferred form), 30s ahead", + "header": "Thu, 01 Oct 2026 12:00:30 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 30 + }, + { + "id": "rfc850", + "description": "RFC 850 date, 60s ahead", + "header": "Thursday, 01-Oct-26 12:01:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 60 + }, + { + "id": "imf-past", + "description": "IMF-fixdate in the past: retry now", + "header": "Sun, 06 Nov 1994 08:49:37 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 0 + }, + { + "id": "imf-now", + "description": "IMF-fixdate equal to now: retry now", + "header": "Thu, 01 Oct 2026 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 0 + }, + { + "id": "rfc850-past", + "description": "RFC 850 date in the past (two-digit year 94 is 1994)", + "header": "Sunday, 06-Nov-94 08:49:37 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 0 + }, + { + "id": "asctime-past", + "description": "asctime date in the past; in the past in every time zone, so it is 0 wherever it is read", + "header": "Sun Nov 6 08:49:37 1994", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 0 + }, + { + "id": "weekday-mismatch", + "description": "the weekday does not match the date; it is ignored", + "header": "Mon, 01 Oct 2026 12:00:10 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 10 + }, + { + "id": "lower-weekday", + "description": "a lower-case weekday is not an HTTP-date", + "header": "thu, 01 Oct 2026 12:00:30 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "two-digit-year-imf", + "description": "an IMF-fixdate with a two-digit year (26) is read as 2026", + "header": "Thu, 01 Oct 26 12:00:30 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 30 + }, + { + "id": "rfc850-year-49", + "description": "RFC 850 two-digit year 49 is read as 2049 by both", + "header": "Friday, 01-Oct-49 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 725846400 + }, + { + "id": "rfc850-year-70", + "description": "RFC 850 two-digit year 70 is read as 1970 by both (RFC 9110's 50-year rule would say 2070: both SDKs agree on 1970 today)", + "header": "Wednesday, 01-Oct-70 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 0 + }, + { + "id": "offset-zone", + "description": "a numeric zone offset is honoured: 13:00:30 +0100 is 12:00:30 GMT", + "header": "Thu, 01 Oct 2026 13:00:30 +0100", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 30 + }, + { + "id": "day-32", + "description": "day 32 is not a date", + "header": "Thu, 32 Oct 2026 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "hour-25", + "description": "hour 25 is not a time", + "header": "Thu, 01 Oct 2026 25:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "year-overflow", + "description": "a year too large to represent (20 digits) is unreadable, not an error", + "header": "Thu, 01 Oct 99999999999999999999 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "fraction", + "description": "not delta-seconds: a fraction", + "header": "1.5", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "negative", + "description": "not delta-seconds: a sign", + "header": "-1", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "plus", + "description": "not delta-seconds: a plus sign", + "header": "+5", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "exponent", + "description": "not delta-seconds: exponent notation", + "header": "1.5e3", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "superscript", + "description": "not delta-seconds: a Unicode digit that is not ASCII", + "header": "²", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "arabic-digit", + "description": "not delta-seconds: an Arabic-Indic digit", + "header": "٣", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "iso-date", + "description": "an ISO 8601 date is not an HTTP-date", + "header": "2026-10-01", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "prose-date", + "description": "a date that does not start with a weekday is not an HTTP-date, even if a date parser would read it", + "header": "March 1, 2027", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "bad-weekday", + "description": "an HTTP-date shape whose weekday is not a weekday", + "header": "X, 21 Oct 2026 07:28:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "unit", + "description": "delta-seconds with a unit", + "header": "5 seconds", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "empty", + "description": "an empty value", + "header": "", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "spaces", + "description": "whitespace only", + "header": " ", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "padded", + "description": "surrounding spaces are trimmed", + "header": " 5 ", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 5 + }, + { + "id": "tab", + "description": "surrounding tabs are trimmed", + "header": "\t5\t", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 5 + }, + { + "id": "absent", + "description": "no Retry-After header at all", + "header": null, + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "asctime", + "description": "asctime date 45s ahead, read as UTC: RFC 9110 says an HTTP-date is always GMT, so a zone-less or asctime date is never read as local time.", + "header": "Thu Oct 1 12:00:45 2026", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 45 + }, + { + "id": "rfc850-year-60", + "description": "RFC 850 two-digit year 60 resolves to 2060 (RFC 9110 §5.6.7): 34 years ahead of `now`, not more than 50, so the current century is kept.", + "header": "Friday, 01-Oct-60 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 1073001600 + }, + { + "id": "rfc850-year-76", + "description": "RFC 850 two-digit year 76 resolves to 2076: exactly 50 years ahead of `now`, the boundary — not *more than* 50, so it stays in the future.", + "header": "Wednesday, 01-Oct-76 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 1577923200 + }, + { + "id": "rfc850-year-77", + "description": "RFC 850 two-digit year 77 would resolve to 2077, 51 years ahead — more than 50 — so RFC 9110 §5.6.7 moves it back a century, to 1977, which is in the past.", + "header": "Friday, 01-Oct-77 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 0 + }, + { + "id": "no-zone", + "description": "an IMF-fixdate without its GMT suffix is read as UTC, never local time.", + "header": "Thu, 01 Oct 2026 12:00:30", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 30 + }, + { + "id": "trailing-garbage", + "description": "an IMF-fixdate followed by extra text is unreadable: trailing text after a valid date is refused, not ignored.", + "header": "Thu, 01 Oct 2026 12:00:30 GMT garbage", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "feb-30", + "description": "30 February is not a calendar date, and is refused rather than rolled over to March.", + "header": "Mon, 30 Feb 2026 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + }, + { + "id": "year-10000", + "description": "a five-digit year is above 9999, and is refused.", + "header": "Fri, 01 Oct 10000 12:00:00 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null + } + ] +} diff --git a/tests/vectors/schema/account-ids.schema.json b/tests/vectors/schema/account-ids.schema.json new file mode 100644 index 00000000..ec112bc2 --- /dev/null +++ b/tests/vectors/schema/account-ids.schema.json @@ -0,0 +1,124 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/StackOneHQ/sdk-conformance/vectors/schema/account-ids.schema.json", + "title": "Account id vectors", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "description": { + "type": "string", + "minLength": 1 + }, + "version": { + "type": "integer", + "minimum": 1, + "description": "Bumped whenever a case's meaning or expected value changes; adding a case does not bump it." + }, + "error_classes": { + "$ref": "#/$defs/classes" + }, + "cases": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/case" + } + }, + "unresolved": { + "type": "array", + "items": { + "$ref": "#/$defs/unresolved" + } + } + }, + "required": ["description", "version", "cases", "error_classes"], + "additionalProperties": false, + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9.-]*$", + "description": "Stable and unique within the file: an SDK test names its case by it." + }, + "description": { + "type": "string", + "minLength": 1 + }, + "classes": { + "type": "object", + "properties": { + "python": { + "const": "ToolsetConfigError" + }, + "node": { + "const": "ToolSetConfigError" + } + }, + "required": ["python", "node"], + "additionalProperties": false + }, + "case": { + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "parameter": { + "enum": ["account_ids", "account_id"] + }, + "value": { + "description": "The value passed, as JSON." + }, + "expected": { + "oneOf": [ + { + "const": "ok" + }, + { + "type": "object", + "properties": { + "error": { + "$ref": "#/$defs/classes" + } + }, + "required": ["error"], + "additionalProperties": false + } + ] + } + }, + "required": ["id", "description", "parameter", "value", "expected"], + "additionalProperties": false + }, + "unresolved": { + "description": "A case the two SDKs disagree on today. Not graded: each SDK's observed value is recorded so the disagreement can be settled, and the case moved to `cases`.", + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "parameter": { + "enum": ["account_ids", "account_id"] + }, + "value": { + "description": "The value passed, as JSON." + }, + "python": { + "description": "What the Python SDK does today." + }, + "node": { + "description": "What the Node SDK does today." + } + }, + "required": ["id", "description", "parameter", "value", "python", "node"], + "additionalProperties": false + } + } +} diff --git a/tests/vectors/schema/argument-encoding.schema.json b/tests/vectors/schema/argument-encoding.schema.json new file mode 100644 index 00000000..40c9b9a0 --- /dev/null +++ b/tests/vectors/schema/argument-encoding.schema.json @@ -0,0 +1,140 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/StackOneHQ/sdk-conformance/vectors/schema/argument-encoding.schema.json", + "title": "Argument encoding vectors", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "description": { + "type": "string", + "minLength": 1 + }, + "version": { + "type": "integer", + "minimum": 1, + "description": "Bumped whenever a case's meaning or expected value changes; adding a case does not bump it." + }, + "reasons": { + "type": "array", + "items": { + "type": "string" + } + }, + "cases": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/case" + } + }, + "unresolved": { + "type": "array", + "items": { + "$ref": "#/$defs/unresolved" + } + } + }, + "required": ["description", "version", "cases", "reasons"], + "additionalProperties": false, + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9.-]*$", + "description": "Stable and unique within the file: an SDK test names its case by it." + }, + "description": { + "type": "string", + "minLength": 1 + }, + "case": { + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "arguments": { + "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + }, + "arguments_json": { + "type": "string", + "description": "JSON text handed to execute instead of a value." + }, + "expected": { + "oneOf": [ + { + "const": "ok" + }, + { + "type": "object", + "properties": { + "error": { + "const": "ToolArgumentsError" + }, + "reason": { + "enum": [ + "not-finite", + "invalid-json", + "not-an-object", + "unencodable" + ] + } + }, + "required": ["error", "reason"], + "additionalProperties": false + } + ] + } + }, + "required": ["id", "description", "expected"], + "additionalProperties": false, + "oneOf": [ + { + "required": ["arguments"] + }, + { + "required": ["arguments_json"] + } + ] + }, + "unresolved": { + "description": "A case the two SDKs disagree on today. Not graded: each SDK's observed value is recorded so the disagreement can be settled, and the case moved to `cases`.", + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "python": { + "description": "What the Python SDK does today." + }, + "node": { + "description": "What the Node SDK does today." + }, + "arguments": { + "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + }, + "arguments_json": { + "type": "string", + "description": "JSON text handed to execute instead of a value." + } + }, + "required": ["id", "description", "python", "node"], + "additionalProperties": false, + "oneOf": [ + { + "required": ["arguments"] + }, + { + "required": ["arguments_json"] + } + ] + } + } +} diff --git a/tests/vectors/schema/backoff.schema.json b/tests/vectors/schema/backoff.schema.json new file mode 100644 index 00000000..8ab781b0 --- /dev/null +++ b/tests/vectors/schema/backoff.schema.json @@ -0,0 +1,183 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/StackOneHQ/sdk-conformance/vectors/schema/backoff.schema.json", + "title": "429 backoff and deadline vectors", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "description": { + "type": "string", + "minLength": 1 + }, + "version": { + "type": "integer", + "minimum": 1, + "description": "Bumped whenever a case's meaning or expected value changes; adding a case does not bump it." + }, + "constants": { + "type": "object", + "properties": { + "max_retries": { + "type": "integer" + }, + "max_attempts": { + "type": "integer" + }, + "backoff_seconds": { + "type": "array", + "items": { + "type": "number" + } + }, + "jitter": { + "type": "object", + "properties": { + "min": { + "type": "number" + }, + "max": { + "type": "number" + }, + "max_exclusive": { + "type": "boolean" + } + }, + "required": ["min", "max", "max_exclusive"], + "additionalProperties": false + }, + "max_delay_seconds": { + "type": "number" + } + }, + "required": [ + "max_retries", + "max_attempts", + "backoff_seconds", + "jitter", + "max_delay_seconds" + ], + "additionalProperties": false + }, + "deadline_cases": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/deadlineCase" + } + }, + "cases": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/case" + } + }, + "unresolved": { + "type": "array", + "items": { + "$ref": "#/$defs/unresolved" + } + } + }, + "required": ["description", "version", "cases", "constants", "deadline_cases"], + "additionalProperties": false, + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9.-]*$", + "description": "Stable and unique within the file: an SDK test names its case by it." + }, + "description": { + "type": "string", + "minLength": 1 + }, + "deadlineCase": { + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "delay_seconds": { + "type": "number", + "minimum": 0, + "description": "The wait before the retry, after the cap." + }, + "remaining_seconds": { + "type": "number", + "description": "Time left before the call's deadline; may be negative." + }, + "expected": { + "enum": ["wait", "return-429"] + } + }, + "required": ["id", "description", "delay_seconds", "remaining_seconds", "expected"], + "additionalProperties": false + }, + "case": { + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "retry": { + "type": "integer", + "minimum": 1, + "maximum": 3, + "description": "Which retry the delay precedes, 1-based." + }, + "random": { + "type": "number", + "minimum": 0, + "exclusiveMaximum": 1, + "description": "The injected uniform value in [0, 1)." + }, + "retry_after_seconds": { + "type": ["number", "null"], + "minimum": 0, + "description": "The 429's Retry-After as read (see retry-after.json); null when absent or unreadable." + }, + "expected_delay_seconds": { + "type": "number", + "minimum": 0 + } + }, + "required": [ + "id", + "description", + "retry", + "random", + "retry_after_seconds", + "expected_delay_seconds" + ], + "additionalProperties": false + }, + "unresolved": { + "description": "A case the two SDKs disagree on today. Not graded: each SDK's observed value is recorded so the disagreement can be settled, and the case moved to `cases`.", + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "python": { + "description": "What the Python SDK does today." + }, + "node": { + "description": "What the Node SDK does today." + } + }, + "required": ["id", "description", "python", "node"], + "additionalProperties": false + } + } +} diff --git a/tests/vectors/schema/header-arguments.schema.json b/tests/vectors/schema/header-arguments.schema.json new file mode 100644 index 00000000..de4582b0 --- /dev/null +++ b/tests/vectors/schema/header-arguments.schema.json @@ -0,0 +1,143 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/StackOneHQ/sdk-conformance/vectors/schema/header-arguments.schema.json", + "title": "Header argument vectors (invariant 4)", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "description": { + "type": "string", + "minLength": 1 + }, + "version": { + "type": "integer", + "minimum": 1, + "description": "Bumped whenever a case's meaning or expected value changes; adding a case does not bump it." + }, + "reasons": { + "type": "array", + "items": { + "type": "string" + } + }, + "cases": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/case" + } + }, + "unresolved": { + "type": "array", + "items": { + "$ref": "#/$defs/unresolved" + } + } + }, + "required": ["description", "version", "cases", "reasons"], + "additionalProperties": false, + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9.-]*$", + "description": "Stable and unique within the file: an SDK test names its case by it." + }, + "description": { + "type": "string", + "minLength": 1 + }, + "warning": { + "type": "object", + "properties": { + "argument": { + "type": "string", + "description": "The top-level argument: `headers`, or `headers_` as supplied." + }, + "header": { + "type": "string", + "description": "For an entry of a `headers` object: its name, trimmed." + }, + "reason": { + "enum": [ + "set-by-sdk", + "not-declared", + "malformed", + "not-an-object", + "not-a-scalar" + ] + } + }, + "required": ["argument", "reason"], + "additionalProperties": false + }, + "case": { + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "schema": { + "type": "object", + "description": "The tool's served inputSchema." + }, + "arguments": { + "type": "object", + "description": "The model's arguments." + }, + "expected_arguments": { + "type": "object", + "description": "The arguments that reach tools/call." + }, + "expected_warnings": { + "type": "array", + "items": { + "$ref": "#/$defs/warning" + }, + "description": "In argument order." + } + }, + "required": [ + "id", + "description", + "schema", + "arguments", + "expected_arguments", + "expected_warnings" + ], + "additionalProperties": false + }, + "unresolved": { + "description": "A case the two SDKs disagree on today. Not graded: each SDK's observed value is recorded so the disagreement can be settled, and the case moved to `cases`.", + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "schema": { + "type": "object", + "description": "The tool's served inputSchema." + }, + "arguments": { + "type": "object", + "description": "The model's arguments." + }, + "python": { + "description": "What the Python SDK does today." + }, + "node": { + "description": "What the Node SDK does today." + } + }, + "required": ["id", "description", "schema", "arguments", "python", "node"], + "additionalProperties": false + } + } +} diff --git a/tests/vectors/schema/header-names.schema.json b/tests/vectors/schema/header-names.schema.json new file mode 100644 index 00000000..5daa1f9c --- /dev/null +++ b/tests/vectors/schema/header-names.schema.json @@ -0,0 +1,109 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/StackOneHQ/sdk-conformance/vectors/schema/header-names.schema.json", + "title": "Nested header name vectors", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "description": { + "type": "string", + "minLength": 1 + }, + "version": { + "type": "integer", + "minimum": 1, + "description": "Bumped whenever a case's meaning or expected value changes; adding a case does not bump it." + }, + "cases": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/case" + } + }, + "unresolved": { + "type": "array", + "items": { + "$ref": "#/$defs/unresolved" + } + } + }, + "required": ["description", "version", "cases"], + "additionalProperties": false, + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9.-]*$", + "description": "Stable and unique within the file: an SDK test names its case by it." + }, + "description": { + "type": "string", + "minLength": 1 + }, + "case": { + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "name": { + "type": "string" + }, + "expected": { + "oneOf": [ + { + "type": "object", + "properties": { + "forwarded": { + "type": "string" + } + }, + "required": ["forwarded"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "dropped": { + "enum": ["set-by-sdk", "not-declared", "malformed"] + } + }, + "required": ["dropped"], + "additionalProperties": false + } + ] + } + }, + "required": ["id", "description", "name", "expected"], + "additionalProperties": false + }, + "unresolved": { + "description": "A case the two SDKs disagree on today. Not graded: each SDK's observed value is recorded so the disagreement can be settled, and the case moved to `cases`.", + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "name": { + "type": "string" + }, + "python": { + "description": "What the Python SDK does today." + }, + "node": { + "description": "What the Node SDK does today." + } + }, + "required": ["id", "description", "name", "python", "node"], + "additionalProperties": false + } + } +} diff --git a/tests/vectors/schema/header-values.schema.json b/tests/vectors/schema/header-values.schema.json new file mode 100644 index 00000000..445e61bd --- /dev/null +++ b/tests/vectors/schema/header-values.schema.json @@ -0,0 +1,133 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/StackOneHQ/sdk-conformance/vectors/schema/header-values.schema.json", + "title": "Nested header value vectors", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "description": { + "type": "string", + "minLength": 1 + }, + "version": { + "type": "integer", + "minimum": 1, + "description": "Bumped whenever a case's meaning or expected value changes; adding a case does not bump it." + }, + "cases": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/case" + } + }, + "unresolved": { + "type": "array", + "items": { + "$ref": "#/$defs/unresolved" + } + }, + "known_differences": { + "type": "array", + "items": { + "$ref": "#/$defs/known_difference" + }, + "description": "A case where the SDKs differ for a reason outside this rule (for example, their JSON parser already produced different values). Not graded." + } + }, + "required": ["description", "version", "cases", "known_differences"], + "additionalProperties": false, + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9.-]*$", + "description": "Stable and unique within the file: an SDK test names its case by it." + }, + "description": { + "type": "string", + "minLength": 1 + }, + "case": { + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "value": { + "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + }, + "expected": { + "oneOf": [ + { + "type": "string", + "description": "The header text forwarded." + }, + { + "type": "object", + "properties": { + "dropped": { + "const": true + } + }, + "required": ["dropped"], + "additionalProperties": false + } + ] + } + }, + "required": ["id", "description", "value", "expected"], + "additionalProperties": false + }, + "unresolved": { + "description": "A case the two SDKs disagree on today. Not graded: each SDK's observed value is recorded so the disagreement can be settled, and the case moved to `cases`.", + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "value": { + "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + }, + "python": { + "description": "What the Python SDK does today." + }, + "node": { + "description": "What the Node SDK does today." + } + }, + "required": ["id", "description", "value", "python", "node"], + "additionalProperties": false + }, + "known_difference": { + "description": "A case that is settled, but not identical across SDKs for a reason outside this rule. Not graded.", + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "value": { + "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + }, + "python": { + "description": "What the Python SDK does." + }, + "node": { + "description": "What the Node SDK does." + } + }, + "required": ["id", "description", "value", "python", "node"], + "additionalProperties": false + } + } +} diff --git a/tests/vectors/schema/messages.schema.json b/tests/vectors/schema/messages.schema.json new file mode 100644 index 00000000..14dfa877 --- /dev/null +++ b/tests/vectors/schema/messages.schema.json @@ -0,0 +1,203 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/StackOneHQ/sdk-conformance/vectors/schema/messages.schema.json", + "title": "Canonical SDK messages", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "description": { + "type": "string", + "minLength": 1 + }, + "version": { + "type": "integer", + "minimum": 1 + }, + "prefixes": { + "type": "object", + "properties": { + "node": { + "type": "string" + }, + "python": { + "type": "string" + } + }, + "required": ["node", "python"], + "additionalProperties": false + }, + "formats": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "reasons": { + "type": "object", + "properties": { + "set-by-sdk": { + "type": "string" + }, + "not-declared": { + "type": "string" + }, + "malformed": { + "type": "string" + }, + "not-an-object": { + "type": "string" + }, + "not-a-scalar": { + "type": "string" + } + }, + "required": [ + "set-by-sdk", + "not-declared", + "malformed", + "not-an-object", + "not-a-scalar" + ], + "additionalProperties": false + }, + "messages": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/message" + } + }, + "unshared": { + "type": "array", + "items": { + "$ref": "#/$defs/unshared" + } + } + }, + "required": [ + "description", + "version", + "prefixes", + "formats", + "reasons", + "messages", + "unshared" + ], + "additionalProperties": false, + "$defs": { + "classes": { + "type": "object", + "properties": { + "python": { + "type": "string" + }, + "node": { + "type": "string" + } + }, + "required": ["python", "node"], + "additionalProperties": false + }, + "message": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]*$" + }, + "kind": { + "enum": ["warning", "error", "tool-result"] + }, + "error": { + "$ref": "#/$defs/classes", + "description": "The class each SDK raises it as." + }, + "template": { + "type": "string", + "description": "The canonical text. `{name}` is a placeholder; no template holds a literal brace." + }, + "placeholders": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "format": { + "enum": [ + "text", + "json", + "integer", + "seconds", + "seconds-2dp", + "json-type", + "reason" + ] + }, + "description": { + "type": "string" + } + }, + "required": ["format", "description"], + "additionalProperties": false + } + }, + "python": { + "type": "string", + "description": "The Python SDK's text today." + }, + "node": { + "type": "string", + "description": "The Node SDK's text today." + }, + "matches": { + "type": "object", + "properties": { + "python": { + "type": "boolean" + }, + "node": { + "type": "boolean" + } + }, + "required": ["python", "node"], + "additionalProperties": false + }, + "notes": { + "type": "string" + } + }, + "required": ["id", "kind", "template", "placeholders", "python", "node", "matches"], + "additionalProperties": false, + "if": { + "properties": { + "kind": { + "const": "error" + } + } + }, + "then": { + "required": ["error"] + } + }, + "unshared": { + "type": "object", + "properties": { + "sdk": { + "enum": ["python", "node"] + }, + "kind": { + "enum": ["warning", "error", "tool-result"] + }, + "text": { + "type": "string" + }, + "notes": { + "type": "string" + } + }, + "required": ["sdk", "kind", "text"], + "additionalProperties": false + } + } +} diff --git a/tests/vectors/schema/retry-after.schema.json b/tests/vectors/schema/retry-after.schema.json new file mode 100644 index 00000000..15f72899 --- /dev/null +++ b/tests/vectors/schema/retry-after.schema.json @@ -0,0 +1,128 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/StackOneHQ/sdk-conformance/vectors/schema/retry-after.schema.json", + "title": "Retry-After vectors", + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "description": { + "type": "string", + "minLength": 1 + }, + "version": { + "type": "integer", + "minimum": 1, + "description": "Bumped whenever a case's meaning or expected value changes; adding a case does not bump it." + }, + "max_delay_seconds": { + "type": "number", + "exclusiveMinimum": 0, + "description": "The cap the caller applies to the value afterwards." + }, + "cases": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/case" + } + }, + "unresolved": { + "type": "array", + "items": { + "$ref": "#/$defs/unresolved" + } + } + }, + "required": ["description", "version", "cases", "max_delay_seconds"], + "additionalProperties": false, + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9.-]*$", + "description": "Stable and unique within the file: an SDK test names its case by it." + }, + "description": { + "type": "string", + "minLength": 1 + }, + "number": { + "description": "A number JSON cannot hold, as a marker an SDK decodes before use.", + "type": "object", + "properties": { + "$number": { + "enum": ["NaN", "Infinity", "-Infinity"] + } + }, + "required": ["$number"], + "additionalProperties": false + }, + "case": { + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "header": { + "type": ["string", "null"], + "description": "The Retry-After value; null when the response carries no Retry-After header." + }, + "now": { + "type": "string", + "format": "date-time", + "description": "The current time the header is read at, RFC 3339." + }, + "expected_seconds": { + "description": "Seconds from `now`, before the cap; null when absent or unreadable.", + "oneOf": [ + { + "type": "number", + "minimum": 0 + }, + { + "type": "null" + }, + { + "$ref": "#/$defs/number" + } + ] + } + }, + "required": ["id", "description", "header", "now", "expected_seconds"], + "additionalProperties": false + }, + "unresolved": { + "description": "A case the two SDKs disagree on today. Not graded: each SDK's observed value is recorded so the disagreement can be settled, and the case moved to `cases`.", + "type": "object", + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "header": { + "type": ["string", "null"], + "description": "The Retry-After value; null when the response carries no Retry-After header." + }, + "now": { + "type": "string", + "format": "date-time", + "description": "The current time the header is read at, RFC 3339." + }, + "python": { + "description": "What the Python SDK does today." + }, + "node": { + "description": "What the Node SDK does today." + } + }, + "required": ["id", "description", "header", "now", "python", "node"], + "additionalProperties": false + } + } +} From ebf13935913471eeae8a9d80204cdd66b5460b4d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:10:03 +0100 Subject: [PATCH 067/151] ci: fail when the vendored vectors differ from the pinned sdk-conformance --- .github/workflows/ci.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 83ef8e48..69e55223 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -165,6 +165,11 @@ jobs: path: sdk-conformance persist-credentials: false + # tests/vectors is a copy of the suite's vectors/ (scripts/sync-vectors.sh), which the unit + # tests run. An edit to the copy, or a pin moved without a re-copy, fails here. + - name: Vendored vectors match the pinned sdk-conformance + run: diff -r sdk/tests/vectors sdk-conformance/vectors + - name: Setup pnpm uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 with: From 99b15169064ab757de69df79015dbb211499dc63 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:11:34 +0100 Subject: [PATCH 068/151] Revert "fix(retry): read a Retry-After date as the shared vectors do" This reverts commit 3ce3c0d32b404bd7cb7bc6cedbea45d990280cf2. --- src/utils/fetch-retry.test.ts | 62 ++++++++++++++++++++++++++--------- src/utils/fetch-retry.ts | 33 ++++++------------- 2 files changed, 56 insertions(+), 39 deletions(-) diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index 3d28876a..bd180a51 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -151,41 +151,71 @@ describe('fetchWithRetry', () => { ); }); - it.each(['soon', 'March 1, 2027'])( - 'backs off as if absent when unreadable (%s)', - async (value) => { - respondWith(limited({ 'Retry-After': value }), ok); - const { delays, timing } = recordedTiming(() => 0); + // Only the three RFC 9110 HTTP-date forms are dates. Python reads these the same way. + it.each([ + 'soon', + '1.5', + '1.5e3', + '-1', + '2026-10-01', + 'March 1, 2027', + 'X, 21 Oct 2015 07:28:00 GMT', + ])('backs off as if absent when unreadable (%s)', async (value) => { + respondWith(limited({ 'Retry-After': value }), ok); + const { delays, timing } = recordedTiming(() => 0); - await fetchWithRetry(url, undefined, { timing }); + await fetchWithRetry(url, undefined, { timing }); - expect(delays).toEqual([500]); - }, - ); + expect(delays).toEqual([500]); + }); }); - // The shared vectors (src/vectors.test.ts) grade the forms, years and refusals; these are - // the calendar edges they leave out. describe('retryAfterMs', () => { const now = Date.parse('2026-10-01T12:00:00Z'); - it('reads a leap second as the start of the next minute', () => { - expect(retryAfterMs('Thu, 01 Oct 2026 12:00:60 GMT', now)).toBe(60_000); + // Each form is GMT, whatever the host's time zone: Date.parse read asctime and a + // zone-less IMF date as local time. + it.each([ + ['IMF-fixdate', 'Thu, 01 Oct 2026 12:00:30 GMT', 30_000], + ['asctime', 'Thu Oct 1 12:00:45 2026', 45_000], + ['RFC 850', 'Thursday, 01-Oct-26 12:01:00 GMT', 60_000], + ['a leap second', 'Thu, 01 Oct 2026 12:00:60 GMT', 60_000], + ['a mismatched weekday', 'Mon, 01 Oct 2026 12:00:10 GMT', 10_000], + ])('reads %s', (_form, value, expected) => { + expect(retryAfterMs(value, now)).toBe(expected); }); - it('reads 29 February in a leap year', () => { - expect(retryAfterMs('Tue, 29 Feb 2028 00:00:00 GMT', now)).toBe( - Date.parse('2028-02-29T00:00:00Z') - now, + // RFC 9110 §5.6.7: a two-digit year more than 50 years ahead is in the previous century. + it.each([ + ['60', 'Friday, 01-Oct-60 12:00:00 GMT', '2060-10-01T12:00:00Z'], + ['75', 'Tuesday, 31-Dec-75 23:59:59 GMT', '2075-12-31T23:59:59Z'], + ['76', 'Thursday, 01-Oct-76 12:00:00 GMT', '1976-10-01T12:00:00Z'], + ])('reads the RFC 850 year %s against now', (_year, value, expected) => { + expect(retryAfterMs(value, Date.parse('2026-01-01T00:00:00Z'))).toBe( + Math.max(0, Date.parse(expected) - Date.parse('2026-01-01T00:00:00Z')), ); }); it.each([ + ['a missing zone', 'Thu, 01 Oct 2026 12:00:30'], + ['trailing text', 'Thu, 01 Oct 2026 12:00:30 GMT garbage'], + ['30 February', 'Mon, 30 Feb 2026 12:00:00 GMT'], ['29 February in a common year', 'Sun, 29 Feb 2026 12:00:00 GMT'], + ['a five-digit year', 'Fri, 01 Oct 10000 12:00:00 GMT'], ['year 0', 'Sat, 01 Jan 0000 12:00:00 GMT'], + ['a numeric zone', 'Thu, 01 Oct 2026 13:00:30 +0100'], + ['a two-digit IMF year', 'Thu, 01 Oct 26 12:00:30 GMT'], ['second 61', 'Thu, 01 Oct 2026 12:00:61 GMT'], + ['a lower-case weekday', 'thu, 01 Oct 2026 12:00:30 GMT'], ])('refuses %s', (_problem, value) => { expect(retryAfterMs(value, now)).toBeUndefined(); }); + + it('reads 29 February in a leap year', () => { + expect(retryAfterMs('Tue, 29 Feb 2028 00:00:00 GMT', now)).toBe( + Date.parse('2028-02-29T00:00:00Z') - now, + ); + }); }); describe('without Retry-After', () => { diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index 8a5cb6c8..1f51e226 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -50,20 +50,14 @@ export const retryTiming: RetryTiming = { now: () => performance.now(), }; -// The three HTTP-date forms of RFC 9110 §5.6.7: case-sensitive, single spaces, nothing after. +// The three HTTP-date forms of RFC 9110 §5.6.7, exactly: case-sensitive, single spaces, GMT only. const WEEKDAY = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)'; const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const MONTH = `(?${MONTHS.join('|')})`; const TIME = '(?\\d{2}):(?\\d{2}):(?\\d{2})'; -/** - * `Sun, 06 Nov 1994 08:49:37 GMT`: RFC 9110's preferred form. As the shared vectors read it, a - * two-digit year is read as RFC 850's is, and the zone may be left out (GMT) or written as an - * offset (`+0100`). - */ -const IMF_FIXDATE = new RegExp( - `^${WEEKDAY}, (?\\d{2}) ${MONTH} (?\\d{4}|\\d{2}) ${TIME}(?: (?GMT|[+-]\\d{4}))?$`, -); +/** `Sun, 06 Nov 1994 08:49:37 GMT`: RFC 9110's preferred form. */ +const IMF_FIXDATE = new RegExp(`^${WEEKDAY}, (?\\d{2}) ${MONTH} (?\\d{4}) ${TIME} GMT$`); /** `Sunday, 06-Nov-94 08:49:37 GMT`: obsolete, with a two-digit year. */ const RFC850_DATE = new RegExp( `^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?\\d{2})-${MONTH}-(?\\d{2}) ${TIME} GMT$`, @@ -107,19 +101,17 @@ function addYears(time: number, years: number): number { * Read an RFC 9110 HTTP-date as a time in milliseconds, or undefined if it is not one. * * Strict, unlike `Date.parse`, which reads a zone-less date in the host's local time, rolls - * 30 February over to 2 March, reads five-digit years and accepts trailing text. A date with no - * zone is GMT. The weekday must be present but need not match the date, which is what the date - * means. + * 30 February over to 2 March and accepts trailing text. All three forms are always GMT. The + * weekday must be present but need not match the date, which is what the date means. */ function parseHttpDate(value: string, now: number): number | undefined { - const fields = (RFC850_DATE.exec(value) ?? IMF_FIXDATE.exec(value) ?? ASCTIME_DATE.exec(value)) - ?.groups; - if (!fields?.year) { + const rfc850 = RFC850_DATE.exec(value); + const fields = (rfc850 ?? IMF_FIXDATE.exec(value) ?? ASCTIME_DATE.exec(value))?.groups; + if (!fields) { return undefined; } - const twoDigitYear = fields.year.length === 2; const thisYear = new Date(now).getUTCFullYear(); - const year = Number(fields.year) + (twoDigitYear ? thisYear - (thisYear % 100) : 0); + const year = Number(fields.year) + (rfc850 ? thisYear - (thisYear % 100) : 0); const month = MONTHS.indexOf(fields.month ?? ''); const d = Number(fields.day); const h = Number(fields.hour); @@ -130,7 +122,7 @@ function parseHttpDate(value: string, now: number): number | undefined { return undefined; } let when = utcTime(year, month, d, h, m, s); - if (twoDigitYear) { + 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); @@ -140,11 +132,6 @@ function parseHttpDate(value: string, now: number): number | undefined { when = addYears(when, 100); } } - const offset = /^([+-])(\d{2})(\d{2})$/.exec(fields.zone ?? ''); - if (offset) { - const minutes = Number(offset[2]) * 60 + Number(offset[3]); - when -= (offset[1] === '-' ? -1 : 1) * minutes * 60_000; - } return when; } From b7c1647c83ef1e2fc7f23ac1a59af9bb6a723018 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:12:13 +0100 Subject: [PATCH 069/151] test(vectors): sync the shared vectors to sdk-conformance daf1140 The corrected Retry-After cases match the strict RFC 9110 parser, so rfc850-year-70 is graded like every other case. --- src/vectors.test.ts | 29 ++++------------------------- tests/vectors/retry-after.json | 16 ++++++++-------- 2 files changed, 12 insertions(+), 33 deletions(-) diff --git a/src/vectors.test.ts b/src/vectors.test.ts index c757e3e4..3b62b1e3 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -205,31 +205,10 @@ describe('retry-after.json', () => { expect(file.version).toBe(1); }); - /** - * Cases these tests cannot pass, each with why. Run with `it.fails`, so a fixed vector fails - * here until it is taken off the list. - */ - const CONTRADICTED: Record = { - // 01-Oct-70 is 44 years ahead of `now`, not more than 50, so RFC 9110 §5.6.7 — and this - // file's own rfc850-year-60, -76 and -77 — put it in 2070, not 1970. - 'rfc850-year-70': 'contradicts rfc850-year-60/76/77', - }; - - it.each(file.cases.filter(({ id }) => !(id in CONTRADICTED)))( - '$id', - ({ header, now, expected_seconds }) => { - const ms = retryAfterMs(header, Date.parse(now)); - expectSeconds(ms === undefined ? null : ms / 1000, expected_seconds); - }, - ); - - it.fails.each(file.cases.filter(({ id }) => id in CONTRADICTED))( - '$id (contradicted by the vectors themselves)', - ({ header, now, expected_seconds }) => { - const ms = retryAfterMs(header, Date.parse(now)); - expectSeconds(ms === undefined ? null : ms / 1000, expected_seconds); - }, - ); + it.each(file.cases)('$id', ({ header, now, expected_seconds }) => { + const ms = retryAfterMs(header, Date.parse(now)); + expectSeconds(ms === undefined ? null : ms / 1000, expected_seconds); + }); }); describe('backoff.json', () => { diff --git a/tests/vectors/retry-after.json b/tests/vectors/retry-after.json index f4b426f0..4a3011e1 100644 --- a/tests/vectors/retry-after.json +++ b/tests/vectors/retry-after.json @@ -106,10 +106,10 @@ }, { "id": "two-digit-year-imf", - "description": "an IMF-fixdate with a two-digit year (26) is read as 2026", + "description": "an IMF-fixdate requires a four-digit year, so a two-digit one is unreadable and falls back to the backoff", "header": "Thu, 01 Oct 26 12:00:30 GMT", "now": "2026-10-01T12:00:00Z", - "expected_seconds": 30 + "expected_seconds": null }, { "id": "rfc850-year-49", @@ -120,17 +120,17 @@ }, { "id": "rfc850-year-70", - "description": "RFC 850 two-digit year 70 is read as 1970 by both (RFC 9110's 50-year rule would say 2070: both SDKs agree on 1970 today)", + "description": "RFC 850 two-digit year 70 is 2070: 44 years ahead is within RFC 9110 §5.6.7's 50-year window", "header": "Wednesday, 01-Oct-70 12:00:00 GMT", "now": "2026-10-01T12:00:00Z", - "expected_seconds": 0 + "expected_seconds": 1388534400 }, { "id": "offset-zone", - "description": "a numeric zone offset is honoured: 13:00:30 +0100 is 12:00:30 GMT", + "description": "an IMF-fixdate is always GMT; a numeric offset is unreadable and falls back to the backoff", "header": "Thu, 01 Oct 2026 13:00:30 +0100", "now": "2026-10-01T12:00:00Z", - "expected_seconds": 30 + "expected_seconds": null }, { "id": "day-32", @@ -288,10 +288,10 @@ }, { "id": "no-zone", - "description": "an IMF-fixdate without its GMT suffix is read as UTC, never local time.", + "description": "an IMF-fixdate without its GMT suffix is unreadable and falls back to the backoff (only the asctime form has no zone, and is read as UTC)", "header": "Thu, 01 Oct 2026 12:00:30", "now": "2026-10-01T12:00:00Z", - "expected_seconds": 30 + "expected_seconds": null }, { "id": "trailing-garbage", From 3405514faa63eb5cca8e1ac89b12d932e43c9e97 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:12:14 +0100 Subject: [PATCH 070/151] ci: pin sdk-conformance to daf1140 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 69e55223..516bd59a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 67103caab5ec1b547fa9919375ee48dd04e44b75 + ref: daf1140a61987c544db2ad32d89960cf99cff184 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From ea6984d135dc7c6cc379420d0c8b25676387c01d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:44:59 +0100 Subject: [PATCH 071/151] docs(migration): qualify the JSON-value and integer-precision rules The JSON-value guarantee only applies to non-header arguments, since header sanitization can stringify or drop values first. The integer rounding note now names the exact safe-integer boundary and recommends strings for exact large integers. --- MIGRATION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index a94dd4d6..edeb1ea0 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -166,9 +166,9 @@ await tool.execute({ id: '1' }, { dryRun: true }); **Arguments are sent as given**, as `tools/call` arguments, except header arguments: each is forwarded only if the tool's schema declares it, and `Authorization`, `x-account-id` and `User-Agent` never are (see below). The SDK no longer splits flat `path_` / `query_` / `body_` keys into an `/actions/rpc` envelope; the server maps them itself. -**Arguments must be JSON values.** `null`, booleans, finite numbers, strings, arrays and plain objects are accepted; a `NaN` or `Infinity`, a `bigint`, a `Date`, `Map`, `Set` or `RegExp`, a function, a symbol, a class instance, a typed array or buffer, or a circular reference, anywhere in the arguments, throws `ToolArgumentsError` naming the path. 2.x let some of these through `JSON.stringify` silently converted (a `Date` to a string, a `Map` to `{}`), which sent the model a value it never supplied. An object property set to `undefined` is still treated as absent; `undefined` inside an array now throws, where 2.x sent it as `null`. +**Non-header arguments must be JSON values.** `null`, booleans, finite numbers, strings, arrays and plain objects are accepted; a `NaN` or `Infinity`, a `bigint`, a `Date`, `Map`, `Set` or `RegExp`, a function, a symbol, a class instance, a typed array or buffer, or a circular reference, anywhere in a non-header argument, throws `ToolArgumentsError` naming the path. 2.x let some of these through `JSON.stringify` silently converted (a `Date` to a string, a `Map` to `{}`), which sent the model a value it never supplied. An object property set to `undefined` is still treated as absent; `undefined` inside an array now throws, where 2.x sent it as `null`. Header arguments follow different rules — see "Header arguments are allowlisted" below. -**Integers above 2^53 are not sent exactly.** JavaScript has already rounded them by the time an argument reaches the SDK, where Python's arbitrary-precision integers reach the server exactly. +**Integers outside the safe range are not sent exactly.** JavaScript's `number` type only represents integers exactly up to `Number.MAX_SAFE_INTEGER` (2^53 − 1); beyond that, a value may already be rounded by the time it reaches the SDK, where Python's arbitrary-precision integers reach the server exactly. Pass such integers as strings if you need the exact value preserved. **`fetchTools()` tools have the server's own argument shape.** 2.x asked the server for the flat, prefixed style (`?param-style=flat_prefixed`). That request is gone, so the argument names are whatever the server serves for your project. Read them from `tool.parameters.properties` rather than hard-coding them: From e7af56d63faea91b88ccc66bdc31b98483465117 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:45:09 +0100 Subject: [PATCH 072/151] fix(tool): treat sparse array holes as undefined in argument validation assertJsonValue used Array.prototype.forEach, which skips unassigned indices, so a hole in a sparse array reached MCP as null instead of raising ToolArgumentsError. Iterate by index instead. --- src/tool.test.ts | 13 +++++++++++++ src/tool.ts | 5 +++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/tool.test.ts b/src/tool.test.ts index 2fb026f3..4346beca 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -483,6 +483,19 @@ describe('StackOneMcpTool as an action tool', () => { expect(calls).toEqual([]); }); + it('rejects a sparse array hole', async () => { + const ids: number[] = [1, 2, 3]; + // 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) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as Error).message).toMatch(/undefined is not a JSON value/); + expect(calls).toEqual([]); + }); + it('rejects a circular reference', async () => { const body: JsonObject = { name: 'Ada' }; body.self = body; diff --git a/src/tool.ts b/src/tool.ts index 04773cb3..5179b7c4 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -521,7 +521,8 @@ function assertJsonValue(value: unknown, path: string, toolName: string, seen: S throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); } seen.add(value); - value.forEach((item, index) => { + for (let index = 0; index < value.length; index++) { + const item = value[index]; const itemPath = `${path}[${index}]`; if (item === undefined) { throw unencodable( @@ -530,7 +531,7 @@ function assertJsonValue(value: unknown, path: string, toolName: string, seen: S ); } assertJsonValue(item, itemPath, toolName, seen); - }); + } seen.delete(value); return; } From 707ceba03cd78745c9c9a13ff8d98f8d830ce2fa Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:45:18 +0100 Subject: [PATCH 073/151] fix(scripts): make sync-vectors.sh atomic and refuse a dirty source Copy into a temp directory and swap it into place only after the copy succeeds, so a failed copy can't leave tests/vectors missing or partial. Also refuse a source that isn't a git checkout, or one with uncommitted or ignored-untracked changes under vectors/, mirroring the Python SDK's sync script. --- scripts/sync-vectors.sh | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/scripts/sync-vectors.sh b/scripts/sync-vectors.sh index 2ff1cc08..76efdf87 100755 --- a/scripts/sync-vectors.sh +++ b/scripts/sync-vectors.sh @@ -15,8 +15,19 @@ if [ ! -d "$source_dir" ]; then echo "$source_dir does not exist" >&2 exit 1 fi +if ! git -C "$1" rev-parse --git-dir >/dev/null 2>&1; then + echo "$1 is not a git checkout" >&2 + exit 1 +fi +if [ -n "$(git -C "$1" status --porcelain --ignored -- vectors)" ]; then + echo "$source_dir has uncommitted or ignored-untracked changes" >&2 + exit 1 +fi target_dir="$(cd "$(dirname "$0")/.." && pwd)/tests/vectors" +tmp_dir="$target_dir.tmp" +rm -rf "$tmp_dir" +cp -R "$source_dir" "$tmp_dir" rm -rf "$target_dir" -cp -R "$source_dir" "$target_dir" +mv "$tmp_dir" "$target_dir" echo "Copied $source_dir to $target_dir" From 59c6eeca175ad9d560d5afa8352cc9ce02ae4ce0 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 10:45:31 +0100 Subject: [PATCH 074/151] test(fetch-retry): cover a leap second rolling into the next year Date.setUTCHours already normalizes an out-of-range second, so a Retry-After leap second at a year boundary (23:59:60 on 31 December 9999) rolls over to 1 January 10000 correctly; add a regression test. --- src/utils/fetch-retry.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts index bd180a51..2bc9f97c 100644 --- a/src/utils/fetch-retry.test.ts +++ b/src/utils/fetch-retry.test.ts @@ -216,6 +216,13 @@ describe('fetchWithRetry', () => { Date.parse('2028-02-29T00:00:00Z') - now, ); }); + + it('reads a leap second that rolls over into the next year', () => { + const yearEnd = Date.parse('9999-12-31T00:00:00Z'); + expect(retryAfterMs('Fri, 31 Dec 9999 23:59:60 GMT', yearEnd)).toBe( + Date.UTC(10000, 0, 1) - yearEnd, + ); + }); }); describe('without Retry-After', () => { From a41e548c57d15d529e9c1eda4abea2735370aaf9 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 11:05:25 +0100 Subject: [PATCH 075/151] test(vectors): sync the shared vectors to sdk-conformance 0906f4d --- tests/vectors/README.md | 10 +- tests/vectors/header-arguments.json | 16 +- tests/vectors/header-values.json | 4 +- tests/vectors/messages.json | 210 +++++++++--------- tests/vectors/retry-after.json | 31 ++- .../schema/argument-encoding.schema.json | 46 +++- tests/vectors/schema/backoff.schema.json | 31 ++- .../schema/header-arguments.schema.json | 23 +- tests/vectors/schema/header-names.schema.json | 2 +- .../vectors/schema/header-values.schema.json | 50 ++++- tests/vectors/schema/messages.schema.json | 5 + 11 files changed, 289 insertions(+), 139 deletions(-) diff --git a/tests/vectors/README.md b/tests/vectors/README.md index d95eb24f..b6fdba53 100644 --- a/tests/vectors/README.md +++ b/tests/vectors/README.md @@ -50,9 +50,10 @@ SDKs disagree on today and the contract does not yet settle; none is open right - **`unresolved`** cases are not graded. Each one says what the two SDKs do differently. Once the contract settles it, the case moves to `cases` with the agreed value, and the SDK that changes fixes its code in the same release. A file only has this array while it has an open case. -- **`known_differences`** cases are not graded either. Each one is settled — the contract has - chosen the expected behaviour, and it is in `cases` — but the two SDKs still produce different - values for a reason outside the rule being tested, so there is nothing to converge on. +- **`known_differences`** cases are not graded either. Each one is a settled exception, recorded + only in `known_differences` and not also in `cases`: the contract has chosen the behaviour, but + the two SDKs still produce different values for a reason outside the rule being tested, so + there is nothing to converge on. A file only has this array while it has such a case. ## Reading the values @@ -76,7 +77,8 @@ SDKs disagree on today and the contract does not yet settle; none is open right Each message has an `id`, a `template` with named placeholders (`{endpoint}`, `{attempt}`, …), a `format` for each placeholder, and the text each SDK emits today (`python`, `node`). `matches` -says whether that text is already the canonical one, and `notes` explain the differences. Render +says whether that text is already the canonical one, and `notes` say where the text depends on +more than the template. Render a template by replacing each placeholder with its value written in the placeholder's format: | Format | Written as | diff --git a/tests/vectors/header-arguments.json b/tests/vectors/header-arguments.json index 7331afb7..402be572 100644 --- a/tests/vectors/header-arguments.json +++ b/tests/vectors/header-arguments.json @@ -626,8 +626,8 @@ "expected_warnings": [] }, { - "id": "string-typed-object-value-still-filtered", - "description": "the ordinary-field exception covers non-object values only: an object is still filtered, and declares nothing", + "id": "string-typed-object-value-is-ordinary", + "description": "a headers property typed \"string\" is an ordinary field whatever the value: an object is forwarded unchanged, not filtered", "schema": { "type": "object", "properties": { @@ -642,15 +642,11 @@ } }, "expected_arguments": { - "headers": {} - }, - "expected_warnings": [ - { - "argument": "headers", - "header": "x-custom", - "reason": "not-declared" + "headers": { + "x-custom": "a" } - ] + }, + "expected_warnings": [] }, { "id": "no-headers-schema-object", diff --git a/tests/vectors/header-values.json b/tests/vectors/header-values.json index 58722b9e..afd55c2a 100644 --- a/tests/vectors/header-values.json +++ b/tests/vectors/header-values.json @@ -122,7 +122,7 @@ { "id": "float-integral", "description": "an integral float is written as JavaScript writes it: 1, not 1.0", - "value": 1, + "value": 1.0, "expected": "1" }, { @@ -140,7 +140,7 @@ { "id": "negative-zero", "description": "negative zero is written 0", - "value": 0, + "value": -0.0, "expected": "0" }, { diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index cbdf3a5d..0c40d27e 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -1,6 +1,6 @@ { "$schema": "./schema/messages.schema.json", - "description": "The canonical wording of every user-facing warning and error message both SDKs emit. `template` is the canonical text; `python` and `node` are each SDK's text today, written with the same placeholders (and `|` between variants), so an SDK can see what changes. A prefix the language adds — Node's `[@stackone/ai] `, Python's logger name — is outside the template. An error's class is in `error`. `matches` says whether an SDK's text is already the canonical one, reading a value written raw between double quotes as its JSON text — the same for every ordinary value; the notes say where not.", + "description": "The canonical wording of every user-facing warning and error message both SDKs emit. `template` is the canonical text; `python` and `node` are each SDK's text today, written with the same placeholders (and `|` between variants), so an SDK can see what changes. A prefix the language adds — Node's `[@stackone/ai] `, Python's logger name — is outside the template. An error's class is in `error`. `matches` says whether an SDK's text is already the canonical one; `notes` say where the text depends on more than the template.", "version": 1, "prefixes": { "node": "Every warning goes through console.warn, prefixed `[@stackone/ai] ` — outside the template.", @@ -37,13 +37,13 @@ "description": "set-by-sdk, not-declared or malformed" } }, - "python": "Dropping header {header!r} from a tool call: it is {reason} | Dropping malformed header {header!r} from a tool call", - "node": "Dropping header \"{header}\" from a tool call: {reason}", + "python": "Dropping header {header} from a tool call: {reason}", + "node": "Dropping header {header} from a tool call: {reason}", "matches": { - "python": false, + "python": true, "node": true }, - "notes": "Python quotes with repr ('x'), prefixes the reason with \"it is\", and words malformed differently. Node writes the name raw between double quotes; the canonical form JSON-escapes it, which only differs for a name holding a quote, a backslash or a control character." + "notes": "The name is JSON text, so a quote, a backslash or a control character in it is escaped." }, { "id": "header-argument-dropped", @@ -59,13 +59,13 @@ "description": "any reason code" } }, - "python": "Dropping header argument {argument!r} from a tool call: it is {reason} | … : not a string, number or boolean | … 'headers' … : not an object | Dropping malformed header argument {argument!r} from a tool call", - "node": "Dropping header argument \"{argument}\" from a tool call: {reason}", + "python": "Dropping header argument {argument} from a tool call: {reason}", + "node": "Dropping header argument {argument} from a tool call: {reason}", "matches": { - "python": false, + "python": true, "node": true }, - "notes": "As header-dropped. Python's not-a-scalar and not-an-object texts already match; its set-by-sdk and not-declared add \"it is\"." + "notes": "The argument is JSON text, as the name in header-dropped is." }, { "id": "rate-limit-retry", @@ -93,13 +93,13 @@ "description": "the wait before the next attempt" } }, - "python": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; retrying in {delay:.2f}s", - "node": "Rate limited (429) by {method} {url}; retrying in {delay_ms}ms (attempt {attempt + 1} of {max_attempts})", + "python": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; retrying in {delay}s", + "node": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; retrying in {delay}s", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Python's sentence is the clearer one: it names the attempt that failed. Node numbers the attempt about to be made, so the two count one apart. Python pads the delay to two decimals (0.00s); the canonical form writes it as a number (0s, 0.75s)." + "notes": "Names the attempt that was answered 429, not the one about to be made." }, { "id": "rate-limit-deadline", @@ -127,13 +127,13 @@ "description": "the wait before the next attempt that would pass the deadline" } }, - "python": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; not retrying, because waiting {delay:.2f}s would outlast the request's deadline ({remaining:.2f}s left)", + "python": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; not retrying, because waiting {delay}s would pass the deadline", "node": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; not retrying, because waiting {delay}s would pass the deadline", "matches": { - "python": false, + "python": true, "node": true }, - "notes": "Both SDKs now emit this, in the style of rate-limit-retry: when the next wait would not finish before the call's deadline, the SDK raises the 429 it already has instead of sleeping. Python's sentence also names how much of the deadline is left ({remaining:.2f}s); the canonical form drops it, as rate-limit-retry drops Python's two-decimal padding." + "notes": "When the next wait would not finish before the call's deadline, the SDK ends the call with the 429 it already has instead of sleeping, and warns this in place of rate-limit-retry." }, { "id": "skip-account", @@ -155,7 +155,7 @@ "python": true, "node": true }, - "notes": "Identical; the error part is whichever message the failure carries, so it matches only where that message does." + "notes": "The error part is whichever message the failure carries, so the whole text is the same in both SDKs only where that message is." }, { "id": "skip-connector", @@ -192,13 +192,13 @@ "description": "up to five of them, sorted, joined by \", \"" } }, - "python": "{count} tool name(s) are served by more than one account ({names}). get_tool() will return the first one listed — pass account_ids to choose.", - "node": "{count} tool name(s) are served by more than one account ({names}). getTool() will return the first one listed — pass accountIds to choose.", + "python": "{count} tool name(s) are served by more than one account ({names}). Looking a tool up by name returns the first one listed — pass account ids to choose.", + "node": "{count} tool name(s) are served by more than one account ({names}). Looking a tool up by name returns the first one listed — pass account ids to choose.", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Language-neutral wording in place of each SDK's method and parameter names." + "notes": "Language-neutral wording: neither SDK's method or parameter names." }, { "id": "ambiguous-connector", @@ -222,11 +222,11 @@ "description": "the one used" } }, - "python": "{action_id!r} matches {count} connectors ({tools}); using {tool}. Pass account_ids to choose.", - "node": "\"{action_id}\" matches {count} connectors ({tools}); using {tool}. Pass accountIds to choose.", + "python": "{action_id} matches {count} connectors ({tools}); using {tool}. Pass account ids to choose.", + "node": "{action_id} matches {count} connectors ({tools}); using {tool}. Pass account ids to choose.", "matches": { - "python": false, - "node": false + "python": true, + "node": true } }, { @@ -247,13 +247,13 @@ "description": "the toolset's timeout" } }, - "python": "MCP request to {endpoint} timed out after {timeout:g}s", - "node": "MCP request to {endpoint} timed out after {timeout_ms}ms", + "python": "MCP request to {endpoint} timed out after {timeout}s", + "node": "MCP request to {endpoint} timed out after {timeout}s", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Seconds, written as a number: 1s, 0.5s, 60s. Python's :g agrees for ordinary values but switches to exponent form below 1e-4 (1e-05s); Node gives milliseconds." + "notes": "Seconds, written as a number: 1s, 0.5s, 60s." }, { "id": "mcp-http-failure", @@ -287,7 +287,7 @@ "python": true, "node": true }, - "notes": "Identical for every status with a reason phrase. For one without, Node trims the trailing space and Python keeps it; the canonical form trims it." + "notes": "For a status with no reason phrase, the space before it is left out too (`failed with 599: …`), as is the `: {body}` suffix for an empty body." }, { "id": "mcp-failure", @@ -349,7 +349,8 @@ "matches": { "python": true, "node": true - } + }, + "notes": "For a status with no reason phrase, Node leaves out the space before the colon and Python keeps it; with an empty body, both keep the trailing `: `. Neither is canonical yet." }, { "id": "accounts-unreachable", @@ -415,13 +416,13 @@ "description": "object, string, number, boolean or null" } }, - "python": "Unexpected /accounts response shape: expected a list, got {type(accounts).__name__}", - "node": "Unexpected /accounts response shape: expected a list, got {typeof accounts}", + "python": "Unexpected /accounts response shape: expected a list, got {json_type}", + "node": "Unexpected /accounts response shape: expected a list, got {json_type}", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Python gives its own type name (dict, str, NoneType); Node gives typeof (object, string) and null. The canonical form names the JSON type." + "notes": "Names the JSON type, not either language's own type name." }, { "id": "no-linked-accounts", @@ -432,12 +433,13 @@ }, "template": "This API key has no linked accounts. Link one in the StackOne dashboard, or pass an account id explicitly.", "placeholders": {}, - "python": "This API key has no linked accounts. Link one in the StackOne dashboard, or pass account_id explicitly.", - "node": "This API key has no linked accounts. Link one in the StackOne dashboard, or pass accountId explicitly.", + "python": "This API key has no linked accounts. Link one in the StackOne dashboard, or pass an account id explicitly.", + "node": "This API key has no linked accounts. Link one in the StackOne dashboard, or pass an account id explicitly.", "matches": { - "python": false, - "node": false - } + "python": true, + "node": true + }, + "notes": "Language-neutral wording: neither SDK's parameter name." }, { "id": "no-active-accounts", @@ -457,11 +459,11 @@ "description": "each as \"{provider} ({status})\", joined by \", \"" } }, - "python": "None of this API key's {count} linked accounts are active: {accounts}. Re-link them in the StackOne dashboard, or pass account_id explicitly.", - "node": "None of this API key's {count} linked accounts are active: {accounts}. Re-link them in the StackOne dashboard, or pass accountId explicitly.", + "python": "None of this API key's {count} linked accounts are active: {accounts}. Re-link them in the StackOne dashboard, or pass an account id explicitly.", + "node": "None of this API key's {count} linked accounts are active: {accounts}. Re-link them in the StackOne dashboard, or pass an account id explicitly.", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, "notes": "A missing provider or status is written None by Python and undefined by Node; neither is canonical yet." }, @@ -537,12 +539,13 @@ }, "template": "An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable", "placeholders": {}, - "python": "API key must be provided either through api_key parameter or STACKONE_API_KEY environment variable", - "node": "API key must be provided either through the apiKey option or the STACKONE_API_KEY environment variable", + "python": "An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable", + "node": "An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable", "matches": { - "python": false, - "node": false - } + "python": true, + "node": true + }, + "notes": "Language-neutral wording: neither SDK's parameter name." }, { "id": "empty-account-id", @@ -564,7 +567,7 @@ "python": true, "node": true }, - "notes": "The same once the parameter is named in each SDK's spelling." + "notes": "Each SDK names the parameter in its own spelling." }, { "id": "account-ids-not-a-list", @@ -584,11 +587,11 @@ "description": "the string given" } }, - "python": "{parameter} must be a list of account ids, not a string. Did you mean [{value!r}]?", - "node": "{parameter} must be an array of account ids, not a string. Did you mean [\"{value}\"]?", + "python": "{parameter} must be a list of account ids, not a string. Did you mean [{value}]?", + "node": "{parameter} must be a list of account ids, not a string. Did you mean [{value}]?", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, "notes": "\"list\", not \"array\": the language-neutral word. The suggestion is JSON, so it reads the same in both." }, @@ -606,13 +609,13 @@ "description": "the parameter's name in the SDK's own spelling: account_ids / accountIds" } }, - "python": "{parameter} must be a list of account id strings, got {ids!r}", - "node": "{parameter} must be an array of account id strings", + "python": "{parameter} must be a list of account id strings", + "node": "{parameter} must be a list of account id strings", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Python appends the list it was given, as a Python repr; dropped, since not every value it could hold is JSON." + "notes": "The list given is not echoed: not every value it could hold is JSON." }, { "id": "account-ids-empty-id", @@ -653,13 +656,13 @@ "description": "the value given" } }, - "python": "{parameter} must be a non-empty string, got {value!r}", + "python": "{parameter} must be a non-empty string, got {value}", "node": "{parameter} must be a non-empty string, got {value}", "matches": { - "python": false, + "python": true, "node": true }, - "notes": "Node already writes the value as JSON; Python as a repr ('' rather than \"\"). Once null means \"not given\" (scenario execute-null-session-id), null no longer raises this." + "notes": "null (None) means the session id was not given, and does not raise this." }, { "id": "invalid-action-id", @@ -679,10 +682,10 @@ "description": "the value given" } }, - "python": "{parameter} must be a non-empty string, got {value!r}", + "python": "{parameter} must be a non-empty string, got {value}", "node": "{parameter} must be a non-empty string, got {value}", "matches": { - "python": false, + "python": true, "node": true } }, @@ -700,13 +703,13 @@ "description": "array, string, number, boolean or null" } }, - "python": "arguments must be a JSON object, got {type(arguments).__name__}", + "python": "arguments must be a JSON object, got {json_type}", "node": "arguments must be a JSON object, got {json_type}", "matches": { - "python": false, + "python": true, "node": true }, - "notes": "Python gives its own type name (list, str); Node already names the JSON type (array, string, null) — no object reaches this message." + "notes": "Names the JSON type; no object reaches this message." }, { "id": "top-k-out-of-range", @@ -730,10 +733,10 @@ "description": "the value given" } }, - "python": "{parameter} must be an integer between 1 and {max}, got {top_k!r}", + "python": "{parameter} must be an integer between 1 and {max}, got {value}", "node": "{parameter} must be an integer between 1 and {max}, got {value}", "matches": { - "python": false, + "python": true, "node": true } }, @@ -755,11 +758,11 @@ "description": "the string given" } }, - "python": "{parameter} must be a list of tool names, not a string. Did you mean [{value!r}]?", - "node": "{parameter} must be an array of tool names, not a string. Did you mean [\"{value}\"]?", + "python": "{parameter} must be a list of tool names, not a string. Did you mean [{value}]?", + "node": "{parameter} must be a list of tool names, not a string. Did you mean [{value}]?", "matches": { - "python": false, - "node": false + "python": true, + "node": true } }, { @@ -792,13 +795,12 @@ "description": "the action id" } }, - "python": "No connector found for \"{action_id}\". Use search() to discover valid action ids.", - "node": "No connector found for \"{action_id}\". Use search() to discover valid action ids.", + "python": "No connector found for {action_id}. Use search() to discover valid action ids.", + "node": "No connector found for {action_id}. Use search() to discover valid action ids.", "matches": { "python": true, "node": true - }, - "notes": "Both write the id raw between double quotes, which is its JSON text for any ordinary id." + } }, { "id": "arguments-not-finite", @@ -818,13 +820,13 @@ "description": "NaN, Infinity or -Infinity" } }, - "python": "Arguments for {tool!r} could not be encoded as JSON: Out of range float values are not JSON compliant: {nan | inf | -inf}", - "node": "Arguments for \"{tool}\" could not be encoded as JSON: Out of range number values are not JSON compliant: {value} (at \"{key}\")", + "python": "Arguments for {tool} could not be encoded as JSON: {value} is not a JSON number", + "node": "Arguments for {tool} could not be encoded as JSON: {value} is not a JSON number", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Both pass on their JSON encoder's wording. The canonical form names the value in JavaScript's spelling and leaves out the location, which Python's encoder does not report." + "notes": "The value is in JavaScript's spelling, and the message leaves out where in the arguments it is, which Python's encoder does not report." }, { "id": "arguments-not-encodable", @@ -844,10 +846,10 @@ "description": "the SDK's own explanation: a circular reference, a non-JSON type, …" } }, - "python": "Arguments for {tool!r} could not be encoded as JSON: {detail}", - "node": "Arguments for \"{tool}\" could not be encoded as JSON: {detail}", + "python": "Arguments for {tool} could not be encoded as JSON: {detail}", + "node": "Arguments for {tool} could not be encoded as JSON: {detail}", "matches": { - "python": false, + "python": true, "node": true }, "notes": "For every reason but a non-finite number, which has its own message above." @@ -870,10 +872,10 @@ "description": "the JSON parser's own message" } }, - "python": "Invalid JSON in arguments for {tool!r}: {detail}", - "node": "Invalid JSON in arguments for \"{tool}\": {detail}", + "python": "Invalid JSON in arguments for {tool}: {detail}", + "node": "Invalid JSON in arguments for {tool}: {detail}", "matches": { - "python": false, + "python": true, "node": true } }, @@ -891,13 +893,13 @@ "description": "the tool's name" } }, - "python": "Tool arguments must be a JSON object", - "node": "Tool arguments for \"{tool}\" must be a JSON object | Invalid parameters type for \"{tool}\". Expected object or string, got {typeof}.", + "python": "Tool arguments for {tool} must be a JSON object", + "node": "Tool arguments for {tool} must be a JSON object", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Node's clearer form, naming the tool. Node has a second message for a value that is neither an object nor a string; the canonical form uses this one for both." + "notes": "For every value that is not an object, including one that is not a string either." }, { "id": "tool-call-failed", @@ -917,8 +919,8 @@ "description": "the result's text, or its structured content as compact JSON" } }, - "python": "Tool \"{tool}\" failed: {detail}", - "node": "Tool \"{tool}\" failed: {detail}", + "python": "Tool {tool} failed: {detail}", + "node": "Tool {tool} failed: {detail}", "matches": { "python": true, "node": true @@ -938,8 +940,8 @@ "description": "the tool's name" } }, - "python": "Tool \"{tool}\" has no executor. Override execute() to run a hand-built tool.", - "node": "Tool \"{tool}\" has no executor. Override execute() to run a hand-built tool.", + "python": "Tool {tool} has no executor. Override execute() to run a hand-built tool.", + "node": "Tool {tool} has no executor. Override execute() to run a hand-built tool.", "matches": { "python": true, "node": true @@ -955,10 +957,10 @@ "description": "the tool call's function name" } }, - "python": "Unknown tool {name!r}", - "node": "Unknown tool \"{name}\"", + "python": "Unknown tool {name}", + "node": "Unknown tool {name}", "matches": { - "python": false, + "python": true, "node": true }, "notes": "Not raised: the `error` of the tool message execute_openai_tool_calls / executeOpenAIToolCalls returns for a call to a tool not in the collection." diff --git a/tests/vectors/retry-after.json b/tests/vectors/retry-after.json index 4a3011e1..3f3069c9 100644 --- a/tests/vectors/retry-after.json +++ b/tests/vectors/retry-after.json @@ -1,6 +1,6 @@ { "$schema": "./schema/retry-after.schema.json", - "description": "How a Retry-After header value reads as seconds from `now`: delta-seconds or an HTTP-date. `expected_seconds` is the RAW value, before the cap: null when the header is absent or unreadable (the caller falls back to its own backoff), 0 for a date in the past. The cap (`max_delay_seconds`) is applied afterwards by the caller, and graded in backoff.json.", + "description": "How a Retry-After header value reads as seconds from `now`: delta-seconds or an HTTP-date. `expected_seconds` is the RAW value, before the cap: null when the header is absent or unreadable (the caller falls back to its own backoff), 0 for a date in the past. An HTTP-date's second may be 60, a leap second, which reads as the first second of the next minute. The cap (`max_delay_seconds`) is applied afterwards by the caller, and graded in backoff.json.", "version": 1, "max_delay_seconds": 30, "cases": [ @@ -27,10 +27,10 @@ }, { "id": "large", - "description": "20 digits: read as a number, not refused; the cap is applied separately, so this is the raw value", + "description": "20 digits: read as a number, not refused; the cap is applied separately, so this is the raw value, compared within the seconds tolerance", "header": "99999999999999999999", "now": "2026-10-01T12:00:00Z", - "expected_seconds": 100000000000000000000 + "expected_seconds": 99999999999999999999 }, { "id": "huge", @@ -275,14 +275,14 @@ { "id": "rfc850-year-76", "description": "RFC 850 two-digit year 76 resolves to 2076: exactly 50 years ahead of `now`, the boundary — not *more than* 50, so it stays in the future.", - "header": "Wednesday, 01-Oct-76 12:00:00 GMT", + "header": "Thursday, 01-Oct-76 12:00:00 GMT", "now": "2026-10-01T12:00:00Z", "expected_seconds": 1577923200 }, { "id": "rfc850-year-77", "description": "RFC 850 two-digit year 77 would resolve to 2077, 51 years ahead — more than 50 — so RFC 9110 §5.6.7 moves it back a century, to 1977, which is in the past.", - "header": "Friday, 01-Oct-77 12:00:00 GMT", + "header": "Saturday, 01-Oct-77 12:00:00 GMT", "now": "2026-10-01T12:00:00Z", "expected_seconds": 0 }, @@ -313,6 +313,27 @@ "header": "Fri, 01 Oct 10000 12:00:00 GMT", "now": "2026-10-01T12:00:00Z", "expected_seconds": null + }, + { + "id": "leap-second", + "description": "second 60 is a leap second: readable, and the first second of the next minute, here of the next year", + "header": "Thu, 31 Dec 2026 23:59:60 GMT", + "now": "2026-12-31T23:59:00Z", + "expected_seconds": 60 + }, + { + "id": "leap-second-year-9999", + "description": "a leap second rolls over even past 31 December 9999: the year limit applies to the year as written, so this is 1 January 10000, not unreadable", + "header": "Fri, 31 Dec 9999 23:59:60 GMT", + "now": "9999-12-31T23:59:00Z", + "expected_seconds": 60 + }, + { + "id": "second-61", + "description": "second 61 is not a time, leap second or not", + "header": "Thu, 01 Oct 2026 12:00:61 GMT", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": null } ] } diff --git a/tests/vectors/schema/argument-encoding.schema.json b/tests/vectors/schema/argument-encoding.schema.json index 40c9b9a0..3de1a34e 100644 --- a/tests/vectors/schema/argument-encoding.schema.json +++ b/tests/vectors/schema/argument-encoding.schema.json @@ -48,6 +48,48 @@ "type": "string", "minLength": 1 }, + "value": { + "description": "Any JSON value, in which an object with a `$number` key is a marker for a number JSON cannot hold, and nothing else.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/value" + } + }, + { + "type": "object", + "properties": { + "$number": { + "enum": ["NaN", "Infinity", "-Infinity"] + } + }, + "required": ["$number"], + "additionalProperties": false + }, + { + "type": "object", + "not": { + "required": ["$number"] + }, + "additionalProperties": { + "$ref": "#/$defs/value" + } + } + ] + }, "case": { "type": "object", "properties": { @@ -58,7 +100,7 @@ "$ref": "#/$defs/description" }, "arguments": { - "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + "$ref": "#/$defs/value" }, "arguments_json": { "type": "string", @@ -118,7 +160,7 @@ "description": "What the Node SDK does today." }, "arguments": { - "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + "$ref": "#/$defs/value" }, "arguments_json": { "type": "string", diff --git a/tests/vectors/schema/backoff.schema.json b/tests/vectors/schema/backoff.schema.json index 8ab781b0..f58501db 100644 --- a/tests/vectors/schema/backoff.schema.json +++ b/tests/vectors/schema/backoff.schema.json @@ -27,9 +27,12 @@ }, "backoff_seconds": { "type": "array", + "minItems": 3, "items": { - "type": "number" - } + "type": "number", + "minimum": 0 + }, + "description": "The base delay before each retry: retry n uses entry n - 1." }, "jitter": { "type": "object", @@ -93,6 +96,17 @@ "type": "string", "minLength": 1 }, + "infinity": { + "description": "Positive infinity, which JSON cannot hold, as a marker an SDK decodes before use.", + "type": "object", + "properties": { + "$number": { + "const": "Infinity" + } + }, + "required": ["$number"], + "additionalProperties": false + }, "deadlineCase": { "type": "object", "properties": { @@ -140,9 +154,16 @@ "description": "The injected uniform value in [0, 1)." }, "retry_after_seconds": { - "type": ["number", "null"], - "minimum": 0, - "description": "The 429's Retry-After as read (see retry-after.json); null when absent or unreadable." + "oneOf": [ + { + "type": ["number", "null"], + "minimum": 0 + }, + { + "$ref": "#/$defs/infinity" + } + ], + "description": "The 429's Retry-After as read (see retry-after.json); null when absent or unreadable. A readable value too large for a float is `{\"$number\": \"Infinity\"}`, as there." }, "expected_delay_seconds": { "type": "number", diff --git a/tests/vectors/schema/header-arguments.schema.json b/tests/vectors/schema/header-arguments.schema.json index de4582b0..14bc5b71 100644 --- a/tests/vectors/schema/header-arguments.schema.json +++ b/tests/vectors/schema/header-arguments.schema.json @@ -57,7 +57,7 @@ }, "header": { "type": "string", - "description": "For an entry of a `headers` object: its name, trimmed." + "description": "For an entry of a `headers` object: its name, trimmed. Present exactly when `argument` is `headers` and the entry, not the whole argument, was dropped." }, "reason": { "enum": [ @@ -70,7 +70,26 @@ } }, "required": ["argument", "reason"], - "additionalProperties": false + "additionalProperties": false, + "if": { + "properties": { + "argument": { + "const": "headers" + }, + "reason": { + "enum": ["set-by-sdk", "not-declared", "malformed"] + } + }, + "required": ["argument", "reason"] + }, + "then": { + "required": ["header"] + }, + "else": { + "not": { + "required": ["header"] + } + } }, "case": { "type": "object", diff --git a/tests/vectors/schema/header-names.schema.json b/tests/vectors/schema/header-names.schema.json index 5daa1f9c..1e544b10 100644 --- a/tests/vectors/schema/header-names.schema.json +++ b/tests/vectors/schema/header-names.schema.json @@ -70,7 +70,7 @@ "type": "object", "properties": { "dropped": { - "enum": ["set-by-sdk", "not-declared", "malformed"] + "enum": ["set-by-sdk", "malformed"] } }, "required": ["dropped"], diff --git a/tests/vectors/schema/header-values.schema.json b/tests/vectors/schema/header-values.schema.json index 445e61bd..6ec72ab5 100644 --- a/tests/vectors/schema/header-values.schema.json +++ b/tests/vectors/schema/header-values.schema.json @@ -37,7 +37,7 @@ "description": "A case where the SDKs differ for a reason outside this rule (for example, their JSON parser already produced different values). Not graded." } }, - "required": ["description", "version", "cases", "known_differences"], + "required": ["description", "version", "cases"], "additionalProperties": false, "$defs": { "id": { @@ -49,6 +49,48 @@ "type": "string", "minLength": 1 }, + "value": { + "description": "Any JSON value, in which an object with a `$number` key is a marker for a number JSON cannot hold, and nothing else.", + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "null" + }, + { + "type": "array", + "items": { + "$ref": "#/$defs/value" + } + }, + { + "type": "object", + "properties": { + "$number": { + "enum": ["NaN", "Infinity", "-Infinity"] + } + }, + "required": ["$number"], + "additionalProperties": false + }, + { + "type": "object", + "not": { + "required": ["$number"] + }, + "additionalProperties": { + "$ref": "#/$defs/value" + } + } + ] + }, "case": { "type": "object", "properties": { @@ -59,7 +101,7 @@ "$ref": "#/$defs/description" }, "value": { - "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + "$ref": "#/$defs/value" }, "expected": { "oneOf": [ @@ -94,7 +136,7 @@ "$ref": "#/$defs/description" }, "value": { - "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + "$ref": "#/$defs/value" }, "python": { "description": "What the Python SDK does today." @@ -117,7 +159,7 @@ "$ref": "#/$defs/description" }, "value": { - "description": "Any JSON value; `{\"$number\": …}` markers stand for non-finite numbers." + "$ref": "#/$defs/value" }, "python": { "description": "What the Python SDK does." diff --git a/tests/vectors/schema/messages.schema.json b/tests/vectors/schema/messages.schema.json index 14dfa877..29fd8ebc 100644 --- a/tests/vectors/schema/messages.schema.json +++ b/tests/vectors/schema/messages.schema.json @@ -178,6 +178,11 @@ }, "then": { "required": ["error"] + }, + "else": { + "not": { + "required": ["error"] + } } }, "unshared": { From dbc296d9b98812e2caa0fd52d58628652c17b640 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 11:05:25 +0100 Subject: [PATCH 076/151] fix(headers): forward an ordinary headers field unchanged whatever its value sanitiseHeaderArguments checked isPlainObject(value) before declared.ordinaryHeadersField, so an object value given for a headers property the schema declares non-object was sanitised as a headers container instead of forwarded as given. Check ordinaryHeadersField first. --- MIGRATION.md | 2 +- src/headers.ts | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index edeb1ea0..1f074ad3 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -183,7 +183,7 @@ await tool.execute({ body: { variables: { first: 25 } } }); **Header arguments are allowlisted.** A header argument is an entry of a `headers` object argument, or a top-level `headers_` argument. Each one is forwarded only if the tool's schema declares it in the same form: under `headers.properties`, or as a `headers_` property. An open `headers` object — `type: "object"`, no `properties`, and `additionalProperties` not `false` — declares every name; without `type: "object"`, or with `additionalProperties: false` and no `properties`, it declares none. `Authorization`, `x-account-id` and `User-Agent` are never forwarded, even when declared, because the SDK sets them itself. Anything dropped is logged as a warning. Every other argument is sent unchanged. -A top-level `headers` argument that isn't a plain object is dropped with a warning, unless the schema declares `headers` itself as a non-object field, in which case it's an ordinary argument that happens to be named `headers` and is sent as given. A `headers_` argument is dropped with a warning when its value is an array or object. +A top-level `headers` argument is sent as given, whatever its value, when the schema declares `headers` itself as a non-object field — it's an ordinary argument that happens to be named `headers`. Otherwise, a `headers` argument that isn't a plain object is dropped with a warning. A `headers_` argument is dropped with a warning when its value is an array or object. `*_execute_action` serves an open `headers` object, so `toolset.execute()` passes your own headers on to the action, with the exception of those three: diff --git a/src/headers.ts b/src/headers.ts index a1033269..ac18d428 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -206,19 +206,20 @@ export function sanitiseHeaders( * `headers_` argument. Every other argument is returned unchanged. A declared * `headers_` keeps its value as given; nested entries are stringified. * - * A top-level `headers` argument that isn't a plain object is forwarded unchanged when the - * schema declares `headers` as something other than an object (it's an ordinary field that - * happens to be named `headers`), and dropped otherwise. A flat `headers_` whose value is - * an array or object is dropped too — only a string, number or boolean can be a header value. + * A top-level `headers` argument is forwarded unchanged, whatever its value, when the schema + * declares `headers` as something other than an object (it's an ordinary field that happens to + * be named `headers`). Otherwise it's sanitised as a headers object if it is a plain object, and + * dropped if it isn't. A flat `headers_` whose value is an array or object is dropped too + * — only a string, number or boolean can be a header value. */ export function sanitiseHeaderArguments(args: JsonObject, declared: DeclaredHeaders): JsonObject { const clean: JsonObject = {}; for (const [key, value] of Object.entries(args)) { if (key === 'headers') { - if (isPlainObject(value)) { - clean.headers = sanitiseHeaders(value, declared.nested); - } else if (declared.ordinaryHeadersField) { + 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`); } From 20d731f635c996b3bcd1f111ab4adc3c6828b783 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 11:05:25 +0100 Subject: [PATCH 077/151] ci: pin sdk-conformance to 0906f4d --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 516bd59a..830a8f6f 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: daf1140a61987c544db2ad32d89960cf99cff184 + ref: 0906f4d8ed8aef20884d65a6da157d65416f6cb0 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From a28f3a7706ebe68648994596914df9156dcf7954 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 11:18:24 +0100 Subject: [PATCH 078/151] docs(migration): an ordinary headers field still passes the JSON-value check --- MIGRATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MIGRATION.md b/MIGRATION.md index 1f074ad3..e6f596ec 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -183,7 +183,7 @@ await tool.execute({ body: { variables: { first: 25 } } }); **Header arguments are allowlisted.** A header argument is an entry of a `headers` object argument, or a top-level `headers_` argument. Each one is forwarded only if the tool's schema declares it in the same form: under `headers.properties`, or as a `headers_` property. An open `headers` object — `type: "object"`, no `properties`, and `additionalProperties` not `false` — declares every name; without `type: "object"`, or with `additionalProperties: false` and no `properties`, it declares none. `Authorization`, `x-account-id` and `User-Agent` are never forwarded, even when declared, because the SDK sets them itself. Anything dropped is logged as a warning. Every other argument is sent unchanged. -A top-level `headers` argument is sent as given, whatever its value, when the schema declares `headers` itself as a non-object field — it's an ordinary argument that happens to be named `headers`. Otherwise, a `headers` argument that isn't a plain object is dropped with a warning. A `headers_` argument is dropped with a warning when its value is an array or object. +A top-level `headers` argument skips header filtering when the schema declares `headers` itself as a non-object field — it's an ordinary argument that happens to be named `headers`, so it is sent as given, subject to the same JSON-value check as every other argument. Otherwise, a `headers` argument that isn't a plain object is dropped with a warning. A `headers_` argument is dropped with a warning when its value is an array or object. `*_execute_action` serves an open `headers` object, so `toolset.execute()` passes your own headers on to the action, with the exception of those three: From 0faa7f5c088c5ac34fd94f945b940c5d0a20419b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 11:18:24 +0100 Subject: [PATCH 079/151] test(vectors): sync the shared vectors to sdk-conformance dfdaca1 --- tests/vectors/README.md | 3 ++- tests/vectors/messages.json | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/vectors/README.md b/tests/vectors/README.md index b6fdba53..2494a45c 100644 --- a/tests/vectors/README.md +++ b/tests/vectors/README.md @@ -46,7 +46,8 @@ SDKs disagree on today and the contract does not yet settle; none is open right - **`id`** is unique within a file and does not change: a test names its cases by it. - **`version`** is bumped when an existing case's meaning or expected value changes. Adding a case - does not bump it. + does not bump it. Versions count from the first release of the vectors: changes made before + `feat/feedback-invariant` merges stay at version 1. - **`unresolved`** cases are not graded. Each one says what the two SDKs do differently. Once the contract settles it, the case moves to `cases` with the agreed value, and the SDK that changes fixes its code in the same release. A file only has this array while it has an open case. diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index 0c40d27e..d1921d89 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -1,6 +1,6 @@ { "$schema": "./schema/messages.schema.json", - "description": "The canonical wording of every user-facing warning and error message both SDKs emit. `template` is the canonical text; `python` and `node` are each SDK's text today, written with the same placeholders (and `|` between variants), so an SDK can see what changes. A prefix the language adds — Node's `[@stackone/ai] `, Python's logger name — is outside the template. An error's class is in `error`. `matches` says whether an SDK's text is already the canonical one; `notes` say where the text depends on more than the template.", + "description": "The canonical wording of every user-facing warning and error message both SDKs emit. `template` is the canonical text; `python` and `node` are each SDK's text today, written with the same placeholders, so an SDK can see what changes. A prefix the language adds — Node's `[@stackone/ai] `, Python's logger name — is outside the template. An error's class is in `error`. `matches` says whether an SDK's text is already the canonical one; `notes` say where the text depends on more than the template.", "version": 1, "prefixes": { "node": "Every warning goes through console.warn, prefixed `[@stackone/ai] ` — outside the template.", From 24174d0d817da0494b76cfd2a72eea6f2b0f2b39 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 11:18:24 +0100 Subject: [PATCH 080/151] ci: pin sdk-conformance to dfdaca1 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 830a8f6f..7b07558e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 0906f4d8ed8aef20884d65a6da157d65416f6cb0 + ref: dfdaca11059adbcfdb0589791c2044d1dc4ab1c1 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 7ff34520c95ca8989362b605609d052860f24a82 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 11:24:34 +0100 Subject: [PATCH 081/151] test(vectors): sync the shared vectors to sdk-conformance ee0bb06 --- tests/vectors/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/vectors/README.md b/tests/vectors/README.md index 2494a45c..24e3fad7 100644 --- a/tests/vectors/README.md +++ b/tests/vectors/README.md @@ -46,8 +46,8 @@ SDKs disagree on today and the contract does not yet settle; none is open right - **`id`** is unique within a file and does not change: a test names its cases by it. - **`version`** is bumped when an existing case's meaning or expected value changes. Adding a case - does not bump it. Versions count from the first release of the vectors: changes made before - `feat/feedback-invariant` merges stay at version 1. + does not bump it. Versions count from the vectors' first release: every change made before it + stays at version 1. - **`unresolved`** cases are not graded. Each one says what the two SDKs do differently. Once the contract settles it, the case moves to `cases` with the agreed value, and the SDK that changes fixes its code in the same release. A file only has this array while it has an open case. From 66dc25e5506a4c07e2a04df4925c8b78e6175cde Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 11:24:34 +0100 Subject: [PATCH 082/151] ci: pin sdk-conformance to ee0bb06 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 7b07558e..b747ac74 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -160,7 +160,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: dfdaca11059adbcfdb0589791c2044d1dc4ab1c1 + ref: ee0bb06e6d52b1cc41bf173fd2fd236ff387cb60 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 6dc31e50907e9134f465aef65b9d91a1749ce5ba Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:11:23 +0100 Subject: [PATCH 083/151] test(vectors): fail on a vector file that no test grades --- src/vectors.test.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/vectors.test.ts b/src/vectors.test.ts index 3b62b1e3..8e3d53c0 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -3,7 +3,7 @@ * (scripts/sync-vectors.sh), run against the SDK's own code. The Python SDK runs the same files. * `unresolved` cases are not graded; every other case must pass. */ -import { readFileSync } from 'node:fs'; +import { readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; import { http, HttpResponse } from 'msw'; @@ -63,6 +63,24 @@ function loadFile(name: string): File { } const load = (name: string): VectorFile => loadFile>(name); +/** Every vector file a describe() below grades. */ +const GRADED = [ + 'account-ids.json', + 'argument-encoding.json', + 'backoff.json', + 'header-arguments.json', + 'header-names.json', + 'header-values.json', + 'messages.json', + 'retry-after.json', +]; + +// 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()); +}); + /** Seconds are compared with a relative tolerance of 1e-9 (README, "Reading the values"). */ const expectSeconds = (actual: number | null, expected: number | null): void => { if (expected === null || actual === null || !Number.isFinite(expected)) { From 3f098d0d4852baef3bf341166230f95775fece64 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:11:24 +0100 Subject: [PATCH 084/151] docs: pass STACKONE_ACCOUNT_ID || undefined in every snippet and example A variable that is set but empty would otherwise throw, as MIGRATION.md warns. --- README.md | 12 ++++++------ examples/ai-sdk-integration.ts | 2 +- examples/anthropic-integration.ts | 2 +- examples/auth-management.ts | 8 ++++---- examples/claude-agent-sdk-integration.ts | 2 +- examples/openai-integration.ts | 2 +- examples/openai-responses-integration.ts | 2 +- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index a5067476..fd80e9b0 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ StackOne uses account IDs to identify different integrations. You can specify th import { StackOneToolSet } from '@stackone/ai'; // Single account, read from your own environment variable. Unset means discovery -const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools(); // Explicit single account @@ -126,7 +126,7 @@ import { OpenAI } from 'openai'; import { StackOneToolSet } from '@stackone/ai'; // Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used -const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools({ actions: ['workday_*'] }); const openai = new OpenAI(); @@ -164,7 +164,7 @@ import OpenAI from 'openai'; import { StackOneToolSet } from '@stackone/ai'; // Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used -const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools(); @@ -194,7 +194,7 @@ import Anthropic from '@anthropic-ai/sdk'; import { StackOneToolSet } from '@stackone/ai'; // Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used -const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools(); @@ -233,7 +233,7 @@ import { generateText, stepCountIs } from 'ai'; import { StackOneToolSet } from '@stackone/ai'; // Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used -const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools(); @@ -260,7 +260,7 @@ import { query } from '@anthropic-ai/claude-agent-sdk'; import { StackOneToolSet } from '@stackone/ai'; // Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used -const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); +const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Fetch tools and convert to Claude Agent SDK format const tools = await toolset.fetchTools(); diff --git a/examples/ai-sdk-integration.ts b/examples/ai-sdk-integration.ts index c5cb08d4..234d62ec 100644 --- a/examples/ai-sdk-integration.ts +++ b/examples/ai-sdk-integration.ts @@ -30,7 +30,7 @@ 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 account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Filter to specific tools to keep token usage manageable const tools = await toolset.fetchTools({ diff --git a/examples/anthropic-integration.ts b/examples/anthropic-integration.ts index cb0d327f..5780c2fb 100644 --- a/examples/anthropic-integration.ts +++ b/examples/anthropic-integration.ts @@ -19,7 +19,7 @@ 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 account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Filter for any relevant tools const tools = await toolset.fetchTools({ diff --git a/examples/auth-management.ts b/examples/auth-management.ts index 8e7804be..b193cc5d 100644 --- a/examples/auth-management.ts +++ b/examples/auth-management.ts @@ -53,8 +53,8 @@ const accountIdFromEnv = async (): Promise => { console.log('=== 2. Account ID from environment ===\n'); // The SDK only reads the API key from env; read the account id yourself and pass it. - // Unset, it is undefined and the toolset discovers every active account instead. - const accountId = process.env.STACKONE_ACCOUNT_ID; + // Unset or empty, it is undefined and the toolset discovers every active account instead. + const accountId = process.env.STACKONE_ACCOUNT_ID || undefined; console.log(` STACKONE_ACCOUNT_ID is ${accountId ? 'set' : 'not set'}`); const toolset = new StackOneToolSet({ accountId }); @@ -66,7 +66,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 = process.env.STACKONE_ACCOUNT_ID || '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 +76,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 = process.env.STACKONE_ACCOUNT_ID || '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 1ebe6760..ce63a2d5 100644 --- a/examples/claude-agent-sdk-integration.ts +++ b/examples/claude-agent-sdk-integration.ts @@ -25,7 +25,7 @@ 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 account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Fetch tools from StackOne and convert to Claude Agent SDK format const tools = await toolset.fetchTools(); diff --git a/examples/openai-integration.ts b/examples/openai-integration.ts index c3587f07..fab84e2b 100644 --- a/examples/openai-integration.ts +++ b/examples/openai-integration.ts @@ -19,7 +19,7 @@ if (!process.env.OPENAI_API_KEY) { 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 account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Filter to specific tools to stay within OpenAI's 128-tool limit const tools = await toolset.fetchTools({ diff --git a/examples/openai-responses-integration.ts b/examples/openai-responses-integration.ts index 0af168a6..e93130bd 100644 --- a/examples/openai-responses-integration.ts +++ b/examples/openai-responses-integration.ts @@ -19,7 +19,7 @@ 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 account linked to the key - const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID }); + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Fetch tools via MCP const tools = await toolset.fetchTools({ From ba3fa71583ee5d5aee87ad1e778c70dd4f7f631b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:11:24 +0100 Subject: [PATCH 085/151] feat(toolsets): warn when STACKONE_ACCOUNT_ID is set but ignored A 2.x setup that relied on it would otherwise widen to every account on the key without a word. --- MIGRATION.md | 2 +- src/toolsets.test.ts | 22 ++++++++++++++++++++++ src/toolsets.ts | 15 +++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/MIGRATION.md b/MIGRATION.md index e6f596ec..281bf19b 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -195,7 +195,7 @@ await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' **With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active account. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. -**`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: +**`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. A toolset constructed with no account while `STACKONE_ACCOUNT_ID` is set warns that it is ignored. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: ```typescript // 2.x: STACKONE_ACCOUNT_ID picked up implicitly diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 666f7395..284b196b 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -86,6 +86,28 @@ describe('configuration', () => { expect(listMock.mock.calls.map(([request]) => accountOf(request))).toEqual(['default', 'acc1']); }); + // 2.x read it, so an upgrade that still relies on it would widen to every account unwarned. + it('warns once when STACKONE_ACCOUNT_ID is set and no account is passed', () => { + vi.stubEnv('STACKONE_ACCOUNT_ID', 'acc3'); + + newToolSet(); + + expect(warnSpy.mock.calls.map(([message]: unknown[]) => String(message))).toEqual([ + '[@stackone/ai] STACKONE_ACCOUNT_ID is set but ignored: with no account passed, the toolset uses every active account linked to the API key. Pass accountId (or accountIds) to choose.', + ]); + }); + + it.each([ + ['an empty STACKONE_ACCOUNT_ID', '', {}], + ['accountId', 'acc3', { accountId: 'acc1' }], + ['accountIds', 'acc3', { accountIds: ['acc1'] }], + ['execute.accountIds', 'acc3', { execute: { accountIds: ['acc1'] } }], + ])('does not warn about STACKONE_ACCOUNT_ID given %s', (_name, value, config) => { + vi.stubEnv('STACKONE_ACCOUNT_ID', value); + newToolSet(config); + expect(warnSpy).not.toHaveBeenCalled(); + }); + it('refuses both accountId and accountIds', () => { expect(() => newToolSet({ accountId: 'a', accountIds: ['b'] } as never)).toThrow( /Cannot provide both accountId and accountIds/, diff --git a/src/toolsets.ts b/src/toolsets.ts index a78397e9..18d2d5b1 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -348,6 +348,8 @@ export class StackOneToolSet { /** * Falls back to `STACKONE_API_KEY` and `STACKONE_BASE_URL`, but never reads an account id from * the environment: `accountId` / `accountIds` must be passed, or every active account is used. + * When `STACKONE_ACCOUNT_ID` is set and no account is passed, that is warned about, since 2.x + * read it. * * @throws ToolSetConfigError If no API key is given or found in `STACKONE_API_KEY`, or both * `accountId` and `accountIds` are given, or `accountId` is an empty string. @@ -387,6 +389,19 @@ export class StackOneToolSet { this.#toolMode = config.toolMode; 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 && + config.accountId == null && + config.accountIds == null && + config.execute?.accountIds == null + ) { + warn( + 'STACKONE_ACCOUNT_ID is set but ignored: with no account passed, the toolset uses every active account linked to the API key. Pass accountId (or accountIds) to choose.', + ); + } } /** From 71206eb4e1001a78031f8c6af1ced6d1a855703c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:11:45 +0100 Subject: [PATCH 086/151] fix(retry): report a timeout while retrying a 429 as the 429 Reported as a timeout, it skipped the account and returned a partial catalog, which a 429 never does. --- src/mcp-client.ts | 40 +++++++++++++++++++++++----- src/rate-limit.test.ts | 57 +++++++++++++++++++++++++++++++++++++++- src/toolsets.ts | 20 ++++++++++++-- src/utils/fetch-retry.ts | 5 +++- 4 files changed, 112 insertions(+), 10 deletions(-) diff --git a/src/mcp-client.ts b/src/mcp-client.ts index 8cea71c3..d0542753 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -73,10 +73,7 @@ export function describeMcpFailure(error: unknown, endpoint: string, timeout: nu { cause: error }, ); } - if ( - error instanceof McpDeadlineError || - (error instanceof McpError && error.code === ErrorCode.RequestTimeout) - ) { + if (isTimeout(error)) { // In seconds, written as a number (0.5s, 60s), as the Python SDK writes it. return new ToolSetLoadError(`MCP request to ${endpoint} timed out after ${timeout / 1000}s`, { cause: error, @@ -103,10 +100,22 @@ export function isRateLimitFailure(error: unknown): boolean { return ( error instanceof StackOneAPIError && error.statusCode === 429 && - error.cause instanceof StreamableHTTPError + (error.cause instanceof StreamableHTTPError || error.cause instanceof RateLimitTimeoutError) ); } +/** A session that timed out while a 429 was being retried. */ +class RateLimitTimeoutError extends Error { + constructor(options: ErrorOptions) { + super('timed out while retrying a 429', options); + this.name = 'RateLimitTimeoutError'; + } +} + +const isTimeout = (error: unknown): boolean => + error instanceof McpDeadlineError || + (error instanceof McpError && error.code === ErrorCode.RequestTimeout); + /** * Open an MCP session, run `work` in it and close it, all within one deadline. * @@ -120,11 +129,18 @@ async function withMcpSession( work: (client: Client) => Promise, ): Promise { const expiresAt = retryTiming.now() + timeout; + let rateLimited = false; const transport = new StreamableHTTPClientTransport(new URL(endpoint), { requestInit: { headers }, // Every request the client sends, handshake included, so it never sees a 429 it could // have waited out — but never one that would outlast the session's deadline. - fetch: (url, init) => fetchWithRetry(url, init, { deadline: expiresAt }), + fetch: (url, init) => + fetchWithRetry(url, init, { + deadline: expiresAt, + onRetry: () => { + rateLimited = true; + }, + }), }); const client = new Client({ name: 'stackone-ai-node', version }); let timer: ReturnType | undefined; @@ -138,6 +154,18 @@ async function withMcpSession( })(); return await Promise.race([session, deadline]); } catch (error) { + // A timeout while a 429 was being retried is the rate limit's doing, not the account's: + // reported as a timeout, it would skip the account and return a partial result, which a + // 429 must never do. + if (rateLimited && isTimeout(error)) { + throw new StackOneAPIError( + `MCP request to ${endpoint} was rate limited (429) and timed out after ${timeout / 1000}s while retrying`, + 429, + null, + undefined, + { cause: new RateLimitTimeoutError({ cause: error }) }, + ); + } throw describeMcpFailure(error, endpoint, timeout); } finally { clearTimeout(timer); diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts index aec8593c..28ef0867 100644 --- a/src/rate-limit.test.ts +++ b/src/rate-limit.test.ts @@ -3,7 +3,7 @@ * retries fails the whole call rather than costing one account. The retry timing itself is * covered in utils/fetch-retry.test.ts; here every 429 carries `Retry-After: 0`, so nothing waits. */ -import { http, HttpResponse } from 'msw'; +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'; @@ -308,6 +308,61 @@ describe('a 429 whose wait would outlast the timeout', () => { }); }); +// A retry that times out is still the rate limit's doing: reported as a timeout, it would skip +// the account and return a partial catalog, which a 429 never does. +describe('a timeout while a 429 is retried', () => { + it('fails a multi-account listing with a 429', async () => { + let acc2Requests = 0; + const app = createMcpApp({ accountTools: accountMcpTools }); + server.use( + http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { + if (request.headers.get('x-account-id') === 'acc2') { + if (acc2Requests++ === 0) { + return HttpResponse.json(RATE_LIMITED, { + status: 429, + headers: { 'Retry-After': '0' }, + }); + } + await delay('infinite'); + } + return app.fetch(request); + }), + ); + + const error = await newToolSet({ timeout: 300 }) + .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( + `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([]); + }); + + it('fails GET /accounts with a 429', async () => { + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, async () => { + if (requests++ === 0) { + return HttpResponse.json(RATE_LIMITED, { status: 429, headers: { 'Retry-After': '0' } }); + } + await delay('infinite'); + return HttpResponse.json([]); + }), + ); + + const error = await newToolSet({ timeout: 300 }) + .fetchAccounts() + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + expect(requests).toBe(2); + }); +}); + describe('other statuses', () => { it.each([400, 500])('does not retry a %i', async (status) => { let requests = 0; diff --git a/src/toolsets.ts b/src/toolsets.ts index 18d2d5b1..a488ba6e 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -455,13 +455,14 @@ export class StackOneToolSet { * `status === 'active'` can serve tools. * * @throws StackOneAPIError If the API answers with an error status, including a 429 that - * outlasted its retries. + * outlasted its retries or timed out while being retried. * @throws ToolSetLoadError If the API cannot be reached, or answers with something that is * not a JSON list (including a body that is not valid UTF-8). */ async fetchAccounts(): Promise { const url = `${this.#baseUrl.replace(/\/+$/, '')}/accounts`; let response: Response; + let rateLimited = false; try { response = await fetchWithRetry( url, @@ -469,9 +470,24 @@ export class StackOneToolSet { headers: buildRequestHeaders({ apiKey: this.#apiKey, extraHeaders: this.#headers }), signal: AbortSignal.timeout(this.#timeout), }, - { deadline: retryTiming.now() + this.#timeout }, + { + deadline: retryTiming.now() + this.#timeout, + onRetry: () => { + rateLimited = true; + }, + }, ); } catch (error) { + // Timing out while a 429 is retried is still the rate limit, as it is over MCP. + if (rateLimited && error instanceof DOMException && error.name === 'TimeoutError') { + throw new StackOneAPIError( + `Listing accounts at ${url} was rate limited (429) and timed out after ${this.#timeout / 1000}s while retrying`, + 429, + null, + undefined, + { cause: error }, + ); + } throw new ToolSetLoadError(`Could not reach ${url}: ${describeError(error)}`, { cause: error, }); diff --git a/src/utils/fetch-retry.ts b/src/utils/fetch-retry.ts index 1f51e226..5db2cff2 100644 --- a/src/utils/fetch-retry.ts +++ b/src/utils/fetch-retry.ts @@ -21,6 +21,8 @@ interface RetryOptions { */ deadline?: number; timing?: RetryTiming; + /** Called with each 429 about to be retried, before the wait. */ + onRetry?: (response: Response) => void; } const sleep = (ms: number, signal?: AbortSignal | null): Promise => @@ -190,7 +192,7 @@ const formatSeconds = (ms: number): string => String(Math.floor((ms / 1000) * 10 export async function fetchWithRetry( input: string | URL, init?: RequestInit, - { deadline, timing = retryTiming }: RetryOptions = {}, + { deadline, timing = retryTiming, onRetry }: RetryOptions = {}, ): Promise { for (let retry = 1; ; retry++) { const response = await fetch(input, init); @@ -212,6 +214,7 @@ export async function fetchWithRetry( // Discarded unread: only the final 429's body is reported. Not awaited, since a cancel can // wait on a producer that never settles (MSW's, for one), and the retry need not wait. void response.body?.cancel().catch(() => undefined); + onRetry?.(response); warn(`${limited}; retrying in ${formatSeconds(delay)}s`); if (delay > 0) { await timing.sleep(delay, init?.signal); From e16e1fafaae8a5a84f2df3f1fe7558a4ee732c4d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:12:13 +0100 Subject: [PATCH 087/151] fix(toolsets): cache healthy accounts and keep each failure when every account fails An account that fails to list is skipped and left out of the cached catalog until FAILED_ACCOUNT_RETRY_MS (30s) has passed, rather than leaving nothing cached and re-listing every account on every call. When every account fails with one HTTP status that StackOneAPIError is rethrown, as with a single account; otherwise the ToolSetLoadError carries each account's error as an AggregateError cause. --- MIGRATION.md | 2 +- README.md | 2 +- src/consts.ts | 7 +++ src/toolsets.test.ts | 114 +++++++++++++++++++++++++++++++----- src/toolsets.ts | 135 +++++++++++++++++++++++++++++-------------- 5 files changed, 200 insertions(+), 60 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 281bf19b..09b6827b 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -244,7 +244,7 @@ const tools = (await toolset.fetchTools()).filter( ); ``` -`submitFeedback()` throws `ToolSetLoadError` when feedback is not enabled. +`submitFeedback()` throws `ToolSetLoadError` when feedback is not enabled. It calls the tool once, on the lowest account id in scope, and sends `actionRunId` as `action_run_id` when given. ## Errors diff --git a/README.md b/README.md index fd80e9b0..91a14f03 100644 --- a/README.md +++ b/README.md @@ -381,7 +381,7 @@ This is especially useful when you want to: - Focus on specific HR/CRM/ATS providers - Get only certain types of operations (e.g., all "list" operations) -The catalog is cached per account scope and mode, so changing a filter never refetches it. Call `clearCatalogCache()` after linking or unlinking accounts. +The catalog is cached per account scope and mode, so changing a filter never refetches it. Call `clearCatalogCache()` after linking or unlinking accounts. An account that fails to list tools is skipped with a warning and left out of the cached catalog for 30 seconds, after which the next call lists it again. If every account fails with the same HTTP status (a revoked key's 401, say), that `StackOneAPIError` is thrown; otherwise a `ToolSetLoadError` whose `cause` holds each account's error. ### Tool schemas diff --git a/src/consts.ts b/src/consts.ts index d9041cd7..6cc22d0a 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -34,3 +34,10 @@ export const RATE_LIMIT_BASE_DELAY_MS = 1_000; /** Upper bound on a server-requested `Retry-After` wait. */ export const RATE_LIMIT_MAX_DELAY_MS = 30_000; + +/** + * How long an account that failed to list tools is left out of a cached catalog before a later + * call tries it again. Short, so a re-linked account comes back quickly; long enough that one + * broken account does not cost every call a fresh round trip, or a full timeout if it hangs. + */ +export const FAILED_ACCOUNT_RETRY_MS = 30_000; diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 284b196b..097c5f06 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -13,12 +13,14 @@ import { createMcpApp, } 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 { StackOneToolSet } from './toolsets'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; +import { retryTiming } from './utils/fetch-retry'; vi.mock('./mcp-client', async (importOriginal) => { const actual = await importOriginal(); @@ -522,28 +524,110 @@ describe('listing', () => { ); }); - it('treats every account failing as a failure, not an empty catalog', async () => { + 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) }; fakeListing((request) => { - throw new Error(`boom for ${accountOf(request)}`); + throw failures[accountOf(request) as 'a' | 'b']; }); - await expect(newToolSet().fetchTools({ accountIds: ['a', 'b'] })).rejects.toThrow( - 'No account returned tools. a: boom for a | b: boom for b', - ); + + const error = await newToolSet() + .fetchTools({ accountIds: ['a', 'b'] }) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolSetLoadError); + expect((error as Error).message).toBe('No account returned 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]); + }); + + // A revoked key is a 401 however many accounts it has, as it is with one. + it('rethrows the API error when every account fails with the same status', async () => { + const revoked = new StackOneAPIError('revoked', 401, null); + fakeListing(() => { + throw revoked; + }); + + const one = await newToolSet({ accountId: 'a' }) + .fetchTools() + .catch((caught: unknown) => caught); + const many = await newToolSet() + .fetchTools({ accountIds: ['a', 'b'] }) + .catch((caught: unknown) => caught); + + expect(one).toBe(revoked); + expect(many).toBe(revoked); }); - it('does not cache a degraded listing', async () => { + describe('an account that fails', () => { + let now = 0; let failB = true; - fakeListing((request) => { - if (accountOf(request) === 'b' && failB) { - throw new Error('boom'); - } - return [def(`tool_${accountOf(request)}`)]; + beforeEach(() => { + now = 1_000; + failB = true; + vi.spyOn(retryTiming, 'now').mockImplementation(() => now); + fakeListing((request) => { + if (accountOf(request) === 'b' && failB) { + throw new Error('boom'); + } + return [def(`tool_${accountOf(request)}`)]; + }); }); - const toolset = newToolSet(); + 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. + it('is left out of the cached catalog, without re-listing or re-warning', async () => { + const toolset = newToolSet(); + + expect(names(await toolset.fetchTools({ accountIds: ['a', 'b'] }))).toEqual(['tool_a']); + now += FAILED_ACCOUNT_RETRY_MS - 1; + expect(names(await toolset.fetchTools({ accountIds: ['a', 'b'] }))).toEqual(['tool_a']); + + expect(listedAccounts()).toEqual(['a', 'b']); + expect(warnSpy).toHaveBeenCalledOnce(); + }); + + it(`is listed again, alone, once ${FAILED_ACCOUNT_RETRY_MS}ms have passed`, async () => { + const toolset = newToolSet(); + await toolset.fetchTools({ accountIds: ['a', 'b'] }); + + failB = false; + now += FAILED_ACCOUNT_RETRY_MS; + expect(names(await toolset.fetchTools({ accountIds: ['b', 'a'] }))).toEqual([ + 'tool_a', + 'tool_b', + ]); + expect(names(await toolset.fetchTools({ accountIds: ['a', 'b'] }))).toEqual([ + 'tool_a', + 'tool_b', + ]); + expect(listedAccounts()).toEqual(['a', 'b', 'b']); + }); + + it('is warned about again when the retry fails too, and waits another period', async () => { + const toolset = newToolSet(); + await toolset.fetchTools({ accountIds: ['a', 'b'] }); + + now += FAILED_ACCOUNT_RETRY_MS; + expect(names(await toolset.fetchTools({ accountIds: ['a', 'b'] }))).toEqual(['tool_a']); + now += FAILED_ACCOUNT_RETRY_MS - 1; + await toolset.fetchTools({ accountIds: ['a', 'b'] }); + + expect(listedAccounts()).toEqual(['a', 'b', 'b']); + expect(warnSpy).toHaveBeenCalledTimes(2); + }); + + it('is forgotten by clearCatalogCache()', async () => { + const toolset = newToolSet(); + await toolset.fetchTools({ accountIds: ['a', 'b'] }); - expect((await toolset.fetchTools({ accountIds: ['a', 'b'] })).length).toBe(1); - failB = false; - expect((await toolset.fetchTools({ accountIds: ['a', 'b'] })).length).toBe(2); + failB = false; + toolset.clearCatalogCache(); + expect(names(await toolset.fetchTools({ accountIds: ['a', 'b'] }))).toEqual([ + 'tool_a', + 'tool_b', + ]); + }); }); it('passes an SDK error through without re-wrapping it', async () => { diff --git a/src/toolsets.ts b/src/toolsets.ts index a488ba6e..faa44330 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -2,6 +2,7 @@ import type { MergeExclusive, SimplifyDeep } from 'type-fest'; import { DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, + FAILED_ACCOUNT_RETRY_MS, MAX_CONCURRENCY, MAX_TOP_K, SUBMIT_FEEDBACK_TOOL_NAME, @@ -201,6 +202,13 @@ interface CatalogEntry { endpoint: string; } +/** A cached catalog: each healthy account's listing, and when each failing one last failed. */ +interface CachedCatalog { + listings: ReadonlyMap; + /** On {@link retryTiming}'s clock. */ + failedAt: ReadonlyMap; +} + const describeError = (error: unknown): string => error instanceof Error ? error.message : String(error); @@ -334,7 +342,7 @@ export class StackOneToolSet { * (`setAccountId` rebinds one), so handing the same instances back on a cache hit let one * caller silently rescope every later caller's tools. */ - readonly #catalogCache = new Map(); + readonly #catalogCache = new Map(); #discoveredAccountIds: string[] | undefined; #discovering: Promise | undefined; /** @@ -628,20 +636,33 @@ export class StackOneToolSet { } /** - * List every scoped account's catalog, tolerating accounts that fail. + * The catalog of every scoped account, from the cache where it can be. * * One unusable account must not cost the caller every other account's tools, so a failing - * account is skipped with a warning — unless every account fails, which is an error rather - * than an empty catalog. A 429 that outlasted its retries is not the account's fault but the - * key's, so it fails the whole listing instead: skipping it would hand back a catalog missing - * whichever accounts happened to be throttled. A degraded listing is not cached: the warning - * fires once, and every later call would otherwise serve the short list silently for the life - * of the process. + * account is skipped with a warning. The healthy accounts' listings are cached all the same, + * and the failed account is left out — silently — until {@link FAILED_ACCOUNT_RETRY_MS} has + * passed, when the next call lists it again. Not caching at all made every call re-list every + * account, and wait out the full timeout on one that hangs. + * + * A 429 that outlasted its retries is not the account's fault but the key's, so it fails the + * whole listing instead: skipping it would hand back a catalog missing whichever accounts + * happened to be throttled. When every account fails, see {@link allAccountsFailed}. */ - async #listCatalog( - scope: readonly string[], - mode: ToolMode | undefined, - ): Promise { + async #catalog(scope: readonly string[], mode: ToolMode | undefined): Promise { + const key = this.#cacheKey(scope, mode); + const cached = this.#catalogCache.get(key); + const now = retryTiming.now(); + const due = cached + ? [...cached.failedAt] + .filter(([, failedAt]) => now - failedAt >= FAILED_ACCOUNT_RETRY_MS) + .map(([accountId]) => accountId) + : scope; + const inScopeOrder = (listings: CachedCatalog['listings']): CatalogEntry[] => + scope.flatMap((accountId) => listings.get(accountId) ?? []); + if (cached && due.length === 0) { + return inScopeOrder(cached.listings); + } + const generation = this.#cacheGeneration; const endpoint = this.#endpoint(mode); const listAccount = async (accountId: string): Promise => { @@ -656,44 +677,47 @@ export class StackOneToolSet { }); return definitions.map((definition) => ({ definition, accountId, endpoint })); }; - - const store = (listing: CatalogEntry[]): void => { + const store = (catalog: CachedCatalog): void => { if (generation === this.#cacheGeneration) { - this.#catalogCache.set(this.#cacheKey(scope, mode), listing); + this.#catalogCache.set(key, catalog); } }; if (scope.length === 1) { - const listing = await listAccount(scope[0] as string); - store(listing); - return listing; + const accountId = scope[0] as string; + const listings = new Map([[accountId, await listAccount(accountId)]]); + store({ listings, failedAt: new Map() }); + return inScopeOrder(listings); } const settled = await settleWithConcurrency( - scope, + due, MAX_CONCURRENCY, listAccount, isRateLimitFailure, ); - const listing: CatalogEntry[] = []; - const failures: string[] = []; + const listings = new Map(cached?.listings); + const failedAt = new Map(cached?.failedAt); + const failures: [accountId: string, reason: unknown][] = []; settled.forEach((outcome, index) => { + const accountId = due[index] as string; if (outcome.status === 'fulfilled') { - listing.push(...outcome.value); + listings.set(accountId, outcome.value); + failedAt.delete(accountId); } else { - failures.push(`${scope[index]}: ${describeError(outcome.reason)}`); + failures.push([accountId, outcome.reason]); } }); - if (failures.length > 0 && listing.length === 0) { - throw new ToolSetLoadError(`No account returned tools. ${failures.join(' | ')}`); + if (listings.size === 0) { + throw allAccountsFailed(failures); } - for (const failure of failures) { - warn(`Skipping account that failed to list tools — ${failure}`); + const failedNow = retryTiming.now(); + for (const [accountId, reason] of failures) { + warn(`Skipping account that failed to list tools — ${accountId}: ${describeError(reason)}`); + failedAt.set(accountId, failedNow); } - if (failures.length === 0) { - store(listing); - } - return listing; + store({ listings, failedAt }); + return inScopeOrder(listings); } /** @@ -725,21 +749,23 @@ export class StackOneToolSet { * * Rate limits: a request answered 429 is retried up to 3 times, after the server's * `Retry-After` (capped at 30s) or a 1s/2s/4s backoff, unless that wait would outlast the - * `timeout`. One still rate limited after that fails the whole call: an account that fails any other way is skipped with a warning, but a 429 - * never yields a partial catalog. + * `timeout`. One still rate limited after that — or that times out while waiting to retry — + * fails the whole call: an account that fails any other way is skipped with a warning, and + * left out for the next {@link FAILED_ACCOUNT_RETRY_MS}, but a 429 never yields a partial + * catalog. * * @throws ToolSetConfigError If no account is configured and none can be discovered. - * @throws StackOneAPIError If the API refuses a listing (e.g. 412 for a dead account), or - * still answers 429 after the retries, on any account. - * @throws ToolSetLoadError If the catalog cannot be loaded. + * @throws StackOneAPIError With status 429 if any account is still rate limited after the + * retries; or with the API's status when every account fails with that same status, so a + * caller can tell a revoked key's 401 from a 429. + * @throws ToolSetLoadError If the catalog cannot be loaded. When every account fails for + * differing reasons, its `cause` is an `AggregateError` of each account's error. */ async fetchTools(options: FetchToolsOptions = {}): Promise { try { const mode = options.mode === undefined ? this.#toolMode : (options.mode ?? undefined); const scope = await this.#resolveAccountScope(options.accountIds); - const listing = - this.#catalogCache.get(this.#cacheKey(scope, mode)) ?? - (await this.#listCatalog(scope, mode)); + const listing = await this.#catalog(scope, mode); let seenFeedbackTool = false; let tools = listing @@ -1026,10 +1052,33 @@ export class StackOneToolSet { } /** - * Two accounts on one provider serve identically named tools, and `getTool()` returns whichever - * was listed first. OpenAI accepts duplicate function names without complaint, so nothing - * downstream surfaces it either — the only symptom would be an action running against an - * account the caller never chose. + * The error for a listing in which every account failed. + * + * When they all failed with one HTTP status, that error is rethrown as it came, so a revoked key + * is a 401 however many accounts it has, as it is with one. Otherwise the summary keeps every + * account's own error as its `cause`. + */ +function allAccountsFailed(failures: readonly [accountId: string, reason: unknown][]): Error { + const reasons = failures.map(([, reason]) => reason); + const [first] = reasons; + if ( + first instanceof StackOneAPIError && + reasons.every( + (reason) => reason instanceof StackOneAPIError && reason.statusCode === first.statusCode, + ) + ) { + return first; + } + return new ToolSetLoadError( + `No account returned tools. ${failures.map(([accountId, reason]) => `${accountId}: ${describeError(reason)}`).join(' | ')}`, + { cause: new AggregateError(reasons, 'Every account failed to list tools') }, + ); +} + +/** + * Two accounts on one provider serve identically named tools. Every lookup and adapter keeps the + * first one listed — the lowest account id — and drops the rest, so warn that the others are + * unreachable by name. */ function warnOnDuplicateNames(tools: readonly StackOneTool[]): void { const counts = new Map(); From 6ab1ab7815338ec30c73d72602c4f36763711235 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:12:35 +0100 Subject: [PATCH 088/151] feat(search): tag each hit with its account_id and apply topK to the merged ranking top_k is per connector on the wire, so topK: 1 over three connectors returned three hits; 2.x capped the whole result, and so does this again. The same action linked on two accounts is two hits, each naming the account that found it. --- src/toolsets.search-execute.test.ts | 45 ++++++++++++++++++++++++++++- src/toolsets.ts | 28 +++++++++++------- src/types.ts | 5 ++++ 3 files changed, 66 insertions(+), 12 deletions(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 04c6e959..aff22e4b 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -129,7 +129,50 @@ describe('search()', () => { session_id: '', })); const [hit] = await newToolSet({ accountId: 'acc1' }).search('x'); - expect(hit).toEqual({ action_id: 'a_x' }); + expect(hit).toEqual({ action_id: 'a_x', account_id: 'acc1' }); + }); + + // Without it, a caller who finds the same action on two accounts cannot choose between them. + it('tags every hit with the account that found it, one hit per account', async () => { + fakeMetaTools(['linear_acc1_search_actions', 'linear_acc2_search_actions'], (tool) => ({ + actions: [ + { + action_id: 'linear_list_issues', + similarity_score: tool.name.includes('acc1') ? 0.5 : 0.9, + account_id: 'spoofed', + }, + ], + })); + + const hits = await newToolSet({ accountIds: ['acc1', 'acc2'] }).search('x'); + + expect(hits).toEqual([ + { action_id: 'linear_list_issues', similarity_score: 0.9, account_id: 'acc2' }, + { action_id: 'linear_list_issues', similarity_score: 0.5, account_id: 'acc1' }, + ]); + }); + + // top_k is per connector on the wire; 2.x's topK capped the whole result, and so does this. + it('cuts the merged ranking to topK, keeping the best across connectors', async () => { + const perConnector: Record = { + a_acc1_search_actions: [ + { action_id: 'a_1', similarity_score: 0.8 }, + { action_id: 'a_2', similarity_score: 0.1 }, + ], + b_acc1_search_actions: [ + { action_id: 'b_1', similarity_score: 0.9 }, + { action_id: 'b_2', similarity_score: 0.2 }, + ], + c_acc1_search_actions: [{ action_id: 'c_1', similarity_score: 0.7 }], + }; + const calls = fakeMetaTools(Object.keys(perConnector), (tool) => ({ + actions: perConnector[tool.name] ?? [], + })); + + const hits = await newToolSet({ accountId: 'acc1' }).search('x', { topK: 2 }); + + expect(hits.map((hit) => hit.action_id)).toEqual(['b_1', 'a_1']); + expect(calls.map((call) => call.args.top_k)).toEqual([2, 2, 2]); }); it('ranks results across connectors rather than concatenating them, tolerating bad scores', async () => { diff --git a/src/toolsets.ts b/src/toolsets.ts index faa44330..b7c50090 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -143,7 +143,7 @@ export interface FetchToolsOptions { * Options for {@link StackOneToolSet.search}. */ export interface SearchOptions { - /** Maximum results per connector, 1–50. Default: 10. */ + /** Maximum results, 1–50, across every connector searched. Default: 10. */ topK?: number; /** * Restrict to these accounts. Defaults to the toolset's accounts, then every active one. @@ -831,9 +831,11 @@ export class StackOneToolSet { * skipped. * * @param query What you want to do, e.g. "list recent comments". - * @returns Actions carrying at least `action_id`, best first, each with the - * `session_id` of the search that found it when the server issued one. Pass it to - * {@link execute} and {@link submitFeedback} to link the calls. + * @returns At most `topK` actions, best first across every connector, each carrying + * `action_id`, the `account_id` of the account whose connector found it, and the + * `session_id` of the search when the server issued one. The same action linked on two + * accounts is two hits. Pass `session_id` to {@link execute} and {@link submitFeedback} to + * link the calls, and `account_id` in `accountIds` to run the action on that account. * @throws ToolSetConfigError If `topK` is not an integer between 1 and 50. * @throws StackOneAPIError With status 429 if a request is still rate limited after retries. * @throws ToolSetLoadError If every connector fails. @@ -863,12 +865,15 @@ export class StackOneToolSet { ); // 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 that produced it. + // still be traced to the search, and the account, that produced it. const sessionId = found.session_id; - if (typeof sessionId !== 'string' || !sessionId) { - return actions; - } - return actions.map((action) => ({ ...action, session_id: sessionId })); + 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 @@ -897,8 +902,9 @@ export class StackOneToolSet { // Concatenating per-connector results would leave them grouped by connector, so results[0] // 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. - return results.sort((left, right) => scoreOf(right) - scoreOf(left)); + // 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); } /** diff --git a/src/types.ts b/src/types.ts index 3a174d9e..0233de8c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -214,6 +214,11 @@ export type SearchResult = JsonObject & { * to `execute()` and `submitFeedback()` to link those calls to this search. */ session_id?: string; + /** + * The account whose connector found this hit. The same action linked on two accounts is two + * hits; pass this in `execute()`'s `accountIds` to run the action on this one. + */ + account_id?: string; }; /** From 3903b07c56a410d6e59eb39e2feded12ef53d469 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:12:35 +0100 Subject: [PATCH 089/151] fix(execute): refuse an action whose connector is linked on more than one account Picking one ran the action on an account the caller never chose. execute() now throws ToolSetConfigError, and passing a search hit's account_id in accountIds routes to it. --- MIGRATION.md | 4 +-- README.md | 3 +- src/toolsets.search-execute.test.ts | 43 +++++++++++++++++++++++++---- src/toolsets.ts | 12 +++++--- 4 files changed, 50 insertions(+), 12 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 09b6827b..26771614 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -86,7 +86,7 @@ const names = await toolset.searchActionNames('time off requests', { topK: 5 }); // 3.0 const toolset = new StackOneToolSet(); -const [hit] = await toolset.search('list employees', { topK: 5 }); // SearchResult[], best first +const [hit] = await toolset.search('list employees', { topK: 5 }); // at most 5, best first if (!hit) throw new Error('No action matched'); const result = await toolset.execute( hit.action_id, @@ -95,7 +95,7 @@ const result = await toolset.execute( ); ``` -`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id`, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `execute()` raises rather than returning `{ error }`: `ToolSetConfigError` before any request when `actionId`, `args` or `sessionId` is malformed, `ToolArgumentsError` when the arguments cannot be encoded as JSON (NaN or Infinity, a `Date`, a circular reference, for example), `ToolSetLoadError` when no linked connector serves the action, and `StackOneAPIError` when the action fails, including when the server rejects the arguments. +`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id` and the `account_id` that found it, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `topK` caps the whole result, as in 2.x, after ranking across every connector; the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` unless `accountIds` picks one, such as `[hit.account_id]`. `execute()` raises rather than returning `{ error }`: `ToolSetConfigError` before any request when `actionId`, `args` or `sessionId` is malformed, `ToolArgumentsError` when the arguments cannot be encoded as JSON (NaN or Infinity, a `Date`, a circular reference, for example), `ToolSetLoadError` when no linked connector serves the action, and `StackOneAPIError` when the action fails, including when the server rejects the arguments. To give a model the search and execute tools, set the tool mode on the toolset. `openai()` no longer takes `mode`. diff --git a/README.md b/README.md index 91a14f03..c6bb84a4 100644 --- a/README.md +++ b/README.md @@ -310,7 +310,8 @@ const result = await toolset.execute(best.action_id, best.example_request, { - The connector is the longest one whose name prefixes the action id, so `browser_linkedin_*` actions are not routed to `browser`. - `action_id` is always the one you pass: an `action_id` inside `args` — for example, one a prompt-injected model put there — is ignored. - Each hit carries the `session_id` of the search that found it, when the server issued one. Pass it back as `sessionId` to link the calls together. -- `topK` is 1–50 (default 10). A connector that fails to search is skipped with a warning, unless every connector fails. +- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. +- `topK` (1–50, default 10) caps the whole result, after ranking across every connector. A connector that fails to search is skipped with a warning, unless every connector fails. [View full example](examples/search-and-execute.ts) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index aff22e4b..9b32bff2 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -397,15 +397,48 @@ describe('execute()', () => { expect(calls[0]?.tool).toBe('browser_linkedin_acc2_execute_action'); }); - it('warns when the same connector is linked twice, and uses the first', async () => { + // Picking one would run the action on an account the caller never chose. + it('refuses to choose when the same connector is linked on two accounts', async () => { const calls = fakeMetaTools(['linear_acc1_execute_action', 'linear_acc2_execute_action']); - await newToolSet({ accountIds: ['acc2', 'acc1'] }).execute('linear_list_issues'); + const error = await newToolSet({ accountIds: ['acc2', 'acc1'] }) + .execute('linear_list_issues') + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolSetConfigError); + expect((error as Error).message).toMatch( + /^"linear_list_issues" matches 2 connectors \(linear_acc1_execute_action, linear_acc2_execute_action\)/, + ); + expect(calls).toEqual([]); + }); - expect(calls[0]?.tool).toBe('linear_acc1_execute_action'); - expect(String(warnSpy.mock.calls[0]?.[0])).toBe( - '[@stackone/ai] "linear_list_issues" matches 2 connectors (linear_acc1_execute_action, linear_acc2_execute_action); using linear_acc1_execute_action. Pass account ids to choose.', + it('routes to the account a search hit names', async () => { + const calls = fakeMetaTools( + [ + 'linear_acc1_search_actions', + 'linear_acc2_search_actions', + 'linear_acc1_execute_action', + 'linear_acc2_execute_action', + ], + (tool): JsonObject => + tool.name.endsWith('_search_actions') + ? { actions: [{ action_id: 'linear_list_issues' }] } + : { data: {} }, + ); + const toolset = newToolSet(); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json([ + { id: 'acc1', provider: 'linear', status: 'active' }, + { id: 'acc2', provider: 'linear', status: 'active' }, + ]), + ), ); + + const hit = (await toolset.search('x')).find((found) => found.account_id === 'acc2'); + await toolset.execute('linear_list_issues', {}, { accountIds: [hit?.account_id as string] }); + + expect(calls.at(-1)?.tool).toBe('linear_acc2_execute_action'); }); it('matches the connector case-insensitively', async () => { diff --git a/src/toolsets.ts b/src/toolsets.ts index b7c50090..78aa67c1 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -187,10 +187,11 @@ export interface SubmitFeedbackOptions { sessionId?: string | null; /** Who produced the feedback. Default: `'model'`. */ source?: FeedbackSource; + /** The action run the feedback is about. Sent as `action_run_id`, only when given. */ + actionRunId?: string; /** - * The feedback is sent through the first of these accounts. Defaults as for - * {@link StackOneToolSet.fetchTools}, in the order given or discovered. `null` is the same as - * leaving it unset. + * The feedback is sent through the lowest of these account ids. Defaults as for + * {@link StackOneToolSet.fetchTools}. `null` is the same as leaving it unset. */ accountIds?: string[] | null; } @@ -925,7 +926,10 @@ export class StackOneToolSet { * @param args The action's arguments. * @param options.sessionId The `session_id` a search hit carries, to link this call to it. * @returns The action's result as the server wrote it: `{ isError: false, result, … }`. - * @throws ToolSetConfigError If the arguments are malformed. + * @param options.accountIds Restrict routing to these accounts. Pass a search hit's + * `account_id` to run the action on the account that found it. + * @throws ToolSetConfigError If the arguments are malformed, or the action's connector is + * linked on more than one account and the call names none. * @throws ToolSetLoadError If no linked connector serves the action. * @throws StackOneAPIError If the action fails. */ From 7a410112631083730ea417489039ebe536c0f624 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:12:35 +0100 Subject: [PATCH 090/151] fix(tools): build every adapter from the first tool of each name toAISDK() kept the last duplicate, toOpenAI() sent both and toClaudeAgentSdk() threw on the second. Every adapter now keeps the one getTool() and executeOpenAIToolCalls() use: the first listed, on the lowest account id. --- src/tool.ts | 23 +++++++++++++++++------ src/toolsets.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/tool.ts b/src/tool.ts index 5179b7c4..a862399f 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -640,6 +640,17 @@ export class Tools implements Iterable { return this.tools.find((tool) => tool.name === name); } + /** + * The first tool of each name, in order: the one {@link getTool} returns. Every adapter is + * built from these, so a model can never call a tool that a lookup by name would not find — + * an AI SDK record would keep the last, OpenAI would get two functions of one name, and the + * Claude Agent SDK refuses the second outright. + */ + #uniqueTools(): BaseTool[] { + const seen = new Set(); + return this.tools.filter((tool) => !seen.has(tool.name) && seen.add(tool.name)); + } + /** * Get a StackOne tool by name */ @@ -670,7 +681,7 @@ export class Tools implements Iterable { * Returns an array of objects with name, description, and schema */ toJsonSchema(): Array<{ name: string; description: string; parameters: JSONSchema }> { - return this.tools.map((tool) => ({ + return this.#uniqueTools().map((tool) => ({ name: tool.name, description: tool.description, parameters: tool.toJsonSchema(), @@ -681,7 +692,7 @@ export class Tools implements Iterable { * Convert all tools to OpenAI Chat Completions API format */ toOpenAI(): ChatCompletionFunctionTool[] { - return this.tools.map((tool) => tool.toOpenAI()); + return this.#uniqueTools().map((tool) => tool.toOpenAI()); } /** @@ -737,7 +748,7 @@ export class Tools implements Iterable { * @see https://docs.anthropic.com/en/docs/build-with-claude/tool-use */ toAnthropic(): AnthropicTool[] { - return this.tools.map((tool) => tool.toAnthropic()); + return this.#uniqueTools().map((tool) => tool.toAnthropic()); } /** @@ -745,7 +756,7 @@ export class Tools implements Iterable { * @see https://platform.openai.com/docs/api-reference/responses */ toOpenAIResponses(options: { strict?: boolean } = {}): OpenAIResponsesFunctionTool[] { - return this.tools.map((tool) => tool.toOpenAIResponses(options)); + return this.#uniqueTools().map((tool) => tool.toOpenAIResponses(options)); } /** @@ -757,7 +768,7 @@ export class Tools implements Iterable { }, ): Promise { const result: AISDKToolResult = {}; - for (const tool of this.tools) { + for (const tool of this.#uniqueTools()) { Object.assign(result, await tool.toAISDK(options)); } return result; @@ -801,7 +812,7 @@ export class Tools implements Iterable { // We use type assertions here because the Zod types from our dynamic import // don't perfectly match the Claude Agent SDK's expected types at compile time const sdkTools = await Promise.all( - this.tools.map(async (baseTool) => { + 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( diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 097c5f06..beda6090 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -854,6 +854,29 @@ describe('duplicate tool names', () => { expect(tools.getTool('hibob_list_employees')).toBe(tools.toArray()[0]); }); + // Every adapter keeps the tool getTool() returns. Left alone, the AI SDK record kept the last, + // OpenAI got two functions of one name, and the Claude Agent SDK refused the second. + it('builds every adapter from the first listed duplicate only', async () => { + fakeListing((request) => [ + { name: 'hibob_list_employees', description: `on ${accountOf(request)}`, inputSchema: {} }, + def(`only_${accountOf(request)}`), + ]); + + const tools = await newToolSet().fetchTools({ accountIds: ['b', 'a'] }); + + const expected = ['hibob_list_employees', 'only_a', 'only_b']; + expect(tools.toOpenAI().map((tool) => tool.function.name)).toEqual(expected); + expect(tools.toOpenAI()[0]?.function.description).toBe('on a'); + expect(tools.toAnthropic().map((tool) => tool.name)).toEqual(expected); + expect(tools.toOpenAIResponses().map((tool) => tool.name)).toEqual(expected); + expect(tools.toJsonSchema().map((tool) => tool.name)).toEqual(expected); + const aiSdk = await tools.toAISDK(); + expect(Object.keys(aiSdk)).toEqual(expected); + expect(aiSdk.hibob_list_employees?.description).toBe('on a'); + await expect(tools.toClaudeAgentSdk()).resolves.toBeDefined(); + expect(warnSpy).toHaveBeenCalledOnce(); + }); + it('stays quiet when names are unique', async () => { await newToolSet().fetchTools({ accountIds: ['acc1', 'acc2'] }); expect(warnSpy).not.toHaveBeenCalled(); From bde595a7550e01f1680db894ff24a5c1f1b21959 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:12:35 +0100 Subject: [PATCH 091/151] feat(feedback): add actionRunId, and send feedback on the lowest account id actionRunId is sent as action_run_id only when given. The account is now the lowest id in scope rather than the first GET /accounts lists, so it does not depend on server order. --- MIGRATION.md | 4 +-- README.md | 3 ++- src/toolsets.search-execute.test.ts | 19 ++++++++++++--- src/toolsets.ts | 38 ++++++++++++++++++++--------- 4 files changed, 45 insertions(+), 19 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 26771614..46ab01b0 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -207,9 +207,9 @@ const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID **An empty account id throws.** `accountId: ''`, or an empty string in `accountIds`, `execute.accountIds`, `setAccounts()` or a call's `accountIds`, now throws `ToolSetConfigError`. In 2.x an empty `accountId` fell back to `STACKONE_ACCOUNT_ID` or discovery; in 3.0 that would silently widen the toolset to every active account. So `accountId: process.env.STACKONE_ACCOUNT_ID` throws when the variable is set but empty (`STACKONE_ACCOUNT_ID=` in a `.env` file, for example): pass `process.env.STACKONE_ACCOUNT_ID || undefined`, as above. -**Listings are merged in sorted account order.** When two accounts serve the same tool name, `getTool()` returns the first one listed — now the one on the lowest account id, where 2.x followed the order you passed. A warning names the clashing tools. Pass `accountIds` to choose the account yourself. +**Listings are merged in sorted account order.** When two accounts serve the same tool name, `getTool()` returns the first one listed — now the one on the lowest account id, where 2.x followed the order you passed — and so do `executeOpenAIToolCalls()` and every adapter (`toOpenAI()`, `toAISDK()`, `toClaudeAgentSdk()` and the rest), which build one tool per name. A warning names the clashing tools. Pass `accountIds` to choose the account yourself. -**`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. An account whose listing fails is skipped with a warning, unless every account fails. +**`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. An account whose listing fails is skipped with a warning, and left out of the cached catalog for 30 seconds, unless every account fails: then the accounts' shared `StackOneAPIError` is thrown when they all failed with one status, and otherwise a `ToolSetLoadError` with each account's error as its `cause`. ## Feedback diff --git a/README.md b/README.md index c6bb84a4..0da0991a 100644 --- a/README.md +++ b/README.md @@ -326,10 +326,11 @@ await toolset.submitFeedback({ feedback: 'Needed two calls to find the right action', category: 'search', // optional sessionId: best.session_id, // optional: links the feedback to that search + actionRunId: 'run_123', // optional: the action run the feedback is about }); ``` -`submitFeedback()` makes exactly one call, on the first account: the first of its `accountIds` when given, otherwise the first the toolset is configured with or discovers. The SDK never builds a feedback tool itself: if the server does not serve it, `submitFeedback()` throws a `ToolSetLoadError` saying feedback is not enabled for the project. +`submitFeedback()` makes exactly one call, on the account with the lowest id among its `accountIds` when given, otherwise among those the toolset is configured with or discovers. The SDK never builds a feedback tool itself: if the server does not serve it, `submitFeedback()` throws a `ToolSetLoadError` saying feedback is not enabled for the project. ### Tool modes diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 9b32bff2..a13d6eb4 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -561,7 +561,7 @@ describe('submitFeedback()', () => { }); // The tool is global, so one call per account would record the same verdict once per account. - it('lists search_execute and calls once, on the first of the given accounts', async () => { + it('lists search_execute and calls once, on the lowest of the given accounts', async () => { const { calls } = serveMock({ accountTools: { acc1: [], acc2: [] }, submitFeedback: true, @@ -577,11 +577,11 @@ describe('submitFeedback()', () => { `${TEST_BASE_URL}/mcp?tool-mode=search_execute`, ]); expect(calls.map((call) => [call.name, call.accountId, call.toolMode])).toEqual([ - ['stackone_submit_feedback', 'acc2', 'search_execute'], + ['stackone_submit_feedback', 'acc1', 'search_execute'], ]); }); - it('calls on the first account GET /accounts lists, not the first by id', async () => { + it('calls on the lowest account id, not the first GET /accounts lists', async () => { const { calls } = serveMock({ accountTools: { zeta: [], alpha: [] }, submitFeedback: true, @@ -599,10 +599,21 @@ describe('submitFeedback()', () => { await newToolSet().submitFeedback({ rating: 'positive', toolNames: ['x'] }); expect(calls.map((call) => [call.name, call.accountId])).toEqual([ - ['stackone_submit_feedback', 'zeta'], + ['stackone_submit_feedback', 'alpha'], ]); }); + it('sends actionRunId as action_run_id, only when given', async () => { + const { calls } = serveMock({ submitFeedback: true }); + const toolset = newToolSet({ accountId: 'acc1' }); + + await toolset.submitFeedback({ rating: 'positive', toolNames: ['a'], actionRunId: 'run-1' }); + await toolset.submitFeedback({ rating: 'positive', toolNames: ['a'] }); + + expect(calls.map((call) => call.arguments.action_run_id)).toEqual(['run-1', undefined]); + expect(Object.keys(calls[1]?.arguments ?? {})).not.toContain('action_run_id'); + }); + it('explains that feedback is not enabled when the server does not serve the tool', async () => { serveMock({ submitFeedback: false }); const error = await newToolSet({ accountId: 'acc1' }) diff --git a/src/toolsets.ts b/src/toolsets.ts index 78aa67c1..c08384e4 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -970,10 +970,10 @@ export class StackOneToolSet { const finalists = matches.filter((tool) => connectorOf(tool, suffix).length === longest); const [tool] = finalists as [StackOneTool, ...StackOneTool[]]; if (finalists.length > 1) { - // The same provider linked twice. Picking one silently would run the action against an - // account the caller never chose. - warn( - `${JSON.stringify(actionId)} matches ${finalists.length} connectors (${finalists.map((t) => t.name).join(', ')}); using ${tool.name}. Pass account ids to choose.`, + // The same provider linked twice, which discovery makes common. Picking one would run the + // action against an account the caller never chose — another end user's, possibly. + throw new ToolSetConfigError( + `${JSON.stringify(actionId)} matches ${finalists.length} connectors (${finalists.map((t) => t.name).join(', ')}). Pass account ids to choose — a search hit's account_id names its account.`, ); } @@ -1001,8 +1001,8 @@ export class StackOneToolSet { * feedback is enabled for the project, and a client-side stand-in would report success for * feedback that went nowhere. Unset optional fields are omitted, never sent as null. * - * Makes exactly one `tools/call`, on the first account: the first of `accountIds` when given, - * otherwise the toolset's first, otherwise the first active account `GET /accounts` lists. + * Makes exactly one `tools/call`, on the account with the lowest id among those the call is + * scoped to: `accountIds` when given, otherwise the toolset's, otherwise every active one. * * @example * ```typescript @@ -1021,7 +1021,15 @@ export class StackOneToolSet { * @throws ToolSetLoadError If feedback is not enabled for this project. */ async submitFeedback(options: SubmitFeedbackOptions): Promise { - const { rating, toolNames, feedback, category, sessionId, source = 'model' } = options; + const { + rating, + toolNames, + feedback, + category, + sessionId, + actionRunId, + source = 'model', + } = options; if (typeof (toolNames as unknown) === 'string') { throw new ToolSetConfigError( `toolNames must be a list of tool names, not a string. Did you mean [${JSON.stringify(toolNames)}]?`, @@ -1037,10 +1045,10 @@ export class StackOneToolSet { } // 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 first account, in the - // order given, is the one a caller can predict. search_execute lists two meta tools per - // connector where individual mode lists every action. - const accountIds = (await this.#accountsInOrder(options.accountIds)).slice(0, 1); + // feedback, and calling each would record it once per account. The lowest id is the one a + // caller can predict, whatever order GET /accounts lists them in. search_execute lists two + // meta tools per connector where individual mode lists every action. + const accountIds = (await this.#resolveAccountScope(options.accountIds)).slice(0, 1); const tool = (await this.fetchTools({ accountIds, mode: 'search_execute' })).getTool( SUBMIT_FEEDBACK_TOOL_NAME, ); @@ -1051,7 +1059,13 @@ export class StackOneToolSet { } const args: JsonObject = { rating, tool_names: [...toolNames] }; - const optional = { feedback, category, session_id: sessionId, source }; + const optional = { + 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; From c6625b012e9396972b041c54cb54f0f4d8b9abea Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:12:53 +0100 Subject: [PATCH 092/151] test(mcp-client): pin image, audio and resource parts as plain JSON under content_parts --- src/mcp-client.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/mcp-client.test.ts b/src/mcp-client.test.ts index 6508b562..50750061 100644 --- a/src/mcp-client.test.ts +++ b/src/mcp-client.test.ts @@ -170,6 +170,26 @@ describe('parseToolResult', () => { }); }); + // The shape both SDKs share: every non-text part exactly as served, in order, under + // content_parts — not decoded, not described. + it('keeps image, audio and resource parts as plain JSON, in order', () => { + const image = { type: 'image', data: 'AAAA', mimeType: 'image/png' }; + const audio = { type: 'audio', data: 'BBBB', mimeType: 'audio/wav' }; + const resource = { + type: 'resource', + resource: { uri: 'file:///report.pdf', mimeType: 'application/pdf', blob: 'CCCC' }, + }; + const link = { type: 'resource_link', uri: 'file:///a.txt', name: 'a.txt' }; + + const parsed = parseToolResult( + { content: [image, { type: 'text', text: '{"a":1}' }, audio, resource, link] }, + 't', + ); + + expect(parsed).toStrictEqual({ a: 1, content_parts: [image, audio, resource, link] }); + expect(JSON.parse(JSON.stringify(parsed))).toStrictEqual(parsed); + }); + describe('the server’s success wrapper', () => { const served = (structuredContent: Record) => ({ content: [{ type: 'text', text: JSON.stringify(structuredContent) }], From 53052d559342dba40a3785df13c9cba243c3044c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:14:28 +0100 Subject: [PATCH 093/151] ci: run the full conformance suite against the Python SDK too The conformance job checks out StackOneHQ/stackone-ai-python at PYTHON_SDK_REF and runs both SDKs, so a drift between them fails here. --- .github/workflows/ci.yaml | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b747ac74..7741d5b3 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -137,10 +137,15 @@ jobs: echo "can-skip=false" >> "$GITHUB_OUTPUT" fi + # Runs the full suite, both SDKs side by side, so a change here that the Python SDK does not + # match fails here rather than drifting. conformance: needs: check-secret if: needs.check-secret.outputs.can-skip != 'true' runs-on: ubuntu-latest + env: + # Switch to main once StackOneHQ/stackone-ai-python#210 merges. + PYTHON_SDK_REF: fix/mcp-submit-feedback steps: - name: Check conformance token is configured env: @@ -165,6 +170,15 @@ jobs: path: sdk-conformance persist-credentials: false + # Public, so no token. + - name: Checkout Python SDK + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + repository: StackOneHQ/stackone-ai-python + ref: ${{ env.PYTHON_SDK_REF }} + path: stackone-ai-python + persist-credentials: false + # tests/vectors is a copy of the suite's vectors/ (scripts/sync-vectors.sh), which the unit # tests run. An edit to the copy, or a pin moved without a re-copy, fails here. - name: Vendored vectors match the pinned sdk-conformance @@ -192,6 +206,15 @@ jobs: working-directory: sdk run: pnpm run build + - name: Setup uv + uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 + with: + python-version: "3.13" + + - name: Install Python SDK dependencies + working-directory: stackone-ai-python + run: uv sync --all-extras --locked + - name: Install conformance dependencies working-directory: sdk-conformance run: pnpm install --frozen-lockfile @@ -200,7 +223,8 @@ jobs: working-directory: sdk-conformance env: NODE_SDK_DIST: ${{ github.workspace }}/sdk/dist/index.mjs - run: pnpm test:node -- --strict-schema + PYTHON_SDK_DIR: ${{ github.workspace }}/stackone-ai-python + run: pnpm test -- --strict-schema # Make this the one required status check. Individually required checks go # missing when a job is renamed or a matrix entry is added, and nothing notices. From 35b475a1f2b18da652aef8185b0838dc72fb1ace Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:40:24 +0100 Subject: [PATCH 094/151] test: clear STACKONE_ACCOUNT_ID for the test run Set in a developer's shell, it would make every toolset built without an account warn. --- vitest.setup.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/vitest.setup.ts b/vitest.setup.ts index d042b3e9..660789ea 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -1,5 +1,9 @@ import { server } from './mocks/node'; +// A STACKONE_ACCOUNT_ID in the developer's shell would make every toolset built without an +// account warn. Tests that need it stub it themselves. +delete process.env.STACKONE_ACCOUNT_ID; + beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); From dd09e38924e48501d6961d15e9ee58c24f1ba343 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:40:24 +0100 Subject: [PATCH 095/151] fix: adopt the review-round messages from sdk-conformance ec4dcfb Syncs the shared vectors and adopts account-id-env-ignored, ambiguous-connector (now an error naming each tool's account), duplicate-tool-names and all-accounts-failed, which replaces no-account-returned-tools. duplicate-tool-names is now also warned by each adapter that drops a duplicate, as the contract asks. --- src/tool.ts | 25 +++++++++++++ src/toolsets.search-execute.test.ts | 4 +- src/toolsets.test.ts | 10 +++-- src/toolsets.ts | 29 ++------------- src/vectors.test.ts | 23 +++++++++--- tests/vectors/messages.json | 57 ++++++++++++++++++----------- 6 files changed, 91 insertions(+), 57 deletions(-) diff --git a/src/tool.ts b/src/tool.ts index a862399f..6596d271 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -9,6 +9,7 @@ import type { import type { FunctionTool as OpenAIResponsesFunctionTool } from 'openai/resources/responses/responses'; import type { OverrideProperties } from 'type-fest'; import { peerDependencies } from '../package.json'; +import { SUBMIT_FEEDBACK_TOOL_NAME } from './consts'; import { type DeclaredHeaders, buildRequestHeaders, @@ -32,6 +33,7 @@ import type { 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 { serializeToolResult } from './utils/serialize'; import { tryImport } from './utils/try-import'; @@ -647,6 +649,7 @@ export class Tools implements Iterable { * Claude Agent SDK refuses the second outright. */ #uniqueTools(): BaseTool[] { + warnOnDuplicateNames(this.tools); const seen = new Set(); return this.tools.filter((tool) => !seen.has(tool.name) && seen.add(tool.name)); } @@ -877,3 +880,25 @@ export class Tools implements Iterable { this.tools.forEach(callback); } } + +/** + * Two accounts on one provider serve identically named tools. Every lookup and adapter keeps the + * first one listed — the lowest account id — and drops the rest, so warn that the others are + * unreachable by name: once when the tools are fetched, and again from each adapter that drops + * them. + */ +export function warnOnDuplicateNames(tools: readonly BaseTool[]): void { + const counts = new Map(); + 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(); + 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 a13d6eb4..d7ef74b7 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -407,7 +407,9 @@ describe('execute()', () => { expect(error).toBeInstanceOf(ToolSetConfigError); expect((error as Error).message).toMatch( - /^"linear_list_issues" matches 2 connectors \(linear_acc1_execute_action, linear_acc2_execute_action\)/, + 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', + ), ); expect(calls).toEqual([]); }); diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index beda6090..89872e27 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -95,7 +95,7 @@ describe('configuration', () => { newToolSet(); expect(warnSpy.mock.calls.map(([message]: unknown[]) => String(message))).toEqual([ - '[@stackone/ai] STACKONE_ACCOUNT_ID is set but ignored: with no account passed, the toolset uses every active account linked to the API key. Pass accountId (or accountIds) to choose.', + '[@stackone/ai] STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.', ]); }); @@ -535,7 +535,7 @@ describe('listing', () => { .catch((caught: unknown) => caught); expect(error).toBeInstanceOf(ToolSetLoadError); - expect((error as Error).message).toBe('No account returned tools. a: boom for a | b: gone'); + 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]); }); @@ -836,7 +836,7 @@ describe('duplicate tool names', () => { expect(tools.length).toBe(4); expect((tools.getTool('hibob_list_employees') as StackOneTool).getAccountId()).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). Looking a tool up by name returns the first one listed — pass account ids to choose.', + '[@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.', ); }); @@ -874,7 +874,9 @@ describe('duplicate tool names', () => { expect(Object.keys(aiSdk)).toEqual(expected); expect(aiSdk.hibob_list_employees?.description).toBe('on a'); await expect(tools.toClaudeAgentSdk()).resolves.toBeDefined(); - expect(warnSpy).toHaveBeenCalledOnce(); + // Once from fetchTools(), then once from each adapter call that dropped a duplicate. + expect(warnSpy).toHaveBeenCalledTimes(8); + expect(new Set(warnSpy.mock.calls.map(([message]: unknown[]) => message)).size).toBe(1); }); it('stays quiet when names are unique', async () => { diff --git a/src/toolsets.ts b/src/toolsets.ts index c08384e4..3833f74a 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -10,7 +10,7 @@ import { import { buildRequestHeaders, isSdkOwnedHeader } from './headers'; import { type McpToolDefinition, isRateLimitFailure, listMcpTools } from './mcp-client'; import { cloneJson, toolParametersFromInputSchema } from './schema'; -import { StackOneMcpTool, type StackOneTool, Tools } from './tool'; +import { StackOneMcpTool, type StackOneTool, Tools, warnOnDuplicateNames } from './tool'; import type { ActionResult, FeedbackCategory, @@ -408,7 +408,7 @@ export class StackOneToolSet { config.execute?.accountIds == null ) { warn( - 'STACKONE_ACCOUNT_ID is set but ignored: with no account passed, the toolset uses every active account linked to the API key. Pass accountId (or accountIds) to choose.', + 'STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.', ); } } @@ -973,7 +973,7 @@ export class StackOneToolSet { // The same provider linked twice, which discovery makes common. Picking one would run the // action against an account the caller never chose — another end user's, possibly. throw new ToolSetConfigError( - `${JSON.stringify(actionId)} matches ${finalists.length} connectors (${finalists.map((t) => t.name).join(', ')}). Pass account ids to choose — a search hit's account_id names its account.`, + `${JSON.stringify(actionId)} matches ${finalists.length} connectors on different accounts (${finalists.map((t) => `${t.name} on ${t.getAccountId()}`).join(', ')}). Pass the account id to use, such as a search hit's account_id.`, ); } @@ -1094,28 +1094,7 @@ function allAccountsFailed(failures: readonly [accountId: string, reason: unknow return first; } return new ToolSetLoadError( - `No account returned tools. ${failures.map(([accountId, reason]) => `${accountId}: ${describeError(reason)}`).join(' | ')}`, + `Every account failed to list tools: ${failures.map(([accountId, reason]) => `${accountId}: ${describeError(reason)}`).join('; ')}`, { cause: new AggregateError(reasons, 'Every account failed to list tools') }, ); } - -/** - * Two accounts on one provider serve identically named tools. Every lookup and adapter keeps the - * first one listed — the lowest account id — and drops the rest, so warn that the others are - * unreachable by name. - */ -function warnOnDuplicateNames(tools: readonly StackOneTool[]): void { - const counts = new Map(); - 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(); - if (clashing.length > 0) { - warn( - `${clashing.length} tool name(s) are served by more than one account (${clashing.slice(0, 5).join(', ')}). Looking a tool up by name returns the first one listed — pass account ids to choose.`, - ); - } -} diff --git a/src/vectors.test.ts b/src/vectors.test.ts index 8e3d53c0..5c26a113 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -580,17 +580,28 @@ const emitters: Record< 'ambiguous-connector': async () => { listByAccount(['linear_acc1_execute_action', 'linear_acc2_execute_action']); respondToCalls(() => ({ data: {} })); - await newToolSet({ accountIds: ['acc1', 'acc2'] }).execute('linear_list_issues'); return { - emitted: { warnings: warnings() }, + emitted: { + error: await errorOf(() => + newToolSet({ accountIds: ['acc2', 'acc1'] }).execute('linear_list_issues'), + ), + }, values: { action_id: 'linear_list_issues', count: 2, - tools: 'linear_acc1_execute_action, linear_acc2_execute_action', - tool: 'linear_acc1_execute_action', + tools: 'linear_acc1_execute_action on acc1, linear_acc2_execute_action on acc2', }, }; }, + 'account-id-env-ignored': async () => { + vi.stubEnv('STACKONE_ACCOUNT_ID', 'acc-1'); + try { + newToolSet(); + return { emitted: { warnings: warnings() }, values: {} }; + } finally { + vi.unstubAllEnvs(); + } + }, 'mcp-timeout': async () => { const endpoint = `${TEST_BASE_URL}/mcp`; return { @@ -691,7 +702,7 @@ const emitters: Record< values: { count: 1, accounts: 'hibob (error)' }, }; }, - 'no-account-returned-tools': async () => { + 'all-accounts-failed': async () => { listMock.mockImplementation(async ({ headers }) => { throw new Error(`down ${headers['x-account-id']}`); }); @@ -699,7 +710,7 @@ const emitters: Record< emitted: { error: await errorOf(() => newToolSet().fetchTools({ accountIds: ['acc-1', 'acc-2'] })), }, - values: { failures: 'acc-1: down acc-1 | acc-2: down acc-2' }, + values: { failures: 'acc-1: down acc-1; acc-2: down acc-2' }, }; }, 'no-connector-returned-results': async () => { diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index d1921d89..eed6839c 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -135,6 +135,19 @@ }, "notes": "When the next wait would not finish before the call's deadline, the SDK ends the call with the 429 it already has instead of sleeping, and warns this in place of rate-limit-retry." }, + { + "id": "account-id-env-ignored", + "kind": "warning", + "template": "STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.", + "placeholders": {}, + "python": "", + "node": "", + "matches": { + "python": false, + "node": false + }, + "notes": "Emitted once, when the toolset is constructed, if the STACKONE_ACCOUNT_ID environment variable is set and non-empty and neither an account id nor account ids were passed. Neither SDK emits it today." + }, { "id": "skip-account", "kind": "warning", @@ -181,7 +194,7 @@ { "id": "duplicate-tool-names", "kind": "warning", - "template": "{count} tool name(s) are served by more than one account ({names}). Looking a tool up by name returns the first one listed — pass account ids to choose.", + "template": "{count} tool name(s) are served by more than one account ({names}). The first one listed, from the lowest account id, is used — pass account ids to choose.", "placeholders": { "count": { "format": "integer", @@ -195,15 +208,19 @@ "python": "{count} tool name(s) are served by more than one account ({names}). Looking a tool up by name returns the first one listed — pass account ids to choose.", "node": "{count} tool name(s) are served by more than one account ({names}). Looking a tool up by name returns the first one listed — pass account ids to choose.", "matches": { - "python": true, - "node": true + "python": false, + "node": false }, - "notes": "Language-neutral wording: neither SDK's method or parameter names." + "notes": "Language-neutral wording: neither SDK's method or parameter names. Emitted once when a fetched collection holds a clashing name, and again by every adapter that keeps the first tool per name and drops the rest: OpenAI, LangChain, Pydantic AI, AI SDK and Claude Agent SDK. Listing order is ascending account id, so the first is the lowest account id's." }, { "id": "ambiguous-connector", - "kind": "warning", - "template": "{action_id} matches {count} connectors ({tools}); using {tool}. Pass account ids to choose.", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "{action_id} matches {count} connectors on different accounts ({tools}). Pass the account id to use, such as a search hit's account_id.", "placeholders": { "action_id": { "format": "json", @@ -211,23 +228,20 @@ }, "count": { "format": "integer", - "description": "how many connectors match" + "description": "how many connectors match: the longest connector prefix, linked on more than one account" }, "tools": { "format": "text", - "description": "the matching *_execute_action tools, joined by \", \"" - }, - "tool": { - "format": "text", - "description": "the one used" + "description": "each matching *_execute_action tool as \"{tool} on {account_id}\", in ascending account-id order, joined by \", \"" } }, "python": "{action_id} matches {count} connectors ({tools}); using {tool}. Pass account ids to choose.", "node": "{action_id} matches {count} connectors ({tools}); using {tool}. Pass account ids to choose.", "matches": { - "python": true, - "node": true - } + "python": false, + "node": false + }, + "notes": "Raised by execute() when the action's connector is linked on more than one account in scope — no account id passed, or several; nothing is called. Was a warning that ran the first match; today's text names the one used as {tool}." }, { "id": "mcp-timeout", @@ -468,25 +482,26 @@ "notes": "A missing provider or status is written None by Python and undefined by Node; neither is canonical yet." }, { - "id": "no-account-returned-tools", + "id": "all-accounts-failed", "kind": "error", "error": { "python": "ToolsetLoadError", "node": "ToolSetLoadError" }, - "template": "No account returned tools. {failures}", + "template": "Every account failed to list tools: {failures}", "placeholders": { "failures": { "format": "text", - "description": "each as \"{account_id}: {error}\", joined by \" | \"" + "description": "each failed account as \"{account_id}: {error}\", where {error} is the failure's own message (as in skip-account), in ascending account-id order, joined by \"; \" — e.g. \"acc-1: ; acc-2: \"" } }, "python": "No account returned tools. {failures}", "node": "No account returned tools. {failures}", "matches": { - "python": true, - "node": true - } + "python": false, + "node": false + }, + "notes": "Only when every account in scope failed to list, and only when the failures do not all share one HTTP status: if they do, the SDK rethrows the StackOneAPIError itself (e.g. two accounts both answering 401 raise StackOneAPIError 401). The failures are the error's cause: Python raises it `from ExceptionGroup(...)` of them, Node passes `{ cause: new AggregateError(...) }`. An account that listed zero tools has not failed. Today both SDKs join the failures with \" | \", and also raise when some accounts failed and the rest listed zero tools. Replaces no-account-returned-tools." }, { "id": "no-connector-returned-results", From 897bb9c2d7f67fcc03a18b4fc3352f372fbc2a1c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:40:24 +0100 Subject: [PATCH 096/151] ci: pin sdk-conformance to ec4dcfb --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 7741d5b3..4881b089 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -165,7 +165,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: ee0bb06e6d52b1cc41bf173fd2fd236ff387cb60 + ref: ec4dcfb10a0eba0ac45def08ccc9cb73f2d433de token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 9addab520f9868de5b60e22dd44a2ae6302c098d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 15:50:13 +0100 Subject: [PATCH 097/151] style: format the conformance job and a listing test --- .github/workflows/ci.yaml | 2 +- src/toolsets.test.ts | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 4881b089..d31375ea 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -209,7 +209,7 @@ jobs: - name: Setup uv uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0 with: - python-version: "3.13" + python-version: '3.13' - name: Install Python SDK dependencies working-directory: stackone-ai-python diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 89872e27..d15ca043 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -535,7 +535,9 @@ describe('listing', () => { .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).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]); }); From 280df89db54a4e73d7fb362e0211f7b8945bdd6f Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 16:04:10 +0100 Subject: [PATCH 098/151] test(vectors): grade the 429-timeout messages --- src/vectors.test.ts | 41 ++++++++++++++++++++++++++++- tests/vectors/messages.json | 52 +++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/src/vectors.test.ts b/src/vectors.test.ts index 5c26a113..eb67d900 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -6,14 +6,16 @@ import { readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; -import { http, HttpResponse } from 'msw'; +import { delay, http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; +import { accountMcpTools, createMcpApp } from '../mocks/mcp-server'; import { server } from '../mocks/node'; 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 { fetchWithRetry, rateLimitDelayMs, retryAfterMs, waitsForRetry } from './utils/fetch-retry'; vi.mock('./mcp-client', async (importOriginal) => { @@ -615,6 +617,43 @@ const emitters: Record< values: { endpoint, timeout: 1.5 }, }; }, + 'mcp-rate-limit-timeout': async () => { + const endpoint = `${TEST_BASE_URL}/mcp`; + const timeout = 300; + let requests = 0; + const app = createMcpApp({ accountTools: accountMcpTools }); + server.use( + http.all(endpoint, async ({ request }) => { + if (requests++ === 0) { + return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); + } + await delay('infinite'); + return app.fetch(request); + }), + ); + const error = await errorOf(() => + realListMcpTools({ endpoint, headers: { 'x-account-id': 'acc-1' }, timeout }), + ); + expect((error as StackOneAPIError).statusCode).toBe(429); + return { emitted: { error }, values: { endpoint, timeout: timeout / 1_000 } }; + }, + 'accounts-rate-limit-timeout': async () => { + const url = `${TEST_BASE_URL}/accounts`; + const timeout = 300; + let requests = 0; + server.use( + http.get(url, async () => { + if (requests++ === 0) { + return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); + } + await delay('infinite'); + return HttpResponse.json([]); + }), + ); + const error = await errorOf(() => newToolSet({ timeout }).fetchAccounts()); + expect((error as StackOneAPIError).statusCode).toBe(429); + return { emitted: { error }, values: { url, timeout: timeout / 1_000 } }; + }, 'mcp-http-failure': async () => { const endpoint = `${TEST_BASE_URL}/mcp`; server.use( diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index eed6839c..9f423004 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -269,6 +269,58 @@ }, "notes": "Seconds, written as a number: 1s, 0.5s, 60s." }, + { + "id": "mcp-rate-limit-timeout", + "kind": "error", + "error": { + "python": "StackOneAPIError", + "node": "StackOneAPIError" + }, + "template": "MCP request to {endpoint} was rate limited (429) and timed out after {timeout}s while retrying", + "placeholders": { + "endpoint": { + "format": "text", + "description": "the MCP endpoint URL, with its ?tool-mode query when it has one" + }, + "timeout": { + "format": "seconds", + "description": "the toolset's timeout" + } + }, + "python": "MCP request to {endpoint} was rate limited (429) and timed out after {timeout}s while retrying", + "node": "MCP request to {endpoint} was rate limited (429) and timed out after {timeout}s while retrying", + "matches": { + "python": true, + "node": true + }, + "notes": "Raised in place of mcp-timeout when the request that timed out was retrying a 429. Its status is 429, so a multi-account call fails with it rather than skipping the account (invariant 14)." + }, + { + "id": "accounts-rate-limit-timeout", + "kind": "error", + "error": { + "python": "StackOneAPIError", + "node": "StackOneAPIError" + }, + "template": "Listing accounts at {url} was rate limited (429) and timed out after {timeout}s while retrying", + "placeholders": { + "url": { + "format": "text", + "description": "the /accounts URL" + }, + "timeout": { + "format": "seconds", + "description": "the toolset's timeout" + } + }, + "python": "Listing accounts at {url} was rate limited (429) and timed out after {timeout}s while retrying", + "node": "Listing accounts at {url} was rate limited (429) and timed out after {timeout}s while retrying", + "matches": { + "python": true, + "node": true + }, + "notes": "GET /accounts' counterpart of mcp-rate-limit-timeout; status 429." + }, { "id": "mcp-http-failure", "kind": "error", From 16eb6971593db03c9327f0a3814d4a09df952438 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 16:04:17 +0100 Subject: [PATCH 099/151] ci: pin sdk-conformance to db6b908 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index d31375ea..f7fd3c4e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -165,7 +165,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: ec4dcfb10a0eba0ac45def08ccc9cb73f2d433de + ref: db6b90851b6807fca21f89cd1e9a1da402a4fbbb token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 7bcab06ad8d546e30fd6bdf2990db6f8fb6428dd Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 16:37:13 +0100 Subject: [PATCH 100/151] fix(types): make SearchResult.account_id required search() always sets account_id on every hit, from the account whose connector found it. --- src/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/types.ts b/src/types.ts index 0233de8c..7ef5aa8c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -218,7 +218,7 @@ export type SearchResult = JsonObject & { * The account whose connector found this hit. The same action linked on two accounts is two * hits; pass this in `execute()`'s `accountIds` to run the action on this one. */ - account_id?: string; + account_id: string; }; /** From 901f680b6c8d970d62ed55685bad044e63e754a1 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 16:37:23 +0100 Subject: [PATCH 101/151] ci: pin the Python SDK checkout to a commit SHA Pin rather than track the branch while stackone-ai-python#210 is open, so the ref only moves when we bump it deliberately. Switch to a main commit once it merges. --- .github/workflows/ci.yaml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index f7fd3c4e..a1500faa 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -144,8 +144,10 @@ jobs: if: needs.check-secret.outputs.can-skip != 'true' runs-on: ubuntu-latest env: - # Switch to main once StackOneHQ/stackone-ai-python#210 merges. - PYTHON_SDK_REF: fix/mcp-submit-feedback + # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is + # open, so this only moves when we bump it deliberately. Switch to a main commit once it + # merges. + PYTHON_SDK_REF: 54322a3ad5f5bba322cf13d94d2726976e6aaba2 steps: - name: Check conformance token is configured env: From 92dd6808d727721179607338ab6b7ad27e409861 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 16:37:42 +0100 Subject: [PATCH 102/151] docs: qualify account scope failure modes and pin accountIds in search examples Spell out that in a multi-account scope, a non-429 account failure is skipped (healthy accounts cached, the failed one retried after 30s), a 429 that outlasts its retries rejects the whole call, and a single-account call just throws. Also say STACKONE_ACCOUNT_ID warns when set to a non-empty value, and pass accountIds: [hit.account_id] alongside sessionId in the search-then-execute examples in MIGRATION.md, README.md and examples/search-and-execute.ts. --- MIGRATION.md | 6 +++--- README.md | 1 + examples/search-and-execute.ts | 4 +++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 46ab01b0..9a9fae50 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -91,7 +91,7 @@ if (!hit) throw new Error('No action matched'); const result = await toolset.execute( hit.action_id, { query: { page_size: 25 } }, // the nested form hit.input_schema describes - { sessionId: hit.session_id }, + { accountIds: [hit.account_id], sessionId: hit.session_id }, ); ``` @@ -195,7 +195,7 @@ await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' **With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active account. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. -**`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. A toolset constructed with no account while `STACKONE_ACCOUNT_ID` is set warns that it is ignored. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: +**`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. A toolset constructed with no account while `STACKONE_ACCOUNT_ID` is set to a non-empty value warns that it is ignored. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: ```typescript // 2.x: STACKONE_ACCOUNT_ID picked up implicitly @@ -209,7 +209,7 @@ const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID **Listings are merged in sorted account order.** When two accounts serve the same tool name, `getTool()` returns the first one listed — now the one on the lowest account id, where 2.x followed the order you passed — and so do `executeOpenAIToolCalls()` and every adapter (`toOpenAI()`, `toAISDK()`, `toClaudeAgentSdk()` and the rest), which build one tool per name. A warning names the clashing tools. Pass `accountIds` to choose the account yourself. -**`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. An account whose listing fails is skipped with a warning, and left out of the cached catalog for 30 seconds, unless every account fails: then the accounts' shared `StackOneAPIError` is thrown when they all failed with one status, and otherwise a `ToolSetLoadError` with each account's error as its `cause`. +**`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. In a multi-account scope, an account whose listing fails with anything other than a 429 is skipped with a warning: the healthy accounts' listings are cached, and the failed account is retried after 30 seconds. A 429 that outlasts its retries instead rejects the whole call, since a rate limit on one account is likely to hit the others too. A single-account call throws its failure rather than skipping it, since there is no other account's catalog to fall back to. ## Feedback diff --git a/README.md b/README.md index 0da0991a..6f356bc9 100644 --- a/README.md +++ b/README.md @@ -302,6 +302,7 @@ const [best] = actions; if (!best) throw new Error('No action matched'); // `input_schema` describes what the action accepts; `example_request` shows the shape const result = await toolset.execute(best.action_id, best.example_request, { + accountIds: [best.account_id], sessionId: best.session_id, }); ``` diff --git a/examples/search-and-execute.ts b/examples/search-and-execute.ts index 0b074edd..85ac3bdd 100644 --- a/examples/search-and-execute.ts +++ b/examples/search-and-execute.ts @@ -47,11 +47,13 @@ const searchAndExecute = async (): Promise => { console.log(`\ninput_schema for ${best.action_id}:`); console.log(JSON.stringify(best.input_schema ?? {}, null, 2).slice(0, 600)); - // Passing the hit's session_id links this call to the search that found it. + // accountIds pins the call to the account that found the hit; session_id links it to the + // search. const result = await toolset.execute( best.action_id, { query: { limit: 2 } }, { + accountIds: [best.account_id], sessionId: best.session_id, }, ); From 0b0ce6d05ec64ee1124099efac4667389d1c85a0 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 16:37:55 +0100 Subject: [PATCH 103/151] fix(toolsets): coalesce concurrent catalog listings and warn on empty accountIds Concurrent fetchTools()/search() calls for the same account scope now share one in-flight listing instead of each listing and storing independently, so whichever finished last could no longer overwrite another caller's healthy catalog with a partial one. The STACKONE_ACCOUNT_ID warning now also fires when accountIds or execute.accountIds is an empty array, since the account resolver already treats an empty list as unset. --- src/toolsets.test.ts | 61 ++++++++++++++++++++++++++++++++++++++++++++ src/toolsets.ts | 55 ++++++++++++++++++++++++++++++++------- 2 files changed, 107 insertions(+), 9 deletions(-) diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index d15ca043..85cfb0e0 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -110,6 +110,20 @@ describe('configuration', () => { expect(warnSpy).not.toHaveBeenCalled(); }); + it.each([ + ['an empty accountIds array', { accountIds: [] }], + ['an empty execute.accountIds array', { execute: { accountIds: [] } }], + ])( + 'still warns about STACKONE_ACCOUNT_ID given %s, since it counts as unset', + (_name, config) => { + vi.stubEnv('STACKONE_ACCOUNT_ID', 'acc3'); + newToolSet(config); + expect(warnSpy.mock.calls.map(([message]: unknown[]) => String(message))).toEqual([ + '[@stackone/ai] STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.', + ]); + }, + ); + it('refuses both accountId and accountIds', () => { expect(() => newToolSet({ accountId: 'a', accountIds: ['b'] } as never)).toThrow( /Cannot provide both accountId and accountIds/, @@ -508,6 +522,53 @@ describe('listing', () => { ]); }); + it('coalesces concurrent listings for the same scope into one request per account', async () => { + let inFlight = 0; + let peak = 0; + fakeListing(async (request) => { + inFlight += 1; + peak = Math.max(peak, inFlight); + await new Promise((resolve) => setTimeout(resolve, 20)); + inFlight -= 1; + return [def(`tool_${accountOf(request)}`)]; + }); + + const toolset = newToolSet(); + const [first, second] = await Promise.all([ + toolset.fetchTools({ accountIds: ['a', 'b'] }), + toolset.fetchTools({ accountIds: ['a', 'b'] }), + ]); + + expect(peak).toBe(2); + expect(listMock.mock.calls.length).toBe(2); + expect(names(first)).toEqual(['tool_a', 'tool_b']); + expect(names(second)).toEqual(['tool_a', 'tool_b']); + }); + + it('does not let one coalesced caller’s partial failure overwrite another’s healthy catalog', async () => { + let callsForB = 0; + fakeListing(async (request) => { + if (accountOf(request) === 'b') { + callsForB += 1; + await new Promise((resolve) => setTimeout(resolve, 10)); + throw new Error('boom'); + } + await new Promise((resolve) => setTimeout(resolve, 20)); + return [def(`tool_${accountOf(request)}`)]; + }); + + const toolset = newToolSet(); + const [first, second] = await Promise.all([ + toolset.fetchTools({ accountIds: ['a', 'b'] }), + toolset.fetchTools({ accountIds: ['a', 'b'] }), + ]); + + // One listing per account, not one per concurrent caller. + expect(callsForB).toBe(1); + expect(names(first)).toEqual(['tool_a']); + expect(names(second)).toEqual(['tool_a']); + }); + it('keeps the healthy accounts when one fails, and says which failed', async () => { fakeListing((request) => { if (accountOf(request) === 'b') { diff --git a/src/toolsets.ts b/src/toolsets.ts index 3833f74a..20d8093d 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -344,6 +344,13 @@ export class StackOneToolSet { * caller silently rescope every later caller's tools. */ readonly #catalogCache = new Map(); + /** + * Listings in flight, keyed the same as {@link #catalogCache}. Concurrent calls for the same + * scope share this promise instead of each listing and storing independently — two callers + * racing to `store()` would let whichever finished last overwrite the other's catalog, which + * could hide a healthy account's tools behind a partial one. + */ + readonly #catalogInFlight = new Map>(); #discoveredAccountIds: string[] | undefined; #discovering: Promise | undefined; /** @@ -403,9 +410,8 @@ export class StackOneToolSet { // every account on the key — other end users' accounts included — so say so, once. if ( process.env.STACKONE_ACCOUNT_ID && - config.accountId == null && - config.accountIds == null && - config.execute?.accountIds == null + 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 account on this API key is used. Pass an account id to scope the toolset.', @@ -651,6 +657,8 @@ export class StackOneToolSet { */ async #catalog(scope: readonly string[], mode: ToolMode | undefined): Promise { const key = this.#cacheKey(scope, mode); + const inScopeOrder = (listings: CachedCatalog['listings']): CatalogEntry[] => + scope.flatMap((accountId) => listings.get(accountId) ?? []); const cached = this.#catalogCache.get(key); const now = retryTiming.now(); const due = cached @@ -658,12 +666,39 @@ export class StackOneToolSet { .filter(([, failedAt]) => now - failedAt >= FAILED_ACCOUNT_RETRY_MS) .map(([accountId]) => accountId) : scope; - const inScopeOrder = (listings: CachedCatalog['listings']): CatalogEntry[] => - scope.flatMap((accountId) => listings.get(accountId) ?? []); if (cached && due.length === 0) { return inScopeOrder(cached.listings); } + const inFlight = this.#catalogInFlight.get(key); + if (inFlight) { + return inScopeOrder((await inFlight).listings); + } + + const listing = this.#listCatalog(key, scope, due, cached, mode); + this.#catalogInFlight.set(key, listing); + try { + return inScopeOrder((await listing).listings); + } finally { + if (this.#catalogInFlight.get(key) === listing) { + this.#catalogInFlight.delete(key); + } + } + } + + /** + * Lists every due account and stores the merged result under `key`, run at most once + * concurrently per key — see {@link #catalogInFlight}. Returns the listings it computed + * regardless of whether {@link #cacheGeneration} let them be cached, so a clear mid-flight + * cannot make a coalesced caller read back nothing. + */ + async #listCatalog( + key: string, + scope: readonly string[], + due: readonly string[], + cached: CachedCatalog | undefined, + mode: ToolMode | undefined, + ): Promise { const generation = this.#cacheGeneration; const endpoint = this.#endpoint(mode); const listAccount = async (accountId: string): Promise => { @@ -687,8 +722,9 @@ export class StackOneToolSet { if (scope.length === 1) { const accountId = scope[0] as string; const listings = new Map([[accountId, await listAccount(accountId)]]); - store({ listings, failedAt: new Map() }); - return inScopeOrder(listings); + const catalog = { listings, failedAt: new Map() }; + store(catalog); + return catalog; } const settled = await settleWithConcurrency( @@ -717,8 +753,9 @@ export class StackOneToolSet { warn(`Skipping account that failed to list tools — ${accountId}: ${describeError(reason)}`); failedAt.set(accountId, failedNow); } - store({ listings, failedAt }); - return inScopeOrder(listings); + const catalog = { listings, failedAt }; + store(catalog); + return catalog; } /** From 53f4347359fb7b15674b7a8caced1c7642e6c877 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 16:38:09 +0100 Subject: [PATCH 104/151] test: remove unreachable fallback paths in rate-limit-timeout vectors Every request after the first 429 hangs in delay('infinite'), so the app.fetch()/HttpResponse.json([]) fallbacks, and the imports that existed only for them, never ran. --- src/vectors.test.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/vectors.test.ts b/src/vectors.test.ts index eb67d900..990670f4 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -8,7 +8,6 @@ import { join } from 'node:path'; import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'; import { delay, http, HttpResponse } from 'msw'; import { TEST_BASE_URL } from '../mocks/constants'; -import { accountMcpTools, createMcpApp } from '../mocks/mcp-server'; import { server } from '../mocks/node'; import { describeMcpFailure, listMcpTools, parseToolResult } from './mcp-client'; import { toolParametersFromInputSchema } from './schema'; @@ -621,14 +620,12 @@ const emitters: Record< const endpoint = `${TEST_BASE_URL}/mcp`; const timeout = 300; let requests = 0; - const app = createMcpApp({ accountTools: accountMcpTools }); server.use( - http.all(endpoint, async ({ request }) => { + http.all(endpoint, async () => { if (requests++ === 0) { return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); } await delay('infinite'); - return app.fetch(request); }), ); const error = await errorOf(() => @@ -647,7 +644,6 @@ const emitters: Record< return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); } await delay('infinite'); - return HttpResponse.json([]); }), ); const error = await errorOf(() => newToolSet({ timeout }).fetchAccounts()); From d849a585c37c9f7dc1a7f66bcf462ddac4e9a44b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 16:38:21 +0100 Subject: [PATCH 105/151] fix(mcp-client): reset the rate-limit flag per request, not per session A 429 retried successfully on an earlier request in the same MCP session (the handshake, say) left the session flagged as rate limited for good, so a later, unrelated timeout (on tools/list, say) was reported as a 429 that outlasted its retries instead of an ordinary timeout. That turns a failure a multi-account call could have skipped the account for into one that fails the whole call. Python had the same bug; this pins the fixed behavior with a test. --- src/mcp-client.ts | 12 +++++++++--- src/rate-limit.test.ts | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/mcp-client.ts b/src/mcp-client.ts index d0542753..7ce943da 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -129,18 +129,24 @@ async function withMcpSession( work: (client: Client) => Promise, ): Promise { const expiresAt = retryTiming.now() + timeout; + // Whether the request currently in flight is waiting out a 429, reset at the start of every + // request the transport sends: a 429 retried successfully on an earlier request (the + // handshake, say) must not make a later, unrelated timeout (on `tools/list`, say) look like + // a rate limit too. let rateLimited = false; const transport = new StreamableHTTPClientTransport(new URL(endpoint), { requestInit: { headers }, // Every request the client sends, handshake included, so it never sees a 429 it could // have waited out — but never one that would outlast the session's deadline. - fetch: (url, init) => - fetchWithRetry(url, init, { + fetch: (url, init) => { + rateLimited = false; + return fetchWithRetry(url, init, { deadline: expiresAt, onRetry: () => { rateLimited = true; }, - }), + }); + }, }); const client = new Client({ name: 'stackone-ai-node', version }); let timer: ReturnType | undefined; diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts index 28ef0867..6774a477 100644 --- a/src/rate-limit.test.ts +++ b/src/rate-limit.test.ts @@ -10,6 +10,7 @@ import { type RecordedToolCall, accountMcpTools, createMcpApp } from '../mocks/m import { server } from '../mocks/node'; import { StackOneToolSet } from './toolsets'; import { StackOneAPIError } from './utils/error-stackone-api'; +import { ToolSetLoadError } from './utils/error-toolset'; import { retryTiming } from './utils/fetch-retry'; const newToolSet = (config: ConstructorParameters[0] = {}) => @@ -363,6 +364,44 @@ describe('a timeout while a 429 is retried', () => { }); }); +describe('a 429 that clears on retry, followed by an unrelated timeout', () => { + // A 429 retried successfully must not taint a later, unrelated timeout in the same session: + // that would report an ordinary timeout as a 429, which fails a multi-account call that + // should instead have skipped the one slow account. + it('reports the later timeout as an ordinary timeout, not a 429', async () => { + const app = createMcpApp({ accountTools: accountMcpTools }); + 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) { + return HttpResponse.json(RATE_LIMITED, { + status: 429, + headers: { 'Retry-After': '0' }, + }); + } + if (message?.method === 'tools/list') { + await delay('infinite'); + } + return app.fetch(request); + }), + ); + + const error = await newToolSet({ timeout: 300 }) + .fetchTools({ accountIds: ['acc1'] }) + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolSetLoadError); + expect(error).not.toBeInstanceOf(StackOneAPIError); + expect((error as Error).message).toBe( + `MCP request to ${TEST_BASE_URL}/mcp timed out after 0.3s`, + ); + }); +}); + describe('other statuses', () => { it.each([400, 500])('does not retry a %i', async (status) => { let requests = 0; From 00da255e05d2455fbffe987737cef2b1daba5045 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 17:02:28 +0100 Subject: [PATCH 106/151] chore: sync vectors and pin sdk-conformance to c794e56 Catches up messages.json with the canonical wording both SDKs now emit (several matches: false entries that were already true), and moves the CI ref to the commit that keeps vectors at version 1 and grades the recovered-429-then-timeout scenario strictly now that Node's fix has landed. --- .github/workflows/ci.yaml | 2 +- tests/vectors/messages.json | 38 ++++++++++++++++++------------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index a1500faa..24cb9368 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: db6b90851b6807fca21f89cd1e9a1da402a4fbbb + ref: c794e56faea6b536ecd2e439af5fd0fb4d5b46f4 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index 9f423004..6e6a00b4 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -140,13 +140,13 @@ "kind": "warning", "template": "STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.", "placeholders": {}, - "python": "", - "node": "", + "python": "STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.", + "node": "STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Emitted once, when the toolset is constructed, if the STACKONE_ACCOUNT_ID environment variable is set and non-empty and neither an account id nor account ids were passed. Neither SDK emits it today." + "notes": "Emitted once, when the toolset is constructed, if the STACKONE_ACCOUNT_ID environment variable is set and non-empty and neither an account id nor account ids were passed." }, { "id": "skip-account", @@ -205,11 +205,11 @@ "description": "up to five of them, sorted, joined by \", \"" } }, - "python": "{count} tool name(s) are served by more than one account ({names}). Looking a tool up by name returns the first one listed — pass account ids to choose.", - "node": "{count} tool name(s) are served by more than one account ({names}). Looking a tool up by name returns the first one listed — pass account ids to choose.", + "python": "{count} tool name(s) are served by more than one account ({names}). The first one listed, from the lowest account id, is used — pass account ids to choose.", + "node": "{count} tool name(s) are served by more than one account ({names}). The first one listed, from the lowest account id, is used — pass account ids to choose.", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, "notes": "Language-neutral wording: neither SDK's method or parameter names. Emitted once when a fetched collection holds a clashing name, and again by every adapter that keeps the first tool per name and drops the rest: OpenAI, LangChain, Pydantic AI, AI SDK and Claude Agent SDK. Listing order is ascending account id, so the first is the lowest account id's." }, @@ -235,13 +235,13 @@ "description": "each matching *_execute_action tool as \"{tool} on {account_id}\", in ascending account-id order, joined by \", \"" } }, - "python": "{action_id} matches {count} connectors ({tools}); using {tool}. Pass account ids to choose.", - "node": "{action_id} matches {count} connectors ({tools}); using {tool}. Pass account ids to choose.", + "python": "{action_id} matches {count} connectors on different accounts ({tools}). Pass the account id to use, such as a search hit's account_id.", + "node": "{action_id} matches {count} connectors on different accounts ({tools}). Pass the account id to use, such as a search hit's account_id.", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Raised by execute() when the action's connector is linked on more than one account in scope — no account id passed, or several; nothing is called. Was a warning that ran the first match; today's text names the one used as {tool}." + "notes": "Raised by execute() when the action's connector is linked on more than one account in scope — no account id passed, or several; nothing is called. Was a warning that ran the first match." }, { "id": "mcp-timeout", @@ -547,13 +547,13 @@ "description": "each failed account as \"{account_id}: {error}\", where {error} is the failure's own message (as in skip-account), in ascending account-id order, joined by \"; \" — e.g. \"acc-1: ; acc-2: \"" } }, - "python": "No account returned tools. {failures}", - "node": "No account returned tools. {failures}", + "python": "Every account failed to list tools: {failures}", + "node": "Every account failed to list tools: {failures}", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, - "notes": "Only when every account in scope failed to list, and only when the failures do not all share one HTTP status: if they do, the SDK rethrows the StackOneAPIError itself (e.g. two accounts both answering 401 raise StackOneAPIError 401). The failures are the error's cause: Python raises it `from ExceptionGroup(...)` of them, Node passes `{ cause: new AggregateError(...) }`. An account that listed zero tools has not failed. Today both SDKs join the failures with \" | \", and also raise when some accounts failed and the rest listed zero tools. Replaces no-account-returned-tools." + "notes": "Only when every account in scope failed to list, and only when the failures do not all share one HTTP status: if they do, the SDK rethrows the StackOneAPIError itself (e.g. two accounts both answering 401 raise StackOneAPIError 401). The failures are the error's cause: Python raises it `from ExceptionGroup(...)` of them, Node passes `{ cause: new AggregateError(...) }`. An account that listed zero tools has not failed. Both SDKs join the failures with \"; \", and also raise when some accounts failed and the rest listed zero tools. Replaces no-account-returned-tools." }, { "id": "no-connector-returned-results", From 82fe558def3fc4b35d5189741747295170f8c72f Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 17:04:48 +0100 Subject: [PATCH 107/151] ci: run conformance against stackone-ai-python 7e9b3ef --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 24cb9368..04e3300a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 54322a3ad5f5bba322cf13d94d2726976e6aaba2 + PYTHON_SDK_REF: 7e9b3efd1101eb953813486b789c57bd0645ad0e steps: - name: Check conformance token is configured env: From 79c272e3ae5ef6c0e01816c7db0c1f2969d8e254 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 17:22:44 +0100 Subject: [PATCH 108/151] feat(toolsets): send x-end-user-id for non-shared accounts GET /accounts reports shared and origin_username per account. The API refuses an MCP request for a non-shared account unless x-end-user-id carries its end user, so record origin_username for every shared: false account on each successful GET /accounts and send it, after caller headers, on every MCP request for that account. Explicit account ids still make no GET /accounts; a caller's own x-end-user-id in headers is then passed through. A model-supplied x-end-user-id header argument is never forwarded. --- MIGRATION.md | 6 +- README.md | 4 +- src/end-user-id.test.ts | 332 ++++++++++++++++++++++++++++++++++++++++ src/headers.test.ts | 25 +++ src/headers.ts | 34 +++- src/tool.ts | 16 +- src/toolsets.ts | 43 +++++- src/types.ts | 7 + 8 files changed, 450 insertions(+), 17 deletions(-) create mode 100644 src/end-user-id.test.ts diff --git a/MIGRATION.md b/MIGRATION.md index 9a9fae50..4444d66b 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -164,7 +164,7 @@ await tool.execute({ id: '1' }, { dryRun: true }); ## Tool arguments and headers -**Arguments are sent as given**, as `tools/call` arguments, except header arguments: each is forwarded only if the tool's schema declares it, and `Authorization`, `x-account-id` and `User-Agent` never are (see below). The SDK no longer splits flat `path_` / `query_` / `body_` keys into an `/actions/rpc` envelope; the server maps them itself. +**Arguments are sent as given**, as `tools/call` arguments, except header arguments: each is forwarded only if the tool's schema declares it, and `Authorization`, `x-account-id`, `User-Agent` and `x-end-user-id` never are (see below). The SDK no longer splits flat `path_` / `query_` / `body_` keys into an `/actions/rpc` envelope; the server maps them itself. **Non-header arguments must be JSON values.** `null`, booleans, finite numbers, strings, arrays and plain objects are accepted; a `NaN` or `Infinity`, a `bigint`, a `Date`, `Map`, `Set` or `RegExp`, a function, a symbol, a class instance, a typed array or buffer, or a circular reference, anywhere in a non-header argument, throws `ToolArgumentsError` naming the path. 2.x let some of these through `JSON.stringify` silently converted (a `Date` to a string, a `Map` to `{}`), which sent the model a value it never supplied. An object property set to `undefined` is still treated as absent; `undefined` inside an array now throws, where 2.x sent it as `null`. Header arguments follow different rules — see "Header arguments are allowlisted" below. @@ -181,7 +181,7 @@ console.log(tool.parameters.properties); await tool.execute({ body: { variables: { first: 25 } } }); ``` -**Header arguments are allowlisted.** A header argument is an entry of a `headers` object argument, or a top-level `headers_` argument. Each one is forwarded only if the tool's schema declares it in the same form: under `headers.properties`, or as a `headers_` property. An open `headers` object — `type: "object"`, no `properties`, and `additionalProperties` not `false` — declares every name; without `type: "object"`, or with `additionalProperties: false` and no `properties`, it declares none. `Authorization`, `x-account-id` and `User-Agent` are never forwarded, even when declared, because the SDK sets them itself. Anything dropped is logged as a warning. Every other argument is sent unchanged. +**Header arguments are allowlisted.** A header argument is an entry of a `headers` object argument, or a top-level `headers_` argument. Each one is forwarded only if the tool's schema declares it in the same form: under `headers.properties`, or as a `headers_` property. An open `headers` object — `type: "object"`, no `properties`, and `additionalProperties` not `false` — declares every name; without `type: "object"`, or with `additionalProperties: false` and no `properties`, it declares none. `Authorization`, `x-account-id`, `User-Agent` and `x-end-user-id` are never forwarded, even when declared, because the SDK sets them itself. Anything dropped is logged as a warning. Every other argument is sent unchanged. A top-level `headers` argument skips header filtering when the schema declares `headers` itself as a non-object field — it's an ordinary argument that happens to be named `headers`, so it is sent as given, subject to the same JSON-value check as every other argument. Otherwise, a `headers` argument that isn't a plain object is dropped with a warning. A `headers_` argument is dropped with a warning when its value is an array or object. @@ -195,6 +195,8 @@ await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' **With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active account. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. +**Non-shared accounts get `x-end-user-id` automatically.** The API refuses an MCP request for a non-shared account unless `x-end-user-id` carries that account's end user. Whenever the SDK calls `GET /accounts` (discovery or `fetchAccounts()`), it records the `origin_username` of every account with `shared: false` and sends it as `x-end-user-id` on every MCP request for that account, overriding a value from the `headers` option. With explicit account ids the SDK makes no `GET /accounts` and sends no `x-end-user-id` of its own: call `fetchAccounts()` once, or set it in `headers`, which is passed through as given. + **`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. A toolset constructed with no account while `STACKONE_ACCOUNT_ID` is set to a non-empty value warns that it is ignored. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: ```typescript diff --git a/README.md b/README.md index 6f356bc9..7a4897ef 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,8 @@ for (const account of await toolset.fetchAccounts()) { > If your organisation has many linked accounts, discovery lists the catalog of every one of them. Pass explicit `accountIds` to avoid the round trips and the model context they cost. +A non-shared account (`shared: false` in `GET /accounts`) belongs to one end user, and the API refuses its MCP requests unless they carry that user's id in `x-end-user-id`. Whenever the toolset calls `GET /accounts` — for discovery, or through `fetchAccounts()` — it records each non-shared account's `origin_username` and sends it as `x-end-user-id` on every MCP request for that account, replacing any value from the `headers` option. With explicit account ids and no `GET /accounts`, it sends none: call `fetchAccounts()` once, or pass `headers: { 'x-end-user-id': '…' }` yourself. + ### Account IDs StackOne uses account IDs to identify different integrations. You can specify the account ID at different levels (a per-call `accountIds` wins, then `setAccounts()`, then the constructor's `accountIds`, then `accountId`, then discovery). The SDK never reads an account id from the environment, so an environment variable cannot silently change which accounts a toolset reaches. To keep yours in `STACKONE_ACCOUNT_ID`, read it yourself: @@ -403,7 +405,7 @@ A tool call's header arguments — the entries of a `headers` object argument, a A top-level `headers` argument that isn't a plain object is dropped with a warning, unless the served schema declares `headers` itself as a non-object field (for example `type: "string"`), in which case it's an ordinary argument that happens to be named `headers` and is sent as given. A `headers_` argument is dropped with a warning when its value is an array or object — only a string, number or boolean can be a header value. -`Authorization`, `x-account-id` and `User-Agent` are always the SDK's own: they are dropped from header arguments even when declared, and ignored with a warning in the `headers` constructor option, so nothing can replace the credential or run a call against another account. +`Authorization`, `x-account-id` and `User-Agent` are always the SDK's own: they are dropped from header arguments even when declared, and ignored with a warning in the `headers` constructor option, so nothing can replace the credential or run a call against another account. `x-end-user-id` is dropped from header arguments the same way, so a model cannot choose the end user; in the `headers` option it is sent as given, unless `GET /accounts` reported the account's end user (see [Authentication](#authentication)), which replaces it. ```typescript // Extra headers for every request (for example, tracing) diff --git a/src/end-user-id.test.ts b/src/end-user-id.test.ts new file mode 100644 index 00000000..4c9f01f8 --- /dev/null +++ b/src/end-user-id.test.ts @@ -0,0 +1,332 @@ +/** + * `x-end-user-id`: the API refuses an MCP request for a non-shared account unless it carries that + * account's end user, which only `GET /accounts` reports. Every assertion here is on the headers + * that actually reached the mock server. + */ +import { http, HttpResponse } from 'msw'; +import { TEST_BASE_URL } from '../mocks/constants'; +import { accountMcpTools, createMcpApp } from '../mocks/mcp-server'; +import { server } from '../mocks/node'; +import { StackOneToolSet } from './toolsets'; +import type { StackOneTool, Tools } from './tool'; +import { StackOneAPIError } from './utils/error-stackone-api'; + +/** One JSON-RPC message that reached `/mcp`, with the headers it came with. */ +interface McpExchange { + method: string; + accountId: string | null; + endUserId: string | null; +} + +const ACCOUNTS = [ + { id: 'acc1', provider: 'mock', status: 'active', shared: false, origin_username: 'alice' }, + { id: 'acc2', provider: 'mock', status: 'active', shared: true, origin_username: 'bob' }, +]; + +/** + * Serve `GET /accounts` and `/mcp`, recording every MCP message. `accounts` is read per request, + * so a test can change what the next `GET /accounts` reports. + */ +const serve = (initial: unknown[] | (() => Response) = ACCOUNTS) => { + const exchanges: McpExchange[] = []; + let accounts = initial; + let accountRequests = 0; + const app = createMcpApp({ + // acc2 also serves acc1_tool_1, so a tool listed on acc2 can be rebound to acc1. + accountTools: { + acc1: accountMcpTools.acc1, + acc2: [...accountMcpTools.acc2, accountMcpTools.acc1[0]], + }, + submitFeedback: true, + }); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + accountRequests += 1; + return typeof accounts === 'function' ? accounts() : HttpResponse.json(accounts); + }), + http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { + if (request.method === 'POST') { + const body = (await request.clone().json()) as unknown; + for (const message of Array.isArray(body) ? body : [body]) { + exchanges.push({ + method: String((message as { method?: unknown }).method), + accountId: request.headers.get('x-account-id'), + endUserId: request.headers.get('x-end-user-id'), + }); + } + } + return app.fetch(request); + }), + ); + return { + exchanges, + accountRequests: () => accountRequests, + setAccounts: (next: unknown[] | (() => Response)) => { + accounts = next; + }, + }; +}; + +const newToolSet = (config: ConstructorParameters[0] = {}) => + new StackOneToolSet({ apiKey: 'test-key', baseUrl: TEST_BASE_URL, ...config }); + +/** The `x-end-user-id` of every message for one account, by JSON-RPC method. */ +const endUserIdsFor = (exchanges: McpExchange[], accountId: string) => + exchanges + .filter((exchange) => exchange.accountId === accountId) + .map(({ method, endUserId }) => [method, endUserId]); + +const getTool = (tools: Tools, name: string): StackOneTool => { + const tool = tools.getStackOneTools().find((candidate) => candidate.name === name); + if (!tool) { + throw new Error(`${name} was not listed`); + } + return tool; +}; + +let warnSpy: ReturnType; +beforeEach(() => { + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('x-end-user-id after account discovery', () => { + it('is sent on every MCP request for a non-shared account, and never for a shared one', async () => { + const { exchanges } = serve(); + const tools = await newToolSet().fetchTools(); + + await getTool(tools, 'acc1_tool_1').execute({ fields: 'name' }); + await getTool(tools, 'acc2_tool_1').execute({ fields: 'name' }); + + expect(endUserIdsFor(exchanges, 'acc1')).toEqual([ + ['initialize', 'alice'], + ['notifications/initialized', 'alice'], + ['tools/list', 'alice'], + ['initialize', 'alice'], + ['notifications/initialized', 'alice'], + ['tools/call', 'alice'], + ]); + expect(endUserIdsFor(exchanges, 'acc2').every(([, endUserId]) => endUserId === null)).toBe( + true, + ); + expect(endUserIdsFor(exchanges, 'acc2')).toHaveLength(6); + }); + + it('is sent on search(), execute() and submitFeedback()', async () => { + const { exchanges } = serve(); + const toolset = newToolSet(); + + await toolset.search('list items'); + 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))); + expect(calls).toEqual([ + { method: 'tools/call', accountId: 'acc1', endUserId: 'alice' }, + { method: 'tools/call', accountId: 'acc1', endUserId: 'alice' }, + { method: 'tools/call', accountId: 'acc1', endUserId: 'alice' }, + { method: 'tools/call', accountId: 'acc2', endUserId: null }, + ]); + for (const exchange of exchanges) { + expect(exchange.endUserId).toBe(exchange.accountId === 'acc1' ? 'alice' : null); + } + }); + + it("replaces a caller's x-end-user-id, in any case, rather than joining the two", async () => { + const { exchanges } = serve(); + const toolset = newToolSet({ + accountId: 'acc1', + headers: { 'X-End-User-Id': 'mallory', 'x-end-user-id': 'eve' }, + }); + await toolset.fetchAccounts(); + await getTool(await toolset.fetchTools(), 'acc1_tool_1').execute({}); + + expect(exchanges.map((exchange) => exchange.endUserId)).toEqual(exchanges.map(() => 'alice')); + }); + + it('follows a tool rebound with setAccountId to its new account', async () => { + const { exchanges } = serve(); + const toolset = newToolSet(); + await toolset.fetchAccounts(); + const tool = getTool(await toolset.fetchTools({ accountIds: ['acc2'] }), 'acc1_tool_1'); + + await tool.execute({}); + expect(exchanges.at(-1)).toEqual({ method: 'tools/call', accountId: 'acc2', endUserId: null }); + + await tool.setAccountId('acc1').execute({}); + expect(exchanges.at(-1)).toEqual({ + method: 'tools/call', + accountId: 'acc1', + endUserId: 'alice', + }); + }); + + it.each([ + ['shared is missing', { origin_username: 'alice' }], + ['shared is true', { shared: true, origin_username: 'alice' }], + ['shared is not a boolean', { shared: 'false', origin_username: 'alice' }], + ['origin_username is missing', { shared: false }], + ['origin_username is empty', { shared: false, origin_username: '' }], + ['origin_username is null', { shared: false, origin_username: null }], + ['origin_username is not a string', { shared: false, origin_username: 42 }], + ])('is not sent when %s', async (_case, fields) => { + const { exchanges } = serve([{ id: 'acc1', status: 'active', ...fields }]); + const tools = await newToolSet().fetchTools(); + await getTool(tools, 'acc1_tool_1').execute({}); + + expect(exchanges.length).toBeGreaterThan(0); + expect(exchanges.every((exchange) => exchange.endUserId === null)).toBe(true); + }); +}); + +describe('x-end-user-id after fetchAccounts()', () => { + it('is sent for an explicit account once fetchAccounts() has reported its end user', async () => { + const { exchanges } = serve(); + const toolset = newToolSet({ accountId: 'acc1' }); + + await toolset.fetchAccounts(); + const tools = await toolset.fetchTools(); + await getTool(tools, 'acc1_tool_1').execute({}); + + expect(exchanges.length).toBeGreaterThan(0); + expect(exchanges.every((exchange) => exchange.endUserId === 'alice')).toBe(true); + }); + + it('reaches tools fetched before the GET /accounts that reported it', async () => { + const { exchanges } = serve(); + const toolset = newToolSet({ accountId: 'acc1' }); + const tool = getTool(await toolset.fetchTools(), 'acc1_tool_1'); + + await toolset.fetchAccounts(); + await tool.execute({}); + + expect(exchanges.at(-1)?.endUserId).toBe('alice'); + }); + + it('is replaced by each successful GET /accounts, and kept through a failed one', async () => { + const { exchanges, setAccounts } = serve(); + const toolset = newToolSet({ accountId: 'acc1' }); + const tool = getTool(await toolset.fetchTools(), 'acc1_tool_1'); + const lastEndUserId = async () => { + await tool.execute({}); + return exchanges.at(-1)?.endUserId; + }; + + await toolset.fetchAccounts(); + expect(await lastEndUserId()).toBe('alice'); + + setAccounts([{ ...ACCOUNTS[0], origin_username: 'carol' }]); + await toolset.fetchAccounts(); + expect(await lastEndUserId()).toBe('carol'); + + setAccounts(() => HttpResponse.json({ message: 'boom' }, { status: 500 })); + await expect(toolset.fetchAccounts()).rejects.toThrow(StackOneAPIError); + expect(await lastEndUserId()).toBe('carol'); + + setAccounts([{ ...ACCOUNTS[0], shared: true }]); + await toolset.fetchAccounts(); + expect(await lastEndUserId()).toBeNull(); + }); + + it('is kept by clearCatalogCache()', async () => { + const { exchanges, accountRequests } = serve(); + const toolset = newToolSet({ accountId: 'acc1' }); + await toolset.fetchAccounts(); + + toolset.clearCatalogCache(); + await toolset.fetchTools(); + + expect(accountRequests()).toBe(1); + expect(exchanges.every((exchange) => exchange.endUserId === 'alice')).toBe(true); + }); +}); + +describe('x-end-user-id with explicit accounts and no GET /accounts', () => { + it('makes no GET /accounts and sends no x-end-user-id', async () => { + const { exchanges, accountRequests } = serve(); + const tools = await newToolSet({ accountIds: ['acc1'] }).fetchTools(); + await getTool(tools, 'acc1_tool_1').execute({}); + + expect(accountRequests()).toBe(0); + expect(exchanges.length).toBeGreaterThan(0); + expect(exchanges.every((exchange) => exchange.endUserId === null)).toBe(true); + }); + + it("passes the caller's own x-end-user-id through, without a warning", async () => { + const { exchanges, accountRequests } = serve(); + const toolset = newToolSet({ accountId: 'acc1', headers: { 'X-End-User-Id': 'carol' } }); + const tools = await toolset.fetchTools(); + await getTool(tools, 'acc1_tool_1').execute({}); + await toolset.search('list items'); + + expect(accountRequests()).toBe(0); + expect(exchanges.length).toBeGreaterThan(0); + expect(exchanges.every((exchange) => exchange.endUserId === 'carol')).toBe(true); + expect(warnSpy).not.toHaveBeenCalled(); + }); +}); + +describe('x-end-user-id as a model-supplied header argument', () => { + it.each(['x-end-user-id', 'X-End-User-Id', ' X-END-USER-ID\t'])( + 'drops %j from an open headers object, keeping the SDK-set value', + async (name) => { + const { exchanges } = serve(); + const toolset = newToolSet(); + await toolset.fetchAccounts(); + + await toolset.execute( + 'mock_list_items', + { headers: { [name]: 'mallory', 'x-trace': 't' } }, + { accountIds: ['acc1'] }, + ); + + expect(exchanges.at(-1)).toEqual({ + method: 'tools/call', + accountId: 'acc1', + endUserId: 'alice', + }); + expect(warnSpy.mock.calls.map((args: unknown[]) => String(args[0]))).toEqual([ + `[@stackone/ai] Dropping header ${JSON.stringify(name.trim())} from a tool call: set by the SDK`, + ]); + }, + ); + + it('drops it from a declared nested header and a declared flat headers_ argument', async () => { + const declaring = { + name: 'acc1_declares_end_user', + description: '', + inputSchema: { + type: 'object' as const, + properties: { + headers: { type: 'object', properties: { 'x-end-user-id': { type: 'string' } } }, + 'headers_x-end-user-id': { type: 'string' }, + 'headers_X-End-User-Id ': { type: 'string' }, + }, + }, + }; + const calls: Record[] = []; + const app = createMcpApp({ + accountTools: { acc1: [declaring] }, + onToolCall: (call) => calls.push(call.arguments), + }); + server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); + const tools = await newToolSet({ accountId: 'acc1' }).fetchTools(); + + await getTool(tools, 'acc1_declares_end_user').execute({ + headers: { 'x-end-user-id': 'mallory' }, + 'headers_x-end-user-id': 'mallory', + 'headers_X-End-User-Id ': 'mallory', + }); + + expect(calls).toEqual([{ headers: {} }]); + expect(warnSpy.mock.calls.map((args: unknown[]) => String(args[0]))).toEqual([ + '[@stackone/ai] Dropping header "x-end-user-id" from a tool call: set by the SDK', + '[@stackone/ai] Dropping header argument "headers_x-end-user-id" from a tool call: set by the SDK', + '[@stackone/ai] Dropping header argument "headers_X-End-User-Id " from a tool call: set by the SDK', + ]); + }); +}); diff --git a/src/headers.test.ts b/src/headers.test.ts index 49f06a08..a6d93147 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -167,3 +167,28 @@ describe('an entry named __proto__', () => { expect(Object.getPrototypeOf(headers)).toBe(Object.prototype); }); }); + +describe('buildRequestHeaders with an end user', () => { + it('sets x-end-user-id last, replacing every case variant the caller sent', () => { + expect( + buildRequestHeaders({ + apiKey: 'k', + accountId: 'acc1', + endUserId: 'alice', + extraHeaders: { 'X-End-User-Id': 'mallory', ' x-end-user-id ': 'eve', 'x-trace': 't' }, + }), + ).toEqual({ + 'x-trace': 't', + 'User-Agent': expect.any(String), + Authorization: 'Basic azo=', + 'x-account-id': 'acc1', + 'x-end-user-id': 'alice', + }); + }); + + it("passes the caller's x-end-user-id through when there is no end user", () => { + expect( + buildRequestHeaders({ apiKey: 'k', extraHeaders: { 'X-End-User-Id': 'carol' } }), + ).toMatchObject({ 'X-End-User-Id': 'carol' }); + }); +}); diff --git a/src/headers.ts b/src/headers.ts index ac18d428..981e5f97 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -10,6 +10,15 @@ import { setEntry } from './utils/set-entry'; */ const SDK_OWNED_HEADERS = ['authorization', 'x-account-id', 'user-agent'] as const; +/** + * The header the API checks a non-shared account's end user against. The SDK sets it, after + * every other header, for an account whose end user `GET /accounts` reported. It is not + * SDK-owned for the `headers` option — a caller with explicit account ids and no discovery may + * set it there — but it is never taken from a tool call: a model choosing the end user is a + * model choosing whose data it reads. + */ +const END_USER_ID_HEADER = 'x-end-user-id'; + const isPlainObject = (value: unknown): value is JsonObject => typeof value === 'object' && value !== null && !Array.isArray(value); @@ -18,6 +27,9 @@ export function isSdkOwnedHeader(name: string): boolean { return (SDK_OWNED_HEADERS as readonly string[]).includes(name.trim().toLowerCase()); } +const isEndUserIdHeader = (name: string): boolean => + name.trim().toLowerCase() === END_USER_ID_HEADER; + /** * HTTP Basic credentials for an API key, as every StackOne endpoint expects them. */ @@ -27,20 +39,23 @@ function buildAuthHeader(apiKey: string): string { /** * The HTTP headers for a request to StackOne: the caller's extra headers first, then the SDK's - * own, so `Authorization`, `x-account-id` and `User-Agent` are always the SDK's. + * own, so `Authorization`, `x-account-id` and `User-Agent` are always the SDK's — and so is + * `x-end-user-id` when an `endUserId` is given. * * Case variants of the owned names are removed before they are set — `fetch` joins * `authorization` and `Authorization` into one comma-separated value rather than letting either - * win. With no `accountId`, no `x-account-id` is sent at all. + * win. With no `accountId`, no `x-account-id` is sent at all; with no `endUserId`, a caller's + * `x-end-user-id` is passed through as given. */ export function buildRequestHeaders(options: { apiKey: string; accountId?: string; + endUserId?: string; extraHeaders?: Record; }): Record { const headers: Record = {}; for (const [name, value] of Object.entries(options.extraHeaders ?? {})) { - if (!isSdkOwnedHeader(name)) { + if (!isSdkOwnedHeader(name) && !(options.endUserId && isEndUserIdHeader(name))) { setEntry(headers, name, value); } } @@ -49,6 +64,9 @@ export function buildRequestHeaders(options: { if (options.accountId) { headers['x-account-id'] = options.accountId; } + if (options.endUserId) { + headers[END_USER_ID_HEADER] = options.endUserId; + } return headers; } @@ -152,12 +170,12 @@ export function declaredHeaders(properties: Record): DeclaredHe /** * Why a header argument must not be forwarded, or `undefined` if it may be. * - * `Authorization`, `x-account-id` and `User-Agent` are refused even when declared, because the - * SDK sets them itself. The value check runs only for a declared header, which is exactly where - * a model-supplied value needs it. + * `Authorization`, `x-account-id`, `User-Agent` and `x-end-user-id` are refused even when + * declared, because the SDK sets them itself. The value check runs only for a declared header, + * which is exactly where a model-supplied value needs it. */ function refuseHeader(name: string, value: string, declared: boolean): string | undefined { - if (isSdkOwnedHeader(name)) { + if (isSdkOwnedHeader(name) || isEndUserIdHeader(name)) { return 'set by the SDK'; } if (!declared) { @@ -179,7 +197,7 @@ function refuseHeader(name: string, value: string, declared: boolean): string | * `X-Api-Key`, …) and is wrong the moment one is missed. * * Names are compared trimmed and case-insensitively: `" x-account-id "` and `"X-ACCOUNT-ID"` - * are the same header to any server. + * are the same header to any server. `x-end-user-id` is refused like the SDK-owned names. */ export function sanitiseHeaders( supplied: JsonObject | undefined, diff --git a/src/tool.ts b/src/tool.ts index 6596d271..a5232fe7 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -368,6 +368,7 @@ export class StackOneMcpTool extends StackOneTool { readonly #endpoint: string; readonly #apiKey: string; readonly #extraHeaders: Record; + readonly #endUserIdFor: (accountId: string) => string | undefined; readonly #timeout: number; readonly #declaredHeaders: DeclaredHeaders; @@ -380,6 +381,11 @@ export class StackOneMcpTool extends StackOneTool { accountId?: string; timeout: number; extraHeaders?: Record; + /** + * The end user of an account, sent as `x-end-user-id`. Looked up per call, so a tool + * rebound with `setAccountId` sends its new account's end user. + */ + endUserIdFor?: (accountId: string) => string | undefined; }) { const executeConfig = { kind: 'mcp', @@ -391,6 +397,7 @@ export class StackOneMcpTool extends StackOneTool { this.#endpoint = options.endpoint; this.#apiKey = options.apiKey; this.#extraHeaders = { ...options.extraHeaders }; + this.#endUserIdFor = options.endUserIdFor ?? (() => undefined); this.#timeout = options.timeout; this.#declaredHeaders = declaredHeaders(options.parameters.properties); } @@ -401,8 +408,9 @@ export class StackOneMcpTool extends StackOneTool { * Arguments are sent as given; the server maps them onto the action. Header arguments — the * entries of a `headers` object, and `headers_` arguments — are the exception: these * arguments are model-controlled, so each is forwarded only if this tool's own schema declares - * it, and `Authorization`, `x-account-id` and `User-Agent` never are. A `headers` property - * served as an object with no `properties`, as on `*_execute_action`, declares every name. + * it, and `Authorization`, `x-account-id`, `User-Agent` and `x-end-user-id` never are. A + * `headers` property served as an object with no `properties`, as on `*_execute_action`, + * declares every name. * * @returns The result as the server wrote it: for an action tool, an `ActionResult`, * `{ isError: false, result, defenderMetadata?, policyMetadata? }`. A file action's `result` @@ -427,12 +435,14 @@ export class StackOneMcpTool extends StackOneTool { return { url: this.#endpoint, method: 'tools/call', name: this.name, arguments: args }; } + const accountId = this.getAccountId(); return callMcpTool( { endpoint: this.#endpoint, headers: buildRequestHeaders({ apiKey: this.#apiKey, - accountId: this.getAccountId(), + accountId, + endUserId: accountId ? this.#endUserIdFor(accountId) : undefined, extraHeaders: this.#extraHeaders, }), timeout: this.#timeout, diff --git a/src/toolsets.ts b/src/toolsets.ts index 20d8093d..d52b9e86 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -82,7 +82,9 @@ interface StackOneToolSetBaseConfig { baseUrl?: string; /** * Extra HTTP headers sent with every request. `Authorization`, `x-account-id` and - * `User-Agent` are always the SDK's own and cannot be set here. + * `User-Agent` are always the SDK's own and cannot be set here. `x-end-user-id` can: it is + * passed through as given, unless `GET /accounts` reported the account's end user, which + * then replaces it. */ headers?: Record; /** @@ -353,6 +355,13 @@ export class StackOneToolSet { readonly #catalogInFlight = new Map>(); #discoveredAccountIds: string[] | undefined; #discovering: Promise | undefined; + /** + * The end user of each non-shared account, as the last successful `GET /accounts` reported it, + * sent as `x-end-user-id` on every MCP request for that account: the API refuses a non-shared + * account's request without it. Replaced whole on each successful `GET /accounts`, and kept + * by {@link clearCatalogCache} — it describes the accounts, not the catalog. + */ + #endUserIds: ReadonlyMap = new Map(); /** * Bumped by {@link clearCatalogCache}. A listing already in flight when the cache is cleared * captured the generation it started under, and refuses to write back if it has moved — @@ -469,6 +478,10 @@ export class StackOneToolSet { * Each entry carries at least `id`, `provider` and `status`. Only accounts with * `status === 'active'` can serve tools. * + * Also records the end user of every non-shared account (`shared: false`, with an + * `origin_username`), which the toolset then sends as `x-end-user-id` on that account's MCP + * requests. + * * @throws StackOneAPIError If the API answers with an error status, including a 429 that * outlasted its retries or timed out while being retried. * @throws ToolSetLoadError If the API cannot be reached, or answers with something that is @@ -547,6 +560,7 @@ export class StackOneToolSet { `Unexpected /accounts response shape: expected a list, got ${jsonType(accounts)}`, ); } + this.#endUserIds = endUserIdsOf(accounts); return accounts as StackOneAccount[]; } @@ -707,6 +721,7 @@ export class StackOneToolSet { headers: buildRequestHeaders({ apiKey: this.#apiKey, accountId, + endUserId: this.#endUserIds.get(accountId), extraHeaders: this.#headers, }), timeout: this.#timeout, @@ -774,6 +789,7 @@ export class StackOneToolSet { accountId, timeout: this.#timeout, extraHeaders: this.#headers, + endUserIdFor: (id) => this.#endUserIds.get(id), }); } @@ -956,8 +972,8 @@ export class StackOneToolSet { * pinned last, so a model-supplied `action_id` in `args` cannot replace it. * * `args.headers` is forwarded to the action: `*_execute_action` serves `headers` as an open - * object, so any header name is declared — except `Authorization`, `x-account-id` and - * `User-Agent`, which the SDK sets itself and drops here with a warning. + * object, so any header name is declared — except `Authorization`, `x-account-id`, + * `User-Agent` and `x-end-user-id`, which the SDK sets itself and drops here with a warning. * * @param actionId The action to run, e.g. `linear_list_issues`. * @param args The action's arguments. @@ -1112,6 +1128,27 @@ export class StackOneToolSet { } } +/** + * The end user of each non-shared account in a `GET /accounts` listing: one with `shared: false` + * and a non-empty `origin_username`. A shared account has no single end user to send. + */ +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); + } + } + return endUserIds; +} + /** * The error for a listing in which every account failed. * diff --git a/src/types.ts b/src/types.ts index 7ef5aa8c..208ae4f4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -190,6 +190,13 @@ export type StackOneAccount = JsonObject & { id: string; provider?: string; status?: string; + /** Whether the account is shared across end users. */ + shared?: boolean; + /** + * The account's end user. For a non-shared account, the toolset sends it as `x-end-user-id` on + * every MCP request for that account. + */ + origin_username?: string | null; }; /** From 65dc4698b2ab49cdaccfcbae7d01b46ccd340127 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 17:46:12 +0100 Subject: [PATCH 109/151] chore: sync vectors and pin sdk-conformance to f46905f --- .github/workflows/ci.yaml | 2 +- tests/vectors/header-arguments.json | 68 ++++++++++++++++++++++++++++- tests/vectors/header-names.json | 26 ++++++++++- 3 files changed, 93 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 04e3300a..72c8f613 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: c794e56faea6b536ecd2e439af5fd0fb4d5b46f4 + ref: f46905fa7cafac4a28b270fc722a20be3a9efafd token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false diff --git a/tests/vectors/header-arguments.json b/tests/vectors/header-arguments.json index 402be572..6207fba1 100644 --- a/tests/vectors/header-arguments.json +++ b/tests/vectors/header-arguments.json @@ -1,6 +1,6 @@ { "$schema": "./schema/header-arguments.schema.json", - "description": "Invariant 4 as data: a tool's served inputSchema, the model's arguments, the arguments that reach tools/call, and the warnings the SDK emits, in argument order. A warning is {argument, header?, reason}: `argument` is the top-level key (`headers` or `headers_`); `header` is the trimmed nested name, for an entry of a `headers` object. `reason` is one of `reasons`; messages.json renders it.", + "description": "Invariant 4 as data: a tool's served inputSchema, the model's arguments, the arguments that reach tools/call, and the warnings the SDK emits, in argument order. A warning is {argument, header?, reason}: `argument` is the top-level key (`headers` or `headers_`); `header` is the trimmed nested name, for an entry of a `headers` object. `reason` is one of `reasons`; messages.json renders it. `x-end-user-id` is SDK-owned like authorization, x-account-id and user-agent, and dropped unconditionally — whether or not the SDK has an end user id recorded for the call's account (SDK-UCA-CONTRACT.md §9): these cases carry no account context, since the owned-name check runs the same regardless.", "version": 1, "reasons": ["set-by-sdk", "not-declared", "malformed", "not-an-object", "not-a-scalar"], "cases": [ @@ -1281,6 +1281,72 @@ }, "expected_warnings": [] }, + { + "id": "nested-end-user-id-is-owned", + "description": "a declared nested x-end-user-id is never forwarded, whatever the schema declares, since it is SDK-owned", + "schema": { + "type": "object", + "properties": { + "headers": { + "type": "object", + "properties": { + "x-custom": { + "type": "string" + }, + "x-end-user-id": { + "type": "string" + } + } + } + } + }, + "arguments": { + "headers": { + "x-custom": "a", + "x-end-user-id": "evil-user" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [ + { + "argument": "headers", + "header": "x-end-user-id", + "reason": "set-by-sdk" + } + ] + }, + { + "id": "flat-end-user-id-is-owned", + "description": "a declared flat headers_x-end-user-id is never forwarded, whatever its case or surrounding space", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_x-end-user-id": { + "type": "string" + } + } + }, + "arguments": { + "path_id": "e", + "headers_x-end-user-id": "evil-user" + }, + "expected_arguments": { + "path_id": "e" + }, + "expected_warnings": [ + { + "argument": "headers_x-end-user-id", + "reason": "set-by-sdk" + } + ] + }, { "id": "flat-and-nested-together", "description": "nested and flat header arguments are filtered independently", diff --git a/tests/vectors/header-names.json b/tests/vectors/header-names.json index 4048cf55..c800eafb 100644 --- a/tests/vectors/header-names.json +++ b/tests/vectors/header-names.json @@ -1,6 +1,6 @@ { "$schema": "./schema/header-names.schema.json", - "description": "How a nested header name — an entry of a top-level `headers` object argument whose served schema is open (`{\"type\": \"object\"}`), with the value \"v\" — is treated. The name is trimmed of what JavaScript's String.prototype.trim() strips, then refused if it is SDK-owned (authorization, x-account-id, user-agent, case-insensitively), then if it is not an RFC 9110 token. A forwarded name is the trimmed one.", + "description": "How a nested header name — an entry of a top-level `headers` object argument whose served schema is open (`{\"type\": \"object\"}`), with the value \"v\" — is treated. The name is trimmed of what JavaScript's String.prototype.trim() strips, then refused if it is SDK-owned (authorization, x-account-id, user-agent, x-end-user-id, case-insensitively — x-end-user-id unconditionally, whether or not the SDK has an end user id recorded for the call's account), then if it is not an RFC 9110 token. A forwarded name is the trimmed one.", "version": 1, "cases": [ { @@ -267,6 +267,14 @@ "dropped": "set-by-sdk" } }, + { + "id": "owned-end-user", + "description": "SDK-owned end-user tenant selector, dropped whether or not the SDK has an end user id recorded for the account", + "name": "X-End-User-Id", + "expected": { + "dropped": "set-by-sdk" + } + }, { "id": "owned-ua", "description": "SDK-owned client identity", @@ -299,6 +307,14 @@ "dropped": "set-by-sdk" } }, + { + "id": "owned-end-user-padded", + "description": "SDK-owned once trimmed", + "name": " x-end-user-id\t", + "expected": { + "dropped": "set-by-sdk" + } + }, { "id": "owned-bom", "description": "SDK-owned once the BOM is trimmed", @@ -339,6 +355,14 @@ "forwarded": "x-account-id-2" } }, + { + "id": "not-owned-end-user-similar", + "description": "a name that merely starts with x-end-user-id is not owned", + "name": "x-end-user-id-2", + "expected": { + "forwarded": "x-end-user-id-2" + } + }, { "id": "proxy-authorization", "description": "only the three names are owned; others are declared by the open schema", From 4dd5df9b41007a9d086ae90f50a9cad09ee378a1 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 18:00:59 +0100 Subject: [PATCH 110/151] feat(toolsets): use the shared ignored-headers warning text Sync vectors from sdk-conformance@0d72282, which makes the toolset's ignored-headers warning a shared canonical message (toolset-headers-ignored). --- src/toolsets.ts | 2 +- src/vectors.test.ts | 7 +++++++ tests/vectors/messages.json | 24 ++++++++++++++++++------ 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/toolsets.ts b/src/toolsets.ts index d52b9e86..7ea85abe 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -403,7 +403,7 @@ export class StackOneToolSet { 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. Use the apiKey and accountId options instead.`, + `Ignoring headers ${ignoredHeaders.map((name) => `"${name}"`).join(', ')}: the SDK sets them itself. Pass the API key and account ids through their own options instead.`, ); } diff --git a/src/vectors.test.ts b/src/vectors.test.ts index 990670f4..617a5db5 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -603,6 +603,13 @@ const emitters: Record< vi.unstubAllEnvs(); } }, + 'toolset-headers-ignored': async () => { + newToolSet({ headers: { Authorization: 'x', 'x-account-id': 'y' } }); + return { + emitted: { warnings: warnings() }, + values: { names: '"Authorization", "x-account-id"' }, + }; + }, 'mcp-timeout': async () => { const endpoint = `${TEST_BASE_URL}/mcp`; return { diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index 6e6a00b4..5e86767a 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -1031,6 +1031,24 @@ "node": true }, "notes": "Not raised: the `error` of the tool message execute_openai_tool_calls / executeOpenAIToolCalls returns for a call to a tool not in the collection." + }, + { + "id": "toolset-headers-ignored", + "kind": "warning", + "template": "Ignoring headers {names}: the SDK sets them itself. Pass the API key and account ids through their own options instead.", + "placeholders": { + "names": { + "format": "text", + "description": "each ignored name as given, in double quotes, joined with \", \", in the order supplied" + } + }, + "python": "(not emitted: the toolset takes no headers option yet)", + "node": "Ignoring headers {names}: the SDK sets them itself. Use the apiKey and accountId options instead.", + "matches": { + "python": false, + "node": false + }, + "notes": "Emitted once at construction when the toolset's headers option names Authorization, x-account-id or User-Agent (any case, surrounding whitespace ignored). x-end-user-id is allowed in this option and is not warned about. The option's other headers go on every request, GET /accounts included, beneath the SDK's own." } ], "unshared": [ @@ -1050,12 +1068,6 @@ "kind": "error", "text": "Tool \"{tool}\" has no API key to authenticate with." }, - { - "sdk": "node", - "kind": "warning", - "text": "Ignoring headers {names}: the SDK sets them itself. Use the apiKey and accountId options instead.", - "notes": "Python's toolset takes no extra headers." - }, { "sdk": "node", "kind": "error", From bb9dc1401ec55421b72d1e5c25be4f361072befc Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 18:01:10 +0100 Subject: [PATCH 111/151] chore(ci): pin sdk-conformance to 0d72282 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 72c8f613..c103085a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: f46905fa7cafac4a28b270fc722a20be3a9efafd + ref: 0d722829f38fd30629a987384aa915235a056869 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 334c84079eb721aaacb1e7c3206980e5d7ccf77c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 20:16:32 +0100 Subject: [PATCH 112/151] test(vectors): sync to sdk-conformance 88c9400 --- tests/vectors/messages.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index 5e86767a..a788c4ec 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -1042,11 +1042,11 @@ "description": "each ignored name as given, in double quotes, joined with \", \", in the order supplied" } }, - "python": "(not emitted: the toolset takes no headers option yet)", - "node": "Ignoring headers {names}: the SDK sets them itself. Use the apiKey and accountId options instead.", + "python": "Ignoring headers {names}: the SDK sets them itself. Pass the API key and account ids through their own options instead.", + "node": "Ignoring headers {names}: the SDK sets them itself. Pass the API key and account ids through their own options instead.", "matches": { - "python": false, - "node": false + "python": true, + "node": true }, "notes": "Emitted once at construction when the toolset's headers option names Authorization, x-account-id or User-Agent (any case, surrounding whitespace ignored). x-end-user-id is allowed in this option and is not warned about. The option's other headers go on every request, GET /accounts included, beneath the SDK's own." } From 8030159b528e56e09cfcf8e06cf2b29382de0906 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Fri, 2 Oct 2026 20:16:32 +0100 Subject: [PATCH 113/151] ci: pin sdk-conformance to 88c9400 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c103085a..465ada9f 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 0d722829f38fd30629a987384aa915235a056869 + ref: 88c9400516f9842ca81dccce747f5d3e66e1fb0a token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 0ccc5eaced3ea323691c5346695e90b32ff365b2 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 09:17:23 +0100 Subject: [PATCH 114/151] ci: run conformance against stackone-ai-python 508ee6e --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 465ada9f..461cd737 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 7e9b3efd1101eb953813486b789c57bd0645ad0e + PYTHON_SDK_REF: 508ee6e161a449d229081fa5c0b1ecd5622eedf5 steps: - name: Check conformance token is configured env: From b9ffddcb62c669092ce7248edb3ab9402a4ad4c1 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 09:34:16 +0100 Subject: [PATCH 115/151] fix(toolsets): keep endUserIds from the most recently started fetchAccounts Overlapping GET /accounts calls could let an older response overwrite a newer one's end-user identities. Guard the write with a generation counter bumped at the start of every fetchAccounts() call, invalidated the same way the account-discovery generation is on a catalog-cache clear. --- src/end-user-id.test.ts | 45 +++++++++++++++++++++++++++++++++++++++++ src/toolsets.ts | 16 ++++++++++++++- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/src/end-user-id.test.ts b/src/end-user-id.test.ts index 4c9f01f8..17323bb2 100644 --- a/src/end-user-id.test.ts +++ b/src/end-user-id.test.ts @@ -232,6 +232,51 @@ describe('x-end-user-id after fetchAccounts()', () => { expect(await lastEndUserId()).toBeNull(); }); + it('keeps the end user from the most recently started GET /accounts, even if an older one resolves later', async () => { + const exchanges: McpExchange[] = []; + const app = createMcpApp({ accountTools: { acc1: accountMcpTools.acc1 } }); + let requests = 0; + let releaseFirst!: () => void; + const firstReleased = new Promise((resolve) => { + releaseFirst = resolve; + }); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, async () => { + requests += 1; + if (requests === 1) { + await firstReleased; + return HttpResponse.json([{ ...ACCOUNTS[0], origin_username: 'alice' }]); + } + return HttpResponse.json([{ ...ACCOUNTS[0], origin_username: 'carol' }]); + }), + http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { + if (request.method === 'POST') { + const body = (await request.clone().json()) as unknown; + for (const message of Array.isArray(body) ? body : [body]) { + exchanges.push({ + method: String((message as { method?: unknown }).method), + accountId: request.headers.get('x-account-id'), + endUserId: request.headers.get('x-end-user-id'), + }); + } + } + return app.fetch(request); + }), + ); + + const toolset = newToolSet({ accountId: 'acc1' }); + const older = toolset.fetchAccounts(); + await vi.waitFor(() => expect(requests).toBe(1)); + await toolset.fetchAccounts(); + releaseFirst(); + await older; + + const tools = await toolset.fetchTools(); + await getTool(tools, 'acc1_tool_1').execute({}); + + expect(exchanges.at(-1)?.endUserId).toBe('carol'); + }); + it('is kept by clearCatalogCache()', async () => { const { exchanges, accountRequests } = serve(); const toolset = newToolSet({ accountId: 'acc1' }); diff --git a/src/toolsets.ts b/src/toolsets.ts index 7ea85abe..16f4f0e2 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -362,6 +362,13 @@ export class StackOneToolSet { * by {@link clearCatalogCache} — it describes the accounts, not the catalog. */ #endUserIds: ReadonlyMap = new Map(); + /** + * Bumped on every {@link fetchAccounts} call. Overlapping calls (it is public, and not + * deduplicated the way {@link #discoverAccountIds} is) can resolve out of order; capturing this + * at the start of each call and refusing to write {@link #endUserIds} back once a later call has + * started keeps the published identities from regressing to a stale response. + */ + #endUserIdsGeneration = 0; /** * Bumped by {@link clearCatalogCache}. A listing already in flight when the cache is cleared * captured the generation it started under, and refuses to write back if it has moved — @@ -489,6 +496,8 @@ export class StackOneToolSet { */ async fetchAccounts(): Promise { const url = `${this.#baseUrl.replace(/\/+$/, '')}/accounts`; + const cacheGeneration = this.#cacheGeneration; + const requestGeneration = ++this.#endUserIdsGeneration; let response: Response; let rateLimited = false; try { @@ -560,7 +569,12 @@ export class StackOneToolSet { `Unexpected /accounts response shape: expected a list, got ${jsonType(accounts)}`, ); } - this.#endUserIds = endUserIdsOf(accounts); + if ( + requestGeneration === this.#endUserIdsGeneration && + cacheGeneration === this.#cacheGeneration + ) { + this.#endUserIds = endUserIdsOf(accounts); + } return accounts as StackOneAccount[]; } From 4c506d0f046a86e9f08f02bbe5a454359545dc02 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 09:34:24 +0100 Subject: [PATCH 116/151] docs(migration): name all four headers execute() withholds from actions --- MIGRATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MIGRATION.md b/MIGRATION.md index 4444d66b..71a01135 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -185,7 +185,7 @@ await tool.execute({ body: { variables: { first: 25 } } }); A top-level `headers` argument skips header filtering when the schema declares `headers` itself as a non-object field — it's an ordinary argument that happens to be named `headers`, so it is sent as given, subject to the same JSON-value check as every other argument. Otherwise, a `headers` argument that isn't a plain object is dropped with a warning. A `headers_` argument is dropped with a warning when its value is an array or object. -`*_execute_action` serves an open `headers` object, so `toolset.execute()` passes your own headers on to the action, with the exception of those three: +`*_execute_action` serves an open `headers` object, so `toolset.execute()` passes your own headers on to the action, with the exception of those four: ```typescript await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' } }); From 2592ff2e6ffbb39dc0971769d901a279b8f7749a Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 09:42:46 +0100 Subject: [PATCH 117/151] test(vectors): sync to sdk-conformance 7347926 --- tests/vectors/header-arguments.json | 56 +++++++++++++++++++++++++++++ tests/vectors/header-names.json | 2 +- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/tests/vectors/header-arguments.json b/tests/vectors/header-arguments.json index 6207fba1..bdd2d202 100644 --- a/tests/vectors/header-arguments.json +++ b/tests/vectors/header-arguments.json @@ -1347,6 +1347,62 @@ } ] }, + { + "id": "flat-end-user-id-is-owned-uppercase", + "description": "a declared flat headers_X-End-User-Id is dropped the same as the lowercase form: the owned-name check is case-insensitive", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_X-End-User-Id": { + "type": "string" + } + } + }, + "arguments": { + "path_id": "e", + "headers_X-End-User-Id": "evil-user" + }, + "expected_arguments": { + "path_id": "e" + }, + "expected_warnings": [ + { + "argument": "headers_X-End-User-Id", + "reason": "set-by-sdk" + } + ] + }, + { + "id": "flat-end-user-id-is-owned-padded", + "description": "a declared flat headers_ x-end-user-id is dropped the same as the untrimmed form: the owned-name check trims surrounding space", + "schema": { + "type": "object", + "properties": { + "path_id": { + "type": "string" + }, + "headers_ x-end-user-id": { + "type": "string" + } + } + }, + "arguments": { + "path_id": "e", + "headers_ x-end-user-id": "evil-user" + }, + "expected_arguments": { + "path_id": "e" + }, + "expected_warnings": [ + { + "argument": "headers_ x-end-user-id", + "reason": "set-by-sdk" + } + ] + }, { "id": "flat-and-nested-together", "description": "nested and flat header arguments are filtered independently", diff --git a/tests/vectors/header-names.json b/tests/vectors/header-names.json index c800eafb..b60af92c 100644 --- a/tests/vectors/header-names.json +++ b/tests/vectors/header-names.json @@ -365,7 +365,7 @@ }, { "id": "proxy-authorization", - "description": "only the three names are owned; others are declared by the open schema", + "description": "only the four names are owned; others are declared by the open schema", "name": "Proxy-Authorization", "expected": { "forwarded": "Proxy-Authorization" From c2b8736179172e1925f02626e42afaff36fa4386 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 09:42:46 +0100 Subject: [PATCH 118/151] ci: pin sdk-conformance to 7347926 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 461cd737..4d2b57e4 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 88c9400516f9842ca81dccce747f5d3e66e1fb0a + ref: 73479260a0dd8529412fabb9158d5e77459c3165 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 552cad9d3e7e8b070799f42b464e2eb2050e541e Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 09:44:55 +0100 Subject: [PATCH 119/151] ci: run conformance against stackone-ai-python d307ed8 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 4d2b57e4..e3eb2304 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 508ee6e161a449d229081fa5c0b1ecd5622eedf5 + PYTHON_SDK_REF: d307ed857079df8e1df77c36458a64ddca752b16 steps: - name: Check conformance token is configured env: From 18a1b5a750ff489619bb5a67e1af62328bdff673 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 12:33:30 +0100 Subject: [PATCH 120/151] fix(toolsets): address the second review on multiple and non-shared accounts - execute() re-lists any account in scope that is marked failed, without waiting out FAILED_ACCOUNT_RETRY_MS, and throws connector-account-unavailable if one still fails and its provider matches the action's connector or is unknown, rather than routing to the remaining account. Providers are recorded per account from GET /accounts. - Discovery skips non-shared accounts unless includeNonShared is set, warning non-shared-accounts-skipped once per discovery. - An explicitly passed non-shared account that the API refuses for a missing end user is looked up with one GET /accounts and the request retried with its end user. - A GET /accounts result is recorded when it is newer than the last one recorded, so a newer request that fails no longer leaves the end users unwritten. - clearCatalogCache() drops in-flight listings. - The rate-limit flag clears once a retry gets a non-429 response, as in Python, so a stalled stream after a cleared 429 is a timeout, not a 429. - Tests: mixed 401 and 403 failures, and every generation and in-flight check. --- src/end-user-id.test.ts | 255 +++++++++++++++++++++++++++- src/mcp-client.ts | 67 +++++++- src/rate-limit.test.ts | 35 ++++ src/tool.ts | 40 ++--- src/toolsets.search-execute.test.ts | 100 +++++++++++ src/toolsets.test.ts | 132 ++++++++++++++ src/toolsets.ts | 250 ++++++++++++++++++++------- 7 files changed, 790 insertions(+), 89 deletions(-) diff --git a/src/end-user-id.test.ts b/src/end-user-id.test.ts index 17323bb2..c20e6b00 100644 --- a/src/end-user-id.test.ts +++ b/src/end-user-id.test.ts @@ -23,11 +23,26 @@ const ACCOUNTS = [ { id: 'acc2', provider: 'mock', status: 'active', shared: true, origin_username: 'bob' }, ]; +/** The 400 UCA's ActiveAccountGuard answers a request without the account's end user with. */ +const endUserMismatch = (accountId: string) => + HttpResponse.json( + { + statusCode: 400, + message: `x-end-user-id header does not match account end user id for account ${accountId}`, + timestamp: '2026-01-01T00:00:00.000Z', + }, + { status: 400 }, + ); + /** * Serve `GET /accounts` and `/mcp`, recording every MCP message. `accounts` is read per request, - * so a test can change what the next `GET /accounts` reports. + * so a test can change what the next `GET /accounts` reports. `guard` maps accounts to the end + * user `/mcp` requires, as UCA's ActiveAccountGuard does. */ -const serve = (initial: unknown[] | (() => Response) = ACCOUNTS) => { +const serve = ( + initial: unknown[] | (() => Response | Promise) = ACCOUNTS, + guard: Record = {}, +) => { const exchanges: McpExchange[] = []; let accounts = initial; let accountRequests = 0; @@ -55,13 +70,18 @@ const serve = (initial: unknown[] | (() => Response) = ACCOUNTS) => { }); } } + const accountId = request.headers.get('x-account-id') ?? ''; + const required = guard[accountId]; + if (required !== undefined && request.headers.get('x-end-user-id') !== required) { + return endUserMismatch(accountId); + } return app.fetch(request); }), ); return { exchanges, accountRequests: () => accountRequests, - setAccounts: (next: unknown[] | (() => Response)) => { + setAccounts: (next: unknown[] | (() => Response | Promise)) => { accounts = next; }, }; @@ -95,7 +115,7 @@ afterEach(() => { describe('x-end-user-id after account discovery', () => { it('is sent on every MCP request for a non-shared account, and never for a shared one', async () => { const { exchanges } = serve(); - const tools = await newToolSet().fetchTools(); + const tools = await newToolSet({ includeNonShared: true }).fetchTools(); await getTool(tools, 'acc1_tool_1').execute({ fields: 'name' }); await getTool(tools, 'acc2_tool_1').execute({ fields: 'name' }); @@ -116,7 +136,7 @@ describe('x-end-user-id after account discovery', () => { it('is sent on search(), execute() and submitFeedback()', async () => { const { exchanges } = serve(); - const toolset = newToolSet(); + const toolset = newToolSet({ includeNonShared: true }); await toolset.search('list items'); await toolset.execute('mock_list_items', {}, { accountIds: ['acc1'] }); @@ -150,7 +170,7 @@ describe('x-end-user-id after account discovery', () => { it('follows a tool rebound with setAccountId to its new account', async () => { const { exchanges } = serve(); - const toolset = newToolSet(); + const toolset = newToolSet({ includeNonShared: true }); await toolset.fetchAccounts(); const tool = getTool(await toolset.fetchTools({ accountIds: ['acc2'] }), 'acc1_tool_1'); @@ -175,7 +195,7 @@ describe('x-end-user-id after account discovery', () => { ['origin_username is not a string', { shared: false, origin_username: 42 }], ])('is not sent when %s', async (_case, fields) => { const { exchanges } = serve([{ id: 'acc1', status: 'active', ...fields }]); - const tools = await newToolSet().fetchTools(); + const tools = await newToolSet({ includeNonShared: true }).fetchTools(); await getTool(tools, 'acc1_tool_1').execute({}); expect(exchanges.length).toBeGreaterThan(0); @@ -277,6 +297,35 @@ describe('x-end-user-id after fetchAccounts()', () => { expect(exchanges.at(-1)?.endUserId).toBe('carol'); }); + it('is recorded by an older GET /accounts when a newer one fails', async () => { + let requests = 0; + let releaseFirst!: () => void; + const firstReleased = new Promise((resolve) => { + releaseFirst = resolve; + }); + const { exchanges } = serve(async () => { + requests += 1; + if (requests === 1) { + await firstReleased; + return HttpResponse.json(ACCOUNTS); + } + return HttpResponse.json({ message: 'boom' }, { status: 500 }); + }); + const toolset = newToolSet({ includeNonShared: true }); + + const discovering = toolset.fetchTools(); + await vi.waitFor(() => expect(requests).toBe(1)); + await expect(toolset.fetchAccounts()).rejects.toThrow(StackOneAPIError); + releaseFirst(); + await discovering; + + expect(endUserIdsFor(exchanges, 'acc1')).toEqual([ + ['initialize', 'alice'], + ['notifications/initialized', 'alice'], + ['tools/list', 'alice'], + ]); + }); + it('is kept by clearCatalogCache()', async () => { const { exchanges, accountRequests } = serve(); const toolset = newToolSet({ accountId: 'acc1' }); @@ -375,3 +424,195 @@ 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(); + + it('are skipped by default, with one warning per discovery', async () => { + const { exchanges } = serve([ + ...ACCOUNTS, + { id: 'acc0', provider: 'mock', status: 'active', shared: false, origin_username: 'dan' }, + ]); + const toolset = newToolSet(); + + expect(accountsOf(await toolset.fetchTools())).toEqual(['acc2']); + await toolset.search('list items'); + expect(warnings()).toEqual([skipped('acc0, acc1')]); + expect(exchanges.every((exchange) => exchange.accountId === 'acc2')).toBe(true); + + toolset.clearCatalogCache(); + await toolset.fetchTools(); + expect(warnings()).toEqual([skipped('acc0, acc1'), skipped('acc0, acc1')]); + }); + + it('still have their end user recorded, for when their id is passed', async () => { + const { exchanges, accountRequests } = serve(); + const toolset = newToolSet(); + await toolset.fetchTools(); + + await toolset.fetchTools({ accountIds: ['acc1'] }); + + expect(accountRequests()).toBe(1); + expect(endUserIdsFor(exchanges, 'acc1').every(([, endUserId]) => endUserId === 'alice')).toBe( + true, + ); + }); + + it('are included, without a warning, with includeNonShared', async () => { + serve(); + const tools = await newToolSet({ includeNonShared: true }).fetchTools(); + + expect(accountsOf(tools)).toEqual(['acc1', 'acc2']); + expect(warnings().filter((warning) => warning.includes('non-shared'))).toEqual([]); + }); + + it('leave an empty catalog when they are all there is', async () => { + serve([ACCOUNTS[0]]); + const toolset = newToolSet(); + + expect((await toolset.fetchTools()).toArray()).toEqual([]); + expect(await toolset.search('list items')).toEqual([]); + expect(warnings()).toEqual([skipped('acc1')]); + }); +}); + +describe('x-end-user-id for an explicit account the API says is not shared', () => { + it('is looked up once and the listing sent again with it', async () => { + const { exchanges, accountRequests } = serve(ACCOUNTS, { acc1: 'alice' }); + const toolset = newToolSet({ accountId: 'acc1' }); + + const tools = await toolset.fetchTools(); + await getTool(tools, 'acc1_tool_1').execute({}); + + expect(accountRequests()).toBe(1); + expect(endUserIdsFor(exchanges, 'acc1')).toEqual([ + ['initialize', null], + ['initialize', 'alice'], + ['notifications/initialized', 'alice'], + ['tools/list', 'alice'], + ['initialize', 'alice'], + ['notifications/initialized', 'alice'], + ['tools/call', 'alice'], + ]); + }); + + it('is looked up once and the tools/call sent again with it', async () => { + const { exchanges, accountRequests } = serve(ACCOUNTS, { acc1: 'alice' }); + const toolset = newToolSet({ accountId: 'acc2' }); + const tool = getTool(await toolset.fetchTools(), 'acc1_tool_1').setAccountId('acc1'); + + await tool.execute({}); + + expect(accountRequests()).toBe(1); + expect(endUserIdsFor(exchanges, 'acc1')).toEqual([ + ['initialize', null], + ['initialize', 'alice'], + ['notifications/initialized', 'alice'], + ['tools/call', 'alice'], + ]); + }); + + it('shares a GET /accounts already in flight', async () => { + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + const { accountRequests } = serve( + async () => { + await released; + return HttpResponse.json(ACCOUNTS); + }, + { acc1: 'alice' }, + ); + const toolset = newToolSet({ accountId: 'acc1' }); + + const fetching = toolset.fetchAccounts(); + const listing = toolset.fetchTools(); + await new Promise((resolve) => setTimeout(resolve, 20)); + release(); + await Promise.all([fetching, listing]); + + expect(accountRequests()).toBe(1); + }); + + it('shares the newest GET /accounts in flight, even once an older one settles', async () => { + const releases: Array<() => void> = []; + let requests = 0; + const { accountRequests } = serve( + async () => { + requests += 1; + if (requests === 1) { + await new Promise((resolve) => releases.push(resolve)); + return HttpResponse.json([ACCOUNTS[1]]); + } + if (requests === 2) { + await new Promise((resolve) => releases.push(resolve)); + } + return HttpResponse.json(ACCOUNTS); + }, + { acc1: 'alice' }, + ); + const toolset = newToolSet({ accountId: 'acc1' }); + + const older = toolset.fetchAccounts(); + await vi.waitFor(() => expect(requests).toBe(1)); + const newer = toolset.fetchAccounts(); + await vi.waitFor(() => expect(requests).toBe(2)); + releases[0]?.(); + await older; + const listing = toolset.fetchTools(); + await new Promise((resolve) => setTimeout(resolve, 50)); + releases[1]?.(); + await Promise.all([newer, listing]); + + expect(accountRequests()).toBe(2); + }); + + it.each([ + ['GET /accounts reports no end user for it', () => HttpResponse.json([ACCOUNTS[1]])], + ['GET /accounts fails', () => HttpResponse.json({ message: 'boom' }, { status: 500 })], + ])('throws the 400 as it came when %s', async (_case, accounts) => { + const { exchanges, accountRequests } = serve(accounts, { acc1: 'alice' }); + + const error = await newToolSet({ accountId: 'acc1' }) + .fetchTools() + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(400); + expect((error as Error).message).toContain( + 'x-end-user-id header does not match account end user id for account acc1', + ); + expect(accountRequests()).toBe(1); + expect(endUserIdsFor(exchanges, 'acc1')).toEqual([['initialize', null]]); + }); + + it('is not looked up again when one is already recorded', async () => { + const { exchanges, accountRequests } = serve([{ ...ACCOUNTS[0], origin_username: 'carol' }], { + acc1: 'alice', + }); + const toolset = newToolSet({ accountId: 'acc1' }); + await toolset.fetchAccounts(); + + await expect(toolset.fetchTools()).rejects.toThrow(StackOneAPIError); + + expect(accountRequests()).toBe(1); + expect(endUserIdsFor(exchanges, 'acc1')).toEqual([['initialize', 'carol']]); + }); + + it('is not looked up for any other 400', async () => { + const { accountRequests } = serve(); + server.use( + http.all(`${TEST_BASE_URL}/mcp`, () => + HttpResponse.json({ statusCode: 400, message: 'Bad request' }, { status: 400 }), + ), + ); + + await expect(newToolSet({ accountId: 'acc1' }).fetchTools()).rejects.toThrow(StackOneAPIError); + expect(accountRequests()).toBe(0); + }); +}); diff --git a/src/mcp-client.ts b/src/mcp-client.ts index 7ce943da..eea0a4a2 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -104,6 +104,58 @@ export function isRateLimitFailure(error: unknown): boolean { ); } +/** + * 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 { + 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; + return ( + message === `x-end-user-id header does not match account end user id for account ${accountId}` + ); +} + +/** 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. */ + recorded: (accountId: string) => string | undefined; + /** Look the account's end user up with `GET /accounts`, and return what is then recorded. */ + lookUp: (accountId: string) => Promise; +} + +/** + * Run an MCP request for `accountId` with its recorded end user, if any. + * + * An account id passed explicitly has no end user recorded until something calls + * `GET /accounts`, so a non-shared one is refused with a 400. When that happens to an account + * with nothing recorded, its end user is looked up once and, if there is one, the request is sent + * again with it. Otherwise the 400 is thrown as it came. + */ +export async function withEndUser( + accountId: string | undefined, + source: EndUserSource | undefined, + request: (endUserId: string | undefined) => Promise, +): Promise { + const recorded = accountId && source ? source.recorded(accountId) : undefined; + try { + return await request(recorded); + } catch (error) { + if (!accountId || !source || recorded !== undefined || !isEndUserMismatch(error, accountId)) { + throw error; + } + const endUserId = await source.lookUp(accountId).catch(() => undefined); + if (endUserId === undefined) { + throw error; + } + return request(endUserId); + } +} + /** A session that timed out while a 429 was being retried. */ class RateLimitTimeoutError extends Error { constructor(options: ErrorOptions) { @@ -129,23 +181,26 @@ async function withMcpSession( work: (client: Client) => Promise, ): Promise { const expiresAt = retryTiming.now() + timeout; - // Whether the request currently in flight is waiting out a 429, reset at the start of every - // request the transport sends: a 429 retried successfully on an earlier request (the - // handshake, say) must not make a later, unrelated timeout (on `tools/list`, say) look like - // a rate limit too. + // Whether the request currently in flight is waiting out a 429. Cleared as soon as a retry is + // answered with anything else, as in Python: a 429 that cleared must not make a later timeout + // — a stalled stream on that same response, or an unrelated request — look like a rate limit. let rateLimited = false; const transport = new StreamableHTTPClientTransport(new URL(endpoint), { requestInit: { headers }, // Every request the client sends, handshake included, so it never sees a 429 it could // have waited out — but never one that would outlast the session's deadline. - fetch: (url, init) => { + fetch: async (url, init) => { rateLimited = false; - return fetchWithRetry(url, init, { + const response = await fetchWithRetry(url, init, { deadline: expiresAt, onRetry: () => { rateLimited = true; }, }); + if (response.status !== 429) { + rateLimited = false; + } + return response; }, }); const client = new Client({ name: 'stackone-ai-node', version }); diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts index 6774a477..d63390d2 100644 --- a/src/rate-limit.test.ts +++ b/src/rate-limit.test.ts @@ -400,6 +400,41 @@ describe('a 429 that clears on retry, followed by an unrelated timeout', () => { `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 + // the account's timeout, so a multi-account listing skips it, as Python does. + it('reports a stalled stream on the retried request as a timeout, skipping the account', async () => { + const app = createMcpApp({ accountTools: accountMcpTools }); + 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') { + if (listAttempts++ === 0) { + return HttpResponse.json(RATE_LIMITED, { + status: 429, + headers: { 'Retry-After': '0' }, + }); + } + return new HttpResponse(new ReadableStream({ start() {} }), { + headers: { 'Content-Type': 'text/event-stream' }, + }); + } + return app.fetch(request); + }), + ); + + const tools = await newToolSet({ timeout: 300 }).fetchTools({ accountIds: ['acc1', 'acc2'] }); + + expect(listAttempts).toBe(2); + expect(tools.toArray().map((tool) => tool.name)).toEqual(['acc1_tool_1', 'acc1_tool_2']); + expect(warnings().filter((message) => message.includes('Skipping'))).toEqual([ + `[@stackone/ai] Skipping account that failed to list tools — acc2: MCP request to ${TEST_BASE_URL}/mcp timed out after 0.3s`, + ]); + }); }); describe('other statuses', () => { diff --git a/src/tool.ts b/src/tool.ts index a5232fe7..f9aee9be 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -16,7 +16,7 @@ import { declaredHeaders, sanitiseHeaderArguments, } from './headers'; -import { callMcpTool } from './mcp-client'; +import { type EndUserSource, callMcpTool, withEndUser } from './mcp-client'; import { cloneJson, foldRootComposition } from './schema'; import type { AISDKToolDefinition, @@ -368,7 +368,7 @@ export class StackOneMcpTool extends StackOneTool { readonly #endpoint: string; readonly #apiKey: string; readonly #extraHeaders: Record; - readonly #endUserIdFor: (accountId: string) => string | undefined; + readonly #endUsers: EndUserSource | undefined; readonly #timeout: number; readonly #declaredHeaders: DeclaredHeaders; @@ -382,10 +382,10 @@ export class StackOneMcpTool extends StackOneTool { timeout: number; extraHeaders?: Record; /** - * The end user of an account, sent as `x-end-user-id`. Looked up per call, so a tool - * rebound with `setAccountId` sends its new account's end user. + * Where the end user of an account, sent as `x-end-user-id`, comes from. Read per call, so + * a tool rebound with `setAccountId` sends its new account's end user. */ - endUserIdFor?: (accountId: string) => string | undefined; + endUsers?: EndUserSource; }) { const executeConfig = { kind: 'mcp', @@ -397,7 +397,7 @@ export class StackOneMcpTool extends StackOneTool { this.#endpoint = options.endpoint; this.#apiKey = options.apiKey; this.#extraHeaders = { ...options.extraHeaders }; - this.#endUserIdFor = options.endUserIdFor ?? (() => undefined); + this.#endUsers = options.endUsers; this.#timeout = options.timeout; this.#declaredHeaders = declaredHeaders(options.parameters.properties); } @@ -436,19 +436,21 @@ export class StackOneMcpTool extends StackOneTool { } const accountId = this.getAccountId(); - return callMcpTool( - { - endpoint: this.#endpoint, - headers: buildRequestHeaders({ - apiKey: this.#apiKey, - accountId, - endUserId: accountId ? this.#endUserIdFor(accountId) : undefined, - extraHeaders: this.#extraHeaders, - }), - timeout: this.#timeout, - }, - this.name, - args, + return withEndUser(accountId, this.#endUsers, (endUserId) => + callMcpTool( + { + endpoint: this.#endpoint, + headers: buildRequestHeaders({ + apiKey: this.#apiKey, + accountId, + endUserId, + extraHeaders: this.#extraHeaders, + }), + timeout: this.#timeout, + }, + this.name, + args, + ), ); } } diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index d7ef74b7..0e4031ae 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -707,3 +707,103 @@ it('keeps every search/execute error inside the StackOneError hierarchy', async serveMock(); await expect(newToolSet().execute('mock_nope')).rejects.toBeInstanceOf(StackOneError); }); + +describe('execute() while an account in scope has failed to list', () => { + const ACCOUNTS = [ + { id: 'acc1', provider: 'linear', status: 'active' }, + { id: 'acc2', provider: 'linear', status: 'active' }, + { id: 'acc3', provider: 'hibob', status: 'active' }, + ]; + const failing = new Set(); + const listed: string[] = []; + + /** Serve `accounts` from GET /accounts, and meta tools for each, failing those in `failing`. */ + const serve = (accounts: typeof ACCOUNTS) => { + server.use(http.get(`${TEST_BASE_URL}/accounts`, () => HttpResponse.json(accounts))); + const calls = fakeMetaTools( + accounts.map(({ id, provider }) => `${provider}_${id}_execute_action`), + ); + const serveListing = listMock.getMockImplementation(); + listMock.mockImplementation(async (request) => { + const accountId = request.headers['x-account-id'] as string; + listed.push(accountId); + if (failing.has(accountId)) { + throw new Error(`${accountId} is down`); + } + return (serveListing as typeof listMcpTools)(request); + }); + return calls; + }; + + beforeEach(() => { + failing.clear(); + listed.length = 0; + }); + + it('refuses when the failed account is on the action’s connector', async () => { + const calls = serve([ACCOUNTS[0], ACCOUNTS[1]] as typeof ACCOUNTS); + failing.add('acc1'); + + const error = await newToolSet() + .execute('linear_list_issues') + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ToolSetLoadError); + expect((error as 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([]); + }); + + it('runs the action when the failed account is on another provider', async () => { + const calls = serve([ACCOUNTS[0], ACCOUNTS[2]] as typeof ACCOUNTS); + failing.add('acc3'); + + await newToolSet().execute('linear_list_issues'); + + expect(calls.map(({ tool }) => tool)).toEqual(['linear_acc1_execute_action']); + }); + + it('refuses when the failed account’s provider is unknown, listing failures by account id', async () => { + const calls = serve(ACCOUNTS); + failing.add('acc3'); + failing.add('acc2'); + + // Explicit ids, so no GET /accounts has said what either failed account's provider is. + const error = await newToolSet({ accountIds: ['acc3', 'acc1', 'acc2'] }) + .execute('linear_list_issues') + .catch((caught: unknown) => caught); + + expect((error as Error).message).toBe( + `"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([]); + }); + + it('lists a failed account again at once, and then applies to whatever it serves', async () => { + const calls = serve([ACCOUNTS[0], ACCOUNTS[1]] as typeof ACCOUNTS); + failing.add('acc1'); + const toolset = newToolSet(); + await toolset.fetchTools({ mode: 'search_execute' }); + expect(listed).toEqual(['acc1', 'acc2']); + + failing.clear(); + const error = await toolset.execute('linear_list_issues').catch((caught: unknown) => caught); + + // 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/); + expect(calls).toEqual([]); + }); + + it('does not re-list when no account has failed', async () => { + serve([ACCOUNTS[0], ACCOUNTS[2]] as typeof ACCOUNTS); + const toolset = newToolSet(); + + await toolset.execute('linear_list_issues'); + await toolset.execute('hibob_list_employees'); + + expect(listed).toEqual(['acc1', 'acc3']); + }); +}); diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 85cfb0e0..345fd2dd 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -271,6 +271,60 @@ describe('account discovery', () => { expect(requests).toBe(2); }); + it('does not keep a discovery that was in flight when the cache was cleared', async () => { + let requests = 0; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, async () => { + requests += 1; + if (requests === 1) { + await released; + return HttpResponse.json([{ id: 'acc1', status: 'active' }]); + } + return HttpResponse.json([{ id: 'acc3', status: 'active' }]); + }), + ); + const toolset = newToolSet(); + + const before = toolset.fetchTools(); + await vi.waitFor(() => expect(requests).toBe(1)); + toolset.clearCatalogCache(); + release(); + await before; + + expect(names(await toolset.fetchTools())).toEqual(['acc3_tool_1']); + expect(requests).toBe(2); + }); + + it('shares the discovery started after a clear, even once the one before it settles', async () => { + let requests = 0; + const releases: Array<() => void> = []; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, async () => { + requests += 1; + await new Promise((resolve) => releases.push(resolve)); + return HttpResponse.json([{ id: 'acc1', status: 'active' }]); + }), + ); + const toolset = newToolSet(); + + const first = toolset.fetchTools(); + await vi.waitFor(() => expect(requests).toBe(1)); + toolset.clearCatalogCache(); + const second = toolset.fetchTools(); + await vi.waitFor(() => expect(requests).toBe(2)); + releases[0]?.(); + await first; + const third = toolset.fetchTools(); + releases[1]?.(); + await Promise.all([second, third]); + + expect(requests).toBe(2); + }); + it('shares one discovery between concurrent calls', async () => { let requests = 0; server.use( @@ -621,6 +675,26 @@ describe('listing', () => { expect(many).toBe(revoked); }); + it('summarises rather than rethrows when every account fails, with differing statuses', async () => { + const failures = { + a: new StackOneAPIError('revoked', 401, null), + b: new StackOneAPIError('forbidden', 403, null), + }; + fakeListing((request) => { + throw failures[accountOf(request) as 'a' | 'b']; + }); + + 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]); + }); + describe('an account that fails', () => { let now = 0; let failB = true; @@ -832,6 +906,64 @@ describe('catalog cache', () => { expect(names(await toolset.fetchTools())).toEqual(['fresh_tool']); }); + it('is not repopulated by a multi-account listing that was in flight when it was cleared', async () => { + const toolset = newToolSet({ accountIds: ['acc1', 'acc2'] }); + fakeListing((request) => { + toolset.clearCatalogCache(); + return [def(`stale_${accountOf(request)}`)]; + }); + + await toolset.fetchTools(); + fakeListing((request) => [def(`fresh_${accountOf(request)}`)]); + + expect(names(await toolset.fetchTools())).toEqual(['fresh_acc1', 'fresh_acc2']); + }); + + it('does not hand a later call a listing that was in flight when it was cleared', async () => { + const toolset = newToolSet({ accountId: 'acc1' }); + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + fakeListing(async () => { + await released; + return [def('stale_tool')]; + }); + const before = toolset.fetchTools(); + await vi.waitFor(() => expect(listMock).toHaveBeenCalledOnce()); + + toolset.clearCatalogCache(); + fakeListing(() => [def('fresh_tool')]); + const after = toolset.fetchTools(); + release(); + + expect(names(await after)).toEqual(['fresh_tool']); + expect(names(await before)).toEqual(['stale_tool']); + expect(names(await toolset.fetchTools())).toEqual(['fresh_tool']); + }); + + it('shares the listing started after a clear, even once the one before it settles', async () => { + const toolset = newToolSet({ accountId: 'acc1' }); + const releases: Array<() => void> = []; + fakeListing(async () => { + await new Promise((resolve) => releases.push(resolve)); + return [def('tool')]; + }); + + const first = toolset.fetchTools(); + await vi.waitFor(() => expect(listMock).toHaveBeenCalledTimes(1)); + toolset.clearCatalogCache(); + const second = toolset.fetchTools(); + await vi.waitFor(() => expect(listMock).toHaveBeenCalledTimes(2)); + releases[0]?.(); + await first; + const third = toolset.fetchTools(); + releases[1]?.(); + await Promise.all([second, third]); + + expect(listMock).toHaveBeenCalledTimes(2); + }); + it('hands every caller fresh tools, so rebinding one never rescopes another', async () => { const toolset = newToolSet({ accountId: 'acc1' }); const first = (await toolset.fetchTools()).getStackOneTool('acc1_tool_1'); diff --git a/src/toolsets.ts b/src/toolsets.ts index 16f4f0e2..7f0f8f89 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -8,7 +8,13 @@ import { SUBMIT_FEEDBACK_TOOL_NAME, } from './consts'; import { buildRequestHeaders, isSdkOwnedHeader } from './headers'; -import { type McpToolDefinition, isRateLimitFailure, listMcpTools } from './mcp-client'; +import { + type EndUserSource, + type McpToolDefinition, + isRateLimitFailure, + listMcpTools, + withEndUser, +} from './mcp-client'; import { cloneJson, toolParametersFromInputSchema } from './schema'; import { StackOneMcpTool, type StackOneTool, Tools, warnOnDuplicateNames } from './tool'; import type { @@ -103,6 +109,13 @@ interface StackOneToolSetBaseConfig { * Defaults to the server's own default (`'individual'`). */ toolMode?: ToolMode; + /** + * Whether account discovery — used when no account id is passed — includes non-shared accounts + * (`shared: false`). Each belongs to a single end user, so by default discovery skips them, + * with a warning, rather than put every end user's accounts in one context. Account ids + * passed explicitly are always used. Default: `false`. + */ + includeNonShared?: boolean; } /** @@ -205,11 +218,18 @@ interface CatalogEntry { endpoint: string; } -/** A cached catalog: each healthy account's listing, and when each failing one last failed. */ +/** A cached catalog: each healthy account's listing, and when and why each failing one failed. */ interface CachedCatalog { listings: ReadonlyMap; - /** On {@link retryTiming}'s clock. */ - failedAt: ReadonlyMap; + /** `at` is on {@link retryTiming}'s clock. */ + failed: ReadonlyMap; +} + +/** The catalog of an account scope: its tools, and each account left out because it failed. */ +interface ScopedCatalog { + entries: CatalogEntry[]; + /** In ascending account id order, with each failure's message. */ + failed: [accountId: string, message: string][]; } const describeError = (error: unknown): string => @@ -337,6 +357,7 @@ export class StackOneToolSet { readonly #headers: Record; readonly #timeout: number; readonly #toolMode: ToolMode | undefined; + readonly #includeNonShared: boolean; readonly #accountId: string | undefined; #accountIds: string[]; @@ -355,20 +376,39 @@ export class StackOneToolSet { readonly #catalogInFlight = new Map>(); #discoveredAccountIds: string[] | undefined; #discovering: Promise | undefined; + /** The `GET /accounts` in flight, if any, so an end-user lookup can share it. */ + #fetchingAccounts: Promise | undefined; /** - * The end user of each non-shared account, as the last successful `GET /accounts` reported it, + * The end user of each non-shared account, as the last recorded `GET /accounts` reported it, * sent as `x-end-user-id` on every MCP request for that account: the API refuses a non-shared - * account's request without it. Replaced whole on each successful `GET /accounts`, and kept - * by {@link clearCatalogCache} — it describes the accounts, not the catalog. + * account's request without it. Replaced whole, with {@link #providers}, by each successful + * `GET /accounts`, and kept by {@link clearCatalogCache} — it describes the accounts, not the + * catalog. */ #endUserIds: ReadonlyMap = new Map(); + /** The provider of each account, recorded with {@link #endUserIds}. */ + #providers: ReadonlyMap = new Map(); /** - * Bumped on every {@link fetchAccounts} call. Overlapping calls (it is public, and not - * deduplicated the way {@link #discoverAccountIds} is) can resolve out of order; capturing this - * at the start of each call and refusing to write {@link #endUserIds} back once a later call has - * started keeps the published identities from regressing to a stale response. + * Bumped at the start of every {@link fetchAccounts} call. Overlapping calls (it is public, and + * not deduplicated the way {@link #discoverAccountIds} is) can resolve out of order, so each + * records only if it started after the call whose result was last recorded + * ({@link #accountsRecorded}): a stale response never replaces a newer one, and a newer call + * that fails does not stop an older one from recording. */ - #endUserIdsGeneration = 0; + #accountsStarted = 0; + #accountsRecorded = 0; + + /** + * Where tools and listings find an account's end user: as recorded, or by looking it up with a + * `GET /accounts` — the one in flight, if there is one. + */ + readonly #endUsers: EndUserSource = { + recorded: (accountId) => this.#endUserIds.get(accountId), + lookUp: async (accountId) => { + await (this.#fetchingAccounts ?? this.fetchAccounts()); + return this.#endUserIds.get(accountId); + }, + }; /** * Bumped by {@link clearCatalogCache}. A listing already in flight when the cache is cleared * captured the generation it started under, and refuses to write back if it has moved — @@ -419,6 +459,7 @@ export class StackOneToolSet { this.#headers = { ...config.headers }; this.#timeout = config.timeout ?? config.execute?.timeout ?? DEFAULT_TIMEOUT_MS; this.#toolMode = config.toolMode; + this.#includeNonShared = config.includeNonShared ?? false; this.#accountId = config.accountId; this.#accountIds = [...(config.accountIds ?? config.execute?.accountIds ?? [])]; @@ -452,11 +493,12 @@ export class StackOneToolSet { * * Call when linked accounts change outside of {@link setAccounts} or when you need to force a * fresh fetch from the StackOne MCP endpoint. A listing already in flight will not write its - * result back into the cache. + * result back into the cache, and no later call joins it. */ clearCatalogCache(): void { this.#cacheGeneration += 1; this.#catalogCache.clear(); + this.#catalogInFlight.clear(); this.#discoveredAccountIds = undefined; this.#discovering = undefined; } @@ -487,7 +529,8 @@ export class StackOneToolSet { * * Also records the end user of every non-shared account (`shared: false`, with an * `origin_username`), which the toolset then sends as `x-end-user-id` on that account's MCP - * requests. + * requests, and every account's provider. Overlapping calls record in the order they started: + * a call's result is recorded unless one started after it has already been. * * @throws StackOneAPIError If the API answers with an error status, including a 429 that * outlasted its retries or timed out while being retried. @@ -495,9 +538,20 @@ export class StackOneToolSet { * not a JSON list (including a body that is not valid UTF-8). */ async fetchAccounts(): Promise { + const fetching = this.#requestAccounts(); + this.#fetchingAccounts = fetching; + const settled = (): void => { + if (this.#fetchingAccounts === fetching) { + this.#fetchingAccounts = undefined; + } + }; + fetching.then(settled, settled); + return fetching; + } + + async #requestAccounts(): Promise { const url = `${this.#baseUrl.replace(/\/+$/, '')}/accounts`; - const cacheGeneration = this.#cacheGeneration; - const requestGeneration = ++this.#endUserIdsGeneration; + const started = ++this.#accountsStarted; let response: Response; let rateLimited = false; try { @@ -569,11 +623,10 @@ export class StackOneToolSet { `Unexpected /accounts response shape: expected a list, got ${jsonType(accounts)}`, ); } - if ( - requestGeneration === this.#endUserIdsGeneration && - cacheGeneration === this.#cacheGeneration - ) { + if (started > this.#accountsRecorded) { + this.#accountsRecorded = started; this.#endUserIds = endUserIdsOf(accounts); + this.#providers = providersOf(accounts); } return accounts as StackOneAccount[]; } @@ -588,6 +641,9 @@ export class StackOneToolSet { * For organisations with many linked accounts, discovery lists the catalog of every one of * them: pass explicit `accountIds` to avoid the round trips and the context they cost. * + * Non-shared accounts are skipped, with a warning, unless `includeNonShared` is set: each + * belongs to a single end user, and one context should not mix every end user's accounts. + * * @throws ToolSetConfigError If the key has no accounts, or none are active. */ async #discoverAccountIds(): Promise { @@ -628,10 +684,20 @@ export class StackOneToolSet { `None of this API key's ${accounts.length} linked accounts are active: ${listed}. Re-link them in the StackOne dashboard, or pass an account id explicitly.`, ); } + const nonShared = new Set( + accounts.filter((account) => account?.shared === false).map((account) => account.id), + ); + const usable = this.#includeNonShared ? active : active.filter((id) => !nonShared.has(id)); + const skipped = active.filter((id) => !usable.includes(id)).sort(); + 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.`, + ); + } if (generation === this.#cacheGeneration) { - this.#discoveredAccountIds = active; + this.#discoveredAccountIds = usable; } - return active; + return usable; } /** @@ -682,31 +748,48 @@ export class StackOneToolSet { * A 429 that outlasted its retries is not the account's fault but the key's, so it fails the * whole listing instead: skipping it would hand back a catalog missing whichever accounts * happened to be throttled. When every account fails, see {@link allAccountsFailed}. + * + * With `retryFailed`, every failed account is listed again now, due or not. A listing already + * in flight is joined either way: the failed accounts all failed in one listing, so they fall + * due together, and it is listing every one of them. A scope with no accounts — discovery + * skipped them all — has an empty catalog. */ - async #catalog(scope: readonly string[], mode: ToolMode | undefined): Promise { + async #catalog( + scope: readonly string[], + mode: ToolMode | undefined, + retryFailed = false, + ): 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]] : []; + }), + }); + if (scope.length === 0) { + return { entries: [], failed: [] }; + } const key = this.#cacheKey(scope, mode); - const inScopeOrder = (listings: CachedCatalog['listings']): CatalogEntry[] => - scope.flatMap((accountId) => listings.get(accountId) ?? []); const cached = this.#catalogCache.get(key); const now = retryTiming.now(); const due = cached - ? [...cached.failedAt] - .filter(([, failedAt]) => now - failedAt >= FAILED_ACCOUNT_RETRY_MS) + ? [...cached.failed] + .filter(([, { at }]) => retryFailed || now - at >= FAILED_ACCOUNT_RETRY_MS) .map(([accountId]) => accountId) : scope; if (cached && due.length === 0) { - return inScopeOrder(cached.listings); + return inScope(cached); } const inFlight = this.#catalogInFlight.get(key); if (inFlight) { - return inScopeOrder((await inFlight).listings); + return inScope(await inFlight); } const listing = this.#listCatalog(key, scope, due, cached, mode); this.#catalogInFlight.set(key, listing); try { - return inScopeOrder((await listing).listings); + return inScope(await listing); } finally { if (this.#catalogInFlight.get(key) === listing) { this.#catalogInFlight.delete(key); @@ -730,16 +813,18 @@ export class StackOneToolSet { const generation = this.#cacheGeneration; const endpoint = this.#endpoint(mode); const listAccount = async (accountId: string): Promise => { - const definitions = await listMcpTools({ - endpoint, - headers: buildRequestHeaders({ - apiKey: this.#apiKey, - accountId, - endUserId: this.#endUserIds.get(accountId), - extraHeaders: this.#headers, + const definitions = await withEndUser(accountId, this.#endUsers, (endUserId) => + listMcpTools({ + endpoint, + headers: buildRequestHeaders({ + apiKey: this.#apiKey, + accountId, + endUserId, + extraHeaders: this.#headers, + }), + timeout: this.#timeout, }), - timeout: this.#timeout, - }); + ); return definitions.map((definition) => ({ definition, accountId, endpoint })); }; const store = (catalog: CachedCatalog): void => { @@ -751,7 +836,7 @@ export class StackOneToolSet { if (scope.length === 1) { const accountId = scope[0] as string; const listings = new Map([[accountId, await listAccount(accountId)]]); - const catalog = { listings, failedAt: new Map() }; + const catalog = { listings, failed: new Map() }; store(catalog); return catalog; } @@ -763,13 +848,13 @@ export class StackOneToolSet { isRateLimitFailure, ); const listings = new Map(cached?.listings); - const failedAt = new Map(cached?.failedAt); + const failed = new Map(cached?.failed); const failures: [accountId: string, reason: unknown][] = []; settled.forEach((outcome, index) => { const accountId = due[index] as string; if (outcome.status === 'fulfilled') { listings.set(accountId, outcome.value); - failedAt.delete(accountId); + failed.delete(accountId); } else { failures.push([accountId, outcome.reason]); } @@ -779,10 +864,11 @@ export class StackOneToolSet { } const failedNow = retryTiming.now(); for (const [accountId, reason] of failures) { - warn(`Skipping account that failed to list tools — ${accountId}: ${describeError(reason)}`); - failedAt.set(accountId, failedNow); + const message = describeError(reason); + warn(`Skipping account that failed to list tools — ${accountId}: ${message}`); + failed.set(accountId, { at: failedNow, message }); } - const catalog = { listings, failedAt }; + const catalog = { listings, failed }; store(catalog); return catalog; } @@ -803,7 +889,7 @@ export class StackOneToolSet { accountId, timeout: this.#timeout, extraHeaders: this.#headers, - endUserIdFor: (id) => this.#endUserIds.get(id), + endUsers: this.#endUsers, }); } @@ -830,13 +916,24 @@ export class StackOneToolSet { * differing reasons, its `cause` is an `AggregateError` of each account's error. */ async fetchTools(options: FetchToolsOptions = {}): Promise { + return (await this.#fetchTools(options)).tools; + } + + /** + * {@link fetchTools}, also returning the accounts left out because they failed to list. With + * `retryFailed`, those are listed again first — see {@link #catalog}. + */ + async #fetchTools( + options: FetchToolsOptions, + retryFailed = false, + ): Promise<{ tools: Tools; failed: ScopedCatalog['failed'] }> { try { const mode = options.mode === undefined ? this.#toolMode : (options.mode ?? undefined); const scope = await this.#resolveAccountScope(options.accountIds); - const listing = await this.#catalog(scope, mode); + const { entries, failed } = await this.#catalog(scope, mode, retryFailed); let seenFeedbackTool = false; - let tools = listing + let tools = entries .filter(({ definition }) => { // Global rather than account-scoped, so every account's listing carries an // identical copy. Keep the first. @@ -859,7 +956,7 @@ export class StackOneToolSet { } warnOnDuplicateNames(tools); - return new Tools(tools); + return { tools: new Tools(tools), failed }; } catch (error) { // StackOneAPIError carries the HTTP status. Re-wrapping it would throw that away, so a // caller could not tell a 401 from a 429. @@ -881,9 +978,16 @@ export class StackOneToolSet { async #metaTools( suffix: string, accountIds: string[] | null | undefined, - ): Promise { - const tools = await this.fetchTools({ accountIds, mode: 'search_execute' }); - return tools.getStackOneTools().filter((tool) => tool.name.endsWith(suffix)); + retryFailed = false, + ): Promise<{ tools: StackOneTool[]; failed: ScopedCatalog['failed'] }> { + const { tools, failed } = await this.#fetchTools( + { accountIds, mode: 'search_execute' }, + retryFailed, + ); + return { + tools: tools.getStackOneTools().filter((tool) => tool.name.endsWith(suffix)), + failed, + }; } /** @@ -921,7 +1025,7 @@ export class StackOneToolSet { throw new ToolSetConfigError(`query must be a string, got ${typeof query}`); } - const tools = await this.#metaTools('_search_actions', options.accountIds); + const { tools } = await this.#metaTools('_search_actions', options.accountIds); if (tools.length === 0) { return []; } @@ -997,7 +1101,9 @@ export class StackOneToolSet { * `account_id` to run the action on the account that found it. * @throws ToolSetConfigError If the arguments are malformed, or the action's connector is * linked on more than one account and the call names none. - * @throws ToolSetLoadError If no linked connector serves the action. + * @throws ToolSetLoadError If no linked connector serves the action, or an account in scope + * failed to list — after being listed again now — and its provider is the action's + * connector or unknown. * @throws StackOneAPIError If the action fails. */ async execute( @@ -1022,9 +1128,22 @@ export class StackOneToolSet { const suffix = '_execute_action'; const lowered = actionId.toLowerCase(); - const matches = (await this.#metaTools(suffix, options.accountIds)).filter((tool) => - lowered.startsWith(`${connectorOf(tool, suffix)}_`), - ); + const { tools, failed } = await this.#metaTools(suffix, options.accountIds, true); + + // An account that failed to list may serve this action too: its own connector's, or one we + // cannot tell. Running on whichever account did list would pick for the caller — possibly + // another end user's account — so refuse until it lists, or the caller names an account. + const unlisted = failed.filter(([accountId]) => { + const provider = this.#providers.get(accountId); + return provider === undefined || lowered.startsWith(`${provider.toLowerCase()}_`); + }); + if (unlisted.length > 0) { + throw new ToolSetLoadError( + `${JSON.stringify(actionId)} may be served by an account that failed to list (${unlisted.map(([accountId, message]) => `${accountId}: ${message}`).join('; ')}). Pass the account id to use, such as a search hit's account_id.`, + ); + } + + const matches = tools.filter((tool) => lowered.startsWith(`${connectorOf(tool, suffix)}_`)); if (matches.length === 0) { throw new ToolSetLoadError( `No connector found for ${JSON.stringify(actionId)}. Use search() to discover valid action ids.`, @@ -1163,6 +1282,23 @@ function endUserIdsOf(accounts: readonly unknown[]): Map { return endUserIds; } +/** 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); + } + } + return providers; +} + /** * The error for a listing in which every account failed. * From 10059fdf873950388599aadc320966f78d483129 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 12:33:30 +0100 Subject: [PATCH 121/151] docs: describe non-shared discovery, the failed-account refusal and the end-user lookup --- MIGRATION.md | 6 +++--- README.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 71a01135..fd065524 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -95,7 +95,7 @@ const result = await toolset.execute( ); ``` -`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id` and the `account_id` that found it, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `topK` caps the whole result, as in 2.x, after ranking across every connector; the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` unless `accountIds` picks one, such as `[hit.account_id]`. `execute()` raises rather than returning `{ error }`: `ToolSetConfigError` before any request when `actionId`, `args` or `sessionId` is malformed, `ToolArgumentsError` when the arguments cannot be encoded as JSON (NaN or Infinity, a `Date`, a circular reference, for example), `ToolSetLoadError` when no linked connector serves the action, and `StackOneAPIError` when the action fails, including when the server rejects the arguments. +`searchTools()`, `searchActionNames()`, `getSearchTool()`, `getSearchConfig()` and `getTools()` are removed. `search()` returns plain objects carrying `action_id` and the `account_id` that found it, plus `description`, `similarity_score`, `input_schema`, `example_request` and `session_id` when the server sends them. `topK` caps the whole result, as in 2.x, after ranking across every connector; the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` unless `accountIds` picks one, such as `[hit.account_id]`. `execute()` raises rather than returning `{ error }`: `ToolSetConfigError` before any request when `actionId`, `args` or `sessionId` is malformed, `ToolArgumentsError` when the arguments cannot be encoded as JSON (NaN or Infinity, a `Date`, a circular reference, for example), `ToolSetLoadError` when no linked connector serves the action or an account in scope that may serve it still fails to list, and `StackOneAPIError` when the action fails, including when the server rejects the arguments. To give a model the search and execute tools, set the tool mode on the toolset. `openai()` no longer takes `mode`. @@ -193,9 +193,9 @@ await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' ## Accounts -**With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active account. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. +**With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active account, skipping non-shared ones (`shared: false`) with a warning unless you pass `includeNonShared: true`. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. -**Non-shared accounts get `x-end-user-id` automatically.** The API refuses an MCP request for a non-shared account unless `x-end-user-id` carries that account's end user. Whenever the SDK calls `GET /accounts` (discovery or `fetchAccounts()`), it records the `origin_username` of every account with `shared: false` and sends it as `x-end-user-id` on every MCP request for that account, overriding a value from the `headers` option. With explicit account ids the SDK makes no `GET /accounts` and sends no `x-end-user-id` of its own: call `fetchAccounts()` once, or set it in `headers`, which is passed through as given. +**Non-shared accounts get `x-end-user-id` automatically.** The API refuses an MCP request for a non-shared account unless `x-end-user-id` carries that account's end user. Whenever the SDK calls `GET /accounts` (discovery or `fetchAccounts()`), it records the `origin_username` of every account with `shared: false` and sends it as `x-end-user-id` on every MCP request for that account, overriding a value from the `headers` option. With explicit account ids the SDK makes no `GET /accounts` up front; if the API then refuses a request for want of an end user, it calls `GET /accounts` once and retries with the recorded one, or throws the API's 400. A value set in `headers` is passed through as given when nothing is recorded. **`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. A toolset constructed with no account while `STACKONE_ACCOUNT_ID` is set to a non-empty value warns that it is ignored. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: diff --git a/README.md b/README.md index 7a4897ef..0adff726 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ for (const account of await toolset.fetchAccounts()) { > If your organisation has many linked accounts, discovery lists the catalog of every one of them. Pass explicit `accountIds` to avoid the round trips and the model context they cost. -A non-shared account (`shared: false` in `GET /accounts`) belongs to one end user, and the API refuses its MCP requests unless they carry that user's id in `x-end-user-id`. Whenever the toolset calls `GET /accounts` — for discovery, or through `fetchAccounts()` — it records each non-shared account's `origin_username` and sends it as `x-end-user-id` on every MCP request for that account, replacing any value from the `headers` option. With explicit account ids and no `GET /accounts`, it sends none: call `fetchAccounts()` once, or pass `headers: { 'x-end-user-id': '…' }` yourself. +A non-shared account (`shared: false` in `GET /accounts`) belongs to one end user, and the API refuses its MCP requests unless they carry that user's id in `x-end-user-id`. Discovery skips non-shared accounts, with a warning naming them, so a toolset built with only an API key never puts every end user's accounts in one context: pass their account ids, or `includeNonShared: true`, to use them. Whenever the toolset calls `GET /accounts` — for discovery, or through `fetchAccounts()` — it records each non-shared account's `origin_username` and sends it as `x-end-user-id` on every MCP request for that account, replacing any value from the `headers` option. With explicit account ids and nothing recorded for one, the API's refusal makes the toolset call `GET /accounts` once and, if that names the account's end user, send the request again with it; otherwise the API's 400 is thrown. Overlapping `GET /accounts` calls are recorded in the order they started. ### Account IDs @@ -313,7 +313,7 @@ const result = await toolset.execute(best.action_id, best.example_request, { - The connector is the longest one whose name prefixes the action id, so `browser_linkedin_*` actions are not routed to `browser`. - `action_id` is always the one you pass: an `action_id` inside `args` — for example, one a prompt-injected model put there — is ignored. - Each hit carries the `session_id` of the search that found it, when the server issued one. Pass it back as `sessionId` to link the calls together. -- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. +- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list, `execute()` lists it again at once, and if it still fails and its provider is the action's connector or unknown, throws `ToolSetLoadError` rather than run the action on whichever account did list. - `topK` (1–50, default 10) caps the whole result, after ranking across every connector. A connector that fails to search is skipped with a warning, unless every connector fails. [View full example](examples/search-and-execute.ts) @@ -386,7 +386,7 @@ This is especially useful when you want to: - Focus on specific HR/CRM/ATS providers - Get only certain types of operations (e.g., all "list" operations) -The catalog is cached per account scope and mode, so changing a filter never refetches it. Call `clearCatalogCache()` after linking or unlinking accounts. An account that fails to list tools is skipped with a warning and left out of the cached catalog for 30 seconds, after which the next call lists it again. If every account fails with the same HTTP status (a revoked key's 401, say), that `StackOneAPIError` is thrown; otherwise a `ToolSetLoadError` whose `cause` holds each account's error. +The catalog is cached per account scope and mode, so changing a filter never refetches it. Call `clearCatalogCache()` after linking or unlinking accounts; a listing already in flight is neither cached nor shared with later calls. An account that fails to list tools is skipped with a warning and left out of the cached catalog for 30 seconds, after which the next call lists it again. If every account fails with the same HTTP status (a revoked key's 401, say), that `StackOneAPIError` is thrown; otherwise a `ToolSetLoadError` whose `cause` holds each account's error. ### Tool schemas From 454c80eb99c3452f2cf246e2e01375dece5a2319 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 12:52:34 +0100 Subject: [PATCH 122/151] fix(toolsets): don't cache a listing scoped by a discovery from before a clear The generation is taken when fetchTools() starts, not when its listing does, as in Python: a clear while GET /accounts is out left the catalog it then listed cached. A listing from an older generation is neither joined nor shared. --- src/toolsets.test.ts | 29 +++++++++++++++++++++++++++++ src/toolsets.ts | 18 +++++++++++++----- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index 345fd2dd..dfcd92d0 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -299,6 +299,35 @@ describe('account discovery', () => { expect(requests).toBe(2); }); + it('does not cache a listing scoped by a discovery from before a clear', async () => { + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + let requests = 0; + server.use( + http.get(`${TEST_BASE_URL}/accounts`, async () => { + requests += 1; + if (requests === 1) { + await released; + } + return HttpResponse.json([{ id: 'acc1', status: 'active' }]); + }), + ); + fakeListing((request) => [def(`${accountOf(request)}_tool`)]); + const toolset = newToolSet(); + + // The clear lands while GET /accounts is out, so the listing starts after it. + const before = toolset.fetchTools(); + await vi.waitFor(() => expect(requests).toBe(1)); + toolset.clearCatalogCache(); + release(); + await before; + await toolset.fetchTools(); + + expect(listMock.mock.calls.map(([request]) => accountOf(request))).toEqual(['acc1', 'acc1']); + }); + it('shares the discovery started after a clear, even once the one before it settles', async () => { let requests = 0; const releases: Array<() => void> = []; diff --git a/src/toolsets.ts b/src/toolsets.ts index 7f0f8f89..e499d3fd 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -757,6 +757,7 @@ export class StackOneToolSet { async #catalog( scope: readonly string[], mode: ToolMode | undefined, + generation: number, retryFailed = false, ): Promise { const inScope = ({ listings, failed }: CachedCatalog): ScopedCatalog => ({ @@ -781,13 +782,17 @@ export class StackOneToolSet { return inScope(cached); } + // A listing that started before a clear is not joined: it belongs to the old generation. const inFlight = this.#catalogInFlight.get(key); - if (inFlight) { + if (inFlight && generation === this.#cacheGeneration) { return inScope(await inFlight); } - const listing = this.#listCatalog(key, scope, due, cached, mode); - this.#catalogInFlight.set(key, listing); + const listing = this.#listCatalog(key, scope, due, cached, mode, generation); + // Only a current listing is shared, so no later call can join one from before a clear. + if (generation === this.#cacheGeneration) { + this.#catalogInFlight.set(key, listing); + } try { return inScope(await listing); } finally { @@ -809,8 +814,8 @@ export class StackOneToolSet { due: readonly string[], cached: CachedCatalog | undefined, mode: ToolMode | undefined, + generation: number, ): Promise { - const generation = this.#cacheGeneration; const endpoint = this.#endpoint(mode); const listAccount = async (accountId: string): Promise => { const definitions = await withEndUser(accountId, this.#endUsers, (endUserId) => @@ -929,8 +934,11 @@ export class StackOneToolSet { ): Promise<{ tools: Tools; failed: ScopedCatalog['failed'] }> { try { const mode = options.mode === undefined ? this.#toolMode : (options.mode ?? undefined); + // Taken before discovery: a clear while GET /accounts is out must stop this call's + // listing being cached, as it was scoped by accounts discovered before the clear. + const generation = this.#cacheGeneration; const scope = await this.#resolveAccountScope(options.accountIds); - const { entries, failed } = await this.#catalog(scope, mode, retryFailed); + const { entries, failed } = await this.#catalog(scope, mode, generation, retryFailed); let seenFeedbackTool = false; let tools = entries From c5f2537d1b6d6b7a1bb214e1a19e7d752b271139 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 13:07:01 +0100 Subject: [PATCH 123/151] test(vectors): sync to sdk-conformance f36bb79 and grade the two new messages --- .github/workflows/ci.yaml | 2 +- src/vectors.test.ts | 45 ++++++++++++++++++++++++++++++++++ tests/vectors/messages.json | 48 +++++++++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e3eb2304..926b8bda 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 73479260a0dd8529412fabb9158d5e77459c3165 + ref: f36bb7929857f45a7fba39801d9b5154926e01c0 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false diff --git a/src/vectors.test.ts b/src/vectors.test.ts index 617a5db5..ec4000a3 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -594,6 +594,51 @@ const emitters: Record< }, }; }, + 'connector-account-unavailable': async () => { + listMock.mockImplementation(async ({ headers }) => { + const account = headers['x-account-id']; + if (account === 'acc2') { + throw new Error('boom'); + } + return [{ name: `linear_${account}_execute_action`, description: '', inputSchema: {} }]; + }); + respondToCalls(() => ({ data: {} })); + // Explicit ids: no GET /accounts, so acc2's provider is unknown and it blocks. + return { + emitted: { + error: await errorOf(() => + newToolSet({ accountIds: ['acc1', 'acc2'] }).execute('linear_list_issues'), + ), + }, + values: { action_id: 'linear_list_issues', failures: 'acc2: boom' }, + }; + }, + 'non-shared-accounts-skipped': async () => { + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json([ + { id: 'acc1', provider: 'linear', status: 'active', shared: true }, + { + id: 'acc3', + provider: 'linear', + status: 'active', + shared: false, + origin_username: 'u3', + }, + { + id: 'acc2', + provider: 'linear', + status: 'active', + shared: false, + origin_username: 'u2', + }, + ]), + ), + ); + listByAccount(['linear_acc1_execute_action']); + await newToolSet().fetchTools(); + return { emitted: { warnings: warnings() }, values: { count: 2, accounts: 'acc2, acc3' } }; + }, 'account-id-env-ignored': async () => { vi.stubEnv('STACKONE_ACCOUNT_ID', 'acc-1'); try { diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index a788c4ec..5e3b3e62 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -1049,6 +1049,54 @@ "node": true }, "notes": "Emitted once at construction when the toolset's headers option names Authorization, x-account-id or User-Agent (any case, surrounding whitespace ignored). x-end-user-id is allowed in this option and is not warned about. The option's other headers go on every request, GET /accounts included, beneath the SDK's own." + }, + { + "id": "connector-account-unavailable", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "{action_id} may be served by an account that failed to list ({failures}). Pass the account id to use, such as a search hit's account_id.", + "placeholders": { + "action_id": { + "format": "json", + "description": "the action id execute() was called with, JSON-quoted as in ambiguous-connector" + }, + "failures": { + "format": "text", + "description": "each failed account as \"{account_id}: {error}\", where {error} is the failure's own message (as in skip-account), in ascending account-id order, joined by \"; \" — same format as all-accounts-failed" + } + }, + "python": "{action_id} may be served by an account that failed to list ({failures}). Pass the account id to use, such as a search hit's account_id.", + "node": "{action_id} may be served by an account that failed to list ({failures}). Pass the account id to use, such as a search hit's account_id.", + "matches": { + "python": true, + "node": true + }, + "notes": "Raised by execute() when an account in scope is marked failed and, after an immediate re-list, still fails, and that account's provider (from GET /accounts) matches the action's connector or is unknown (no GET /accounts record). A failed account on a different known provider does not block routing to the remaining account." + }, + { + "id": "non-shared-accounts-skipped", + "kind": "warning", + "template": "Discovery skipped {count} 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.", + "placeholders": { + "count": { + "format": "integer", + "description": "how many non-shared accounts were skipped" + }, + "accounts": { + "format": "text", + "description": "the skipped accounts' ids, ascending, joined by \", \"" + } + }, + "python": "Discovery skipped {count} 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.", + "node": "Discovery skipped {count} 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.", + "matches": { + "python": true, + "node": true + }, + "notes": "Emitted once per discovery (fetchTools / search) that skips any account with shared === false from GET /accounts, unless the toolset opts in: Python include_non_shared=True, Node includeNonShared: true. End-user ids are still recorded from every GET /accounts regardless." } ], "unshared": [ From 1e07443be1aad6194818e5ce97915b3ee1777afd Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 13:07:25 +0100 Subject: [PATCH 124/151] ci: run conformance against stackone-ai-python 7db755c --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 926b8bda..7c132a11 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: d307ed857079df8e1df77c36458a64ddca752b16 + PYTHON_SDK_REF: 7db755ca65783f4071474cce05a46848bda49f78 steps: - name: Check conformance token is configured env: From 2f50a5e65eb182dfa748877e2c6ce57b934bf0f2 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 13:30:18 +0100 Subject: [PATCH 125/151] fix(toolsets): refuse only for a failed account on the action's own connector, and keep a lookup 429 fatal - execute() compares a failed account's provider with the action's connector, the longest prefix among listed connectors and known providers, as it routes: a failed `linear` account no longer blocks a `linear_beta_*` action. - A 429 from the end-user lookup's GET /accounts is rethrown, and a GET /accounts 429 now counts as a rate-limit failure, so it stays fatal to a fan-out instead of skipping the account. - The end-user refusal is matched on the guard's fixed wording, not the account id it ends with. --- src/end-user-id.test.ts | 44 +++++++++++++++++++++++++++++ src/mcp-client.ts | 33 ++++++++++++++++++---- src/toolsets.search-execute.test.ts | 14 +++++++++ src/toolsets.ts | 19 ++++++++++++- 4 files changed, 104 insertions(+), 6 deletions(-) diff --git a/src/end-user-id.test.ts b/src/end-user-id.test.ts index c20e6b00..ec6a4d1f 100644 --- a/src/end-user-id.test.ts +++ b/src/end-user-id.test.ts @@ -604,6 +604,50 @@ describe('x-end-user-id for an explicit account the API says is not shared', () expect(endUserIdsFor(exchanges, 'acc1')).toEqual([['initialize', 'carol']]); }); + it('stays fatal to a fan-out when the lookup is rate limited', async () => { + serve(ACCOUNTS, { acc1: 'alice' }); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json( + { statusCode: 429, message: 'Too many requests' }, + { status: 429, headers: { 'Retry-After': '0' } }, + ), + ), + ); + + // acc2 lists fine; acc1 needs the lookup, which is rate limited. Skipping acc1 would hand + // back a partial catalog, so the call fails with the 429 instead. + const error = await newToolSet({ accountIds: ['acc1', 'acc2'] }) + .fetchTools() + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + }); + + it('is looked up whatever the refusal names the account as', async () => { + serve(ACCOUNTS, { acc1: 'alice' }); + 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') + ? undefined + : HttpResponse.json( + { + statusCode: 400, + message: + 'x-end-user-id header does not match account end user id for account "acc1"', + }, + { status: 400 }, + ), + ), + ); + + // Without the lookup, the reworded refusal would be thrown; with it, acc1 lists. + const tools = await newToolSet({ accountId: 'acc1' }).fetchTools(); + expect(tools.toArray().length).toBeGreaterThan(0); + }); + it('is not looked up for any other 400', async () => { const { accountRequests } = serve(); server.use( diff --git a/src/mcp-client.ts b/src/mcp-client.ts index eea0a4a2..1d5e98dc 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -100,23 +100,39 @@ export function isRateLimitFailure(error: unknown): boolean { return ( error instanceof StackOneAPIError && error.statusCode === 429 && - (error.cause instanceof StreamableHTTPError || error.cause instanceof RateLimitTimeoutError) + (error.cause instanceof StreamableHTTPError || + error.cause instanceof RateLimitTimeoutError || + error.cause instanceof HttpRateLimitError) ); } +/** + * The cause of a `StackOneAPIError` 429 that a plain HTTP request (`GET /accounts`) was answered + * with after its retries, so {@link isRateLimitFailure} reads it as the rate limit it is. + */ +export class HttpRateLimitError extends Error { + constructor(url: string) { + super(`${url} answered 429 after every retry`); + this.name = 'HttpRateLimitError'; + } +} + /** * 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): boolean { 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; + // Matched on the guard's fixed wording, not the account id it ends with, so a change to how + // the id is written does not silently turn the lookup off. return ( - message === `x-end-user-id header does not match account end user id for account ${accountId}` + typeof message === 'string' && + message.startsWith('x-end-user-id header does not match account end user id') ); } @@ -145,10 +161,17 @@ export async function withEndUser( try { return await request(recorded); } catch (error) { - if (!accountId || !source || recorded !== undefined || !isEndUserMismatch(error, accountId)) { + if (!accountId || !source || recorded !== undefined || !isEndUserMismatch(error)) { throw error; } - const endUserId = await source.lookUp(accountId).catch(() => undefined); + // A failed lookup leaves the refusal to be thrown, except a rate limit: that is the key's, + // not the account's, and must stay fatal to a fan-out. + const endUserId = await source.lookUp(accountId).catch((lookupError: unknown) => { + if (isRateLimitFailure(lookupError)) { + throw lookupError; + } + return undefined; + }); if (endUserId === undefined) { throw error; } diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 0e4031ae..50368133 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -764,6 +764,20 @@ describe('execute() while an account in scope has failed to list', () => { expect(calls.map(({ tool }) => tool)).toEqual(['linear_acc1_execute_action']); }); + it('is not blocked by a failed account on a shorter provider prefix', async () => { + // acc2's provider `linear` prefixes `linear_beta_list_items`, but the action's connector is + // `linear_beta`, the longest prefix, so acc2 could not serve it. + const calls = serve([ + { id: 'acc1', provider: 'linear_beta', status: 'active' }, + { id: 'acc2', provider: 'linear', status: 'active' }, + ]); + failing.add('acc2'); + + await newToolSet().execute('linear_beta_list_items'); + + expect(calls.map(({ tool }) => tool)).toEqual(['linear_beta_acc1_execute_action']); + }); + it('refuses when the failed account’s provider is unknown, listing failures by account id', async () => { const calls = serve(ACCOUNTS); failing.add('acc3'); diff --git a/src/toolsets.ts b/src/toolsets.ts index e499d3fd..afb61aae 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -10,6 +10,7 @@ import { import { buildRequestHeaders, isSdkOwnedHeader } from './headers'; import { type EndUserSource, + HttpRateLimitError, type McpToolDefinition, isRateLimitFailure, listMcpTools, @@ -603,6 +604,8 @@ export class StackOneToolSet { `${`Listing accounts at ${url} failed with ${response.status} ${response.statusText}`.trimEnd()}: ${text}`, response.status, text, + undefined, + response.status === 429 ? { cause: new HttpRateLimitError(url) } : undefined, ); } @@ -1141,9 +1144,23 @@ export class StackOneToolSet { // An account that failed to list may serve this action too: its own connector's, or one we // cannot tell. Running on whichever account did list would pick for the caller — possibly // another end user's account — so refuse until it lists, or the caller names an account. + // The action's connector is the longest prefix among those listed and the providers + // `GET /accounts` named, as execute() routes: a failed `browser` account cannot serve + // `browser_linkedin_search`. + const connectors = [ + ...tools.map((tool) => connectorOf(tool, suffix)), + ...[...this.#providers.values()].map((provider) => provider.toLowerCase()), + ]; + const connector = connectors + .filter((candidate) => lowered.startsWith(`${candidate}_`)) + .reduce( + (longest, candidate) => + longest === undefined || candidate.length > longest.length ? candidate : longest, + undefined, + ); const unlisted = failed.filter(([accountId]) => { const provider = this.#providers.get(accountId); - return provider === undefined || lowered.startsWith(`${provider.toLowerCase()}_`); + return provider === undefined || provider.toLowerCase() === connector; }); if (unlisted.length > 0) { throw new ToolSetLoadError( From e721aac32f994d4f15e52f4240c9375c741a3ef5 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 13:44:24 +0100 Subject: [PATCH 126/151] fix(mcp-client): match an end-user refusal by the account id it ends with, as Python does Quoted or not, rather than anywhere in the message, so a refusal naming acc10 is not read as acc1's. --- src/mcp-client.ts | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/mcp-client.ts b/src/mcp-client.ts index 1d5e98dc..246ace90 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -121,18 +121,27 @@ 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): boolean { +function isEndUserMismatch(error: unknown, accountId: string): boolean { 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; - // Matched on the guard's fixed wording, not the account id it ends with, so a change to how - // the id is written does not silently turn the lookup off. + // 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 ( + typeof message !== 'string' || + !message.startsWith('x-end-user-id header does not match account end user id') + ) { + return false; + } return ( - typeof message === 'string' && - message.startsWith('x-end-user-id header does not match account end user id') + message + .trimEnd() + .split(' ') + .pop() + ?.replace(/^["']|["']$/g, '') === accountId ); } @@ -161,7 +170,7 @@ export async function withEndUser( try { return await request(recorded); } catch (error) { - if (!accountId || !source || recorded !== undefined || !isEndUserMismatch(error)) { + if (!accountId || !source || recorded !== undefined || !isEndUserMismatch(error, accountId)) { throw error; } // A failed lookup leaves the refusal to be thrown, except a rate limit: that is the key's, From 9d332abc109934702a297e6b23c7af4c3727854a Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 13:50:44 +0100 Subject: [PATCH 127/151] ci: pin sdk-conformance to 27796bb --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 7c132a11..8714a0a1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: f36bb7929857f45a7fba39801d9b5154926e01c0 + ref: 27796bb9da96c0c7e1d58db45c2a84b316be7b00 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 213f7f1d1e13fbd8523b206791e628d7d2adc3b4 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 13:50:50 +0100 Subject: [PATCH 128/151] ci: run conformance against stackone-ai-python 8ab4a17 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 8714a0a1..eb81dd8f 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 7db755ca65783f4071474cce05a46848bda49f78 + PYTHON_SDK_REF: 8ab4a1713242a693f86f1542630f2c5cc63b31d6 steps: - name: Check conformance token is configured env: From 92bfc809f196eb5fffd42a69bf5b17798231b30c Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 17:32:47 +0100 Subject: [PATCH 129/151] fix(toolset): re-list only the failed accounts that could serve the action --- src/toolsets.search-execute.test.ts | 21 ++++++++ src/toolsets.ts | 77 +++++++++++++++++------------ 2 files changed, 67 insertions(+), 31 deletions(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 50368133..d887d0fe 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -811,6 +811,27 @@ describe('execute() while an account in scope has failed to list', () => { 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; + listMock.mockImplementation(async (request) => { + if (request.headers['x-account-id'] === 'acc3' && listed.includes('acc3')) { + listed.push('acc3'); + return new Promise(() => {}); + } + return listOnce(request); + }); + failing.add('acc3'); + const toolset = newToolSet(); + await toolset.fetchTools({ mode: 'search_execute' }); + + await toolset.execute('linear_list_issues'); + + expect(listed).toEqual(['acc1', 'acc3']); + expect(calls.map(({ tool }) => tool)).toEqual(['linear_acc1_execute_action']); + }); + it('does not re-list when no account has failed', async () => { serve([ACCOUNTS[0], ACCOUNTS[2]] as typeof ACCOUNTS); const toolset = newToolSet(); diff --git a/src/toolsets.ts b/src/toolsets.ts index afb61aae..8cd84f5e 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -295,6 +295,17 @@ function matchGlob(value: string, pattern: string): boolean { const isPlainObject = (value: unknown): value is JsonObject => typeof value === 'object' && value !== null && !Array.isArray(value); +/** The longest of `connectors` that prefixes `actionId` (both lowercase), as execute() routes. */ +function longestConnector(actionId: string, connectors: string[]): string | undefined { + return connectors + .filter((connector) => actionId.startsWith(`${connector}_`)) + .reduce( + (longest, connector) => + longest === undefined || connector.length > longest.length ? connector : longest, + undefined, + ); +} + /** * The connector a meta tool belongs to: its name minus the account id and the suffix. * @@ -752,16 +763,15 @@ export class StackOneToolSet { * whole listing instead: skipping it would hand back a catalog missing whichever accounts * happened to be throttled. When every account fails, see {@link allAccountsFailed}. * - * With `retryFailed`, every failed account is listed again now, due or not. A listing already - * in flight is joined either way: the failed accounts all failed in one listing, so they fall - * due together, and it is listing every one of them. A scope with no accounts — discovery - * skipped them all — has an empty catalog. + * The failed accounts in `retry` are listed again now, due or not. A listing already in flight + * is joined either way, and its result stands even if it was not listing them. A scope with no + * accounts — discovery skipped them all — has an empty catalog. */ async #catalog( scope: readonly string[], mode: ToolMode | undefined, generation: number, - retryFailed = false, + retry: ReadonlySet = new Set(), ): Promise { const inScope = ({ listings, failed }: CachedCatalog): ScopedCatalog => ({ entries: scope.flatMap((accountId) => listings.get(accountId) ?? []), @@ -778,7 +788,9 @@ export class StackOneToolSet { const now = retryTiming.now(); const due = cached ? [...cached.failed] - .filter(([, { at }]) => retryFailed || now - at >= FAILED_ACCOUNT_RETRY_MS) + .filter( + ([accountId, { at }]) => retry.has(accountId) || now - at >= FAILED_ACCOUNT_RETRY_MS, + ) .map(([accountId]) => accountId) : scope; if (cached && due.length === 0) { @@ -928,12 +940,12 @@ export class StackOneToolSet { } /** - * {@link fetchTools}, also returning the accounts left out because they failed to list. With - * `retryFailed`, those are listed again first — see {@link #catalog}. + * {@link fetchTools}, also returning the accounts left out because they failed to list. Those in + * `retry` are listed again first — see {@link #catalog}. */ async #fetchTools( options: FetchToolsOptions, - retryFailed = false, + retry?: ReadonlySet, ): Promise<{ tools: Tools; failed: ScopedCatalog['failed'] }> { try { const mode = options.mode === undefined ? this.#toolMode : (options.mode ?? undefined); @@ -941,7 +953,7 @@ export class StackOneToolSet { // listing being cached, as it was scoped by accounts discovered before the clear. const generation = this.#cacheGeneration; const scope = await this.#resolveAccountScope(options.accountIds); - const { entries, failed } = await this.#catalog(scope, mode, generation, retryFailed); + const { entries, failed } = await this.#catalog(scope, mode, generation, retry); let seenFeedbackTool = false; let tools = entries @@ -989,12 +1001,9 @@ export class StackOneToolSet { async #metaTools( suffix: string, accountIds: string[] | null | undefined, - retryFailed = false, + retry?: ReadonlySet, ): Promise<{ tools: StackOneTool[]; failed: ScopedCatalog['failed'] }> { - const { tools, failed } = await this.#fetchTools( - { accountIds, mode: 'search_execute' }, - retryFailed, - ); + const { tools, failed } = await this.#fetchTools({ accountIds, mode: 'search_execute' }, retry); return { tools: tools.getStackOneTools().filter((tool) => tool.name.endsWith(suffix)), failed, @@ -1139,7 +1148,7 @@ export class StackOneToolSet { const suffix = '_execute_action'; const lowered = actionId.toLowerCase(); - const { tools, failed } = await this.#metaTools(suffix, options.accountIds, true); + let { tools, failed } = await this.#metaTools(suffix, options.accountIds); // An account that failed to list may serve this action too: its own connector's, or one we // cannot tell. Running on whichever account did list would pick for the caller — possibly @@ -1147,21 +1156,27 @@ export class StackOneToolSet { // The action's connector is the longest prefix among those listed and the providers // `GET /accounts` named, as execute() routes: a failed `browser` account cannot serve // `browser_linkedin_search`. - const connectors = [ - ...tools.map((tool) => connectorOf(tool, suffix)), - ...[...this.#providers.values()].map((provider) => provider.toLowerCase()), - ]; - const connector = connectors - .filter((candidate) => lowered.startsWith(`${candidate}_`)) - .reduce( - (longest, candidate) => - longest === undefined || candidate.length > longest.length ? candidate : longest, - undefined, - ); - const unlisted = failed.filter(([accountId]) => { - const provider = this.#providers.get(accountId); - return provider === undefined || provider.toLowerCase() === connector; - }); + const inReach = (): ScopedCatalog['failed'] => { + const connector = longestConnector(lowered, [ + ...tools.map((tool) => connectorOf(tool, suffix)), + ...[...this.#providers.values()].map((provider) => provider.toLowerCase()), + ]); + return failed.filter(([accountId]) => { + const provider = this.#providers.get(accountId); + return provider === undefined || provider.toLowerCase() === connector; + }); + }; + // Listed again now rather than when due, but only those that could serve the action: + // re-listing an account on another provider would make this call wait out its timeout. + const retry = inReach(); + if (retry.length > 0) { + ({ tools, failed } = await this.#metaTools( + suffix, + options.accountIds, + new Set(retry.map(([accountId]) => accountId)), + )); + } + const unlisted = inReach(); if (unlisted.length > 0) { throw new ToolSetLoadError( `${JSON.stringify(actionId)} may be served by an account that failed to list (${unlisted.map(([accountId, message]) => `${accountId}: ${message}`).join('; ')}). Pass the account id to use, such as a search hit's account_id.`, From f012ef09f6221366115dd20f0a527525c7e95db2 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 17:34:23 +0100 Subject: [PATCH 130/151] fix(toolset): look up the providers of failed accounts named explicitly before refusing an action --- src/toolsets.search-execute.test.ts | 17 ++++++++++++++++- src/toolsets.ts | 6 ++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index d887d0fe..d304a628 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -778,12 +778,27 @@ describe('execute() while an account in scope has failed to list', () => { expect(calls.map(({ tool }) => tool)).toEqual(['linear_beta_acc1_execute_action']); }); + it('looks up the providers of failed accounts named explicitly, then runs the action', async () => { + const calls = serve([ACCOUNTS[0], ACCOUNTS[2]] as typeof ACCOUNTS); + failing.add('acc3'); + + // Explicit ids, so only the lookup can say acc3 is hibob, which cannot serve a linear action. + await newToolSet({ accountIds: ['acc1', 'acc3'] }).execute('linear_list_issues'); + + expect(calls.map(({ tool }) => tool)).toEqual(['linear_acc1_execute_action']); + }); + it('refuses when the failed account’s provider is unknown, listing failures by account id', async () => { const calls = serve(ACCOUNTS); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json({ error: 'forbidden' }, { status: 403 }), + ), + ); failing.add('acc3'); failing.add('acc2'); - // Explicit ids, so no GET /accounts has said what either failed account's provider is. + // Explicit ids, and GET /accounts fails, so neither failed account's provider is known. const error = await newToolSet({ accountIds: ['acc3', 'acc1', 'acc2'] }) .execute('linear_list_issues') .catch((caught: unknown) => caught); diff --git a/src/toolsets.ts b/src/toolsets.ts index 8cd84f5e..ff82600d 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -1166,6 +1166,12 @@ export class StackOneToolSet { return provider === undefined || provider.toLowerCase() === connector; }); }; + // With explicit account ids no GET /accounts has named the failed accounts' providers, so + // one dead account would refuse every action. Ask once — joining a lookup in flight — and + // treat the provider as unknown still if that fails too. + if (failed.some(([accountId]) => !this.#providers.has(accountId))) { + await (this.#fetchingAccounts ?? this.fetchAccounts()).catch(() => undefined); + } // Listed again now rather than when due, but only those that could serve the action: // re-listing an account on another provider would make this call wait out its timeout. const retry = inReach(); From 03b8f0c4a4f0fac25c14562db78a53931d78dff9 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 17:36:22 +0100 Subject: [PATCH 131/151] fix(mcp-client): give the end-user refusal the failed lookup as its cause --- src/end-user-id.test.ts | 20 ++++++++++++++++++++ src/mcp-client.ts | 25 +++++++++++++++++++------ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/end-user-id.test.ts b/src/end-user-id.test.ts index ec6a4d1f..ffa5b21a 100644 --- a/src/end-user-id.test.ts +++ b/src/end-user-id.test.ts @@ -591,6 +591,26 @@ describe('x-end-user-id for an explicit account the API says is not shared', () expect(endUserIdsFor(exchanges, 'acc1')).toEqual([['initialize', null]]); }); + it('throws the 400 with the failed lookup as its cause', async () => { + serve(() => HttpResponse.json({ message: 'missing scope platform.read' }, { status: 403 }), { + acc1: 'alice', + }); + + const error = await newToolSet({ accountId: 'acc1' }) + .fetchTools() + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(400); + expect((error as 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'); + }); + it('is not looked up again when one is already recorded', async () => { const { exchanges, accountRequests } = serve([{ ...ACCOUNTS[0], origin_username: 'carol' }], { acc1: 'alice', diff --git a/src/mcp-client.ts b/src/mcp-client.ts index 246ace90..9ecf6b6c 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -159,7 +159,8 @@ export interface EndUserSource { * An account id passed explicitly has no end user recorded until something calls * `GET /accounts`, so a non-shared one is refused with a 400. When that happens to an account * with nothing recorded, its end user is looked up once and, if there is one, the request is sent - * again with it. Otherwise the 400 is thrown as it came. + * again with it. Otherwise the 400 is thrown as it came — with the lookup's error as its `cause`, + * if the lookup failed. */ export async function withEndUser( accountId: string | undefined, @@ -173,14 +174,26 @@ export async function withEndUser( if (!accountId || !source || recorded !== undefined || !isEndUserMismatch(error, accountId)) { throw error; } - // A failed lookup leaves the refusal to be thrown, except a rate limit: that is the key's, - // not the account's, and must stay fatal to a fan-out. - const endUserId = await source.lookUp(accountId).catch((lookupError: unknown) => { + // 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; } - return undefined; - }); + const refusal = error as StackOneAPIError; + throw new StackOneAPIError( + refusal.message, + refusal.statusCode, + refusal.responseBody, + refusal.requestBody, + { cause: lookupError }, + ); + } if (endUserId === undefined) { throw error; } From c53fdd3a4243608062b7b60b33bbf659590f1802 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 17:37:48 +0100 Subject: [PATCH 132/151] fix(toolset): fail discovery when every active account is non-shared --- src/end-user-id.test.ts | 14 +++++++++----- src/toolsets.ts | 12 ++++++++++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/end-user-id.test.ts b/src/end-user-id.test.ts index ffa5b21a..fbfe986f 100644 --- a/src/end-user-id.test.ts +++ b/src/end-user-id.test.ts @@ -10,6 +10,7 @@ import { server } from '../mocks/node'; import { StackOneToolSet } from './toolsets'; import type { StackOneTool, Tools } from './tool'; import { StackOneAPIError } from './utils/error-stackone-api'; +import { ToolSetConfigError } from './utils/error-toolset'; /** One JSON-RPC message that reached `/mcp`, with the headers it came with. */ interface McpExchange { @@ -470,13 +471,16 @@ describe('non-shared accounts in discovery', () => { expect(warnings().filter((warning) => warning.includes('non-shared'))).toEqual([]); }); - it('leave an empty catalog when they are all there is', async () => { - serve([ACCOUNTS[0]]); + it('fail discovery, without a warning, when they are all there is', async () => { + serve([ACCOUNTS[0], { ...ACCOUNTS[0], id: 'acc0', origin_username: 'dan' }]); const toolset = newToolSet(); + const message = + "None of this API key's 2 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."; - expect((await toolset.fetchTools()).toArray()).toEqual([]); - expect(await toolset.search('list items')).toEqual([]); - expect(warnings()).toEqual([skipped('acc1')]); + await expect(toolset.fetchTools()).rejects.toBeInstanceOf(ToolSetConfigError); + await expect(toolset.fetchTools()).rejects.toThrow(message); + await expect(toolset.search('list items')).rejects.toThrow(message); + expect(warnings()).toEqual([]); }); }); diff --git a/src/toolsets.ts b/src/toolsets.ts index ff82600d..f324ddba 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -658,7 +658,8 @@ export class StackOneToolSet { * Non-shared accounts are skipped, with a warning, unless `includeNonShared` is set: each * belongs to a single end user, and one context should not mix every end user's accounts. * - * @throws ToolSetConfigError If the key has no accounts, or none are active. + * @throws ToolSetConfigError If the key has no accounts, none are active, or every active one is + * non-shared and `includeNonShared` is not set. */ async #discoverAccountIds(): Promise { if (this.#discoveredAccountIds) { @@ -702,6 +703,13 @@ export class StackOneToolSet { accounts.filter((account) => account?.shared === false).map((account) => account.id), ); const usable = this.#includeNonShared ? active : active.filter((id) => !nonShared.has(id)); + // A key with nothing usable fails, as one with no active accounts does, rather than leave + // fetchTools() empty and execute() pointing at search(). + if (usable.length === 0) { + throw new ToolSetConfigError( + `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(); if (skipped.length > 0) { warn( @@ -765,7 +773,7 @@ export class StackOneToolSet { * * The failed accounts in `retry` are listed again now, due or not. A listing already in flight * is joined either way, and its result stands even if it was not listing them. A scope with no - * accounts — discovery skipped them all — has an empty catalog. + * accounts has an empty catalog. */ async #catalog( scope: readonly string[], From 6dd4300cd7ed2232bf794d420dfb9d9d18a19e85 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 17:40:12 +0100 Subject: [PATCH 133/151] fix(toolset): say shared accounts are used, in the STACKONE_ACCOUNT_ID warning and the docs --- MIGRATION.md | 10 ++++----- README.md | 21 +++++++++++------- examples/ai-sdk-integration.ts | 2 +- examples/anthropic-integration.ts | 2 +- examples/auth-management.ts | 2 +- examples/claude-agent-sdk-integration.ts | 2 +- examples/openai-integration.ts | 2 +- examples/openai-responses-integration.ts | 2 +- src/toolsets.test.ts | 4 ++-- src/toolsets.ts | 27 ++++++++++++++---------- tests/vectors/messages.json | 6 +++--- 11 files changed, 45 insertions(+), 35 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index fd065524..eb483433 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -193,11 +193,11 @@ await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' ## Accounts -**With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active account, skipping non-shared ones (`shared: false`) with a warning unless you pass `includeNonShared: true`. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. +**With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active shared account, skipping non-shared ones (`shared: false`) with a warning unless you pass `includeNonShared: true`; if every active account is non-shared, it throws `ToolSetConfigError`. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. -**Non-shared accounts get `x-end-user-id` automatically.** The API refuses an MCP request for a non-shared account unless `x-end-user-id` carries that account's end user. Whenever the SDK calls `GET /accounts` (discovery or `fetchAccounts()`), it records the `origin_username` of every account with `shared: false` and sends it as `x-end-user-id` on every MCP request for that account, overriding a value from the `headers` option. With explicit account ids the SDK makes no `GET /accounts` up front; if the API then refuses a request for want of an end user, it calls `GET /accounts` once and retries with the recorded one, or throws the API's 400. A value set in `headers` is passed through as given when nothing is recorded. +**Non-shared accounts get `x-end-user-id` automatically.** The API refuses an MCP request for a non-shared account unless `x-end-user-id` carries that account's end user. Whenever the SDK calls `GET /accounts` (discovery or `fetchAccounts()`), it records the `origin_username` of every account with `shared: false` and sends it as `x-end-user-id` on every MCP request for that account, overriding a value from the `headers` option. With explicit account ids the SDK makes no `GET /accounts` up front; if the API then refuses a request for want of an end user, it calls `GET /accounts` once and retries with the recorded one, or throws the API's 400 (with the lookup's error as its `cause` if `GET /accounts` failed). A value set in `headers` is passed through as given when nothing is recorded. -**`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. A toolset constructed with no account while `STACKONE_ACCOUNT_ID` is set to a non-empty value warns that it is ignored. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: +**`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active shared account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. A toolset constructed with no account while `STACKONE_ACCOUNT_ID` is set to a non-empty value warns that it is ignored. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: ```typescript // 2.x: STACKONE_ACCOUNT_ID picked up implicitly @@ -207,11 +207,11 @@ const toolset = new StackOneToolSet(); const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); ``` -**An empty account id throws.** `accountId: ''`, or an empty string in `accountIds`, `execute.accountIds`, `setAccounts()` or a call's `accountIds`, now throws `ToolSetConfigError`. In 2.x an empty `accountId` fell back to `STACKONE_ACCOUNT_ID` or discovery; in 3.0 that would silently widen the toolset to every active account. So `accountId: process.env.STACKONE_ACCOUNT_ID` throws when the variable is set but empty (`STACKONE_ACCOUNT_ID=` in a `.env` file, for example): pass `process.env.STACKONE_ACCOUNT_ID || undefined`, as above. +**An empty account id throws.** `accountId: ''`, or an empty string in `accountIds`, `execute.accountIds`, `setAccounts()` or a call's `accountIds`, now throws `ToolSetConfigError`. In 2.x an empty `accountId` fell back to `STACKONE_ACCOUNT_ID` or discovery; in 3.0 that would silently widen the toolset to every active shared account. So `accountId: process.env.STACKONE_ACCOUNT_ID` throws when the variable is set but empty (`STACKONE_ACCOUNT_ID=` in a `.env` file, for example): pass `process.env.STACKONE_ACCOUNT_ID || undefined`, as above. **Listings are merged in sorted account order.** When two accounts serve the same tool name, `getTool()` returns the first one listed — now the one on the lowest account id, where 2.x followed the order you passed — and so do `executeOpenAIToolCalls()` and every adapter (`toOpenAI()`, `toAISDK()`, `toClaudeAgentSdk()` and the rest), which build one tool per name. A warning names the clashing tools. Pass `accountIds` to choose the account yourself. -**`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. In a multi-account scope, an account whose listing fails with anything other than a 429 is skipped with a warning: the healthy accounts' listings are cached, and the failed account is retried after 30 seconds. A 429 that outlasts its retries instead rejects the whole call, since a rate limit on one account is likely to hit the others too. A single-account call throws its failure rather than skipping it, since there is no other account's catalog to fall back to. +**`fetchTools()` returns fresh tool instances on every call**, never the cached `Tools`, so `setAccountId()` on one tool no longer changes what later callers get. In a multi-account scope, an account whose listing fails with anything other than a 429 is skipped with a warning: the healthy accounts' listings are cached, and the failed account is retried after 30 seconds, or straight away by an `execute()` whose action it could serve. A 429 that outlasts its retries instead rejects the whole call, since a rate limit on one account is likely to hit the others too. A single-account call throws its failure rather than skipping it, since there is no other account's catalog to fall back to. ## Feedback diff --git a/README.md b/README.md index 0adff726..23c1669f 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ for (const account of await toolset.fetchAccounts()) { > If your organisation has many linked accounts, discovery lists the catalog of every one of them. Pass explicit `accountIds` to avoid the round trips and the model context they cost. -A non-shared account (`shared: false` in `GET /accounts`) belongs to one end user, and the API refuses its MCP requests unless they carry that user's id in `x-end-user-id`. Discovery skips non-shared accounts, with a warning naming them, so a toolset built with only an API key never puts every end user's accounts in one context: pass their account ids, or `includeNonShared: true`, to use them. Whenever the toolset calls `GET /accounts` — for discovery, or through `fetchAccounts()` — it records each non-shared account's `origin_username` and sends it as `x-end-user-id` on every MCP request for that account, replacing any value from the `headers` option. With explicit account ids and nothing recorded for one, the API's refusal makes the toolset call `GET /accounts` once and, if that names the account's end user, send the request again with it; otherwise the API's 400 is thrown. Overlapping `GET /accounts` calls are recorded in the order they started. +A non-shared account (`shared: false` in `GET /accounts`) belongs to one end user, and the API refuses its MCP requests unless they carry that user's id in `x-end-user-id`. Discovery skips non-shared accounts, with a warning naming them, so a toolset built with only an API key never puts every end user's accounts in one context: pass their account ids, or `includeNonShared: true`, to use them. If every active account is non-shared, discovery throws `ToolSetConfigError` instead. Whenever the toolset calls `GET /accounts` — for discovery, or through `fetchAccounts()` — it records each non-shared account's `origin_username` and sends it as `x-end-user-id` on every MCP request for that account, replacing any value from the `headers` option. With explicit account ids and nothing recorded for one, the API's refusal makes the toolset call `GET /accounts` once and, if that names the account's end user, send the request again with it; otherwise the API's 400 is thrown, with the lookup's error as its `cause` if the lookup failed. Overlapping `GET /accounts` calls are recorded in the order they started. ### Account IDs @@ -127,7 +127,8 @@ npm install @stackone/ai openai # or: yarn/pnpm/bun add import { OpenAI } from 'openai'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +// Reads STACKONE_API_KEY from the environment. Without an account id, every active shared account +// is used (non-shared ones too with includeNonShared: true) const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools({ actions: ['workday_*'] }); @@ -165,7 +166,8 @@ npm install @stackone/ai openai # or: yarn/pnpm/bun add import OpenAI from 'openai'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +// Reads STACKONE_API_KEY from the environment. Without an account id, every active shared account +// is used (non-shared ones too with includeNonShared: true) const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools(); @@ -195,7 +197,8 @@ npm install @stackone/ai @anthropic-ai/sdk # or: yarn/pnpm/bun add import Anthropic from '@anthropic-ai/sdk'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +// Reads STACKONE_API_KEY from the environment. Without an account id, every active shared account +// is used (non-shared ones too with includeNonShared: true) const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools(); @@ -234,7 +237,8 @@ import { openai } from '@ai-sdk/openai'; import { generateText, stepCountIs } from 'ai'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +// Reads STACKONE_API_KEY from the environment. Without an account id, every active shared account +// is used (non-shared ones too with includeNonShared: true) const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); const tools = await toolset.fetchTools(); @@ -261,7 +265,8 @@ npm install @stackone/ai @anthropic-ai/claude-agent-sdk zod # or: yarn/pnpm/bun import { query } from '@anthropic-ai/claude-agent-sdk'; import { StackOneToolSet } from '@stackone/ai'; -// Reads STACKONE_API_KEY from the environment. Without an account id, every active account is used +// Reads STACKONE_API_KEY from the environment. Without an account id, every active shared account +// is used (non-shared ones too with includeNonShared: true) const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Fetch tools and convert to Claude Agent SDK format @@ -313,7 +318,7 @@ const result = await toolset.execute(best.action_id, best.example_request, { - The connector is the longest one whose name prefixes the action id, so `browser_linkedin_*` actions are not routed to `browser`. - `action_id` is always the one you pass: an `action_id` inside `args` — for example, one a prompt-injected model put there — is ignored. - Each hit carries the `session_id` of the search that found it, when the server issued one. Pass it back as `sessionId` to link the calls together. -- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list, `execute()` lists it again at once, and if it still fails and its provider is the action's connector or unknown, throws `ToolSetLoadError` rather than run the action on whichever account did list. +- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list and its provider is the action's connector or unknown, `execute()` lists it again at once (asking `GET /accounts` first for any provider it does not know), and if it still fails, throws `ToolSetLoadError` rather than run the action on whichever account did list. A failed account on another provider is not listed again, so it costs the call nothing. - `topK` (1–50, default 10) caps the whole result, after ranking across every connector. A connector that fails to search is skipped with a warning, unless every connector fails. [View full example](examples/search-and-execute.ts) @@ -386,7 +391,7 @@ This is especially useful when you want to: - Focus on specific HR/CRM/ATS providers - Get only certain types of operations (e.g., all "list" operations) -The catalog is cached per account scope and mode, so changing a filter never refetches it. Call `clearCatalogCache()` after linking or unlinking accounts; a listing already in flight is neither cached nor shared with later calls. An account that fails to list tools is skipped with a warning and left out of the cached catalog for 30 seconds, after which the next call lists it again. If every account fails with the same HTTP status (a revoked key's 401, say), that `StackOneAPIError` is thrown; otherwise a `ToolSetLoadError` whose `cause` holds each account's error. +The catalog is cached per account scope and mode, so changing a filter never refetches it. Call `clearCatalogCache()` after linking or unlinking accounts; a listing already in flight is neither cached nor shared with later calls. An account that fails to list tools is skipped with a warning and left out of the cached catalog for 30 seconds, after which the next call lists it again. `execute()` does not wait: it lists a failed account that could serve the action again straight away. If every account fails with the same HTTP status (a revoked key's 401, say), that `StackOneAPIError` is thrown; otherwise a `ToolSetLoadError` whose `cause` holds each account's error. ### Tool schemas diff --git a/examples/ai-sdk-integration.ts b/examples/ai-sdk-integration.ts index 234d62ec..aec03e93 100644 --- a/examples/ai-sdk-integration.ts +++ b/examples/ai-sdk-integration.ts @@ -29,7 +29,7 @@ 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 account linked to the key + // without one, the toolset uses every active shared account linked to the key const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Filter to specific tools to keep token usage manageable diff --git a/examples/anthropic-integration.ts b/examples/anthropic-integration.ts index 5780c2fb..535511ec 100644 --- a/examples/anthropic-integration.ts +++ b/examples/anthropic-integration.ts @@ -18,7 +18,7 @@ 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 account linked to the key + // without one, the toolset uses every active shared account linked to the key const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Filter for any relevant tools diff --git a/examples/auth-management.ts b/examples/auth-management.ts index b193cc5d..5ec144ca 100644 --- a/examples/auth-management.ts +++ b/examples/auth-management.ts @@ -53,7 +53,7 @@ const accountIdFromEnv = async (): Promise => { console.log('=== 2. Account ID from environment ===\n'); // 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 account instead. + // 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'}`); diff --git a/examples/claude-agent-sdk-integration.ts b/examples/claude-agent-sdk-integration.ts index ce63a2d5..f79219b3 100644 --- a/examples/claude-agent-sdk-integration.ts +++ b/examples/claude-agent-sdk-integration.ts @@ -24,7 +24,7 @@ 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 account linked to the key + // without one, the toolset uses every active shared account linked to the key const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Fetch tools from StackOne and convert to Claude Agent SDK format diff --git a/examples/openai-integration.ts b/examples/openai-integration.ts index fab84e2b..6937ecf7 100644 --- a/examples/openai-integration.ts +++ b/examples/openai-integration.ts @@ -18,7 +18,7 @@ if (!process.env.OPENAI_API_KEY) { 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 account linked to the key + // without one, the toolset uses every active shared account linked to the key const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Filter to specific tools to stay within OpenAI's 128-tool limit diff --git a/examples/openai-responses-integration.ts b/examples/openai-responses-integration.ts index e93130bd..65161bf8 100644 --- a/examples/openai-responses-integration.ts +++ b/examples/openai-responses-integration.ts @@ -18,7 +18,7 @@ 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 account linked to the key + // without one, the toolset uses every active shared account linked to the key const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Fetch tools via MCP diff --git a/src/toolsets.test.ts b/src/toolsets.test.ts index dfcd92d0..f2721132 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -95,7 +95,7 @@ describe('configuration', () => { newToolSet(); expect(warnSpy.mock.calls.map(([message]: unknown[]) => String(message))).toEqual([ - '[@stackone/ai] STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.', + '[@stackone/ai] 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.', ]); }); @@ -119,7 +119,7 @@ describe('configuration', () => { vi.stubEnv('STACKONE_ACCOUNT_ID', 'acc3'); newToolSet(config); expect(warnSpy.mock.calls.map(([message]: unknown[]) => String(message))).toEqual([ - '[@stackone/ai] STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.', + '[@stackone/ai] 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.', ]); }, ); diff --git a/src/toolsets.ts b/src/toolsets.ts index f324ddba..e95c8d82 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -42,7 +42,8 @@ interface SingleAccountConfig { /** * Single account ID for StackOne API operations * Use this when working with a single account. Never read from the environment: with no - * account configured, the toolset uses every active account linked to the API key. + * account configured, the toolset uses every active shared account linked to the API key + * (non-shared ones too with `includeNonShared`). */ accountId: string; } @@ -131,7 +132,8 @@ export type StackOneToolSetConfig = StackOneToolSetBaseConfig & Partial { * its `tools/call`; the only other request is `GET /accounts`, to discover accounts. Schemas and * arguments are passed through as served, never rewritten, filtered or invented. * - * An API key is enough: with no account configured, the toolset lists every active account - * linked to the key. + * An API key is enough: with no account configured, the toolset lists every active shared + * account linked to the key, and non-shared ones too with `includeNonShared`. */ export class StackOneToolSet { readonly #apiKey: string; @@ -431,7 +433,8 @@ export class StackOneToolSet { /** * Falls back to `STACKONE_API_KEY` and `STACKONE_BASE_URL`, but never reads an account id from - * the environment: `accountId` / `accountIds` must be passed, or every active account is used. + * the environment: `accountId` / `accountIds` must be passed, or every active shared account is + * used (non-shared ones too with `includeNonShared`). * When `STACKONE_ACCOUNT_ID` is set and no account is passed, that is warned about, since 2.x * read it. * @@ -445,7 +448,7 @@ export class StackOneToolSet { ); } // An empty accountId is usually an unset variable, and treating it as unset would silently - // widen every call to all active accounts. + // widen every call to every discovered account. if (config.accountId === '') { throw new ToolSetConfigError('accountId must not be an empty string'); } @@ -483,7 +486,7 @@ export class StackOneToolSet { this.#accountIds.length === 0 ) { warn( - 'STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.', + '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.', ); } } @@ -724,7 +727,8 @@ export class StackOneToolSet { /** * The accounts a call is scoped to, in the order they were given: the call's own, then the - * toolset's, then its single account, then every active account in `GET /accounts` order. + * toolset's, then its single account, then every discovered account — active and shared, or + * non-shared too with `includeNonShared` — in `GET /accounts` order. */ async #accountsInOrder(accountIds: string[] | null | undefined): Promise { assertAccountIdList(accountIds, 'accountIds'); @@ -1242,7 +1246,8 @@ export class StackOneToolSet { * feedback that went nowhere. Unset optional fields are omitted, never sent as null. * * Makes exactly one `tools/call`, on the account with the lowest id among those the call is - * scoped to: `accountIds` when given, otherwise the toolset's, otherwise every active one. + * scoped to: `accountIds` when given, otherwise the toolset's, otherwise every active shared + * one (non-shared ones too with `includeNonShared`). * * @example * ```typescript diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index 5e3b3e62..359ad94e 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -138,10 +138,10 @@ { "id": "account-id-env-ignored", "kind": "warning", - "template": "STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.", + "template": "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.", "placeholders": {}, - "python": "STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.", - "node": "STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active account on this API key is used. Pass an account id to scope the toolset.", + "python": "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.", + "node": "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.", "matches": { "python": true, "node": true From f8f8d3a1c74c6026464dfdfd306bed87a4e1a937 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 18:09:41 +0100 Subject: [PATCH 134/151] fix(toolset): don't re-list an account that failed during the same execute() Only failures recorded before the call started are listed again at once; one from the call's own first listing would only double the wait. --- src/toolsets.search-execute.test.ts | 13 +++++++++++++ src/toolsets.ts | 14 ++++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index d304a628..6c42d4a8 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -847,6 +847,19 @@ describe('execute() while an account in scope has failed to list', () => { expect(calls.map(({ tool }) => tool)).toEqual(['linear_acc1_execute_action']); }); + it('does not re-list an account that failed during the same call', async () => { + serve([ACCOUNTS[0], ACCOUNTS[1]] as typeof ACCOUNTS); + failing.add('acc1'); + + // A fresh toolset: acc1 fails in this call's own listing, so listing it again at once + // would only double the wait. + await newToolSet() + .execute('linear_list_issues') + .catch(() => undefined); + + expect(listed).toEqual(['acc1', 'acc2']); + }); + it('does not re-list when no account has failed', async () => { serve([ACCOUNTS[0], ACCOUNTS[2]] as typeof ACCOUNTS); const toolset = newToolSet(); diff --git a/src/toolsets.ts b/src/toolsets.ts index e95c8d82..37adfaac 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -231,8 +231,8 @@ interface CachedCatalog { /** The catalog of an account scope: its tools, and each account left out because it failed. */ interface ScopedCatalog { entries: CatalogEntry[]; - /** In ascending account id order, with each failure's message. */ - failed: [accountId: string, message: string][]; + /** In ascending account id order, with each failure's message and when it failed. */ + failed: [accountId: string, message: string, at: number][]; } const describeError = (error: unknown): string => @@ -789,7 +789,7 @@ export class StackOneToolSet { entries: scope.flatMap((accountId) => listings.get(accountId) ?? []), failed: scope.flatMap((accountId): ScopedCatalog['failed'] => { const failure = failed.get(accountId); - return failure ? [[accountId, failure.message]] : []; + return failure ? [[accountId, failure.message, failure.at]] : []; }), }); if (scope.length === 0) { @@ -1160,6 +1160,7 @@ export class StackOneToolSet { const suffix = '_execute_action'; const lowered = actionId.toLowerCase(); + const started = retryTiming.now(); let { tools, failed } = await this.#metaTools(suffix, options.accountIds); // An account that failed to list may serve this action too: its own connector's, or one we @@ -1184,9 +1185,10 @@ export class StackOneToolSet { if (failed.some(([accountId]) => !this.#providers.has(accountId))) { await (this.#fetchingAccounts ?? this.fetchAccounts()).catch(() => undefined); } - // Listed again now rather than when due, but only those that could serve the action: - // re-listing an account on another provider would make this call wait out its timeout. - const retry = inReach(); + // Listed again now rather than when due, but only those that could serve the action and did + // not just fail for this call: re-listing an account on another provider would make this + // call wait out its timeout. + const retry = inReach().filter(([, , at]) => at < started); if (retry.length > 0) { ({ tools, failed } = await this.#metaTools( suffix, From 4576c2444261180eb018a91aadfb02deee653903 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 18:40:04 +0100 Subject: [PATCH 135/151] fix(mcp-client): keep a retried 429 on record while another request in the session is answered The client's event-stream GET, answered while a tools/list retry hung, cleared the flag, so the retry's timeout was reported as an ordinary timeout and the account skipped (intermittent in conformance's rate-limit-429-then-timeout). Counted per request; Python does the same. --- src/mcp-client.ts | 23 ++++++++++++++--------- src/rate-limit.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/src/mcp-client.ts b/src/mcp-client.ts index 9ecf6b6c..18d69170 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -226,24 +226,29 @@ async function withMcpSession( work: (client: Client) => Promise, ): Promise { const expiresAt = retryTiming.now() + timeout; - // Whether the request currently in flight is waiting out a 429. Cleared as soon as a retry is - // answered with anything else, as in Python: a 429 that cleared must not make a later timeout - // — a stalled stream on that same response, or an unrelated request — look like a rate limit. - let rateLimited = false; + // How many requests are waiting out a 429. One leaves the count as soon as a retry is answered + // with anything else, as in Python: a 429 that cleared must not make a later timeout — a + // stalled stream on that same response, or an unrelated request — look like a rate limit. It + // is counted per request because the client's requests overlap: its event-stream GET, say, + // answered while a tools/list retry hangs, must not clear the tools/list's 429. + let rateLimited = 0; const transport = new StreamableHTTPClientTransport(new URL(endpoint), { requestInit: { headers }, // Every request the client sends, handshake included, so it never sees a 429 it could // have waited out — but never one that would outlast the session's deadline. fetch: async (url, init) => { - rateLimited = false; + let retrying = false; const response = await fetchWithRetry(url, init, { deadline: expiresAt, onRetry: () => { - rateLimited = true; + if (!retrying) { + retrying = true; + rateLimited += 1; + } }, }); - if (response.status !== 429) { - rateLimited = false; + if (retrying && response.status !== 429) { + rateLimited -= 1; } return response; }, @@ -263,7 +268,7 @@ async function withMcpSession( // A timeout while a 429 was being retried is the rate limit's doing, not the account's: // reported as a timeout, it would skip the account and return a partial result, which a // 429 must never do. - if (rateLimited && isTimeout(error)) { + if (rateLimited > 0 && isTimeout(error)) { throw new StackOneAPIError( `MCP request to ${endpoint} was rate limited (429) and timed out after ${timeout / 1000}s while retrying`, 429, diff --git a/src/rate-limit.test.ts b/src/rate-limit.test.ts index d63390d2..1bbbfd5c 100644 --- a/src/rate-limit.test.ts +++ b/src/rate-limit.test.ts @@ -342,6 +342,42 @@ describe('a timeout while a 429 is retried', () => { expect(warnings().filter((message) => message.includes('Skipping'))).toEqual([]); }); + // The client's own event-stream GET overlaps the tools/list: answered while the retry hangs, it + // must not clear the tools/list's 429. + it('fails the listing with a 429 when another request is answered meanwhile', async () => { + let listAttempts = 0; + let answeredMeanwhile = false; + const app = createMcpApp({ accountTools: accountMcpTools }); + server.use( + http.all(`${TEST_BASE_URL}/mcp`, async ({ request }) => { + if (request.method === 'GET') { + await delay(100); + answeredMeanwhile = listAttempts === 2; + return new HttpResponse(null, { status: 405 }); + } + const message = (await request.clone().json()) as { method?: string }; + if (message.method === 'tools/list') { + if (listAttempts++ === 0) { + return HttpResponse.json(RATE_LIMITED, { + status: 429, + headers: { 'Retry-After': '0' }, + }); + } + await delay('infinite'); + } + return app.fetch(request); + }), + ); + + const error = await newToolSet({ timeout: 300 }) + .fetchTools({ accountIds: ['acc1'] }) + .catch((caught: unknown) => caught); + + expect(answeredMeanwhile).toBe(true); + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + }); + it('fails GET /accounts with a 429', async () => { let requests = 0; server.use( From 9a401638e8d60acf0560fc70d61b554c61e3aeb1 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 18:58:43 +0100 Subject: [PATCH 136/151] test(vectors): sync to sdk-conformance 7369b74, with a no-shared-accounts emitter --- src/vectors.test.ts | 15 +++++++++++++++ tests/vectors/messages.json | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/vectors.test.ts b/src/vectors.test.ts index ec4000a3..9a172349 100644 --- a/src/vectors.test.ts +++ b/src/vectors.test.ts @@ -789,6 +789,21 @@ const emitters: Record< values: { count: 1, accounts: 'hibob (error)' }, }; }, + 'no-shared-accounts': async () => { + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json([ + { id: 'a', provider: 'linear', status: 'active', shared: false, origin_username: 'u1' }, + { id: 'b', provider: 'jira', status: 'active', shared: false, origin_username: 'u2' }, + { id: 'c', provider: 'jira', status: 'error', shared: true }, + ]), + ), + ); + return { + emitted: { error: await errorOf(() => newToolSet().fetchTools()) }, + values: { count: 2 }, + }; + }, 'all-accounts-failed': async () => { listMock.mockImplementation(async ({ headers }) => { throw new Error(`down ${headers['x-account-id']}`); diff --git a/tests/vectors/messages.json b/tests/vectors/messages.json index 359ad94e..868235b1 100644 --- a/tests/vectors/messages.json +++ b/tests/vectors/messages.json @@ -1097,6 +1097,28 @@ "node": true }, "notes": "Emitted once per discovery (fetchTools / search) that skips any account with shared === false from GET /accounts, unless the toolset opts in: Python include_non_shared=True, Node includeNonShared: true. End-user ids are still recorded from every GET /accounts regardless." + }, + { + "id": "no-shared-accounts", + "kind": "error", + "error": { + "python": "ToolsetConfigError", + "node": "ToolSetConfigError" + }, + "template": "None of this API key's {count} 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.", + "placeholders": { + "count": { + "format": "integer", + "description": "how many active accounts this API key has" + } + }, + "python": "None of this API key's {count} 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.", + "node": "None of this API key's {count} 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.", + "matches": { + "python": true, + "node": true + }, + "notes": "Raised by discovery (fetchTools / search) instead of non-shared-accounts-skipped when every active account on this API key is non-shared and the toolset has not opted in. With no shared account to serve a catalog, discovery fails outright rather than warning and returning an empty one." } ], "unshared": [ From 9d7f2af1e7c6152988eb13b625f8f19da6b70f14 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 18:58:43 +0100 Subject: [PATCH 137/151] ci: pin sdk-conformance to 7369b74 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index eb81dd8f..a3ed9e3a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 27796bb9da96c0c7e1d58db45c2a84b316be7b00 + ref: 7369b74f43ac7c2691650cc9e3a16cc6c7256f4e token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 6b76a7d4f57292a3dd168a83c0eb089c6b3d884b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 18:59:12 +0100 Subject: [PATCH 138/151] ci: run conformance against stackone-ai-python 80b580b --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index a3ed9e3a..2c55d1f4 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 8ab4a1713242a693f86f1542630f2c5cc63b31d6 + PYTHON_SDK_REF: 80b580b34b78ecff24aff9842ee0c6e1b3f3d49a steps: - name: Check conformance token is configured env: From 071ffed72d3c352aade1b879879813ec5bb03b0b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 19:07:30 +0100 Subject: [PATCH 139/151] docs: qualify the lookup cause for a rate limit, and what a failed account on another provider costs --- MIGRATION.md | 2 +- README.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index eb483433..463e035f 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -195,7 +195,7 @@ await toolset.execute('linear_list_comments', { headers: { 'x-request-id': 'abc' **With no account id, the SDK discovers your accounts.** In 2.x, calling `fetchTools()` with no account listed tools without an `x-account-id`, which the API refuses. In 3.0 it asks `GET /accounts` (also available as `toolset.fetchAccounts()`) and lists the catalog of every active shared account, skipping non-shared ones (`shared: false`) with a warning unless you pass `includeNonShared: true`; if every active account is non-shared, it throws `ToolSetConfigError`. If you have many accounts, pass `accountId`, `accountIds` or call `setAccounts()` so the SDK does not fetch every catalog. -**Non-shared accounts get `x-end-user-id` automatically.** The API refuses an MCP request for a non-shared account unless `x-end-user-id` carries that account's end user. Whenever the SDK calls `GET /accounts` (discovery or `fetchAccounts()`), it records the `origin_username` of every account with `shared: false` and sends it as `x-end-user-id` on every MCP request for that account, overriding a value from the `headers` option. With explicit account ids the SDK makes no `GET /accounts` up front; if the API then refuses a request for want of an end user, it calls `GET /accounts` once and retries with the recorded one, or throws the API's 400 (with the lookup's error as its `cause` if `GET /accounts` failed). A value set in `headers` is passed through as given when nothing is recorded. +**Non-shared accounts get `x-end-user-id` automatically.** The API refuses an MCP request for a non-shared account unless `x-end-user-id` carries that account's end user. Whenever the SDK calls `GET /accounts` (discovery or `fetchAccounts()`), it records the `origin_username` of every account with `shared: false` and sends it as `x-end-user-id` on every MCP request for that account, overriding a value from the `headers` option. With explicit account ids the SDK makes no `GET /accounts` up front; if the API then refuses a request for want of an end user, it calls `GET /accounts` once and retries with the recorded one, or throws the API's 400 (with the lookup's error as its `cause` if `GET /accounts` failed, or the lookup's 429 `StackOneAPIError` itself if it was rate limited). A value set in `headers` is passed through as given when nothing is recorded. **`STACKONE_ACCOUNT_ID` is no longer read.** Pass the account id as `accountId` or `accountIds`. Since an unset account now means every active shared account, an environment variable that set it implicitly could widen or narrow a toolset's scope without the code saying so. `STACKONE_API_KEY` is still read. A toolset constructed with no account while `STACKONE_ACCOUNT_ID` is set to a non-empty value warns that it is ignored. To keep the variable, read it yourself; unset, it is `undefined` and the toolset discovers your accounts: diff --git a/README.md b/README.md index 23c1669f..377c51bc 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ for (const account of await toolset.fetchAccounts()) { > If your organisation has many linked accounts, discovery lists the catalog of every one of them. Pass explicit `accountIds` to avoid the round trips and the model context they cost. -A non-shared account (`shared: false` in `GET /accounts`) belongs to one end user, and the API refuses its MCP requests unless they carry that user's id in `x-end-user-id`. Discovery skips non-shared accounts, with a warning naming them, so a toolset built with only an API key never puts every end user's accounts in one context: pass their account ids, or `includeNonShared: true`, to use them. If every active account is non-shared, discovery throws `ToolSetConfigError` instead. Whenever the toolset calls `GET /accounts` — for discovery, or through `fetchAccounts()` — it records each non-shared account's `origin_username` and sends it as `x-end-user-id` on every MCP request for that account, replacing any value from the `headers` option. With explicit account ids and nothing recorded for one, the API's refusal makes the toolset call `GET /accounts` once and, if that names the account's end user, send the request again with it; otherwise the API's 400 is thrown, with the lookup's error as its `cause` if the lookup failed. Overlapping `GET /accounts` calls are recorded in the order they started. +A non-shared account (`shared: false` in `GET /accounts`) belongs to one end user, and the API refuses its MCP requests unless they carry that user's id in `x-end-user-id`. Discovery skips non-shared accounts, with a warning naming them, so a toolset built with only an API key never puts every end user's accounts in one context: pass their account ids, or `includeNonShared: true`, to use them. If every active account is non-shared, discovery throws `ToolSetConfigError` instead. Whenever the toolset calls `GET /accounts` — for discovery, or through `fetchAccounts()` — it records each non-shared account's `origin_username` and sends it as `x-end-user-id` on every MCP request for that account, replacing any value from the `headers` option. With explicit account ids and nothing recorded for one, the API's refusal makes the toolset call `GET /accounts` once and, if that names the account's end user, send the request again with it; otherwise the API's 400 is thrown, with the lookup's error as its `cause` if the lookup failed — unless the lookup was rate limited, when its 429 `StackOneAPIError` is thrown instead. Overlapping `GET /accounts` calls are recorded in the order they started. ### Account IDs @@ -318,7 +318,7 @@ const result = await toolset.execute(best.action_id, best.example_request, { - The connector is the longest one whose name prefixes the action id, so `browser_linkedin_*` actions are not routed to `browser`. - `action_id` is always the one you pass: an `action_id` inside `args` — for example, one a prompt-injected model put there — is ignored. - Each hit carries the `session_id` of the search that found it, when the server issued one. Pass it back as `sessionId` to link the calls together. -- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list and its provider is the action's connector or unknown, `execute()` lists it again at once (asking `GET /accounts` first for any provider it does not know), and if it still fails, throws `ToolSetLoadError` rather than run the action on whichever account did list. A failed account on another provider is not listed again, so it costs the call nothing. +- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list and its provider is the action's connector or unknown, `execute()` lists it again at once (asking `GET /accounts` first for any provider it does not know), and if it still fails, throws `ToolSetLoadError` rather than run the action on whichever account did list. A failed account on another provider is not listed again early, so it never costs the call a listing timeout, though learning its provider with explicit ids takes one `GET /accounts`; like any account, it is listed again once its 30 seconds are up. - `topK` (1–50, default 10) caps the whole result, after ranking across every connector. A connector that fails to search is skipped with a warning, unless every connector fails. [View full example](examples/search-and-execute.ts) From 023dbea383f92d0b5aeeef842b986c6392c21371 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 19:08:30 +0100 Subject: [PATCH 140/151] ci: pin sdk-conformance to ddd2074 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 2c55d1f4..a3c96c17 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 7369b74f43ac7c2691650cc9e3a16cc6c7256f4e + ref: ddd207441a9206a7b42756763b03aff5d09f0940 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 4f69dc8c14518f6f32b357ee66760542faa6d4b6 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Mon, 5 Oct 2026 19:08:37 +0100 Subject: [PATCH 141/151] ci: run conformance against stackone-ai-python b9bf8ea --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index a3c96c17..9a45a16c 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 80b580b34b78ecff24aff9842ee0c6e1b3f3d49a + PYTHON_SDK_REF: b9bf8ea18a55c1efc144b0eb6fc2b5b4b6695864 steps: - name: Check conformance token is configured env: From 0967e611eadc3cf649d54f7d574ed65380fa287b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 09:50:09 +0100 Subject: [PATCH 142/151] fix(toolsets): rethrow a rate-limited provider lookup from execute() execute() swallowed every failure of the GET /accounts it makes to learn a failed account's provider, 429 included. A rate limit is the key's, not the account's, so it is now thrown, as the end-user lookup already does. --- README.md | 2 +- src/toolsets.search-execute.test.ts | 20 ++++++++++++++++++++ src/toolsets.ts | 12 +++++++++--- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 377c51bc..c9177f32 100644 --- a/README.md +++ b/README.md @@ -318,7 +318,7 @@ const result = await toolset.execute(best.action_id, best.example_request, { - The connector is the longest one whose name prefixes the action id, so `browser_linkedin_*` actions are not routed to `browser`. - `action_id` is always the one you pass: an `action_id` inside `args` — for example, one a prompt-injected model put there — is ignored. - Each hit carries the `session_id` of the search that found it, when the server issued one. Pass it back as `sessionId` to link the calls together. -- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list and its provider is the action's connector or unknown, `execute()` lists it again at once (asking `GET /accounts` first for any provider it does not know), and if it still fails, throws `ToolSetLoadError` rather than run the action on whichever account did list. A failed account on another provider is not listed again early, so it never costs the call a listing timeout, though learning its provider with explicit ids takes one `GET /accounts`; like any account, it is listed again once its 30 seconds are up. +- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list and its provider is the action's connector or unknown, `execute()` lists it again at once (asking `GET /accounts` first for any provider it does not know, and throwing its 429 if rate limited), and if it still fails, throws `ToolSetLoadError` rather than run the action on whichever account did list. A failed account on another provider is not listed again early, so it never costs the call a listing timeout, though learning its provider with explicit ids takes one `GET /accounts`; like any account, it is listed again once its 30 seconds are up. - `topK` (1–50, default 10) caps the whole result, after ranking across every connector. A connector that fails to search is skipped with a warning, unless every connector fails. [View full example](examples/search-and-execute.ts) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 6c42d4a8..7041da71 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -809,6 +809,26 @@ describe('execute() while an account in scope has failed to list', () => { expect(calls).toEqual([]); }); + it('throws the 429 when the provider lookup is rate limited', async () => { + serve([ACCOUNTS[0], ACCOUNTS[1]] as typeof ACCOUNTS); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => + HttpResponse.json( + { statusCode: 429, message: 'Too many requests' }, + { status: 429, headers: { 'Retry-After': '0' } }, + ), + ), + ); + failing.add('acc2'); + + const error = await newToolSet({ accountIds: ['acc1', 'acc2'] }) + .execute('linear_list_issues') + .catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(StackOneAPIError); + expect((error as StackOneAPIError).statusCode).toBe(429); + }); + it('lists a failed account again at once, and then applies to whatever it serves', async () => { const calls = serve([ACCOUNTS[0], ACCOUNTS[1]] as typeof ACCOUNTS); failing.add('acc1'); diff --git a/src/toolsets.ts b/src/toolsets.ts index 37adfaac..f914634d 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -1136,7 +1136,8 @@ export class StackOneToolSet { * @throws ToolSetLoadError If no linked connector serves the action, or an account in scope * failed to list — after being listed again now — and its provider is the action's * connector or unknown. - * @throws StackOneAPIError If the action fails. + * @throws StackOneAPIError If the action fails, or the lookup of a failed account's provider + * is rate limited. */ async execute( actionId: string, @@ -1181,9 +1182,14 @@ export class StackOneToolSet { }; // With explicit account ids no GET /accounts has named the failed accounts' providers, so // one dead account would refuse every action. Ask once — joining a lookup in flight — and - // treat the provider as unknown still if that fails too. + // treat the provider as unknown still if that fails too, unless it was rate limited: the + // key's 429 is fatal, as it is to the end-user lookup. if (failed.some(([accountId]) => !this.#providers.has(accountId))) { - await (this.#fetchingAccounts ?? this.fetchAccounts()).catch(() => undefined); + await (this.#fetchingAccounts ?? this.fetchAccounts()).catch((error: unknown) => { + if (isRateLimitFailure(error)) { + throw error; + } + }); } // Listed again now rather than when due, but only those that could serve the action and did // not just fail for this call: re-listing an account on another provider would make this From 494f820f2927aeb190c8a465b731b55e6adeaf19 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 09:54:21 +0100 Subject: [PATCH 143/151] fix(toolsets): remember when execute()'s provider lookup cannot name a failed account A GET /accounts that fails, or does not list a failed account, left nothing behind, so every execute() looked the account up again and re-listed it, paying a GET /accounts and possibly a listing timeout per call. The miss is now kept for FAILED_ACCOUNT_RETRY_MS: the account is still refused as unknown, but neither looked up nor listed early again until then. clearCatalogCache() forgets misses with failures. --- README.md | 2 +- src/toolsets.search-execute.test.ts | 58 +++++++++++++++++++++++++++++ src/toolsets.ts | 44 ++++++++++++++++++---- 3 files changed, 95 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index c9177f32..fae716e2 100644 --- a/README.md +++ b/README.md @@ -318,7 +318,7 @@ const result = await toolset.execute(best.action_id, best.example_request, { - The connector is the longest one whose name prefixes the action id, so `browser_linkedin_*` actions are not routed to `browser`. - `action_id` is always the one you pass: an `action_id` inside `args` — for example, one a prompt-injected model put there — is ignored. - Each hit carries the `session_id` of the search that found it, when the server issued one. Pass it back as `sessionId` to link the calls together. -- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list and its provider is the action's connector or unknown, `execute()` lists it again at once (asking `GET /accounts` first for any provider it does not know, and throwing its 429 if rate limited), and if it still fails, throws `ToolSetLoadError` rather than run the action on whichever account did list. A failed account on another provider is not listed again early, so it never costs the call a listing timeout, though learning its provider with explicit ids takes one `GET /accounts`; like any account, it is listed again once its 30 seconds are up. +- Each hit carries the `account_id` of the account that found it, and the same action linked on two accounts is two hits. When an action's connector is linked on more than one account, `execute()` throws `ToolSetConfigError` rather than pick one: pass the hit's account as `{ accountIds: [hit.account_id] }`. Likewise, if an account in scope failed to list and its provider is the action's connector or unknown, `execute()` lists it again at once (asking `GET /accounts` first for any provider it does not know, and throwing its 429 if rate limited; an account that lookup failed to name is neither asked about nor listed early again for 30 seconds), and if it still fails, throws `ToolSetLoadError` rather than run the action on whichever account did list. A failed account on another provider is not listed again early, so it never costs the call a listing timeout, though learning its provider with explicit ids takes one `GET /accounts`; like any account, it is listed again once its 30 seconds are up. - `topK` (1–50, default 10) caps the whole result, after ranking across every connector. A connector that fails to search is skipped with a warning, unless every connector fails. [View full example](examples/search-and-execute.ts) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index 7041da71..aa2be926 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -17,6 +17,7 @@ import { StackOneToolSet } from './toolsets'; import type { JsonObject } from './types'; import { StackOneAPIError } from './utils/error-stackone-api'; import { StackOneError } from './utils/error-stackone'; +import { retryTiming } from './utils/fetch-retry'; import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; vi.mock('./mcp-client', async (importOriginal) => { @@ -829,6 +830,63 @@ describe('execute() while an account in scope has failed to list', () => { expect((error as StackOneAPIError).statusCode).toBe(429); }); + describe('when the provider lookup cannot name a failed account', () => { + let now = 0; + let accountRequests = 0; + /** acc2 always fails to list, and GET /accounts always answers 403. */ + const serveUnnameable = () => { + serve([ACCOUNTS[0], ACCOUNTS[1]] as typeof ACCOUNTS); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => { + accountRequests += 1; + return HttpResponse.json({ error: 'forbidden' }, { status: 403 }); + }), + ); + failing.add('acc2'); + return newToolSet({ accountIds: ['acc1', 'acc2'] }); + }; + /** A second after the last call, so its failures are no longer this call's own. */ + 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/); + }; + const listings = (accountId: string) => listed.filter((id) => id === accountId).length; + + beforeEach(() => { + now = 0; + accountRequests = 0; + vi.spyOn(retryTiming, 'now').mockImplementation(() => now); + }); + + it('neither looks it up nor re-lists it again for 30 seconds', async () => { + const toolset = serveUnnameable(); + + await refuses(toolset); + await refuses(toolset); + await refuses(toolset); + + expect(accountRequests).toBe(1); + expect(listings('acc2')).toBe(1); + + now += 30_000; + await refuses(toolset); + + expect(accountRequests).toBe(2); + expect(listings('acc2')).toBe(2); + }); + + it('forgets the miss when the cache is cleared', async () => { + const toolset = serveUnnameable(); + await refuses(toolset); + + toolset.clearCatalogCache(); + await refuses(toolset); + + expect(accountRequests).toBe(2); + }); + }); + it('lists a failed account again at once, and then applies to whatever it serves', async () => { const calls = serve([ACCOUNTS[0], ACCOUNTS[1]] as typeof ACCOUNTS); failing.add('acc1'); diff --git a/src/toolsets.ts b/src/toolsets.ts index f914634d..0e4c84e6 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -402,6 +402,13 @@ export class StackOneToolSet { #endUserIds: ReadonlyMap = new Map(); /** The provider of each account, recorded with {@link #endUserIds}. */ #providers: ReadonlyMap = new Map(); + /** + * When {@link execute}'s provider lookup last failed to name each failed account, on + * {@link retryTiming}'s clock. For {@link FAILED_ACCOUNT_RETRY_MS} after, `execute()` neither + * looks the account up nor lists it again early, so a key that cannot name it does not cost + * every call a `GET /accounts` and a listing. Forgotten by {@link clearCatalogCache}. + */ + readonly #providerMisses = new Map(); /** * Bumped at the start of every {@link fetchAccounts} call. Overlapping calls (it is public, and * not deduplicated the way {@link #discoverAccountIds} is) can resolve out of order, so each @@ -516,6 +523,7 @@ export class StackOneToolSet { this.#catalogInFlight.clear(); this.#discoveredAccountIds = undefined; this.#discovering = undefined; + this.#providerMisses.clear(); } /** @@ -1134,8 +1142,8 @@ export class StackOneToolSet { * @throws ToolSetConfigError If the arguments are malformed, or the action's connector is * linked on more than one account and the call names none. * @throws ToolSetLoadError If no linked connector serves the action, or an account in scope - * failed to list — after being listed again now — and its provider is the action's - * connector or unknown. + * failed to list — after being listed again now, unless the provider lookup failed to name + * it in the last 30 seconds — and its provider is the action's connector or unknown. * @throws StackOneAPIError If the action fails, or the lookup of a failed account's provider * is rate limited. */ @@ -1183,18 +1191,38 @@ export class StackOneToolSet { // With explicit account ids no GET /accounts has named the failed accounts' providers, so // one dead account would refuse every action. Ask once — joining a lookup in flight — and // treat the provider as unknown still if that fails too, unless it was rate limited: the - // key's 429 is fatal, as it is to the end-user lookup. - if (failed.some(([accountId]) => !this.#providers.has(accountId))) { + // key's 429 is fatal, as it is to the end-user lookup. An account the lookup recently + // failed to name is not asked about again until its window is up. + const failedIds = failed.map(([accountId]) => accountId); + const missedRecently = new Set( + failedIds.filter( + (accountId) => + started - (this.#providerMisses.get(accountId) ?? -Infinity) < FAILED_ACCOUNT_RETRY_MS, + ), + ); + const unknown = failedIds.filter( + (accountId) => !this.#providers.has(accountId) && !missedRecently.has(accountId), + ); + if (unknown.length > 0) { await (this.#fetchingAccounts ?? this.fetchAccounts()).catch((error: unknown) => { if (isRateLimitFailure(error)) { throw error; } }); + const missedAt = retryTiming.now(); + for (const accountId of unknown) { + if (!this.#providers.has(accountId)) { + this.#providerMisses.set(accountId, missedAt); + } + } } - // Listed again now rather than when due, but only those that could serve the action and did - // not just fail for this call: re-listing an account on another provider would make this - // call wait out its timeout. - const retry = inReach().filter(([, , at]) => at < started); + // Listed again now rather than when due, but only those that could serve the action, did + // not just fail for this call, and were not recently missed by the lookup: re-listing an + // account on another provider would make this call wait out its timeout, and re-listing one + // the lookup cannot name would make every call wait it out. + const retry = inReach().filter( + ([accountId, , at]) => at < started && !missedRecently.has(accountId), + ); if (retry.length > 0) { ({ tools, failed } = await this.#metaTools( suffix, From 92b23de1e626890c4eedd17df2a4a6afe5b2c68b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 10:05:58 +0100 Subject: [PATCH 144/151] ci: pin sdk-conformance to 960a542 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 9a45a16c..0a7281aa 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: ddd207441a9206a7b42756763b03aff5d09f0940 + ref: 960a5429b1db8a24c11ff64355f599ab8ebb6380 token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 64f14c523f83374f435649cf00e881edadb5be7f Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 10:06:05 +0100 Subject: [PATCH 145/151] ci: run conformance against stackone-ai-python 970d7b8 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 0a7281aa..29708f86 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: b9bf8ea18a55c1efc144b0eb6fc2b5b4b6695864 + PYTHON_SDK_REF: 970d7b88a6a24a7146aa820e08fc190f31ad8a44 steps: - name: Check conformance token is configured env: From dbee8bd45662bbea0decfe6992ac44a647336964 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 10:08:59 +0100 Subject: [PATCH 146/151] fix(toolsets): act on a provider-lookup miss in the call that made it, drop one across a clear, and forget it once the account is named Concurrent execute() calls each re-listed an account their shared lookup had just missed; a clearCatalogCache() during the lookup was undone by the miss written after it; and a later GET /accounts naming the account still left it held out for the window. --- src/toolsets.search-execute.test.ts | 51 +++++++++++++++++++++++++++++ src/toolsets.ts | 12 ++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/toolsets.search-execute.test.ts b/src/toolsets.search-execute.test.ts index aa2be926..1f51d3a2 100644 --- a/src/toolsets.search-execute.test.ts +++ b/src/toolsets.search-execute.test.ts @@ -885,6 +885,57 @@ describe('execute() while an account in scope has failed to list', () => { expect(accountRequests).toBe(2); }); + + it('does not re-list it in the call whose lookup missed it', async () => { + const toolset = serveUnnameable(); + await toolset.fetchTools({ mode: 'search_execute' }); + + // Concurrent calls join the one lookup, and none of them waits out acc2 again. + await Promise.all([refuses(toolset), refuses(toolset)]); + + expect(accountRequests).toBe(1); + expect(listings('acc2')).toBe(1); + }); + + it('does not record a miss across a clear made during the lookup', async () => { + const toolset = serveUnnameable(); + let release = () => {}; + const held = new Promise((resolve) => { + release = resolve; + }); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, async () => { + accountRequests += 1; + if (accountRequests === 1) { + await held; + } + return HttpResponse.json({ error: 'forbidden' }, { status: 403 }); + }), + ); + + const first = refuses(toolset); + await vi.waitFor(() => expect(accountRequests).toBe(1)); + toolset.clearCatalogCache(); + release(); + await first; + await refuses(toolset); + + expect(accountRequests).toBe(2); + }); + + it('forgets the miss once GET /accounts names the account', async () => { + const toolset = serveUnnameable(); + await refuses(toolset); + server.use( + http.get(`${TEST_BASE_URL}/accounts`, () => HttpResponse.json([ACCOUNTS[0], ACCOUNTS[1]])), + ); + await toolset.fetchAccounts(); + + await refuses(toolset); + + // acc2 is linear's, so it is listed again at once rather than after the window. + expect(listings('acc2')).toBe(2); + }); }); it('lists a failed account again at once, and then applies to whatever it serves', async () => { diff --git a/src/toolsets.ts b/src/toolsets.ts index 0e4c84e6..bda10d93 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -652,6 +652,10 @@ export class StackOneToolSet { this.#accountsRecorded = started; this.#endUserIds = endUserIdsOf(accounts); this.#providers = providersOf(accounts); + // An account this response names is no longer one the lookup missed. + for (const accountId of this.#providers.keys()) { + this.#providerMisses.delete(accountId); + } } return accounts as StackOneAccount[]; } @@ -1204,15 +1208,21 @@ export class StackOneToolSet { (accountId) => !this.#providers.has(accountId) && !missedRecently.has(accountId), ); if (unknown.length > 0) { + const generation = this.#cacheGeneration; await (this.#fetchingAccounts ?? this.fetchAccounts()).catch((error: unknown) => { if (isRateLimitFailure(error)) { throw error; } }); + // A miss is this call's to act on whatever happens, but only recorded for later calls + // if no clearCatalogCache() came in between, which promises to forget misses. const missedAt = retryTiming.now(); for (const accountId of unknown) { if (!this.#providers.has(accountId)) { - this.#providerMisses.set(accountId, missedAt); + missedRecently.add(accountId); + if (generation === this.#cacheGeneration) { + this.#providerMisses.set(accountId, missedAt); + } } } } From 629a6918f4f728331a9b0a1753c5233b45114e91 Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 10:11:33 +0100 Subject: [PATCH 147/151] ci: run conformance against stackone-ai-python 9a84c2b --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 29708f86..5bcd7132 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 970d7b88a6a24a7146aa820e08fc190f31ad8a44 + PYTHON_SDK_REF: 9a84c2bb25c938a91e5eda9d707ab89c07a754a5 steps: - name: Check conformance token is configured env: From 2253466371a22c839524d008a635ceb9f2c0959b Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 10:13:25 +0100 Subject: [PATCH 148/151] ci: pin sdk-conformance to 55bd126 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 5bcd7132..3dd4b472 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: repository: StackOneHQ/sdk-conformance - ref: 960a5429b1db8a24c11ff64355f599ab8ebb6380 + ref: 55bd126b0187a0f28f187803ecf48e791d157bfc token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} path: sdk-conformance persist-credentials: false From 42a7b72cc6c139166df6894dc5a711ce9633b91f Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 10:13:32 +0100 Subject: [PATCH 149/151] ci: run conformance against stackone-ai-python eeef2c0 --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 3dd4b472..563140f2 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 9a84c2bb25c938a91e5eda9d707ab89c07a754a5 + PYTHON_SDK_REF: eeef2c00aeeaddf5d4de70e7e0d2e4b12d60176f steps: - name: Check conformance token is configured env: From 767eff061f0cbf036052fb8f163c9bdeaf01494d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 10:24:24 +0100 Subject: [PATCH 150/151] ci: run conformance against stackone-ai-python 9a35e2e --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 563140f2..4e1043e7 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: eeef2c00aeeaddf5d4de70e7e0d2e4b12d60176f + PYTHON_SDK_REF: 9a35e2e409b2ba3715c155188f725ff6248ca950 steps: - name: Check conformance token is configured env: From 4f3f75da2655e2b9e95f3fa7643627eb92161a5d Mon Sep 17 00:00:00 2001 From: Will Leeney Date: Tue, 6 Oct 2026 13:18:26 +0100 Subject: [PATCH 151/151] ci: run conformance against stackone-ai-python 441a0ca --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 4e1043e7..20504b83 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -147,7 +147,7 @@ jobs: # Pinned to a commit rather than the branch while StackOneHQ/stackone-ai-python#210 is # open, so this only moves when we bump it deliberately. Switch to a main commit once it # merges. - PYTHON_SDK_REF: 9a35e2e409b2ba3715c155188f725ff6248ca950 + PYTHON_SDK_REF: 441a0caecd11079aafe6bd94299be47e00780605 steps: - name: Check conformance token is configured env: