Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 139 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,53 @@

[![npm next-devtools-mcp package](https://img.shields.io/npm/v/next-devtools-mcp.svg)](https://npmjs.org/package/next-devtools-mcp)

`next-devtools-mcp` is a Model Context Protocol (MCP) server that provides Next.js development tools and utilities for AI coding assistants like Claude and Cursor.
`next-devtools-mcp` is a Model Context Protocol (MCP) server that provides Next.js development tools and utilities for coding agents like Claude and Cursor.

## Features

- **MCP Tools**: Callable tools for automating Next.js upgrades and Cache Components setup
- **Development Prompts**: Pre-configured prompts for common Next.js development tasks
- **Next.js Documentation**: Access Next.js documentation and best practices
- **Browser Testing**: Integrate with Playwright for browser automation and testing
- **Next.js Agent**: Access internal state, diagnostics, and errors from running Next.js dev servers via MCP
This MCP server provides coding agents with comprehensive Next.js development capabilities through three primary mechanisms:

> **Learn more:** See the [Next.js MCP documentation](https://nextjs.org/docs/app/guides/mcp) for details on how MCP servers work with Next.js and AI coding agents.
### **1. Runtime Diagnostics & Live State Access** (Next.js 16+)
Connect directly to your running Next.js dev server's built-in MCP endpoint to query:
- Real-time build and runtime errors
- Application routes, pages, and component metadata
- Development server logs and diagnostics
- Server Actions and component hierarchies

### **2. Development Automation**
Tools for common Next.js workflows:
- **Automated Next.js 16 upgrades** with official codemods
- **Cache Components setup** with error detection and automated fixes
- **Browser testing integration** via Playwright for visual verification

### **3. Knowledge Base & Documentation**
- Curated Next.js 16 knowledge base (12 focused resources on Cache Components, async APIs, etc.)
- Direct access to official Next.js documentation via search API
- Pre-configured prompts for upgrade guidance and Cache Components enablement

> **Learn more:** See the [Next.js MCP documentation](https://nextjs.org/docs/app/guides/mcp) for details on how MCP servers work with Next.js and coding agents.

## How It Works

This package provides a **bridge MCP server** that connects your coding agent to Next.js development tools:

```
Coding Agent
next-devtools-mcp (this package)
├─→ Next.js Dev Server MCP Endpoint (/_next/mcp) ← Runtime diagnostics
├─→ Playwright MCP Server ← Browser automation
└─→ Knowledge Base & Tools ← Documentation, upgrades, setup automation
```

**Key Architecture Points:**

1. **For Next.js 16+ projects**: This server automatically discovers and connects to your running Next.js dev server's built-in MCP endpoint at `http://localhost:PORT/_next/mcp`. This gives coding agents direct access to runtime errors, routes, logs, and application state.

2. **For all Next.js projects**: Provides development automation tools (upgrades, Cache Components setup), documentation access, and browser testing capabilities that work independently of the runtime connection.

3. **Auto-discovery**: The `nextjs_runtime` tool scans common ports (3000, 3001, etc.) to find running Next.js servers, so you don't need to manually specify ports in most cases.

## Requirements

Expand Down Expand Up @@ -156,42 +192,53 @@ Navigate to `Settings | AI | Manage MCP Servers` and select `+ Add` to register

</details>

### Next.js Internal State Access (Recommended for Next.js >= 16)
## Quick Start

### For Next.js 16+ Projects (Recommended)

**Restart your Next.js dev server:**
To unlock the full power of runtime diagnostics, start your Next.js dev server:

```bash
npm run dev
```

**Benefits:**
Next.js 16+ has MCP enabled by default at `http://localhost:3000/_next/mcp` (or whichever port your dev server uses). The `next-devtools-mcp` server will automatically discover and connect to it.

- **MCP Server Discovery**: Automatically discover and connect to Next.js dev servers running with MCP enabled
- **Internal State Access**: Query your running Next.js instance for errors, routes, build status, and diagnostics
- **Real-time Error Detection**: Access internal Next.js error state and compiler diagnostics through MCP
- **Direct Communication**: AI coding agents communicate directly with Next.js through MCP protocol for accurate, real-time information
**Try these prompts in your coding agent:**

### Your First Prompt
```
Next Devtools, what errors are in my Next.js application?
```

Enter the following prompt in your MCP client to check if everything is working:
```
Next Devtools, show me the structure of my routes
```

```
Next Devtools, help me upgrade my Next.js app to version 16
Next Devtools, what's in the development server logs?
```

Your MCP client should provide guidance and tools for upgrading your Next.js application.
Your coding agent will use the `nextjs_runtime` tool to query your running application's actual state.

### For All Next.js Projects

You can use the development automation and documentation tools regardless of Next.js version:

If you're on **Next.js 16 or later** with `experimental.mcpServer` enabled, you can also try:
```
Next Devtools, help me upgrade my Next.js app to version 16
```

```
Next Devtools, what's the structure of my Next.js routes?
Next Devtools, enable Cache Components in my Next.js app
```

Claude Code will query your running dev server for actual route information and component diagnostics.
```
Next Devtools, search Next.js docs for generateMetadata
```

## MCP Resources

Next.js 16 knowledge base resources are automatically available to your AI assistant.
Next.js 16 knowledge base resources are automatically available to your coding agent.

These resources provide comprehensive documentation split into focused sections for efficient context management:

Expand All @@ -213,7 +260,7 @@ These resources provide comprehensive documentation split into focused sections

</details>

Resources are loaded on-demand by your AI assistant, providing targeted knowledge without overwhelming the context window.
Resources are loaded on-demand by your coding agent, providing targeted knowledge without overwhelming the context window.

## MCP Prompts

Expand All @@ -235,18 +282,21 @@ Pre-configured prompts to help with common Next.js development tasks:
Search and retrieve Next.js official documentation and knowledge base.

**Capabilities:**
- First searches MCP resources (Next.js 16 knowledge base) for latest information
- Falls back to official Next.js documentation if nothing is found
- Two-step process: 1) Search for docs by keyword to get paths, 2) Fetch full markdown content by path
- Uses official Next.js documentation search API
- Provides access to comprehensive Next.js guides, API references, and best practices
- Smart keyword matching for topics like cache, prefetch, params, cookies, headers, etc.
- Supports filtering by router type (App Router, Pages Router, or both)

**Input:**
- `query` (required) - Search query to find relevant Next.js documentation sections
- `category` (optional) - Filter by category: `all`, `getting-started`, `guides`, `api-reference`, `architecture`, `community`
- `action` (required) - Action to perform: `search` to find docs, `get` to fetch full content
- `query` (optional) - Required for `search`. Keyword search query (e.g., 'metadata', 'generateStaticParams', 'middleware')
- `path` (optional) - Required for `get`. Doc path from search results (e.g., '/docs/app/api-reference/functions/refresh')
- `anchor` (optional) - Optional for `get`. Anchor/section from search results (e.g., 'usage')
- `routerType` (optional) - For `search` only. Filter by: `app`, `pages`, or `all` (default: `all`)

**Output:**
- Relevant documentation sections from Next.js 16 knowledge base (with content preview)
- Links to official Next.js documentation pages
- Search results with doc titles, paths, content snippets, sections, and anchors
- Full markdown content for specific documentation pages

</details>

Expand Down Expand Up @@ -292,21 +342,67 @@ Automate and test web applications using Playwright browser automation.
<details>
<summary><code>nextjs_runtime</code></summary>

Discover running MCP servers from Next.js instances and invoke their MCP devtools.
Connect to your running Next.js dev server's built-in MCP endpoint to access live application state, runtime diagnostics, and internal information.

**What this tool does:**

This tool acts as a bridge between your coding agent and Next.js 16's built-in MCP endpoint at `/_next/mcp`. It provides three key actions:

1. **`discover_servers`**: Find all running Next.js dev servers on your machine
2. **`list_tools`**: See what runtime diagnostic tools are available from Next.js
3. **`call_tool`**: Execute a specific Next.js runtime tool (e.g., get errors, query routes, fetch logs)

**Available Next.js Runtime Tools** (accessed via `call_tool`):

Once connected to a Next.js 16+ dev server, you can access these built-in tools:
- `get_errors` - Get current build, runtime, and type errors
- `get_logs` - Get path to development log file (browser console + server output)
- `get_page_metadata` - Query application routes, pages, and component metadata
- `get_project_metadata` - Get project structure, config, and dev server URL
- `get_server_action_by_id` - Look up Server Actions by ID to find source files

**Requirements:**
- Next.js 16 or later (MCP support added in v16)
- MCP is enabled by default in Next.js 16+
- Next.js 16+ (MCP enabled by default)
- Running dev server (`npm run dev`)

**Input:**
- `action` (required) - Action to perform: `discover_servers`, `list_tools`, `call_tool`
- `port` (optional) - Port number of Next.js dev server (auto-discovers if not provided)
- `toolName` (optional) - Name of the Next.js MCP tool to call (required for `call_tool`)
- `args` (optional) - Arguments object to pass to the tool
- `includeUnverified` (optional) - Include servers even if MCP verification fails
**Typical workflow:**

```javascript
// Step 1: Discover running servers (optional - auto-discovery works in most cases)
{
"action": "discover_servers"
}

// Step 2: List available runtime tools
{
"action": "list_tools",
"port": 3000 // optional if only one server is running
}

// Step 3: Call a specific tool
{
"action": "call_tool",
"port": 3000,
"toolName": "get_errors"
// args is optional and only needed if the tool requires parameters
}
```

**Input Parameters:**
- `action` (required) - `discover_servers`, `list_tools`, or `call_tool`
- `port` (optional) - Dev server port (auto-discovers if not provided)
- `toolName` (required for `call_tool`) - Name of the Next.js tool to invoke
- `args` (optional) - Arguments object for the tool (only if required by that tool)
- `includeUnverified` (optional) - For `discover_servers`: include servers even if MCP verification fails

**Output:**
- JSON with discovered servers, available tools, or tool execution results
- JSON with discovered servers, available tools list, or tool execution results

**Example prompts that use this tool:**
- "Next Devtools, what errors are in my Next.js app?"
- "Next Devtools, show me my application routes"
- "Next Devtools, what's in the dev server logs?"
- "Next Devtools, find the Server Action with ID xyz"

</details>

Expand Down Expand Up @@ -386,12 +482,14 @@ To run the MCP server locally for development:
"mcpServers": {
"next-devtools": {
"command": "node",
"args": ["/path/to/next-devtools-mcp/dist/stdio.js"]
"args": ["/absolute/path/to/next-devtools-mcp/dist/stdio.js"]
}
}
}
```

Note: Replace `/absolute/path/to/next-devtools-mcp` with the actual absolute path to your cloned repository.

or manually add, e.g. with codex:
```
codex mcp add next-devtools-local -- node dist/stdio.js
Expand Down
9 changes: 4 additions & 5 deletions src/_internal/nextjs-runtime-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ async function makeNextJsMCPRequest(
throw new Error(
`MCP endpoint not found. Next.js MCP support requires Next.js 16+. ` +
`If you're on an older version, upgrade using the 'upgrade-nextjs-16' MCP prompt. ` +
`If you're already on Next.js 16+: MCP is enabled by default - make sure the dev server is running. ` +
`For Next.js < 16: enable MCP with __NEXT_EXPERIMENTAL_MCP_SERVER=true or experimental.mcpServer: true in next.config.js`
`If you're already on Next.js 16+: MCP is enabled by default - make sure the dev server is running.`
)
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
Expand All @@ -121,9 +120,9 @@ async function makeNextJsMCPRequest(
if (error instanceof TypeError && error.message.includes("fetch failed")) {
throw new Error(
`Cannot connect to Next.js dev server on port ${port}. ` +
`Make sure the dev server is running. For Next.js < 16: ` +
`enable MCP with __NEXT_EXPERIMENTAL_MCP_SERVER=true or experimental.mcpServer: true. ` +
`For Next.js >= 16: MCP is enabled by default. If you're on Next.js 15 or earlier, upgrade using the 'upgrade-nextjs-16' MCP prompt.`
`Make sure the dev server is running. ` +
`Next.js MCP support requires Next.js 16+ where MCP is enabled by default. ` +
`If you're on Next.js 15 or earlier, upgrade using the 'upgrade-nextjs-16' MCP prompt.`
)
}

Expand Down
14 changes: 7 additions & 7 deletions src/prompts/enable-cache-components-prompt.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ This prompt automates the complete Cache Components enablement workflow:
- ✅ Document existing Route Segment Config for migration

**Dev Server & MCP Setup (Phase 3):**
- ✅ Start dev server once with MCP enabled (`__NEXT_EXPERIMENTAL_MCP_SERVER=true`)
- ✅ Start dev server (MCP is enabled by default in Next.js 16+)
- ✅ Verify MCP server is active and responding
- ✅ Capture base URL and MCP endpoint for error detection

Expand Down Expand Up @@ -900,8 +900,8 @@ After completing Step 3 and fixing all errors, verify with a final build:

If you want to verify routes interactively:
```bash
# Start dev server
__NEXT_EXPERIMENTAL_MCP_SERVER=true <pkg-manager> dev
# Start dev server (MCP is enabled by default in Next.js 16+)
<pkg-manager> dev
```

Then:
Expand Down Expand Up @@ -949,12 +949,12 @@ This provides build verification strategies and troubleshooting guidance.

**If Phase 3 Step 3C had unclear errors that couldn't be fixed from build output:**

1. **Start Dev Server with MCP**
1. **Start Dev Server**
```bash
# Start dev server with MCP enabled
__NEXT_EXPERIMENTAL_MCP_SERVER=true <pkg-manager> dev
# Start dev server (MCP is enabled by default in Next.js 16+)
<pkg-manager> dev
```

Wait for server to show ready message with URL.

2. **Verify MCP Server Active**
Expand Down
2 changes: 1 addition & 1 deletion src/tools/enable-cache-components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const metadata = {

Handles ALL steps for enabling and verifying Cache Components:
- Configuration: Updates cacheComponents flag (experimental in 16.0.0, stable in canary > 16), removes incompatible flags
- Dev Server: Starts dev server with MCP enabled (__NEXT_EXPERIMENTAL_MCP_SERVER=true)
- Dev Server: Starts dev server (MCP is enabled by default in Next.js 16+)
- Error Detection: Loads all routes via browser automation, collects errors using Next.js MCP
- Automated Fixing: Adds Suspense boundaries, "use cache" directives, generateStaticParams, cacheLife profiles, cache tags
- Verification: Validates all routes work with zero errors
Expand Down
13 changes: 6 additions & 7 deletions src/tools/nextjs-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,8 @@ REQUIREMENTS:
- Next.js 16 or later (MCP support was added in v16)
- If you're on Next.js 15 or earlier, use the 'upgrade-nextjs-16' MCP prompt to upgrade first

Next.js exposes an MCP (Model Context Protocol) endpoint at /_next/mcp when started with:
- For Next.js < 16: experimental.mcpServer: true in next.config.js, OR __NEXT_EXPERIMENTAL_MCP_SERVER=true environment variable
- For Next.js >= 16: MCP is enabled by default (no configuration needed)
Next.js 16+ exposes an MCP (Model Context Protocol) endpoint at /_next/mcp automatically when the dev server starts.
No configuration needed - MCP is enabled by default in Next.js 16 and later.

This tool allows you to:
1. Discover running Next.js dev servers and their ports
Expand All @@ -99,9 +98,9 @@ IMPORTANT: When calling tools:
- Check the tool's inputSchema from 'list_tools' to see what arguments are required

If the MCP endpoint is not available:
1. Check if you're running Next.js 16+ (if not, use the 'upgrade-nextjs-16' prompt)
2. For Next.js < 16: Ensure the dev server is started with __NEXT_EXPERIMENTAL_MCP_SERVER=true or experimental.mcpServer: true
3. For Next.js >= 16: MCP should be enabled by default - check if the dev server is running`,
1. Ensure you're running Next.js 16 or later (use the 'upgrade-nextjs-16' prompt to upgrade)
2. Verify the dev server is running (npm run dev)
3. Check that the dev server started successfully without errors`,
}

export default async function nextjsRuntime(args: InferSchema<typeof schema>): Promise<string> {
Expand All @@ -117,7 +116,7 @@ export default async function nextjsRuntime(args: InferSchema<typeof schema>): P
message: verifyMCP
? "No running Next.js dev servers with MCP enabled found"
: "No running Next.js dev servers found",
hint: "For Next.js < 16: Start with __NEXT_EXPERIMENTAL_MCP_SERVER=true or experimental.mcpServer: true. For Next.js >= 16: MCP is enabled by default.",
hint: "Make sure you're running Next.js 16+ (MCP is enabled by default). Start the dev server with 'npm run dev'. If on Next.js 15 or earlier, upgrade using the 'upgrade-nextjs-16' prompt.",
count: 0,
})
}
Expand Down