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
10 changes: 10 additions & 0 deletions .changeset/calm-eels-appear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"nitro-mcp-toolkit": major
"@nuxtjs/mcp-toolkit": major
---

Keep file-discovered endpoints when authentication needs runtime configuration. Set `auth` to a server-only file default-exporting `defineMcpAuth()` options; callbacks read private credentials at request time instead of embedding them in generated configuration. Missing files and invalid exports refuse access.

Nitro 2 consumers now tree-shake the toolkit's own MCP engine, H3 v2 and JWT dependencies while preserving the host's H3 v1 runtime. When neither the endpoint nor the application uses OAuth/JWT helpers, deployment output omits `jose`; configured OAuth continues to verify JWT access tokens.

Infer literal and enum output fields in `defineMcpTool()` callbacks without return-type annotations or `satisfies`. Typed output remains validated, including array fields and explicit protocol results.
6 changes: 6 additions & 0 deletions .changeset/loud-cups-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@nuxtjs/mcp-toolkit": patch
"nitro-mcp-toolkit": patch
---

Keep continuation helpers compatible with Nuxt's Nitro 2 host types. Input-response helpers and signed request-state codecs now expose canonical H3 v2 event signatures while retaining the shared engine's function references and inferred response types. The test client accepts a request-only fetch handler, including a composed Nuxt handler.
6 changes: 6 additions & 0 deletions .changeset/quiet-servers-meet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"nitro-mcp-toolkit": major
"@nuxtjs/mcp-toolkit": major
---

Configure each discovered endpoint from an optional `index.ts` beside its tools, resources and prompts. Default-export `defineMcpServer({ name, instructions, auth })` to keep metadata and runtime authentication out of framework configuration. Module options retain routing, directory selection and OAuth metadata; the index overrides other defaults. The first root containing an index wins across layers. Ambiguous files, invalid exports and conflicting authentication refuse requests. New and removed indexes trigger development rebuilds. Nuxt installation links and `llms.txt` use the discovered public server metadata.
22 changes: 5 additions & 17 deletions .github/snippets/installation.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,9 @@
Use `nuxt` to install the module automatically:
This branch documents the 1.0 beta API and requires Nuxt 4.6 or later. Install the beta explicitly:

```bash
npx nuxt add mcp
```sh
pnpm add @nuxtjs/mcp-toolkit@beta zod
```

Or install manually:
Before the first beta publication, use the exact package-preview command from the reviewed PR. An unversioned install selects stable 0.x while `latest` remains there.

```bash
# npm
npm install -D @nuxtjs/mcp-toolkit zod

# yarn
yarn add -D @nuxtjs/mcp-toolkit zod

# pnpm
pnpm add -D @nuxtjs/mcp-toolkit zod

# bun
bun add -D @nuxtjs/mcp-toolkit zod
```
Register the module and create typed definitions using the [Nuxt package guide](packages/nuxt-mcp-toolkit/README.md). Existing applications should follow the [migration guide](apps/docs/content/1.getting-started/7.beta-migration.md).
12 changes: 11 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ The app installs `mcp()` from `nitro-mcp-toolkit/module` twice, on `/mcp` and `/

`dir` can also be an array in priority order: the first root containing the same relative definition file wins, and all roots are watched. Plugins come from the first root containing `plugins.*`; an ambiguous pair in that root remains an error. Framework integrations add generated module specifiers through `include.tools`, `include.resources`, `include.prompts`, and `include.plugins`. Definition modules default-export one definition; plugins modules default-export arrays appended after the discovered plugins. Included definitions remain additive and participate in duplicate validation.

