next-devtools-mcp-skill

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Next.js DevTools MCP Skill

Next.js DevTools MCP技能

Skill by ara.so — Devtools Skills collection.
Expert skill for using
next-devtools-mcp
, a Model Context Protocol (MCP) server that provides Next.js development tools and utilities for AI coding agents. Provides runtime diagnostics, documentation search, browser automation, and development workflow automation for Next.js projects.
ara.so提供的技能 — 开发者工具技能合集。
这是一款用于使用
next-devtools-mcp
的专业技能,
next-devtools-mcp
是一款Model Context Protocol(MCP)服务器,为AI编码Agent提供Next.js开发工具和实用程序。它可为Next.js项目提供运行时诊断、文档搜索、浏览器自动化以及开发工作流自动化功能。

What is next-devtools-mcp?

什么是next-devtools-mcp?

next-devtools-mcp
is an MCP server that gives AI coding agents powerful Next.js development capabilities:
  • Runtime Diagnostics (Next.js 16+): Query running Next.js applications for errors, routes, logs, and real-time state
  • Documentation Search: Access official Next.js docs and knowledge base directly in conversations
  • Browser Automation: Test and verify Next.js pages with Playwright integration
  • Development Workflows: Automated upgrade guides and feature enablement prompts
next-devtools-mcp
是一款MCP服务器,为AI编码Agent提供强大的Next.js开发能力:
  • 运行时诊断(Next.js 16+):查询运行中的Next.js应用的错误、路由、日志和实时状态
  • 文档搜索:在对话中直接访问官方Next.js文档和知识库
  • 浏览器自动化:通过Playwright集成测试和验证Next.js页面
  • 开发工作流:自动化升级指南和功能启用提示

Installation

安装

Quick Install (Recommended)

快速安装(推荐)

Install for all detected AI coding agents in your project:
bash
npx add-mcp next-devtools-mcp@latest
Add
-y
to skip confirmation. Add
-g
for global installation across all projects.
为项目中所有检测到的AI编码Agent安装:
bash
npx add-mcp next-devtools-mcp@latest
添加
-y
可跳过确认步骤,添加
-g
可在所有项目中全局安装。

Manual Installation

手动安装

Add to your MCP client configuration file:
json
{
  "mcpServers": {
    "next-devtools": {
      "command": "npx",
      "args": ["-y", "next-devtools-mcp@latest"]
    }
  }
}
将其添加到你的MCP客户端配置文件中:
json
{
  "mcpServers": {
    "next-devtools": {
      "command": "npx",
      "args": ["-y", "next-devtools-mcp@latest"]
    }
  }
}

Agent-Specific Configuration

特定Agent配置

Claude Code / Claude Desktop:
bash
claude mcp add next-devtools npx next-devtools-mcp@latest
Cursor: Click: Install in Cursor
Or manually:
Cursor Settings
MCP
New MCP Server
Codex:
bash
codex mcp add next-devtools -- npx next-devtools-mcp@latest
For Windows 11, update
.codex/config.toml
:
toml
env = { SystemRoot="C:\\Windows", PROGRAMFILES="C:\\Program Files" }
startup_timeout_ms = 20_000
VS Code / Copilot:
bash
code --add-mcp '{"name":"next-devtools","command":"npx","args":["-y","next-devtools-mcp@latest"]}'
Claude Code / Claude Desktop:
bash
claude mcp add next-devtools npx next-devtools-mcp@latest
Cursor: 点击:在Cursor中安装
或手动操作:
Cursor设置
MCP
新建MCP服务器
Codex:
bash
codex mcp add next-devtools -- npx next-devtools-mcp@latest
对于Windows 11,更新
.codex/config.toml
toml
env = { SystemRoot="C:\\Windows", PROGRAMFILES="C:\\Program Files" }
startup_timeout_ms = 20_000
VS Code / Copilot:
bash
code --add-mcp '{"name":"next-devtools","command":"npx","args":["-y","next-devtools-mcp@latest"]}'

Requirements

要求

  • Node.js v20.19+ (latest maintenance LTS)
  • npm or pnpm
  • For runtime diagnostics: Next.js 16+ dev server running
  • Node.js v20.19+(最新维护版LTS)
  • npm或pnpm
  • 若要使用运行时诊断:需运行Next.js 16+开发服务器

Core Workflow

核心工作流

1. Always Initialize First

1. 始终先初始化

