diff --git a/CODEBASE.md b/CODEBASE.md index 5f61650..f7620c5 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`, `describeToolAnnotations`, `describeTokenFootprint` 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`, `describeToolAnnotations`, `describeTokenFootprint` 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 03e8af6..f5e578c 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`, `describeToolAnnotations`, `describeTokenFootprint`, `measureTokenFootprint`, `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`, `describeToolAnnotations`, `describeTokenFootprint`, `measureTokenFootprint`, `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..b1bb981 --- /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://mcp.example.com/.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..3dc274b --- /dev/null +++ b/src/host/transient.test.ts @@ -0,0 +1,59 @@ +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 +} + +/** 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', { + 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 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 }], + ['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')], + ['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], + ])('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..b7a0032 --- /dev/null +++ b/src/host/transient.ts @@ -0,0 +1,50 @@ +const TRANSIENT_CODES = new Set([ + 'ECONNREFUSED', + 'ECONNRESET', + 'ETIMEDOUT', + 'ENOTFOUND', + 'EAI_AGAIN', + 'EPIPE', + 'UND_ERR_CONNECT_TIMEOUT', + 'UND_ERR_SOCKET', +]) + +function codeOf(value: unknown): unknown { + return (value as { code?: unknown } | undefined)?.code +} + +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 (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. + */ +export function isTransientValidationError(error: unknown): boolean { + if (error instanceof Error) { + if (error.name === 'TimeoutError' || error.name === 'AbortError') 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 + } + + // 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 && status <= 599) 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..82a3fe9 --- /dev/null +++ b/src/host/verdict-cache.test.ts @@ -0,0 +1,82 @@ +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('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') + + 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..dcc0633 --- /dev/null +++ b/src/host/verdict-cache.ts @@ -0,0 +1,55 @@ +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) { + 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) + 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() + }, + } +}