**Discovery generates two Nitro virtual modules per instance** — `#mcp/<slug>/registry`, which imports each definition file, and `#mcp/<slug>/handler`, which is what `options.handlers` mounts. Apps never import those ids: every instance is re-exported from a third virtual, `nitro-mcp-toolkit/servers` (`mcp` for `/mcp`, `adminMcp` for `/admin/mcp`). These were established empirically and are easy to break:
**Discovery generates registry and handler Nitro virtual modules per instance** — `#mcp/<slug>/registry`, which imports each definition file, and `#mcp/<slug>/handler`, which is what `options.handlers` mounts. A metadata-only `#mcp-config:<route>` virtual also exposes the resolved name, description and website to Nuxt installation links and `llms.txt`, without loading definitions or plugins. Apps never import those ids: every instance is re-exported from a third virtual, `nitro-mcp-toolkit/servers` (`mcp` for `/mcp`, `adminMcp` for `/admin/mcp`). These were established empirically and are easy to break:

- A bare `nitro-mcp-toolkit` import inside a virtual module resolves fine, in dev and in a production build, so the generated handler imports the toolkit exactly as a user's file does — one module instance.
- The registry inlines its own `fromFile` helper rather than importing one, which keeps build-time naming out of the runtime bundle and the runtime free of an export that only generated code would call.
Expand Down Expand Up @@ -209,6 +209,10 @@ The runtime is written against a pinned `h3-mcp` (currently 0.2.0). That release

**Plugins reach a `mcp()` server through `<dir>/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`.

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

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

For Nitro tools with `outputSchema`, plain objects are schema data; full protocol envelopes must use `toolResult()`.
Expand All @@ -217,6 +221,8 @@ For Nitro tools with `outputSchema`, plain objects are schema data; full protoco

`nitro-mcp-toolkit/module/nitro2` shares module setup with Nitro 3. Only imports from the toolkit runtime and h3-mcp resolve to the internal H3 v2; the host keeps H3 v1. The generated adapter preserves middleware context, headers, request bodies, and runtime facilities. H3 v1 does not cancel a returned web stream when its socket closes, so the adapter relays SSE and cancels its source reader on disconnect.

The Nitro 2 module inlines the toolkit runtime, h3-mcp, its own H3 v2 and jose for tree-shaking. Its matcher covers package specifiers and resolved paths without matching the host's H3 v1. Keeping only dependency paths misses imports behind an external toolkit package. Leaving jose external lets Nitro's tracer copy it even after unused OAuth exports disappear. Packed consumers check that bearer-only servers emit no JWT code or external jose files, and that OAuth still verifies signed tokens on Nitro 2 and 3.

The toolkit notifier lives at `event.context.mcp.notifier`. Preserve the engine's callable `event.context.mcp.notify`, which progress and logging use. `handler.notify` continues to broadcast catalog changes.

### Composition and verification (`nitro-mcp-toolkit`)
Expand Down Expand Up @@ -248,6 +254,8 @@ Schemas are complete Standard Schema objects. With input, handlers receive `(arg

For definitions without arguments, omit `inputSchema` and any unused schema-library import. Do not add an empty `z.object({})` as boilerplate.

The 1.0 docs include Nuxt OAuth setup at `/getting-started/oauth`, and retired Code Mode links redirect to migration guidance. Keep examples complete and validate them against generated Nuxt types; document provider-login checks separately from local JWT verification.

Keep substantive documentation examples for typed output and caching. Explain the actual beta API: schema `examples` are JSON Schema annotations, MCP `_meta` is extension metadata, and `_meta.inputExamples` is a custom client convention. Do not present removed convenience options as implemented APIs or remove useful examples merely to shorten a guide.

Resources use `uri` or `uriTemplate`, top-level MIME metadata, and text or contents results. Prompt strings are user messages; explicit messages support other roles. Completion uses explicit prompt `arguments` or resource-template callbacks.
Expand Down Expand Up @@ -468,3 +476,5 @@ Discovery catalog: [https://mcp-toolkit.nuxt.dev/.well-known/skills/index.json](
A correction is a few lines, not a rewrite — keep this file lean.

The Nuxt integration builds the Nitro toolkit before generating types. Its public H3 types import `h3/generic` so Nuxt’s H3 v1 alias cannot change the MCP callback’s web request type. The composed-route adapter preserves the host context by reference and relays disconnects; do not replace it with a context copy.

Engine input helpers retain their original function references and publish `h3/generic` event signatures, including signed-state codecs. The test client requires only a request-to-response fetch function, independently of host context types.
22 changes: 5 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,27 +66,15 @@ Review my MCP implementation

<!-- automd:file src=".github/snippets/installation.md" -->

Use `nuxt` to install the module automatically:
This branch documents the 1.0 beta API and requires Nuxt 4.6 or later. Install the beta explicitly:

```bash
npx nuxt add mcp
```sh
pnpm add @nuxtjs/mcp-toolkit@beta zod
```

