Skip to content
Open
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
8 changes: 8 additions & 0 deletions .changeset/toolkit-owned-types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"nitro-mcp-toolkit": major
"@nuxtjs/mcp-toolkit": major
---

The public API no longer re-exports engine types under h3-mcp's names. Import the toolkit's names instead: `McpAuthOptions`, `McpAuthCredentials`, `McpAuthScheme`, `McpCacheHints`, `McpEra`, `McpExtensionPlugin`, `McpOriginOptions` and `McpHandlerSetup` replace `AuthOptions`, `AuthCredentials`, `AuthScheme`, `CacheHints`, `Era`, `ExtensionPlugin`, `OriginOptions` and `PluginOptions`. `McpRequestContext` types `event.context.mcp`, and `McpSessionOptions` and `McpLimitsOptions` type the `session` and `limits` options. MCP spec types such as `CallToolResult` and `Icon` are unchanged.

`McpHandlerOptions` now lists its options explicitly instead of accepting every h3-mcp handler option. The engine callbacks `onListen`, `onStream`, `onCancelled`, `onProgress`, `onLogLevelSet`, `onSubscribe` and `onUnsubscribe`, and the `cache`, `extensions`, `subscriptions` and `echoServerInfo` options, are no longer accepted. Use `handler.notify` to push list-changed and resource-updated events.
6 changes: 4 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,9 @@ Windows is covered by a dedicated `test-windows` CI job that runs this package's

**h3-mcp owns origin allow-listing; the toolkit supplies the loopback default** via `origin.validate`. The default accepts a page the app serves to itself on a loopback host and refuses every other origin; requests with no `Origin` — every MCP client proper — are unaffected. The loopback condition is not decoration: `event.url` reads the `Host` header, so a bare same-origin comparison is satisfied by DNS rebinding, where the attacker's own hostname lands in both `Host` and `Origin`. Do not drop it to "simplify" the check. `allow` adds explicit origins on top of the default; a user's own `allow` list does not cost the loopback case.

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 }`. `nitro` and `nitropack` are optional peers used by their module entrypoints; H3 v2 is an internal dependency.
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.

**`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.

Expand All @@ -211,7 +213,7 @@ The runtime is written against a pinned `h3-mcp` (currently 0.2.0). That release

**Endpoint runtime configuration** lives in an optional `<dir>/index.ts` default-exporting `defineMcpServer({ ... })`. Keep metadata, instructions and authentication callbacks there; keep routing, directory discovery and OAuth metadata mounting in module options. The first root containing an index wins, and its settings override module defaults. Combining index authentication with module authentication or OAuth is an error. Creating or deleting an index triggers a development rebuild.

**Runtime endpoint authentication** uses an explicit `auth: './server/mcp-admin/auth.ts'` module reference. The file default-exports `defineMcpAuth()` with the engine's `AuthOptions`; callbacks read runtime secrets and receive the current MCP event. Nuxt resolves aliases and project-relative paths before delegation; bare Nitro resolves relative paths from its root. Keep file discovery and let the engine authenticate both eras. Never serialize a callback or read private tokens in build-time configuration. A missing or invalid auth export must fail closed.
**Runtime endpoint authentication** uses an explicit `auth: './server/mcp-admin/auth.ts'` module reference. The file default-exports `defineMcpAuth()` with `McpAuthOptions`; callbacks read runtime secrets and receive the current MCP event. Nuxt resolves aliases and project-relative paths before delegation; bare Nitro resolves relative paths from its root. Keep file discovery and let the engine authenticate both eras. Never serialize a callback or read private tokens in build-time configuration. A missing or invalid auth export must fail closed.

**OAuth** is a generic resource-server: `mcp({ oauth: { resource, authorizationServers, jwt } })` or `createMcpOAuth`. JWT verify, claims on `event.context.oauth`, RFC 9728 metadata mounted. Connectors (`nitro-mcp-toolkit/oauth/clerk`, `/okta`, `/workos`) return that same options object — Clerk infers issuer/JWKS from `CLERK_PUBLISHABLE_KEY` and requires `aud` equal to the MCP resource. WorkOS uses `WORKOS_AUTHKIT_ISSUER` and Connect resource-bound tokens, not AuthKit session tokens. JWTs require `exp`; disabling audience checks requires a custom resource verifier. The package does not mint tokens. Opaque tokens still mean `createMcpOAuth({ verify })` in a route file.

