Skip to content

feat(host): add the host's side of the token contract - #8

Merged
scottlovegrove merged 6 commits into
mainfrom
feat/host-guard-helpers
Nov 9, 2026
Merged

scottlovegrove merged 6 commits into
mainfrom
feat/host-guard-helpers

Conversation

@scottlovegrove

@scottlovegrove scottlovegrove commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

What

Three framework-neutral helpers in @doist/mcp-core/host, for whatever serves an MCP server over HTTP:

  • isTransientValidationError(error): whether a ValidateToken rejection is worth retrying. That covers a timeout or abort, a dropped or refused connection (by its code, on the error or on its cause, or undici's "fetch failed" message), or a status from 500 to 599 carried as httpStatusCode or statusCode. A redirect, a 404 or a 429 is not transient.
  • buildBearerChallenge({ error?, resourceMetadataUrl? }): the WWW-Authenticate value. It's Bearer, with error="insufficient_scope" and resource_metadata="…" when given.
  • createTokenVerdictCache({ ttlMs, maxEntries, now? }): verdicts keyed by token and base URL, kept for ttlMs, with the oldest dropped when full and nothing kept when maxEntries is 0. now defaults to Date.now, and lets the TTL be tested without fake timers.

feat:, so this releases a minor version. Nothing existing changes.

Why

mcp-core now defines what a validator resolves and what it throws. But reading a rejection is still the host's own job: isTransientError in todoist-ai-integrations' transient-error.ts decides whether to fail open or answer 503. The challenge header and the verdict cache are written twice, once in the host's NestJS guard and once in todoist-mcp's Express middleware for its HTTP mode. With these here, both can drop their copies, and the rule for what counts as transient sits next to the code that throws.

Verification

  • npm run verify passes.
  • isTransientValidationError: 26 cases. The connection-error cases use a message other than "fetch failed", so the cause.code check is tested on its own. Removing the cause check, the message check or the timeout check, or treating 4xx as transient, each fails tests.
  • Compared with the host: I ran todoist-ai-integrations' isTransientError (from main) and the built isTransientValidationError over the same 32 inputs. Three answers differ, all on purpose, from review. A message that only mentions ECONNREFUSED, with no code, is no longer transient. statusCode: 600 is no longer transient. A Node error carrying code: 'ECONNRESET' whose message doesn't say so is now transient; the host's version misses it. A real Node network error, which carries both the code and the message, gets the same answer as before, and so does everything else: timeouts, undici cause codes, "fetch failed", and statuses from 200 to 599.
  • buildBearerChallenge: all four combinations of error and resourceMetadataUrl, matching the headers both the host and todoist-mcp send today.
  • createTokenVerdictCache: tested with an injected clock, covering:
    • a per-token and per-base-URL key;
    • the TTL boundary;
    • eviction of the oldest entry;
    • replacing an entry without evicting another;
    • clear.

Adoption

Separate PRs once this is released:

  • todoist-ai-integrations: its guard and BearerAuthGuard use all three, and transient-error.ts goes.
  • todoist-mcp: its HTTP middleware uses the challenge and the cache. It keeps failing open on every error, which is its documented behaviour.

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.
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.
@scottlovegrove scottlovegrove self-assigned this Nov 9, 2026

@doistbot doistbot left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds three framework-neutral host helpers to @doist/mcp-core/host — isTransientValidationError, buildBearerChallenge, and createTokenVerdictCache — so HTTP hosts can share one implementation of transient-error classification, the bearer challenge header, and verdict caching instead of maintaining duplicates. Well covered by tests, including parity checks against the host's existing logic.

Few things worth tightening:

  • createTokenVerdictCache still stores a verdict when maxEntries: 0, exceeding the advertised limit — skip insertion for zero capacity (or reject unsupported limits) and add a regression test.
  • isTransientValidationError matches ECONNREFUSED/ETIMEDOUT/ENOTFOUND via message substring, which can over-classify any error mentioning those strings; check error.code against TRANSIENT_CAUSE_CODES instead and keep only the undici 'fetch failed' message fallback.

I also included a few optional follow-up notes in the details below.

Optional follow-up notes (2)
  • P3 src/host/challenge.test.ts:4: This test fixture hard-codes the Doist hostname ai.todoist.net in a public repository. The repo's test rules require fixtures to use invented content and example.com, and the privacy check flags internal/product URLs. Use an example.com placeholder here (as the README does) so the published source doesn't expose the internal metadata endpoint.
  • P3 src/host/transient.ts:41: The documented contract is "a 5xx is transient", but this treats any numeric status >= 500 as transient. A custom ValidateToken that rejects with a non-HTTP numeric code such as { statusCode: 600 } or { httpStatusCode: 1000 } would be misclassified as transient and fail open. Bound the check to the HTTP 5xx range: status >= 500 && status <= 599.

Share Feedback • Review Logs

Comment thread src/host/verdict-cache.ts Resolved
Comment thread src/host/transient.ts Resolved
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.
- 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.
…ost-guard-helpers

# Conflicts:
#	CODEBASE.md
#	README.md
@scottlovegrove scottlovegrove added the 🚢 Ship PR requires passing checks before merge, but no independent human review. label Nov 9, 2026
@scottlovegrove
scottlovegrove merged commit a30de57 into main Nov 9, 2026
5 checks passed
@scottlovegrove
scottlovegrove deleted the feat/host-guard-helpers branch November 9, 2026 12:34
@doist-release-bot

Copy link
Copy Markdown

🎉 This PR is included in version 0.4.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

scottlovegrove added a commit to todoist/todoist-mcp that referenced this pull request Nov 9, 2026
…helpers (#693)

## What

`@doist/mcp-core` 0.4.0 ships the shared test suites (todoist/mcp-core#7)
and the host's side of the token contract (todoist/mcp-core#8). This
adopts both, one commit each.

**Test suites**
- **`src/tools/tool-annotations.test.ts`** → `describeToolAnnotations`.
All 49 tools' expected titles and hints are unchanged, now keyed by
`ToolNames`. They're checked exactly as a client receives them on
`tools/list`, defaults included. The old test spied on
`McpServer.prototype.registerTool` and matched only partially. The MCP
Apps `_meta` check for `find-tasks-by-date` stays, now reading the
advertised tool through `listAdvertisedTools`.
- **`src/token-footprint.test.ts`** → `describeTokenFootprint`. It
measures the payload and the instructions from a running server, instead
of rebuilding each entry with `z.toJSONSchema` and local copies of the
registrar's title and `_meta` logic.

**HTTP mode** (`requireValidTodoistToken`)
- The `WWW-Authenticate` challenge comes from `buildBearerChallenge`,
and the verdict cache from `createTokenVerdictCache`. They're the same
pieces todoist-ai-integrations will use.
- There's one cache per TTL (5 minutes static, 2 dynamic, or
`cacheTtlMs`), shared by every middleware with that TTL, as the single
module-wide cache was before. When full, it drops the oldest verdict,
where it used to prune expired entries and then clear everything.
`clearTokenValidationCache()` still empties them all.
- It still fails open on any validation error, as before. The log line
now says "Validation failed, proceeding" rather than "Transient error",
since it covers every error.

`fix(deps):` so the 0.4.0 bump releases, and todoist-ai-integrations
gets a single copy of mcp-core.

## The budget

| | Old test | Measured from the server |
| --- | --- | --- |
| `tools/list` payload (49 tools) | 35,624 | 35,177 |
| instructions | 971 | 971 |
| **Combined** | **36,595** | **36,148** |

`DEFAULT_TOKEN_BUDGET` moves down from 36,600 to 36,200. The old count
sat 5 tokens under the old budget; the real cost now has a similar small
margin of 52.

## Verification

- `npm run verify` passes.
- The annotations file runs 51 tests: one per tool, the coverage check,
and the `_meta` check.
- The middleware's tests are unchanged and all pass: 401 and 403
challenges with and without `resource_metadata`, caching of each
verdict, expiry under fake timers, a separate cache per base URL, and
failing open. Together with `http-app.test.ts` that's 60 tests. They pin
the behaviour across the refactor. From review, a new test fills the
cache past 10,000 tokens and checks that the oldest verdict goes and the
rest stay; it fails if the limit is off by one. The base URL test now
fails if the cache key drops the base URL, because the two middlewares
share a cache again.
doist-release-bot Bot added a commit to todoist/todoist-mcp that referenced this pull request Nov 9, 2026
## [14.0.2](v14.0.1...v14.0.2) (2026-11-09)

### Bug Fixes

* **deps:** move to @doist/mcp-core 0.4.0, its shared suites and host helpers ([#693](#693)) ([4f986dd](4f986dd)), closes [todoist/mcp-core#7](todoist/mcp-core#7) [todoist/mcp-core#8](todoist/mcp-core#8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released 🚢 Ship PR requires passing checks before merge, but no independent human review.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants