Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
16 changes: 8 additions & 8 deletions .agents/skills/write-tests/references/test-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ You saw the test fail once: before the fix, or with the feature undone. A test t

Assert what the caller gets or what reaches the API: `toHaveBeenCalledWith(<exact args>)`, `structuredContent` fields, the text. Flag an assertion that cannot tell right from wrong.

| Flag | Fine |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `toHaveBeenCalled()` or `toHaveBeenCalledTimes(n)` as the only evidence the behaviour happened: nothing checks which arguments reached the API (`src/tools/mark-done.test.ts:73` counts three `archiveThread` calls, never the IDs) | `toHaveBeenCalledTimes(n)` next to `toHaveBeenCalledWith` on the same call (`src/tools/list-channels.test.ts:247`) |
| | `.not.toHaveBeenCalled()`: proves a call did **not** happen (about 40 in this repo, e.g. `src/tools/create-thread.test.ts:56`) |
| `toBeDefined()` / `toBeTruthy()` as the last word on a value | The same as a guard right before reading the value's fields (`src/tools/get-mentions.test.ts:54`, `src/tools/tool-annotations.test.ts:198`) |
| `expect.any(...)` where the input fixes the exact value (`src/tools/fetch-inbox.test.ts:217` accepts any `Date` for a given `sinceDate`) | `expect.any(...)` for a value the test cannot know, such as a generated ID, or a time taken from the clock |
| `expect.objectContaining` that leaves out the field the test is about | `expect.objectContaining` around the fields the test is about, leaving out the rest (about a dozen in `src/tools/fetch-inbox.test.ts`) |
| A test whose only assertion is that no error was thrown, when the behaviour is a result | `rejects.toThrow('<message>')`: the error **is** the behaviour |
| Flag | Fine |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `toHaveBeenCalled()` or `toHaveBeenCalledTimes(n)` as the only evidence the behaviour happened: nothing checks which arguments reached the API (`src/tools/mark-done.test.ts:73` counts three `archiveThread` calls, never the IDs) | `toHaveBeenCalledTimes(n)` next to `toHaveBeenCalledWith` on the same call (`src/tools/list-channels.test.ts:247`) |
| | `.not.toHaveBeenCalled()`: proves a call did **not** happen (about 40 in this repo, e.g. `src/tools/create-thread.test.ts:56`) |
| `toBeDefined()` / `toBeTruthy()` as the last word on a value | The same as a guard right before reading the value's fields (`src/tools/get-mentions.test.ts:54`) |
| `expect.any(...)` where the input fixes the exact value (`src/tools/fetch-inbox.test.ts:217` accepts any `Date` for a given `sinceDate`) | `expect.any(...)` for a value the test cannot know, such as a generated ID, or a time taken from the clock |
| `expect.objectContaining` that leaves out the field the test is about | `expect.objectContaining` around the fields the test is about, leaving out the rest (about a dozen in `src/tools/fetch-inbox.test.ts`) |
| A test whose only assertion is that no error was thrown, when the behaviour is a result | `rejects.toThrow('<message>')`: the error **is** the behaviour |

Judge a test by its point, the behaviour its name describes. A weak assertion beside the ones that carry that point is fine.

Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
},
"dependencies": {
"@doist/comms-sdk": "3.12.0",
"@doist/mcp-core": "0.3.0",
"@doist/mcp-core": "0.4.0",
"dotenv": "17.4.2",
"p-limit": "6.2.0",
"zod": "4.6.7"
Expand Down
75 changes: 6 additions & 69 deletions src/token-footprint.test.ts
Original file line number Diff line number Diff line change
@@ -1,80 +1,17 @@
import { Client, InMemoryTransport } from '@modelcontextprotocol/client'
import { describeTokenFootprint } from '@doist/mcp-core/testing'
import { encode } from 'gpt-tokenizer'
import { getMcpServer } from './mcp-server.js'
import { registeredTools } from './tool-registry.js'

/**
* Budget for the fixed cost every session pays before a tool runs: the `tools/list` payload
* plus the `instructions` block. Treat it as a ratchet rather than headroom: it should move down
* over time, and a rise needs justifying in the PR that causes it. Override it with
* `MCP_TOKEN_BUDGET=NNNN` to experiment without editing the source.
* `MCP_TOKEN_BUDGET=NNNN` to experiment without editing the source; `npm run verify` ignores it.
*/
const DEFAULT_TOKEN_BUDGET = 13_250
const TOKEN_BUDGET = Number(process.env.MCP_TOKEN_BUDGET ?? DEFAULT_TOKEN_BUDGET)

function tokens(text: string): number {
return encode(text).length
}

function pad(value: string | number, width: number): string {
return String(value).padStart(width)
}

// What a client receives, read from a running server, so nothing here restates how
// registration titles a tool or compiles its schemas.
async function readAdvertisedSurface() {
const server = getMcpServer({ token: 'test-token' })
const client = new Client({ name: 'token-footprint', version: '1.0.0' })
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair()
await Promise.all([server.connect(serverTransport), client.connect(clientTransport)])
try {
const { tools } = await client.listTools()
return { tools, instructions: client.getInstructions() }
} finally {
await client.close()
await server.close()
}
}

describe('token footprint', () => {
it('keeps the tools/list payload and instructions within the budget', async () => {
const { tools, instructions } = await readAdvertisedSurface()
// Both halves of the fixed cost must be there: a lost block would read as a saving.
expect(tools).toHaveLength(registeredTools.length)
expect(instructions).toEqual(expect.stringMatching(/\S/))

const rows = tools
.map((tool) => ({
name: tool.name,
total: tokens(JSON.stringify(tool)),
description: tokens(tool.description ?? ''),
inputSchema: tokens(JSON.stringify(tool.inputSchema)),
outputSchema: tool.outputSchema ? tokens(JSON.stringify(tool.outputSchema)) : 0,
}))
.sort((a, b) => b.total - a.total)
// One JSON array on the wire: the per-tool rows above are only the breakdown.
const toolsList = tokens(JSON.stringify(tools))
const instructionsTokens = tokens(instructions ?? '')
const combined = toolsList + instructionsTokens

console.log(
[
'',
'=== MCP token footprint ===',
`tools registered: ${tools.length}`,
`instructions: ${instructionsTokens} tokens`,
`tools/list payload: ${toolsList} tokens`,
`combined fixed cost: ${combined} tokens`,
`budget: ${TOKEN_BUDGET} tokens`,
'',
'Per tool (total / description / inputSchema / outputSchema):',
...rows.map(
(row) =>
` ${pad(row.total, 5)} ${pad(row.description, 4)} ${pad(row.inputSchema, 5)} ${pad(row.outputSchema, 5)} ${row.name}`,
),
].join('\n'),
)

expect(combined).toBeLessThan(TOKEN_BUDGET)
})
describeTokenFootprint({
createServer: () => getMcpServer({ token: 'test-token' }),
countTokens: (text) => encode(text).length,
budget: Number(process.env.MCP_TOKEN_BUDGET ?? DEFAULT_TOKEN_BUDGET),
})
Loading
Loading