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
15 changes: 9 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`, `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

Expand All @@ -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
Expand Down
63 changes: 52 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`, `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

Expand Down Expand Up @@ -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<Response | 'proceed'> {
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:
Expand Down
18 changes: 18 additions & 0 deletions src/host/challenge.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
21 changes: 21 additions & 0 deletions src/host/challenge.ts
Original file line number Diff line number Diff line change
@@ -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'
}
7 changes: 7 additions & 0 deletions src/host/index.ts
Original file line number Diff line number Diff line change
@@ -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'
59 changes: 59 additions & 0 deletions src/host/transient.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
50 changes: 50 additions & 0 deletions src/host/transient.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>
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
}
Loading
Loading