Quick-start: Context Engineering with Cursor¶
Get up and running with context engineering in Cursor IDE in under 10 minutes. This guide provides immediate, practical steps to improve your AI-assisted development workflow.
🎯 Before You Begin¶
Prerequisites Checklist¶
- Cursor IDE installed (version 0.20+ recommended)
- Project repository initialized
- Basic understanding of your project structure
- 10 minutes for initial setup
- CDF project access (for CDF-specific setup)
🚀 5-Minute Setup¶
Step 1: Create Your First Context File¶
Create a .cursor/rules.md file in your project root:
Step 2: Choose Your Project Type¶
🏭 Option A: CDF Data Pipeline Project
# CDF Data Pipeline Project Rules
## Technology Stack
- Cognite Python SDK 7.13.0
- Python 3.11 with type hints
- Apache Spark 3.5 for transformations
- Pytest for testing
- GitHub Actions for CI/CD
## CDF Standards
- Project: my-cdf-project
- Cluster: api.cognitedata.com
- Data Space: sp_data_platform
- Naming: {source}:{type}:{identifier}
## Coding Standards
- Use type hints for all functions
- Follow PEP 8 with Black formatter
- Document with Google-style docstrings
- Handle CogniteAPIError explicitly
- Use async where possible
## Architecture Patterns
- RAW → Staging → Core data flow
- Idempotent transformations
- Batch operations (1000 items max)
- Exponential backoff for retries
## Example Pattern
```python
from cognite.client import CogniteClient
from cognite.client.data_classes import Asset
from typing import List
import logging
logger = logging.getLogger(__name__)
async def create_assets_batch(
client: CogniteClient,
assets: List[dict],
data_set_id: int
) -> List[Asset]:
"""Create assets in CDF with proper error handling.
Args:
client: Authenticated CogniteClient
assets: List of asset dictionaries
data_set_id: Target dataset ID
Returns:
List of created Asset objects
"""
try:
asset_objects = [
Asset(
external_id=f"sap:{asset['TAG']}",
name=asset['NAME'],
data_set_id=data_set_id,
metadata={
'source': 'SAP',
'lastUpdated': asset.get('CHANGED_DATE')
}
)
for asset in assets
]
return client.assets.create(asset_objects)
except CogniteAPIError as e:
logger.error(f"Failed to create assets: {e}")
raise
</details>
<details>
<summary><b>📈 Option B: CDF Analytics Project</b></summary>
```markdown
# CDF Analytics Project Rules
## Technology Stack
- Cognite Python SDK 7.13.0
- Pandas 2.0+ for data analysis
- Plotly for visualizations
- Streamlit for dashboards
- Jupyter for exploration
## CDF Query Patterns
- Use projections to limit fields
- Implement pagination for large datasets
- Cache frequently accessed data
- Use aggregates for time series
## Analysis Standards
- Document all assumptions
- Include data quality checks
- Version control notebooks
- Export reusable functions
## Example Analysis Pattern
```python
import pandas as pd
from cognite.client import CogniteClient
from datetime import datetime, timedelta
import plotly.express as px
def analyze_equipment_performance(
client: CogniteClient,
asset_ids: List[int],
days_back: int = 30
) -> pd.DataFrame:
"""Analyze equipment performance metrics."""
# Fetch time series data
end_time = datetime.now()
start_time = end_time - timedelta(days=days_back)
# Get relevant time series
timeseries = client.time_series.list(
asset_ids=asset_ids,
limit=None
)
# Aggregate data
aggregates = client.time_series.data.retrieve(
external_id=[ts.external_id for ts in timeseries],
start=start_time,
end=end_time,
aggregates=['average', 'min', 'max'],
granularity='1h'
)
# Convert to DataFrame for analysis
df = aggregates.to_pandas()
# Calculate KPIs
df['efficiency'] = (df['actual'] / df['target']) * 100
df['availability'] = df['runtime'] / (24 * days_back)
return df
</details>
<details>
<summary><b>📱 Option C: CDF InField App Project</b></summary>
```markdown
# CDF InField App Project Rules
## Technology Stack
- React Native 0.73 with TypeScript
- Cognite SDK JS 9.13.0
- React Navigation 6.x
- React Native Paper for UI
- Offline storage with MMKV
## Mobile-Specific Patterns
- Offline-first architecture
- Queue mutations when offline
- Sync on connection restore
- Handle auth token refresh
- Optimize for battery life
## CDF Mobile Integration
```typescript
import { CogniteClient } from '@cognite/sdk';
import NetInfo from '@react-native-community/netinfo';
import { MMKV } from 'react-native-mmkv';
const storage = new MMKV();
export class OfflineCDFClient {
private client: CogniteClient;
private syncQueue: any[] = [];
constructor(config: ClientConfig) {
this.client = new CogniteClient(config);
this.setupOfflineHandling();
}
private setupOfflineHandling() {
NetInfo.addEventListener(state => {
if (state.isConnected && this.syncQueue.length > 0) {
this.processSyncQueue();
}
});
}
async createAsset(asset: AssetInput): Promise<Asset> {
const isOnline = await NetInfo.fetch().then(s => s.isConnected);
if (!isOnline) {
// Queue for later
this.syncQueue.push({ type: 'CREATE_ASSET', data: asset });
storage.set('syncQueue', JSON.stringify(this.syncQueue));
return asset as Asset; // Optimistic response
}
return this.client.assets.create([asset])[0];
}
}
</details>
### Step 3: Test Your Context
Open Cursor IDE and try a prompt specific to your project type:
**For CDF Data Pipeline:**
The AI should now generate code that follows your CDF-specific patterns.
## 🎯 Immediate Improvements
### Better Prompts with Context
**Before** (without context):
### Feature-Level Context
When working on a specific feature, open relevant files in your editor:
1. **Open related components** that the AI should reference
2. **Include API schemas** or data models
3. **Show existing patterns** you want to follow
### Task-Level Context
Be specific about your immediate goal:
## 📈 Quick Wins & Success Metrics
### Immediate Improvements (Day 1)
| Metric | Without Context | With Context | Improvement |
|--------|----------------|--------------|-------------|
| **Code Accuracy** | 45-60% | 85-95% | +40-50% |
| **Refactoring Time** | 20-30 min/feature | 5-10 min/feature | -60-80% |
| **Pattern Consistency** | 40% | 90%+ | +50% |
| **First-Try Success** | 30% | 75% | +45% |
### How to Measure Your Success
1. **Time Tracking**
```bash
# Before context engineering
Feature A: 2h (30m coding, 90m refactoring)
# After context engineering
Feature B: 45m (35m coding, 10m refactoring)
.cursor/
├── rules.md # General project rules
├── rules.frontend.md # Frontend-specific patterns
├── rules.backend.md # Backend-specific patterns
└── rules.testing.md # Testing patterns
# Add to .cursor/rules.md
## IMPORTANT: Always follow these patterns
### ❌ Bad Example (DO NOT GENERATE):
```python
def get_data():
return requests.get(url).json()
from cognite.client import CogniteClient
from typing import Optional
import logging
logger = logging.getLogger(__name__)
def get_asset_data(
client: CogniteClient,
asset_id: int
) -> Optional[Asset]:
"""Fetch asset with proper error handling."""
try:
return client.assets.retrieve(id=asset_id)
except CogniteAPIError as e:
logger.error(f"Failed to fetch asset {asset_id}: {e}")
return None
## MANDATORY Rules
- ALWAYS use type hints
- NEVER use print() - use logger
- ALWAYS handle CogniteAPIError
- MUST include docstrings
# Optimal Context Structure
## Critical Rules (Always Active) - Keep under 500 lines
- Core patterns
- Essential standards
- Must-follow rules
## Extended Context (Reference as needed) - Can be larger
- Detailed examples
- Edge cases
- Historical decisions
.cursor/
├── rules.md # Core rules (2KB)
├── examples/
│ ├── assets.md # Asset examples (3KB)
│ ├── timeseries.md # Time series examples (3KB)
│ └── transformations.md # Transform examples (4KB)
└── architecture/
├── decisions.md # ADRs and rationale (5KB)
└── patterns.md # Detailed patterns (5KB)
📋 Context Engineering Cheat Sheet
# Quick Context Template
## Must Have
- Technology stack with versions
- Primary coding patterns
- Error handling approach
- 2-3 concrete examples
## Should Have
- Architecture decisions
- Performance requirements
- Security patterns
- Testing approach
## Nice to Have
- Historical context
- Migration guides
- Team preferences
- Future roadmap