CRITICAL: Call the
init
tool at the start of every Next.js session:
Use the init tool to set up Next.js DevTools context
This establishes proper documentation requirements and context. For automation, add to your agent's configuration:
.claude/CLAUDE.md
or
.cursorrules
:
markdown
When starting work on a Next.js project, ALWAYS call the `init` tool from
next-devtools-mcp FIRST to set up proper context and establish documentation
requirements. Do this automatically without being asked.
至关重要: 在每个Next.js会话开始时调用
init
工具:
使用init工具设置Next.js DevTools上下文
这会建立合适的文档要求和上下文。若要自动化,可将其添加到Agent的配置中:
.claude/CLAUDE.md
.cursorrules
markdown
开始处理Next.js项目时,务必首先调用next-devtools-mcp中的`init`工具,以设置合适的上下文并确立文档要求。无需询问,自动执行此操作。

2. Start Next.js Dev Server (for Runtime Diagnostics)

2. 启动Next.js开发服务器(用于运行时诊断)

For Next.js 16+ projects:
bash
npm run dev
对于Next.js 16+项目:
bash
npm run dev

or

pnpm dev

MCP is enabled by default at `http://localhost:3000/_next/mcp`. The `next-devtools-mcp` server auto-discovers and connects.
pnpm dev

MCP默认在`http://localhost:3000/_next/mcp`启用。`next-devtools-mcp`服务器会自动发现并连接。

MCP Tools Reference

MCP工具参考

init

init

Initialize Next.js DevTools MCP context. Call this first in every session.
typescript
// Tool input schema
{
  project_path?: string  // Optional, defaults to current directory
}
Example prompts:
  • "Use the init tool to set up Next.js DevTools context"
  • "Initialize Next.js DevTools for this project"
What it does:
  • Sets up AI assistant context for Next.js development
  • Establishes documentation-first approach (use
    nextjs_docs
    for all queries)
  • Documents all available tools and workflows
  • Provides best practices checklist
初始化Next.js DevTools MCP上下文。每次会话都要首先调用此工具。
typescript
// 工具输入 schema
{
  project_path?: string  // 可选,默认值为当前目录
}
示例提示:
  • "使用init工具设置Next.js DevTools上下文"
  • "为该项目初始化Next.js DevTools"
