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
84 changes: 83 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,15 @@ npm run dev

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.

**Try these prompts in your coding agent:**
**⚠️ IMPORTANT: Start every Next.js session by calling the `init` tool to set up proper context:**

```
Use the init tool to set up Next.js DevTools context
```

This initializes the MCP context and ensures the AI assistant uses official Next.js documentation for all queries.

**After initialization, try these prompts to explore runtime diagnostics:**

```
Next Devtools, what errors are in my Next.js application?
Expand Down Expand Up @@ -236,6 +244,54 @@ Next Devtools, enable Cache Components in my Next.js app
Next Devtools, search Next.js docs for generateMetadata
```

### 💡 Pro Tip: Auto-Initialize on Every Session

To make your AI assistant **automatically call the `init` tool** at the start of every Next.js session without being asked, add this instruction to your agent's configuration file:

<details>
<summary>Claude Code / Claude Desktop</summary>

Add to `~/.claude/CLAUDE.md` (global) or `./.claude/CLAUDE.md` (project-specific):

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

</details>

<details>
<summary>Cursor</summary>

Add to `.cursorrules` in your project root or global Cursor settings:

```
When working with Next.js, always call the init tool from next-devtools-mcp
at the start of the session to establish proper context and documentation requirements.
```

</details>

<details>
<summary>Codex / Other AI Coding Assistants</summary>

Add to your agent's configuration file (e.g., `.codex/instructions.md`, `agent.md`, or similar):

```markdown
**Next.js Initialization**: When starting work on a Next.js project, automatically
call the `init` tool from the next-devtools-mcp server FIRST. This establishes
proper context and ensures all Next.js queries use official documentation.
```

</details>

**Why this matters:**
- ✅ Ensures consistent context across all Next.js work
- ✅ Automatically establishes the documentation-first requirement
- ✅ No need to manually call init every time
- ✅ Works across all your Next.js projects

## MCP Resources

Next.js 16 knowledge base resources are automatically available to your coding agent.
Expand Down Expand Up @@ -269,13 +325,39 @@ Pre-configured prompts to help with common Next.js development tasks:
<details>
<summary>💡 Available Prompts (click to expand)</summary>

- **`init`** - Initialize context for Next.js development with MCP tools and documentation requirements
- **`upgrade-nextjs-16`** - Guide for upgrading to Next.js 16
- **`enable-cache-components`** - Enable caching for React components

</details>

## MCP Tools

<details>
<summary><code>init</code></summary>

Initialize Next.js DevTools MCP context and establish documentation requirements.

**Capabilities:**
- Sets up proper context for AI assistants working with Next.js
- Establishes requirement to use `nextjs_docs` for ALL Next.js-related queries
- Documents all available MCP tools and their use cases
- Provides best practices for Next.js development with MCP
- Includes example workflows and quick start checklist

**When to use:**
- At the beginning of a Next.js development session
- To understand available tools and establish proper context
- To ensure documentation-first approach for Next.js development

**Input:**
- `project_path` (optional) - Path to Next.js project (defaults to current directory)

**Output:**
- Comprehensive initialization context and guidance for Next.js development with MCP tools

</details>

<details>
<summary><code>nextjs_docs</code></summary>

Expand Down
32 changes: 32 additions & 0 deletions src/_internal/global-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Global state for the MCP server
* Tracks initialization status and other server-wide state
*/

interface GlobalState {
initCalled: boolean
initTimestamp: number | null
}

const globalState: GlobalState = {
initCalled: false,
initTimestamp: null,
}

export function markInitCalled(): void {
globalState.initCalled = true
globalState.initTimestamp = Date.now()
}

export function isInitCalled(): boolean {
return globalState.initCalled
}

export function getInitTimestamp(): number | null {
return globalState.initTimestamp
}

export function resetGlobalState(): void {
globalState.initCalled = false
globalState.initTimestamp = null
}
235 changes: 235 additions & 0 deletions src/tools/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
import { type InferSchema } from "xmcp"
import { z } from "zod"
import { markInitCalled } from "../_internal/global-state"

export const schema = {
project_path: z
.string()
.optional()
.describe("Path to the Next.js project (defaults to current directory)"),
}

export const metadata = {
name: "init",
description: `⚠️ CALL THIS FIRST - Initialize Next.js DevTools MCP context and establish MANDATORY documentation requirements.

**IMPORTANT: This tool MUST be called at the START of every Next.js development session.**

This tool fetches the latest Next.js documentation and establishes ABSOLUTE requirements for using the nextjs_docs tool for ALL Next.js-related queries.

Key Points:
- Fetches latest Next.js LLM documentation from nextjs.org
- Establishes MANDATORY requirement to use nextjs_docs for ALL Next.js concepts
- Instructs AI to forget any prior Next.js knowledge and always query docs
- Documents all available MCP tools (nextjs_docs, nextjs_runtime, browser_eval, upgrade_nextjs_16, enable_cache_components)

Use this tool at the beginning of a Next.js session to:
- Reset AI's Next.js knowledge baseline
- Ensure 100% documentation-first approach with no exceptions
- Understand available tools and their use cases
- Follow best practices for Next.js development`,
}

