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..03e8af6 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: 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..5c5ea64 --- /dev/null +++ b/src/testing/token-footprint.test.ts @@ -0,0 +1,99 @@ +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 } + +// 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.', + parameters: { query: z.string() }, + outputSchema: { tasks: z.array(z.object({ id: z.string() })) }, + annotations: hints, + execute: async () => ({}), + }, +] + +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[] = [] + 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([ + ['ping', 'Fixture: Ping'], + ['find-tasks', 'Fixture: Find Tasks'], + ]) + }) + + 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..b689e80 --- /dev/null +++ b/src/testing/token-footprint.ts @@ -0,0 +1,109 @@ +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 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) => + ` ${String(tool.total).padStart(5)} ${String(tool.description).padStart(4)} ${String(tool.inputSchema).padStart(5)} ${String(tool.outputSchema).padStart(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 + /** + * 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 +} + +/** + * 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..7c49a2c --- /dev/null +++ b/src/testing/tool-annotations.ts @@ -0,0 +1,51 @@ +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: 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. */ + 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, + }) + }) + }) + }) +}