功能:
  • 为Next.js开发设置AI助手上下文
  • 确立文档优先的方法(所有查询都使用
    nextjs_docs
  • 记录所有可用工具和工作流
  • 提供最佳实践清单

nextjs_docs

nextjs_docs

Search and retrieve official Next.js documentation.
typescript
// Search for docs
{
  action: "search",
  query: string,           // e.g., "metadata", "generateStaticParams"
  routerType?: "app" | "pages" | "all"  // default: "all"
}

// Get full doc content
{
  action: "get",
  path: string,            // e.g., "/docs/app/api-reference/functions/refresh"
  anchor?: string          // e.g., "usage"
}
Example workflow:
Search Next.js docs for generateMetadata
Agent uses:
  1. nextjs_docs
    with
    action: "search"
    ,
    query: "generateMetadata"
  2. Reviews search results (titles, paths, snippets)
  3. nextjs_docs
    with
    action: "get"
    ,
    path: "/docs/app/api-reference/functions/generate-metadata"
  4. Provides answer based on official documentation
Common searches:
  • "Search Next.js docs for metadata generation"
  • "Find Next.js documentation on generateStaticParams"
  • "Look up middleware configuration in Next.js docs"
  • "Search App Router caching documentation"
搜索并获取官方Next.js文档。
typescript
// 搜索文档
{
  action: "search",
  query: string,           // 例如:"metadata", "generateStaticParams"
  routerType?: "app" | "pages" | "all"  // 默认值:"all"
}

// 获取完整文档内容
{
  action: "get",
  path: string,            // 例如:"/docs/app/api-reference/functions/refresh"
  anchor?: string          // 例如:"usage"
}
示例工作流:
在Next.js文档中搜索generateMetadata
Agent执行步骤:
  1. 使用
    nextjs_docs
    ,参数为
    action: "search"
    ,
    query: "generateMetadata"
  2. 查看搜索结果(标题、路径、片段)
  3. 使用
    nextjs_docs
    ,参数为
    action: "get"
    ,
    path: "/docs/app/api-reference/functions/generate-metadata"
  4. 根据官方文档提供答案
常见搜索场景:
  • "在Next.js文档中搜索元数据生成"
  • "查找Next.js中关于generateStaticParams的文档"
  • "查阅Next.js文档中的中间件配置"
  • "搜索App Router缓存相关文档"

nextjs_index

nextjs_index

Query available runtime diagnostic resources from Next.js 16+ dev server.
typescript
// No input required
{}
Example prompts:
  • "What runtime diagnostics are available?"
  • "Show me what I can query from the dev server"
  • "List available Next.js MCP resources"
Output: List of available resource URIs (errors, routes, logs, etc.)
从Next.js 16+开发服务器查询可用的运行时诊断资源。
typescript
// 无需输入参数
{}
示例提示:
  • "有哪些可用的运行时诊断功能?"
  • "展示我可以从开发服务器查询的内容"
  • "列出可用的Next.js MCP资源"
输出: 可用资源URI列表(错误、路由、日志等)

nextjs_call

nextjs_call

Call a specific runtime diagnostic resource from Next.js 16+ dev server.
typescript
{
  uri: string  // Resource URI from nextjs_index
}
Example workflows:
Check for errors:
Next Devtools, what errors are in my Next.js application?
Agent calls:
nextjs_call
with
uri: "nextjs://errors"
View route structure:
Next Devtools, show me the structure of my routes
Agent calls:
nextjs_call
with
uri: "nextjs://routes"
Check dev server logs:
Next Devtools, what's in the development server logs?
Agent calls:
nextjs_call
with
uri: "nextjs://logs"
Common URIs:
  • nextjs://errors
    - Runtime errors and warnings
  • nextjs://routes
    - App Router route structure
  • nextjs://logs
    - Development server logs
  • nextjs://config
    - Next.js configuration
  • nextjs://env
    - Environment variables
从Next.js 16+开发服务器调用特定的运行时诊断资源。
typescript
{
  uri: string  // 来自nextjs_index的资源URI
}
示例工作流:
检查错误:
Next Devtools,我的Next.js应用中有哪些错误?
Agent调用:
nextjs_call
,参数为
uri: "nextjs://errors"
查看路由结构:
Next Devtools,展示我的路由结构
Agent调用:
nextjs_call
,参数为
uri: "nextjs://routes"
检查开发服务器日志:
Next Devtools,开发服务器日志中有什么内容?
Agent调用:
nextjs_call
,参数为
uri: "nextjs://logs"
常见URI:
  • nextjs://errors
    - 运行时错误和警告
  • nextjs://routes
    - App Router路由结构
  • nextjs://logs
    - 开发服务器日志
  • nextjs://config
    - Next.js配置
  • nextjs://env
    - 环境变量

browser_eval

browser_eval

Automate browser testing with Playwright. Use for verifying pages, testing interactions, and detecting runtime issues.
typescript
// Start browser
{
  action: "start",
  browser?: "chrome" | "firefox" | "webkit" | "msedge",  // default: "chrome"
  headless?: boolean  // default: true
}

// Navigate to URL
{
  action: "navigate",
  url: string
}

// Click element
{
  action: "click",
  selector: string  // CSS selector
}

// Type text
{
  action: "type",
  selector: string,
  text: string
}

// Fill form
{
  action: "fill_form",
  fields: Array<{ selector: string; value: string }>
}

// Execute JavaScript
{
  action: "evaluate",
  script: string
}

// Take screenshot
{
  action: "screenshot",
  path?: string  // default: auto-generated
}

// Get console messages
{
  action: "console_messages"
}

// Close browser
{
  action: "close"
}
Example workflow - Test Next.js page:
Test the homepage at localhost:3000 and take a screenshot
Agent executes:
typescript
// 1. Start browser
{ action: "start", headless: true }

// 2. Navigate
{ action: "navigate", url: "http://localhost:3000" }

// 3. Wait for content
{ action: "evaluate", script: "document.querySelector('h1')?.textContent" }

// 4. Screenshot
{ action: "screenshot" }

// 5. Check for errors
{ action: "console_messages" }

// 6. Clean up
{ action: "close" }
Common patterns:
Verify upgrade (Next.js 15 → 16):
Verify that my app works on localhost:3000 after the upgrade
Test navigation:
Test navigating from home to /about page
Check for hydration errors:
Load the page and check for React hydration errors in the console
Important: For Next.js 16+, prefer
nextjs_index
and
nextjs_call
over
browser_eval
console messages for error detection.
使用Playwright实现浏览器测试自动化。用于验证页面、测试交互以及检测运行时问题。
typescript
// 启动浏览器
{
  action: "start",
  browser?: "chrome" | "firefox" | "webkit" | "msedge",  // 默认值:"chrome"
  headless?: boolean  // 默认值:true
}

// 导航至URL
{
  action: "navigate",
  url: string
}

// 点击元素
{
  action: "click",
  selector: string  // CSS选择器
}

// 输入文本
{
  action: "type",
  selector: string,
  text: string
}

// 填充表单
{
  action: "fill_form",
  fields: Array<{ selector: string; value: string }>
}

// 执行JavaScript
{
  action: "evaluate",
  script: string
}

// 截图
{
  action: "screenshot",
  path?: string  // 默认值:自动生成
}

// 获取控制台消息
{
  action: "console_messages"
}

// 关闭浏览器
{
  action: "close"
}
示例工作流 - 测试Next.js页面:
测试localhost:3000的首页并截图
Agent执行:
typescript
// 1. 启动浏览器
{ action: "start", headless: true }

// 2. 导航
{ action: "navigate", url: "http://localhost:3000" }

// 3. 等待内容加载
{ action: "evaluate", script: "document.querySelector('h1')?.textContent" }

// 4. 截图
{ action: "screenshot" }

// 5. 检查错误
{ action: "console_messages" }

// 6. 清理
{ action: "close" }
常见模式:
验证升级(Next.js 15 → 16):
验证我的应用在升级后能否在localhost:3000正常运行
测试导航:
测试从首页导航至/about页面
检查水合错误:
加载页面并检查控制台中的React水合错误
重要提示: 对于Next.js 16+项目,检测错误时优先使用
nextjs_index
nextjs_call
,而非
browser_eval
控制台消息。

Pre-Configured Prompts

预配置提示

upgrade-nextjs-16

upgrade-nextjs-16

Guide for upgrading from Next.js 15 to Next.js 16.
Help me upgrade my Next.js app to version 16
What it does:
  1. Analyzes current project setup
  2. Updates dependencies in
    package.json
  3. Applies codemods for breaking changes
  4. Updates configuration files
  5. Tests the upgrade with browser verification
从Next.js 15升级到Next.js 16的指南。
帮我将Next.js应用升级到16版本
功能:
  1. 分析当前项目设置
  2. 更新
    package.json
    中的依赖
  3. 应用代码转换以适配破坏性变更
  4. 更新配置文件
  5. 通过浏览器验证测试升级效果

enable-cache-components

enable-cache-components

Enable Cache Components mode in Next.js 16.
Enable Cache Components in my Next.js app
What it does:
  1. Adds
    cache: "components"
    to
    next.config.ts
  2. Migrates components to use
    "use cache"
    directive
  3. Updates data fetching patterns
  4. Provides examples and documentation
在Next.js 16中启用缓存组件模式。
在我的Next.js应用中启用缓存组件
功能:
  1. next.config.ts
    中添加
    cache: "components"
  2. 迁移组件以使用
    "use cache"
    指令
  3. 更新数据获取模式
  4. 提供示例和文档

Knowledge Base Resources

知识库资源

The MCP server includes focused documentation resources automatically available to agents:
Cache Components (12 sections):
  • cache-components://overview
  • cache-components://core-mechanics
  • cache-components://public-caches
  • cache-components://private-caches
  • cache-components://runtime-prefetching
  • cache-components://request-apis
  • cache-components://cache-invalidation
  • cache-components://advanced-patterns
  • cache-components://build-behavior
  • cache-components://error-patterns
  • cache-components://test-patterns
  • cache-components://reference
Migration Guides:
  • nextjs16://migration/beta-to-stable
  • nextjs16://migration/examples
Fundamentals:
  • nextjs-fundamentals://use-client
Resources are loaded on-demand by the agent as needed.
MCP服务器包含聚焦型文档资源,可自动供Agent使用:
缓存组件(12个章节):
  • cache-components://overview
  • cache-components://core-mechanics
  • cache-components://public-caches
  • cache-components://private-caches
  • cache-components://runtime-prefetching
  • cache-components://request-apis
  • cache-components://cache-invalidation
  • cache-components://advanced-patterns
  • cache-components://build-behavior
  • cache-components://error-patterns
  • cache-components://test-patterns
  • cache-components://reference
迁移指南:
  • nextjs16://migration/beta-to-stable
  • nextjs16://migration/examples
基础内容:
  • nextjs-fundamentals://use-client
Agent会根据需要按需加载这些资源。

Real-World Examples

实际案例

Example 1: Debug Runtime Error

案例1:调试运行时错误

User request:
My Next.js app shows a blank page. Help me figure out what's wrong.
Agent workflow:
typescript
// 1. Initialize (if not done)
init({ project_path: "." })

// 2. Check runtime errors
nextjs_call({ uri: "nextjs://errors" })

// Output shows: "ReferenceError: window is not defined at Component.render"

// 3. Search docs for server component issues
nextjs_docs({ 
  action: "search", 
  query: "window is not defined server component" 
})

// 4. Get full doc content
nextjs_docs({ 
  action: "get", 
  path: "/docs/app/building-your-application/rendering/server-components"
})

// 5. Provide solution: Add "use client" directive
用户请求:
我的Next.js应用显示空白页面。帮我找出问题所在。
Agent工作流:
typescript
// 1. 初始化(如果尚未执行)
init({ project_path: "." })

// 2. 检查运行时错误
nextjs_call({ uri: "nextjs://errors" })

// 输出显示:"ReferenceError: window is not defined at Component.render"

// 3. 搜索服务器组件相关问题的文档
nextjs_docs({ 
  action: "search", 
  query: "window is not defined server component" 
})

// 4. 获取完整文档内容
nextjs_docs({ 
  action: "get", 
  path: "/docs/app/building-your-application/rendering/server-components"
})

// 5. 提供解决方案:添加"use client"指令

Example 2: Upgrade to Next.js 16 with Cache Components

案例2:升级到Next.js 16并启用缓存组件

User request:
Upgrade my app to Next.js 16 and enable Cache Components
Agent workflow:
typescript
// 1. Initialize
init({ project_path: "." })

// 2. Use upgrade prompt
// Triggers: upgrade-nextjs-16 prompt
// - Updates package.json
// - Runs codemods
// - Updates config

// 3. Enable Cache Components
// Triggers: enable-cache-components prompt
// - Adds cache: "components" to next.config.ts
// - Shows migration examples

// 4. Verify with browser
browser_eval({ action: "start" })
browser_eval({ action: "navigate", url: "http://localhost:3000" })
browser_eval({ action: "console_messages" })
browser_eval({ action: "screenshot" })
browser_eval({ action: "close" })

// 5. Check runtime state
nextjs_call({ uri: "nextjs://errors" })
用户请求:
将我的应用升级到Next.js 16并启用缓存组件
Agent工作流:
typescript
// 1. 初始化
init({ project_path: "." })

// 2. 使用升级提示
// 触发:upgrade-nextjs-16提示
// - 更新package.json
// - 运行代码转换
// - 更新配置

// 3. 启用缓存组件
// 触发:enable-cache-components提示
// - 在next.config.ts中添加cache: "components"
// - 展示迁移示例

// 4. 通过浏览器验证
browser_eval({ action: "start" })
browser_eval({ action: "navigate", url: "http://localhost:3000" })
browser_eval({ action: "console_messages" })
browser_eval({ action: "screenshot" })
browser_eval({ action: "close" })

// 5. 检查运行时状态
nextjs_call({ uri: "nextjs://errors" })

Example 3: Implement Metadata Generation

案例3:实现元数据生成

User request:
Add proper SEO metadata to my blog post page
Agent workflow:
typescript
// 1. Search docs
nextjs_docs({ 
  action: "search", 
  query: "generateMetadata" 
})

// 2. Get detailed docs
nextjs_docs({ 
  action: "get", 
  path: "/docs/app/api-reference/functions/generate-metadata" 
})

// 3. Implement based on docs
Example implementation:
typescript
// app/blog/[slug]/page.tsx
import { Metadata } from 'next'

interface Props {
  params: { slug: string }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const post = await fetch(`${process.env.API_URL}/posts/${params.slug}`)
    .then(res => res.json())
  
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      images: [{ url: post.image }],
    },
  }
}

