# Cursor Rules Guide ## Summary Comprehensive guide to Cursor's rule system for controlling AI behaviour in the IDE. Covers the modern .mdc format, rule types, priority system, and best practices for building effective rules without overloading context. ## Details ## Understanding the Rule System Cursor is built as a sophisticated wrapper around large language models, functioning as an agentic coding system. At its core, it uses LLMs that predict the next token in a sequence, enhanced with tool-calling capabilities to interact with your codebase. Cursor supports three types of rules that work together to provide context-aware AI assistance: ### 1. Project Rules (Modern Approach) - **Location**: `.cursor/rules/` directory in your project root - **Format**: `.mdc` files (Markdown Components) - **Scope**: Project-specific, version-controlled - **Priority**: Applied based on rule type and context ### 2. User Rules (Global Settings) - **Location**: Cursor Settings > Rules > User Rules - **Format**: Plain text only (no MDC support) - **Scope**: All projects globally - **Priority**: Always included in context ### 3. Legacy .cursorrules (Deprecated) - **Location**: Project root as `.cursorrules` - **Status**: Still supported but deprecated - **Migration**: Recommended to move to Project Rules ## Rule Priority and Loading ### Loading Order 1. **User Rules**: Always loaded first (global preferences) 2. **Project Rules**: Loaded based on rule type and context 3. **Legacy .cursorrules**: Loaded if present (deprecated) ## How Rules Work Internally ### Rule Loading Mechanism Rules are not simply appended to the system prompt. Instead, they function as named sets of instructions that the AI can fetch dynamically. The AI sees a list of rule names and descriptions, then uses a `fetch_rules()` tool to retrieve specific rule content when needed. ### Context and Tool Integration Cursor optimises performance by: - Using prompt caching for static system prompts and tool definitions - Employing multiple specialised models (main agent, code-apply model, search/ranking models) - Implementing semantic diff editing rather than full file rewrites - Providing rich lint feedback to help the AI self-correct ### Rule Types and When They Apply | Rule Type | When Applied | Use Case | |-----------|-------------|----------| | **Always** | Every request | Core project standards | | **Auto Attached** | When matching files are referenced | File-specific guidelines | | **Agent Requested** | AI decides based on description | Optional best practices | | **Manual** | Explicitly mentioned with @ruleName | Specialised workflows | ## Project Rules Structure ### Basic .mdc File Format ```markdown --- description: Optional description for Agent Requested rules globs: ["**/*.js", "**/*.ts"] # For Auto Attached rules alwaysApply: false # Set to true for Always rules --- # Rule Content Starts Here - Use specific patterns - Follow these conventions - Reference files: @path/to/file.ts ``` ### File Organisation #### Basic Structure ```text project/ ├── .cursor/ │ └── rules/ │ ├── core-standards.mdc # Always apply │ ├── typescript-rules.mdc # Auto attached to *.ts │ ├── api-patterns.mdc # Agent requested │ └── deployment.mdc # Manual └── src/ ``` #### Nested Directory Support (v0.47+) Cursor now supports nested directories within `.cursor/rules`, enabling highly targeted rule organisation for monorepos and complex projects: ```text project/ ├── .cursor/ │ └── rules/ │ ├── core.mdc # Project-wide standards │ ├── backend/ │ │ ├── go-patterns.mdc # Go-specific rules │ │ ├── api-standards.mdc # Backend API rules │ │ └── database/ │ │ ├── migrations.mdc # Database migration rules │ │ └── queries.mdc # Query optimisation rules │ ├── frontend/ │ │ ├── react-components.mdc # React component guidelines │ │ ├── styling.mdc # CSS/styling rules │ │ └── src/ │ │ ├── components/ │ │ │ └── forms.mdc # Form component patterns │ │ └── tests/ │ │ ├── unit-tests.mdc # Unit testing patterns │ │ └── mocking.mdc # Mock and stub guidelines │ └── shared/ │ ├── typescript.mdc # Shared TS patterns │ └── utils.mdc # Utility function standards ├── backend/ ├── frontend/ └── shared/ ``` #### Targeting Strategy Use the nested structure to create increasingly specific rules: 1. **Project Root** (`.cursor/rules/`): Core standards that apply everywhere 2. **Technology Level** (`.cursor/rules/frontend/`, `.cursor/rules/backend/`): Language/framework-specific rules 3. **Module Level** (`.cursor/rules/frontend/src/components/`): Component or feature-specific patterns 4. **Specific Context** (`.cursor/rules/frontend/src/tests/`): Highly targeted rules for specific scenarios #### Combining Nested Structure with Glob Patterns Even with nested directories, glob patterns in the frontmatter provide additional targeting control: **Highly Targeted Rule Example**: ```markdown --- description: React component testing patterns with Jest and React Testing Library globs: [ "frontend/src/**/*.test.tsx", "frontend/src/**/*.spec.tsx", "packages/ui/src/**/*.test.tsx" ] --- # React Component Testing Standards - Use React Testing Library over Enzyme - Focus on user interactions, not implementation details - Mock external dependencies using MSW - Test accessibility with jest-axe ``` **Cross-Technology Rule Example**: ```markdown --- description: Error handling patterns across all services globs: [ "services/**/*.ts", "services/**/*.py", "services/**/*.go" ] --- # Service Error Handling Standards - Always use structured error responses - Include correlation IDs for tracing - Log errors with appropriate severity levels - Return appropriate HTTP status codes ``` #### Best Practices for Nested Rules 1. **Start broad, get specific**: Place general rules at higher levels, specific patterns deeper 2. **Avoid duplication**: Don't repeat the same guidance in multiple nested rules 3. **Use descriptive names**: Rule names should indicate their scope (e.g., `frontend-testing.mdc` vs `react-component-testing.mdc`) 4. **Combine with globs strategically**: Use glob patterns to fine-tune when nested rules apply 5. **Consider rule inheritance**: Rules in parent directories may still apply to child contexts ## Advanced Rule Writing Principles ### Think Like Encyclopedia Articles Write rules as reference documentation rather than commands. Since rules are fetched dynamically based on relevance, they should be comprehensive standalone articles about specific aspects of your codebase. ### Rule Names and Descriptions Are Critical The AI uses rule names and descriptions to decide which rules to fetch. Spend time crafting: - **Intuitive names** that clearly indicate when the rule applies - **Dense, specific descriptions** that help the AI understand relevance - **Multiple rules with different names** for the same concept if needed to improve discoverability ### What NOT to Do - **Avoid identity statements**: Don't write "You are a senior frontend engineer" - the AI already has an identity from system prompts - **Don't override system behaviour**: Avoid "don't add comments" or "ask questions before coding" - these conflict with internal tool usage - **Minimize negative instructions**: Focus on "For X, do Y" rather than lists of restrictions - **Don't duplicate system prompts**: Avoid repeating what's already in Cursor's built-in prompts ### Optimise for AI-Friendly Codebases Excessive rules often indicate a codebase that isn't AI-friendly. Consider: - **Unique file names** across the project (avoid multiple `page.js` files) - **Files under 500 lines** to work better with the apply model - **Clear file and function documentation** with semantic descriptions - **Consistent patterns** that reduce the need for extensive rules ## Best Practices for Building Rules ### 1. Start Small and Focused - Begin with 1-3 core rules - Keep each rule under 500 lines - Focus on specific, actionable guidance ### 2. Layer Your Rules Strategically **User Rules (Global)**: ```text Be concise and direct in responses. Prefer functional programming patterns. Use UK English spelling. ``` **Project Always Rules**: ```markdown --- alwaysApply: true --- # Core Project Standards - Use TypeScript with strict mode - Follow conventional commit format - Implement comprehensive error handling ``` **Auto Attached Rules**: ```markdown --- description: React component guidelines globs: ["**/*.tsx", "**/components/**/*.ts"] --- # React Component Rules - Use functional components with hooks - Implement proper TypeScript interfaces - Include error boundaries for components ``` ### 3. Use Examples and File References ```markdown --- description: API endpoint patterns globs: ["**/api/**/*.ts"] --- # API Endpoint Standards Follow this pattern for all endpoints: @src/api/users/route.ts Key requirements: - Input validation with Zod schemas - Proper error handling with custom types - Consistent response format ``` ### 4. Avoid Context Overload **Good**: Specific, focused rules ```markdown # Authentication Rules - Use NextAuth.js for session management - Implement middleware for protected routes - Validate JWT tokens on server side ``` **Poor**: Overly broad rules ```markdown # Everything about authentication, authorisation, security, # database connections, error handling, logging, monitoring... ``` ### 5. Leverage Link Syntax and File References Use MDC link syntax to reference key files and definitions. This provides crucial context to help the AI understand your codebase structure: ```markdown # API Response Patterns All API responses should follow the format defined in @types/api.ts For error handling, reference @utils/errors.ts patterns Authentication middleware: @middleware/auth.ts ``` ### 6. Use Cursor to Generate Rules Let the AI help write rules for other AIs. Use prompts like: - "@folder/ generate a markdown file describing key file paths and definitions for common changes" - "Create a rule that explains our authentication patterns" - "Document the expected structure for new API endpoints" ## Example Rule Sets ### 1. TypeScript/React Project **core-standards.mdc** (Always): ```markdown --- alwaysApply: true --- # Core Project Standards - TypeScript strict mode enabled - ESLint and Prettier configured - Conventional commits required - Test coverage minimum 80% ``` **react-components.mdc** (Auto Attached): ```markdown --- description: React component best practices globs: ["**/*.tsx", "**/components/**"] --- # React Component Guidelines - Functional components with TypeScript interfaces - Use React.memo for performance optimisation - Implement proper error boundaries - Export components as default ``` **api-routes.mdc** (Auto Attached): ```markdown --- description: API route patterns globs: ["**/api/**/*.ts", "**/app/api/**"] --- # API Route Standards - Input validation with Zod - Proper HTTP status codes - Consistent error response format - Rate limiting implemented ``` ### 2. Node.js Backend Project **architecture.mdc** (Always): ```markdown --- alwaysApply: true --- # Architecture Standards - Clean Architecture principles - Dependency injection pattern - Repository pattern for data access - Event-driven design where appropriate ``` **database.mdc** (Auto Attached): ```markdown --- description: Database interaction patterns globs: ["**/repositories/**", "**/models/**", "**/*.sql"] --- # Database Guidelines - Use Prisma ORM for type safety - Implement proper connection pooling - Database migrations version controlled - No raw SQL in business logic ``` ## Managing Rule Complexity ### 1. Progressive Enhancement Start with basic rules and add complexity gradually: **Phase 1**: Core standards only ```markdown # Basic Standards - Use TypeScript - Follow project structure - Write tests ``` **Phase 2**: Add specific patterns ```markdown # Enhanced Standards - Use specific error handling patterns: @utils/errors.ts - Follow API response format: @types/api.ts - Implement logging: @utils/logger.ts ``` **Phase 3**: Domain-specific rules ```markdown # Domain Rules - Authentication flows: @auth/patterns.md - Payment processing: @payments/guidelines.md - Data validation: @validation/schemas.ts ``` ### 2. Rule Decomposition Instead of one large rule: ```markdown # Everything about React, TypeScript, styling, testing, deployment... ``` Split into focused rules: - `react-components.mdc` - `typescript-patterns.mdc` - `styling-guidelines.mdc` - `testing-standards.mdc` - `deployment-process.mdc` ### 3. Context-Aware Loading Use Auto Attached rules to load only relevant context: ```markdown --- description: Testing utilities and patterns globs: ["**/*.test.ts", "**/*.spec.ts", "**/tests/**"] --- # Testing Guidelines Only loaded when working with test files ``` ### 4. Monorepo and Complex Project Strategies #### Strategy 1: Mirror Directory Structure Mirror your project's directory structure within `.cursor/rules/`: ```text monorepo/ ├── .cursor/rules/ │ ├── global-standards.mdc # Workspace-wide rules │ ├── apps/web-app/ │ │ ├── nextjs-patterns.mdc │ │ └── api/routes-patterns.mdc │ ├── packages/ui/ │ │ ├── component-patterns.mdc │ │ └── storybook-standards.mdc │ └── services/auth/ │ ├── node-patterns.mdc │ └── database/schema-rules.mdc ├── apps/web-app/ ├── packages/ui/ └── services/auth/ ``` #### Strategy 2: Technology-Based Organisation Organise rules by technology stack rather than project structure: ```text monorepo/ ├── .cursor/rules/ │ ├── core-standards.mdc │ ├── typescript/ │ │ ├── strict-patterns.mdc │ │ ├── frontend/react-patterns.mdc │ │ └── backend/node-patterns.mdc │ ├── python/ │ │ ├── pep8-standards.mdc │ │ └── testing/pytest-patterns.mdc │ ├── databases/ │ │ ├── postgresql-patterns.mdc │ │ └── migrations/schema-rules.mdc │ └── testing/ │ ├── integration-tests.mdc │ └── e2e-patterns.mdc └── ... ``` #### Strategy 3: Hybrid Approach Combine structure mirroring with technology organisation: ```text monorepo/ ├── .cursor/rules/ │ ├── workspace-standards.mdc # Always apply │ ├── shared/ # Technology rules │ │ ├── typescript.mdc │ │ ├── testing.mdc │ │ └── security.mdc │ ├── frontend/ # Frontend-specific │ │ ├── react-patterns.mdc │ │ ├── styling/ │ │ │ ├── css-modules.mdc │ │ │ └── responsive-design.mdc │ │ └── testing/ │ │ ├── component-tests.mdc │ │ └── accessibility.mdc │ └── backend/ # Backend-specific │ ├── api-design.mdc │ ├── services/ │ │ ├── microservice-patterns.mdc │ │ └── error-handling.mdc │ └── data/ │ ├── database-patterns.mdc │ └── caching-strategies.mdc └── ... ``` ## Technical Insights and Optimisation ### How Cursor Actually Works Understanding Cursor's internal architecture helps write better rules: **Multi-Model Architecture**: - **Main Agent**: Handles planning and decision-making - **Code-Apply Model**: Converts semantic diffs to actual code - **Search Models**: Handle codebase search and file ranking - **Embedding Models**: Create vector indices for semantic search **Semantic Diff System**: Cursor doesn't rewrite entire files. Instead: 1. Main agent produces a "semantic diff" with change instructions 2. Specialised apply model converts this to actual code changes 3. Linter provides feedback for self-correction 4. This is why you see random comments - they guide the apply model **Performance Optimisations**: - Static system prompts enable prompt caching for speed and cost reduction - @file/@folder syntax is syntactic sugar for context injection - Vector search handles semantic queries like "find auth code" - Multiple search tools (grep, file search, codebase search) provide different search strategies ### Optimisation Tips Based on Architecture - **Improve linting**: High-quality linters dramatically improve AI performance - **Use @file/@folder aggressively**: More explicit context leads to better results - **Keep files under 500 LoC**: The apply model struggles with very large files - **Add file-level documentation**: Comments guide embedding models for better search - **Use unique filenames**: Reduces ambiguity in edit operations - **Organise related code together**: Minimises context-switching between files ## Common Pitfalls to Avoid 1. **Over-specification**: Don't include every possible rule upfront 2. **Vague guidance**: Be specific about what to do, not just what to avoid 3. **Conflicting rules**: Ensure User Rules and Project Rules don't contradict 4. **Context bloat**: Avoid loading irrelevant rules for every request 5. **Static thinking**: Rules should evolve with your project 6. **Fighting the apply model**: Don't try to control comment insertion or minor formatting 7. **Identity confusion**: Don't give the AI a different identity than its system prompt 8. **System prompt conflicts**: Avoid overriding built-in behaviours ## Migration Strategy ### From .cursorrules to Project Rules 1. **Audit existing rules**: Identify what's working and what isn't 2. **Categorise by purpose**: Separate always-apply vs context-specific rules 3. **Create focused .mdc files**: Split large rules into specific domains 4. **Test incrementally**: Migrate one rule type at a time 5. **Iterate based on usage**: Refine rules based on AI performance ### Example Migration **Old .cursorrules**: ```markdown # Large monolithic file with everything - TypeScript patterns - React guidelines - API standards - Testing requirements - Deployment process ``` **New structure**: ```text .cursor/rules/ ├── core.mdc # Always apply ├── typescript.mdc # Auto attach to *.ts ├── react.mdc # Auto attach to *.tsx ├── api.mdc # Auto attach to api/** └── testing.mdc # Auto attach to *.test.* ``` ## Key Takeaways 1. **Start minimal**: Begin with User Rules and 1-2 core Project Rules 2. **Layer strategically**: Use rule types appropriately for different contexts 3. **Leverage nested directories**: Use `.cursor/rules/` subdirectories for targeted organisation in monorepos 4. **Stay focused**: Each rule should have a clear, specific purpose 5. **Combine structure with globs**: Use both directory structure and glob patterns for precise targeting 6. **Iterate regularly**: Refine rules based on how the AI performs 7. **Avoid overload**: Don't include every possible instruction upfront 8. **Mirror or organise by technology**: Choose the structure that best fits your project needs The goal is to provide just enough context for the AI to be helpful without overwhelming it with irrelevant information. With nested directory support, you can now create highly targeted rules that only apply to specific parts of your codebase, making the AI more context-aware and effective. ## 🔗 Related Resources ### Official Documentation - [Cursor Rules Documentation](https://docs.cursor.com/context/rules) - Official rules reference ### Community Collections - [Awesome Cursor Rules](https://github.com/PatrickJS/awesome-cursorrules) - Large collection of examples - [Cursor Rules MDC Collection](https://github.com/sanjeed5/awesome-cursor-rules-mdc) - Modern .mdc format examples - [Cursor Directory](https://cursor.directory/) - Curated rules for different frameworks ### In-Depth Guides - [How Cursor (AI IDE) Works](https://blog.sshh.io/p/how-cursor-ai-ide-works) - Technical deep dive into Cursor's architecture and rule system - [Trigger.dev Rules Guide](https://trigger.dev/blog/cursor-rules) - How to write effective rules - [Mastering Cursor Rules](https://dev.to/dpaluy/mastering-cursor-rules-a-developers-guide-to-smart-ai-integration-1k65) - Comprehensive guide ### Related Tools - [WebDev Arena](https://web.lmarena.ai/leaderboard) - Leaderboard for agentic coding performance - [Model Context Protocol](https://modelcontextprotocol.io/introduction) - Protocol for enhanced AI tool integration