Context Fragmentation
Related code lives in different repositories
Modern software architectures often span multiple repositories. Whether you’re working with microservices, modular monoliths, or polyglot systems, Cursor provides powerful features for managing multi-repo workflows efficiently.
Context Fragmentation
Related code lives in different repositories
Dependency Tracking
Changes in one repo affect others
Consistent Standards
Maintaining coding standards across repos
Cross-Repo Refactoring
Making coordinated changes across services
Create a workspace file that includes all related repositories:
// company.code-workspace{ "folders": [ { "name": "🌐 API Gateway", "path": "../api-gateway" }, { "name": "👤 User Service", "path": "../user-service" }, { "name": "💳 Payment Service", "path": "../payment-service" }, { "name": "📧 Notification Service", "path": "../notification-service" }, { "name": "📚 Shared Libraries", "path": "../shared-libs" } ], "settings": { "cursor.workspaceIndexing": { "strategy": "selective", "priority": ["API Gateway", "Shared Libraries"] } }}
{ "folders": [ // User Domain {"name": "User API", "path": "../services/user-api"}, {"name": "User DB", "path": "../services/user-db"}, {"name": "User UI", "path": "../frontends/user-dashboard"},
// Payment Domain {"name": "Payment API", "path": "../services/payment-api"}, {"name": "Payment Processor", "path": "../services/payment-processor"}, {"name": "Payment UI", "path": "../frontends/payment-portal"},
// Shared {"name": "Common Types", "path": "../libraries/types"}, {"name": "Utils", "path": "../libraries/utils"} ]}
{ "folders": [ // Backend Services {"name": "Node Services", "path": "../backend/node"}, {"name": "Go Services", "path": "../backend/go"}, {"name": "Python Services", "path": "../backend/python"},
// Frontend Apps {"name": "React Apps", "path": "../frontend/react"}, {"name": "Vue Apps", "path": "../frontend/vue"},
// Infrastructure {"name": "Terraform", "path": "../infra/terraform"}, {"name": "K8s Configs", "path": "../infra/kubernetes"} ]}
{ "folders": [ // Platform Team {"name": "Auth Service", "path": "../platform/auth"}, {"name": "API Gateway", "path": "../platform/gateway"},
// Product Team A {"name": "Feature X API", "path": "../team-a/feature-x-api"}, {"name": "Feature X UI", "path": "../team-a/feature-x-ui"},
// Product Team B {"name": "Feature Y API", "path": "../team-b/feature-y-api"}, {"name": "Feature Y UI", "path": "../team-b/feature-y-ui"} ]}
// Search across all repositories"@all Find all implementations of UserService interface"
// Search in specific repos"@workspace:'User Service' @workspace:'Payment Service'Find all API calls between these services"
// Search by technology"@ext:go Find all gRPC service definitions""@ext:ts @ext:tsx Find all React components using UserContext"
// Search by pattern across repos"@search('import.*@company/shared') Find all shared library usage"
Create a dependency map that Cursor can use:
services: user-service: depends_on: - shared-libs/auth - shared-libs/database consumers: - api-gateway - notification-service
payment-service: depends_on: - shared-libs/auth - user-service/api consumers: - api-gateway - order-service
api-gateway: depends_on: - user-service/api - payment-service/api - order-service/api
// Custom MCP server for dependency trackingclass DependencyTracker { async analyzeDependencies(service: string) { const deps = await this.scanImports(service); const consumers = await this.findConsumers(service);
return { directDependencies: deps.direct, transitiveDependencies: deps.transitive, consumers: consumers, circularDependencies: this.detectCircular(deps), outdated: await this.checkVersions(deps), }; }
async impactAnalysis(changedFile: string) { // Find all services affected by a change const affected = new Set<string>();
const service = this.getServiceFromPath(changedFile); const consumers = await this.getConsumerChain(service);
for (const consumer of consumers) { affected.add(consumer); // Recursively find affected services const downstream = await this.getConsumerChain(consumer); downstream.forEach((s) => affected.add(s)); }
return Array.from(affected); }}
Maintain consistent AI behavior across repositories:
#!/bin/bash# sync-rules.sh - Sync Cursor rules across all repos
REPOS=( "user-service" "payment-service" "notification-service" "api-gateway")
for repo in "${REPOS[@]}"; do echo "Syncing rules to $repo..."
# Create .cursor directory if it doesn't exist mkdir -p "../$repo/.cursor/rules"
# Copy base rules cp ./rules/base-rules.md "../$repo/.cursor/rules/"
# Copy technology-specific rules if [[ -f "../$repo/package.json" ]]; then cp ./rules/frontend-rules.md "../$repo/.cursor/rules/" fi
if [[ -f "../$repo/go.mod" ]]; then cp ./rules/backend-rules.md "../$repo/.cursor/rules/" fi
# Always include security rules cp ./rules/security-rules.md "../$repo/.cursor/rules/"done
// shared-mcp.json - Common MCP servers for all repos{ "mcpServers": { "company-docs": { "command": "npx", "args": ["@company/docs-mcp"], "env": { "DOCS_URL": "https://docs.company.internal" } }, "service-registry": { "command": "npx", "args": ["@company/service-registry-mcp"], "env": { "REGISTRY_URL": "https://registry.company.internal" } }, "shared-db": { "command": "npx", "args": ["@modelcontextprotocol/server-postgres"], "env": { "DATABASE_URL": "${SHARED_DB_URL}" } } }}
Plan the Refactoring
"Analyze impact of renaming UserProfile to UserAccountacross all services. Create refactoring plan."
Create Checkpoints
"Create checkpoint in each affected repository"
Execute in Order
"1. Update shared-libs/types first2. Update user-service API3. Update consuming services4. Update frontend apps"
Validate Changes
"Run integration tests across all services"
Coordinate Commits
"Create linked commits with consistent message:'refactor: Rename UserProfile to UserAccount [TICKET-123]'"
// Example: Updating API across services"@workspace:'User Service' @workspace:'Payment Service' @workspace:'API Gateway'
Task: Add rate limiting to all public endpoints1. Add rate limit middleware to shared-libs2. Update each service to use the middleware3. Configure limits in API gateway4. Update documentation5. Add integration tests
Maintain backward compatibility throughout."
A team migrating from monolith to microservices:
// Before: Monolithlegacy-app/├── src/│ ├── users/│ ├── payments/│ ├── orders/│ └── notifications/
// After: Microservicesservices/├── user-service/├── payment-service/├── order-service/├── notification-service/└── legacy-app/ (being decomposed)
{ "folders": [ {"name": "Legacy (Reference)", "path": "./legacy-app"}, {"name": "User Service", "path": "./services/user-service"}, {"name": "Payment Service", "path": "./services/payment-service"}, {"name": "Migration Scripts", "path": "./migration"} ], "settings": { "cursor.rules": [ "Reference legacy code for business logic", "Maintain API compatibility", "Extract gradually, test thoroughly" ] }}
// Use Cursor to manage migration# Migration workflow using CursorextractService() { local DOMAIN=$1
# 1. Analyze legacy code echo "Analyzing legacy code for $DOMAIN..." cursor legacy-app/ # Use Agent mode (Ctrl+I): # "Find all code related to $DOMAIN functionality" # "List all files, functions, and dependencies for $DOMAIN" # "Identify database tables and queries used by $DOMAIN"
# 2. Generate service scaffold mkdir -p "services/$DOMAIN-service" cd "services/$DOMAIN-service" cursor . # Agent prompt: # "Create a new microservice structure for $DOMAIN" # "Use our standard microservice template from @Docs" # "Include API endpoints, models, and test structure"
# 3. Migrate business logic cursor legacy-app/ "services/$DOMAIN-service/" # Agent prompts: # "Port the $DOMAIN business logic from legacy-app to the new service" # "Maintain exact behavior and all edge cases" # "Create comprehensive tests to verify behavior matches"
# 4. Create adapter layer cursor legacy-app/adapters/ # Agent prompt: # "Create an adapter to redirect $DOMAIN calls to the new service" # "Implement circuit breaker and fallback to legacy code" # "Add feature flag to toggle between legacy and new service"}
Managing multiple frontend applications:
// Workspace for microfrontend architecture{ "folders": [ // Shell application {"name": "Shell App", "path": "./apps/shell"},
// Feature apps {"name": "User Dashboard", "path": "./apps/user-dashboard"}, {"name": "Admin Portal", "path": "./apps/admin-portal"}, {"name": "Analytics", "path": "./apps/analytics"},
// Shared {"name": "Component Library", "path": "./packages/ui-components"}, {"name": "State Management", "path": "./packages/state"}, {"name": "API Client", "path": "./packages/api-client"} ], "cursor": { "crossRepoImports": { "@company/ui": "./packages/ui-components/src", "@company/state": "./packages/state/src", "@company/api": "./packages/api-client/src" } }}
#!/bin/bash# Coordinate branches across repos
FEATURE_BRANCH="feature/add-oauth2"REPOS=("user-service" "api-gateway" "shared-libs")
# Create feature branches in all reposfor repo in "${REPOS[@]}"; do cd "../$repo" git checkout -b "$FEATURE_BRANCH" cd -done
# Use Cursor to make coordinated changescursor --workspace company.code-workspace
// Create linked PRs across repositoriesasync function createLinkedPRs(feature: string, repos: string[]) { const prUrls = [];
for (const repo of repos) { const pr = await github.createPR({ repo, title: `${feature} [Multi-Repo]`, body: ` Part of multi-repo change for ${feature}
Related PRs: ${prUrls.map((url) => `- ${url}`).join('\n')} `, branch: `feature/${feature}`, });
prUrls.push(pr.url); }
// Update all PRs with complete list for (let i = 0; i < prUrls.length; i++) { await github.updatePR(prUrls[i], { body: generatePRBody(feature, prUrls), }); }}
#!/bin/bash# Optimize workspace for specific tasksoptimizeForTask() { local TASK=$1
# Define task dependencies case $TASK in "frontend") REQUIRED_REPOS="web-app design-system shared-components" ;; "backend") REQUIRED_REPOS="api-gateway auth-service data-service shared-libs" ;; "fullstack") REQUIRED_REPOS="web-app api-gateway auth-service shared-libs" ;; esac
# Create optimized workspace file cat > .cursor/workspace-$TASK.code-workspace << EOF{ "folders": [EOF
# Add required repos to workspace for repo in $REQUIRED_REPOS; do cat >> .cursor/workspace-$TASK.code-workspace << EOF { "path": "../$repo", "name": "$repo" },EOF done
# Close the workspace file cat >> .cursor/workspace-$TASK.code-workspace << EOF ], "settings": { "cursor.ai.model": "claude-3.5-sonnet", "search.exclude": { "**/node_modules": true, "**/dist": true, "**/build": true } }}EOF
# Open optimized workspace cursor .cursor/workspace-$TASK.code-workspace
echo "Workspace optimized for $TASK development" echo "Loaded repos: $REQUIRED_REPOS"}
# Example usage:# optimizeForTask "frontend"# optimizeForTask "backend"# optimizeForTask "fullstack"
// Multi-repo cache configuration{ "cursor.cache": { "sharedCache": true, "cacheLocation": "~/.cursor/multi-repo-cache", "perRepoLimit": "500MB", "totalLimit": "5GB", "ttl": "7d" }}
Create a multi-repo documentation hub:
# Service Architecture Overview
## Service Map
```mermaidgraph TB Gateway[API Gateway] UserSvc[User Service] PaymentSvc[Payment Service] NotifSvc[Notification Service]
Gateway --> UserSvc Gateway --> PaymentSvc UserSvc --> NotifSvc PaymentSvc --> NotifSvc```
## Best Practices
<CardGrid> <Card title="Start Small" icon="seedling"> Begin with 2-3 related repos, expand gradually </Card> <Card title="Consistent Structure" icon="building"> Maintain similar directory structures across repos </Card> <Card title="Shared Tooling" icon="wrench"> Use common linters, formatters, and build tools </Card> <Card title="Document Dependencies" icon="book"> Keep dependency graphs up-to-date </Card></CardGrid>
<Aside type="caution"> **Performance Warning**: Opening too many repositories simultaneously can degrade Cursor's performance. Start with essential repos and add others as needed.</Aside>
## Next Steps
Master multi-repo workflows:
1. **Set Up Your First Multi-Root Workspace** - Start with 2-3 repos2. **Implement Shared Configuration** - Standardize across repos3. **Practice Cross-Repo Refactoring** - Try a simple rename4. **Explore Custom Rules** - Continue to the next section
Remember: Multi-repo workflows are about maintaining coherence across distributed systems. Master this, and you'll handle complex architectures with ease.