From 56bc31fce85d719c42a3251000cc42601ea25f76 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Mon, 9 Nov 2026 12:18:39 +0000 Subject: [PATCH 1/4] feat(testing): add token footprint and tool annotation suites All three servers keep their own token-footprint and tool-annotations tests. todoist-mcp's and automations-mcp's footprint tests rebuild the tools/list payload with z.toJSONSchema, and todoist-mcp's copies the registrar's title and _meta logic, so they measure what they think a client receives rather than what it does. - describeTokenFootprint / measureTokenFootprint read the tools/list payload and instructions from a running server, count the payload as the one array a client receives, print the cost per tool, and fail over budget or when either half goes missing. The tokenizer is passed in as countTokens, so mcp-core depends on none. - describeToolAnnotations pins every advertised tool's annotations as a client receives them, defaults included, and fails on a tool advertised without an expectation or expected but not advertised. readAdvertisedSurface, which listAdvertisedTools now uses, reads both from one in-memory client. --- CODEBASE.md | 14 ++-- README.md | 51 +++++++++--- src/testing/advertised-schemas.ts | 17 +++- src/testing/index.ts | 13 +++ src/testing/token-footprint.test.ts | 95 ++++++++++++++++++++++ src/testing/token-footprint.ts | 113 +++++++++++++++++++++++++++ src/testing/tool-annotations.test.ts | 57 ++++++++++++++ src/testing/tool-annotations.ts | 54 +++++++++++++ 8 files changed, 394 insertions(+), 20 deletions(-) create mode 100644 src/testing/token-footprint.test.ts create mode 100644 src/testing/token-footprint.ts create mode 100644 src/testing/tool-annotations.test.ts create mode 100644 src/testing/tool-annotations.ts diff --git a/CODEBASE.md b/CODEBASE.md index 99bda2a..5f61650 100644 --- a/CODEBASE.md +++ b/CODEBASE.md @@ -43,11 +43,11 @@ oxlint + oxfmt · semantic-release. ## Public API surface (`package.json#exports`) -| Subpath | Provides | Peers it needs | -| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -| `.` (root) | The tool types, `createToolRegistrar`, `getToolOutput`, `removeNullFields`, schema cache, annotations | `@modelcontextprotocol/server`, `zod` | -| `@doist/mcp-core/host` | `validateBearerToken`, `TokenValidationError` and the host contract types (`TokenValidationResult`, `ValidateToken`, `McpServerOptions`) | none | -| `@doist/mcp-core/testing` | `describeOutputSchemaNullability`, `describeAdvertisedToolSchemas` and the helpers they use | the above; also imports `@modelcontextprotocol/client` and `vitest`, undeclared | +| Subpath | Provides | Peers it needs | +| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- | +| `.` (root) | The tool types, `createToolRegistrar`, `getToolOutput`, `removeNullFields`, schema cache, annotations | `@modelcontextprotocol/server`, `zod` | +| `@doist/mcp-core/host` | `validateBearerToken`, `TokenValidationError` and the host contract types (`TokenValidationResult`, `ValidateToken`, `McpServerOptions`) | none | +| `@doist/mcp-core/testing` | `describeOutputSchemaNullability`, `describeAdvertisedToolSchemas`, `describeToolAnnotations`, `describeTokenFootprint` and the helpers they use | the above; also imports `@modelcontextprotocol/client` and `vitest`, undeclared | ## `src/` tree @@ -70,7 +70,9 @@ src/ └─ testing/ # ./testing subpath: suites the servers run over their own tools ├─ index.ts # ./testing barrel ├─ nullable-output.ts # findNullablePaths, describeOutputSchemaNullability - └─ advertised-schemas.ts # listAdvertisedTools, describeAdvertisedToolSchemas + ├─ advertised-schemas.ts # listAdvertisedTools, describeAdvertisedToolSchemas, readAdvertisedSurface + ├─ tool-annotations.ts # describeToolAnnotations + └─ token-footprint.ts # measureTokenFootprint, describeTokenFootprint ``` Every module has a colocated `.test.ts`. diff --git a/README.md b/README.md index d506b63..f0f4b3b 100644 --- a/README.md +++ b/README.md @@ -21,17 +21,17 @@ The MCP SDK and Zod are peer dependencies, so the server and the core share one ## What's in it -| Module | Key exports | -| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| `tool` | `McpTool`, `AnyMcpTool`, `ToolResult`, `ExecuteResult`, `RequiredToolAnnotations`, `ToolSchemaSource` (types) | -| `register-tool` | `createToolRegistrar`, `ToolRegistrarOptions`, `RegisterTool`, `ToolFailure` | -| `tool-output` | `getToolOutput`, `getErrorOutput`, `ToolOutputOptions` | -| `sanitize` | `removeNullFields`, `RemoveNullFieldsOptions` | -| `tool-schemas` | `getToolSchemas`, `ToolSchemas` | -| `annotations` | `getMcpAnnotations`, `formatToolTitle` | -| `app-meta` | `normalizeToolMeta` | -| `host` (subpath) | `validateBearerToken`, `ValidateBearerTokenOptions`, `TokenValidationError`, `TokenValidationResult`, `ValidateToken`, `McpServerOptions` | -| `testing` (subpath) | `describeOutputSchemaNullability`, `describeAdvertisedToolSchemas`, `findNullablePaths`, `listAdvertisedTools` | +| Module | Key exports | +| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tool` | `McpTool`, `AnyMcpTool`, `ToolResult`, `ExecuteResult`, `RequiredToolAnnotations`, `ToolSchemaSource` (types) | +| `register-tool` | `createToolRegistrar`, `ToolRegistrarOptions`, `RegisterTool`, `ToolFailure` | +| `tool-output` | `getToolOutput`, `getErrorOutput`, `ToolOutputOptions` | +| `sanitize` | `removeNullFields`, `RemoveNullFieldsOptions` | +| `tool-schemas` | `getToolSchemas`, `ToolSchemas` | +| `annotations` | `getMcpAnnotations`, `formatToolTitle` | +| `app-meta` | `normalizeToolMeta` | +| `host` (subpath) | `validateBearerToken`, `ValidateBearerTokenOptions`, `TokenValidationError`, `TokenValidationResult`, `ValidateToken`, `McpServerOptions` | +| `testing` (subpath) | `describeOutputSchemaNullability`, `describeAdvertisedToolSchemas`, `describeToolAnnotations`, `describeTokenFootprint`, `measureTokenFootprint`, `findNullablePaths`, `listAdvertisedTools` | ## Usage @@ -162,6 +162,35 @@ describeAdvertisedToolSchemas({ Both take any `{ name, parameters, outputSchema? }`, so a server can run them before its tools move to `McpTool`. +Two more read only what a client receives, so they restate nothing about registration: + +```ts +import { describeTokenFootprint, describeToolAnnotations } from '@doist/mcp-core/testing' +import { encode } from 'gpt-tokenizer' + +const createServer = () => getMcpServer({ token: 'test-token' }) + +describeTokenFootprint({ + createServer, + countTokens: (text) => encode(text).length, + budget: Number(process.env.MCP_TOKEN_BUDGET ?? 13_250), +}) +describeToolAnnotations({ + createServer, + expected: { + 'find-notes': { + title: 'Notes: Find Notes', + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + }, + }, +}) +``` + +- `describeTokenFootprint`: the fixed cost every session pays (the `tools/list` payload as one array, plus `instructions`) stays under `budget`, and either half going missing fails too. It prints the cost per tool. Treat the budget as a ratchet: a rise needs justifying in the change that causes it. `measureTokenFootprint` returns the same numbers. The tokenizer is yours to pass, so mcp-core depends on none. +- `describeToolAnnotations`: every advertised tool has exactly the expected annotations, title and defaults included (`openWorldHint` defaults to false), and every expected tool is advertised. Clients decide from these whether a call needs the user's confirmation. + ## Rules for tools These hold for every Doist MCP server. Where the core can enforce one, it says how. diff --git a/src/testing/advertised-schemas.ts b/src/testing/advertised-schemas.ts index 3224f38..a01d216 100644 --- a/src/testing/advertised-schemas.ts +++ b/src/testing/advertised-schemas.ts @@ -6,21 +6,32 @@ import type { ToolSchemaSource } from '../tool.js' const JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema' -/** The tools a server advertises on `tools/list`, read through an in-memory client. */ -export async function listAdvertisedTools(server: McpServer): Promise { +/** + * What a client sees of a server before it calls anything: the `tools/list` payload and the + * `instructions` block, read through an in-memory client. Closes the server afterwards. + */ +export async function readAdvertisedSurface( + server: McpServer, +): Promise<{ tools: Tool[]; instructions: string | undefined }> { const client = new Client({ name: 'mcp-core-testing', version: '1.0.0' }) const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair() await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]) try { - return (await client.listTools()).tools + const { tools } = await client.listTools() + return { tools, instructions: client.getInstructions() } } finally { await client.close() await server.close() } } +/** The tools a server advertises on `tools/list`, read through an in-memory client. */ +export async function listAdvertisedTools(server: McpServer): Promise { + return (await readAdvertisedSurface(server)).tools +} + export type AdvertisedSchemasConfig = { /** Every tool the server should register. */ tools: readonly ToolSchemaSource[] diff --git a/src/testing/index.ts b/src/testing/index.ts index ddd0ca5..4894268 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -4,3 +4,16 @@ export { type AdvertisedSchemasConfig, } from './advertised-schemas.js' export { describeOutputSchemaNullability, findNullablePaths } from './nullable-output.js' +export { + describeTokenFootprint, + measureTokenFootprint, + type CountTokens, + type TokenFootprint, + type TokenFootprintConfig, + type ToolTokenCost, +} from './token-footprint.js' +export { + describeToolAnnotations, + type ExpectedToolAnnotations, + type ToolAnnotationsConfig, +} from './tool-annotations.js' diff --git a/src/testing/token-footprint.test.ts b/src/testing/token-footprint.test.ts new file mode 100644 index 0000000..e600479 --- /dev/null +++ b/src/testing/token-footprint.test.ts @@ -0,0 +1,95 @@ +import { McpServer } from '@modelcontextprotocol/server' +import { describe, expect, it } from 'vitest' +import { z } from 'zod' +import { createToolRegistrar } from '../register-tool.js' +import type { AnyMcpTool } from '../tool.js' +import { describeTokenFootprint, measureTokenFootprint } from './token-footprint.js' + +const hints = { readOnlyHint: true, destructiveHint: false, idempotentHint: true } + +const tools: AnyMcpTool[] = [ + { + name: 'find-tasks', + description: 'Finds tasks.', + parameters: { query: z.string() }, + outputSchema: { tasks: z.array(z.object({ id: z.string() })) }, + annotations: hints, + execute: async () => ({}), + }, + { + name: 'ping', + description: 'Checks the server answers.', + parameters: {}, + annotations: hints, + execute: async () => ({ textContent: 'pong' }), + }, +] + +const INSTRUCTIONS = 'Use find-tasks before asking the user.' + +function createServer(instructions: string | null = INSTRUCTIONS): McpServer { + const server = new McpServer( + { name: 'fixture', version: '1.0.0' }, + { instructions: instructions ?? undefined }, + ) + const register = createToolRegistrar({ + titlePrefix: 'Fixture', + createContext: () => undefined, + formatError: String, + }) + for (const tool of tools) register(server, tool) + return server +} + +// One token per character keeps every expected count readable. +function countCharacters(text: string): number { + return text.length +} + +describe('measureTokenFootprint', () => { + it('measures the tools/list payload as one array, the way a client receives it', async () => { + const measured: string[] = [] + await measureTokenFootprint(createServer(), (text) => { + measured.push(text) + return 1 + }) + + const asArray = measured + .filter((text) => text.startsWith('[')) + .map( + (text) => JSON.parse(text) as { name: string; annotations?: { title?: string } }[], + )[0] + expect(asArray?.map((tool) => [tool.name, tool.annotations?.title])).toEqual([ + ['find-tasks', 'Fixture: Find Tasks'], + ['ping', 'Fixture: Ping'], + ]) + }) + + it('adds the instructions to the tools/list payload', async () => { + const footprint = await measureTokenFootprint(createServer(), countCharacters) + + expect(footprint.instructions).toBe(38) + expect(footprint.combined).toBe(footprint.toolsList + 38) + }) + + it('breaks the cost down per tool, most expensive first', async () => { + const footprint = await measureTokenFootprint(createServer(), countCharacters) + + expect(footprint.tools.map((tool) => tool.name)).toEqual(['find-tasks', 'ping']) + expect(footprint.tools[1]).toMatchObject({ + name: 'ping', + description: 'Checks the server answers.'.length, + outputSchema: 0, + }) + expect(footprint.tools[0]?.outputSchema).toBeGreaterThan(0) + }) + + it('counts missing instructions as zero', async () => { + const footprint = await measureTokenFootprint(createServer(null), countCharacters) + + expect(footprint.instructions).toBe(0) + expect(footprint.combined).toBe(footprint.toolsList) + }) +}) + +describeTokenFootprint({ createServer, countTokens: countCharacters, budget: 5_000 }) diff --git a/src/testing/token-footprint.ts b/src/testing/token-footprint.ts new file mode 100644 index 0000000..9ca352c --- /dev/null +++ b/src/testing/token-footprint.ts @@ -0,0 +1,113 @@ +import type { McpServer } from '@modelcontextprotocol/server' +import { describe, expect, it } from 'vitest' +import { readAdvertisedSurface } from './advertised-schemas.js' + +/** Counts tokens the way the model a server targets would. */ +export type CountTokens = (text: string) => number + +/** What one advertised tool costs, as listed on `tools/list`. */ +export type ToolTokenCost = { + name: string + /** The whole tool entry: name, title, description, schemas, annotations, `_meta`. */ + total: number + description: number + inputSchema: number + outputSchema: number +} + +/** The fixed cost every session pays before a tool runs. */ +export type TokenFootprint = { + /** Per tool, most expensive first. A breakdown: these don't add up to `toolsList` exactly. */ + tools: ToolTokenCost[] + /** The `tools/list` payload, measured as the one array a client receives. */ + toolsList: number + /** The `instructions` block, or 0 when the server sends none. */ + instructions: number + combined: number +} + +/** + * Measures the fixed token cost of a server from what it advertises to a client, so nothing + * here restates how registration titles a tool or compiles its schemas. Closes the server. + */ +export async function measureTokenFootprint( + server: McpServer, + countTokens: CountTokens, +): Promise { + const { tools, instructions } = await readAdvertisedSurface(server) + + const costs = tools + .map((tool) => ({ + name: tool.name, + total: countTokens(JSON.stringify(tool)), + description: countTokens(tool.description ?? ''), + inputSchema: countTokens(JSON.stringify(tool.inputSchema)), + outputSchema: tool.outputSchema ? countTokens(JSON.stringify(tool.outputSchema)) : 0, + })) + .sort((a, b) => b.total - a.total) + const toolsList = countTokens(JSON.stringify(tools)) + const instructionsCost = instructions ? countTokens(instructions) : 0 + + return { + tools: costs, + toolsList, + instructions: instructionsCost, + combined: toolsList + instructionsCost, + } +} + +function pad(value: string | number, width: number): string { + return String(value).padStart(width) +} + +function formatFootprint(footprint: TokenFootprint, budget: number): string { + return [ + '', + '=== MCP token footprint ===', + `tools advertised: ${footprint.tools.length}`, + `instructions: ${footprint.instructions} tokens`, + `tools/list payload: ${footprint.toolsList} tokens`, + `combined fixed cost: ${footprint.combined} tokens`, + `budget: ${budget} tokens`, + '', + 'Per tool (total / description / inputSchema / outputSchema):', + ...footprint.tools.map( + (tool) => + ` ${pad(tool.total, 5)} ${pad(tool.description, 4)} ${pad(tool.inputSchema, 5)} ${pad(tool.outputSchema, 5)} ${tool.name}`, + ), + ].join('\n') +} + +export type TokenFootprintConfig = { + /** Builds a fresh server with every tool registered. */ + createServer: () => McpServer + /** The tokenizer, such as `(text) => encode(text).length` from `gpt-tokenizer`. */ + countTokens: CountTokens + /** + * The most the fixed cost may be. Treat it as a ratchet rather than headroom: a rise needs + * justifying in the change that causes it. + */ + budget: number +} + +/** + * Tests that the `tools/list` payload plus the `instructions` block stay under `budget`, and + * prints the cost per tool so a reviewer can see where it went. Fails as well if either half + * goes missing: a lost block would otherwise read as a saving. + */ +export function describeTokenFootprint({ + createServer, + countTokens, + budget, +}: TokenFootprintConfig): void { + describe('token footprint', () => { + it('keeps the tools/list payload and instructions within the budget', async () => { + const footprint = await measureTokenFootprint(createServer(), countTokens) + + expect(footprint.tools.length, 'tools advertised').toBeGreaterThan(0) + expect(footprint.instructions, 'instructions advertised').toBeGreaterThan(0) + console.log(formatFootprint(footprint, budget)) + expect(footprint.combined).toBeLessThan(budget) + }) + }) +} diff --git a/src/testing/tool-annotations.test.ts b/src/testing/tool-annotations.test.ts new file mode 100644 index 0000000..e4c23a2 --- /dev/null +++ b/src/testing/tool-annotations.test.ts @@ -0,0 +1,57 @@ +import { McpServer } from '@modelcontextprotocol/server' +import { z } from 'zod' +import { createToolRegistrar } from '../register-tool.js' +import type { AnyMcpTool } from '../tool.js' +import { describeToolAnnotations } from './tool-annotations.js' + +const tools: AnyMcpTool[] = [ + { + name: 'find-tasks', + description: 'Finds tasks.', + parameters: { query: z.string() }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }, + execute: async () => ({}), + }, + { + name: 'share-project', + description: 'Shares a project with someone.', + parameters: { email: z.email() }, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: true, + }, + execute: async () => ({}), + }, +] + +function createServer(): McpServer { + const server = new McpServer({ name: 'fixture', version: '1.0.0' }) + const register = createToolRegistrar({ + titlePrefix: 'Fixture', + createContext: () => undefined, + formatError: String, + }) + for (const tool of tools) register(server, tool) + return server +} + +describeToolAnnotations({ + createServer, + expected: { + 'find-tasks': { + title: 'Fixture: Find Tasks', + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + }, + 'share-project': { + title: 'Fixture: Share Project', + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: true, + }, + }, +}) diff --git a/src/testing/tool-annotations.ts b/src/testing/tool-annotations.ts new file mode 100644 index 0000000..ccb1cbc --- /dev/null +++ b/src/testing/tool-annotations.ts @@ -0,0 +1,54 @@ +import type { McpServer, Tool } from '@modelcontextprotocol/server' +import { beforeAll, describe, expect, it } from 'vitest' +import { listAdvertisedTools } from './advertised-schemas.js' + +/** The annotations one tool should advertise. */ +export type ExpectedToolAnnotations = { + /** The full advertised title, prefix included: `'Todoist: Add Tasks'`. */ + title: string + readOnlyHint: boolean + destructiveHint: boolean + idempotentHint: boolean + /** Defaults to false, as registration does: true only for a tool that reaches outside the account. */ + openWorldHint?: boolean +} + +export type ToolAnnotationsConfig = { + /** Builds a fresh server with every tool registered. */ + createServer: () => McpServer + /** Every tool the server should advertise, by name. */ + expected: Readonly> +} + +/** + * Pins every tool's annotations as a client receives them on `tools/list`, defaults included. + * Clients decide from these whether a call needs the user's confirmation, so a hint that changes + * should change on purpose. Fails as well on a tool advertised without an expectation, or + * expected and not advertised. + */ +export function describeToolAnnotations({ createServer, expected }: ToolAnnotationsConfig): void { + describe('tool annotations', () => { + let advertised: Map + + beforeAll(async () => { + const tools = await listAdvertisedTools(createServer()) + advertised = new Map(tools.map((tool) => [tool.name, tool])) + }) + + it('pins every advertised tool, and only those', () => { + expect([...advertised.keys()].sort()).toEqual(Object.keys(expected).sort()) + }) + + describe.each(Object.entries(expected))('%s', (name, expectation) => { + it('advertises the expected annotations', () => { + expect(advertised.get(name)?.annotations).toEqual({ + title: expectation.title, + readOnlyHint: expectation.readOnlyHint, + destructiveHint: expectation.destructiveHint, + idempotentHint: expectation.idempotentHint, + openWorldHint: expectation.openWorldHint ?? false, + }) + }) + }) + }) +} From 204d215bc1b69ababf033f527d5c45d152219a72 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Mon, 9 Nov 2026 12:20:54 +0000 Subject: [PATCH 2/4] feat(host): add the host's side of the token contract mcp-core defines what a validator resolves and throws; deciding what a rejection means was still todoist-ai-integrations' own transient-error.ts, and the WWW-Authenticate challenge and the verdict cache were written twice: in its NestJS guard and in todoist-mcp's Express middleware. The framework-neutral parts move here: - isTransientValidationError: the host's isTransientError, unchanged (the same answer for 29 inputs, from timeouts and undici cause codes to every status class); - buildBearerChallenge: Bearer, with error="insufficient_scope" and resource_metadata when given; - createTokenVerdictCache: verdicts keyed by token and base URL, kept for a TTL, the oldest dropped when full, with an injectable clock. --- CODEBASE.md | 15 ++++--- README.md | 63 ++++++++++++++++++++++++----- src/host/challenge.test.ts | 18 +++++++++ src/host/challenge.ts | 21 ++++++++++ src/host/index.ts | 7 ++++ src/host/transient.test.ts | 48 ++++++++++++++++++++++ src/host/transient.ts | 45 +++++++++++++++++++++ src/host/verdict-cache.test.ts | 74 ++++++++++++++++++++++++++++++++++ src/host/verdict-cache.ts | 54 +++++++++++++++++++++++++ 9 files changed, 328 insertions(+), 17 deletions(-) create mode 100644 src/host/challenge.test.ts create mode 100644 src/host/challenge.ts create mode 100644 src/host/transient.test.ts create mode 100644 src/host/transient.ts create mode 100644 src/host/verdict-cache.test.ts create mode 100644 src/host/verdict-cache.ts diff --git a/CODEBASE.md b/CODEBASE.md index 99bda2a..13de4c4 100644 --- a/CODEBASE.md +++ b/CODEBASE.md @@ -43,11 +43,11 @@ oxlint + oxfmt · semantic-release. ## Public API surface (`package.json#exports`) -| Subpath | Provides | Peers it needs | -| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -| `.` (root) | The tool types, `createToolRegistrar`, `getToolOutput`, `removeNullFields`, schema cache, annotations | `@modelcontextprotocol/server`, `zod` | -| `@doist/mcp-core/host` | `validateBearerToken`, `TokenValidationError` and the host contract types (`TokenValidationResult`, `ValidateToken`, `McpServerOptions`) | none | -| `@doist/mcp-core/testing` | `describeOutputSchemaNullability`, `describeAdvertisedToolSchemas` and the helpers they use | the above; also imports `@modelcontextprotocol/client` and `vitest`, undeclared | +| Subpath | Provides | Peers it needs | +| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | +| `.` (root) | The tool types, `createToolRegistrar`, `getToolOutput`, `removeNullFields`, schema cache, annotations | `@modelcontextprotocol/server`, `zod` | +| `@doist/mcp-core/host` | `validateBearerToken`, `TokenValidationError`, the host contract types (`TokenValidationResult`, `ValidateToken`, `McpServerOptions`), and the host's helpers (`isTransientValidationError`, `buildBearerChallenge`, `createTokenVerdictCache`) | none | +| `@doist/mcp-core/testing` | `describeOutputSchemaNullability`, `describeAdvertisedToolSchemas` and the helpers they use | the above; also imports `@modelcontextprotocol/client` and `vitest`, undeclared | ## `src/` tree @@ -66,7 +66,10 @@ src/ ├─ host/ # ./host subpath: what a server offers the host that serves it │ ├─ index.ts # ./host barrel │ ├─ server-contract.ts # TokenValidationResult, ValidateToken, McpServerOptions (types only) -│ └─ validate-bearer-token.ts # validateBearerToken, TokenValidationError +│ ├─ validate-bearer-token.ts # validateBearerToken, TokenValidationError +│ ├─ transient.ts # isTransientValidationError +│ ├─ challenge.ts # buildBearerChallenge +│ └─ verdict-cache.ts # createTokenVerdictCache └─ testing/ # ./testing subpath: suites the servers run over their own tools ├─ index.ts # ./testing barrel ├─ nullable-output.ts # findNullablePaths, describeOutputSchemaNullability diff --git a/README.md b/README.md index d506b63..043ba21 100644 --- a/README.md +++ b/README.md @@ -21,17 +21,17 @@ The MCP SDK and Zod are peer dependencies, so the server and the core share one ## What's in it -| Module | Key exports | -| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| `tool` | `McpTool`, `AnyMcpTool`, `ToolResult`, `ExecuteResult`, `RequiredToolAnnotations`, `ToolSchemaSource` (types) | -| `register-tool` | `createToolRegistrar`, `ToolRegistrarOptions`, `RegisterTool`, `ToolFailure` | -| `tool-output` | `getToolOutput`, `getErrorOutput`, `ToolOutputOptions` | -| `sanitize` | `removeNullFields`, `RemoveNullFieldsOptions` | -| `tool-schemas` | `getToolSchemas`, `ToolSchemas` | -| `annotations` | `getMcpAnnotations`, `formatToolTitle` | -| `app-meta` | `normalizeToolMeta` | -| `host` (subpath) | `validateBearerToken`, `ValidateBearerTokenOptions`, `TokenValidationError`, `TokenValidationResult`, `ValidateToken`, `McpServerOptions` | -| `testing` (subpath) | `describeOutputSchemaNullability`, `describeAdvertisedToolSchemas`, `findNullablePaths`, `listAdvertisedTools` | +| Module | Key exports | +| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `tool` | `McpTool`, `AnyMcpTool`, `ToolResult`, `ExecuteResult`, `RequiredToolAnnotations`, `ToolSchemaSource` (types) | +| `register-tool` | `createToolRegistrar`, `ToolRegistrarOptions`, `RegisterTool`, `ToolFailure` | +| `tool-output` | `getToolOutput`, `getErrorOutput`, `ToolOutputOptions` | +| `sanitize` | `removeNullFields`, `RemoveNullFieldsOptions` | +| `tool-schemas` | `getToolSchemas`, `ToolSchemas` | +| `annotations` | `getMcpAnnotations`, `formatToolTitle` | +| `app-meta` | `normalizeToolMeta` | +| `host` (subpath) | `validateBearerToken`, `ValidateBearerTokenOptions`, `TokenValidationError`, `TokenValidationResult`, `ValidateToken`, `McpServerOptions`, `isTransientValidationError`, `buildBearerChallenge`, `createTokenVerdictCache` | +| `testing` (subpath) | `describeOutputSchemaNullability`, `describeAdvertisedToolSchemas`, `findNullablePaths`, `listAdvertisedTools` | ## Usage @@ -138,6 +138,47 @@ export const validateNotesToken: ValidateToken = (token, baseUrl = 'https://note The body is drained unread, so a change to the response's shape can't misclassify a token and the connection goes back to the pool. Redirects aren't followed: a sign-in page that answers 200 would otherwise pass for an accepted token. Pass `classifyForbidden` when a 403 can also mean a refusal that consent can't lift, `headers` to tag the request, and `fetch` when the server's API client has its own transport (a proxy from `HTTPS_PROXY`, say), so validation goes the same way as every other call. +On the host's side, three helpers turn a validator's answer into a response, whatever the HTTP framework: + +```ts +import { + buildBearerChallenge, + createTokenVerdictCache, + isTransientValidationError, +} from '@doist/mcp-core/host' + +const verdicts = createTokenVerdictCache({ ttlMs: 120_000, maxEntries: 10_000 }) + +async function checkToken(token: string, baseUrl: string): Promise { + let result = verdicts.get(token, baseUrl) + if (!result) { + try { + result = await validateNotesToken(token, baseUrl) + } catch (error) { + if (isTransientValidationError(error)) return 'proceed' // or a 503; never cached + throw error + } + verdicts.set(token, baseUrl, result) + } + if (result === 'valid') return 'proceed' + const forbidden = result === 'forbidden' + return new Response(null, { + status: forbidden ? 403 : 401, + headers: { + 'WWW-Authenticate': buildBearerChallenge({ + error: forbidden ? 'insufficient_scope' : undefined, + resourceMetadataUrl: + 'https://notes.example.com/.well-known/oauth-protected-resource/mcp', + }), + }, + }) +} +``` + +- `isTransientValidationError`: a timeout, a dropped or refused connection, or a 5xx, the rejections worth retrying. A redirect or a 404 is not. +- `buildBearerChallenge`: `Bearer`, with `error="insufficient_scope"` and `resource_metadata="…"` when given. +- `createTokenVerdictCache`: verdicts keyed by token and base URL, kept for `ttlMs`, the oldest dropped when full. + ### Contract tests `@doist/mcp-core/testing` holds suites a server runs over its own tool registry: diff --git a/src/host/challenge.test.ts b/src/host/challenge.test.ts new file mode 100644 index 0000000..0bb3e3a --- /dev/null +++ b/src/host/challenge.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { buildBearerChallenge } from './challenge.js' + +const METADATA = 'https://ai.todoist.net/.well-known/oauth-protected-resource/mcp' + +describe('buildBearerChallenge', () => { + it.each([ + [{}, 'Bearer'], + [{ resourceMetadataUrl: METADATA }, `Bearer resource_metadata="${METADATA}"`], + [{ error: 'insufficient_scope' as const }, 'Bearer error="insufficient_scope"'], + [ + { error: 'insufficient_scope' as const, resourceMetadataUrl: METADATA }, + `Bearer error="insufficient_scope", resource_metadata="${METADATA}"`, + ], + ])('builds the challenge for %o', (options, expected) => { + expect(buildBearerChallenge(options)).toBe(expected) + }) +}) diff --git a/src/host/challenge.ts b/src/host/challenge.ts new file mode 100644 index 0000000..a89a0c8 --- /dev/null +++ b/src/host/challenge.ts @@ -0,0 +1,21 @@ +export type BearerChallengeOptions = { + /** + * `insufficient_scope` (RFC 6750) for a 403 on a token that lacks a scope, so the client asks + * for consent again. Left out for a 401, where the client refreshes its token. + */ + error?: 'insufficient_scope' + /** The resource's protected-resource metadata (RFC 9728), where the client finds how to authorise. */ + resourceMetadataUrl?: string +} + +/** The `WWW-Authenticate` value for a refused bearer token. */ +export function buildBearerChallenge({ + error, + resourceMetadataUrl, +}: BearerChallengeOptions = {}): string { + const params = [ + ...(error ? [`error="${error}"`] : []), + ...(resourceMetadataUrl ? [`resource_metadata="${resourceMetadataUrl}"`] : []), + ] + return params.length > 0 ? `Bearer ${params.join(', ')}` : 'Bearer' +} diff --git a/src/host/index.ts b/src/host/index.ts index 8f1601b..baa5c51 100644 --- a/src/host/index.ts +++ b/src/host/index.ts @@ -1,6 +1,13 @@ +export { buildBearerChallenge, type BearerChallengeOptions } from './challenge.js' export type { McpServerOptions, TokenValidationResult, ValidateToken } from './server-contract.js' +export { isTransientValidationError } from './transient.js' export { TokenValidationError, validateBearerToken, type ValidateBearerTokenOptions, } from './validate-bearer-token.js' +export { + createTokenVerdictCache, + type TokenVerdictCache, + type TokenVerdictCacheOptions, +} from './verdict-cache.js' diff --git a/src/host/transient.test.ts b/src/host/transient.test.ts new file mode 100644 index 0000000..53d06e7 --- /dev/null +++ b/src/host/transient.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { isTransientValidationError } from './transient.js' +import { TokenValidationError } from './validate-bearer-token.js' + +function withName(name: string): Error { + const error = new Error('stopped') + error.name = name + return error +} + +function fetchFailed(code: string): TypeError { + // Not 'fetch failed', so only the code on `cause` can mark it transient. + return new TypeError('request could not be sent', { + cause: Object.assign(new Error(code), { code }), + }) +} + +describe('isTransientValidationError', () => { + it.each([ + ['a timeout', withName('TimeoutError')], + ['an abort', withName('AbortError')], + ['a refused connection', fetchFailed('ECONNREFUSED')], + ['a reset connection', fetchFailed('ECONNRESET')], + ['a DNS failure', fetchFailed('ENOTFOUND')], + ['a temporary DNS failure', fetchFailed('EAI_AGAIN')], + ['an undici connect timeout', fetchFailed('UND_ERR_CONNECT_TIMEOUT')], + ['an undici socket error', fetchFailed('UND_ERR_SOCKET')], + ['a "fetch failed" without a cause', new TypeError('fetch failed')], + ['a 500', new TokenValidationError(500)], + ['a 503', new TokenValidationError(503)], + ['a plain object carrying a 502', { httpStatusCode: 502 }], + ['a plain object carrying statusCode 504', { statusCode: 504 }], + ])('treats %s as transient', (_label, error) => { + expect(isTransientValidationError(error)).toBe(true) + }) + + it.each([ + ['a 404 from a misconfigured base URL', new TokenValidationError(404)], + ['a redirect', new TokenValidationError(302)], + ['a 429', new TokenValidationError(429)], + ['an unrelated error', new Error('boom')], + ['a string', 'fetch failed'], + ['null', null], + ['undefined', undefined], + ])('treats %s as not transient', (_label, error) => { + expect(isTransientValidationError(error)).toBe(false) + }) +}) diff --git a/src/host/transient.ts b/src/host/transient.ts new file mode 100644 index 0000000..9ddfee3 --- /dev/null +++ b/src/host/transient.ts @@ -0,0 +1,45 @@ +const TRANSIENT_CAUSE_CODES = new Set([ + 'ECONNREFUSED', + 'ECONNRESET', + 'ETIMEDOUT', + 'ENOTFOUND', + 'EAI_AGAIN', + 'EPIPE', + 'UND_ERR_CONNECT_TIMEOUT', + 'UND_ERR_SOCKET', +]) + +const TRANSIENT_MESSAGES = ['fetch failed', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'] + +function statusOf(error: object): number | undefined { + const record = error as Record + if (typeof record.httpStatusCode === 'number') return record.httpStatusCode + if (typeof record.statusCode === 'number') return record.statusCode + return undefined +} + +/** + * Whether a `ValidateToken` rejection is worth retrying rather than a fault to report: a timeout, + * a dropped or refused connection, or a 5xx (`TokenValidationError` carries it as + * `httpStatusCode`). A host can then let the request through or answer 503, and never caches + * the failure as a verdict. Anything else, such as a redirect or a 404 from a misconfigured base + * URL, is not transient. + */ +export function isTransientValidationError(error: unknown): boolean { + if (error instanceof Error) { + if (error.name === 'TimeoutError' || error.name === 'AbortError') return true + + // undici wraps transport failures in "fetch failed" and puts the code on `cause`. + const causeCode = (error.cause as { code?: unknown } | undefined)?.code + if (typeof causeCode === 'string' && TRANSIENT_CAUSE_CODES.has(causeCode)) return true + + if (TRANSIENT_MESSAGES.some((message) => error.message.includes(message))) return true + } + + if (error !== null && typeof error === 'object') { + const status = statusOf(error) + if (status !== undefined && status >= 500) return true + } + + return false +} diff --git a/src/host/verdict-cache.test.ts b/src/host/verdict-cache.test.ts new file mode 100644 index 0000000..03eba40 --- /dev/null +++ b/src/host/verdict-cache.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from 'vitest' +import { createTokenVerdictCache } from './verdict-cache.js' + +function clock(start = 1_000) { + let now = start + return { + now: () => now, + advance: (ms: number) => { + now += ms + }, + } +} + +describe('createTokenVerdictCache', () => { + it('returns what was stored for the same token and base URL', () => { + const cache = createTokenVerdictCache({ ttlMs: 1_000, maxEntries: 10 }) + + cache.set('tok', 'https://api.test', 'forbidden') + + expect(cache.get('tok', 'https://api.test')).toBe('forbidden') + }) + + it('keeps a token apart per base URL, so staging and production never share a verdict', () => { + const cache = createTokenVerdictCache({ ttlMs: 1_000, maxEntries: 10 }) + + cache.set('tok', 'https://api.test', 'valid') + + expect(cache.get('tok', 'https://staging.test')).toBeUndefined() + expect(cache.get('tok')).toBeUndefined() + }) + + it('forgets a verdict once the TTL has passed, and keeps it until then', () => { + const time = clock() + const cache = createTokenVerdictCache({ ttlMs: 1_000, maxEntries: 10, now: time.now }) + + cache.set('tok', undefined, 'valid') + time.advance(999) + expect(cache.get('tok')).toBe('valid') + time.advance(1) + expect(cache.get('tok')).toBeUndefined() + }) + + it('evicts the oldest verdict when full', () => { + const cache = createTokenVerdictCache({ ttlMs: 1_000, maxEntries: 2 }) + + cache.set('first', undefined, 'valid') + cache.set('second', undefined, 'invalid') + cache.set('third', undefined, 'forbidden') + + expect(cache.get('first')).toBeUndefined() + expect(cache.get('second')).toBe('invalid') + expect(cache.get('third')).toBe('forbidden') + }) + + it('replaces a verdict for the same token without evicting another', () => { + const cache = createTokenVerdictCache({ ttlMs: 1_000, maxEntries: 2 }) + + cache.set('first', undefined, 'valid') + cache.set('second', undefined, 'valid') + cache.set('second', undefined, 'invalid') + + expect(cache.get('first')).toBe('valid') + expect(cache.get('second')).toBe('invalid') + }) + + it('forgets everything on clear', () => { + const cache = createTokenVerdictCache({ ttlMs: 1_000, maxEntries: 10 }) + cache.set('tok', undefined, 'valid') + + cache.clear() + + expect(cache.get('tok')).toBeUndefined() + }) +}) diff --git a/src/host/verdict-cache.ts b/src/host/verdict-cache.ts new file mode 100644 index 0000000..d7d425e --- /dev/null +++ b/src/host/verdict-cache.ts @@ -0,0 +1,54 @@ +import type { TokenValidationResult } from './server-contract.js' + +export type TokenVerdictCacheOptions = { + /** How long a verdict stands before the token is validated again. */ + ttlMs: number + /** The most verdicts kept; the oldest goes first when full. */ + maxEntries: number + /** The clock, for tests. Defaults to `Date.now`. */ + now?: () => number +} + +export type TokenVerdictCache = { + get(token: string, baseUrl?: string): TokenValidationResult | undefined + set(token: string, baseUrl: string | undefined, result: TokenValidationResult): void + clear(): void +} + +/** + * Remembers token verdicts for a while, so a host doesn't validate the same token on every + * request. Keyed by token and base URL, so one token is never judged against another + * environment's verdict. Store only verdicts: a transient failure is not one. + */ +export function createTokenVerdictCache({ + ttlMs, + maxEntries, + now = Date.now, +}: TokenVerdictCacheOptions): TokenVerdictCache { + const entries = new Map() + const keyOf = (token: string, baseUrl?: string) => `${token}::${baseUrl ?? ''}` + + return { + get(token, baseUrl) { + const key = keyOf(token, baseUrl) + const entry = entries.get(key) + if (!entry) return undefined + if (now() < entry.expiresAt) return entry.result + entries.delete(key) + return undefined + }, + set(token, baseUrl, result) { + const key = keyOf(token, baseUrl) + // Re-inserting moves the key to the end, so eviction order stays oldest-first. + entries.delete(key) + if (entries.size >= maxEntries) { + const oldest = entries.keys().next().value + if (oldest !== undefined) entries.delete(oldest) + } + entries.set(key, { result, expiresAt: now() + ttlMs }) + }, + clear() { + entries.clear() + }, + } +} From 1bb9cd5ca611071581ef317c8a63191144d4f262 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Mon, 9 Nov 2026 12:29:07 +0000 Subject: [PATCH 3/4] fix(host): read error codes, bound 5xx, and honour a zero-entry cache From review: - isTransientValidationError reads the code on the error as well as on its cause, and matches only undici's "fetch failed" by message. An error that merely mentions ECONNREFUSED is no longer transient; a Node error carrying the code is, whatever its message says. - Only 500-599 counts as a transient status, not any number above 500. - createTokenVerdictCache keeps nothing when maxEntries is 0. - The challenge test uses an example.com metadata URL. --- src/host/challenge.test.ts | 2 +- src/host/transient.test.ts | 11 +++++++++++ src/host/transient.ts | 23 ++++++++++++++--------- src/host/verdict-cache.test.ts | 8 ++++++++ src/host/verdict-cache.ts | 1 + 5 files changed, 35 insertions(+), 10 deletions(-) diff --git a/src/host/challenge.test.ts b/src/host/challenge.test.ts index 0bb3e3a..b1bb981 100644 --- a/src/host/challenge.test.ts +++ b/src/host/challenge.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { buildBearerChallenge } from './challenge.js' -const METADATA = 'https://ai.todoist.net/.well-known/oauth-protected-resource/mcp' +const METADATA = 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp' describe('buildBearerChallenge', () => { it.each([ diff --git a/src/host/transient.test.ts b/src/host/transient.test.ts index 53d06e7..3dc274b 100644 --- a/src/host/transient.test.ts +++ b/src/host/transient.test.ts @@ -8,6 +8,11 @@ function withName(name: string): Error { return error } +/** A Node network error: the code on the error itself, as `net` and `dns` raise them. */ +function nodeError(code: string): Error { + return Object.assign(new Error(`connect ${code} 192.0.2.1:443`), { code }) +} + function fetchFailed(code: string): TypeError { // Not 'fetch failed', so only the code on `cause` can mark it transient. return new TypeError('request could not be sent', { @@ -26,6 +31,9 @@ describe('isTransientValidationError', () => { ['an undici connect timeout', fetchFailed('UND_ERR_CONNECT_TIMEOUT')], ['an undici socket error', fetchFailed('UND_ERR_SOCKET')], ['a "fetch failed" without a cause', new TypeError('fetch failed')], + ['a Node error with a refused connection code', nodeError('ECONNREFUSED')], + ['a Node error with a timed-out connection code', nodeError('ETIMEDOUT')], + ['a 599', { httpStatusCode: 599 }], ['a 500', new TokenValidationError(500)], ['a 503', new TokenValidationError(503)], ['a plain object carrying a 502', { httpStatusCode: 502 }], @@ -39,6 +47,9 @@ describe('isTransientValidationError', () => { ['a redirect', new TokenValidationError(302)], ['a 429', new TokenValidationError(429)], ['an unrelated error', new Error('boom')], + ['an error that only mentions a code', new Error('upstream said ECONNREFUSED earlier')], + ['a Node error with an unknown code', nodeError('EACCES')], + ['a status code past the HTTP range', { statusCode: 600 }], ['a string', 'fetch failed'], ['null', null], ['undefined', undefined], diff --git a/src/host/transient.ts b/src/host/transient.ts index 9ddfee3..b7a0032 100644 --- a/src/host/transient.ts +++ b/src/host/transient.ts @@ -1,4 +1,4 @@ -const TRANSIENT_CAUSE_CODES = new Set([ +const TRANSIENT_CODES = new Set([ 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', @@ -9,7 +9,9 @@ const TRANSIENT_CAUSE_CODES = new Set([ 'UND_ERR_SOCKET', ]) -const TRANSIENT_MESSAGES = ['fetch failed', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'] +function codeOf(value: unknown): unknown { + return (value as { code?: unknown } | undefined)?.code +} function statusOf(error: object): number | undefined { const record = error as Record @@ -20,8 +22,8 @@ function statusOf(error: object): number | undefined { /** * Whether a `ValidateToken` rejection is worth retrying rather than a fault to report: a timeout, - * a dropped or refused connection, or a 5xx (`TokenValidationError` carries it as - * `httpStatusCode`). A host can then let the request through or answer 503, and never caches + * a dropped or refused connection (by its `code`, on the error or on its `cause`), or a 5xx + * (`TokenValidationError` carries it as `httpStatusCode`). A host can then let the request through or answer 503, and never caches * the failure as a verdict. Anything else, such as a redirect or a 404 from a misconfigured base * URL, is not transient. */ @@ -29,16 +31,19 @@ export function isTransientValidationError(error: unknown): boolean { if (error instanceof Error) { if (error.name === 'TimeoutError' || error.name === 'AbortError') return true - // undici wraps transport failures in "fetch failed" and puts the code on `cause`. - const causeCode = (error.cause as { code?: unknown } | undefined)?.code - if (typeof causeCode === 'string' && TRANSIENT_CAUSE_CODES.has(causeCode)) return true + // Node's net and dns errors carry the code themselves; undici wraps them in "fetch failed" + // and puts the code on `cause`. + for (const code of [codeOf(error), codeOf(error.cause)]) { + if (typeof code === 'string' && TRANSIENT_CODES.has(code)) return true + } - if (TRANSIENT_MESSAGES.some((message) => error.message.includes(message))) return true + // undici's own wording for a request that never got a response, when it gives no code. + if (error.message.includes('fetch failed')) return true } if (error !== null && typeof error === 'object') { const status = statusOf(error) - if (status !== undefined && status >= 500) return true + if (status !== undefined && status >= 500 && status <= 599) return true } return false diff --git a/src/host/verdict-cache.test.ts b/src/host/verdict-cache.test.ts index 03eba40..82a3fe9 100644 --- a/src/host/verdict-cache.test.ts +++ b/src/host/verdict-cache.test.ts @@ -63,6 +63,14 @@ describe('createTokenVerdictCache', () => { expect(cache.get('second')).toBe('invalid') }) + it('keeps nothing when maxEntries is 0', () => { + const cache = createTokenVerdictCache({ ttlMs: 1_000, maxEntries: 0 }) + + cache.set('tok', undefined, 'valid') + + expect(cache.get('tok')).toBeUndefined() + }) + it('forgets everything on clear', () => { const cache = createTokenVerdictCache({ ttlMs: 1_000, maxEntries: 10 }) cache.set('tok', undefined, 'valid') diff --git a/src/host/verdict-cache.ts b/src/host/verdict-cache.ts index d7d425e..dcc0633 100644 --- a/src/host/verdict-cache.ts +++ b/src/host/verdict-cache.ts @@ -38,6 +38,7 @@ export function createTokenVerdictCache({ return undefined }, set(token, baseUrl, result) { + if (maxEntries <= 0) return const key = keyOf(token, baseUrl) // Re-inserting moves the key to the end, so eviction order stays oldest-first. entries.delete(key) From 32a577ed8749f767ebd1761f6ada3c0d00402d26 Mon Sep 17 00:00:00 2001 From: Scott Lovegrove Date: Mon, 9 Nov 2026 12:31:01 +0000 Subject: [PATCH 4/4] test(testing): pin the measured total and the sort, from review - The one-array test asserts toolsList itself: with a tokenizer that returns 1 per call it is 1, where a sum over the tools would be 2. - The fixture registers the cheaper tool first, so only the sort puts the more expensive one ahead; both checks failed with the calculation or the sort taken out. - ExpectedToolAnnotations is RequiredToolAnnotations plus the title. - The budget docstring says "must stay under", as the check does, and the README example uses a fixed budget rather than an env override. - pad is gone in favour of padStart. readAdvertisedSurface stays exported: token-footprint.ts imports it. --- README.md | 2 +- src/testing/token-footprint.test.ts | 22 +++++++++++++--------- src/testing/token-footprint.ts | 10 +++------- src/testing/tool-annotations.ts | 17 +++++++---------- 4 files changed, 24 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index f0f4b3b..03e8af6 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ const createServer = () => getMcpServer({ token: 'test-token' }) describeTokenFootprint({ createServer, countTokens: (text) => encode(text).length, - budget: Number(process.env.MCP_TOKEN_BUDGET ?? 13_250), + budget: 13_250, }) describeToolAnnotations({ createServer, diff --git a/src/testing/token-footprint.test.ts b/src/testing/token-footprint.test.ts index e600479..5c5ea64 100644 --- a/src/testing/token-footprint.test.ts +++ b/src/testing/token-footprint.test.ts @@ -7,7 +7,15 @@ import { describeTokenFootprint, measureTokenFootprint } from './token-footprint const hints = { readOnlyHint: true, destructiveHint: false, idempotentHint: true } +// The cheaper tool is registered first, so only the sort can put find-tasks ahead of it. const tools: AnyMcpTool[] = [ + { + name: 'ping', + description: 'Checks the server answers.', + parameters: {}, + annotations: hints, + execute: async () => ({ textContent: 'pong' }), + }, { name: 'find-tasks', description: 'Finds tasks.', @@ -16,13 +24,6 @@ const tools: AnyMcpTool[] = [ annotations: hints, execute: async () => ({}), }, - { - name: 'ping', - description: 'Checks the server answers.', - parameters: {}, - annotations: hints, - execute: async () => ({ textContent: 'pong' }), - }, ] const INSTRUCTIONS = 'Use find-tasks before asking the user.' @@ -49,19 +50,22 @@ function countCharacters(text: string): number { describe('measureTokenFootprint', () => { it('measures the tools/list payload as one array, the way a client receives it', async () => { const measured: string[] = [] - await measureTokenFootprint(createServer(), (text) => { + const footprint = await measureTokenFootprint(createServer(), (text) => { measured.push(text) return 1 }) + // One call for the whole list: a sum over the tools would count 2. + expect(footprint.toolsList).toBe(1) + const asArray = measured .filter((text) => text.startsWith('[')) .map( (text) => JSON.parse(text) as { name: string; annotations?: { title?: string } }[], )[0] expect(asArray?.map((tool) => [tool.name, tool.annotations?.title])).toEqual([ - ['find-tasks', 'Fixture: Find Tasks'], ['ping', 'Fixture: Ping'], + ['find-tasks', 'Fixture: Find Tasks'], ]) }) diff --git a/src/testing/token-footprint.ts b/src/testing/token-footprint.ts index 9ca352c..b689e80 100644 --- a/src/testing/token-footprint.ts +++ b/src/testing/token-footprint.ts @@ -56,10 +56,6 @@ export async function measureTokenFootprint( } } -function pad(value: string | number, width: number): string { - return String(value).padStart(width) -} - function formatFootprint(footprint: TokenFootprint, budget: number): string { return [ '', @@ -73,7 +69,7 @@ function formatFootprint(footprint: TokenFootprint, budget: number): string { 'Per tool (total / description / inputSchema / outputSchema):', ...footprint.tools.map( (tool) => - ` ${pad(tool.total, 5)} ${pad(tool.description, 4)} ${pad(tool.inputSchema, 5)} ${pad(tool.outputSchema, 5)} ${tool.name}`, + ` ${String(tool.total).padStart(5)} ${String(tool.description).padStart(4)} ${String(tool.inputSchema).padStart(5)} ${String(tool.outputSchema).padStart(5)} ${tool.name}`, ), ].join('\n') } @@ -84,8 +80,8 @@ export type TokenFootprintConfig = { /** The tokenizer, such as `(text) => encode(text).length` from `gpt-tokenizer`. */ countTokens: CountTokens /** - * The most the fixed cost may be. Treat it as a ratchet rather than headroom: a rise needs - * justifying in the change that causes it. + * What the fixed cost must stay under. Treat it as a ratchet rather than headroom: a rise + * needs justifying in the change that causes it. */ budget: number } diff --git a/src/testing/tool-annotations.ts b/src/testing/tool-annotations.ts index ccb1cbc..7c49a2c 100644 --- a/src/testing/tool-annotations.ts +++ b/src/testing/tool-annotations.ts @@ -1,17 +1,14 @@ import type { McpServer, Tool } from '@modelcontextprotocol/server' import { beforeAll, describe, expect, it } from 'vitest' +import type { RequiredToolAnnotations } from '../tool.js' import { listAdvertisedTools } from './advertised-schemas.js' -/** The annotations one tool should advertise. */ -export type ExpectedToolAnnotations = { - /** The full advertised title, prefix included: `'Todoist: Add Tasks'`. */ - title: string - readOnlyHint: boolean - destructiveHint: boolean - idempotentHint: boolean - /** Defaults to false, as registration does: true only for a tool that reaches outside the account. */ - openWorldHint?: boolean -} +/** + * The annotations one tool should advertise: its own hints, as the tool declares them, plus the + * full advertised `title`, prefix included (`'Todoist: Add Tasks'`). `openWorldHint` defaults to + * false, as registration does. + */ +export type ExpectedToolAnnotations = RequiredToolAnnotations & { title: string } export type ToolAnnotationsConfig = { /** Builds a fresh server with every tool registered. */