Expand Down
2 changes: 1 addition & 1 deletion apps/docs/content/5.handlers/2.structure-and-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Put live extension plugins in `<dir>/plugins.ts`, default-exported through `defi



Use the installed engine's `ExtensionPlugin` contract when implementing an extension. Plugins are functions, so a `plugins` array in `nuxt.config.ts` is not the discovery API. Ambiguous plugin files in a root are rejected.
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.

## Compose a handler directly

Expand Down
6 changes: 3 additions & 3 deletions packages/nitro-mcp-toolkit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ mcp({
})
```

These cross into generated code, so they are data only. For runtime authentication, set `auth` to a file path as shown below. Other callbacks such as `onListen` still require [wiring it by hand](#wiring-it-by-hand).
These cross into generated code, so they are data only. For runtime authentication, set `auth` to a file path as shown below.

### Browser clients

Expand Down Expand Up @@ -526,7 +526,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 }` 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.

Framework adapters can pass request context by reference with `handler.fetch(request, context)`:

Expand Down Expand Up @@ -562,7 +562,7 @@ export default defineMcpAuth({
})
```

`verifyAccessToken` is your application service and must return a boolean. The options use the engine's `AuthOptions` contract; each request still authenticates, including legacy clients. Credentials read by the runtime module stay out of generated module configuration. A missing file fails setup; an invalid default export refuses requests. Nuxt uses the same reference in `mcp.servers.admin.auth`, with Nuxt aliases supported.
`verifyAccessToken` is your application service and must return a boolean. The options are typed as `McpAuthOptions`; each request still authenticates, including legacy clients. Credentials read by the runtime module stay out of generated module configuration. A missing file fails setup; an invalid default export refuses requests. Nuxt uses the same reference in `mcp.servers.admin.auth`, with Nuxt aliases supported.

Off by default — many MCP endpoints sit behind a gateway that already authenticates. Turn it on and every request to the route, `POST`, `GET` and `DELETE` alike, must present a credential:

Expand Down
7 changes: 4 additions & 3 deletions packages/nitro-mcp-toolkit/src/module/options.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Era, HandlerOptions, Icon } from 'h3-mcp'
import type { Icon } from 'h3-mcp'
import type { DefinitionDir } from './discover.ts'
import type { McpEra, McpLimitsOptions } from '../runtime/handler.ts'
import type { McpOAuthSetup } from '../runtime/oauth.ts'