export default async function BlogPost({ params }: Props) {
  const post = await fetch(`${process.env.API_URL}/posts/${params.slug}`)
    .then(res => res.json())
  
  return (
    <article>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
    </article>
  )
}
用户请求:
为我的博客文章页面添加合适的SEO元数据
Agent工作流:
typescript
// 1. 搜索文档
nextjs_docs({ 
  action: "search", 
  query: "generateMetadata" 
})

// 2. 获取详细文档
nextjs_docs({ 
  action: "get", 
  path: "/docs/app/api-reference/functions/generate-metadata" 
})

// 3. 根据文档实现
示例实现:
typescript
// app/blog/[slug]/page.tsx
import { Metadata } from 'next'

interface Props {
  params: { slug: string }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const post = await fetch(`${process.env.API_URL}/posts/${params.slug}`)
    .then(res => res.json())
  
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      images: [{ url: post.image }],
    },
  }
}

export default async function BlogPost({ params }: Props) {
  const post = await fetch(`${process.env.API_URL}/posts/${params.slug}`)
    .then(res => res.json())
  
  return (
    <article>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
    </article>
  )
}

Example 4: Migrate to Cache Components

案例4:迁移到缓存组件

User request:
Convert my data fetching component to use Cache Components
Before (traditional approach):
typescript
// app/posts/page.tsx
export const revalidate = 3600