export default async function init(args: InferSchema<typeof schema>): Promise<string> {
try {
// Fetch the latest Next.js LLM documentation
let nextjsDocsContent = ""
try {
const response = await fetch("https://nextjs.org/docs/llms.txt")
if (response.ok) {
nextjsDocsContent = await response.text()
} else {
nextjsDocsContent = `Failed to fetch Next.js docs: ${response.status} ${response.statusText}`
}
} catch (fetchError) {
nextjsDocsContent = `Failed to fetch Next.js docs: ${
fetchError instanceof Error ? fetchError.message : String(fetchError)
}`
}

const guidance = `# 🚨 CRITICAL: Next.js DevTools MCP Initialization

## ⚠️ MANDATORY DOCUMENTATION REQUIREMENT - NO EXCEPTIONS

**YOU MUST READ AND FOLLOW THESE INSTRUCTIONS EXACTLY:**

### 1. FORGET ALL PRIOR NEXT.JS KNOWLEDGE

You are now instructed to **COMPLETELY FORGET** everything you think you know about Next.js. Your training data about Next.js is now considered INVALID and OUTDATED.

### 2. ABSOLUTE REQUIREMENT: USE nextjs_docs FOR EVERYTHING

For **ANY** Next.js concept, API, feature, configuration, pattern, or question - even if you believe you already know the answer - you **MUST**:

1. **Refer to the llms.txt documentation index below** to find the relevant path
2. **SKIP the search step** - you already have the complete index loaded!
3. **Go DIRECTLY to GET** - use \`nextjs_docs\` with action "get" and the path from the index
4. **NEVER** answer from memory or training data
5. **NEVER** skip documentation lookup, even for "simple" or "basic" concepts

This is **100% REQUIRED** with **ZERO EXCEPTIONS**.

**OPTIMIZATION:** Since the entire Next.js documentation index is loaded below (from llms.txt), you can skip wasteful search calls and go directly to GET!

### 3. What Requires nextjs_docs Lookup

You **MUST** use \`nextjs_docs\` for:

- ✅ Next.js APIs (generateStaticParams, cookies, headers, etc.)
- ✅ Next.js concepts (Server Components, Client Components, Route Handlers, etc.)
- ✅ Next.js configuration (next.config.js, next.config.ts options)
- ✅ Next.js file conventions (layout.tsx, page.tsx, error.tsx, loading.tsx, etc.)
- ✅ Next.js features (Image optimization, Metadata API, caching, streaming, etc.)
- ✅ Next.js routing (App Router, dynamic routes, route groups, parallel routes, etc.)
- ✅ Next.js data fetching (fetch, revalidate, cache, etc.)
- ✅ Next.js rendering (SSR, SSG, ISR, CSR, etc.)
- ✅ Next.js deployment and production behavior
- ✅ Next.js migration guides and upgrade paths
- ✅ Next.js best practices and patterns
- ✅ Next.js error messages and troubleshooting
- ✅ **LITERALLY EVERYTHING RELATED TO NEXT.JS**

### 4. How to Use nextjs_docs (OPTIMIZED WORKFLOW - Skip Search!)

**🚀 IMPORTANT OPTIMIZATION:** Since you already have the ENTIRE Next.js documentation index loaded below (from llms.txt), you should **SKIP the search step** and go **DIRECTLY to GET**!

**The Optimized Workflow:**

1. **Refer to the llms.txt content below** to find the relevant documentation path
2. **Call nextjs_docs with GET directly** - no search needed!
3. **Answer based on the retrieved full documentation**

**Direct GET call (preferred):**
\`\`\`
nextjs_docs({ action: "get", path: "/docs/app/api-reference/functions/generate-static-params" })
\`\`\`

**Only use search as a fallback** if you cannot find the exact path in the llms.txt index below:
\`\`\`
nextjs_docs({ action: "search", query: "your search term" })
\`\`\`

### 5. Example: The ONLY Correct Way to Answer Next.js Questions

**❌ WRONG (DO NOT DO THIS):**
\`\`\`
User: "How do I use generateStaticParams?"
You: "Based on my knowledge, generateStaticParams is used to..."
\`\`\`

**❌ ALSO WRONG (Wasteful - doing unnecessary search when you have the index):**
\`\`\`
User: "How do I use generateStaticParams?"
You: [Wastes time calling search when index is already loaded]
nextjs_docs({ action: "search", query: "generateStaticParams" })
[Then calls get]
nextjs_docs({ action: "get", path: "..." })
\`\`\`

**✅ CORRECT (ALWAYS DO THIS - Direct GET):**
\`\`\`
User: "How do I use generateStaticParams?"
You: [Checks the llms.txt index below]
[Found it! Path is /docs/app/api-reference/functions/generate-static-params]
[Goes directly to GET - skips wasteful search!]
nextjs_docs({ action: "get", path: "/docs/app/api-reference/functions/generate-static-params" })
[Answers based on retrieved documentation]
\`\`\`

### 6. Why This Is Non-Negotiable

- ✅ Ensures 100% accuracy from official Next.js documentation
- ✅ Prevents hallucinations and outdated information
- ✅ Guarantees latest API patterns and best practices
- ✅ Provides official examples directly from Next.js team
- ✅ Accounts for frequent Next.js updates and changes

---

## 📚 Complete Next.js Documentation Index (from llms.txt)

The following is the **COMPLETE** Next.js documentation index fetched from https://nextjs.org/docs/llms.txt:

\`\`\`
${nextjsDocsContent}
\`\`\`

**IMPORTANT:** This index above contains ALL Next.js documentation paths. When you need documentation:
1. **Search this index above** for the relevant path
2. **Call nextjs_docs with GET directly** using the path you found
3. **Skip the search step** - you already have the complete index!

You MUST still use the \`nextjs_docs\` tool with GET to retrieve the full detailed documentation for any Next.js concept - but you can skip the search step since the index is right here!

---

## 🛠️ Available MCP Tools

### 1. **nextjs_docs** (MANDATORY FOR ALL NEXT.JS QUERIES)
- **Get** full docs (preferred): \`{ action: "get", path: "..." }\` ← Use this! Refer to the llms.txt index above for paths
- **Search** documentation (fallback only): \`{ action: "search", query: "..." }\` ← Only if you can't find the path in the index
- **REQUIRED** for ALL Next.js-related questions
- **OPTIMIZATION:** Skip search and go directly to GET since you have the complete index loaded above!

### 2. **nextjs_runtime** - Live Next.js Dev Server Integration
- Get real-time errors and logs from running dev server
- Inspect routes, components, and runtime diagnostics
- Requires Next.js 16+ (or experimental.mcpServer in older versions)

### 3. **browser_eval** - Browser Automation
- Test Next.js pages with Playwright
- Verify functionality and capture runtime errors
- Use after implementing features to verify behavior

### 4. **upgrade_nextjs_16** - Next.js 16 Upgrade Guide
- Complete upgrade workflow from Next.js 15 (or earlier) to 16
- Handles breaking changes, codemods, and migration

### 5. **enable_cache_components** - Cache Components Setup
- Enable and configure Cache Components (Next.js 16+)
- Error detection, fixing, and best practices

---

## 🎯 Workflow Summary

1. **ALWAYS** start by calling this \`init\` tool
2. **ALWAYS** use \`nextjs_docs\` with GET (not search!) for ANY Next.js concept (even if you think you know it)
- Refer to the llms.txt index above to find the path
- Skip the search step - go directly to GET!
3. Use \`nextjs_runtime\` for debugging running applications
4. Use \`browser_eval\` to verify implementations
5. Use specialized tools (\`upgrade_nextjs_16\`, \`enable_cache_components\`) as needed

---

## ⚡ Remember: DOCUMENTATION FIRST, ALWAYS

**THE GOLDEN RULE:** Your training data about Next.js is now invalid. You MUST use \`nextjs_docs\` with GET for every single Next.js-related query, concept, or implementation. No exceptions. No shortcuts. No answering from memory.

**THE OPTIMIZATION RULE:** Since you have the complete llms.txt index loaded above, SKIP the search step and go DIRECTLY to GET. Find the path in the index above, then call GET immediately. This is faster and more efficient!

🚀 Next.js DevTools MCP Initialized Successfully!
`

// Mark that init has been called
markInitCalled()

return JSON.stringify({
success: true,
description: "Next.js DevTools MCP Initialization",
guidance,
critical_requirement:
"MANDATORY: Use nextjs_docs for ALL Next.js concepts. Forget all prior Next.js knowledge. Documentation lookup is 100% REQUIRED with ZERO exceptions.",
ai_response_instruction:
"⚠️ DO NOT summarize or explain this initialization. Simply respond with: 'Initialization complete.' Nothing more.",
})
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
return JSON.stringify({
success: false,
error: errorMessage,
details: "Failed to load initialization context",
})
}
}
Loading