Cursor × Claude Code Integration Guide
Modern AI-native development combines the strengths of specialized tools. Cursor editor and Claude Code CLI each bring unique capabilities to the table. When used together strategically, they create a development experience that transcends what either tool could achieve alone. This guide explores how to leverage both tools effectively and establish workflows that maximize productivity.
What is Cursor?
Cursor is an AI-native code editor built on VS Code. It's not simply VS Code with an AI plugin—AI is baked into the core of the editor itself.
Key Features:
- AI-powered code completion — Contextual predictions as you type
- Chat within code — Ask questions and get answers without leaving the editor
- Command mode — Use
Cmd+Kto instruct AI to modify code - VS Code compatibility — All extensions and keybindings work seamlessly
- Claude Sonnet built-in — The powerful Claude 3.5 Sonnet is the default model
- Per-file context — AI understands the current file deeply and instantly
Cursor excels at localized, focused editing: UI refinement, bug fixes, logic adjustments, and interactive coding sessions. It's designed for sprints of concentrated work on specific components or functions.
Why Combine Claude Code with Cursor?
While Cursor is powerful on its own, adding Claude Code CLI extends your toolkit to handle larger project scopes and architectural changes.
Claude Code's Strengths:
- Grasps entire project context at once
- Makes coordinated changes across many files
- Creates, runs, and interprets test suites
- Handles Git operations and PR workflows
- Discovers patterns and opportunities across the codebase
- Generates complete feature scaffolds from scratch
Cursor's Strengths:
- Rapid iteration on single files
- Fine-tuned UI and CSS adjustments
- Real-time completion for speed
- Interactive refactoring with immediate feedback
- Pair-programming feel for complex logic
- Minimal context switching within a file
Setting Up Cursor
Let's get Cursor installed and configured for optimal development.
Installation
Download and install Cursor from the official site:
# macOS (using Homebrew)
brew install cursor
# Windows
# Visit https://cursor.com and download the installer
# Linux
# Visit https://cursor.com and download the AppImageConfiguring Your AI Model
When Cursor launches for the first time, you'll be prompted to select an AI model.
- Click the gear icon (Settings) in the bottom left
- Navigate to Features → Models
- Select Claude 3.5 Sonnet or Claude Opus
Essential Keyboard Shortcuts
Learn these Cursor shortcuts for faster workflows:
Cmd+K — AI-powered code editing (describe what to change)
Cmd+L — Open AI chat panel
Cmd+A — Show all AI suggestions
Cmd+Shift+E — Execute editor commands
Cmd+/ — Toggle comment
To customize keybindings, edit ~/.cursor/settings.json:
{
"keybindings": [
{
"key": "cmd+k",
"command": "inline.insertEdit",
"when": "editorTextFocus && !editorReadonly"
},
{
"key": "cmd+l",
"command": "chat.openChatPanel"
},
{
"key": "cmd+shift+r",
"command": "inline.refactor"
}
],
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
}Using Claude Code from the Terminal
Cursor's integrated terminal becomes your command center for Claude Code CLI operations.
Installation and Authentication
Install Claude Code CLI:
# Via npm
npm install -g @anthropic-ai/claude-code
# Via Homebrew (if available)
brew install claude-codeAuthenticate with your API key:
claude-code auth
# Paste your API key from https://console.anthropic.com/api/keysVerify installation:
claude-code --version
# Should output: Claude Code CLI v0.x.xOpening the Terminal in Cursor
Open Cursor's integrated terminal:
Ctrl+` (backtick) — Opens/closes terminal
Or: View menu → Terminal
Now you can execute Claude Code commands directly:
# Edit a single file with AI assistance
claude-code edit src/components/Button.tsx
# Run tests through Claude Code
claude-code run npm test
# Analyze entire directory structure
claude-code analyze src/ --focus="performance opportunities"
# Create new files with templates
claude-code create src/api/users.ts --template="REST API with error handling"
# Multi-file editing
claude-code edit src/api/users.ts src/api/auth.ts \
--prompt "Synchronize error handling patterns across these files"Practical Workflow Examples
Workflow 1: Cursor for Tweaks → Claude Code for Testing & Fixing
Scenario: You've completed a major refactor and need to test individual functions and make targeted fixes.
Step 1: Claude Code performs broad refactoring
# Terminal in Cursor
claude-code edit src/utils/validation.ts \
--prompt "Refactor all validation functions to use zod for schema validation"The AI analyzes your existing patterns and generates the complete refactored version.
Step 2: Cursor fine-tunes specific functions
With the file open in Cursor, press Cmd+K and write:
"Update the email validation to reject temporary email services"
Cursor applies the change instantly, and you can review it in real-time.
Step 3: Claude Code runs the test suite
Back in the terminal:
claude-code run npm test -- src/utils/validation.test.tsReview test results and see which assertions failed.
Step 4: Claude Code fixes failures
claude-code edit src/utils/validation.ts \
--prompt "Fix the validation logic to pass all test cases. The tests are asserting that temporary email domains should be rejected."Step 5: Loop back to Step 2 if needed
This cycle ensures high-quality, well-tested code through collaborative AI assistance.
Workflow 2: Claude Code Scaffolds → Cursor Refines
Scenario: Building a new feature from scratch—generate structure with Claude Code, then polish with Cursor.
Step 1: Claude Code creates the foundation
claude-code create src/features/payment/PaymentProcessor.ts \
--prompt "Create a TypeScript class that:
- Processes credit card payments via Stripe API
- Validates card details before processing
- Handles errors gracefully with specific error codes
- Logs all transactions for auditing
- Supports retry logic for failed transactions"Claude Code generates a complete, well-structured class with proper error handling.
Step 2: Cursor improves error messages
Open the generated file in Cursor. Use Cmd+K:
"Rewrite all error messages to be user-friendly. Include error codes so users can reference them in support tickets."
Step 3: Cursor adds documentation
Again with Cmd+K:
"Add comprehensive JSDoc comments to every public method. Include parameter descriptions, return types, and example usage."
Step 4: Claude Code generates tests
claude-code create src/features/payment/PaymentProcessor.test.ts \
--prompt "Write comprehensive unit tests for PaymentProcessor.ts covering:
- Successful payment processing
- Invalid card validation
- Stripe API errors and retries
- Logging and audit trail
- Edge cases like duplicate transaction IDs"Step 5: Cursor validates the test structure
Open the test file and use Cmd+L to chat:
"Are these test cases comprehensive? What scenarios might we be missing?"
Cursor's AI responds with suggestions, which you can implement quickly.
Workflow 3: Claude Code Refactors → Cursor Validates Inline
Scenario: Modernizing existing code by extracting patterns into custom hooks.
Step 1: Claude Code analyzes patterns
claude-code analyze src/components/ \
--prompt "Identify repetitive useEffect and useState patterns that could be extracted into custom hooks"Claude Code reports findings with specific locations.
Step 2: Claude Code performs refactoring
claude-code edit src/components/ \
--prompt "Extract common patterns into these custom hooks:
- useLocalStorage for any component using localStorage
- useFetchData for any component with fetch logic
- useFormState for components managing form state
Refactor all components to use the new hooks."Step 3: Cursor validates each component
Open each refactored component in Cursor. Use Cmd+L:
"Does this custom hook properly handle cleanup? Are there any memory leaks?"
Walk through the logic and confirm everything is correct.
Step 4: Cursor optimizes performance
For performance-critical components, press Cmd+K:
"Add React.memo and useMemo where appropriate to prevent unnecessary re-renders"
Decision Framework: When to Use Each Tool
Use Cursor When:
- Editing a single file — Logic adjustments, bug fixes within one component
- Polishing UI/CSS — Fine-tuning styles, aligning layouts, tweaking colors
- Interactive problem-solving — You need to explore solutions as you type
- Quick iterations — Testing multiple approaches to a small problem
- Learning code — Reading and understanding existing logic
- Inline refactoring — Small, focused improvements within a file
Use Claude Code When:
- Coordinating multiple files — Refactoring affects 3+ files across the codebase
- Analyzing the project — Finding patterns, duplications, or improvement opportunities
- Test creation & execution — Generating test suites and running full test passes
- Git workflows — Creating commits, branches, and preparing PRs
- Feature scaffolding — Generating complete, interconnected components from scratch
- Search & replace at scale — Complex replacements across the entire codebase
Quick Decision Tree:
How many files will be changed?
├─ 1 file → Use Cursor
├─ 2–3 related files → Depends on similarity (high → Claude Code, low → Cursor)
└─ 4+ files → Use Claude Code
MCP Integration: Extending Both Tools
MCP (Model Context Protocol) is a standard that allows AI models to access external tools and data sources. Both Cursor and Claude Code support MCP, meaning they can share the same MCP servers and plugins.
Shared MCP Configuration
Create ~/.mcp-config.json (shared between Cursor and Claude Code):
{
"mcpServers": {
"filesystem": {
"command": "node",
"args": ["~/.mcp/file-server.js"],
"env": {
"ALLOWED_PATHS": "/Users/yourname/projects:/Users/yourname/work"
}
},
"git": {
"command": "python3",
"args": ["~/.mcp/git-server.py"],
"env": {
"GIT_REPO_PATH": "/Users/yourname/projects/myapp"
}
},
"database": {
"command": "node",
"args": ["~/.mcp/db-server.js"],
"env": {
"DATABASE_URL": "postgresql://localhost/development",
"DB_USER": "dev",
"DB_PASSWORD": "secure_password_here"
}
},
"web-search": {
"command": "node",
"args": ["~/.mcp/search-server.js"],
"env": {
"SEARCH_API_KEY": "your_api_key"
}
}
}
}Cursor configuration (~/.cursor/settings.json):
{
"mcp": {
"configPath": "~/.mcp-config.json"
}
}Claude Code configuration:
# Claude Code reads from ~/.mcp-config.json automatically
# Or set the config file location:
export CLAUDE_MCP_CONFIG=~/.mcp-config.jsonWhat This Enables:
- Both tools query the same Git history
- Shared filesystem access with consistent permissions
- Database queries work identically in both environments
- Web search results are consistent across tools
Tips & Best Practices
1. Create a Shared CLAUDE.md Context File
Place a CLAUDE.md file in your project root. Both Cursor and Claude Code will read it, ensuring consistent context:
# Development Guidelines
## Project Overview
Full-stack e-commerce platform built with Next.js 14, PostgreSQL, and TypeScript.
## Technology Stack
- **Frontend:** Next.js 14 with React 18 and TypeScript
- **Backend:** Next.js API routes
- **Database:** PostgreSQL with Prisma ORM
- **Testing:** Vitest for unit tests, Playwright for E2E
- **Styling:** Tailwind CSS v3
- **Auth:** NextAuth.js v5
## Code Conventions
- **Variables/Functions:** camelCase
- **Components/Classes:** PascalCase
- **Constants:** UPPER_SNAKE_CASE
- **Types/Interfaces:** PascalCase with T prefix optional (e.g., `UserProfile` or `TUserProfile`)
## API Response Format
All endpoints return a consistent format:
```typescript
interface ApiResponse<T> {
data: T | null;
error: string | null;
status: "success" | "error";
timestamp: string;
}Database Standards
- Use Prisma migrations:
npm run prisma:migrate - All transactions must use
prisma.$transaction() - Never use raw SQL except for performance-critical queries
- Index commonly-filtered fields
Testing Requirements
- All new features require unit tests (>80% coverage)
- Critical workflows require E2E tests
- Test files:
*.test.tsor*.test.tsx
Common Commands
npm run dev # Start dev server
npm run test # Run unit tests
npm run test:e2e # Run end-to-end tests
npm run build # Production build
npm run prisma:migrate # Run database migrations
npm run type-check # TypeScript checkPerformance Targets
- Largest bundle: <500KB gzipped
- Core Web Vitals: LCP <2.5s, FID <100ms, CLS <0.1
- Database queries: <100ms
- API responses: <200ms
Known Gotchas
- Prisma relations require explicit includes—don't assume nested data
- NextAuth sessions live in cookies—be aware of size limits
- PostgreSQL arrays should be indexed with GIN indexes
- Tailwind classes must be static strings (no dynamic class names)
### 2. Distinguish Between `.cursorrules` and `CLAUDE.md`
Use `.cursorrules` for Cursor-specific behaviors:
.cursorrules — Cursor-specific preferences
When suggesting code completions:
- Prioritize performance and memory efficiency
- For React components, suggest memoization opportunities
- Highlight potential accessibility issues
- Suggest TypeScript types that are too permissive (e.g.,
any)
When the user presses Cmd+K:
- Ask for clarification if the intent is ambiguous
- Show before/after diffs for significant changes
- Suggest related improvements in the same file
Keep general development rules in `CLAUDE.md` so both tools follow them.
### 3. Optimize Your Terminal Layout
The ideal Cursor setup uses a side-by-side layout:
┌──────────────────────┬──────────────────────┐ │ │ │ │ Cursor Editor │ Integrated │ │ (code viewing │ Terminal │ │ & editing) │ (Claude Code CLI) │ │ │ │ └──────────────────────┴──────────────────────┘
**Setup:**
1. Open terminal in Cursor: `Ctrl+``
2. Click the split button in the terminal header
3. Adjust pane widths using `View → Appearance → Panel Size`
**Benefits:**
- See code changes while Claude Code executes
- Monitor test results in real-time
- Context remains in one view
- No need to switch between windows
### 4. Create a Development Script
Create `dev.sh` to launch your optimal Cursor+Claude Code setup:
```bash
#!/bin/bash
# dev.sh — Start your complete development environment
echo "Starting Claude Code + Cursor development environment..."
# Start dev server in background
npm run dev &
DEV_PID=$!
# Start Claude Code auth check
claude-code auth:check
# Open Cursor with the current directory
cursor .
# Cleanup on exit
trap "kill $DEV_PID" EXIT
echo "Development environment ready!"
echo "Use Claude Code in the integrated terminal to work at scale."
Run with: chmod +x dev.sh && ./dev.sh
5. Use .gitignore Effectively
Ensure Cursor and Claude Code don't interfere with version control:
# IDE and AI Tool Files
.cursor/
.claude/
.cursorignore
.claudeignore
# Dependencies
node_modules/
.pnp
# Build outputs
.next/
dist/
build/
# Environment
.env
.env.local
.env.*.local
# OS
.DS_Store
Thumbs.dbComparison with Other AI Editors
Cursor vs. Windsurf
| Aspect | Cursor | Windsurf |
|---|---|---|
| Base | VS Code | VS Code |
| AI Models | Claude, GPT-4 | Claude, GPT-4, Grok |
| Chat | Yes | Yes |
| Multi-file Edit | Good | Excellent |
| Speed | Very Fast | Fast |
| Learning Curve | Low | Medium |
Cursor is lighter and more responsive; Windsurf offers more sophisticated multi-file reasoning.
Cursor vs. GitHub Copilot
Copilot: VS Code Extension (augments existing editor)
Cursor: Standalone Editor (AI is native)
Key difference: Copilot is a plugin; Cursor is the editor itself. Copilot excels at completion; Cursor excels at interactive editing.
Cursor vs. Claude Code CLI
Cursor: Real-time visual feedback, immediate iteration
Claude Code: Powerful analysis, multi-file coordination, CI/CD automation
They're complementary, not competing. Use them together as this guide demonstrates.
Advanced Patterns
Pattern 1: Test-Driven Development
- Claude Code creates initial feature scaffold and test file
- Cursor iteratively develops the feature while tests are visible
- Claude Code runs full test suite and identifies gaps
- Cursor adds edge case handling
Pattern 2: Code Review Automation
# Claude Code analyzes changes
claude-code analyze src/ --since="main"
# Generates review comments
# Cursor displays them inline
# You review and confirm before committingPattern 3: Documentation Generation
# Cursor: Write code with clear logic
# Claude Code: Generate documentation from code
claude-code generate-docs src/ --output="docs/"
# Cursor: Review and edit for clarityWrapping up
Cursor and Claude Code represent two complementary approaches to AI-assisted development:
- Cursor for interactive, real-time editing with deep single-file context
- Claude Code for strategic, large-scale changes with full project vision
- Together they form a system where each tool does what it does best
Start with one simple project. Use Cursor for an afternoon of polishing a component. Use Claude Code for refactoring a feature across files. Within days, you'll intuitively know which tool to reach for, and your development speed will exceed what either tool alone could provide.
Next Steps:
- Install both Cursor and Claude Code
- Create a test project or use an existing one
- Follow Workflow 1, 2, or 3 above
- Adjust based on your team's needs and preferences
- Share your workflows with teammates—they'll want to adopt this too
Happy coding with your new AI dev team!