Effective context management is crucial for agent performance and cost efficiency. Learn how to scope context, use MDC files, track state, and manage dynamic context.
Define what information the agent needs access to.
- Include Only What's Necessary: More context = higher cost + slower responses
- Prioritize Recent Changes: Focus on files currently being modified
- Exclude Dependencies: Don't include node_modules, vendor files, etc.
- Use Abstractions: Include high-level docs instead of entire codebases
Include only relevant files:
# Good: Specific files
cursor-agent "@src/auth/user-service.ts @src/auth/auth-service.ts refactor authentication"
# Bad: Entire directory
cursor-agent "@src/ refactor authentication"When working on a module:
# Include module directory and related tests
cursor-agent "@src/auth/ @tests/auth/ improve authentication module"Use .cursorignore to exclude files:
# .cursorignore
node_modules/
dist/
build/
*.log
.env
coverage/
- Small (< 10 files): Fast, cheap, focused
- Medium (10-50 files): Balanced, good for module work
- Large (50+ files): Slow, expensive, use sparingly
MDC files are markdown documents that serve as context sources for agents.
Create .mdc files to provide structured context:
# Project Architecture
## Overview
This project is a REST API built with Node.js and Express.
## Key Components
- Authentication: JWT-based auth in src/auth/
- Database: PostgreSQL with Prisma ORM
- API Routes: RESTful routes in src/routes/
## Conventions
- Use async/await for all async operations
- Follow RESTful naming conventions
- All routes require authentication except /auth/loginReference MDC files in agent prompts:
cursor-agent "@architecture.mdc implement new feature following project architecture"Organize MDC files by purpose:
docs/
architecture.mdc
api-spec.mdc
database-schema.mdc
coding-standards.mdc
Track what has been completed vs. what remains.
{
"task": "refactor-authentication",
"started": "2024-01-15T10:00:00Z",
"completedSteps": [
{
"step": "analyze-current-code",
"completed": "2024-01-15T10:05:00Z",
"result": "Identified 3 files to refactor"
},
{
"step": "write-tests",
"completed": "2024-01-15T10:15:00Z",
"result": "15 tests written"
}
],
"currentStep": "refactor-user-service",
"remainingSteps": [
"refactor-auth-service",
"refactor-token-service",
"verify-all-tests"
],
"filesModified": [
"src/auth/user-service.ts",
"tests/auth/user-service.test.ts"
]
}Update state after each agent action:
#!/bin/bash
STATE_FILE=".agent-state.json"
# Load state
STATE=$(cat $STATE_FILE)
# Agent completes step
cursor-agent "complete current step: $(echo $STATE | jq -r '.currentStep')"
# Update state
echo $STATE | jq '.completedSteps += [{"step": "refactor-user-service", "completed": "'$(date -Iseconds)'"}]' > $STATE_FILEInject results from previous iterations into subsequent agent prompts.
#!/bin/bash
# Initial attempt
RESULT=$(cursor-agent "implement UserService.getUser(id)")
# Run tests
TEST_OUTPUT=$(npm test 2>&1)
# Inject test results into next iteration
cursor-agent "previous implementation failed tests: $TEST_OUTPUT. Fix the implementation."Build context incrementally:
# Step 1: Analysis
ANALYSIS=$(cursor-agent "analyze authentication code structure")
# Step 2: Use analysis for refactoring
cursor-agent "based on this analysis: $ANALYSIS, refactor the code"
# Step 3: Use refactoring results for testing
REFACTOR_RESULT=$(cursor-agent "based on refactoring, write comprehensive tests")Compress context when it grows too large:
# Original context (too large)
LARGE_CONTEXT=$(cat large-file.txt)
# Compress to summary
SUMMARY=$(cursor-agent "summarize this context in 100 words: $LARGE_CONTEXT")
# Use summary for next iteration
cursor-agent "based on summary: $SUMMARY, implement feature"Refresh context for long-running tasks to prevent staleness.
- Files modified outside agent control
- Dependencies updated
- External APIs changed
- Team members made changes
#!/bin/bash
# Check if context needs refresh
LAST_REFRESH=$(cat .context-refresh)
CURRENT_TIME=$(date +%s)
REFRESH_INTERVAL=3600 # 1 hour
if [ $(($CURRENT_TIME - $LAST_REFRESH)) -gt $REFRESH_INTERVAL ]; then
echo "Refreshing context..."
# Re-read relevant files
CONTEXT=$(cat src/**/*.ts | head -10000)
# Update refresh time
echo $CURRENT_TIME > .context-refresh
fi# Start with minimal context
cursor-agent "@specific-file.ts implement feature"
# Expand if needed
cursor-agent "@specific-file.ts @related-file.ts implement feature with integration"Instead of entire codebase, use:
- Architecture diagrams
- API specifications
- Design documents
- High-level summaries
# Cache common context
echo "$(cursor-agent 'analyze project structure')" > .cached-context.txt
# Reuse cached context
cursor-agent "@.cached-context.txt implement new feature"Remove completed items from context:
# Before: Includes completed steps
CONTEXT="completed: step1, step2, step3 | current: step4"
# After: Only current and remaining
CONTEXT="current: step4 | remaining: step5, step6"Track context versions for reproducibility:
# Save context version
echo "context-v1-$(date +%Y%m%d)" > .context-version
# Reference version in prompts
cursor-agent "@.context-version implement feature"Estimate context size before sending:
# Count tokens (approximate)
CONTEXT_SIZE=$(wc -w context.txt | awk '{print $1}')
echo "Context size: ~$CONTEXT_SIZE tokens"Validate context before use:
# Check for required files
for file in $REQUIRED_FILES; do
if [ ! -f "$file" ]; then
echo "Missing required file: $file"
exit 1
fi
doneCreate reusable context templates:
# template-context.sh
cat << EOF
Project: $PROJECT_NAME
Language: $LANGUAGE
Framework: $FRAMEWORK
Key Files: $KEY_FILES
Conventions: $CONVENTIONS
EOF- Implement guardrails: Guardrails
- Learn multi-agent orchestration: Multi-Agent Orchestration