export default async function PostsPage() {
  const posts = await fetch('https://api.example.com/posts')
    .then(res => res.json())
  
  return (
    <div>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
        </article>
      ))}
    </div>
  )
}
Agent searches docs:
typescript
nextjs_docs({ 
  action: "search", 
  query: "use cache directive" 
})

// Then gets resource
// (agent has cache-components://core-mechanics available)
After (Cache Components):
typescript
// app/posts/page.tsx
import { Posts } from './Posts'

export default function PostsPage() {
  return <Posts />
}

// app/posts/Posts.tsx
"use cache"
export const revalidate = 3600

export async function Posts() {
  const posts = await fetch('https://api.example.com/posts')
    .then(res => res.json())
  
  return (
    <div>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
        </article>
      ))}
    </div>
  )
}
用户请求:
将我的数据获取组件转换为使用缓存组件
转换前(传统方式):
typescript
// app/posts/page.tsx
export const revalidate = 3600

export default async function PostsPage() {
  const posts = await fetch('https://api.example.com/posts')
    .then(res => res.json())
  
  return (
    <div>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
        </article>
      ))}
    </div>
  )
}
Agent搜索文档:
typescript
nextjs_docs({ 
  action: "search", 
  query: "use cache directive" 
})

// 然后获取资源
// (Agent可访问cache-components://core-mechanics)
转换后(缓存组件方式):
typescript
// app/posts/page.tsx
import { Posts } from './Posts'