/**
Expand All @@ -26,13 +27,13 @@ export interface McpServerOptions {
*
* @default 'dual'
*/
era?: Era
era?: McpEra
/** Enable the engine's legacy protocol sessions. */
session?: boolean | { enabled?: boolean; maxSessions?: number }
/** Advertise client logging support. */
logging?: boolean
/** Request body, batch, and header limits, enforced by the engine. */
limits?: HandlerOptions['limits']
limits?: false | McpLimitsOptions
/**
* Browser origins allowed beyond the app's own loopback pages, which pass by
* default. Requests carrying no `Origin` — every MCP client proper — are
Expand Down
8 changes: 6 additions & 2 deletions packages/nitro-mcp-toolkit/src/runtime/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import type { AuthOptions } from 'h3-mcp'
import type { AuthCredentials, AuthOptions, AuthScheme } from 'h3-mcp'
import type { McpOAuth } from './oauth.ts'

export type McpAuthOptions = AuthOptions
export type McpAuthCredentials = AuthCredentials
export type McpAuthScheme = AuthScheme

export function assertMcpOAuth(oauth: McpOAuth): void {
if (
!oauth ||
Expand All @@ -14,7 +18,7 @@ export function assertMcpOAuth(oauth: McpOAuth): void {
}

/** Type runtime auth modules and refuse an invalid export before serving requests. */
export function defineMcpAuth(auth: AuthOptions): AuthOptions {
export function defineMcpAuth(auth: McpAuthOptions): McpAuthOptions {
if (!auth || typeof auth !== 'object') {
throw new TypeError('MCP auth modules must default-export authentication options.')
}
Expand Down
23 changes: 22 additions & 1 deletion packages/nitro-mcp-toolkit/src/runtime/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,35 @@ export interface McpNotifier {
resourceUpdated: (uri: string) => void
}

/** 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 }

/**
* The event a tool, resource or prompt handler is called with: a plain
* `H3Event` whose `context.mcp` is guaranteed present, rather than the
* optional field every other event on the app carries.
*/
export type McpEvent = H3Event & {
context: H3Event['context'] & {
mcp: RequestContext & { notifier: McpNotifier }
mcp: McpRequestContext
oauth?: import('./oauth.ts').McpOAuthClaims
}
}
Expand Down
51 changes: 32 additions & 19 deletions packages/nitro-mcp-toolkit/src/runtime/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@ import { defineMcpHandler } from 'h3-mcp'
import { assertMcpOAuth } from './auth.ts'
import { parseMcpToolsHeader, unknownToolNames, unknownToolsResponse } from './tools-header.ts'
import { resolveDefinitions, summarize } from './validate.ts'
import type { HandlerOptions as EngineOptions, PluginOptions, Subscription } from 'h3-mcp'
import type {
HandlerOptions as EngineOptions,
LimitsOptions,
OriginOptions,
PluginOptions,
SessionOptions,
Subscription,
} from 'h3-mcp'
import type { McpAuthOptions } from './auth.ts'
import type { McpOAuth, McpOAuthClaims } from './oauth.ts'
import type { McpNotifier } from './context.ts'
import type { McpToolCallListener } from './tool.ts'
Expand All @@ -16,17 +24,26 @@ import type {
McpTool,
} from './definition.ts'

/**
* Everything the engine takes that is not a definition: eras, caching, auth,
* origin checks, request limits, subscriptions. Passed straight through, so the
* toolkit never has to keep up with it.
*/
type EngineWiring = Omit<
EngineOptions,
'name' | 'version' | 'tools' | 'resources' | 'resourceTemplates' | 'prompts'
>
/** 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. */
export type McpHandlerSetup = PluginOptions

export interface McpHandlerOptions extends EngineWiring {
export interface McpHandlerOptions extends Pick<
EngineOptions,
'title' | 'description' | 'icons' | 'websiteUrl' | 'instructions' | 'logging'
> {
/** @default 'dual' */
era?: McpEra
/** Legacy protocol sessions. */
session?: boolean | McpSessionOptions
/** Request body, batch, and header limits. */
limits?: false | McpLimitsOptions
/** Bearer token or API key authentication. */
auth?: false | McpAuthOptions
/** Prepared OAuth resource server, also used to serve discovery metadata. */
oauth?: McpOAuth
/** Runs after authentication for each request. A denied user receives HTTP 403. */
Expand All @@ -53,7 +70,7 @@ export interface McpHandlerOptions extends EngineWiring {
* createMcpHandler({ origin: { allow: ['https://app.example.com'] } })
* ```
*/
origin?: EngineWiring['origin']
origin?: false | McpOriginOptions
/**
* Called once per tool call that settles into a result, with its duration.
* An error it throws reaches the client.
Expand Down Expand Up @@ -93,7 +110,7 @@ function resolveOrigin(origin: McpHandlerOptions['origin']): EngineOptions['orig

function createNotifier(): {
notify: McpNotifier
onListen: NonNullable<EngineWiring['onListen']>
onListen: NonNullable<EngineOptions['onListen']>
} {
const listeners = new Set<Subscription>()

Expand Down Expand Up @@ -166,7 +183,7 @@ export interface McpHandler {
*/
export function createMcpHandler(
options: McpHandlerOptions = {},
setup?: PluginOptions,
setup?: McpHandlerSetup,
): McpHandler {
const {
name = 'nitro-mcp-server',
Expand All @@ -178,7 +195,6 @@ export function createMcpHandler(
auth: configuredAuth,
oauth,
authorize,
onListen: userOnListen,
onToolCall,
...wiring
} = options
Expand Down Expand Up @@ -277,10 +293,7 @@ export function createMcpHandler(
resources: buckets.resources,
resourceTemplates: buckets.resourceTemplates,
prompts: buckets.prompts,
onListen(subscription, listenEvent) {
onListen(subscription, listenEvent)
return userOnListen?.(subscription, listenEvent)
},
onListen,
}
}, setup)

Expand Down
23 changes: 13 additions & 10 deletions packages/nitro-mcp-toolkit/src/runtime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export { createMcpHandler } from './handler.ts'
export { defineMcpServer } from './server.ts'
export type { McpServerConfig } from './server.ts'
export { defineMcpAuth } from './auth.ts'
export type { McpAuthCredentials, McpAuthOptions, McpAuthScheme } from './auth.ts'
export {
createMcpOAuth,
authorizationServerMetadataUrl,
Expand All @@ -26,8 +27,17 @@ export {
} from './input.ts'
export { mcpElicit, mcpElicitUrl, McpJsonRpcError } from 'h3-mcp'

export type { McpEvent, McpNotifier } from './context.ts'
export type { McpHandler, McpHandlerOptions } from './handler.ts'
export type { McpEvent, McpNotifier, McpRequestContext } from './context.ts'
export type {
McpEra,
McpHandler,
McpHandlerOptions,
McpHandlerSetup,
McpLimitsOptions,
McpOriginOptions,
McpSessionOptions,
} from './handler.ts'
export type { McpExtensionPlugin } from './plugins.ts'
export type {
McpOAuth,
McpOAuthClaims,
Expand All @@ -43,6 +53,7 @@ export type {
McpPromptReturn,
} from './prompt.ts'
export type {
McpCacheHints,
McpResourceDefinition,
McpResourceReturn,
McpResourceTemplateDefinition,
Expand All @@ -66,20 +77,12 @@ export type {
} from './tool.ts'

export type {
AuthCredentials,
AuthOptions,
AuthScheme,
CacheHints,
CallToolResult,
ContentBlock,
EmbeddedResource,
Era,
ExtensionPlugin,
GetPromptResult,
Icon,
InputRequiredResult,
OriginOptions,
PluginOptions,
ReadResourceResult,
ResourceLink,
StandardTypedV1,
Expand Down
6 changes: 3 additions & 3 deletions packages/nitro-mcp-toolkit/src/runtime/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from './oauth-url.ts'
import type { H3Event } from 'h3/generic'
import type { JWTPayload } from 'jose'
import type { AuthOptions } from 'h3-mcp'
import type { McpAuthOptions } from './auth.ts'

export { authorizationServerMetadataUrl, protectedResourceMetadataUrl } from './oauth-url.ts'

Expand Down Expand Up @@ -119,7 +119,7 @@ export interface McpOAuth {
resourceMetadataUrl: string
metadata: McpProtectedResourceMetadata
/** Pass as `auth` to `createMcpHandler`. */
auth: AuthOptions
auth: McpAuthOptions
metadataHandler: (event: H3Event) => Response
/**
* RFC 8414 document for this issuer, with CORS. Only set when
Expand Down Expand Up @@ -251,7 +251,7 @@ export function createMcpOAuth(options: McpOAuthOptions): McpOAuth {
...(options.scopesSupported ? { scopes_supported: options.scopesSupported } : {}),
}

const auth: AuthOptions = {
const auth: McpAuthOptions = {
schemes: ['bearer'],
resourceMetadataUrl: metadataUrl.href,
validate: async (credential, event) => {
Expand Down
7 changes: 6 additions & 1 deletion packages/nitro-mcp-toolkit/src/runtime/plugins.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { ExtensionPlugin } from 'h3-mcp'

/** An engine extension, such as `mcpTasks()` from `h3-mcp/tasks`. */
export type McpExtensionPlugin = ExtensionPlugin

/**
* Define the extension plugins an endpoint installs, as the default export of
* `<dir>/plugins.ts`.
Expand All @@ -15,6 +18,8 @@ import type { ExtensionPlugin } from 'h3-mcp'
* export default defineMcpPlugins([mcpTasks({ max: 100 })])
* ```
*/
export function defineMcpPlugins(plugins: readonly ExtensionPlugin[]): readonly ExtensionPlugin[] {
export function defineMcpPlugins(
plugins: readonly McpExtensionPlugin[],
): readonly McpExtensionPlugin[] {
return plugins
}
5 changes: 4 additions & 1 deletion packages/nitro-mcp-toolkit/src/runtime/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import type { McpResource } from './definition.ts'

type Awaitable<T> = T | Promise<T>

/** How long clients may cache what a resource read returns. */
export type McpCacheHints = CacheHints

/**
* What a resource handler may return: the text of the resource, or a full
* protocol result when it carries several contents or binary data.
Expand All @@ -40,7 +43,7 @@ interface McpResourceMetadata {
mimeType?: string
icons?: Icon[]
/** Advertised to clients so they may cache the read. */
cache?: CacheHints
cache?: McpCacheHints
}

export interface McpResourceDefinition extends McpResourceMetadata {
Expand Down
Loading
Loading