Or install manually:

```bash
# npm
npm install -D @nuxtjs/mcp-toolkit zod

# yarn
yarn add -D @nuxtjs/mcp-toolkit zod

# pnpm
pnpm add -D @nuxtjs/mcp-toolkit zod
Before the first beta publication, use the exact package-preview command from the reviewed PR. An unversioned install selects stable 0.x while `latest` remains there.

# bun
bun add -D @nuxtjs/mcp-toolkit zod
```
Register the module and create typed definitions using the [Nuxt package guide](packages/nuxt-mcp-toolkit/README.md). Existing applications should follow the [migration guide](apps/docs/content/1.getting-started/7.beta-migration.md).

<!-- /automd -->

Expand Down
158 changes: 21 additions & 137 deletions apps/docs/content/1.getting-started/1.introduction.md
Original file line number Diff line number Diff line change
@@ -1,158 +1,42 @@
---
title: Introduction
description: Learn about the Model Context Protocol and how this module makes it easy to create MCP servers in Nuxt.
title: Create an MCP server in Nuxt
description: Expose application tools, resources, and prompts through the shared Nitro MCP runtime in Nuxt 4.6 or later.
navigation:
icon: i-lucide-book-open
icon: i-lucide-plug
seo:
title: Introduction to Nuxt MCP Toolkit
description: Learn about the Model Context Protocol and how this module makes it easy to create MCP servers in Nuxt.
title: Create an MCP server in Nuxt
description: Expose application tools, resources, and prompts through the shared Nitro MCP runtime in Nuxt 4.6 or later.
---

## What is Model Context Protocol?
## Choose what to expose

The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) is an open protocol that enables AI assistants to securely access external data sources and tools. It provides a standardized way for AI applications to:
An MCP client connects an AI application to capabilities you publish. A **tool** performs an operation, a **resource** supplies content at a URI, and a **prompt** supplies a reusable conversation template. Your application owns its data and authorization.

- **Access Tools**: Execute functions and operations
- **Read Resources**: Access files, databases, APIs, and other data sources
- **Use Prompts**: Leverage predefined prompt templates
Nuxt MCP Toolkit discovers these definitions from files. Nuxt supplies layers, server middleware, auto-imports, DevTools integration, and installation links. The shared `nitro-mcp-toolkit` runtime handles the protocol on Nitro 2 and Nitro 3.

MCP servers act as bridges between AI assistants and external systems, enabling them to interact with your application's data and functionality in a secure, controlled manner.
This documentation describes the 1.0 beta API. Existing 0.x applications should follow the [migration guide](/getting-started/beta-migration). Built-in MCP Apps and Code Mode are excluded from this beta.

## What is Nuxt MCP Toolkit?
## Start with a useful tool

The Nuxt MCP Toolkit makes it incredibly easy to create MCP servers directly in your Nuxt application. Instead of building a separate MCP server, you can define tools, resources, and prompts right alongside your Nuxt application code.

### Key Benefits

::card-group
:::card
---
icon: i-lucide-zap
title: Zero Configuration
---
Automatic discovery of definitions. Just create files in the right directories and they're automatically registered.
:::