export default function PostsPage() {
  return <Posts />
}

// app/posts/Posts.tsx
"use cache"
export const revalidate = 3600

export async function Posts() {
  const posts = await fetch('https://api.example.com/posts')
    .then(res => res.json())
  
  return (
    <div>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
        </article>
      ))}
    </div>
  )
}

Configuration Patterns

配置模式

next.config.ts with Cache Components

带有缓存组件的next.config.ts

typescript
import type { NextConfig } from 'next'

const config: NextConfig = {
  experimental: {
    cache: 'components',  // Enable Cache Components
  },
}

export default config
typescript
import type { NextConfig } from 'next'

const config: NextConfig = {
  experimental: {
    cache: 'components',  // 启用缓存组件
  },
}

export default config

Environment Variables

环境变量

Use environment variables for API keys and sensitive data:
bash
undefined
使用环境变量存储API密钥和敏感数据:
bash
undefined

.env.local

.env.local

API_URL=https://api.example.com NEXTAUTH_SECRET=your-secret-here NEXTAUTH_URL=http://localhost:3000

Access in code:
```typescript
const apiUrl = process.env.API_URL
const secret = process.env.NEXTAUTH_SECRET
API_URL=https://api.example.com NEXTAUTH_SECRET=your-secret-here NEXTAUTH_URL=http://localhost:3000

在代码中访问:
```typescript
const apiUrl = process.env.API_URL
const secret = process.env.NEXTAUTH_SECRET

MCP Auto-Discovery

MCP自动发现

Next.js 16+ automatically enables MCP at:
http://localhost:{PORT}/_next/mcp
No configuration needed. The
next-devtools-mcp
server discovers it automatically.
Next.js 16+会自动在以下地址启用MCP:
http://localhost:{PORT}/_next/mcp
无需额外配置。
next-devtools-mcp
服务器会自动发现该地址。

Troubleshooting

故障排除

Issue: Runtime diagnostics not available

问题:运行时诊断不可用

Symptoms:
nextjs_index
returns empty or
nextjs_call
fails
Solution:
  1. Verify Next.js 16+ is installed:
    npm list next
  2. Ensure dev server is running:
    npm run dev
  3. Check dev server logs for MCP endpoint
  4. Verify port (default 3000, check
    next.config.ts
    for custom port)
症状:
nextjs_index
返回空结果或
nextjs_call
调用失败
解决方案:
  1. 验证是否安装了Next.js 16+:
    npm list next
  2. 确保开发服务器正在运行:
    npm run dev
  3. 检查开发服务器日志中的MCP端点
  4. 验证端口(默认3000,可在
    next.config.ts
    中查看自定义端口)

Issue: Documentation search returns no results

问题:文档搜索无结果

Symptoms:
nextjs_docs
with
action: "search"
returns empty
Solution:
  1. Try broader search terms (e.g., "metadata" instead of "generateMetadata function")
  2. Check spelling
  3. Try
    routerType: "all"
    to search both App and Pages Router docs
  4. Use multiple searches for complex topics
