
The Ultimate .cursorrules Guide: Modular System Prompts for AI Coding Agents
Quick Start (Production Root .cursorrules Template)
Drop this modular .cursorrules file into the root of your project to immediately eliminate AI laziness, prevent fake package hallucinations, and stop the model from leaving unfinished // TODO blocks:
# Autonomous AI Coding Assistant Directives
You are an expert senior software engineer. Strictly adhere to these rules across all suggestions, diffs, and terminal commands:
## 1. Code Integrity & Completeness
- NEVER output placeholder comments like "// ... rest of code unchanged" or "// TODO: implement later". Output fully functional, complete snippets.
- Do NOT delete existing comments, docstrings, or type definitions unless explicitly instructed.
- When modifying an existing function, preserve unaffected parameters, interfaces, and error handling.
## 2. Dependencies & Framework Standards
- Do NOT invent or import third-party packages that are not listed in package.json or pyproject.toml without asking first.
- Prefer built-in language primitives and standard library tools before introducing new dependencies.
- Use explicit type annotations everywhere (no `any` in TypeScript, no bare `except:` in Python).
## 3. Terminal & Execution Safety
- Run non-destructive commands automatically (tests, builds, linters).
- NEVER execute destructive commands (`rm -rf`, `git reset --hard`, `DROP TABLE`) without explicit user confirmation.
- Format all terminal commands to run in non-interactive, headless modes (e.g., pass `-y` or `--non-interactive`).
1. Root .cursorrules vs Modern Scoped .cursor/rules/*.mdc
Cursor updated its Rules for AI system to support modular, glob-scoped rule files located under .cursor/rules/. Instead of stuffing 2,000 tokens of rules into a single root file that consumes context on every query, scoped rules activate only when relevant files are edited.
+-----------------------------------------------------------------------------------------+
| CURSOR SCOPED RULE RESOLUTION & INJECTION ENGINE |
+-----------------------------------------------------------------------------------------+
| |
| [ User Opens / Edits File: src/components/NavBar.tsx ] |
| | |
| +----------------------------+ |
| | | |
| v v |
| Legacy Root .cursorrules Modern Scoped Engine (.cursor/rules/) |
| (Always injected: 1,450 tok) |-> Evaluates Glob Matches: |
| | - typescript.mdc (globs: **/*.{ts,tsx}) -> MATCH (320 tok)|
| | - python.mdc (globs: **/*.py) -> SKIP (0 tok) |
| | - git.mdc (globs: **/*) -> MATCH (180 tok)|
| | |
| +-> Combined Context Overhead: 500 tokens (65.5% saving) |
| |
| Result: 950 extra context tokens preserved for AST syntax and large dependency trees |
+-----------------------------------------------------------------------------------------+
| Feature | Legacy Root .cursorrules |
Modern Scoped .cursor/rules/*.mdc |
|---|---|---|
| File Location | /.cursorrules |
/.cursor/rules/<name>.mdc |
| Trigger Mechanism | Always loaded on every prompt | Loaded only when matching glob patterns |
| Token Efficiency | Low (Consumes 500 to 2,000 tokens constantly) | High (Loaded selectively per active file) |
| Team Organization | Monolithic single file | Modular files per tech stack (frontend, backend, db) |
| Average Context Overhead | 1,450 tokens / query | 480 tokens / query (-66.8% reduction) |
Pairing scoped rules with external tools gives assistants surgical precision. If you integrate external tooling via MCP, review our guide on building custom MCP servers for Cursor and Claude Code.
2. Production Scoped Rule Templates
Template A: Strict TypeScript & React (.cursor/rules/typescript.mdc)
Apply to files matching: **/*.{ts,tsx}
---
description: Strict TypeScript and modern React engineering standards
globs: **/*.{ts,tsx}
---
# TypeScript & React Rules
- Always enable and write code adhering to `strict: true`.
- Never use `any`. Use `unknown` with type narrowing or generic constraints.
- Prefer `type` over `interface` for union types and primitive aliases; prefer `interface` for extensible object contracts.
- React components:
- Write pure functional components with explicit Props typing (`interface Props { ... }`).
- Do not use `useEffect` for data synchronization that can be computed during render.
- Wrap database or external network calls in React Server Components or dedicated server actions.
Template B: Modern Python & FastAPI (.cursor/rules/python.mdc)
Apply to files matching: **/*.py (enforcing Pydantic v2 schemas)
---
description: Modern Python 3.12+ and FastAPI architecture rules
globs: **/*.py
---
# Python Engineering Rules
- Target Python 3.12+ syntax (use native `list[str]`, `dict[str, int]`, and `T | None` instead of `typing.Union`).
- Enforce strict typing with Pydantic v2 `BaseModel` for all request/response schemas.
- Async by default: Use `async def` for I/O-bound route handlers; use standard `def` for CPU-bound utility functions.
- Never catch bare `Exception` unless re-raising; catch specific error classes (`KeyError`, `ValueError`, `httpx.HTTPStatusError`).
When building autonomous loops with open-source Python AI agent frameworks, enforcing explicit error classes in system rules prevents silent infinite retry loops. It works. The failure disappears. Clean exceptions keep agents reliable.
Template C: Git Workflows & Atomic Commits (.cursor/rules/git.mdc)
Apply to files matching: **/* (adhering to the Conventional Commits specification)
---
description: Semantic Git commits and branch isolation standards
globs: **/*
---
# Git Workflow & Commit Rules
- Follow Conventional Commits format strictly (`feat:`, `fix:`, `refactor:`, `test:`, `docs:`).
- Keep commit descriptions imperative and concise ("feat: add OAuth login", not "feat: added OAuth").
- Never stage or commit environment secret files (`.env`, `.env.local`, `credentials.json`, `*.pem`).
- Stage modified files explicitly with `git add <path>` rather than indiscriminately running `git add .`.
- Before suggesting a branch merge or push, run `git status` to verify that untracked temporary files are excluded.
If multiple agents edit code in parallel, review our comparison of Cline vs. Roo Code vs. Continue.dev multi-agent workflows to eliminate dirty stash conflicts.
3. Anti-Hallucination Checklist
Add these defensive constraints to your prompt files to guard against model regressions:
- Verify Before Suggesting: Require the model to run
git statusor grep existing files before assuming a file or directory does not exist. - Deterministic Imports: Instruct the model to inspect existing source files to determine whether your codebase uses ES Module syntax (
import) or CommonJS (require). - No Phantom APIs: Force the model to query local docstrings or package versions rather than guessing deprecated method names from older framework versions.
- Clean Diffs: Mandate that diffs modify only contiguous blocks rather than scattering small whitespace changes across entire files.
- Linting Verification: Instruct the assistant to run
npm run lintorruff check .immediately after applying edits.
If your team compares alternatives to Cursor such as Cline or Roo Code, explore our architectural breakdown of Cline vs Roo Code vs Continue. For multi-file refactoring workflows across IDEs and terminal agents, see our comparison of Cursor, Claude Code, and Windsurf.
If agents possess shell execution permissions, pair prompt rules with transport-level isolation as detailed in our guide to securing remote MCP servers and Bubblewrap Linux sandboxing.
4. Summary Reference
- Use root
.cursorrulesfor repository-wide behavior (terminal safety, communication style, git workflow). - Migrate framework-specific guidelines into
.cursor/rules/<tech>.mdcwith targetedglobsto save context window tokens. - Explicit negative constraints (“NEVER do X”) are significantly more reliable at stopping AI regressions than positive suggestions.