diff --git a/.changeset/engine-neutral-shapes.md b/.changeset/engine-neutral-shapes.md
new file mode 100644
index 00000000..fe800f38
--- /dev/null
+++ b/.changeset/engine-neutral-shapes.md
@@ -0,0 +1,12 @@
+---
+"nitro-mcp-toolkit": major
+"@nuxtjs/mcp-toolkit": major
+---
+
+Public types no longer follow the protocol engine's shapes. `McpRequestContext`, `McpAuthOptions`, `McpAuthCredentials`, `McpOriginOptions`, `McpSessionOptions` and `McpLimitsOptions` are now the toolkit's own interfaces, with the same fields as before, and `McpLogLevel` types the request's log level.
+
+Definitions returned by `defineMcpTool`, `defineMcpResource` and `defineMcpPrompt` no longer have a `build` method. Spreading a definition still works.
+
+`McpOAuth` no longer exposes `resource`, `resourceMetadataUrl`, `metadata` or `challengeScope`. Serve the metadata document with `oauth.metadataHandler(event)`, which now also accepts a Nitro 2 event, and read the challenge URL from `oauth.auth.resourceMetadataUrl`.
+
+Extension plugins (`McpExtensionPlugin`, `defineMcpPlugins`, `
/plugins.ts` and the `{ extensionPlugins }` argument) are now documented as experimental. They expose the engine's plugin contract and may change in any release.
diff --git a/.github/V1_ROLLOUT.md b/.github/V1_ROLLOUT.md
index 67581e09..03152f91 100644
--- a/.github/V1_ROLLOUT.md
+++ b/.github/V1_ROLLOUT.md
@@ -8,13 +8,17 @@ Open the foundation PR first. Later PRs target the preceding branch while it is
| Order | Branch | Review scope |
| --- | --- | --- |
-| 1 | `v1-01-release-rails` | CI for the integration branch and stack, release-channel checks, beta activation for both packages |
-| 2 | `v1-02-nitro2` | Nitro 2 adapter, H3 version isolation, transport/context/cancellation tests |
-| 3 | `v1-03-shared-api` | Definition metadata, directory overlays, generated imports, shared request APIs |
-| 4 | `v1-04-no-mcp-apps` | Remove built-in MCP Apps, their Vue bundler and host bridge, and update migration guidance |
-| 5 | `v1-05-nuxt` | Nuxt adapter, retirement of the old runtime and APIs, migrated fixtures and example applications |
-| 6 | `v1-06-docs` | Complete migration guide, docs site, READMEs, published agent skill |
-| 7 | `v1-07-beta` | Beta consumer validation and release readiness |
+| 1 | `v1-01-release-rails` | CI for the integration branch and stack, release-channel checks, beta activation for both packages (merged, #398) |
+| 2 | `v1-02-nitro2` | Nitro 2 adapter, H3 version isolation, transport/context/cancellation tests (merged, #399) |
+| 3 | `v1-03-shared-api` | Definition metadata, directory overlays, generated imports, shared request APIs (#402) |
+| 4 | `v1-04-no-mcp-apps` | Remove built-in MCP Apps, their Vue bundler and host bridge, and update migration guidance (#403) |
+| 5 | `v1-05-nuxt` | Nuxt adapter, retirement of the old runtime and APIs, migrated fixtures and example applications (#405) |
+| 6 | `v1-06-docs` | Migration guide, docs site, READMEs, published agent skill, server configuration DX (#406) |
+| 7 | `v1-07-auth-dx` | Runtime OAuth provider adapters (#415) |
+| 8 | `v1-08-toolkit-types` | Toolkit-owned names for exported engine types (#420) |
+| 9 | `v1-09-oauth-challenges` | OAuth scope challenges and service tokens (#421) |
+| 10 | `v1-10-engine-seams` | Engine-neutral public shapes, experimental plugins |
+| 11 | not opened | Beta consumer validation and release readiness |
Keep each step buildable and tested. Public changes carry their own changesets and enough documentation to use them; the docs step completes the migration material. Example application code moves with the API changes it consumes so CI previews remain usable.
diff --git a/AGENTS.md b/AGENTS.md
index 73f23b5d..2a0a12a4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -203,11 +203,11 @@ Windows is covered by a dedicated `test-windows` CI job that runs this package's
The runtime is written against a pinned `h3-mcp` (currently 0.2.0). That release dropped the `Mcp` prefix on types, owns MRTR helpers and RFC 9728 `resourceMetadataUrl`, and requires URI templates to pass through `defineResourceTemplate` so RFC 6570 matching is in the bundle — `defineMcpResource` already does that. Re-export the engine's elicitation kit (`inputRequired`, `mcpElicit`, `mcpElicitUrl`, `getElicitedContent`, `getInputResponses`, `getMissingInputs`, `canRequestInput`, `getSupportedInputs`, `defineRequestState`) and `McpJsonRpcError`; do not reimplement them. `createMcpHandler`'s second argument is h3-mcp's `{ extensionPlugins }`, typed as `McpHandlerSetup`.
-**The public API names only toolkit types.** Engine concepts are exported under `Mcp`-prefixed names (`McpAuthOptions`, `McpEra`, `McpExtensionPlugin`, `McpRequestContext`, …), and MCP spec types keep their spec names; never re-export an h3-mcp type under its own name. `McpHandlerOptions` lists each option it maps onto the engine instead of extending h3-mcp's `HandlerOptions` — `test/types.test.ts` pins the set, so a new option is a deliberate change. h3-mcp's own `H3EventContext.mcp` augmentation still widens `McpEvent.context.mcp` to the engine's full context; that leak goes away only with the engine. `nitro` and `nitropack` are optional peers used by their module entrypoints; H3 v2 is an internal dependency.
+**The public API names only toolkit types.** Engine concepts are exported under `Mcp`-prefixed names (`McpAuthOptions`, `McpEra`, `McpExtensionPlugin`, `McpRequestContext`, …), and MCP spec types keep their spec names; never re-export an h3-mcp type under its own name. `McpHandlerOptions` lists each option it maps onto the engine instead of extending h3-mcp's `HandlerOptions` — `test/types.test.ts` pins the set, so a new option is a deliberate change. h3-mcp's own `H3EventContext.mcp` augmentation still widens `McpEvent.context.mcp` to the engine's full context; that leak goes away only with the engine. `McpRequestContext`, `McpAuthOptions`, `McpOriginOptions`, `McpSessionOptions` and `McpLimitsOptions` are written out as toolkit interfaces rather than aliases, so an engine upgrade cannot silently change them. A definition's engine registration lives under a non-exported symbol (`buildDefinition` in `src/runtime/definition.ts`), and so does what an `McpOAuth` needs for its challenges (`oauthChallenge`), so neither is part of the public shape; symbol keys survive spreading and `Object.assign`, which the generated registry and the provider adapters rely on. Extension plugins are documented as experimental: they are h3-mcp's plugin contract. `nitro` and `nitropack` are optional peers used by their module entrypoints; H3 v2 is an internal dependency.
**`X-MCP-Tools` is the same kind of gate** (`src/runtime/tools-header.ts`): allowlist of tool names, HTTP 400 on unknowns. Unknown names run a separate engine with no application definitions or plugins on the original event, so authentication sees middleware context and the original body. `handler.definitions` stays the full catalog. Tool names and registration positions are indexed once; the last header selection is retained per handler to avoid repeated parsing and sorting. The cache holds only catalog membership, never authentication or request state. Different selections replace it, and every request still runs auth and scope checks.
-**`scopes` gates invocation and application callbacks; static definition metadata stays listed.** Resource-template enumeration/completion and prompt completion check scopes before calling application code; unauthorized enumeration fails `resources/list`, rather than returning a partial list. `requireScopes` (`src/runtime/scopes.ts`) wraps the handler each of the three `build()` methods pushes, reads `event.context.oauth`, and throws `McpJsonRpcError(-32003, …, { status: 403 })`; `settle()` relays that without turning it into an `isError` result. That `status` only reaches the wire on the modern revision — a legacy request gets the same JSON-RPC error inside a `200` stream, as it does for every error — so assert on the code, not the status, unless the test pins an era. It fails closed — scopes on an endpoint with no OAuth refuse every call. With OAuth, `createMcpHandler` turns that modern `403` into RFC 6750's `insufficient_scope` challenge (granted plus required scopes, `resource_metadata`) from the scopes `requireScopes` records per event, and adds `scope` from `scopesSupported` to h3-mcp's `401` challenge; an `authorize` denial stays a bare `403`. Filtering `tools/list` instead is not available: h3-mcp resolves the handler's options (where the `X-MCP-Tools` filter lives) **before** `checkAuth` populates `event.context.oauth`, and that resolution is synchronous, so no JWT check fits there. The `decorate` plugin hook does run after auth, but only from `handleModernPost`, so it would leave legacy requests ungated while `era` is `dual`. Hiding listings needs a post-auth hook covering both eras upstream in h3-mcp; do not grow a local workaround. Read scopes from `scope` (space-delimited, RFC 6749) and `scp` (string or array, Okta/Entra ID) only — `permissions` is Auth0-specific and was left out on purpose.
+**`scopes` gates invocation and application callbacks; static definition metadata stays listed.** Resource-template enumeration/completion and prompt completion check scopes before calling application code; unauthorized enumeration fails `resources/list`, rather than returning a partial list. `requireScopes` (`src/runtime/scopes.ts`) wraps the handler each of the three `[buildDefinition]()` methods pushes, reads `event.context.oauth`, and throws `McpJsonRpcError(-32003, …, { status: 403 })`; `settle()` relays that without turning it into an `isError` result. That `status` only reaches the wire on the modern revision — a legacy request gets the same JSON-RPC error inside a `200` stream, as it does for every error — so assert on the code, not the status, unless the test pins an era. It fails closed — scopes on an endpoint with no OAuth refuse every call. With OAuth, `createMcpHandler` turns that modern `403` into RFC 6750's `insufficient_scope` challenge (granted plus required scopes, `resource_metadata`) from the scopes `requireScopes` records per event, and adds `scope` from `scopesSupported` to h3-mcp's `401` challenge; an `authorize` denial stays a bare `403`. Filtering `tools/list` instead is not available: h3-mcp resolves the handler's options (where the `X-MCP-Tools` filter lives) **before** `checkAuth` populates `event.context.oauth`, and that resolution is synchronous, so no JWT check fits there. The `decorate` plugin hook does run after auth, but only from `handleModernPost`, so it would leave legacy requests ungated while `era` is `dual`. Hiding listings needs a post-auth hook covering both eras upstream in h3-mcp; do not grow a local workaround. Read scopes from `scope` (space-delimited, RFC 6749) and `scp` (string or array, Okta/Entra ID) only — `permissions` is Auth0-specific and was left out on purpose.
**Plugins reach a `mcp()` server through `/plugins.ts`, not through an option** — an `ExtensionPlugin` is a live function and `mcp()` options cross into generated code as JSON. `discoverPlugins` returns *every* match so the caller can refuse an ambiguous pair; `onePluginsFile` in `src/module/index.ts` does that where it can name the route, which also keeps the watcher's `served()` from dying on a misconfiguration. The handler virtual is `async` for the same reason the registry is: a file written after `setup` must be seen at rebuild. The file's default export goes through `defineMcpPlugins` (`src/runtime/plugins.ts`), an identity function that exists purely to typecheck it — generated code is its only importer and is not checked with the app. Keep its parameter `readonly ExtensionPlugin[]` and **not** a generic: a generic preserves each plugin's `TState` but loses excess-property checking during inference, so a misspelled hook slips through, and nothing reads state through the array anyway (`pluginState` types off the instance). Adding the convention means four places, not one — `discover.ts`, `template.ts` (`renderHandler`'s second argument), `watch.ts` (`couldChangeServed` plus `served`, or creating the file triggers no `rollup:reload`), and `report.ts`.
diff --git a/apps/docs/content/5.handlers/2.structure-and-options.md b/apps/docs/content/5.handlers/2.structure-and-options.md
index 54b6eb90..889a2631 100644
--- a/apps/docs/content/5.handlers/2.structure-and-options.md
+++ b/apps/docs/content/5.handlers/2.structure-and-options.md
@@ -16,7 +16,9 @@ All options passed through discovery become generated code, so they must be seri
Put live extension plugins in `/plugins.ts`, default-exported through `defineMcpPlugins`.
-
+::warning
+Extension plugins are experimental. `McpExtensionPlugin`, `defineMcpPlugins`, `/plugins.ts` and the `{ extensionPlugins }` argument expose the protocol engine's plugin contract, so they may change in any release, including after 1.0.
+::
Type an extension with `McpExtensionPlugin`; it is the engine's plugin contract, so an extension written against it depends on that engine. Plugins are functions, so a `plugins` array in `nuxt.config.ts` is not the discovery API. Ambiguous plugin files in a root are rejected.
diff --git a/apps/docs/content/8.examples/1.authentication.md b/apps/docs/content/8.examples/1.authentication.md
index 689ffbf6..28486e31 100644
--- a/apps/docs/content/8.examples/1.authentication.md
+++ b/apps/docs/content/8.examples/1.authentication.md
@@ -145,22 +145,10 @@ export default createMcpHandler({
import { defineEventHandler } from 'nuxt/server'
import { oauth } from '../../../utils/mcp-oauth'
-const headers = {
- 'access-control-allow-origin': '*',
- 'access-control-allow-methods': 'GET, OPTIONS',
- 'access-control-allow-headers': '*',
-}
-
-export default defineEventHandler((event) => {
- if (event.req.method === 'OPTIONS') return new Response(null, { status: 204, headers })
- if (event.req.method !== 'GET') {
- return new Response(null, { status: 405, headers: { ...headers, allow: 'GET, OPTIONS' } })
- }
- return Response.json(oauth.metadata, { headers })
-})
+export default defineEventHandler(event => oauth.metadataHandler(event))
```
-`createMcpHandler` accepts the prepared `oauth` instance and exposes it as `handler.oauth`. It also accepts `authorize(identity, event)` alongside `oauth`. `oauth.metadataPath` identifies this metadata URL. Use the public resource origin consistently; it is also carried in authentication challenges. The configured module mounts metadata through its native adapter automatically, while a manual route owns its host HTTP integration.
+`createMcpHandler` accepts the prepared `oauth` instance and exposes it as `handler.oauth`. It also accepts `authorize(identity, event)` alongside `oauth`. `oauth.metadataPath` identifies this metadata URL, and `oauth.metadataHandler` answers it, CORS preflight included. Use the public resource origin consistently; it is also carried in authentication challenges. The configured module mounts metadata through its native adapter automatically, while a manual route owns its host HTTP integration.
For opaque tokens, replace the `jwt` option with `verify(token, event)` backed by your provider's resource-aware verifier, keeping `resource` and `authorizationServers`. Populate verified `event.context.oauth` claims for identity/scopes. Do not accept a token merely because it exists or belongs to another API.
diff --git a/apps/docs/skills/manage-mcp/SKILL.md b/apps/docs/skills/manage-mcp/SKILL.md
index ac9d02ee..f98074f1 100644
--- a/apps/docs/skills/manage-mcp/SKILL.md
+++ b/apps/docs/skills/manage-mcp/SKILL.md
@@ -82,7 +82,7 @@ This mounts `/mcp` and `/mcp/admin`. Each server scans only its own roots. Paths
Use groups and tags for metadata, not authorization. Import generated endpoints from `nitro-mcp-toolkit/servers` and filter `handler.definitions` with ordinary arrays. A non-default export name follows the camel-cased route slug. See [servers](references/handlers.md).
-Put endpoint extension plugins in `/plugins.ts` with `defineMcpPlugins([...])`. An `auth` file default-exports `defineMcpAuth({ schemes: ['bearer'], validate })` options; callbacks can read private runtime configuration. Paths resolve from the project root, with Nuxt aliases supported. Keep automatic discovery for live verifiers; manual collections can still use an ordinary route exporting `createMcpHandler(...)`.
+Put endpoint extension plugins in `/plugins.ts` with `defineMcpPlugins([...])`. Plugins are experimental: they expose the engine's plugin contract and may change in any release. An `auth` file default-exports `defineMcpAuth({ schemes: ['bearer'], validate })` options; callbacks can read private runtime configuration. Paths resolve from the project root, with Nuxt aliases supported. Keep automatic discovery for live verifiers; manual collections can still use an ordinary route exporting `createMcpHandler(...)`.
## Authorization and request context
diff --git a/packages/nitro-mcp-toolkit/README.md b/packages/nitro-mcp-toolkit/README.md
index 07b6827b..e981719e 100644
--- a/packages/nitro-mcp-toolkit/README.md
+++ b/packages/nitro-mcp-toolkit/README.md
@@ -160,6 +160,9 @@ Declared `group`, non-empty `tags`, and non-empty `scopes` take precedence over
### Plugins
+> [!WARNING]
+> Extension plugins are experimental. They expose the protocol engine's plugin contract, so `McpExtensionPlugin`, `defineMcpPlugins`, `plugins.ts` and `{ extensionPlugins }` may change in any release, including after 1.0.
+
`server/mcp/plugins.ts`, beside the three directories, installs [h3-mcp](https://github.com/h3js/h3-mcp) extension plugins on that endpoint. Its default export is the array:
```ts
@@ -526,7 +529,7 @@ export default createMcpHandler({ name: 'my-server', version: '1.0.0', tools: [g
Handwritten definitions name themselves, since no filename is there to do it.
-The handler also exposes a web-standard `fetch`, so it mounts anywhere else too — `new H3().all('/mcp', handler)`, or straight onto any fetch-native runtime. Pass `{ extensionPlugins }` (`McpHandlerSetup`) as the second argument to install [h3-mcp](https://mcp.h3.dev) extensions such as tasks or MCP Apps.
+The handler also exposes a web-standard `fetch`, so it mounts anywhere else too — `new H3().all('/mcp', handler)`, or straight onto any fetch-native runtime. Pass `{ extensionPlugins }` (`McpHandlerSetup`) as the second argument to install [h3-mcp](https://mcp.h3.dev) extensions such as tasks or MCP Apps. Like `plugins.ts`, this is experimental.
Framework adapters can pass request context by reference with `handler.fetch(request, context)`:
diff --git a/packages/nitro-mcp-toolkit/src/runtime/auth.ts b/packages/nitro-mcp-toolkit/src/runtime/auth.ts
index 6f8eec28..3e54295a 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/auth.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/auth.ts
@@ -1,9 +1,29 @@
-import type { AuthCredentials, AuthOptions, AuthScheme } from 'h3-mcp'
+import type { H3Event } from 'h3/generic'
import type { McpOAuth } from './oauth.ts'
-export type McpAuthOptions = AuthOptions
-export type McpAuthCredentials = AuthCredentials
-export type McpAuthScheme = AuthScheme
+export type McpAuthScheme = 'bearer' | 'api-key'
+
+/** The credential a request presented, as `validate` receives it. */
+export interface McpAuthCredentials {
+ scheme: McpAuthScheme
+ token: string
+}
+
+/** Bearer token or API key authentication for an endpoint. */
+export interface McpAuthOptions {
+ /** @default true */
+ enabled?: boolean
+ /** @default ['bearer'] */
+ schemes?: McpAuthScheme[]
+ /** Static tokens accepted as-is. */
+ tokens?: string[]
+ /** Return `true` to accept the credential. Runs when no static token matched. */
+ validate?: (credentials: McpAuthCredentials, event: H3Event) => boolean | Promise
+ /** Header carrying an API key. */
+ header?: string
+ /** RFC 9728 metadata URL carried on the `401` challenge. */
+ resourceMetadataUrl?: string
+}
export function assertMcpOAuth(oauth: McpOAuth): void {
if (
diff --git a/packages/nitro-mcp-toolkit/src/runtime/context.ts b/packages/nitro-mcp-toolkit/src/runtime/context.ts
index b0ef9c9e..66dabfb9 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/context.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/context.ts
@@ -1,5 +1,5 @@
import type { H3Event } from 'h3/generic'
-import type { RequestContext } from 'h3-mcp'
+import type { ClientCapabilities, Implementation } from 'h3-mcp'
/**
* Push list-changed and resource-updated events to every client currently
@@ -12,26 +12,47 @@ export interface McpNotifier {
resourceUpdated: (uri: string) => void
}
+/** Minimum severity a client asked to receive, per RFC 5424. */
+export type McpLogLevel =
+ | 'debug'
+ | 'info'
+ | 'notice'
+ | 'warning'
+ | 'error'
+ | 'critical'
+ | 'alert'
+ | 'emergency'
+
/** What a definition handler can read about the MCP request it serves. */
-export type McpRequestContext = Pick<
- RequestContext,
- | 'sessionId'
- | 'requestId'
- | 'signal'
- | 'protocolVersion'
- | 'meta'
- | 'era'
- | 'clientCapabilities'
- | 'clientInfo'
- | 'logLevel'
- | 'trace'
- | 'inputResponses'
- | 'notify'
- | 'progress'
- | 'log'
- | 'requireClientCapability'
- | 'requireExtension'
-> & { notifier: McpNotifier }
+export interface McpRequestContext {
+ /** Legacy protocol session, when sessions are enabled. */
+ sessionId?: string
+ requestId?: string | number
+ /** Aborted when the client cancels the request or its stream closes. */
+ signal?: AbortSignal
+ protocolVersion?: string
+ /** The request's raw `params._meta`. Untrusted input. */
+ meta?: Record
+ era?: 'modern' | 'legacy'
+ clientCapabilities?: ClientCapabilities
+ clientInfo?: Implementation
+ logLevel?: McpLogLevel
+ /** W3C trace-context values propagated through `_meta`. */
+ trace?: { traceparent?: string; tracestate?: string; baggage?: string }
+ /** Multi round-trip responses the client sent back on a retry. */
+ inputResponses?: Record
+ /** Send a notification on this request's response stream, when it has one. */
+ notify?: (method: string, params?: Record) => void
+ /** Report progress. A no-op when the request carried no progress token. */
+ progress?: (progress: number, total?: number, message?: string) => void
+ /** Send `notifications/message`. A no-op unless the client asked for this level. */
+ log?: (level: McpLogLevel, data: unknown, logger?: string) => void
+ /** Throw `-32021` when the client did not declare these capabilities. */
+ requireClientCapability?: (...capabilities: string[]) => void
+ /** Throw `-32021` when the client did not negotiate these extensions. */
+ requireExtension?: (...extensionIds: string[]) => void
+ notifier: McpNotifier
+}
/**
* The event a tool, resource or prompt handler is called with: a plain
diff --git a/packages/nitro-mcp-toolkit/src/runtime/definition.ts b/packages/nitro-mcp-toolkit/src/runtime/definition.ts
index 35891d2c..e88189ed 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/definition.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/definition.ts
@@ -16,6 +16,23 @@ export interface McpDefinitionBuckets {
prompts: NonNullable
}
+/**
+ * Key of the function that adds a definition to what an endpoint serves. Not
+ * exported from the package, so a definition is data to everyone but
+ * `createMcpHandler`; spreading a definition keeps it.
+ *
+ * @internal
+ */
+export const buildDefinition: unique symbol = Symbol.for('nitro-mcp-toolkit.build')
+
+/** @internal */
+export type McpDefinitionBuild = (
+ identity: McpIdentity,
+ into: McpDefinitionBuckets,
+ notify: McpNotifier,
+ onToolCall?: McpToolCallListener,
+) => void
+
/**
* Where a definition was found, for definitions the module discovered on disk.
*/
@@ -57,18 +74,8 @@ export interface McpDefinition {
readonly _meta?: Record
/** Set for discovered definitions; absent for hand-written ones. */
readonly source?: McpDefinitionSource
- /**
- * Adds this definition to what the endpoint serves, under `identity` when the
- * definition does not name itself.
- *
- * @internal
- */
- readonly build: (
- identity: McpIdentity,
- into: McpDefinitionBuckets,
- notify: McpNotifier,
- onToolCall?: McpToolCallListener,
- ) => void
+ /** @internal */
+ readonly [buildDefinition]: McpDefinitionBuild
}
/**
diff --git a/packages/nitro-mcp-toolkit/src/runtime/handler.ts b/packages/nitro-mcp-toolkit/src/runtime/handler.ts
index c09198f2..b02b4f39 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/handler.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/handler.ts
@@ -3,17 +3,11 @@ import type { H3Event as McpRequestEvent, H3EventContext } from 'h3/generic'
import { defineMcpHandler } from 'h3-mcp'
import { assertMcpOAuth } from './auth.ts'
import { insufficientScope } from './scopes.ts'
-import { challengeScopes } from './oauth.ts'
+import { challengeScopes, oauthChallenge } from './oauth.ts'
import { parseMcpToolsHeader, unknownToolNames, unknownToolsResponse } from './tools-header.ts'
import { resolveDefinitions, summarize } from './validate.ts'
-import type {
- HandlerOptions as EngineOptions,
- LimitsOptions,
- OriginOptions,
- PluginOptions,
- SessionOptions,
- Subscription,
-} from 'h3-mcp'
+import { buildDefinition } from './definition.ts'
+import type { HandlerOptions as EngineOptions, PluginOptions, Subscription } from 'h3-mcp'
import type { McpAuthOptions } from './auth.ts'
import type { McpOAuth, McpOAuthClaims } from './oauth.ts'
import type { McpNotifier } from './context.ts'
@@ -28,10 +22,36 @@ import type {
/** Which protocol eras an endpoint serves: `dual` answers both 2026-07-28 and the 2025 revisions. */
export type McpEra = 'dual' | 'modern' | 'legacy'
-export type McpOriginOptions = OriginOptions
-export type McpSessionOptions = SessionOptions
-export type McpLimitsOptions = LimitsOptions
-/** Engine setup that is not data, such as extension plugins. */
+
+/** Which browser origins may reach an endpoint. */
+export interface McpOriginOptions {
+ /** Origins accepted beside the default. */
+ allow?: string[]
+ /** Accept requests without an `Origin` header. */
+ allowMissing?: boolean
+ /** Replaces the default loopback check. */
+ validate?: (origin: string, event: McpRequestEvent) => boolean | Promise
+}
+
+/** Legacy protocol sessions. */
+export interface McpSessionOptions {
+ enabled?: boolean
+ generateId?: (event: McpRequestEvent) => string | Promise
+ maxSessions?: number
+}
+
+/** Request body, batch, and content-type limits. `false` lifts one. */
+export interface McpLimitsOptions {
+ maxBodySize?: number | false
+ contentType?: false | string | string[]
+ maxBatchSize?: number | false
+}
+
+/**
+ * Engine setup that is not data, such as extension plugins.
+ *
+ * @experimental Follows the protocol engine's plugin contract and may change in any release.
+ */
export type McpHandlerSetup = PluginOptions
export interface McpHandlerOptions extends Pick<
@@ -97,15 +117,16 @@ export interface McpHandlerOptions extends Pick<
* failure inside a `200` stream, which carries no challenge.
*/
function withOAuthChallenge(response: Response, event: H3Event, oauth: McpOAuth): Response {
- const metadata = `resource_metadata="${oauth.resourceMetadataUrl}"`
+ const { resourceMetadataUrl, scope: challengeScope } = oauth[oauthChallenge]
+ const metadata = `resource_metadata="${resourceMetadataUrl}"`
let challenge: string | undefined
- if (response.status === 401 && oauth.challengeScope) {
+ if (response.status === 401 && challengeScope) {
const current = response.headers.get('www-authenticate')
if (current?.includes('Bearer ') && !current.includes('scope=')) {
challenge = current.replace(
/(Bearer realm="mcp"(?:, resource_metadata="[^"]*")?)/,
- `$1, scope="${oauth.challengeScope}"`,
+ `$1, scope="${challengeScope}"`,
)
}
} else if (response.status === 403) {
@@ -278,7 +299,7 @@ export function createMcpHandler(
}
for (const { definition, identity } of registrations) {
- definition.build(identity, buckets, notify, onToolCall)
+ definition[buildDefinition](identity, buckets, notify, onToolCall)
}
const toolNames = new Set(tools.map((tool) => tool.name!))
diff --git a/packages/nitro-mcp-toolkit/src/runtime/index.ts b/packages/nitro-mcp-toolkit/src/runtime/index.ts
index aece89f4..cd056c63 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/index.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/index.ts
@@ -27,7 +27,7 @@ export {
} from './input.ts'
export { mcpElicit, mcpElicitUrl, McpJsonRpcError } from 'h3-mcp'
-export type { McpEvent, McpNotifier, McpRequestContext } from './context.ts'
+export type { McpEvent, McpLogLevel, McpNotifier, McpRequestContext } from './context.ts'
export type {
McpEra,
McpHandler,
@@ -42,6 +42,7 @@ export type {
McpOAuth,
McpOAuthClaims,
McpOAuthJwtOptions,
+ McpMetadataEvent,
McpOAuthOptions,
McpOAuthServiceToken,
McpOAuthSetup,
diff --git a/packages/nitro-mcp-toolkit/src/runtime/oauth.ts b/packages/nitro-mcp-toolkit/src/runtime/oauth.ts
index 2a9630a5..0a2a2ca2 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/oauth.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/oauth.ts
@@ -132,26 +132,41 @@ export type McpOAuthSetup = Omit & {
jwt: Omit & { audience?: string | string[] }
}
+/** What the metadata handlers read from a request event. */
+export interface McpMetadataEvent {
+ req: { method: string }
+}
+
+/**
+ * Key of what the handler needs to build OAuth challenges. Kept off the public
+ * shape so a request-derived `resource` can be added without changing it.
+ *
+ * @internal
+ */
+export const oauthChallenge: unique symbol = Symbol.for('nitro-mcp-toolkit.oauth-challenge')
+
+/** @internal */
+export interface McpOAuthChallenge {
+ /** Absolute URL carried on every `401` `WWW-Authenticate`. */
+ resourceMetadataUrl: string
+ /** Scopes named in the `401` challenge (`scopesSupported`), when any are advertised. */
+ scope?: string
+}
+
export interface McpOAuth {
- resource: string
/** Path to mount `metadataHandler` on, derived from `resource` per RFC 9728. */
metadataPath: string
- /** Absolute URL carried on every `401` `WWW-Authenticate`. */
- resourceMetadataUrl: string
- metadata: McpProtectedResourceMetadata
- /**
- * Scopes named in the `401` challenge (`scopesSupported`), which MCP
- * clients request first. Absent when no scopes are advertised.
- */
- challengeScope?: string
/** Pass as `auth` to `createMcpHandler`. */
auth: McpAuthOptions
- metadataHandler: (event: H3Event) => Response
+ /** Serves the RFC 9728 protected resource metadata, with CORS. Nitro 2 events work too. */
+ metadataHandler: (event: McpMetadataEvent) => Response
/**
* RFC 8414 document for this issuer, with CORS. Only set when
* `authorizationServer` was given.
*/
- authorizationServerHandler?: (event: H3Event) => Promise
+ authorizationServerHandler?: (event: McpMetadataEvent) => Promise
+ /** @internal */
+ readonly [oauthChallenge]: McpOAuthChallenge
}
function corsResponse(body: unknown, status = 200): Response {
@@ -239,7 +254,7 @@ function normalizeIssuer(value: string, label: string): string {
}
function metadataHandlerFor(metadata: McpProtectedResourceMetadata) {
- return (event: H3Event): Response => {
+ return (event: McpMetadataEvent): Response => {
if (event.req.method === 'OPTIONS') return corsResponse(null, 204)
return corsResponse(metadata)
}
@@ -248,7 +263,7 @@ function metadataHandlerFor(metadata: McpProtectedResourceMetadata) {
function authorizationServerHandlerFor(issuer: string) {
const url = authorizationServerMetadataUrl(issuer).href
- return async (event: H3Event): Promise => {
+ return async (event: McpMetadataEvent): Promise => {
if (event.req.method === 'OPTIONS') return corsResponse(null, 204)
const response = await fetch(url)
@@ -329,19 +344,16 @@ export function createMcpOAuth(options: McpOAuthOptions): McpOAuth {
},
}
+ const scope = challengeScopes(options.scopesSupported)
+
return {
- resource,
metadataPath: metadataUrl.pathname,
- resourceMetadataUrl: metadataUrl.href,
- metadata,
- ...(challengeScopes(options.scopesSupported)
- ? { challengeScope: challengeScopes(options.scopesSupported) }
- : {}),
auth,
metadataHandler: metadataHandlerFor(metadata),
...(authorizationServer
? { authorizationServerHandler: authorizationServerHandlerFor(authorizationServer) }
: {}),
+ [oauthChallenge]: { resourceMetadataUrl: metadataUrl.href, ...(scope ? { scope } : {}) },
}
}
diff --git a/packages/nitro-mcp-toolkit/src/runtime/plugins.ts b/packages/nitro-mcp-toolkit/src/runtime/plugins.ts
index b04a7dcb..0fa22507 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/plugins.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/plugins.ts
@@ -1,12 +1,18 @@
import type { ExtensionPlugin } from 'h3-mcp'
-/** An engine extension, such as `mcpTasks()` from `h3-mcp/tasks`. */
+/**
+ * An engine extension, such as `mcpTasks()` from `h3-mcp/tasks`.
+ *
+ * @experimental This is the protocol engine's plugin contract and may change in any release.
+ */
export type McpExtensionPlugin = ExtensionPlugin
/**
* Define the extension plugins an endpoint installs, as the default export of
* `/plugins.ts`.
*
+ * @experimental Plugins follow the protocol engine's contract and may change in any release.
+ *
* Only the generated handler imports that file, and generated code is not
* typechecked with the app, so this call is what checks it.
*
diff --git a/packages/nitro-mcp-toolkit/src/runtime/prompt.ts b/packages/nitro-mcp-toolkit/src/runtime/prompt.ts
index 6b04290d..c438805c 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/prompt.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/prompt.ts
@@ -1,4 +1,5 @@
import { attachNotify } from './context.ts'
+import { buildDefinition } from './definition.ts'
import { resolveSchema } from './schema.ts'
import { requireScopes } from './scopes.ts'
import { resolveMeta } from './validate.ts'
@@ -95,7 +96,7 @@ export function defineMcpPrompt(
tags,
scopes,
_meta,
- build(identity, into, notify) {
+ [buildDefinition](identity, into, notify) {
const advertised = {
name: identity.name,
title: identity.title,
diff --git a/packages/nitro-mcp-toolkit/src/runtime/resource.ts b/packages/nitro-mcp-toolkit/src/runtime/resource.ts
index 2c22a08f..5690b4d7 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/resource.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/resource.ts
@@ -1,5 +1,6 @@
import { defineResourceTemplate } from 'h3-mcp'
import { attachNotify } from './context.ts'
+import { buildDefinition } from './definition.ts'
import { requireScopes } from './scopes.ts'
import { resolveMeta } from './validate.ts'
import type { H3Event } from 'h3'
@@ -107,7 +108,7 @@ export function defineMcpResource(
scopes,
_meta,
uri: isStaticUri ? definition.uri : definition.uriTemplate,
- build(identity, into, notify) {
+ [buildDefinition](identity, into, notify) {
const advertised = {
name: identity.name,
title: identity.title,
diff --git a/packages/nitro-mcp-toolkit/src/runtime/tool.ts b/packages/nitro-mcp-toolkit/src/runtime/tool.ts
index 875f61f4..3f0f0bba 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/tool.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/tool.ts
@@ -1,5 +1,6 @@
import { McpJsonRpcError } from 'h3-mcp'
import { attachNotify } from './context.ts'
+import { buildDefinition } from './definition.ts'
import { isInputRequired, toCallToolResult, toErrorResult } from './results.ts'
import { resolveSchema } from './schema.ts'
import { requireScopes } from './scopes.ts'
@@ -174,7 +175,7 @@ export function defineMcpTool(
tags,
scopes,
_meta,
- build(identity, into, notify, onToolCall) {
+ [buildDefinition](identity, into, notify, onToolCall) {
const advertised = {
name: identity.name,
title: identity.title,
diff --git a/packages/nitro-mcp-toolkit/test/fixtures/consumer/oauth-better-auth.ts b/packages/nitro-mcp-toolkit/test/fixtures/consumer/oauth-better-auth.ts
index 9d709d6d..934c3739 100644
--- a/packages/nitro-mcp-toolkit/test/fixtures/consumer/oauth-better-auth.ts
+++ b/packages/nitro-mcp-toolkit/test/fixtures/consumer/oauth-better-auth.ts
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict'
import { once } from 'node:events'
import { createServer } from 'node:http'
+import { H3Event } from 'h3'
import { exportJWK, generateKeyPair, SignJWT } from 'jose'
import { createMcpHandler, defineMcpServer, defineMcpTool } from 'nitro-mcp-toolkit'
import { betterAuth } from 'nitro-mcp-toolkit/oauth/better-auth'
@@ -56,7 +57,8 @@ try {
}),
],
})
- assert.deepEqual(handler.oauth?.metadata, {
+ assert(handler.oauth)
+ assert.deepEqual(await handler.oauth.metadataHandler(new H3Event(new Request(resource))).json(), {
resource,
authorization_servers: [issuer],
bearer_methods_supported: ['header'],
diff --git a/packages/nitro-mcp-toolkit/test/oauth-better-auth.test.ts b/packages/nitro-mcp-toolkit/test/oauth-better-auth.test.ts
index 01d4e699..22eef0d0 100644
--- a/packages/nitro-mcp-toolkit/test/oauth-better-auth.test.ts
+++ b/packages/nitro-mcp-toolkit/test/oauth-better-auth.test.ts
@@ -59,7 +59,7 @@ describe('betterAuth', () => {
return new H3Event(new Request(RESOURCE))
}
- it('returns prepared resource-server options with explicit provider URLs and advertised scopes', () => {
+ it('returns prepared resource-server options with explicit provider URLs and advertised scopes', async () => {
const options = betterAuth({
resource: RESOURCE,
issuer: ISSUER,
@@ -75,7 +75,9 @@ describe('betterAuth', () => {
verify: expect.any(Function),
})
expect(options.jwt).toBeUndefined()
- expect(options.metadata.scopes_supported).toEqual(['mcp:read'])
+ expect(await options.metadataHandler(new H3Event(new Request(RESOURCE))).json()).toMatchObject({
+ scopes_supported: ['mcp:read'],
+ })
expect(options.auth.schemes).toEqual(['bearer'])
expect(options.authorizationServerHandler).toBeTypeOf('function')
})
@@ -95,12 +97,14 @@ describe('betterAuth', () => {
it('verifies the resource audience advertised for a URL with a trailing slash', async () => {
const options = betterAuth({ resource: `${RESOURCE}/`, issuer: ISSUER, jwks })
- expect(options.metadata.resource).toBe(RESOURCE)
+ expect(await options.metadataHandler(new H3Event(new Request(RESOURCE))).json()).toMatchObject({
+ resource: RESOURCE,
+ })
const request = event()
expect(await options.auth.validate?.({ scheme: 'bearer', token: await sign() }, request)).toBe(
true,
)
- expect(request.context.oauth?.aud).toBe(options.metadata.resource)
+ expect(request.context.oauth?.aud).toBe(RESOURCE)
})
it('verifies a signed access token with the official verifier and publishes its claims', async () => {
diff --git a/packages/nitro-mcp-toolkit/test/oauth-clerk-runtime.test.ts b/packages/nitro-mcp-toolkit/test/oauth-clerk-runtime.test.ts
index 30760bc8..dd8161b4 100644
--- a/packages/nitro-mcp-toolkit/test/oauth-clerk-runtime.test.ts
+++ b/packages/nitro-mcp-toolkit/test/oauth-clerk-runtime.test.ts
@@ -64,10 +64,12 @@ describe('Clerk runtime OAuth', () => {
it('passes the advertised audience to the SDK for a resource with a trailing slash', async () => {
const { client, event } = fixture()
const options = clerk({ resource: `${RESOURCE}/`, publishableKey: KEY, client })
- expect(options.metadata.resource).toBe(RESOURCE)
+ expect(await options.metadataHandler(new H3Event(new Request(RESOURCE))).json()).toMatchObject({
+ resource: RESOURCE,
+ })
expect(await options.auth.validate?.({ scheme: 'bearer', token: OPAQUE }, event)).toBe(true)
- expect(client.authenticateRequest.mock.calls[0]?.[1].audience).toBe(options.metadata.resource)
- expect(event.context.oauth?.aud).toBe(options.metadata.resource)
+ expect(client.authenticateRequest.mock.calls[0]?.[1].audience).toBe(RESOURCE)
+ expect(event.context.oauth?.aud).toBe(RESOURCE)
})
it.each([OPAQUE, jwt()])(
diff --git a/packages/nitro-mcp-toolkit/test/oauth-connectors.test.ts b/packages/nitro-mcp-toolkit/test/oauth-connectors.test.ts
index 5c24e12f..c507a63f 100644
--- a/packages/nitro-mcp-toolkit/test/oauth-connectors.test.ts
+++ b/packages/nitro-mcp-toolkit/test/oauth-connectors.test.ts
@@ -1,3 +1,4 @@
+import { H3Event } from 'h3'
import { describe, expect, it } from 'vitest'
import { createMcpOAuth } from '../src/runtime/index.ts'
import { clerk } from '../src/runtime/oauth/clerk.ts'
@@ -50,10 +51,11 @@ describe('clerk', () => {
)
})
- it('is accepted by createMcpOAuth', () => {
+ it('is accepted by createMcpOAuth', async () => {
const oauth = createMcpOAuth(clerk({ resource: RESOURCE, publishableKey: clerkKey() }))
-
- expect(oauth.metadata.authorization_servers).toEqual(['https://acme.clerk.accounts.dev'])
+ expect(await oauth.metadataHandler(new H3Event(new Request(RESOURCE))).json()).toMatchObject({
+ authorization_servers: ['https://acme.clerk.accounts.dev'],
+ })
expect(oauth.authorizationServerHandler).toBeTypeOf('function')
})
})
diff --git a/packages/nitro-mcp-toolkit/test/oauth-runtime.test.ts b/packages/nitro-mcp-toolkit/test/oauth-runtime.test.ts
index 55d87b7d..560a039f 100644
--- a/packages/nitro-mcp-toolkit/test/oauth-runtime.test.ts
+++ b/packages/nitro-mcp-toolkit/test/oauth-runtime.test.ts
@@ -1,3 +1,4 @@
+import { H3Event } from 'h3'
import { describe, expect, it } from 'vitest'
import {
MODERN_PROTOCOL_VERSION,
@@ -39,7 +40,7 @@ describe('runtime OAuth server configuration', () => {
const config = defineMcpServer({ oauth: createMcpOAuth(provider) })
expect(defineMcpServer(config).oauth).toBe(config.oauth)
const handler = createMcpHandler(config)
- expect(handler.oauth?.metadata).toMatchObject({
+ expect(await handler.oauth?.metadataHandler(new H3Event(request())).json()).toMatchObject({
resource,
authorization_servers: provider.authorizationServers,
})
diff --git a/packages/nitro-mcp-toolkit/test/oauth.test.ts b/packages/nitro-mcp-toolkit/test/oauth.test.ts
index 642c513b..9b316360 100644
--- a/packages/nitro-mcp-toolkit/test/oauth.test.ts
+++ b/packages/nitro-mcp-toolkit/test/oauth.test.ts
@@ -111,11 +111,10 @@ describe('createMcpOAuth', () => {
})
expect(oauth.metadataPath).toBe('/.well-known/oauth-protected-resource/mcp')
- expect(oauth.resourceMetadataUrl).toBe(
+ expect(oauth.auth.schemes).toEqual(['bearer'])
+ expect(oauth.auth.resourceMetadataUrl).toBe(
'https://api.example.com/.well-known/oauth-protected-resource/mcp',
)
- expect(oauth.auth.schemes).toEqual(['bearer'])
- expect(oauth.auth.resourceMetadataUrl).toBe(oauth.resourceMetadataUrl)
})
it('answers RFC 9728 metadata with CORS, including OPTIONS', async () => {
@@ -157,7 +156,7 @@ describe('createMcpOAuth', () => {
const unauthenticated = await handler.fetch(ping())
expect(unauthenticated.status).toBe(401)
expect(unauthenticated.headers.get('www-authenticate')).toBe(
- `Bearer realm="mcp", resource_metadata="${oauth.resourceMetadataUrl}"`,
+ 'Bearer realm="mcp", resource_metadata="http://localhost:3030/.well-known/oauth-protected-resource/mcp"',
)
const denied = await handler.fetch(ping('http://localhost:3030/mcp', 'nope'))
diff --git a/packages/nitro-mcp-toolkit/test/types.test.ts b/packages/nitro-mcp-toolkit/test/types.test.ts
index 8251bfad..29af79a9 100644
--- a/packages/nitro-mcp-toolkit/test/types.test.ts
+++ b/packages/nitro-mcp-toolkit/test/types.test.ts
@@ -19,6 +19,7 @@ import type {
McpEvent,
McpHandler,
McpHandlerOptions,
+ McpOAuth,
McpPrompt,
McpResource,
McpTool,
@@ -183,6 +184,21 @@ it('lists the handler options the toolkit owns', () => {
>()
})
+// A definition is data: how the engine registers it is not reachable by name.
+it('keeps engine registration off the definition shape', () => {
+ expectTypeOf>().toEqualTypeOf<
+ 'kind' | 'name' | 'title' | 'description' | 'group' | 'tags' | 'scopes' | '_meta' | 'source'
+ >()
+})
+
+// `resource` may later come from the request, so nothing derived from it as an
+// absolute URL is public.
+it('exposes only request-independent OAuth fields', () => {
+ expectTypeOf>().toEqualTypeOf<
+ 'metadataPath' | 'auth' | 'metadataHandler' | 'authorizationServerHandler'
+ >()
+})
+
describe('scope typing', () => {
it('takes scopes on every kind of definition', () => {
expectTypeOf(
diff --git a/packages/nitro-mcp-toolkit/tsconfig.json b/packages/nitro-mcp-toolkit/tsconfig.json
index 3148696e..16517932 100644
--- a/packages/nitro-mcp-toolkit/tsconfig.json
+++ b/packages/nitro-mcp-toolkit/tsconfig.json
@@ -19,7 +19,9 @@
// `typecheck` independent of whether `dist` has been built.
"paths": {
"nitro-mcp-toolkit": ["./src/runtime/index.ts"],
- "nitro-mcp-toolkit/servers": ["./src/runtime/servers.ts"]
+ "nitro-mcp-toolkit/servers": ["./src/runtime/servers.ts"],
+ "nitro-mcp-toolkit/oauth/*": ["./src/runtime/oauth/*.ts"],
+ "nitro-mcp-toolkit/testing": ["./src/testing/index.ts"]
}
},
"include": ["src/**/*.ts", "test/**/*.ts", "benchmarks/**/*.ts"],