症状: 使用
nextjs_docs
action: "search"
返回空结果
解决方案:
  1. 尝试更宽泛的搜索词(例如用"metadata"代替"generateMetadata function")
  2. 检查拼写是否正确
  3. 尝试设置
    routerType: "all"
    以同时搜索App Router和Pages Router文档
  4. 针对复杂主题进行多次搜索

Issue: Browser automation fails on first run

问题:首次运行浏览器自动化失败

Symptoms:
browser_eval
with
action: "start"
times out
Solution:
  1. Playwright installs browsers on first run (this is automatic but takes time)
  2. Increase timeout expectations for first use
  3. On Windows 11 with Codex, ensure environment variables are set in
    .codex/config.toml
  4. Run manually once:
    npx playwright install chromium
症状: 使用
browser_eval
action: "start"
超时
解决方案:
  1. Playwright会在首次运行时安装浏览器(此过程自动进行但需要时间)
  2. 提高首次使用的超时预期
  3. 在Windows 11搭配Codex使用时,确保
    .codex/config.toml
    中已设置环境变量
  4. 手动运行一次:
    npx playwright install chromium

Issue: Init tool not being called

问题:未调用Init工具

Symptoms: Agent doesn't use Next.js docs properly, context is missing
Solution:
  1. Explicitly prompt: "Use the init tool to set up Next.js DevTools context"
  2. Add auto-init instruction to agent config (see Core Workflow section)
  3. Verify MCP server is connected (check agent's MCP status)
症状: Agent无法正确使用Next.js文档,缺少上下文
解决方案:
  1. 明确提示:"使用init工具设置Next.js DevTools上下文"
  2. 将自动初始化指令添加到Agent配置中(参见核心工作流章节)
  3. 验证MCP服务器已连接(检查Agent的MCP状态)

Issue: Upgrade prompt makes incorrect changes

问题:升级提示做出错误变更

Symptoms: Breaking changes after running upgrade-nextjs-16 prompt
Solution:
  1. Always commit code before running upgrades
  2. Review changes made by codemods
  3. Use
    nextjs_docs
    to verify migration patterns
  4. Test with
    browser_eval
    before deploying
  5. Check
    nextjs://errors
    for runtime issues
症状: 运行upgrade-nextjs-16提示后出现破坏性变更
解决方案:
  1. 运行升级前务必提交代码
  2. 查看代码转换所做的变更
  3. 使用
    nextjs_docs
    验证迁移模式
  4. 部署前使用
    browser_eval
    进行测试
  5. 检查
    nextjs://errors
    中的运行时问题

Best Practices

最佳实践

1. Documentation-First Approach

1. 文档优先方法

Always use
nextjs_docs
before implementing Next.js features:
typescript
// Search first
nextjs_docs({ action: "search", query: "feature-name" })

// Get detailed docs
nextjs_docs({ action: "get", path: "/docs/..." })

// Then implement based on official documentation
始终在实现Next.js功能前使用
nextjs_docs
typescript
// 先搜索
nextjs_docs({ action: "search", query: "feature-name" })

// 获取详细文档
nextjs_docs({ action: "get", path: "/docs/..." })

// 然后根据官方文档实现

2. Runtime Diagnostics Over Browser Console

2. 优先使用运行时诊断而非浏览器控制台

For Next.js 16+ projects, prefer built-in diagnostics:
typescript
// ✅ Preferred
nextjs_call({ uri: "nextjs://errors" })

// ❌ Avoid when above is available
browser_eval({ action: "console_messages" })
Browser automation is still valuable for visual verification and interaction testing.
对于Next.js 16+项目,优先使用内置诊断功能:
typescript
// ✅ 推荐方式
nextjs_call({ uri: "nextjs://errors" })

// ❌ 当上述方式可用时避免使用
browser_eval({ action: "console_messages" })
浏览器自动化仍适用于视觉验证和交互测试。

3. Initialize Every Session

3. 每次会话都初始化

Make
init
the first tool call:
typescript
// At start of every Next.js session
init({ project_path: "." })
Or automate with agent configuration (see Core Workflow).
init
作为第一个工具调用:
typescript
// 在每个Next.js会话开始时
init({ project_path: "." })
或通过Agent配置实现自动化(参见核心工作流章节)。

4. Two-Step Documentation Workflow

4. 两步式文档工作流

Don't skip the search step:
typescript
// Step 1: Search to find relevant docs
nextjs_docs({ action: "search", query: "..." })

// Step 2: Get full content from search results
nextjs_docs({ action: "get", path: "..." })
This ensures you get the most relevant and up-to-date documentation.
不要跳过搜索步骤:
typescript
// 步骤1:搜索以找到相关文档
nextjs_docs({ action: "search", query: "..." })

// 步骤2:从搜索结果中获取完整内容
nextjs_docs({ action: "get", path: "..." })
这可确保你获取最相关且最新的文档。

5. Verify Changes with Multiple Tools

5. 使用多种工具验证变更

After making changes, use a combination:
typescript
// 1. Check runtime errors
nextjs_call({ uri: "nextjs://errors" })

// 2. Visual verification
browser_eval({ action: "start" })
browser_eval({ action: "navigate", url: "http://localhost:3000" })
browser_eval({ action: "screenshot" })
browser_eval({ action: "close" })

// 3. Check routes structure
nextjs_call({ uri: "nextjs://routes" })
做出变更后,组合使用多种工具:
typescript
// 1. 检查运行时错误
nextjs_call({ uri: "nextjs://errors" })

// 2. 视觉验证
browser_eval({ action: "start" })
browser_eval({ action: "navigate", url: "http://localhost:3000" })
browser_eval({ action: "screenshot" })
browser_eval({ action: "close" })

// 3. 检查路由结构
nextjs_call({ uri: "nextjs://routes" })

Common User Prompts

常见用户提示

Recognize and handle these user requests:
  • "Help me debug my Next.js app" → Use
    nextjs_call
    for errors
  • "Upgrade to Next.js 16" → Use upgrade-nextjs-16 prompt
  • "Enable Cache Components" → Use enable-cache-components prompt
  • "Search Next.js docs for X" → Use
    nextjs_docs
    two-step workflow
  • "Test my page at localhost:3000" → Use
    browser_eval
    workflow
  • "What errors are showing?" → Use
    nextjs_call
    with
    nextjs://errors
  • "Show my routes" → Use
    nextjs_call
    with
    nextjs://routes
  • "Check the dev server logs" → Use
    nextjs_call
    with
    nextjs://logs
  • "Add metadata to my page" → Search docs, then implement
    generateMetadata
  • "How do I configure X in Next.js?" → Use
    nextjs_docs
    to find config docs
识别并处理以下用户请求:
  • "帮我调试我的Next.js应用" → 使用
    nextjs_call
    检查错误
  • "升级到Next.js 16" → 使用upgrade-nextjs-16提示
  • "启用缓存组件" → 使用enable-cache-components提示
  • "在Next.js文档中搜索X" → 使用
    nextjs_docs
    两步式工作流
  • "测试我在localhost:3000的页面" → 使用
    browser_eval
    工作流
  • "显示有哪些错误?" → 使用
    nextjs_call
    ,参数为
    nextjs://errors
  • "展示我的路由" → 使用
    nextjs_call
    ,参数为
    nextjs://routes
  • "检查开发服务器日志" → 使用
    nextjs_call
    ,参数为
    nextjs://logs
  • "为我的页面添加元数据" → 搜索文档,然后实现
    generateMetadata
  • "如何在Next.js中配置X?" → 使用
    nextjs_docs
    查找配置文档

Summary

总结

The
next-devtools-mcp
skill enables AI coding agents to:
  1. Initialize properly with the
    init
    tool (critical first step)
  2. Access official Next.js documentation on-demand with
    nextjs_docs
  3. Query runtime diagnostics from Next.js 16+ dev servers with
    nextjs_index
    and
    nextjs_call
  4. Automate browser testing with
    browser_eval
    using Playwright
  5. Execute complex workflows like upgrades and migrations with pre-configured prompts
  6. Access knowledge base resources for Cache Components, migrations, and fundamentals
Always prioritize documentation lookup over assumptions, verify changes with runtime diagnostics, and test thoroughly with browser automation.
next-devtools-mcp
技能使AI编码Agent能够:
  1. 正确初始化:使用
    init
    工具(关键的第一步)
  2. 按需访问官方Next.js文档:使用
    nextjs_docs
  3. 查询Next.js 16+开发服务器的运行时诊断信息:使用
    nextjs_index
    nextjs_call
  4. 实现浏览器测试自动化:使用
    browser_eval
    和Playwright
  5. 执行复杂工作流:如升级和迁移,使用预配置提示
  6. 访问知识库资源:包括缓存组件、迁移和基础内容相关资源
始终优先查阅文档而非凭经验假设,使用运行时诊断验证变更,并通过浏览器自动化进行全面测试。