@ai-mapping/mcp-nextjs-dev
Version:
MCP server for managing Next.js development processes with AI tools
241 lines (186 loc) • 8.42 kB
Markdown
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## 🚨 IMPORTANT: Building From Scratch
**THIS IS A NEW PROJECT BEING BUILT FROM SCRATCH**. Currently initialized with:
- Git repository initialized on `master` branch
- Basic package.json created with project name `@ai-mapping/mcp-nextjs-dev`
- Remote repository set to: `git@github.com:ai-mapping/mcp-nextjs-dev.git`
**PRIMARY INSTRUCTION**: Always refer to `CLAUDE.local.md` for the complete technical specification and implementation details. That file contains the authoritative development instructions for building this MCP server from the ground up.
### Current Project Status
- ✅ Git repository initialized
- ✅ package.json created (needs updating per CLAUDE.local.md spec)
- ✅ Development plan created (see DEVELOPMENT_PLAN.md)
- ✅ Progress tracking established (see PROGRESS.md)
- ✅ TypeScript configuration created
- ✅ Core MCP server implemented (Stage 2 complete)
- ✅ Dependencies installed
### Development Tracking
- **DEVELOPMENT_PLAN.md**: Comprehensive task list and milestones
- **PROGRESS.md**: Quick status check and current focus
- Check these files at the start of each session to continue where we left off
- **IMPORTANT**: Keep all development plans in @DEVELOPMENT_PLAN.md and update it as per the progress
## Project Overview
This is a Model Context Protocol (MCP) server that solves Claude Code's limitation with long-running Next.js development processes. It enables AI assistants to start Next.js development servers in the background and access their real-time logs without blocking.
**Key Problem Solved**: When Claude Code runs `npm run dev`, the process doesn't terminate, causing it to hang indefinitely. This MCP server provides asynchronous tools to manage Next.js processes independently.
## Development Workflow
### Our Development Process
We follow a structured, iterative development workflow that ensures quality and maintainability:
1. **Small, Testable Steps**: Develop the project following the implementation plan split into small, testable, and manually reviewable steps
2. **Verification at Each Step**: Each completed step must be:
- ✅ Tested (functionality works as expected)
- ✅ Type-checked (TypeScript compilation passes)
- ✅ Lint tested (code style compliance)
- ✅ Documented in CLAUDE.md
- ✅ Git committed with clear message
- ✅ Passed to developer for manual testing and review
3. **Flexibility in Implementation**: While CLAUDE.local.md specifies the main instruction and core architecture, during development and testing we may find better, simpler, or just working solutions that differ from the spec. This is acceptable as long as we're still moving toward the project goal.
4. **Push After Review**: If manual review passes successfully, changes should be pushed to GitHub
5. **Update README**: After implementing steps that bring major changes or significant development progress, update README.md to reflect the current state
### Implementation Plan
Since this is a new project, follow these steps to build it:
1. **Read CLAUDE.local.md**: This contains the complete technical specification
2. **Update package.json**: Update it based on the spec in CLAUDE.local.md (lines 38-72)
3. **Set up TypeScript**: Configure tsconfig.json for Node.js 22+ with ESM
4. **Create project structure**: Follow the directory structure in CLAUDE.local.md (lines 421-457)
5. **Implement core components**: Follow the architecture defined in CLAUDE.local.md
6. **Test with MCP Inspector**: Verify each tool works correctly
### Next Steps for Implementation
1. Update package.json with proper dependencies, scripts, and metadata
2. Create tsconfig.json for TypeScript configuration
3. Create the source directory structure
4. Implement the MCP server core with the 4 tools specified
5. Add proper error handling and logging
6. Test with MCP Inspector
### Package Manager
This project uses **pnpm v10** as its package manager. Make sure you have pnpm v10 installed:
```bash
# Check pnpm version
pnpm --version
# Install dependencies
pnpm install
```
### Development Checklist Template
For each development step, ensure:
- [ ] Code implemented and working
- [ ] TypeScript compiles without errors
- [ ] Linting passes (when configured)
- [ ] Manual testing completed
- [ ] CLAUDE.md updated if needed
- [ ] Git commit with descriptive message
- [ ] Manual review approved
- [ ] Changes pushed to GitHub (after approval)
## Essential Commands (After Project Setup)
### Development
```bash
# Install dependencies
pnpm install
# Build TypeScript
pnpm run build
# Run in development mode with watch
pnpm run dev
# Start the MCP server (after build)
node dist/bin/cli.js
# Test with MCP Inspector
pnpm dlx @modelcontextprotocol/inspector pnpm dlx .
```
### Testing
```bash
# Run unit tests
pnpm test
# Run specific test file
pnpm test -- src/tools/dev-start.test.ts
# Manual testing with debug mode
DEBUG=1 node dist/bin/cli.js --debug
# Test MCP protocol compliance
pnpm dlx @modelcontextprotocol/inspector pnpm dlx .
```
### Linting & Type Checking
```bash
# Run TypeScript type checking
pnpm run typecheck
# Run ESLint
pnpm run lint
# Fix linting issues
pnpm run lint:fix
```
## Architecture & Key Concepts
### MCP Server Structure
The project uses the official `@modelcontextprotocol/sdk` with a simplified architecture:
- **McpServer**: Core server handling JSON-RPC 2.0 protocol
- **StdioServerTransport**: Communication layer for Claude Code integration
- **Tool Registration**: Each tool is registered with Zod schemas for validation
### Core Components
1. **Process Manager** (`src/managers/process-manager.ts`)
- Manages single Next.js dev server lifecycle
- Uses `child_process.spawn()` for non-blocking execution
- Handles graceful shutdown and cleanup
2. **Log Collector** (`src/managers/log-collector.ts`)
- Captures stdout/stderr from Next.js process
- Maintains circular buffer (max 1000 entries)
- Provides filtering by level, content, and time
3. **MCP Tools** (`src/tools/`)
- `nextjs_dev_start`: Starts dev server asynchronously
- `nextjs_get_logs`: Retrieves filtered logs
- `nextjs_get_status`: Checks server status
- `nextjs_stop_server`: Stops server gracefully
### State Management
Single global state object tracks:
- Process status (running/stopped)
- Server configuration (port, URL)
- Log entries in memory
- Process metadata
## Important Implementation Details
### Tool Response Format
All tools return JSON responses formatted for AI consumption:
```typescript
{
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}],
isError?: boolean // Set to true for errors
}
```
### Process Management Rules
- Only one Next.js process per MCP server instance
- Processes are spawned with `detached: false` for proper cleanup
- SIGTERM for graceful shutdown, SIGKILL after timeout
- Always validate project paths to prevent directory traversal
### Log Level Detection
Logs are automatically categorized based on content:
- "error" or "failed" → error level
- "warn" or "warning" → warn level
- Everything else → info level
## Development Workflow
When implementing new features:
1. Check the technical specification in `CLAUDE.local.md`
2. Follow the established patterns in existing tools
3. Use Zod for parameter validation
4. Return structured JSON responses
5. Handle errors with proper error responses
6. Add debug logging when `DEBUG=1`
## Testing Strategy
### Manual Testing Steps
1. Build the project: `npm run build`
2. Start server with debug: `DEBUG=1 node dist/bin/cli.js --debug`
3. Use MCP Inspector to test each tool
4. Verify Next.js process actually starts/stops
5. Check log collection and filtering
### Integration Testing
Test with actual Claude Code by adding to `claude_desktop_config.json`:
```json
{
"mcpServers": {
"nextjs-dev": {
"command": "node",
"args": ["/path/to/dist/bin/cli.js"],
"cwd": "."
}
}
}
```
## Common Issues & Solutions
1. **Port Already in Use**: Check and kill existing processes on the port
2. **Process Not Cleaning Up**: Ensure proper signal handlers are registered
3. **Logs Not Captured**: Verify stdio pipes are configured correctly
4. **Zod Validation Errors**: Check parameter types match schema definitions