This is a Model Context Protocol (MCP) server for automated compliance scanning, built with TypeScript/Node.js. The project has evolved through multiple phases and now includes both server-side compliance scanning and a VS Code extension with local compliance engine.
# Juro MCP Server - Cursor Rules
## Project Overview
This is a Model Context Protocol (MCP) server for automated compliance scanning, built with TypeScript/Node.js. The project has evolved through multiple phases and now includes both server-side compliance scanning and a VS Code extension with local compliance engine.
## Architecture & Design Patterns
### Core Architecture
- **Hybrid Server**: Combines HTTP API (port 8080) with MCP TCP server (port 3000)
- **Service Container**: Dependency injection pattern for all services
- **MCP Protocol**: JSON-RPC 2.0 over TCP for AI agent communication
- **Auto-Detection Engine**: Intelligent project type and regulation detection
- **Integrated Compliance**: Uses `@juro/core` and `@juro/rules` packages
- **VS Code Extension**: Local compliance engine with daily rule sync
### Key Services
- `IntegratedComplianceService`: Main compliance scanning engine (server-side)
- `SimpleComplianceEngine`: Local compliance engine (VS Code extension)
- `ProjectDetectionService`: Auto-detects project types (Node.js, Python, Java, Go, Web)
- `RegulationMapper`: Maps project types to relevant regulations
- `RulePackManager`: Manages compliance rule packs with caching
- `ConfigurationGenerator`: Auto-generates project configurations
- `AutoDetectionEngine`: Orchestrates 1-step integration setup
- `RuleSyncManager`: Daily rule synchronization for VS Code extension
## Code Style & Standards
### TypeScript Guidelines
- Use strict TypeScript with proper type definitions
- Prefer interfaces over types for object shapes
- Use `any` sparingly, prefer `unknown` or specific types
- Always handle async/await properly with try-catch
- Use Zod for runtime validation of external data
### File Organization
```
src/
├── core/ # Core MCP server implementation
├── services/ # Business logic services
├── tools/ # MCP tool implementations
├── models/ # Type definitions and interfaces
├── vscode/ # VS Code extension components
│ ├── extension.ts # Main extension entry point
│ ├── providers/ # VS Code providers
│ │ ├── ViolationTreeProvider.ts
│ │ └── ComplianceScoreProvider.ts
│ └── commands/ # Command implementations
├── engine/ # Local compliance engine
│ ├── SimpleComplianceEngine.ts
│ └── RuleSyncManager.ts
├── mcp/ # MCP client implementation
├── config/ # Configuration management
└── utils/ # Utility functions
```
### Naming Conventions
- **Files**: PascalCase for classes, kebab-case for files
- **Classes**: PascalCase (e.g., `IntegratedComplianceService`)
- **Methods**: camelCase (e.g., `scanDirectory`)
- **Constants**: UPPER_SNAKE_CASE
- **Interfaces**: PascalCase with 'I' prefix for service interfaces
## Compliance & Regulations
### Supported Regulations
- **GDPR**: General Data Protection Regulation
- **DORA**: Digital Operational Resilience Act
- **SOC 2**: Service Organization Control 2
- **ISO 27001**: Information Security Management
- **WCAG**: Web Content Accessibility Guidelines
- **OWASP Top 10**: Web Application Security
- **CSP**: Content Security Policy
### File Type Support
Support 20+ programming languages and file types:
- **Backend**: TypeScript, JavaScript, Python, Java, Go, Rust, C/C++, PHP, Ruby
- **Frontend**: HTML, CSS, SCSS, Less, TypeScript React, JavaScript React
- **Config**: JSON, YAML, XML, TOML, INI
- **Docs**: Markdown, AsciiDoc, reStructuredText
- **Deployment**: Docker, Kubernetes, Terraform, Ansible
## Development Guidelines
### Error Handling
- Always use try-catch for async operations
- Log errors with structured logging (winston)
- Provide meaningful error messages to users
- Handle network failures gracefully
- Implement proper cleanup in error scenarios
### Testing Strategy
- **Unit Tests**: Jest for individual service testing
- **BDD Tests**: Gherkin scenarios for integration testing
- **Manual Tests**: Comprehensive test cases for real-world validation
- **Negative Tests**: Error handling and edge case testing
### Performance Considerations
- Use streaming for large file processing
- Implement caching for rule packs and configurations
- Set reasonable file size limits (50MB default)
- Use parallel processing where possible
- Monitor memory usage for large scans
## Integration Patterns
### 1-Step Integration Philosophy
Every integration should be:
- **Zero Configuration**: Works out of the box
- **Auto-Detection**: Automatically detects project type and regulations
- **Smart Defaults**: Provides sensible defaults for all settings
- **Progressive Enhancement**: Allows customization as needed
### VS Code Extension Patterns
- **Local-First**: Prefer local compliance engine over server calls
- **Real-Time**: Provide immediate feedback on file changes
- **Non-Blocking**: Use async operations to avoid UI freezing
- **Debounced**: Implement proper debouncing for file save events
- **Loop Prevention**: Prevent infinite scanning loops with cooldowns
### MCP Tool Implementation
- All tools must implement the `MCPTool` interface
- Use proper JSON-RPC 2.0 response format
- Include comprehensive error handling
- Provide detailed tool descriptions and schemas
- Support both required and optional parameters
### Service Dependencies
- Use dependency injection through `ServiceContainer`
- Avoid circular dependencies
- Keep services focused on single responsibilities
- Use interfaces for service contracts
## File Patterns & Detection
### Include Patterns
```typescript
const includePatterns = [
// Backend languages
'**/*.{ts,js,tsx,jsx,py,java,go,rs,cpp,c,cc,cxx,h,hpp,php,rb}',
// Frontend
'**/*.{html,htm,css,scss,less,vue,svelte}',
// Config files
'**/*.{json,yaml,yml,xml,toml,ini,env,properties}',
// Documentation
'**/*.{md,mdown,markdown,adoc,rst,txt}',
// Deployment
'**/*.{dockerfile,docker-compose.yml,yml,yaml}',
'**/Dockerfile*',
'**/docker-compose*.yml',
// Infrastructure
'**/*.{tf,hcl,json}',
'**/terraform/**/*',
// CI/CD
'**/.github/workflows/*.yml',
'**/.gitlab-ci.yml',
'**/Jenkinsfile*',
'**/azure-pipelines.yml'
];
```
### Local Compliance Engine Patterns
```typescript
// Rule definition structure
interface ComplianceRule {
id: string;
name: string;
description: string;
regulation: 'GDPR' | 'DORA' | 'SOC2' | 'ISO27001';
category: string;
severity: 'HIGH' | 'MEDIUM' | 'LOW';
patterns: string[];
caseSensitive: boolean;
}
// Violation structure
interface ComplianceViolation {
ruleId: string;
ruleName: string;
description: string;
regulation: string;
category: string;
severity: 'HIGH' | 'MEDIUM' | 'LOW';
lineNumber: number;
columnNumber: number;
codeSnippet: string;
filePath: string;
fixSuggestion?: string;
}
```
### Exclude Patterns
```typescript
const excludePatterns = [
'**/node_modules/**',
'**/dist/**',
'**/build/**',
'**/.git/**',
'**/coverage/**',
'**/.nyc_output/**',
'**/tmp/**',
'**/temp/**'
];
```
## Configuration Management
### Environment Variables
- `PORT`: HTTP server port (default: 8080)
- `MCP_PORT`: MCP server port (default: 3000)
- `LOG_LEVEL`: Logging level (debug, info, warn, error)
- `NODE_ENV`: Environment (development, production)
### Configuration Files
- `juro.config.json`: Main configuration
- `juro/rules/`: Rule pack configurations
- `.juroignore`: File exclusion patterns
## Security Considerations
### Data Handling
- Never log sensitive data (passwords, tokens, personal data)
- Use secure file handling for temporary files
- Implement proper input validation
- Sanitize file paths to prevent directory traversal
### Network Security
- Use proper error handling for network operations
- Implement timeouts for all network requests
- Validate all incoming data
- Use HTTPS in production
## Documentation Standards
### Code Documentation
- Use JSDoc for all public methods
- Include parameter types and return types
- Provide usage examples for complex methods
- Document error conditions and exceptions
### API Documentation
- Document all MCP tools with examples
- Include request/response schemas
- Provide integration guides
- Maintain up-to-date README files
## Deployment & Operations
### Build Process
- Use TypeScript compilation with strict mode
- Run tests before deployment
- Generate source maps for debugging
- Optimize bundle size
### Monitoring
- Use structured logging with correlation IDs
- Monitor performance metrics
- Track compliance scan results
- Alert on critical errors
## Common Patterns
### Service Initialization
```typescript
async initialize(): Promise<void> {
try {
// Initialize service
this.logger.info('Service initializing...');
// Perform initialization steps
await this.setup();
this.logger.info('Service initialized successfully');
} catch (error) {
this.logger.error('Service initialization failed:', error);
throw error;
}
}
```
### VS Code Extension Patterns
```typescript
// Extension activation
export function activate(context: vscode.ExtensionContext) {
// Initialize providers
const violationProvider = new ViolationTreeProvider();
const scoreProvider = new ComplianceScoreProvider();
// Register tree views
vscode.window.createTreeView('juro-violations', {
treeDataProvider: violationProvider
});
// Register commands with proper error handling
const scanCommand = vscode.commands.registerCommand('juro.scanFile', async () => {
try {
await scanCurrentFile();
} catch (error) {
vscode.window.showErrorMessage(`Scan failed: ${error.message}`);
}
});
context.subscriptions.push(scanCommand);
}
// Compliance scanning with loop prevention
class ComplianceScanner {
private lastScanTime = 0;
private readonly SCAN_COOLDOWN = 5000; // 5 seconds
async scanFile(document: vscode.TextDocument): Promise<void> {
const now = Date.now();
if (now - this.lastScanTime < this.SCAN_COOLDOWN) {
return; // Prevent scanning loops
}
this.lastScanTime = now;
// Perform scan...
}
}
```
### MCP Tool Implementation
```typescript
const tool: MCPTool = {
name: 'tool_name',
description: 'Tool description',
inputSchema: {
type: 'object',
properties: {
// Define parameters
},
required: ['param1']
},
handler: async (params: any) => {
try {
// Tool logic
return { success: true, result: data };
} catch (error) {
throw new Error(`Tool execution failed: ${error.message}`);
}
}
};
```
### Error Response Format
```typescript
{
jsonrpc: '2.0',
id: requestId,
error: {
code: -32603,
message: 'Internal error',
data: {
type: 'COMPLIANCE_ERROR',
details: 'Specific error details'
}
}
}
```
## Testing Guidelines
### BDD Scenarios
- Use Given-When-Then format
- Test both positive and negative cases
- Include edge cases and error conditions
- Test integration points thoroughly
### Manual Testing
- Test with real project structures
- Verify auto-detection accuracy
- Test error handling scenarios
- Validate performance with large projects
## Future Considerations
### Extensibility
- Design for easy addition of new regulations
- Support for custom rule packs
- Plugin architecture for integrations
- API versioning strategy
### Scalability
- Horizontal scaling considerations
- Database integration for large datasets
- Caching strategies
- Performance monitoring
## Project Evolution & Current State
### Phase 1: Core MCP Server ✅
- [x] Basic MCP server implementation
- [x] HTTP API endpoints
- [x] Compliance scanning tools
- [x] Service container architecture
### Phase 2: Enhanced Integration & File Type Support ✅
- [x] Full integration with `@juro/core` and `@juro/rules`
- [x] Extended file type support (20+ languages)
- [x] Enhanced file pattern matching
- [x] Improved rule loading and error handling
- [x] Performance optimizations
### Phase 3: VS Code Extension with Local Engine ✅
- [x] Local compliance engine implementation
- [x] VS Code extension architecture
- [x] Real-time compliance scanning
- [x] Loop prevention and debouncing
- [x] Daily rule synchronization
- [x] Compliance scoring system
### Current Architecture
- **Server-Side**: MCP server with `@juro/core` integration
- **Client-Side**: VS Code extension with local compliance engine
- **Hybrid Approach**: Local scanning with daily rule sync
- **Performance**: Instant local scanning, no network delays
### Key Achievements
- **151 Tests Passing**: Comprehensive test coverage
- **590+ Violations Detected**: Real compliance scanning results
- **20+ File Types**: Support for all major programming languages
- **22+ Compliance Rules**: GDPR, DORA, SOC 2, ISO 27001 coverage
- **Zero Configuration**: Works out of the box
- **Real-Time Feedback**: Immediate compliance checking
Remember: This project focuses on making compliance scanning as easy as possible for developers while maintaining enterprise-grade reliability and security. The evolution from server-dependent to local-first architecture demonstrates our commitment to user experience and performance.
Comprehensive .cursorrules file for Next.js 15 App Router projects with TypeScript, enforcing server components by default, proper use of "use client" directive, and App Router conventions.
Cursor rules for Python FastAPI projects enforcing async patterns, Pydantic v2 models, dependency injection, and proper error handling.
Rules for consistent React component development with TypeScript interfaces, proper hook patterns, and component composition.
Rules optimizing Cursor Agent mode behavior including multi-file editing context, session management, and autonomous task completion patterns.
Cursor rules for projects using Tailwind CSS with shadcn/ui component library, enforcing consistent utility class usage and component patterns.
Rules for Go backend services enforcing idiomatic Go patterns, proper error handling, and clean architecture conventions.