:::card
---
icon: i-lucide-type
title: TypeScript First
---
Full TypeScript support with auto-imports and complete type safety. All helpers are available globally in your server files.
:::

:::card
---
icon: i-lucide-code
title: Simple API
---
Intuitive API that matches the MCP SDK structure, making it easy to migrate existing code or learn from examples.
:::

:::card
---
icon: i-lucide-layers
title: Flexible Architecture
---
Support for multiple MCP handlers in a single application, custom paths, and hooks for advanced use cases.
:::
::

## How It Works

The module automatically:

1. **Scans** your `server/mcp/` directory (or custom path) for definitions
2. **Discovers** tools, resources, and prompts from your files
3. **Registers** them with the MCP server
4. **Exposes** an HTTP endpoint for MCP clients to connect

```
server/
└── mcp/
├── tools/
│ ├── echo.ts
│ └── calculator.ts
├── resources/
│ ├── readme.ts
│ └── files.ts
└── prompts/
├── greeting.ts
└── summarize.ts
```

## Core Concepts

### Tools

Tools are functions that AI assistants can call. They accept input parameters (validated with Zod) and return results.

```typescript
```ts [server/mcp/tools/greet.ts]
import { z } from 'zod'
import { defineMcpTool } from '@nuxtjs/mcp-toolkit/server'

export default defineMcpTool({
name: 'calculate-bmi',
inputSchema: {
weightKg: z.number(),
heightM: z.number(),
},
handler: async ({ weightKg, heightM }) => {
const bmi = weightKg / (heightM * heightM)
return `BMI: ${bmi}`
},
description: 'Greet someone by name',
annotations: { readOnlyHint: true, openWorldHint: false },
inputSchema: z.object({ name: z.string().min(1) }),
outputSchema: z.object({ greeting: z.string() }),
handler: ({ name }) => ({ greeting: `Hello ${name}!` }),
})
```

### Resources

Resources provide access to data via URIs. They can be static files or dynamic data sources.

```typescript
import { defineMcpResource } from '@nuxtjs/mcp-toolkit/server'

export default defineMcpResource({
name: 'readme',
uri: 'file:///README.md',
handler: async (uri: URL) => {
const content = await readFile(uri.pathname, 'utf-8')
return {
contents: [{ uri: uri.toString(), text: content }],
}
},
})
```

### Prompts

Prompts are reusable message templates that can include dynamic arguments.

```typescript
import { defineMcpPrompt } from '@nuxtjs/mcp-toolkit/server'

export default defineMcpPrompt({
name: 'greeting',
inputSchema: {
name: z.string(),
},
handler: async ({ name }) => {
return {
messages: [{
role: 'user',
content: { type: 'text', text: `Hello, ${name}!` },
}],
}
},
})
```
The filename supplies the name `greet`. Inputs are parsed before the handler runs. The output schema validates returned data and advertises its shape; clients receive structured data and a JSON text fallback.

Built-in MCP Apps support is deferred for the 1.0 beta. See the [beta migration guide](/getting-started/beta-migration) to move App handlers into regular tools.
## Keep request state explicit

## Next Steps
With inputs, callbacks receive `(args, event)`; without inputs, they receive `event`. Use verified request context for identity. Keep services and storage independent of MCP, and authorize each operation before accessing private data.

Ready to get started? Check out:
The default endpoint is `/mcp`. Configure [independent endpoints](/handlers/overview) when catalogs or authentication differ. Keep `era: 'dual'` for modern and legacy client paths; advanced interactions still depend on client capabilities.

- [Installation Guide](/getting-started/installation) - Set up the module in your project
- [Configuration](/getting-started/configuration) - Configure the module
- [Tools Guide](/tools/overview) - Create your first MCP tool
- [Beta migration](/getting-started/beta-migration) - Move existing MCP App handlers into tools
Continue with [installation](/getting-started/installation), [OAuth](/getting-started/oauth), or [tool schemas](/tools/schema-handler).
Loading
Loading