diff --git a/.env.example b/.env.example index ba48917c..2c43b8c9 100644 --- a/.env.example +++ b/.env.example @@ -1,8 +1,11 @@ # Required for all examples STACKONE_API_KEY=your-stackone-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, 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/.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 diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index bfeaf8c2..20504b83 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -116,6 +116,136 @@ 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 + + # 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: + # 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: 441a0caecd11079aafe6bd94299be47e00780605 + 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: 55bd126b0187a0f28f187803ecf48e791d157bfc + token: ${{ secrets.CONFORMANCE_REPO_TOKEN }} + 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 + run: diff -r sdk/tests/vectors sdk-conformance/vectors + + - 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: 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 + + - name: Run conformance suite + working-directory: sdk-conformance + env: + NODE_SDK_DIST: ${{ github.workspace }}/sdk/dist/index.mjs + 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. + 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/.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/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/MIGRATION.md b/MIGRATION.md new file mode 100644 index 00000000..463e035f --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,331 @@ +# 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 }); // at most 5, 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 + { accountIds: [hit.account_id], sessionId: hit.session_id }, +); +``` + +`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`. + +```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? }`, 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 { 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`. + +**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 } = (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())); +``` + +**`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 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. + +**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: + +```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 — `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. + +`*_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' } }); +``` + +## 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 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, 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: + +```typescript +// 2.x: STACKONE_ACCOUNT_ID picked up implicitly +const toolset = new StackOneToolSet(); + +// 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 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, 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 + +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'); +if (!hit) throw new Error('No action matched'); +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. It calls the tool once, on the lowest account id in scope, and sends `actionRunId` as `action_run_id` when given. + +## Errors + +**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 { + 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.** 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 hibobTools = tools.toArray().filter((tool) => tool.connector === 'hibob'); + +// 3.0 +const hibobTools = await toolset.fetchTools({ providers: ['hibob'] }); +``` diff --git a/README.md b/README.md index 5557f042..fae716e2 100644 --- a/README.md +++ b/README.md @@ -6,39 +6,53 @@ +> **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, 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 }); +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 +const tools = await toolset.fetchTools({ actions: ['*_list_*'] }); +const listTool = tools.getTool('workday_list_workers'); +const workers = await listTool?.execute(); ``` ### Authentication @@ -49,17 +63,29 @@ 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. + +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 -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`, 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 || undefined }); const tools = await toolset.fetchTools(); // Explicit single account @@ -78,11 +104,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. @@ -98,27 +127,30 @@ 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 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(); +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) @@ -134,8 +166,9 @@ 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 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(); @@ -164,8 +197,9 @@ 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 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(); @@ -203,8 +237,9 @@ 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 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(); @@ -230,8 +265,9 @@ 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 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 const tools = await toolset.fetchTools(); @@ -259,6 +295,64 @@ 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; +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, +}); +``` + +- `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. +- 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) + +### 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 + actionRunId: 'run_123', // optional: the action run the feedback is about +}); +``` + +`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 + +```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 +366,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 +374,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,61 +391,46 @@ 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. +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. -#### Basic Usage +### Tool schemas -```typescript -import { StackOneToolSet } from '@stackone/ai'; +`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: -// Reads STACKONE_API_KEY and STACKONE_ACCOUNT_ID from environment -const toolset = new StackOneToolSet(); -const searchTool = toolset.getSearchTool(); +| 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. | -// Search for relevant tools — returns a Tools collection -const tools = await searchTool.search('manage employees', { topK: 5 }); +### Headers -// Execute a discovered tool directly -const listTool = tools.getTool('workday_list_workers'); -const result = await listTool.execute({ query: { limit: 10 } }); -``` +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. -### Semantic Search +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. -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`. +`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 -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 }); +// Extra headers for every request (for example, tracing) +const toolset = new StackOneToolSet({ headers: { 'X-Request-Source': 'my-agent' } }); ``` -#### Search Modes +### Errors and timeouts -Control which search backend `searchTools()` uses via the `search` option: +Everything the SDK throws is a `StackOneError`: -```typescript -// 'auto' (default) — tries semantic search first, falls back to local -const tools = await toolset.searchTools('manage employees', { search: 'auto' }); +- `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. -// 'semantic' — semantic API only, throws if unavailable -const tools = await toolset.searchTools('manage employees', { search: 'semantic' }); +`timeout` (milliseconds, default 60000) bounds every MCP listing and `tools/call`, and account discovery. -// 'local' — local BM25+TF-IDF only, no semantic API call -const tools = await toolset.searchTools('manage employees', { search: 'local' }); -``` +### Rate limits -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. +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 @@ -361,256 +440,48 @@ 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: +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: "...", -// mappedParams: { ... } +// 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 full URL with query parameters -- `method`: The HTTP method -- `headers`: The request headers -- `body`: The request body -- `mappedParams`: The parameters after mapping and derivation - ### 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); -} -``` - -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), or `null` - -> **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", ... } - } - ] -} +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 } +// } +// } ``` -#### 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. +`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 diff --git a/examples/README.md b/examples/README.md index 06af90b9..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 +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 ``` @@ -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 @@ -66,23 +70,15 @@ 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. - -### [`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. +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()`) | -| `OPENAI_API_KEY` | For OpenAI / AI SDK examples | `openai-integration.ts`, `openai-responses-integration.ts`, `ai-sdk-integration.ts`, `search-tools.ts` (section 5) | -| `ANTHROPIC_API_KEY` | For Anthropic examples | `anthropic-integration.ts`, `claude-agent-sdk-integration.ts` | +| Variable | Required | Used By | +| --------------------- | ---------------------------- | ----------------------------------------------------------------------------------- | +| `STACKONE_API_KEY` | Yes | All examples | +| `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..aec03e93 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 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 const tools = await toolset.fetchTools({ diff --git a/examples/anthropic-integration.ts b/examples/anthropic-integration.ts index b7be566e..535511ec 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 shared account linked to the key + 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 dbb4f77f..5ec144ca 100644 --- a/examples/auth-management.ts +++ b/examples/auth-management.ts @@ -4,7 +4,10 @@ * 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, 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'; @@ -19,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 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`); @@ -33,15 +36,28 @@ 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'); - // The Node SDK reads STACKONE_ACCOUNT_ID from env automatically - const accountId = process.env.STACKONE_ACCOUNT_ID; + // The SDK only reads the API key from env; read the account id yourself and pass it. + // Unset or empty, it is undefined and the toolset discovers every active shared account instead. + const accountId = process.env.STACKONE_ACCOUNT_ID || undefined; console.log(` STACKONE_ACCOUNT_ID is ${accountId ? 'set' : 'not set'}`); - const 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`); }; @@ -50,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`); @@ -60,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'); @@ -91,6 +107,7 @@ const perToolOverride = async (): Promise => { // --- Run all sections --- await apiKeyFromEnv(); await apiKeyExplicit(); +await apiKeyAlone(); await accountIdFromEnv(); await accountIdInConstructor(); await setAccountsGlobally(); diff --git a/examples/claude-agent-sdk-integration.ts b/examples/claude-agent-sdk-integration.ts index 5012d8d7..f79219b3 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 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 const tools = await toolset.fetchTools(); 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/examples/openai-integration.ts b/examples/openai-integration.ts index 4daa23e5..6937ecf7 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 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 const tools = await toolset.fetchTools({ @@ -31,33 +32,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/openai-responses-integration.ts b/examples/openai-responses-integration.ts index 0d55fe79..65161bf8 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 shared account linked to the key + const toolset = new StackOneToolSet({ accountId: process.env.STACKONE_ACCOUNT_ID || undefined }); // Fetch tools via MCP const tools = await toolset.fetchTools({ diff --git a/examples/search-and-execute.ts b/examples/search-and-execute.ts new file mode 100644 index 00000000..85ac3bdd --- /dev/null +++ b/examples/search-and-execute.ts @@ -0,0 +1,91 @@ +/** + * 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) { + 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 + // 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)); + + // 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, + }, + ); + 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/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/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/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', 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..d6a002e7 100644 --- a/mocks/handlers.mcp.ts +++ b/mocks/handlers.mcp.ts @@ -5,23 +5,25 @@ import { createMcpApp, defaultMcpTools, exampleBamboohrTools, + metaLookalikeTools, 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` refuses 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, + lookalike: metaLookalikeTools, + // 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 ca386773..00000000 --- a/mocks/handlers.stackone-ai.ts +++ /dev/null @@ -1,98 +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 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({ - 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 deleted file mode 100644 index 3ed0bed6..00000000 --- a/mocks/handlers.stackone-rpc.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { http, HttpResponse } from 'msw'; -import { TEST_BASE_URL } from './constants'; - -/** - * 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 }, - ); - } - - 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; - }; - - // 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 }, - ); - } - - // 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/mocks/handlers.ts b/mocks/handlers.ts index d1fc784c..43b6b4c0 100644 --- a/mocks/handlers.ts +++ b/mocks/handlers.ts @@ -1,13 +1,5 @@ -import { exampleApiHandlers } from './handlers.example-api'; import { mcpHandlers } from './handlers.mcp'; import { openaiHandlers } from './handlers.openai'; -import { stackoneAiHandlers } from './handlers.stackone-ai'; -import { stackoneRpcHandlers } from './handlers.stackone-rpc'; +import { stackoneAccountsHandlers } from './handlers.stackone-accounts'; -export const handlers = [ - ...openaiHandlers, - ...stackoneRpcHandlers, - ...stackoneAiHandlers, - ...exampleApiHandlers, - ...mcpHandlers, -]; +export const handlers = [...openaiHandlers, ...stackoneAccountsHandlers, ...mcpHandlers]; diff --git a/mocks/mcp-server.ts b/mocks/mcp-server.ts index 24a53258..7ecdf633 100644 --- a/mocks/mcp-server.ts +++ b/mocks/mcp-server.ts @@ -2,10 +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 { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { + CallToolRequestSchema, + type CallToolResult, + ListToolsRequestSchema, +} from '@modelcontextprotocol/sdk/types.js'; import { Hono } from 'hono'; import { basicAuth } from 'hono/basic-auth'; @@ -17,36 +25,151 @@ export interface McpToolDefinition { properties?: Record; required?: string[]; additionalProperties?: boolean; + [keyword: string]: unknown; }; } +/** 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; + /** 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. */ +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) }], +}); + +/** + * 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({ + 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 wrapped({ + 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, toolResults = {} } = options; // Create a Hono app that handles MCP protocol const app = new Hono(); @@ -61,31 +184,81 @@ 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); + } - // Create a new MCP server instance per request - const mcp = new McpServer({ name: 'test-mcp-server', version: '1.0.0' }); - const transport = new StreamableHTTPTransport(); + const toolMode = c.req.query('tool-mode'); + const listed: McpToolDefinition[] = [ + ...(submitFeedback ? [submitFeedbackTool] : []), + ...(toolMode === 'search_execute' ? metaTools(accountId) : (accountTools[accountId] ?? [])), + ]; - 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, - }), + // 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: listed.map((tool) => ({ ...tool, inputSchema: structuredClone(tool.inputSchema) })), + })); + mcp.setRequestHandler(CallToolRequestSchema, (request): CallToolResult => { + const { name } = request.params; + const args = request.params.arguments ?? {}; + + 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 wrapped({ + message: 'Feedback recorded', + submitted_at: new Date(0).toISOString(), + session_id: args.session_id ?? null, + }); + } + // 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 ( + (toolMode === 'search_execute' ? callMetaTool(name, args) : undefined) ?? + wrapped({ data: { action: name, account_id: accountId, arguments: args } }) ); + }); + + // 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); }); @@ -229,6 +402,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/package.json b/package.json index 435f649f..ee0af930 100644 --- a/package.json +++ b/package.json @@ -62,9 +62,7 @@ "run:example": "tsx --env-file .env" }, "dependencies": { - "@modelcontextprotocol/sdk": "catalog:prod", - "@orama/orama": "catalog:prod", - "defu": "catalog:prod" + "@modelcontextprotocol/sdk": "catalog:prod" }, "devDependencies": { "@fast-check/vitest": "catalog:dev", @@ -87,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 f69b367d..e14e9a72 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -81,12 +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 importers: @@ -101,12 +95,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 devDependencies: '@fast-check/vitest': specifier: catalog:dev @@ -134,7 +122,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 +186,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 +780,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==} @@ -1373,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'} @@ -1757,94 +1738,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.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.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.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 +2788,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': @@ -3232,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): @@ -3654,7 +3640,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..78e45457 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -31,11 +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 - '@orama/orama': ^3.1.11 - defu: ^6.1.4 enablePrePostScripts: true 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/scripts/sync-vectors.sh b/scripts/sync-vectors.sh new file mode 100755 index 00000000..76efdf87 --- /dev/null +++ b/scripts/sync-vectors.sh @@ -0,0 +1,33 @@ +#!/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 +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" +mv "$tmp_dir" "$target_dir" +echo "Copied $source_dir to $target_dir" 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..6cc22d0a 100644 --- a/src/consts.ts +++ b/src/consts.ts @@ -1,20 +1,43 @@ +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; + +/** + * The one global tool the MCP endpoint serves, in every tool mode, when feedback is enabled for + * the project. It is listed once however many accounts serve it. + */ +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; + +/** 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; + /** - * 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) + * 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 DEFAULT_HYBRID_ALPHA = 0.2; +export const FAILED_ACCOUNT_RETRY_MS = 30_000; diff --git a/src/end-user-id.test.ts b/src/end-user-id.test.ts new file mode 100644 index 00000000..fbfe986f --- /dev/null +++ b/src/end-user-id.test.ts @@ -0,0 +1,686 @@ +/** + * `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'; +import { ToolSetConfigError } from './utils/error-toolset'; + +/** 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' }, +]; + +/** 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. `guard` maps accounts to the end + * user `/mcp` requires, as UCA's ActiveAccountGuard does. + */ +const serve = ( + initial: unknown[] | (() => Response | Promise) = ACCOUNTS, + guard: Record = {}, +) => { + 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'), + }); + } + } + 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 | Promise)) => { + 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({ includeNonShared: true }).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({ includeNonShared: true }); + + 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({ includeNonShared: true }); + 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({ includeNonShared: true }).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('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 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' }); + 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', + ]); + }); +}); + +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('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."; + + 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([]); + }); +}); + +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('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', + }); + 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('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( + 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/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/headers.test.ts b/src/headers.test.ts index 3bb4f099..a6d93147 100644 --- a/src/headers.test.ts +++ b/src/headers.test.ts @@ -1,4 +1,11 @@ -import { normalizeHeaders } from './headers'; +import { + buildRequestHeaders, + declaredHeaders, + normalizeHeaders, + sanitiseHeaderArguments, + sanitiseHeaders, +} from './headers'; +import type { JsonObject } from './types'; describe('normalizeHeaders', () => { it('returns empty object for undefined input', () => { @@ -67,3 +74,121 @@ 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( + 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']), + ordinaryHeadersField: false, + }); + }); + + 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'])); + }); +}); + +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', () => { + 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({}); + }); +}); + +// 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(), + ordinaryHeadersField: false, + }); + 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); + }); +}); + +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 76eec146..981e5f97 100644 --- a/src/headers.ts +++ b/src/headers.ts @@ -1,46 +1,268 @@ -import { z } from 'zod/v4-mini'; -import type { JsonObject } from './types'; +import { USER_AGENT } from './consts'; +import type { JsonObject, JsonValue } from './types'; +import { warn } from './utils/logger'; +import { setEntry } from './utils/set-entry'; /** - * 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; /** - * Zod schema for StackOne API headers (branded) - * These headers are forwarded as HTTP headers in API requests + * 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. */ -export const stackOneHeadersSchema = z.record(z.string(), z.string()).brand<'StackOneHeaders'>(); +const END_USER_ID_HEADER = 'x-end-user-id'; + +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()); +} + +const isEndUserIdHeader = (name: string): boolean => + name.trim().toLowerCase() === END_USER_ID_HEADER; /** - * Branded type for StackOne API headers + * HTTP Basic credentials for an API key, as every StackOne endpoint expects them. */ -export type StackOneHeaders = z.infer; +function buildAuthHeader(apiKey: string): string { + return `Basic ${Buffer.from(`${apiKey}:`).toString('base64')}`; +} /** - * Normalizes header values from JsonObject to StackOneHeaders (branded type) - * Converts numbers and booleans to strings, and serializes objects to JSON + * 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 — 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; 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) && !(options.endUserId && isEndUserIdHeader(name))) { + setEntry(headers, name, value); + } + } + headers['User-Agent'] = USER_AGENT; + headers.Authorization = buildAuthHeader(options.apiKey); + if (options.accountId) { + headers['x-account-id'] = options.accountId; + } + if (options.endUserId) { + headers[END_USER_ID_HEADER] = options.endUserId; + } + 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. * * @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 { 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; - } - } - return stackOneHeadersSchema.parse(result); + for (const [key, value] of Object.entries(headers ?? {})) { + const text = headerText(value); + if (text !== undefined) { + setEntry(result, key, text); + } + } + return 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 FLAT_HEADER_PREFIX = 'headers_'; + +/** + * The header arguments a served tool schema declares. + * + * 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 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"` (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. */ + 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. True + * when `type` is a non-`"object"` string, or an array of types that doesn't include `"object"` + * (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. + */ + ordinaryHeadersField: boolean; +} + +/** 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, 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 = objectTyped && schema.additionalProperties !== false; + 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, + ordinaryHeadersField, + }; +} + +/** + * Why a header argument must not be forwarded, or `undefined` if it may be. + * + * `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) || isEndUserIdHeader(name)) { + return 'set by the SDK'; + } + if (!declared) { + return 'not declared by the schema'; + } + if (!HEADER_NAME_PATTERN.test(name) || !HEADER_VALUE_PATTERN.test(value)) { + return 'malformed'; + } + return undefined; +} + +/** + * 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" + * 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. `x-end-user-id` is refused like the SDK-owned names. + */ +export function sanitiseHeaders( + supplied: JsonObject | undefined, + allowed: ReadonlySet | 'any', +): Record { + const clean: Record = {}; + for (const [key, value] of Object.entries(normalizeHeaders(supplied))) { + const name = key.trim(); + const declared = allowed === 'any' || allowed.has(name.toLowerCase()); + const reason = refuseHeader(name, value, declared); + if (reason) { + warn(`Dropping header ${JSON.stringify(name)} from a tool call: ${reason}`); + continue; + } + setEntry(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. + * + * 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 (declared.ordinaryHeadersField) { + setEntry(clean, key, value); + } else if (isPlainObject(value)) { + clean.headers = sanitiseHeaders(value, declared.nested); + } else { + warn(`Dropping header argument ${JSON.stringify(key)} from a tool call: not an object`); + } + continue; + } + if (!key.startsWith(FLAT_HEADER_PREFIX)) { + setEntry(clean, key, value); + continue; + } + if (isPlainObject(value) || Array.isArray(value)) { + warn( + `Dropping header argument ${JSON.stringify(key)} from a tool call: not a string, number or boolean`, + ); + continue; + } + const text = headerText(value); + if (text === undefined) { + continue; + } + const reason = refuseHeader(key.slice(FLAT_HEADER_PREFIX.length), text, declared.flat.has(key)); + if (reason) { + warn(`Dropping header argument ${JSON.stringify(key)} from a tool call: ${reason}`); + continue; + } + setEntry(clean, key, value); + } + return clean; } diff --git a/src/index.ts b/src/index.ts index fa54c85f..333a67a5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,46 +3,34 @@ */ 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'; +export { ToolArgumentsError } from './utils/error-tool-arguments'; +export { ToolSetConfigError, ToolSetError, ToolSetLoadError } from './utils/error-toolset'; export { - SearchTool, StackOneToolSet, - ToolSetConfigError, - ToolSetError, - ToolSetLoadError, - type AuthenticationConfig, - type BaseToolSetConfig, + type ExecuteActionOptions, type ExecuteToolsConfig, - type SearchMode, - type SearchToolsOptions, - type SearchActionNamesOptions, + type FetchToolsOptions, + type SearchOptions, type StackOneToolSetConfig, + type SubmitFeedbackOptions, } from './toolsets'; -export { - SemanticSearchClient, - SemanticSearchError, - type SemanticSearchOptions, - type SemanticSearchResponse, - type SemanticSearchResult, -} from './semantic-search'; - -export { DEFAULT_DEFENDER_CONFIG } from './types'; - export type { + ActionResult, AISDKToolDefinition, AISDKToolResult, - DefenderConfig, - DefenderMode, ExecuteConfig, ExecuteOptions, + FeedbackCategory, + FeedbackRating, + FeedbackSource, JsonObject, JsonValue, - ParameterLocation, - SearchConfig, + SearchResult, + StackOneAccount, ToolDefinition, + ToolMode, } 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/mcp-client.test.ts b/src/mcp-client.test.ts index 2519401e..50750061 100644 --- a/src/mcp-client.test.ts +++ b/src/mcp-client.test.ts @@ -1,93 +1,325 @@ -/** - * 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')); -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(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 /); + } }); - expect(mcpClient.client).toBeInstanceOf(Client); - expect(mcpClient.transport).toBeInstanceOf(StreamableHTTPClientTransport); + it('surfaces an unscoped request as a 400 StackOneAPIError', async () => { + const error = (await listMcpTools(requestFor(undefined)).catch( + (caught: unknown) => caught, + )) as StackOneAPIError; + + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(400); + expect(error.message).toContain('x-account-id'); + }); + + // 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' }] }); + }); - await using mcpClient = await createMCPClient({ - baseUrl: 'http://localhost/mcp', - headers: { - Authorization: `Basic ${Buffer.from('test-key:').toString('base64')}`, - }, + 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 mcpClient.client.connect(mcpClient.transport); - await mcpClient.client.listTools(); + it('falls back to structuredContent when there is no text', () => { + expect(parseToolResult({ content: [], structuredContent: { ok: true } }, 't')).toEqual({ + ok: true, + }); + }); - server.events.removeListener('request:start', listener); + 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], + }); + }); + + // 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); + }); - const mcpRequest = recordedRequests.find((request) => request.url.includes('/mcp')); - expect(mcpRequest?.headers.get('user-agent')).toBe(`stackone-ai-node/${version}`); + 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', () => { + 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; + } + + 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({ + isError: false, + result: { message: 'Feedback recorded', session_id: 's-1' }, + }); + }); +}); + +describe('MCP timeouts', () => { + let silent: NetServer; + const sockets: Socket[] = []; + let port = 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)); }); - await mcpClient.client.connect(mcpClient.transport); - const result = await mcpClient.client.listTools(); + 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); - expect(result.tools).toBeDefined(); - expect(Array.isArray(result.tools)).toBe(true); - expect(result.tools.length).toBeGreaterThan(0); + expect(error).toBeInstanceOf(ToolSetLoadError); + expect((error as Error).message).toBe( + `MCP request to http://127.0.0.1:${port}/mcp timed out after 0.3s`, + ); + expect(Date.now() - started).toBeLessThan(5_000); + }); - const tool = result.tools[0]; - expect(tool.name).toBe('dummy_action'); - expect(tool.description).toBe('Dummy tool'); - expect(tool.inputSchema).toBeDefined(); + 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..18d69170 100644 --- a/src/mcp-client.ts +++ b/src/mcp-client.ts @@ -1,62 +1,406 @@ +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'; +import { fetchWithRetry, retryTiming } from './utils/fetch-retry'; -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; +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; +} + +/** 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; + } +}; + +/** + * Turn the MCP client's failure into something a caller can act on. + * + * 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 (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, + }); + } + 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, + }); +} + +/** + * 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 || + error.cause instanceof RateLimitTimeoutError || + error.cause instanceof HttpRateLimitError) + ); +} - /** underlying transport */ - transport: StreamableHTTPClientTransport; +/** + * 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 { + 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; + // 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 ( + message + .trimEnd() + .split(' ') + .pop() + ?.replace(/^["']|["']$/g, '') === accountId + ); +} - /** cleanup client and transport */ - [Symbol.asyncDispose](): Promise; +/** 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; } /** - * Create a Model Context Protocol (MCP) client. + * Run an MCP request for `accountId` with its recorded end user, if any. * - * @example - * ```ts - * import { createMCPClient } from '@stackone/ai'; + * 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 — with the lookup's error as its `cause`, + * if the lookup failed. + */ +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; + } + // A failed lookup leaves the refusal to be thrown, with the lookup's error as its cause — + // a key without platform.read would otherwise be told only that the header is wrong. A rate + // limit is thrown instead: that is the key's, not the account's, and must stay fatal to a + // fan-out. + let endUserId: string | undefined; + try { + endUserId = await source.lookUp(accountId); + } catch (lookupError) { + if (isRateLimitFailure(lookupError)) { + throw lookupError; + } + const refusal = error as StackOneAPIError; + throw new StackOneAPIError( + refusal.message, + refusal.statusCode, + refusal.responseBody, + refusal.requestBody, + { cause: lookupError }, + ); + } + 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) { + 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. * - * await using clients = await createMCPClient({ - * baseUrl: 'https://api.modelcontextprotocol.org', - * headers: { - * 'Authorization': 'Bearer YOUR_API_KEY', - * }, - * }); - * ``` - */ -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, - }, + * 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. + */ +async function withMcpSession( + { endpoint, headers, timeout }: McpRequest, + work: (client: Client) => Promise, +): Promise { + const expiresAt = retryTiming.now() + timeout; + // 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) => { + let retrying = false; + const response = await fetchWithRetry(url, init, { + deadline: expiresAt, + onRetry: () => { + if (!retrying) { + retrying = true; + rateLimited += 1; + } + }, + }); + if (retrying && response.status !== 429) { + rateLimited -= 1; + } + return response; }, }); + 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) { + // 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 > 0 && 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); + 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; }); +} - return { - client, - transport, - async [Symbol.asyncDispose]() { - await Promise.all([client.close(), transport.close()]); - }, - }; +interface ContentPart { + type: string; + text?: unknown; +} + +/** + * 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. 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 + * 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 ${JSON.stringify(name)} failed: ${payload || JSON.stringify(parsed)}`, + statusOf(parsed), + parsed, + ); + } + + // A copy, so content_parts below never writes into the caller's structuredContent. + const returned = { ...parsed }; + if (nonText.length > 0) { + returned.content_parts = nonText as unknown as JsonObject[]; + } + return returned; +} + +/** + * 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/rate-limit.test.ts b/src/rate-limit.test.ts new file mode 100644 index 00000000..1bbbfd5c --- /dev/null +++ b/src/rate-limit.test.ts @@ -0,0 +1,511 @@ +/** + * 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 { delay, http, HttpResponse } from 'msw'; +import { TEST_BASE_URL } from '../mocks/constants'; +import { mockAccounts } from '../mocks/handlers.stackone-accounts'; +import { type RecordedToolCall, accountMcpTools, createMcpApp } from '../mocks/mcp-server'; +import { 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] = {}) => + 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; + /** The `Retry-After` each 429 carries. Default: `'0'`. */ + retryAfter?: 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': throttle.retryAfter ?? '0' }, + }); + } + return app.fetch(request); + }), + ); + 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 }); + + 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\\] POST ${TEST_BASE_URL}/mcp was rate limited \\(429\\) on attempt 1 of 4; retrying in 0s$`, + ), + ), + ]); + }); + + 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([ + `[@stackone/ai] GET ${TEST_BASE_URL}/accounts was rate limited (429) on attempt 1 of 4; retrying in 0s`, + ]); + }); +}); + +describe('a 429 that outlasts its retries', () => { + 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 1 of 4', + 'attempt 2 of 4', + 'attempt 3 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('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([ + `[@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 () => { + 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); + }); +}); + +// 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([]); + }); + + // 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( + 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('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`, + ); + }); + + // 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', () => { + 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/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 deleted file mode 100644 index 08332e2b..00000000 --- a/src/rpc-client.test.ts +++ /dev/null @@ -1,303 +0,0 @@ -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 { StackOneAPIError } from './utils/error-stackone-api'; - -/** - * 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 response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'bamboohr_get_employee', - body: { fields: 'name,email' }, - path: { id: 'emp-123' }, - }), - ); - - // Response matches server's ActionsRpcResponseApiModel structure - expect(response).toHaveProperty('data'); - expect(response.data).toMatchObject({ - id: 'emp-123', - name: 'Test Employee', - }); -}); - -test('should send correct payload structure', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); - - 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' }, - }), - ); - - // 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' }, - }, - }); -}); - -test('should handle list actions with array data', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); - - const response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'bamboohr_list_employees', - }), - ); - - // 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) }, - ]); -}); - -test('should throw StackOneAPIError on server error', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); - - await expect( - client.actions.rpcAction({ - action: 'test_error_action', - }), - ).rejects.toThrow(StackOneAPIError); -}); - -test('should include request body in error for debugging', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); - - await expect( - client.actions.rpcAction({ - action: 'test_error_action', - body: { debug: 'data' }, - }), - ).rejects.toMatchObject({ - statusCode: 500, - requestBody: { action: 'test_error_action' }, - }); -}); - -test('should work with only action parameter', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); - - const response = await client.actions.rpcAction({ - action: 'simple_action', - }); - - // Response has data field (server returns { data: { action, received } }) - expect(response).toHaveProperty('data'); -}); - -test('should send x-account-id as HTTP header', async () => { - const client = new RpcClient({ - serverURL: TEST_BASE_URL, - security: { username: 'test-api-key' }, - }); - - const response = expectJsonResponse( - await client.actions.rpcAction({ - action: 'test_account_id_header', - headers: stackOneHeadersSchema.parse({ 'x-account-id': 'test-account-123' }), - }), - ); - - // 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', - }); -}); - -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 - * - * 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. - */ -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. - 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().actions.rpcAction({ - action: 'googledrive_unified_download_file', - path: { id: 'file-123' }, - query: { export_format: 'application/pdf' }, - }); - - expect(isBinaryDownloadResult(result)).toBe(true); - if (!isBinaryDownloadResult(result)) throw new Error('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); - 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, { - status: 200, - headers: { 'content-type': 'application/octet-stream' }, - }), - ), - ); - - const result = await newClient().actions.rpcAction({ action: 'some_unified_download_file' }); - - expect(isBinaryDownloadResult(result)).toBe(true); - if (!isBinaryDownloadResult(result)) throw new Error('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' }, - }); - - expect(isBinaryDownloadResult(result)).toBe(false); - expect(result).toHaveProperty('data'); - }); - - 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}}', { - 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); - }); -}); diff --git a/src/rpc-client.ts b/src/rpc-client.ts deleted file mode 100644 index 45f45a4f..00000000 --- a/src/rpc-client.ts +++ /dev/null @@ -1,161 +0,0 @@ -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 { - 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'; - -/** - * Custom RPC client for StackOne API. - * Replaces the @stackone/stackone-client-ts dependency. - * - * @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 class RpcClient { - private readonly baseUrl: string; - private readonly authHeader: string; - private readonly timeout: number; - - 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; - } - - /** - * Actions namespace containing RPC methods - */ - 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, - ...(validatedRequest.defender_config !== undefined && { - defender_config: validatedRequest.defender_config, - }), - 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; - - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.timeout); - - let response: Response; - let responseBody: unknown; - try { - response = await fetch(url, { - method: 'POST', - headers: httpHeaders, - body: JSON.stringify(requestBody), - signal: controller.signal, - }); - - // 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); - } - - if (!response.ok) { - throw new StackOneAPIError( - `RPC action failed for ${url}`, - response.status, - responseBody, - requestBody, - ); - } - - const validation = rpcActionResponseSchema.safeParse(responseBody); - - if (!validation.success) { - throw new StackOneAPIError( - `Invalid RPC action response for ${url}`, - response.status, - responseBody, - requestBody, - ); - } - - return validation.data; - }, - }; -} diff --git a/src/schema.test.ts b/src/schema.test.ts new file mode 100644 index 00000000..9ba138b1 --- /dev/null +++ b/src/schema.test.ts @@ -0,0 +1,139 @@ +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('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); + }); + + 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 345abfa8..d0b61f60 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -1,76 +1,113 @@ -import { z } from 'zod/v4-mini'; -import { stackOneHeadersSchema } from './headers'; - /** - * Zod schema for nested defender configuration sent with each RPC request + * 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. */ -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()), -}); +import type { JSONSchema, JsonSchemaProperties, ToolParameters } from './types'; +import { setEntry } from './utils/set-entry'; -/** - * Zod schema for RPC action request validation - * @see https://docs.stackone.com/platform/api-reference/actions/make-an-rpc-call-to-an-action - */ -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())), -}); +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)) { + setEntry(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/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/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..4346beca 100644 --- a/src/tool.test.ts +++ b/src/tool.test.ts @@ -1,38 +1,15 @@ +import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { jsonSchema } from 'ai'; -import { BaseTool, StackOneTool, Tools } from './tool'; -import { - type AISDKToolResult, - type ExecuteConfig, - type JSONSchema, - ParameterLocation, - type ToolParameters, -} from './types'; +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 { toolParametersFromInputSchema } from './schema'; +import { BaseTool, StackOneMcpTool, StackOneTool, Tools } from './tool'; +import type { AISDKToolResult, JsonObject, JSONSchema, ToolParameters } from './types'; 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'; +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` @@ -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,855 @@ 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( + new StackOneError( + 'Tool "test_tool" has no executor. Override execute() to run a hand-built tool.', + ), + ); }); - it('should handle API errors', async () => { - const tool = createMockTool(); + describe('toJsonSchema', () => { + it('is the served schema, verbatim', () => { + expect(localTool('rich', richSchema).toJsonSchema()).toEqual(richSchema); + }); + + 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 = {}; - 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; + expect(tool.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('omits an empty required list', () => { + expect( + localTool('t', { type: 'object', properties: {}, required: [] }).toJsonSchema(), + ).toEqual({ + type: 'object', + properties: {}, + }); + }); }); - it('should convert to Anthropic tool format', () => { - const tool = createMockTool(); - const anthropicFormat = tool.toAnthropic(); + /** + * 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; + }, + ], + [ + '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'); + }, + ); - 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.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' }, + ]); + }); - 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.each(adapters)('%s is otherwise exactly the served root', async (_name, adapt) => { + expect(await adapt()).toEqual(providerRoot); + }); - 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('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); + }); - 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('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 convert to Claude Agent SDK tool format', async () => { - const tool = createMockTool(); + 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' } } }, + }, + }); + }); - const claudeTool = await tool.toClaudeAgentSdkTool(); + 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' } } }, + }); + }); - 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'); + it('converts to the OpenAI Responses shape, strict by default', () => { + const strict = simpleTool().toOpenAIResponses(); + expect(strict).toMatchObject({ type: 'function', name: 'test_tool', strict: true }); - // 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'); + const lax = simpleTool().toOpenAIResponses({ strict: false }); + expect(lax.strict).toBe(false); + expect(lax.parameters).not.toHaveProperty('additionalProperties'); }); - it('should include execution metadata by default in AI SDK conversion', async () => { - const tool = createMockTool(); + 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(); + }); - const aiSdkTool = await tool.toAISDK(); - const execution = aiSdkTool.test_tool.execution; + 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/, + ); + }); - 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('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 allow disabling execution metadata exposure for AI SDK conversion', async () => { - const tool = createMockTool().setExposeExecutionMetadata(false); + 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 aiSdkTool = await tool.toAISDK(); + const result = await definition.handler({}); - expect(aiSdkTool.test_tool.execution).toBeUndefined(); + expect(JSON.parse(result.content[0]?.text ?? '')).toEqual({ + content: Buffer.from('%PDF').toString('base64'), + ok: true, + }); }); +}); - 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' } }, - }, - }, - }, - { - kind: 'http', - method: 'GET', - url: 'https://example.com/complex', - bodyType: 'json', - params: [], - }, - ); +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 }), + endpoint: `${TEST_BASE_URL}/mcp`, + apiKey: 'test-key', + accountId: 'acc1', + timeout: 5_000, + }); - const aiSdkTool = await complexTool.toAISDK(); + 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' }, + }; - // Check that the tool is defined - expect(aiSdkTool).toBeDefined(); - expect(aiSdkTool.complex_tool).toBeDefined(); + const result = await actionTool().execute(args); - // Check that inputSchema is defined - expect(aiSdkTool.complex_tool.inputSchema).toBeDefined(); + 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 } }, + }); + }); - // 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'); + // `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}'); - // 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'); + expect(Object.entries(calls[0]?.arguments ?? {})).toEqual([ + ['__proto__', 'p'], + ['constructor', 'c'], + ['q', 1], + ]); }); - it('should execute AI SDK tool with parameters', async () => { - const tool = createMockTool(); - const aiSdkTool = await tool.toAISDK(); - - expect(aiSdkTool.test_tool.execute).toBeDefined(); + 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); + }); - const result = await executeAISDKTool(aiSdkTool, 'test_tool', { id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); + it('accepts arguments as a JSON string', async () => { + await actionTool().execute('{"path":{"id":"7"}}'); + expect(calls[0]?.arguments).toEqual({ path: { id: '7' } }); }); - it('should return error message as string when AI SDK tool execution fails', async () => { - const tool = createMockTool(); - const aiSdkTool = await tool.toAISDK(); + 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(() => {}); - expect(aiSdkTool.test_tool.execute).toBeDefined(); + await actionTool().execute({ headers: { [name]: value } }); - // 'invalid' id returns 400 error via MSW handler - const result = await executeAISDKTool(aiSdkTool, 'test_tool', { id: 'invalid' }); - expect(result).toMatch(/Error executing tool:/); + expect(calls[0]?.arguments.headers).toEqual({}); + expect(calls[0]?.accountId).toBe('acc1'); + vi.restoreAllMocks(); }); - it('should set and get headers', () => { - const tool = createMockTool(); + it('keeps a header a nested schema declares, and drops one carrying CR/LF', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + 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(); + }); - // Set headers - const headers = { 'X-Custom-Header': 'test-value' }; - tool.setHeaders(headers); + 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(actionTool().execute(input)).rejects.toThrow(message); + }); - // Headers should include custom header - const updatedHeaders = tool.getHeaders(); - expect(updatedHeaders['X-Custom-Header']).toBe('test-value'); + it('rejects a non-object, non-string argument', async () => { + // @ts-expect-error - intentionally passing an invalid type + await expect(actionTool().execute(12345)).rejects.toThrow( + new ToolArgumentsError('Tool arguments for "crm_update_contact" must be a JSON object'), + ); + }); - // Set additional headers - tool.setHeaders({ 'X-Another-Header': 'another-value' }); + 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([]); + }, + ); + + // What a model emits when a token boundary splits an emoji: not Unicode text, so not UTF-8. + it.each([ + ['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([]); + }); - // 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'); + it('accepts a surrogate pair', async () => { + await actionTool().execute({ name: 'Ada \uD83D\uDE00' }); + expect(calls).toHaveLength(1); }); - it('should use basic authentication', async () => { - const headers = { - Authorization: `Basic ${Buffer.from('testuser:testpass').toString('base64')}`, - }; - const tool = createMockTool(headers); + // 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() + .execute(text) + .catch((caught: unknown) => caught); - const result = await tool.execute({ id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); - }); + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as Error).message).toMatch( + /^Invalid JSON in arguments for "crm_update_contact": /, + ); + expect(calls).toEqual([]); + }, + ); - it('should use bearer authentication', async () => { - const headers = { - Authorization: 'Bearer test-token', - }; - const tool = createMockTool(headers); + 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); - const result = await tool.execute({ id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as Error).message).toMatch(/undefined is not a JSON value/); + expect(calls).toEqual([]); }); - it('should use api-key authentication', async () => { - const apiKey = 'test-api-key'; - const headers = { - Authorization: `Bearer ${apiKey}`, - }; - const tool = createMockTool(headers); + 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); - const result = await tool.execute({ id: '123' }); - expect(result).toEqual({ id: '123', name: 'Test' }); + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as Error).message).toMatch(/undefined is not a JSON value/); + expect(calls).toEqual([]); }); -}); -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' }, - }, - ); + it('rejects a circular reference', async () => { + const body: JsonObject = { name: 'Ada' }; + body.self = body; - await expect(rpcTool.execute({})).rejects.toThrow( - 'BaseTool.execute is only available for HTTP-backed tools', - ); - }); + const error = await actionTool() + .execute({ body }) + .catch((caught: unknown) => caught); - it('should throw error for invalid parameter type', async () => { - const tool = createMockTool(); + expect(error).toBeInstanceOf(ToolArgumentsError); + expect((error as Error).message).toMatch(/circular reference/); + expect(calls).toEqual([]); + }); - // @ts-expect-error - intentionally passing invalid type - await expect(tool.execute(12345)).rejects.toThrow('Invalid parameters type'); + 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('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('is refused by the server when it has no account', async () => { + const error = (await actionTool() + .setAccountId(undefined) + .execute({}) + .catch((caught: unknown) => caught)) as StackOneAPIError; - 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', - }); - } + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(400); }); - 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('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, }, - ); - - const aiSdkTool = await localTool.toAISDK({ executable: false }); - const execution = aiSdkTool.local_tool.execution; + }); - 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(await actionTool().execute({})).toEqual({ isError: false, result: link }); }); - 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: [], + 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, }, - headers: { 'X-Custom': 'value' }, }; + serve({ + crm_update_contact: { + isError: true, + content: [{ type: 'text', text: JSON.stringify(structuredContent) }], + structuredContent, + }, + }); - const aiSdkTool = await tool.toAISDK({ execution: customExecution }); - const execution = aiSdkTool.test_tool.execution; + const error = (await actionTool() + .execute({}) + .catch((caught: unknown) => caught)) as StackOneAPIError; - 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' }); + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(501); }); - it('should return undefined execution when execution option is false', async () => { - const tool = createMockTool(); + it('can be rebound to another account', async () => { + const tool = actionTool(); + + tool.setAccountId('acc2'); + await tool.execute({}); - const aiSdkTool = await tool.toAISDK({ execution: false }); - expect(aiSdkTool.test_tool.execution).toBeUndefined(); + expect(tool.getAccountId()).toBe('acc2'); + expect(calls[0]?.accountId).toBe('acc2'); }); +}); - it('should return undefined execute when executable option is false', async () => { - const tool = createMockTool(); +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?tool-mode=search_execute`, + apiKey: 'test-key', + accountId: 'acc1', + timeout: 5_000, + }); - const aiSdkTool = await tool.toAISDK({ executable: false }); - expect(aiSdkTool.test_tool.execute).toBeUndefined(); - }); + 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 get headers from tool without requestBuilder', () => { - const rpcTool = new BaseTool( - 'rpc_tool', - 'RPC tool', - { type: 'object', properties: {} }, + expect(result).toMatchObject({ + isError: false, + result: { data: { nodes: [] }, echoed_query: { page_size: 2 } }, + }); + expect(calls).toEqual([ { - kind: 'rpc', - method: 'test_method', - url: 'https://api.example.com/rpc', - payloadKeys: { action: 'action', body: 'body' }, + accountId: 'acc1', + toolMode: 'search_execute', + name: 'mock_acc1_execute_action', + arguments: { action_id: 'mock_list_items', query: { page_size: 2 } }, }, - { 'X-Custom': 'value' }, - ); - - 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' }, + // The meta tools take a `headers` object the server unpacks, and these arguments are + // model-controlled. This schema declares no headers at all, so nothing survives. + it('drops every model-supplied header', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + 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', }, - ); + }); - rpcTool.setHeaders({ 'X-New-Header': 'new-value' }); - expect(rpcTool.getHeaders()).toEqual({ 'X-New-Header': 'new-value' }); + expect(calls[0]?.arguments.headers).toEqual({}); + vi.restoreAllMocks(); }); -}); -describe('Tools', () => { - it('should get tool by name', () => { - const tool = createMockTool(); - const tools = new Tools([tool]); - - expect(tools.getTool('test_tool')).toBe(tool); - expect(tools.getTool('nonexistent')).toBeUndefined(); + it('keeps a header its own schema declares', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + await mcpTool({ + headers: { type: 'object', properties: { 'x-trace': { type: 'string' } } }, + }).execute({ + action_id: 'mock_list_items', + headers: { 'X-Trace': 'abc', 'X-Other': 'no' }, + }); + expect(calls[0]?.arguments.headers).toEqual({ 'X-Trace': 'abc' }); + vi.restoreAllMocks(); }); - 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', - }, - ], - }, - ); - - 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', - }, - ); - - const tools = new Tools([tool1, tool2]); - const openAITools = tools.toOpenAI(); + 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; - 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.message).toContain('Unknown action mock_not_a_real_action'); + expect(error.statusCode).toBe(404); }); - 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', - }, - ], - }, - ); - - 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', - }, - ], - }, - ); - - const tools = new Tools([tool1, tool2]); - const anthropicTools = tools.toAnthropic(); - - 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'); + 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' } }); }); +}); - 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: [], - }, - ); +describe('Tools', () => { + const named = (name: string) => localTool(name, { type: 'object', properties: {} }); - const tools = new Tools([tool1, tool2]); - const responsesTools = tools.toOpenAIResponses(); + it('looks tools up by name, first match wins', () => { + const first = named('dup'); + const tools = new Tools([first, named('dup'), named('other')]); - 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(tools.getTool('dup')).toBe(first); + expect(tools.getTool('missing')).toBeUndefined(); + expect(tools.length).toBe(3); }); - 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 }); - - expect(responsesTools[0].strict).toBe(false); + 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 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', - }, - ], - }, - { - authorization: 'Bearer test_key', - }, - ); - - const tools = new Tools([tool1, tool2]); - - const aiSdkTools = await tools.toAISDK(); + it('filters, maps, iterates and copies', () => { + const tools = new Tools([named('a_x'), named('b_x')]); - 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'); + 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 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', - }, + it('tells StackOne tools apart', () => { + const stackOneTool = new StackOneTool( + 's', + '', + { type: 'object', properties: {} }, + { kind: 'local' }, + 'acc', ); + const tools = new Tools([named('plain'), stackOneTool]); - const tools = new Tools([tool1, tool2]); + expect(tools.getStackOneTools()).toEqual([stackOneTool]); + expect(tools.getStackOneTool('s').getAccountId()).toBe('acc'); + expect(() => tools.getStackOneTool('plain')).toThrow(StackOneError); + expect(tools.isStackOneTool(stackOneTool)).toBe(true); + }); - const mcpServer = await tools.toClaudeAgentSdk(); + it('converts every tool with every adapter', async () => { + const tools = new Tools([named('a'), localTool('b', richSchema)]); - expect(mcpServer).toBeDefined(); - expect(mcpServer.type).toBe('sdk'); - expect(mcpServer.name).toBe('stackone-tools'); - expect(mcpServer.instance).toBeDefined(); + expect(tools.toJsonSchema().map((entry) => entry.parameters)).toEqual([ + { type: 'object', properties: {} }, + richSchema, + ]); + 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']); }); - 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', + it('builds a Claude Agent SDK MCP server', async () => { + const mcpServer = await new Tools([named('a')]).toClaudeAgentSdk({ + serverName: 'custom', serverVersion: '2.0.0', }); - expect(mcpServer).toBeDefined(); expect(mcpServer.type).toBe('sdk'); - expect(mcpServer.name).toBe('my-custom-server'); + expect(mcpServer.name).toBe('custom'); expect(mcpServer.instance).toBeDefined(); }); - - 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', - }, - ); - - const tools = new Tools([tool1, tool2]); - - let count = 0; - for (const tool of tools) { - expect(tool).toBeDefined(); - expect(tool.name).toBeDefined(); - count++; - } - - expect(count).toBe(2); - }); }); -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'); - }); - - 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'); +describe('ToolParameters typing', () => { + it('accepts a served schema as parameters', () => { + const parameters: ToolParameters = toolParametersFromInputSchema(richSchema); + expect(parameters.type).toBe('object'); }); +}); - 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(''); +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('should return lowercase connector', () => { - const tool = new BaseTool( - 'BambooHR_create_employee', - 'Create employee', - { type: 'object', properties: {} }, - { kind: 'http', method: 'POST', url: 'https://example.com', bodyType: 'json', params: [] }, - ); - expect(tool.connector).toBe('bamboohr'); - }); -}); + it('runs each call and pairs its result with the call id', async () => { + const { tools, seen } = toolsWith(async () => ({ data: { n: 1 } })); -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 messages = await tools.executeOpenAIToolCalls([ + call('linear_list_issues', '{"body_variables": {}}'), ]); - const connectors = tools.getConnectors(); - expect(connectors).toEqual(new Set(['bamboohr', 'hibob', 'slack'])); + expect(messages).toEqual([ + { role: 'tool', tool_call_id: 'call_1', content: '{"data":{"n":1}}' }, + ]); + expect(seen).toEqual(['{"body_variables": {}}']); }); - it('should return empty set for empty tools', () => { - const tools = new Tools([]); - expect(tools.getConnectors()).toEqual(new Set()); - }); + it('keeps the order of several calls', async () => { + const { tools } = toolsWith(async (args) => ({ echoed: args as string })); - 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: [] }, - ), + const messages = await tools.executeOpenAIToolCalls([ + call('linear_list_issues', '{"a":1}', 'c1'), + call('linear_list_issues', '{"a":2}', 'c2'), ]); - const connectors = tools.getConnectors(); - expect(connectors).toEqual(new Set(['bamboohr'])); + expect(messages.map((message) => message.tool_call_id)).toEqual(['c1', 'c2']); }); -}); - -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; + 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 }]); + }); - expect(properties.arrayWithItems.items).toBeDefined(); - expect((properties.arrayWithItems.items as JSONSchema).type).toBe('number'); + 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', + }); }); - 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; + const [message] = await tools.executeOpenAIToolCalls([call('linear_list_issues')]); - expect(nestedObject.type).toBe('object'); - expect(nestedObject.properties).toBeDefined(); + expect(JSON.parse(message?.content as string)).toEqual({ + error: '400 Bad Request: path.id is missing', + response_body: { message: 'path.id is missing' }, }); }); - 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' }, - ); + it('reports malformed arguments the same way', async () => { + const tool = new StackOneMcpTool({ + name: 'linear_list_issues', + description: '', + parameters: { type: 'object', properties: {} }, + 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'), + ]); + expect(JSON.parse(message?.content as string).error).toMatch(/Invalid JSON in arguments/); + }); - const aiSdkTool = await tool.toAISDK(); - const toolObj = aiSdkTool[tool.name]; + 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"', + }); + }); - 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'); + 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"', + }); + }); - // @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('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('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' }, - ); + 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'); + }); - 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(); + 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 62912401..f9aee9be 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -1,27 +1,40 @@ 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'; -import { RequestBuilder } from './requestBuilder'; +import { SUBMIT_FEEDBACK_TOOL_NAME } from './consts'; +import { + type DeclaredHeaders, + buildRequestHeaders, + declaredHeaders, + sanitiseHeaderArguments, +} from './headers'; +import { type EndUserSource, callMcpTool, withEndUser } from './mcp-client'; +import { cloneJson, foldRootComposition } from './schema'; import type { AISDKToolDefinition, AISDKToolResult, ClaudeAgentSdkOptions, ExecuteConfig, ExecuteOptions, - HttpExecuteConfig, JsonObject, JSONSchema, - LocalExecuteConfig, - RpcExecuteConfig, + McpExecuteConfig, ToolExecution, ToolParameters, } from './types'; - +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'; /** @@ -31,167 +44,110 @@ import { tryImport } from './utils/try-import'; type ObjectJSONSchema = OverrideProperties; /** - * Base class for all tools. Provides common functionality for executing API calls - * and converting to various formats (OpenAI, AI SDK) + * 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 + * to each framework's tool format. + * + * `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; 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 + * Control whether execution metadata should be exposed in AI SDK conversions. */ - setHeaders(headers: Record): BaseTool { - this.#headers = { ...this.#headers, ...headers }; - if (this.requestBuilder) { - this.requestBuilder.setHeaders(headers); - } + setExposeExecutionMetadata(expose: boolean): this { + this.#exposeExecutionMetadata = expose; 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. + * Execute the tool with the provided parameters. * - * Tool names follow the format `{connector}_{action}_{entity}`, - * e.g. `"bamboohr_list_employees"` → `"bamboohr"`. + * @throws StackOneError Always, on a `BaseTool`: override this to make a tool executable. */ - get connector(): string { - return this.name.split('_')[0]?.toLowerCase() ?? ''; + async execute( + _inputParams?: JsonObject | string, + _options?: ExecuteOptions, + ): Promise { + throw new StackOneError( + `Tool ${JSON.stringify(this.name)} has no executor. Override execute() to run a hand-built tool.`, + ); } /** - * Control whether execution metadata should be exposed in AI SDK conversions. + * 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. */ - setExposeExecutionMetadata(expose: boolean): this { - this.#exposeExecutionMetadata = expose; - return this; + toJsonSchema(): ObjectJSONSchema { + const { required, ...rest } = cloneJson(this.parameters); + const schema: Record = { + ...rest, + type: rest.type || 'object', + properties: rest.properties ?? {}, + }; + if (Array.isArray(required) && required.length > 0) { + schema.required = required; + } + return schema as ObjectJSONSchema; } /** - * Execute the tool with the provided parameters + * {@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. */ - 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)}`, - ); - } + #toProviderSchema(): ObjectJSONSchema { + return foldRootComposition(this.toJsonSchema()) as ObjectJSONSchema; } - /** - * 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 - */ - toJsonSchema(): ObjectJSONSchema { - return { - type: 'object', - properties: this.parameters.properties, - required: this.parameters.required, - }; + #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 { @@ -199,26 +155,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; @@ -228,7 +197,7 @@ export class BaseTool { description: this.description, strict, parameters: { - ...this.toJsonSchema(), + ...this.#toProviderSchema(), ...(strict ? { additionalProperties: false } : {}), }, }; @@ -238,6 +207,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<{ @@ -252,7 +224,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 { @@ -262,14 +234,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 } = { @@ -277,9 +255,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( @@ -292,7 +270,7 @@ export class BaseTool { options.execution !== undefined ? options.execution : this.#exposeExecutionMetadata - ? this.createExecutionMetadata() + ? this.#createExecutionMetadata() : false; const toolDefinition = { @@ -320,23 +298,336 @@ 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 ToolArgumentsError If the arguments are not a JSON object. + */ + protected parseArguments(input: JsonObject | string | undefined): JsonObject { + if (input === undefined || input === null) { + return {}; + } + let parsed: unknown = input; + if (typeof input === 'string') { + try { + parsed = JSON.parse(input); + } catch (error) { + throw new ToolArgumentsError( + `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 ${JSON.stringify(this.name)} must be a JSON object`, + ); + } + return { ...parsed }; + } +} + +/** + * 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; + readonly #apiKey: string; + readonly #extraHeaders: Record; + readonly #endUsers: EndUserSource | undefined; + readonly #timeout: number; + readonly #declaredHeaders: DeclaredHeaders; + + constructor(options: { + name: string; + description: string; + parameters: ToolParameters; + endpoint: string; + apiKey: string; + accountId?: string; + timeout: number; + extraHeaders?: Record; + /** + * 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. + */ + endUsers?: EndUserSource; + }) { + 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.#endUsers = options.endUsers; + this.#timeout = options.timeout; + this.#declaredHeaders = declaredHeaders(options.parameters.properties); + } + + /** + * Call the tool. + * + * 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`, `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` + * 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 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. + */ + override async execute( + inputParams?: JsonObject | string, + options?: ExecuteOptions, + ): 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 }; + } + + const accountId = this.getAccountId(); + 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, + ), + ); + } +} + +/** + * 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}`; +} + +/** 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') { + 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 unencodable(toolName, `${value} is not a JSON number`); + } + return; + } + if (Array.isArray(value)) { + if (seen.has(value)) { + throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); + } + seen.add(value); + for (let index = 0; index < value.length; index++) { + const item = value[index]; + const itemPath = `${path}[${index}]`; + if (item === undefined) { + throw unencodable( + toolName, + `undefined is not a JSON value (at ${JSON.stringify(itemPath)})`, + ); + } + assertJsonValue(item, itemPath, toolName, seen); + } + seen.delete(value); + return; + } + if (isPlainObject(value)) { + if (seen.has(value)) { + throw unencodable(toolName, `circular reference (at ${JSON.stringify(path)})`); + } + seen.add(value); + for (const [key, entry] of Object.entries(value)) { + // An object property set to undefined is treated as absent, as JSON.stringify treats it. + if (entry === undefined) { + continue; + } + assertJsonKey(key, path, toolName); + assertJsonValue(entry, `${path}.${key}`, toolName, seen); + } + seen.delete(value); + return; + } + 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}. + * + * @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; + } + assertJsonKey(key, undefined, toolName); + assertJsonValue(value, key, toolName, new Set()); + } +} + +/** + * 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 || {} }; } /** @@ -346,7 +637,7 @@ export class Tools implements Iterable { private tools: BaseTool[]; constructor(tools: BaseTool[]) { - this.tools = tools; + this.tools = [...tools]; } /** @@ -357,12 +648,24 @@ 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); } + /** + * 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[] { + warnOnDuplicateNames(this.tools); + const seen = new Set(); + return this.tools.filter((tool) => !seen.has(tool.name) && seen.add(tool.name)); + } + /** * Get a StackOne tool by name */ @@ -393,7 +696,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(), @@ -404,7 +707,55 @@ 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()); + } + + /** + * 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 ${JSON.stringify(name)}` }; + } else { + try { + result = await tool.execute(args); + } catch (error) { + if (!(error instanceof StackOneError)) { + throw error; + } + const body = error instanceof StackOneAPIError ? error.responseBody : undefined; + result = { + error: error.message, + ...(body != null && body !== '' ? { response_body: body } : {}), + }; + } + } + messages.push({ role: 'tool', tool_call_id: id, content: serializeToolResult(result) }); + } + return messages; } /** @@ -412,7 +763,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()); } /** @@ -420,7 +771,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)); } /** @@ -432,7 +783,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; @@ -476,7 +827,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( @@ -503,31 +854,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 */ @@ -566,3 +892,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 new file mode 100644 index 00000000..1f51d3a2 --- /dev/null +++ b/src/toolsets.search-execute.test.ts @@ -0,0 +1,1001 @@ +/** + * 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 { retryTiming } from './utils/fetch-retry'; +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(() => { + 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', 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 () => { + 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([ + 'tool-mode=search_execute', + undefined, + ]); + }); +}); + +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({ + isError: false, + result: { 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.result as JsonObject).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('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'); + 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( + '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({}); + }); + + // *_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() + .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('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'); + }); + + // 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']); + + 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( + 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([]); + }); + + 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 () => { + 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/, + ], + [ + '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); + 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({ + isError: false, + result: { message: 'Feedback recorded', session_id: MOCK_SEARCH_SESSION_ID }, + }); + expect(calls).toEqual([ + { + accountId: 'acc1', + toolMode: 'search_execute', + 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' }); + }); + + // `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: [] }, + 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']); + }); + + // 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 lowest 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', 'acc1', 'search_execute'], + ]); + }); + + it('calls on the lowest account id, not the first GET /accounts lists', 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', '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' }) + .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('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' }) + .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({ + rating: 'positive', + toolNames: 'a' as never, + }), + ).rejects.toThrow( + new ToolSetConfigError( + 'toolNames must be a list of tool names, not a string. Did you mean ["a"]?', + ), + ); + }); + + 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(); + + 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); +}); + +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('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('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, 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); + + 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('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); + }); + + 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('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 () => { + 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 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 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(); + + await toolset.execute('linear_list_issues'); + await toolset.execute('hibob_list_employees'); + + expect(listed).toEqual(['acc1', 'acc3']); + }); +}); diff --git a/src/toolsets.test-d.ts b/src/toolsets.test-d.ts index 2a7642f0..7e0b1b57 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 { ActionResult, JsonObject, JsonValue, SearchResult } from './types'; // Valid configurations - only accountId test('StackOneToolSetConfig accepts only accountId', () => { @@ -38,7 +39,32 @@ 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 +test('SearchResult declares the fields the server serves', () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toExtend< + 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.test.ts b/src/toolsets.test.ts index 4e5f1b1d..f2721132 100644 --- a/src/toolsets.test.ts +++ b/src/toolsets.test.ts @@ -1,1521 +1,1393 @@ /** - * 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 { SemanticSearchError } from './semantic-search'; import { - SearchTool, - StackOneToolSet, - ToolSetConfigError, - __resetDefenderInfoLog, -} from './toolsets'; + type McpToolDefinition, + type RecordedToolCall, + accountMcpTools, + 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(); + return { ...actual, listMcpTools: vi.fn(actual.listMcpTools) }; +}); -describe('StackOneToolSet', () => { - beforeEach(() => { - vi.stubEnv('STACKONE_API_KEY', 'test_key'); - }); +const listMock = vi.mocked(listMcpTools); +const { listMcpTools: realListMcpTools } = + await vi.importActual('./mcp-client'); - afterEach(() => { - vi.unstubAllEnvs(); +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(() => { + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + listMock.mockReset(); + listMock.mockImplementation(realListMcpTools); +}); + +describe('configuration', () => { + it('requires an API key', () => { + vi.stubEnv('STACKONE_API_KEY', ''); + expect(() => new StackOneToolSet()).toThrow(ToolSetConfigError); + expect(() => new StackOneToolSet()).toThrow( + 'An API key must be provided, either to the toolset or in the STACKONE_API_KEY environment variable', + ); }); - describe('initialization', () => { - it('should initialize with API key from constructor', () => { - 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); + }); - expect(toolset).toBeDefined(); - // @ts-expect-error - Accessing private property for testing - expect(toolset.authentication?.credentials?.username).toBe('custom_key'); - }); + it('ignores STACKONE_ACCOUNT_ID, so the environment cannot change the account scope', async () => { + vi.stubEnv('STACKONE_ACCOUNT_ID', 'acc3'); - it('should initialize with API key from environment', () => { - const toolset = new StackOneToolSet(); + 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']); + }); - expect(toolset).toBeDefined(); - // @ts-expect-error - Accessing private property for testing - expect(toolset.authentication?.credentials?.username).toBe('test_key'); - }); + // 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'); - it('should initialize with custom values', () => { - const baseUrl = 'https://api.example.com'; - const headers = { 'X-Custom-Header': 'test' }; + newToolSet(); - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - baseUrl, - headers, - }); + 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 shared account on this API key is used. Pass an account id to scope the toolset.', + ]); + }); - // @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'); - }); + 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('should set API key in headers', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); + 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 shared account on this API key is used. Pass an account id to scope the toolset.', + ]); + }, + ); - // @ts-expect-error - Accessing private property for testing - expect(toolset.headers.Authorization).toBe('Basic Y3VzdG9tX2tleTo='); - }); + it('refuses both accountId and accountIds', () => { + expect(() => newToolSet({ accountId: 'a', accountIds: ['b'] } as never)).toThrow( + /Cannot provide both accountId and accountIds/, + ); + }); - it('should set account ID in headers if provided', () => { - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - accountId: 'test_account', - }); + 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( + new ToolSetConfigError( + 'accountIds must be a list of account ids, not a string. Did you mean ["acc1"]?', + ), + ); + }); - // 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'); - }); + 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('should allow setting account IDs via setAccounts', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); + it('refuses an empty accountId rather than widening to every account', () => { + expect(() => newToolSet({ accountId: '' })).toThrow( + new ToolSetConfigError('accountId must not be an empty string'), + ); + }); - const result = toolset.setAccounts(['account-1', 'account-2']); + it('returns itself from setAccounts for chaining', () => { + const toolset = newToolSet(); + expect(toolset.setAccounts(['acc1'])).toBe(toolset); + }); - // 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('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"'); + }); +}); - it('should initialize with multiple account IDs from constructor', () => { - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - accountIds: ['account-1', 'account-2', 'account-3'], - }); +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']); + }); - // @ts-expect-error - Accessing private property for testing - expect(toolset.accountIds).toEqual(['account-1', 'account-2', 'account-3']); - }); + it('lists every given account', async () => { + expect((await newToolSet().fetchTools({ accountIds: ['acc1', 'acc2', 'acc3'] })).length).toBe( + 5, + ); + }); - it('should initialize with empty accountIds array when not provided', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); + 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']); + }); - // @ts-expect-error - Accessing private property for testing - expect(toolset.accountIds).toEqual([]); - }); + it('lets fetchTools override setAccounts without changing it', async () => { + const toolset = newToolSet().setAccounts(['acc1', 'acc2']); - 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']); - }); + expect(names(await toolset.fetchTools({ accountIds: ['acc3'] }))).toEqual(['acc3_tool_1']); + expect((await toolset.fetchTools()).length).toBe(4); + }); - 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('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 set baseUrl from config', () => { - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - baseUrl: 'https://api.example.com', - }); + 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.baseUrl).toBe('https://api.example.com'); - }); + 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', + ]); }); +}); - describe('authentication', () => { - it('should configure basic auth with API key from constructor', () => { - const toolset = new StackOneToolSet({ apiKey: 'custom_key' }); +/** + * 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(); - // @ts-expect-error - Accessing private property for testing - expect(toolset.authentication).toEqual({ - type: 'basic', - credentials: { - username: 'custom_key', - password: '', - }, - }); - }); + expect(names(tools)).toEqual(['default_tool_1', 'default_tool_2']); + expect(listMock.mock.calls.map(([request]) => accountOf(request))).toEqual(['default']); + }); - it('should configure basic auth with API key from environment', () => { - const toolset = new StackOneToolSet(); + it('exposes the linked accounts', async () => { + const accounts = await newToolSet().fetchAccounts(); - // @ts-expect-error - Accessing private property for testing - expect(toolset.authentication).toEqual({ - type: 'basic', - credentials: { - username: 'test_key', - password: '', - }, - }); - }); + expect(accounts.map((account) => account.id)).toEqual(['default', 'dead']); + expect(accounts.filter((account) => account.status === 'active').map((a) => a.id)).toEqual([ + 'default', + ]); + }); - it('should throw ToolSetConfigError if no API key is provided and strict mode is enabled', () => { - vi.stubEnv('STACKONE_API_KEY', undefined); + 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); + }); - expect(() => { - new StackOneToolSet({ strict: true }); - }).toThrow(ToolSetConfigError); - }); + 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('should not override custom headers with authentication', () => { - const customHeaders = { - 'Custom-Header': 'test-value', - Authorization: 'Bearer custom-token', - }; + 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']); + }); - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - headers: customHeaders, - }); + 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); + }); - // @ts-expect-error - Accessing private property for testing - expect(toolset.headers).toEqual(customHeaders); - }); + 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(); - it('should combine authentication and account ID headers', () => { - const toolset = new StackOneToolSet({ - apiKey: 'custom_key', - accountId: 'test_account', - }); + await Promise.all([toolset.search('x'), toolset.fetchTools(), toolset.fetchTools()]); - 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'); - }); + expect(requests).toBe(1); }); - 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('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); + }); - const tools = await toolset.fetchTools(); - // 1 dummy_action tool + 1 feedback tool - expect(tools.length).toBe(2); + 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 tool = tools.toArray().find((t) => t.name === 'dummy_action'); - expect(tool).toBeDefined(); - expect(tool?.name).toBe('dummy_action'); + 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 an account id explicitly.', + ), + ); + }); - 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('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 executableTool = (await tool?.toAISDK())?.dummy_action; - expect(executableTool?.execute).toBeDefined(); - }); + 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"}'); + }); - 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); - }), - ); + 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 toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); - await toolset.fetchTools(); + 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`), + ); + }); +}); - expect(requestedUrl).toBe(`${TEST_BASE_URL}/mcp?param-style=flat_prefixed`); +/** 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'); }); - describe('account filtering', () => { - it('supports setAccounts() for chaining', () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + 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; - // Test chaining - const result = toolset.setAccounts(['acc1', 'acc2']); - expect(result).toBe(toolset); - }); + expect(error).toBeInstanceOf(StackOneAPIError); + expect(error.statusCode).toBe(404); + }); - it('fetches tools without account filtering when no accountIds provided', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + it('refuses execution without an account', async () => { + const tool = (await newToolSet().fetchTools({ accountIds: ['test-account'] })).getStackOneTool( + 'dummy_action', + ); + tool.setAccountId(undefined); - const tools = await toolset.fetchTools(); - // 2 default tools + 1 feedback tool - expect(tools.length).toBe(3); - 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'); - }); + const error = (await tool + .execute({ foo: 'bar' }) + .catch((caught: unknown) => caught)) as StackOneAPIError; + expect(error.statusCode).toBe(400); + }); +}); - it('uses x-account-id header when fetching tools with accountIds', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); +describe('listing', () => { + // No param-style pin: tools/call arguments are mapped by the server, whichever style it serves. + it('lists from the bare MCP endpoint, taking the server’s param-style', async () => { + fakeListing(() => []); + await newToolSet({ baseUrl: 'https://api.example.com/' }).fetchTools({ accountIds: ['acc1'] }); + expect(listMock.mock.calls[0]?.[0].endpoint).toBe('https://api.example.com/mcp'); + }); - // Fetch tools for acc1 - const tools = await toolset.fetchTools({ accountIds: ['acc1'] }); - // 2 acc1 tools + 1 feedback tool - expect(tools.length).toBe(3); - 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.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('uses setAccounts when no accountIds provided in fetchTools', 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]); + }); - // 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, + 1 feedback tool = 5 - expect(tools.length).toBe(5); - 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('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 accountIds from constructor when no accountIds provided in fetchTools', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountIds: ['acc1', 'acc2'], - }); - - // 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, + 1 feedback tool = 5 - expect(tools.length).toBe(5); - 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'); + 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('setAccounts overrides constructor accountIds', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountIds: ['acc1'], - }); + 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); + }); - // Override with setAccounts - toolset.setAccounts(['acc2', 'acc3']); - - // Fetch without accountIds - should use setAccounts, not constructor - 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); - 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('runs accounts concurrently, bounded by the slowest', async () => { + fakeListing(async (request) => { + await new Promise((resolve) => setTimeout(resolve, 150)); + 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']); + const started = performance.now(); + await newToolSet().fetchTools({ accountIds: ['a', 'b', 'c', 'd', 'e'] }); - // Fetch with accountIds - should override setAccounts - const tools = await toolset.fetchTools({ accountIds: ['acc3'] }); + // Sequential would be 5 × 150ms; give CI generous headroom. + expect(performance.now() - started).toBeLessThan(450); + }); - // Should fetch tools only for acc3 (ignoring acc1, acc2) + 1 feedback tool - expect(tools.length).toBe(2); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('acc3_tool_1'); - expect(toolNames).toContain('tool_feedback'); + 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)}`)]; }); - // 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', - }); - - const tools = await toolset.fetchTools({ accountIds: ['acc1', 'acc2', 'acc3'] }); - - 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'); - } - } + const tools = await newToolSet().fetchTools({ + accountIds: Array.from({ length: 25 }, (_, index) => `acc-${index}`), }); - 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'] }), - ]); - - 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(tools.length).toBe(25); + expect(peak).toBe(10); }); - 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'); + 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', + ]); + }); - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); + 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']); + }); - 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('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)}`)]; }); - 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 toolset = newToolSet(); + const [first, second] = await Promise.all([ + toolset.fetchTools({ accountIds: ['a', 'b'] }), + toolset.fetchTools({ accountIds: ['a', 'b'] }), + ]); - 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 }, - ); + // 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']); + }); - expect(result.mappedParams).toEqual({ - body: { name: 'test' }, - path: { id: '123' }, - query: { limit: 10 }, - headers: { 'x-custom': 'value' }, - }); + 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('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 tools = await newToolSet().fetchTools({ accountIds: ['a', 'b'] }); - const result = await tool.execute(JSON.stringify({ body: { name: 'test' } }), { - dryRun: true, - }); + expect(names(tools)).toEqual(['tool_a']); + expect(String(warnSpy.mock.calls[0]?.[0])).toMatch( + /Skipping account that failed to list tools — b: boom/, + ); + }); - expect(result.mappedParams).toEqual({ body: { name: 'test' } }); + 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 failures[accountOf(request) as 'a' | '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 error = await newToolSet() + .fetchTools({ accountIds: ['a', 'b'] }) + .catch((caught: unknown) => caught); - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + expect(error).toBeInstanceOf(ToolSetLoadError); + expect((error as Error).message).toBe( + 'Every account failed to list tools: a: boom for a; b: gone', + ); + expect((error as Error).cause).toBeInstanceOf(AggregateError); + expect(((error as Error).cause as AggregateError).errors).toEqual([failures.a, failures.b]); + }); - // @ts-expect-error - intentionally passing invalid type - await expect(tool.execute(12345)).rejects.toThrow('Invalid parameters type'); + // 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; }); - it('should wrap non-StackOneError in execute', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); + const one = await newToolSet({ accountId: 'a' }) + .fetchTools() + .catch((caught: unknown) => caught); + const many = await newToolSet() + .fetchTools({ accountIds: ['a', 'b'] }) + .catch((caught: unknown) => caught); - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + expect(one).toBe(revoked); + expect(many).toBe(revoked); + }); - // Pass invalid JSON string to trigger JSON.parse error - await expect(tool.execute('not valid json')).rejects.toThrow('Error executing RPC action'); + 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']; }); - it('should include extra params in rpcBody', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'test-account', - }); + const error = await newToolSet() + .fetchTools({ accountIds: ['a', 'b'] }) + .catch((caught: unknown) => caught); - 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(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]); + }); - // 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, + describe('an account that fails', () => { + let now = 0; + let failB = true; + 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 listedAccounts = () => listMock.mock.calls.map(([request]) => accountOf(request)); - 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'); + // 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(); - const result = await tool.execute( - { - path_id: '123', - query_limit: 10, - 'headers_x-custom': 'value', - body_name: 'test', - }, - { dryRun: true }, - ); + 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']); - 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' }); - expect((result.headers as Record)['x-custom']).toBe('value'); + expect(listedAccounts()).toEqual(['a', 'b']); + expect(warnSpy).toHaveBeenCalledOnce(); }); - it('preserves fields named after Object.prototype members', 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'); + it(`is listed again, alone, once ${FAILED_ACCOUNT_RETRY_MS}ms have passed`, async () => { + const toolset = newToolSet(); + await toolset.fetchTools({ accountIds: ['a', 'b'] }); - const result = await tool.execute( - { body_constructor: 'x', path_toString: 'y', query_valueOf: 'z' }, - { dryRun: true }, - ); - - 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' }); + 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('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('is warned about again when the retry fails too, and waits another period', async () => { + const toolset = newToolSet(); + await toolset.fetchTools({ accountIds: ['a', 'b'] }); - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + 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'] }); - 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 }, - ); - - expect(JSON.parse(nestedFirst.body as string).path).toEqual({ id: 'flat' }); - expect(JSON.parse(flatFirst.body as string).path).toEqual({ id: 'flat' }); + expect(listedAccounts()).toEqual(['a', 'b', 'b']); + expect(warnSpy).toHaveBeenCalledTimes(2); }); - 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', - }); - - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + it('is forgotten by clearCatalogCache()', async () => { + const toolset = newToolSet(); + await toolset.fetchTools({ accountIds: ['a', 'b'] }); - const result = await tool.execute( - { body: 'oops', path: 5, real_field: 'kept' }, - { dryRun: true }, - ); - - // `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(); + failB = false; + toolset.clearCatalogCache(); + expect(names(await toolset.fetchTools({ accountIds: ['a', 'b'] }))).toEqual([ + 'tool_a', + 'tool_b', + ]); }); }); - 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('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('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('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('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 }); +describe('filtering', () => { + const mixed = () => newToolSet({ accountId: 'mixed' }); - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody).not.toHaveProperty('defender_config'); - }); + 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', + ]); + }); - 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 }, - }); + 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 tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + 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']); + }); - const result = await tool.execute({ body: { name: 'test' } }); + 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); + }); - expect(result).toMatchObject({ - data: { received: { defender_config: { enabled: true } } }, - }); - }); + 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']); + }); +}); - 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, - }); +describe('catalog cache', () => { + const listingCount = () => listMock.mock.calls.length; - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + 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); + }); - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); + 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 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, - }); - }); + await toolset.fetchTools({ accountIds: ['acc1', 'acc2'] }); + await toolset.fetchTools({ accountIds: ['acc2', 'acc1', 'acc2'] }); + expect(listingCount()).toBe(4); + }); - 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 }, - }); + 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); + }); - const tools = await toolset.fetchTools(); - const tool = tools.toArray().find((t) => t.name === 'dummy_action'); - assert(tool, 'tool should be defined'); + 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); + }); - const result = await tool.execute({ body: { name: 'test' } }, { dryRun: true }); + 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); - const parsedBody = JSON.parse(result.body as string); - expect(parsedBody).not.toHaveProperty('defender_config'); - }); + toolset.setAccounts(['acc1']); + await toolset.fetchTools(); + expect(listingCount()).toBe(3); + }); - 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); + // 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')]; }); - 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'); - }); + await toolset.fetchTools(); + fakeListing(() => [def('fresh_tool')]); - it('returns "disabled" when defender is null', () => { - const toolset = new StackOneToolSet({ apiKey: 'test-key', defender: null }); - expect(toolset.defenderMode).toBe('disabled'); - }); + expect(names(await toolset.fetchTools())).toEqual(['fresh_tool']); + }); - 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'); - }); + 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)}`)]; }); - describe('override info log', () => { - beforeEach(() => { - __resetDefenderInfoLog(); - }); + await toolset.fetchTools(); + fakeListing((request) => [def(`fresh_${accountOf(request)}`)]); - 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(); - }); - }); + expect(names(await toolset.fetchTools())).toEqual(['fresh_acc1', 'fresh_acc2']); }); - 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 + 1 feedback tool - expect(tools.length).toBe(5); - 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('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; }); - - it('filters tools by actions with exact match', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - }); - - // Filter by exact action names - const tools = await toolset.fetchTools({ - actions: ['hibob_list_employees', 'hibob_create_employees'], - }); - - // 2 filtered tools + 1 feedback tool - expect(tools.length).toBe(3); - 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'); + fakeListing(async () => { + await released; + return [def('stale_tool')]; }); + const before = toolset.fetchTools(); + await vi.waitFor(() => expect(listMock).toHaveBeenCalledOnce()); - it('filters tools by actions with glob pattern', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - }); + toolset.clearCatalogCache(); + fakeListing(() => [def('fresh_tool')]); + const after = toolset.fetchTools(); + release(); - // Filter by glob pattern - const tools = await toolset.fetchTools({ actions: ['*_list_employees'] }); - - // 3 filtered tools + 1 feedback tool - expect(tools.length).toBe(4); - 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'); - }); + expect(names(await after)).toEqual(['fresh_tool']); + expect(names(await before)).toEqual(['stale_tool']); + expect(names(await toolset.fetchTools())).toEqual(['fresh_tool']); + }); - 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('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); + }); - // 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); - }), - ); + 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'); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); + const second = (await toolset.fetchTools()).getStackOneTool('acc1_tool_1'); - // Combine account and action filters - const tools = await toolset.fetchTools({ - accountIds: ['acc1', 'acc2'], - actions: ['*_list_employees'], - }); + expect(second).not.toBe(first); + expect(second.getAccountId()).toBe('acc1'); + }); - // 2 filtered tools + 1 feedback tool - 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).not.toContain('hibob_create_employees'); - expect(toolNames).not.toContain('bamboohr_get_employee'); - expect(toolNames).toContain('tool_feedback'); - }); + it('does not share nested schema between callers', async () => { + fakeListing(() => [def('t', { properties: { body_x: { type: 'object', properties: {} } } })]); + const toolset = newToolSet({ accountId: 'acc1' }); - 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' } }, - }, - }, - ]; + const first = (await toolset.fetchTools()).getTool('t'); + const nested = first?.parameters.properties.body_x?.properties; + assert(nested); + (nested as Record).injected = { type: 'string' }; - // 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); - }), - ); + const second = (await toolset.fetchTools()).getTool('t'); + expect(second?.parameters.properties.body_x?.properties).toEqual({}); + }); +}); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); +describe('tool mode', () => { + it('builds MCP tools by default', async () => { + fakeListing(() => [def('t')]); + expect((await newToolSet({ accountId: 'acc1' }).fetchTools()).getTool('t')).toBeInstanceOf( + StackOneMcpTool, + ); + }); - // Combine all filters - const tools = await toolset.fetchTools({ - accountIds: ['acc1'], - providers: ['hibob'], - actions: ['*_list_*'], - }); + 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(); - // Should only return hibob_list_employees (matches all filters) + 1 feedback tool - expect(tools.length).toBe(2); - const toolNames = tools.toArray().map((t) => t.name); - expect(toolNames).toContain('hibob_list_employees'); - expect(toolNames).toContain('tool_feedback'); - }); + expect(tools.getTool('t')).toBeInstanceOf(StackOneMcpTool); + expect(listMock.mock.calls[0]?.[0].endpoint).toBe( + `${TEST_BASE_URL}/mcp?tool-mode=search_execute`, + ); }); - 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: {}, - }); + 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(StackOneMcpTool); + expect((await toolset.fetchTools({ mode: 'individual' })).getTool('t')).toBeInstanceOf( + StackOneMcpTool, + ); + expect(listMock.mock.calls.map(([request]) => request.endpoint.split('?')[1])).toEqual([ + undefined, + 'tool-mode=individual', + ]); + }); +}); - // 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, - }); - }), - ); +describe('duplicate tool names', () => { + it('warns when two accounts serve the same name', async () => { + fakeListing(() => [def('hibob_list_employees'), def('hibob_get_employee')]); - const tools = await toolset.searchTools('list employees', { topK: 5 }); - const toolNames = tools.toArray().map((t) => t.name); + const tools = await newToolSet().fetchTools({ accountIds: ['a', 'b'] }); - expect(toolNames).toContain('hibob_list_employees'); - expect(toolNames).toContain('bamboohr_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])).toBe( + '[@stackone/ai] 2 tool name(s) are served by more than one account (hibob_get_employee, hibob_list_employees). The first one listed, from the lowest account id, is used — pass account ids to choose.', + ); + }); - 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: {}, - }); + // 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')]); - // Mock semantic search to fail - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return new HttpResponse('Service Unavailable', { status: 503 }); - }), - ); + const tools = await newToolSet().fetchTools({ accountIds: ['b', 'a'] }); - // Should fall back to local search without throwing - const tools = await toolset.searchTools('list employees', { - search: 'auto', - topK: 5, - }); + expect(tools.toArray().map((tool) => (tool as StackOneTool).getAccountId())).toEqual([ + 'a', + 'b', + ]); + expect(tools.getTool('hibob_list_employees')).toBe(tools.toArray()[0]); + }); - // Local search should return some results from the mixed provider tools - expect(tools.length).toBeGreaterThan(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(); + // 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('throws SemanticSearchError in semantic mode when API fails', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); + it('stays quiet when names are unique', async () => { + await newToolSet().fetchTools({ accountIds: ['acc1', 'acc2'] }); + expect(warnSpy).not.toHaveBeenCalled(); + }); +}); - // Mock semantic search to fail - server.use( - http.post(`${TEST_BASE_URL}/actions/search`, () => { - return new HttpResponse('Internal Server Error', { status: 500 }); - }), - ); +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(); + }); - await expect(toolset.searchTools('list employees', { search: 'semantic' })).rejects.toThrow( - SemanticSearchError, + 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', ); - }); - 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, - }); + expect(tool).toBeInstanceOf(StackOneMcpTool); + expect( + await tool?.execute({ rating: 'positive', tool_names: ['acc1_tool_1'] }), + ).toMatchObject({ isError: false, result: { 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(); + }); +}); - // 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); +describe('execution through fetched tools', () => { + 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).toEqual({ + isError: false, + result: { + data: { + action: 'bamboohr_get_employee', + account_id: 'your-bamboohr-account-id', + arguments: { id: 'emp-123' }, + }, + }, }); + }); - 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('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' }, + }, + }, }); + }); +}); - 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'); +describe('model-supplied headers', () => { + const serveTool = (inputSchema: McpToolDefinition['inputSchema']) => { + const calls: RecordedToolCall[] = []; + const app = createMcpApp({ + accountTools: { + 'tenant-a': [{ name: 'crm_list_contacts', description: 'List contacts', inputSchema }], + }, + onToolCall: (call) => calls.push(call), + }); + server.use(http.all(`${TEST_BASE_URL}/mcp`, ({ request }) => app.fetch(request))); + return calls; + }; + const fetchTool = async () => { + const tool = (await newToolSet({ accountId: 'tenant-a' }).fetchTools()).getTool( + 'crm_list_contacts', + ); + assert(tool, 'tool should be listed'); + return tool; + }; + + // Regression: the RPC envelope's headers were merged OVER the tool's own, so a model-supplied + // x-account-id replaced the account the tool was fetched for. Over tools/call the tenant is + // the transport's x-account-id, which the SDK sets; the argument never reaches the server. + it('cannot switch tenant with headers_x-account-id, even when the schema declares it', async () => { + const calls = serveTool({ + type: 'object', + properties: { 'headers_x-account-id': { type: 'string' }, query_limit: { type: 'number' } }, + }); + const tool = await fetchTool(); + + 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 }); + }); - // Should fall back to local search and return results (not empty) - expect(tools.length).toBeGreaterThan(0); + it('cannot switch tenant with a nested headers object', async () => { + const calls = serveTool({ + type: 'object', + properties: { headers: { type: 'object', properties: {} } }, }); + const tool = await fetchTool(); - 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', - }); - }), - ); + await tool.execute({ headers: { 'X-Account-Id': 'tenant-b', Authorization: 'Bearer stolen' } }); - const tools = await toolset.searchTools('list employees', { search: 'semantic' }); - - // Semantic mode should return empty, not fall back - expect(tools.length).toBe(0); - }); + expect(calls[0]?.accountId).toBe('tenant-a'); + expect(calls[0]?.arguments.headers).toEqual({}); }); - 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: {}, - }); + 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(); - 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', - }); - }), - ); + await tool.execute({ headers_foo: 'bar', query_limit: 1 }); - const results = await toolset.searchActionNames('list employees'); + 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', + ); + }); - expect(results.length).toBeGreaterThan(0); - expect(results[0].id).toBe('hibob_1.0.0_hibob_list_employees_global'); + 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(); - 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 }); - }), - ); + await tool.execute({ 'headers_x-trace': 'abc', query_limit: 1 }); - const results = await toolset.searchActionNames('list employees'); - expect(results).toEqual([]); - }); + expect(calls[0]?.arguments).toEqual({ 'headers_x-trace': 'abc', query_limit: 1 }); }); - 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('forwards a header the served schema declares', async () => { + const calls = serveTool({ + type: 'object', + properties: { headers: { type: 'object', properties: { 'x-trace': { type: 'string' } } } }, }); + const tool = await fetchTool(); - it('SearchTool.search delegates to searchTools', async () => { - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - accountId: 'mixed', - search: {}, - }); + await tool.execute({ headers: { 'x-trace': 'abc', 'x-other': 'dropped' } }); - 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', - }); - }), - ); + expect(calls[0]?.arguments.headers).toEqual({ 'x-trace': 'abc' }); + }); - const searchTool = toolset.getSearchTool(); - const tools = await searchTool.search('list employees'); - const toolNames = tools.toArray().map((t) => t.name); + 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(); - expect(toolNames).toContain('hibob_list_employees'); + await tool.execute({ + headers: { 'x-custom': 'yes', Authorization: 'Bearer stolen', 'x-account-id': 'tenant-b' }, }); - 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); - }); + 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', + ]); }); - 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: {} }, - }, - ], + 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 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); }); + const tool = await fetchTool(); + const args = { + query_limit: 1, + path: { id: 'c1' }, + body: { headers: { Authorization: 'kept' }, headers_x: 'kept' }, + x_account_id: 'kept', + }; - it('uses separate cache entries for different account sets', async () => { - const counter = installMcpSpy(); - const toolset = new StackOneToolSet({ - baseUrl: TEST_BASE_URL, - apiKey: 'test-key', - }); - - await toolset.fetchTools({ accountIds: ['acc1'] }); - const afterAcc1 = counter.count; - - await toolset.fetchTools({ accountIds: ['acc1'] }); - expect(counter.count).toBe(afterAcc1); - - await toolset.fetchTools({ accountIds: ['acc2'] }); - expect(counter.count).toBeGreaterThan(afterAcc1); - const afterAcc2 = counter.count; - - await toolset.fetchTools({ accountIds: ['acc1'] }); - expect(counter.count).toBe(afterAcc2); - }); + await tool.execute(args); - 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(calls[0]?.arguments).toEqual(args); + }); +}); - 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 a42d046f..bda10d93 100644 --- a/src/toolsets.ts +++ b/src/toolsets.ts @@ -1,133 +1,39 @@ -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'; -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'; + DEFAULT_BASE_URL, + DEFAULT_TIMEOUT_MS, + FAILED_ACCOUNT_RETRY_MS, + MAX_CONCURRENCY, + MAX_TOP_K, + SUBMIT_FEEDBACK_TOOL_NAME, +} from './consts'; +import { buildRequestHeaders, isSdkOwnedHeader } from './headers'; +import { + type EndUserSource, + HttpRateLimitError, + type McpToolDefinition, + isRateLimitFailure, + listMcpTools, + withEndUser, +} from './mcp-client'; +import { cloneJson, toolParametersFromInputSchema } from './schema'; +import { StackOneMcpTool, type StackOneTool, Tools, warnOnDuplicateNames } from './tool'; import type { - DefenderConfig, - DefenderMode, - ExecuteOptions, + ActionResult, + FeedbackCategory, + FeedbackRating, + FeedbackSource, JsonObject, - JsonSchemaProperties, - LocalExecuteConfig, - RpcExecuteConfig, - SearchConfig, - ToolParameters, + SearchResult, + StackOneAccount, + ToolMode, } 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 - * 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']; - -/** - * 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 - */ -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 { StackOneError } from './utils/error-stackone'; +import { ToolSetConfigError, ToolSetLoadError } from './utils/error-toolset'; +import { settleWithConcurrency } from './utils/concurrency'; +import { fetchWithRetry, retryTiming } from './utils/fetch-retry'; +import { warn } from './utils/logger'; /** * Configuration with a single account ID @@ -135,7 +41,9 @@ export interface BaseToolSetConfig { 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 shared account linked to the API key + * (non-shared ones too with `includeNonShared`). */ accountId: string; } @@ -146,10 +54,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; } /** @@ -162,8 +71,8 @@ type AccountConfig = SimplifyDeep; + /** + * Request timeout in milliseconds, applied to every MCP call (listing and `tools/call`) 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; /** - * 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 + * 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'`). */ - defender?: DefenderConfig | null; + 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; } /** @@ -211,16 +129,17 @@ export type StackOneToolSetConfig = StackOneToolSetBaseConfig & Partial { - return this.toolset.searchTools(query, { - ...options, - search: options?.search ?? this.defaultConfig.method, - topK: options?.topK ?? this.defaultConfig.topK, - minSimilarity: options?.minSimilarity ?? this.defaultConfig.minSimilarity, - }); - } + 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 lowest of these account ids. Defaults as for + * {@link StackOneToolSet.fetchTools}. `null` is the same as leaving it unset. + */ + accountIds?: string[] | null; } -// --- 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; - } - }; +/** One served tool, with the account it was listed for. What the catalog cache holds. */ +interface CatalogEntry { + definition: McpToolDefinition; + accountId: string; + endpoint: string; +} - return tool; +/** A cached catalog: each healthy account's listing, and when and why each failing one failed. */ +interface CachedCatalog { + listings: ReadonlyMap; + /** `at` is on {@link retryTiming}'s clock. */ + failed: ReadonlyMap; } -/** @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'), - ); +/** 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 and when it failed. */ + failed: [accountId: string, message: string, at: number][]; +} - 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; +const describeError = (error: unknown): string => + error instanceof Error ? error.message : String(error); - if (!cachedTools) { - cachedTools = await toolset.fetchTools({ accountIds }); - } - const target = cachedTools.getTool(parsed.tool_name); +/** + * 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()}_`)); +} - if (!target) { - return { - error: `Tool "${parsed.tool_name}" not found. Use tool_search to find available tools.`, - }; +/** + * 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++; } - - 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 (pattern[end] === ']') { + end++; } - 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, - }; + 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; } - throw error; + } else { + source += char.replace(/[.+^${}()|[\]\\/]/g, '\\$&'); } - }; - - return tool; + } + return new RegExp(`^${source}$`, 's').test(value); } -/** 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; -} +const isPlainObject = (value: unknown): value is JsonObject => + typeof value === 'object' && value !== null && !Array.isArray(value); -/** Type guard: discriminate the `useProjectSettings: true` variant of DefenderConfig. */ -function usesProjectSettings(config: DefenderConfig): config is { useProjectSettings: true } { - return 'useProjectSettings' in config && config.useProjectSettings === true; +/** 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, + ); } /** - * 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 + * 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. */ -export function __resetDefenderInfoLog(): void { - loggedDefenderShapes.clear(); +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(); } -/** 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`; +/** 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; } -/** - * 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.', - ), - ); +/** The JSON type of a value, as the messages shared with the Python SDK name it. */ +const jsonType = (value: unknown): string => + 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 == null) { 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 (typeof accountIds === 'string') { + throw new ToolSetConfigError( + `${parameter} must be a list of account ids, not a string. Did you mean [${JSON.stringify(accountIds)}]?`, + ); } - if (usesProjectSettings(config)) { - return {}; + if (!Array.isArray(accountIds) || accountIds.some((id) => typeof id !== 'string')) { + throw new ToolSetConfigError(`${parameter} must be a list of account id strings`); } - 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, - }, - }; -} + // 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`); + } +}; /** - * Class for loading StackOne tools via MCP + * The StackOne toolset: lists the served tool catalog and exposes it to agent frameworks. + * + * 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 shared + * account linked to the key, and non-shared ones too with `includeNonShared`. */ export class StackOneToolSet { - private baseUrl?: string; - private authentication?: AuthenticationConfig; - 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; + readonly #apiKey: string; + readonly #baseUrl: string; + readonly #headers: Record; + readonly #timeout: number; + readonly #toolMode: ToolMode | undefined; + readonly #includeNonShared: boolean; + readonly #accountId: string | undefined; + #accountIds: string[]; + + /** + * 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. + */ + 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; + /** 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 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, 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(); + /** + * 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 + * 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. + */ + #accountsStarted = 0; + #accountsRecorded = 0; /** - * Account ID for StackOne API + * 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. */ - private accountId?: string; - private accountIds: string[] = []; + 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 — + * 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) + * 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 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. + * + * @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. */ - 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.', ); } + // An empty accountId is usually an unset variable, and treating it as unset would silently + // widen every call to every discovered account. + if (config.accountId === '') { + throw new ToolSetConfigError('accountId must not be an empty string'); + } + assertAccountIdList(config.accountIds, 'accountIds'); + assertAccountIdList(config.execute?.accountIds, 'execute.accountIds'); - const apiKey = config?.apiKey || process.env.STACKONE_API_KEY; - - if (!apiKey && 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.', + 'An API key must be provided, either to the toolset or in 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. Pass the API key and account ids through their own 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.searchConfig = config?.search != null ? { method: 'auto', ...config.search } : null; - 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; + 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.#includeNonShared = config.includeNonShared ?? false; + this.#accountId = config.accountId; + this.#accountIds = [...(config.accountIds ?? config.execute?.accountIds ?? [])]; + + // 2.x read STACKONE_ACCOUNT_ID. An upgrade that keeps relying on it would silently widen to + // every account on the key — other end users' accounts included — so say so, once. if ( - defenderInput != null && - typeof defenderInput === 'object' && - usesProjectSettings(defenderInput) && - Object.keys(defenderInput).length > 1 + process.env.STACKONE_ACCOUNT_ID && + this.#accountId == null && + this.#accountIds.length === 0 ) { - throw new ToolSetConfigError( - 'Cannot combine useProjectSettings: true with explicit defender options. Use one or the other.', + warn( + 'STACKONE_ACCOUNT_ID is set, but the SDK does not read it: with no account id passed, every active shared account on this API key is used. Pass an account id to scope the toolset.', ); } - this.defenderConfig = - defenderInput === undefined ? { useProjectSettings: true } : defenderInput; - this.defenderFields = buildDefenderFields(this.defenderConfig); - logDefenderOverride(this.defenderConfig, this.defenderFields); - - // 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 }; - } - } - } - - private semanticSearchClient?: SemanticSearchClient; - private catalogCache: Map = new Map(); - private toolIndexCache?: { tools: Tools; index: ToolIndex }; - - /** - * 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 + * @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 { - this.accountIds = accountIds; + setAccounts(accountIds: string[] | null): this { + 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, and no later call joins it. */ clearCatalogCache(): void { - this.catalogCache.clear(); - this.toolIndexCache = undefined; + this.#cacheGeneration += 1; + this.#catalogCache.clear(); + this.#catalogInFlight.clear(); + this.#discoveredAccountIds = undefined; + this.#discovering = undefined; + this.#providerMisses.clear(); } /** - * Get or lazily create the semantic search client. + * Get tools in OpenAI function calling format. + * + * @param options - Options + * @param options.accountIds - Account IDs to scope tools. Defaults to the toolset's accounts. + * @returns List of tool definitions in OpenAI function format. + * + * @example + * ```typescript + * const toolset = new StackOneToolSet(); + * const tools = await toolset.openai(); + * ``` */ - private getSemanticClient(): SemanticSearchClient { - if (!this.semanticSearchClient) { - const apiKey = this.getApiKey(); - this.semanticSearchClient = new SemanticSearchClient({ - apiKey, - baseUrl: this.baseUrl, - }); - } - return this.semanticSearchClient; + async openai(options?: { accountIds?: string[] | null }): Promise> { + const tools = await this.fetchTools({ accountIds: options?.accountIds }); + return tools.toOpenAI(); } /** - * Get the current search config. + * 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. + * + * 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, 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. + * @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). */ - getSearchConfig(): SearchConfig | null { - return this.searchConfig; + 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; } - /** - * 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.', + async #requestAccounts(): Promise { + const url = `${this.#baseUrl.replace(/\/+$/, '')}/accounts`; + const started = ++this.#accountsStarted; + let response: Response; + let rateLimited = false; + try { + response = await fetchWithRetry( + url, + { + headers: buildRequestHeaders({ apiKey: this.#apiKey, extraHeaders: this.#headers }), + signal: AbortSignal.timeout(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, + }); } - 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.', + let bytes: ArrayBuffer; + try { + bytes = await response.arrayBuffer(); + } catch (error) { + throw new ToolSetLoadError( + `Could not read the response from ${url}: ${describeError(error)}`, + { + cause: error, + }, ); } - const config: SearchConfig = options?.search - ? { ...this.searchConfig, method: options.search } - : this.searchConfig; + 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}`.trimEnd()}: ${text}`, + response.status, + text, + undefined, + response.status === 429 ? { cause: new HttpRateLimitError(url) } : undefined, + ); + } - return new SearchTool(this, config); + 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, + }); + } + 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 ${jsonType(accounts)}`, + ); + } + if (started > this.#accountsRecorded) { + 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[]; } /** - * Get tool_search + tool_execute for agent-driven discovery. + * 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. * - * Returns a Tools collection with two tools that let the LLM - * discover and execute tools on-demand. + * 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. * - * @param options - Options to scope tool discovery - * @returns Tools collection containing tool_search and tool_execute + * @throws ToolSetConfigError If the key has no accounts, none are active, or every active one is + * non-shared and `includeNonShared` is not set. */ - getTools(options?: { accountIds?: string[] }): Tools { - const accountIds = - options?.accountIds ?? - this.executeConfig?.accountIds ?? - (this.accountIds.length > 0 ? this.accountIds : undefined); - return this.buildTools(accountIds); + async #discoverAccountIds(): Promise { + 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; } - /** - * Build tool_search + tool_execute tools scoped to this toolset. - */ - private buildTools(accountIds?: string[], connectors?: string): Tools { - if (this.searchConfig === null) { + async #fetchActiveAccountIds(): Promise { + 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 an account id explicitly.', + ); + } + const listed = accounts + .map((account) => `${String(account?.provider)} (${String(account?.status)})`) + .join(', '); throw new ToolSetConfigError( - 'Search is disabled. Initialize StackOneToolSet with a search config to enable.', + `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 searchTool = createSearchTool(this, accountIds, connectors); - const executeTool = createExecuteTool(this, accountIds, connectors); - return new Tools([searchTool, executeTool]); + 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)); + // 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( + `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 = usable; + } + return usable; } /** - * 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' }); - * ``` + * 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 discovered account — active and shared, or + * non-shared too with `includeNonShared` — in `GET /accounts` order. */ - 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(); + async #accountsInOrder(accountIds: string[] | null | 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(); + } + return scope; + } - const tools = await this.fetchTools({ accountIds: effectiveAccountIds }); - return tools.toOpenAI(); + 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(); + } + + #endpoint(mode: ToolMode | undefined): string { + const endpoint = `${this.#baseUrl.replace(/\/+$/, '')}/mcp`; + return mode ? `${endpoint}?tool-mode=${mode}` : endpoint; } /** - * 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 }); + * 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]); + } + + /** + * The catalog of every scoped account, from the cache where it can be. * - * // Explicit semantic search - * const tools = await toolset.searchTools('manage employees', { search: 'semantic' }); + * One unusable account must not cost the caller every other account's tools, so a failing + * 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. * - * // Local BM25+TF-IDF search - * const tools = await toolset.searchTools('manage employees', { search: 'local' }); + * 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}. * - * // Filter by connector - * const tools = await toolset.searchTools('create time off request', { - * connector: 'bamboohr', - * search: 'semantic', - * }); - * ``` + * 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 has an empty catalog. */ - 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.', - ); + async #catalog( + scope: readonly string[], + mode: ToolMode | undefined, + generation: number, + retry: ReadonlySet = new Set(), + ): Promise { + const inScope = ({ listings, failed }: CachedCatalog): ScopedCatalog => ({ + entries: scope.flatMap((accountId) => listings.get(accountId) ?? []), + failed: scope.flatMap((accountId): ScopedCatalog['failed'] => { + const failure = failed.get(accountId); + return failure ? [[accountId, failure.message, failure.at]] : []; + }), + }); + if (scope.length === 0) { + return { entries: [], failed: [] }; } - - const 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([]); + const key = this.#cacheKey(scope, mode); + const cached = this.#catalogCache.get(key); + const now = retryTiming.now(); + const due = cached + ? [...cached.failed] + .filter( + ([accountId, { at }]) => retry.has(accountId) || now - at >= FAILED_ACCOUNT_RETRY_MS, + ) + .map(([accountId]) => accountId) + : scope; + if (cached && due.length === 0) { + return inScope(cached); } - // Local-only search — skip semantic API entirely - if (search === 'local') { - return this.localSearch(query, allTools, mergedOptions); + // A listing that started before a clear is not joined: it belongs to the old generation. + const inFlight = this.#catalogInFlight.get(key); + if (inFlight && generation === this.#cacheGeneration) { + return inScope(await inFlight); } + 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 { - // 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([]); + return inScope(await listing); + } finally { + if (this.#catalogInFlight.get(key) === listing) { + this.#catalogInFlight.delete(key); } + } + } - // 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), + /** + * 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, + generation: number, + ): Promise { + const endpoint = this.#endpoint(mode); + const listAccount = async (accountId: string): Promise => { + const definitions = await withEndUser(accountId, this.#endUsers, (endUserId) => + listMcpTools({ + endpoint, + headers: buildRequestHeaders({ + apiKey: this.#apiKey, + accountId, + endUserId, + extraHeaders: this.#headers, + }), + timeout: this.#timeout, + }), ); - - // 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 definitions.map((definition) => ({ definition, accountId, endpoint })); + }; + const store = (catalog: CachedCatalog): void => { + if (generation === this.#cacheGeneration) { + this.#catalogCache.set(key, catalog); } + }; - return new Tools(matchedTools); - } catch (error) { - if (error instanceof SemanticSearchError) { - if (search === 'semantic') { - throw error; - } + if (scope.length === 1) { + const accountId = scope[0] as string; + const listings = new Map([[accountId, await listAccount(accountId)]]); + const catalog = { listings, failed: new Map() }; + store(catalog); + return catalog; + } - // Auto mode: silently fall back to local search - return this.localSearch(query, allTools, mergedOptions); + const settled = await settleWithConcurrency( + due, + MAX_CONCURRENCY, + listAccount, + isRateLimitFailure, + ); + const listings = new Map(cached?.listings); + 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); + failed.delete(accountId); + } else { + failures.push([accountId, outcome.reason]); } - throw error; + }); + if (listings.size === 0) { + throw allAccountsFailed(failures); + } + const failedNow = retryTiming.now(); + for (const [accountId, reason] of failures) { + const message = describeError(reason); + warn(`Skipping account that failed to list tools — ${accountId}: ${message}`); + failed.set(accountId, { at: failedNow, message }); } + const catalog = { listings, failed }; + store(catalog); + return catalog; } /** - * Search for action names without fetching tools. + * 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): StackOneTool { + const { definition, accountId, endpoint } = entry; + return new StackOneMcpTool({ + name: definition.name, + description: definition.description ?? '', + parameters: toolParametersFromInputSchema(cloneJson(definition.inputSchema)), + endpoint, + apiKey: this.#apiKey, + accountId, + timeout: this.#timeout, + extraHeaders: this.#headers, + endUsers: this.#endUsers, + }); + } + + /** + * Fetch tools with optional filtering by account IDs, providers, and actions. * - * Useful when you need to inspect search results before fetching, - * or when building custom filtering logic. + * 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. * - * @param query - Natural language description of needed functionality - * @param options - Search options - * @returns List of SemanticSearchResult with action names, scores, and metadata + * `stackone_submit_feedback` is served once per account listing; it is returned once. * - * @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)}`); - * } + * 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 — 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. * - * // 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 }); - * ``` + * @throws ToolSetConfigError If no account is configured and none can be discovered. + * @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 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 []; - } - } + async fetchTools(options: FetchToolsOptions = {}): Promise { + return (await this.#fetchTools(options)).tools; + } + /** + * {@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, + retry?: ReadonlySet, + ): Promise<{ tools: Tools; failed: ScopedCatalog['failed'] }> { 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 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, generation, retry); + + let seenFeedbackTool = false; + let tools = entries + .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; } - }); - - 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; + const first = !seenFeedbackTool; + seenFeedbackTool = true; + return first; + }) + .map((entry) => this.#createTool(entry)); + + if (options.providers?.length) { + const providers = options.providers; + tools = tools.filter((tool) => matchesProvider(tool.name, providers)); + } + if (options.actions?.length) { + const actions = options.actions; + tools = tools.filter((tool) => actions.some((pattern) => matchGlob(tool.name, pattern))); } - // 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; + warnOnDuplicateNames(tools); + return { tools: new Tools(tools), failed }; } catch (error) { - if (error instanceof SemanticSearchError) { - return []; + // 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 error; + throw new ToolSetLoadError(`Error fetching tools: ${describeError(error)}`, { + cause: error, + }); } } /** - * Run local BM25+TF-IDF search over already-fetched tools. + * 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. */ - 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); + async #metaTools( + suffix: string, + accountIds: string[] | null | undefined, + retry?: ReadonlySet, + ): Promise<{ tools: StackOneTool[]; failed: ScopedCatalog['failed'] }> { + const { tools, failed } = await this.#fetchTools({ accountIds, mode: 'search_execute' }, retry); + return { + tools: tools.getStackOneTools().filter((tool) => tool.name.endsWith(suffix)), + failed, + }; } /** - * 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 + * 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. + * + * 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 search rather than being + * skipped. + * + * @param query What you want to do, e.g. "list recent comments". + * @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. */ - 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; + 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)}`, + ); } - - // 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(); - }); - - 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); + if (typeof query !== 'string') { + throw new ToolSetConfigError(`query must be a string, got ${typeof query}`); } - // 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; - } - - /** - * 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'); + const { tools } = await this.#metaTools('_search_actions', options.accountIds); + if (tools.length === 0) { + return []; } - await using clients = await createMCPClient({ - baseUrl: `${this.baseUrl}/mcp?param-style=${MCP_PARAM_STYLE}`, - headers: requestHeaders, - }); + const searchOne = async (tool: StackOneTool): Promise => { + const found = await tool.execute({ query, top_k: topK }); + const actions = (Array.isArray(found.actions) ? found.actions : []).filter( + (action): action is SearchResult => isPlainObject(action), + ); + // The server returns session_id once per search, beside the actions. Results from every + // connector are merged and re-ranked below, so this is the last point at which a hit can + // still be traced to the search, and the account, that produced it. + const sessionId = found.session_id; + const traced = typeof sessionId === 'string' && sessionId ? { session_id: sessionId } : {}; + const accountId = tool.getAccountId(); + return actions.map((action) => ({ + ...action, + ...traced, + ...(accountId ? { account_id: accountId } : {}), + })); + }; - 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, - }); + // 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, + isRateLimitFailure, + ); + 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)}`); + } }); - - return new Tools(tools); - } - - /** - * 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); - }); + if (failures.length > 0 && results.length === 0) { + throw new ToolSetLoadError(`No connector returned results. ${failures.join(' | ')}`); } - - // 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)), - ); + for (const failure of failures) { + warn(`Skipping connector that failed to search — ${failure}`); } - return new Tools(filteredTools); + // 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, 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); } /** - * 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 + * 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: {...} }`. + * 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 + * 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. + * @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, … }`. + * @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, or an account in scope + * 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. */ - 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 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)}`, + ); } - - 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) { + if (args !== undefined && !isPlainObject(args)) { + throw new ToolSetConfigError(`arguments must be a JSON object, got ${jsonType(args)}`); + } + const { sessionId } = options; + if (sessionId != null && (typeof sessionId !== 'string' || !sessionId)) { 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.', + `sessionId must be a non-empty string, got ${JSON.stringify(sessionId)}`, ); } - this.rpcClient = new RpcClient({ - serverURL: this.baseUrl, - security: { - username: apiKey, - password, - }, - timeout: this.timeout, - }); - - return this.rpcClient; - } - - 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 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; - const extraHeaders = normalizeHeaders(envelope.headers); - // defu merges extraHeaders into baseHeaders, both are already branded types - const actionHeaders = defu(extraHeaders, baseHeaders); - - const rpcBody: JsonObject = envelope.body; - - if (options?.dryRun) { - const requestPayload = { - action: name, - body: rpcBody, - ...this.defenderFields, - 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, - ...this.defenderFields, - headers: actionHeaders, - path: pathParams ?? undefined, - query: queryParams ?? undefined, - }); - - return rpcResponseToJsonObject(response); - } catch (error) { - if (error instanceof StackOneError) { + 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 + // 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 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; + }); + }; + // 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. 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) { + const generation = this.#cacheGeneration; + await (this.#fetchingAccounts ?? this.fetchAccounts()).catch((error: unknown) => { + if (isRateLimitFailure(error)) { throw error; } - throw new StackOneError(`Error executing RPC action ${name}`, { cause: 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)) { + missedRecently.add(accountId); + if (generation === this.#cacheGeneration) { + this.#providerMisses.set(accountId, missedAt); + } + } } - }; + } + // 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, + 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.`, + ); + } - return tool; - } + 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.`, + ); + } - private buildActionHeaders(headers: Record): StackOneHeaders { - const sanitizedEntries = Object.entries(headers).filter( - ([key]) => key.toLowerCase() !== 'authorization', - ); + // 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, 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 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.`, + ); + } - return stackOneHeadersSchema.parse( - Object.fromEntries(sanitizedEntries.map(([key, value]) => [key, String(value)])), - ); + // 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 != null) { + delete callArguments.session_id; + callArguments.session_id = sessionId; + } + callArguments.action_id = actionId; + + // `*_execute_action` answers with the action's result wrapper; see ActionResult. + return (await tool.execute(callArguments)) as ActionResult; } /** - * Splits LLM-supplied tool arguments into the RPC envelope (path/query/headers/body). + * 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. + * + * 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 shared + * one (non-shared ones too with `includeNonShared`). * - * 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. + * @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', + * toolNames: [hit.action_id], + * sessionId: hit.session_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. */ - 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), - }; - - // 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]; - } - }; + async submitFeedback(options: SubmitFeedbackOptions): Promise { + 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)}]?`, + ); + } + if (!Array.isArray(toolNames)) { + throw new ToolSetConfigError('toolNames must be an array of tool names'); + } + if (sessionId != null && (typeof sessionId !== 'string' || !sessionId)) { + throw new ToolSetConfigError( + `sessionId must be a non-empty string, got ${JSON.stringify(sessionId)}`, + ); + } - const entries = Object.entries(params); + // One account, one tools/call: the tool is global, so every account's copy records the same + // feedback, and calling each would record it once per account. The lowest id is the one a + // 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, + ); + if (!tool) { + throw new ToolSetLoadError( + `The server did not serve ${SUBMIT_FEEDBACK_TOOL_NAME}: feedback is not enabled for this project.`, + ); + } - // 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 args: JsonObject = { rating, tool_names: [...toolNames] }; + 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; } } + return (await tool.execute(args)) as ActionResult; + } +} - // 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); - } - } - continue; - } - assignField(buckets.body, key, value); +/** + * 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; +} - // 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 }, - }; +/** 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. + * + * 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( + `Every account failed to list tools: ${failures.map(([accountId, reason]) => `${accountId}: ${describeError(reason)}`).join('; ')}`, + { cause: new AggregateError(reasons, 'Every account failed to list tools') }, + ); } diff --git a/src/types.ts b/src/types.ts index 2b2ff738..208ae4f4 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,56 +65,30 @@ 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 MCP `tools/call`, on the endpoint that listed the tool. Every tool a toolset + * returns executes this way. */ -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; +export interface McpExecuteConfig { + kind: 'mcp'; url: string; - bodyType: HttpBodyType; - params: HttpExecuteParameter[]; // full list of params used to execute. Comes straight from the OpenAPI spec. + toolName: string; } -export interface RpcExecuteConfig { - kind: 'rpc'; - method: string; - url: string; - payloadKeys: { - action: string; - body?: string; - headers?: string; - path?: string; - query?: string; - }; -} - -export interface LocalExecuteConfig { +/** + * A tool whose `execute` is supplied by the caller rather than by the SDK. + */ +interface LocalExecuteConfig { kind: 'local'; identifier?: string; description?: string; @@ -129,15 +97,14 @@ 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 = 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 `tools/call` the tool would send instead of sending it. */ dryRun?: boolean; } @@ -147,22 +114,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 { +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[]; } /** @@ -205,25 +171,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'. @@ -236,62 +183,74 @@ export interface ClaudeAgentSdkOptions { } /** - * 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. + * An account linked to the API key, as `GET /accounts` returns it. Only accounts whose `status` + * is `'active'` can serve tools. */ -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; - }; +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; +}; /** - * 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. + * 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 const DEFAULT_DEFENDER_CONFIG = { - enabled: true, - blockHighRisk: false, - useTier1Classification: true, - useTier2Classification: true, -} as const; +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. + */ + 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; +}; /** - * Resolved defender behavior on a `StackOneToolSet`. + * 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. * - * - `'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. + * 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 DefenderMode = 'project' | 'disabled' | 'explicit'; +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'; + +/** Who produced the feedback. */ +export type FeedbackSource = 'model' | 'user' | 'system'; + +/** What the feedback is about. */ +export type FeedbackCategory = 'search' | 'execute' | 'defender' | 'connection' | 'general'; diff --git a/src/utils/binary-response.test.ts b/src/utils/binary-response.test.ts deleted file mode 100644 index de7cc3ce..00000000 --- a/src/utils/binary-response.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { filenameFromContentDisposition, isJsonContentType } 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 - fall back to the raw (undecoded) value. - ["attachment; filename*=UTF-8''bad%ZZname", 'bad%ZZname'], - ['attachment', null], - [null, null], - ['', null], - ])('filenameFromContentDisposition(%j) === %j', (input, expected) => { - expect(filenameFromContentDisposition(input as string | null)).toBe(expected); - }); -}); diff --git a/src/utils/binary-response.ts b/src/utils/binary-response.ts deleted file mode 100644 index 432e67fc..00000000 --- a/src/utils/binary-response.ts +++ /dev/null @@ -1,100 +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. 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. - */ - -/** - * 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'); -} - -/** - * Extract the filename from a Content-Disposition header value, if present. - * - * 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. - */ -export function filenameFromContentDisposition(value: string | null): 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 quoted = value.match(/filename\s*=\s*"([^"]*)"/i); - if (quoted) { - return quoted[1]?.trim() || null; - } - const bare = value.match(/filename\s*=\s*([^;]+)/i); - if (bare?.[1]) { - return bare[1].trim().replace(/^"+|"+$/g, '') || null; - } - 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/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 new file mode 100644 index 00000000..8c94805c --- /dev/null +++ b/src/utils/concurrency.ts @@ -0,0 +1,35 @@ +/** + * 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. + * + * 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 (!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 }; + } + } + }; + 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..64376493 100644 --- a/src/utils/error-stackone-api.test.ts +++ b/src/utils/error-stackone-api.test.ts @@ -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', () => { diff --git a/src/utils/error-stackone-api.ts b/src/utils/error-stackone-api.ts index fba587ab..343f5762 100644 --- a/src/utils/error-stackone-api.ts +++ b/src/utils/error-stackone-api.ts @@ -2,7 +2,8 @@ import { USER_AGENT } from '../consts'; import { StackOneError } from './error-stackone'; /** - * Raised when the StackOne API returns an error + * 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 +18,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/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 new file mode 100644 index 00000000..f531c78e --- /dev/null +++ b/src/utils/error-toolset.test.ts @@ -0,0 +1,29 @@ +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', () => { + // `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)], + ['ToolArgumentsError', new ToolArgumentsError('x')], + ])('%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'; + } +} diff --git a/src/utils/fetch-retry.test.ts b/src/utils/fetch-retry.test.ts new file mode 100644 index 00000000..2bc9f97c --- /dev/null +++ b/src/utils/fetch-retry.test.ts @@ -0,0 +1,339 @@ +import { http, HttpResponse, type JsonBodyType } from 'msw'; +import { TEST_BASE_URL } from '../../mocks/constants'; +import { server } from '../../mocks/node'; +import { fetchWithRetry, retryAfterMs } 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, 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, + }, + }; +}; + +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] POST ${url} was rate limited (429) on attempt 1 of 4; retrying in 2s`, + ]); + }); + + 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])).toBe( + `[@stackone/ai] GET ${url} was rate limited (429) on attempt 1 of 4; retrying in 0s`, + ); + }); + + // 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 }); + + expect(delays).toEqual([500]); + }); + }); + + 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, + ); + }); + + 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', () => { + 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); + }); + }); + }); + + 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.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 () => { + 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(); + 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..5db2cff2 --- /dev/null +++ b/src/utils/fetch-retry.ts @@ -0,0 +1,223 @@ +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; + /** 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; + /** Called with each 429 about to be retried, before the wait. */ + onRetry?: (response: Response) => void; +} + +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 }); + }); + +/** + * 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(), +}; + +// 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, 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. + */ +export function retryAfterMs(header: string | null, now: number = Date.now()): number | undefined { + const value = header?.trim(); + if (!value) { + return undefined; + } + if (/^\d+$/.test(value)) { + return Number(value) * 1000; + } + 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. + */ +export 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. + */ +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); + +/** + * `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. + * + * 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, + { deadline, timing = retryTiming, onRetry }: RetryOptions = {}, +): Promise { + for (let retry = 1; ; retry++) { + const response = await fetch(input, init); + if (response.status !== 429 || retry > RATE_LIMIT_MAX_RETRIES) { + return response; + } + const delay = rateLimitDelayMs( + retry, + 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); + onRetry?.(response); + warn(`${limited}; retrying in ${formatSeconds(delay)}s`); + if (delay > 0) { + await timing.sleep(delay, init?.signal); + } + } +} 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}`); +} 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/serialize.ts b/src/utils/serialize.ts new file mode 100644 index 00000000..ff8342a3 --- /dev/null +++ b/src/utils/serialize.ts @@ -0,0 +1,29 @@ +/** + * Serialise a tool result for a model. + * + * 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 + * 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 { + 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'; +} 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, + }); +} 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); - } -} diff --git a/src/vectors.test.ts b/src/vectors.test.ts new file mode 100644 index 00000000..9a172349 --- /dev/null +++ b/src/vectors.test.ts @@ -0,0 +1,1019 @@ +/** + * 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, readdirSync } from 'node:fs'; +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 { 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) => { + 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); + +/** 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)) { + 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); + }); + + 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', () => { + 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: {} })); + return { + 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 on acc1, linear_acc2_execute_action on acc2', + }, + }; + }, + '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 { + newToolSet(); + return { emitted: { warnings: warnings() }, values: {} }; + } finally { + 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 { + emitted: { + error: describeMcpFailure( + new McpError(ErrorCode.RequestTimeout, 'timed out'), + endpoint, + 1_500, + ), + }, + values: { endpoint, timeout: 1.5 }, + }; + }, + 'mcp-rate-limit-timeout': async () => { + const endpoint = `${TEST_BASE_URL}/mcp`; + const timeout = 300; + let requests = 0; + server.use( + http.all(endpoint, async () => { + if (requests++ === 0) { + return HttpResponse.json({}, { status: 429, headers: { 'Retry-After': '0' } }); + } + await delay('infinite'); + }), + ); + 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'); + }), + ); + 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( + 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-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']}`); + }); + 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/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/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), - }); - }); -}); diff --git a/tests/examples/fetch-tools.test.ts b/tests/examples/fetch-tools.test.ts index 37bb6f76..ce0de301 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 @@ -97,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 da5793fd..e8dd5d12 100644 --- a/tests/examples/openai-integration.test.ts +++ b/tests/examples/openai-integration.test.ts @@ -69,5 +69,19 @@ 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({ + 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 new file mode 100644 index 00000000..ade5a5e7 --- /dev/null +++ b/tests/examples/search-and-execute.test.ts @@ -0,0 +1,65 @@ +/** + * 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_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( + { isError: false, result: { data: { nodes: [] } } }, + ); + await expect( + toolset.submitFeedback({ rating: 'positive', toolNames: [best.action_id] }), + ).rejects.toBeInstanceOf(ToolSetLoadError); + }); +}); 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: {} } }); }); }); diff --git a/tests/vectors/README.md b/tests/vectors/README.md new file mode 100644 index 00000000..24e3fad7 --- /dev/null +++ b/tests/vectors/README.md @@ -0,0 +1,144 @@ +# 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. 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. +- **`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 + +- **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` 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 | +|---|---| +| `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..bdd2d202 --- /dev/null +++ b/tests/vectors/header-arguments.json @@ -0,0 +1,1484 @@ +{ + "$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. `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": [ + { + "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-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": { + "headers": { + "type": "string" + } + } + }, + "arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_arguments": { + "headers": { + "x-custom": "a" + } + }, + "expected_warnings": [] + }, + { + "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": "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-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", + "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..b60af92c --- /dev/null +++ b/tests/vectors/header-names.json @@ -0,0 +1,407 @@ +{ + "$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, 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": [ + { + "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-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", + "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-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", + "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": "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 four 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..afd55c2a --- /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.0, + "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.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..868235b1 --- /dev/null +++ b/tests/vectors/messages.json @@ -0,0 +1,1172 @@ +{ + "$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, 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.", + "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} from a tool call: {reason}", + "node": "Dropping header {header} from a tool call: {reason}", + "matches": { + "python": true, + "node": true + }, + "notes": "The name is JSON text, so a quote, a backslash or a control character in it is escaped." + }, + { + "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} from a tool call: {reason}", + "node": "Dropping header argument {argument} from a tool call: {reason}", + "matches": { + "python": true, + "node": true + }, + "notes": "The argument is JSON text, as the name in header-dropped 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}s", + "node": "{method} {url} was rate limited (429) on attempt {attempt} of {max_attempts}; retrying in {delay}s", + "matches": { + "python": true, + "node": true + }, + "notes": "Names the attempt that was answered 429, not the one about to be made." + }, + { + "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}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": true, + "node": true + }, + "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 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 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 + }, + "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", + "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": "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", + "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}). The first one listed, from the lowest account id, is used — 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}). 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": 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." + }, + { + "id": "ambiguous-connector", + "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", + "description": "the action id" + }, + "count": { + "format": "integer", + "description": "how many connectors match: the longest connector prefix, linked on more than one account" + }, + "tools": { + "format": "text", + "description": "each matching *_execute_action tool as \"{tool} on {account_id}\", in ascending account-id order, joined by \", \"" + } + }, + "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": 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." + }, + { + "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}s", + "node": "MCP request to {endpoint} timed out after {timeout}s", + "matches": { + "python": true, + "node": true + }, + "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", + "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": "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", + "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 + }, + "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", + "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 {json_type}", + "node": "Unexpected /accounts response shape: expected a list, got {json_type}", + "matches": { + "python": true, + "node": true + }, + "notes": "Names the JSON type, not either language's own type name." + }, + { + "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 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": true, + "node": true + }, + "notes": "Language-neutral wording: neither SDK's parameter name." + }, + { + "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 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": true, + "node": true + }, + "notes": "A missing provider or status is written None by Python and undefined by Node; neither is canonical yet." + }, + { + "id": "all-accounts-failed", + "kind": "error", + "error": { + "python": "ToolsetLoadError", + "node": "ToolSetLoadError" + }, + "template": "Every account failed to list tools: {failures}", + "placeholders": { + "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 \"; \" — e.g. \"acc-1: ; acc-2: \"" + } + }, + "python": "Every account failed to list tools: {failures}", + "node": "Every account failed to list tools: {failures}", + "matches": { + "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. 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", + "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": "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": true, + "node": true + }, + "notes": "Language-neutral wording: neither SDK's parameter name." + }, + { + "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": "Each SDK names the parameter in its own 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}]?", + "node": "{parameter} must be a list of account ids, not a string. Did you mean [{value}]?", + "matches": { + "python": true, + "node": true + }, + "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", + "node": "{parameter} must be a list of account id strings", + "matches": { + "python": true, + "node": true + }, + "notes": "The list given is not echoed: 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}", + "node": "{parameter} must be a non-empty string, got {value}", + "matches": { + "python": true, + "node": true + }, + "notes": "null (None) means the session id was not given, and does not raise 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}", + "node": "{parameter} must be a non-empty string, got {value}", + "matches": { + "python": true, + "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 {json_type}", + "node": "arguments must be a JSON object, got {json_type}", + "matches": { + "python": true, + "node": true + }, + "notes": "Names the JSON type; 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 {value}", + "node": "{parameter} must be an integer between 1 and {max}, got {value}", + "matches": { + "python": true, + "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}]?", + "node": "{parameter} must be a list of tool names, not a string. Did you mean [{value}]?", + "matches": { + "python": true, + "node": true + } + }, + { + "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 + } + }, + { + "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} 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": true, + "node": true + }, + "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", + "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} could not be encoded as JSON: {detail}", + "node": "Arguments for {tool} could not be encoded as JSON: {detail}", + "matches": { + "python": true, + "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}: {detail}", + "node": "Invalid JSON in arguments for {tool}: {detail}", + "matches": { + "python": true, + "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 for {tool} must be a JSON object", + "node": "Tool arguments for {tool} must be a JSON object", + "matches": { + "python": true, + "node": true + }, + "notes": "For every value that is not an object, including one that is not a string either." + }, + { + "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}", + "node": "Unknown tool {name}", + "matches": { + "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." + }, + { + "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": "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": 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." + }, + { + "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." + }, + { + "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": [ + { + "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": "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..3f3069c9 --- /dev/null +++ b/tests/vectors/retry-after.json @@ -0,0 +1,339 @@ +{ + "$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. 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": [ + { + "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, compared within the seconds tolerance", + "header": "99999999999999999999", + "now": "2026-10-01T12:00:00Z", + "expected_seconds": 99999999999999999999 + }, + { + "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 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": null + }, + { + "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 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": 1388534400 + }, + { + "id": "offset-zone", + "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": null + }, + { + "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": "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": "Saturday, 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 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": null + }, + { + "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 + }, + { + "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/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..3de1a34e --- /dev/null +++ b/tests/vectors/schema/argument-encoding.schema.json @@ -0,0 +1,182 @@ +{ + "$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 + }, + "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": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "arguments": { + "$ref": "#/$defs/value" + }, + "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": { + "$ref": "#/$defs/value" + }, + "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..f58501db --- /dev/null +++ b/tests/vectors/schema/backoff.schema.json @@ -0,0 +1,204 @@ +{ + "$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", + "minItems": 3, + "items": { + "type": "number", + "minimum": 0 + }, + "description": "The base delay before each retry: retry n uses entry n - 1." + }, + "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 + }, + "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": { + "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": { + "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", + "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..14bc5b71 --- /dev/null +++ b/tests/vectors/schema/header-arguments.schema.json @@ -0,0 +1,162 @@ +{ + "$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. Present exactly when `argument` is `headers` and the entry, not the whole argument, was dropped." + }, + "reason": { + "enum": [ + "set-by-sdk", + "not-declared", + "malformed", + "not-an-object", + "not-a-scalar" + ] + } + }, + "required": ["argument", "reason"], + "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", + "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..1e544b10 --- /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", "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..6ec72ab5 --- /dev/null +++ b/tests/vectors/schema/header-values.schema.json @@ -0,0 +1,175 @@ +{ + "$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"], + "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 + }, + "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": { + "id": { + "$ref": "#/$defs/id" + }, + "description": { + "$ref": "#/$defs/description" + }, + "value": { + "$ref": "#/$defs/value" + }, + "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": { + "$ref": "#/$defs/value" + }, + "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": { + "$ref": "#/$defs/value" + }, + "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..29fd8ebc --- /dev/null +++ b/tests/vectors/schema/messages.schema.json @@ -0,0 +1,208 @@ +{ + "$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"] + }, + "else": { + "not": { + "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 + } + } +} 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": [ 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());