Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions CODEBASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 `<name>.test.ts`.
Expand Down
51 changes: 40 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down
17 changes: 14 additions & 3 deletions src/testing/advertised-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Tool[]> {
/**
* 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<Tool[]> {
return (await readAdvertisedSurface(server)).tools
}

export type AdvertisedSchemasConfig = {
/** Every tool the server should register. */
tools: readonly ToolSchemaSource[]
Expand Down
13 changes: 13 additions & 0 deletions src/testing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
95 changes: 95 additions & 0 deletions src/testing/token-footprint.test.ts
Original file line number Diff line number Diff line change
@@ -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 })
113 changes: 113 additions & 0 deletions src/testing/token-footprint.ts
Original file line number Diff line number Diff line change
@@ -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<TokenFootprint> {
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)
})
})
}
Loading
Loading