diff --git a/.changeset/oauth-challenges-service-tokens.md b/.changeset/oauth-challenges-service-tokens.md
new file mode 100644
index 00000000..f33ac4fe
--- /dev/null
+++ b/.changeset/oauth-challenges-service-tokens.md
@@ -0,0 +1,8 @@
+---
+"nitro-mcp-toolkit": major
+"@nuxtjs/mcp-toolkit": major
+---
+
+OAuth endpoints send the challenges the MCP authorization specification describes. The `401` challenge names `scopesSupported` in its `scope` parameter, and a call refused for a missing scope on the modern revision returns HTTP `403` with `WWW-Authenticate: Bearer error="insufficient_scope"`, the scopes needed and `resource_metadata`, so clients can request more access.
+
+`createMcpOAuth` accepts `serviceTokens`: static bearer tokens for callers that cannot sign in, such as agents or scheduled jobs. Each token is read at request time and sets fixed claims, so `scopes` and `authorize` apply to it.
diff --git a/AGENTS.md b/AGENTS.md
index 119347bd..73f23b5d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -207,7 +207,7 @@ The runtime is written against a pinned `h3-mcp` (currently 0.2.0). That release
**`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. 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 `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.
**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/1.getting-started/8.oauth.md b/apps/docs/content/1.getting-started/8.oauth.md
index ae7e5381..d49e4f7e 100644
--- a/apps/docs/content/1.getting-started/8.oauth.md
+++ b/apps/docs/content/1.getting-started/8.oauth.md
@@ -95,6 +95,8 @@ export default defineMcpTool({
`scopesSupported` advertises available scopes; `scopes` requires every named scope on each invocation. Scope claims come from verified `scope` or `scp`. Checks also protect resource-template enumeration and resource/prompt completion callbacks.
+Missing or invalid credentials get a `401` whose challenge names `scopesSupported` in `scope`; MCP clients request those scopes first. On the modern revision, a call refused for a missing scope returns HTTP `403` with `WWW-Authenticate: Bearer error="insufficient_scope"`, the scopes the token holds plus the ones the call needs, and `resource_metadata`, so the client can ask for more access. A legacy request reports the same JSON-RPC error inside a `200` stream, without a challenge.
+
Scoped definitions still appear in the authenticated catalog. Protect an endpoint separately when its metadata is sensitive. Authentication and authorization run for the current request; application queries must also enforce ownership and tenant boundaries.
## Configure OAuth per endpoint
@@ -234,6 +236,30 @@ This adapter verifies JWT OAuth access tokens only. It has no auth-instance over
Your application must still configure [Better Auth's OAuth provider plugin](https://www.better-auth.com/docs/plugins/oauth-provider), its resources and scopes, login and consent pages, client registration, and the plugin's database schema or migrations. The toolkit adds no database or provider tables. A Better Auth login session alone does not issue an MCP access token. See the provider's [resource-server guide](https://www.better-auth.com/docs/plugins/oauth-provider/resource-server) for the distinction between session tokens and OAuth access tokens. Provider support for DPoP does not enable DPoP in the toolkit.
+## Accept a service token
+
+Callers that cannot sign in, such as an agent or a scheduled job, can use a static bearer token beside OAuth access tokens:
+
+```ts [server/mcp-admin/index.ts]
+import { createMcpOAuth, defineMcpServer } from '@nuxtjs/mcp-toolkit/server'
+import { useRuntimeConfig } from 'nitropack/runtime'
+
+export default defineMcpServer({
+ oauth: createMcpOAuth({
+ resource: 'https://example.com/mcp/admin',
+ authorizationServers: ['https://auth.example.com'],
+ jwt: { jwks: 'https://auth.example.com/.well-known/jwks.json' },
+ scopesSupported: ['admin:read'],
+ serviceTokens: [{
+ token: () => useRuntimeConfig().mcpAgentToken,
+ claims: { sub: 'agent', scope: 'admin:read' },
+ }],
+ }),
+})
+```
+
+Each token is read at request time, so keep it in private runtime configuration; an empty value matches nothing. A matching token skips `jwt` and `verify` and sets `claims` on `event.context.oauth`, so `scopes` and `authorize` apply to it like any other identity. Every entry needs `claims.sub`. Prefer OAuth for people: a service token does not expire and identifies a caller, not a user.
+
## Use a request-aware verifier
`createMcpOAuth` also accepts `verify(token, event)` for opaque tokens or provider-specific verification. The callback must validate the token for this resource, set verified claims on `event.context.oauth`, and return a boolean. Set a nonempty `sub` when using `authorize`; set verified `scope` or `scp` claims when requiring scopes. Never treat decoding a JWT or reading a session cookie as token verification.
diff --git a/packages/nitro-mcp-toolkit/src/runtime/handler.ts b/packages/nitro-mcp-toolkit/src/runtime/handler.ts
index 0df84c5c..c09198f2 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/handler.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/handler.ts
@@ -2,6 +2,8 @@ import { H3Event, HTTPError, toResponse } from 'h3'
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 { parseMcpToolsHeader, unknownToolNames, unknownToolsResponse } from './tools-header.ts'
import { resolveDefinitions, summarize } from './validate.ts'
import type {
@@ -88,6 +90,39 @@ export interface McpHandlerOptions extends Pick<
onToolCall?: McpToolCallListener
}
+/**
+ * RFC 6750 challenges the MCP authorization spec asks for: `scope` on the
+ * `401` so clients request it first, and `insufficient_scope` on a `403` from
+ * a scoped definition so they can step up. A legacy request reports a scope
+ * failure inside a `200` stream, which carries no challenge.
+ */
+function withOAuthChallenge(response: Response, event: H3Event, oauth: McpOAuth): Response {
+ const metadata = `resource_metadata="${oauth.resourceMetadataUrl}"`
+ let challenge: string | undefined
+
+ if (response.status === 401 && oauth.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}"`,
+ )
+ }
+ } else if (response.status === 403) {
+ const scope = challengeScopes(insufficientScope.get(event))
+ if (scope) challenge = `Bearer error="insufficient_scope", scope="${scope}", ${metadata}`
+ }
+
+ if (!challenge) return response
+ const headers = new Headers(response.headers)
+ headers.set('www-authenticate', challenge)
+ return new Response(response.body, {
+ status: response.status,
+ statusText: response.statusText,
+ headers,
+ })
+}
+
class AccessDenied extends HTTPError {
constructor() {
super({ status: 403, statusText: 'Forbidden' })
@@ -312,12 +347,14 @@ export function createMcpHandler(
}
const run = async (event: H3Event): Promise => {
+ let response: Response
try {
- return await execute(event)
+ response = await execute(event)
} catch (error) {
- if (error instanceof AccessDenied) return toResponse(error, event)
- throw error
+ if (!(error instanceof AccessDenied)) throw error
+ response = await toResponse(error, event)
}
+ return oauth ? withOAuthChallenge(response, event, oauth) : response
}
return Object.assign(run, {
diff --git a/packages/nitro-mcp-toolkit/src/runtime/index.ts b/packages/nitro-mcp-toolkit/src/runtime/index.ts
index bcecd5b3..aece89f4 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/index.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/index.ts
@@ -43,6 +43,7 @@ export type {
McpOAuthClaims,
McpOAuthJwtOptions,
McpOAuthOptions,
+ McpOAuthServiceToken,
McpOAuthSetup,
McpProtectedResourceMetadata,
} from './oauth.ts'
diff --git a/packages/nitro-mcp-toolkit/src/runtime/oauth.ts b/packages/nitro-mcp-toolkit/src/runtime/oauth.ts
index 56f1f257..2a9630a5 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/oauth.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/oauth.ts
@@ -95,6 +95,22 @@ export interface McpOAuthOptions {
* auth runs before any tool handler.
*/
verify?: (token: string, event: H3Event) => boolean | Promise
+ /**
+ * Static bearer tokens accepted beside OAuth access tokens, for callers that
+ * cannot sign in, such as an agent or a scheduled job. Each token is read at
+ * request time, so it can come from private runtime configuration; an empty
+ * value matches nothing. A match skips `jwt` and `verify` and sets `claims`
+ * on `event.context.oauth`, so `scopes` and `authorize` apply to it as well.
+ *
+ * @example
+ * ```ts
+ * serviceTokens: [{
+ * token: () => useRuntimeConfig().agentToken,
+ * claims: { sub: 'agent', scope: 'reports:read' },
+ * }]
+ * ```
+ */
+ serviceTokens?: McpOAuthServiceToken[]
/**
* When set, `authorizationServerHandler` proxies this issuer's RFC 8414
* document. Old MCP clients look for it on the resource origin rather than
@@ -103,6 +119,11 @@ export interface McpOAuthOptions {
authorizationServer?: string
}
+export interface McpOAuthServiceToken {
+ token: string | (() => string | undefined)
+ claims: McpOAuthClaims & { sub: string }
+}
+
/**
* JWT resource-server config with `jwt` required. Connectors return this;
* `mcp({ oauth })` accepts it. Opaque tokens still use `createMcpOAuth({ verify })`.
@@ -118,6 +139,11 @@ export interface McpOAuth {
/** 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
@@ -178,6 +204,35 @@ function createJwtVerifier(jwt: McpOAuthJwtOptions, resource: string, issuers: s
}
}
+const encoder = new TextEncoder()
+
+// Compares every byte whatever the first difference, so timing does not reveal a prefix.
+function sameToken(expected: string, actual: string): boolean {
+ const a = encoder.encode(expected)
+ const b = encoder.encode(actual)
+ let difference = a.length ^ b.length
+ for (let index = 0; index < b.length; index++) difference |= (a[index] ?? 0) ^ b[index]!
+ return difference === 0
+}
+
+function matchServiceToken(
+ serviceTokens: McpOAuthServiceToken[] | undefined,
+ token: string,
+): McpOAuthServiceToken | undefined {
+ return serviceTokens?.find((entry) => {
+ const expected = typeof entry.token === 'function' ? entry.token() : entry.token
+ return typeof expected === 'string' && expected !== '' && sameToken(expected, token)
+ })
+}
+
+// RFC 6749 scope tokens: printable ASCII without space, `"` or `\`, so they fit a quoted challenge.
+const SCOPE_TOKEN = /^[\x21\x23-\x5B\x5D-\x7E]+$/
+
+export function challengeScopes(scopes: readonly string[] | undefined): string | undefined {
+ const valid = scopes?.filter((scope) => SCOPE_TOKEN.test(scope))
+ return valid?.length ? valid.join(' ') : undefined
+}
+
function normalizeIssuer(value: string, label: string): string {
const url = assertAbsoluteHttpUrl(value, label)
return url.href.replace(/\/+$/, '') || url.origin
@@ -229,6 +284,12 @@ export function createMcpOAuth(options: McpOAuthOptions): McpOAuth {
throw new Error('[nitro-mcp-toolkit] `createMcpOAuth` needs `jwt` or `verify`.')
}
+ for (const entry of options.serviceTokens ?? []) {
+ if (typeof entry?.claims?.sub !== 'string' || entry.claims.sub === '') {
+ throw new Error('[nitro-mcp-toolkit] Each `serviceTokens` entry needs `claims.sub`.')
+ }
+ }
+
if (options.jwt?.audience === false && !options.verify) {
throw new Error(
'[nitro-mcp-toolkit] Disabling audience validation requires a resource verifier in `verify`.',
@@ -257,6 +318,11 @@ export function createMcpOAuth(options: McpOAuthOptions): McpOAuth {
validate: async (credential, event) => {
delete event.context.oauth
if (credential.scheme !== 'bearer') return false
+ const service = matchServiceToken(options.serviceTokens, credential.token)
+ if (service) {
+ stashClaims(event, { ...service.claims })
+ return true
+ }
if (verifyJwt && !(await verifyJwt(credential.token, event))) return false
if (options.verify && !(await options.verify(credential.token, event))) return false
return true
@@ -268,6 +334,9 @@ export function createMcpOAuth(options: McpOAuthOptions): McpOAuth {
metadataPath: metadataUrl.pathname,
resourceMetadataUrl: metadataUrl.href,
metadata,
+ ...(challengeScopes(options.scopesSupported)
+ ? { challengeScope: challengeScopes(options.scopesSupported) }
+ : {}),
auth,
metadataHandler: metadataHandlerFor(metadata),
...(authorizationServer
diff --git a/packages/nitro-mcp-toolkit/src/runtime/scopes.ts b/packages/nitro-mcp-toolkit/src/runtime/scopes.ts
index 3a55a50d..dbf52c00 100644
--- a/packages/nitro-mcp-toolkit/src/runtime/scopes.ts
+++ b/packages/nitro-mcp-toolkit/src/runtime/scopes.ts
@@ -9,6 +9,9 @@ import type { McpOAuthClaims } from './oauth.ts'
*/
const INSUFFICIENT_SCOPE = -32003
+/** Scopes a refused call needs, per request, for the `403` `WWW-Authenticate` challenge. */
+export const insufficientScope = new WeakMap