An advanced MCP (Model Context Protocol) server for CodeQL integration with Claude Code, featuring AI-optimized responses, natural language query generation, and intelligent error recovery.
This MCP server provides comprehensive documentation directly through the MCP protocol itself:
- Tool Descriptions: Each tool exposes detailed descriptions including usage notes, warnings, and examples
- Parameter Documentation: Every parameter includes format specifications, examples, and defaults in the
inputSchema - Error Messages: Actionable error messages with specific problem identification and solution suggestions
- No External Docs Needed: MCP clients receive all necessary information through the protocol - no external documentation required
- 🔍 Comprehensive Code Analysis - Security, quality, and structural analysis
- 💬 Natural Language Queries - Convert English to CodeQL queries
- ⚡ Incremental Analysis - 10x faster for small changes
- 🤖 AI-Optimized - Token reduction and structured responses
- 🔄 Smart Caching - Persistent cache for improved performance
- 🛡️ Intelligent Error Recovery - Automatic retry and fallback strategies
- 🌊 Stream Processing - Memory-efficient processing of large files (>10MB)
- 📊 Performance Monitoring - Comprehensive timing, memory, and throughput metrics
- 🌍 Multi-Language Support - Full support for 9 languages, experimental support for 4+
These languages have complete CodeQL extractors with full security, quality, and structural analysis:
| Language | Version Support | Query Packs | Features |
|---|---|---|---|
| C | C89-C23 (beta for C23) | cpp-security-extended, cpp-code-quality-extended | Full dataflow, taint tracking |
| C++ | C++98-C++23 (beta for C++23) | cpp-security-extended, cpp-code-quality-extended | Full dataflow (no C++20 modules) |
| C# | Up to version 13 | csharp-security-extended, csharp-code-quality-extended | Full .NET analysis |
| Go | Up to version 1.25 | go-security-extended, go-code-quality-extended | Full module support |
| Java | Versions 7-24 | java-security-extended, java-code-quality-extended | Spring, Android support |
| JavaScript | ES2023+ | javascript-security-extended, javascript-code-quality-extended | React, Node.js, Vue support |
| Python | 2.7, 3.5-3.13 | python-security-extended, python-code-quality-extended | Django, Flask support |
| Ruby | Up to version 3.3 | ruby-security-extended, ruby-code-quality-extended | Rails support |
| TypeScript | Versions 2.6-5.8 | javascript-security-extended, javascript-code-quality-extended | Full type analysis |
These languages have CodeQL extractors but with experimental or limited capabilities:
| Language | Version Support | Query Packs | Limitations |
|---|---|---|---|
| GitHub Actions | YAML workflows | actions-security, actions-best-practices | Experimental, workflow analysis only |
| Kotlin | 1.6.0-2.2.2 | java-security-extended | Uses Java query packs |
| Rust | Editions 2021, 2024 | rust-security-extended | Requires rustup, experimental |
| Swift | 5.4-6.1 | swift-security-extended | macOS only, experimental |
| Language | Status | Notes |
|---|---|---|
| Scala | Community | Limited query packs, basic analysis |
| Language | Status | Notes |
|---|---|---|
| HTML | Pattern matching only | Basic text analysis, no AST |
| XML | Pattern matching only | Basic structure analysis |
| YAML | Pattern matching only | Configuration file analysis |
| Properties | Pattern matching only | Java properties file support |
# Clone and run automated setup
git clone https://github.com/codeql/mcp-server
cd codeql-mcp-server
npm run setup
# Add to Claude Code (use absolute path)
claude mcp add -s user codeql "node" "$(pwd)/dist/index.js"The server includes comprehensive performance monitoring with detailed timing, memory usage, and throughput metrics:
# Run performance tests
npm run test:performance
# Run performance examples and demos
npm run performance:demo
# View performance monitoring documentation
open docs/PERFORMANCE_MONITORING.md- High-resolution timing with
performance.now()andprocess.hrtime.bigint() - Memory usage tracking with before/after snapshots and delta calculations
- Throughput metrics for operations processing files, lines, or bytes
- Performance statistics with percentiles, averages, and success rates
- Automatic instrumentation via decorators and wrappers
- Configurable monitoring with enable/disable and threshold controls
# Performance monitoring configuration
PERFORMANCE_MONITORING_ENABLED=true # Enable/disable monitoring
PERFORMANCE_HISTORY_SIZE=1000 # Max measurements to retain
PERFORMANCE_AUTO_LOG=false # Auto-log performance metrics
PERFORMANCE_INCLUDE_MEMORY=true # Include memory snapshots
PERFORMANCE_MIN_LOG_DURATION=100 # Min duration to log (ms)import { timeAsync, performanceMonitor } from './utils/performance-monitor.js';
// Time an async operation
const result = await timeAsync('database-creation', async () => {
return await createDatabase(params);
}, 'database-component');
// Get performance statistics
const stats = performanceMonitor.getOperationStats('database-creation');
console.log(`Average: ${stats.avgDuration}ms, Success: ${stats.successRate}%`);- Getting Started - Setup and configuration for Claude Code
- API Reference - Complete tool API documentation
- Tools Guide - Practical usage examples and workflows
- Architecture - System design and components
- Features - Comprehensive feature overview
- Security - Security model and best practices
- Testing - Testing strategy and guidelines
- Workflows - Common usage patterns
# Clone repository
git clone https://github.com/codeql/mcp-server
cd codeql-mcp-server
# Install dependencies and build
npm install
npm run build
# Add to Claude Code
claude mcp add codeql "node" "$(pwd)/dist/index.js"For detailed setup instructions, see CLAUDE.md.
The MCP server provides 11 comprehensive MCP tools for complete CodeQL integration.
Create a CodeQL database for code analysis.
Parameters:
projectPath(string, required): Path to the project to analyzelanguage(string, optional): Programming language (auto-detect if not specified)useCache(boolean, optional): Use cached database if available (default: true)
Run comprehensive CodeQL analysis.
Parameters:
databasePath(string, required): Path to CodeQL databasequeryPack(string, optional): Query pack to use (default: javascript-security-extended)outputFormat(enum, optional): Output format - sarif/csv/json (default: sarif)parallel(boolean, optional): Use parallel execution (default: true)
Query Packs:
{language}-security-extended- Comprehensive security analysis (e.g.,javascript-security-extended){language}-code-quality- Code quality and maintainability checks (e.g.,python-code-quality){language}-cwe-extended- CWE-specific vulnerability detection (e.g.,java-cwe-extended)- Language-specific packs ensure optimal analysis for each programming language
Execute a specific CodeQL query.
Parameters:
databasePath(string, required): Path to CodeQL databasequery(string, required): Query path or inline QL codetimeout(number, optional): Query timeout in seconds (default: 3600)
Process SARIF results with various operations.
Parameters:
sarifPath(string, required): Path to SARIF fileoperation(enum, required): Operation to perform (summarize/filter/merge/convert)filter(string, optional): Filter criteria (for filter operation)targetFormat(enum, optional): Target format (for convert operation)
Extract codebase structure for understanding.
Parameters:
databasePath(string, required): Path to CodeQL databaseextractType(enum, required): Type of structure to extractarchitecture- Overall system architecturedependencies- Dependency graphapi- Public API surfacecomplexity- Complexity metrics
depth(number, optional): Analysis depth (default: 3)
Search for code patterns using various methods.
Parameters:
databasePath(string, required): Path to CodeQL databasepattern(string, required): Pattern to search forpatternType(enum, optional): Type of pattern search (regex/ast/dataflow)maxResults(number, optional): Maximum results (default: 100)scope(enum, optional): Search scope (all/methods/classes/expressions/statements)
Get code metrics and statistics.
Parameters:
databasePath(string, required): Path to CodeQL databasemetricType(enum, optional): Type of metrics (loc/complexity/dependencies/all)
Convert natural language to CodeQL queries.
Parameters:
description(string, required): Natural language descriptionlanguage(string, required): Target programming languagerefine(boolean, optional): Provide refinement suggestions (default: false)
Response Example:
{
"query": "import java\n...",
"intent": {
"type": "vulnerability",
"confidence": 0.85
},
"explanation": "Query explanation",
"refinementSuggestions": ["Add limit", "Specify severity"]
}Perform incremental analysis on changed files.
Parameters:
projectPath(string, required): Path to the projectlanguage(string, required): Programming languagequeryType(string, required): Type of analysisqueryParams(object, optional): Additional parameters
List all supported CodeQL languages and their extractors.
Parameters: None
Returns: List of supported languages with their names, display names, and extractor availability. Note: PHP is included for detection only but has no CodeQL analysis capabilities.
Automatically detect the primary language of a project.
Parameters:
projectPath(string, required): Path to the project directory
Returns: Detected language with confidence score and file extensions found. Languages without extractor support (e.g., PHP) can be detected but cannot be analyzed.
Reduces response size while maintaining essential information for AI consumption.
- Detail Levels:
- SUMMARY (<100 tokens)
- ESSENTIAL (<500 tokens)
- DETAILED (<2000 tokens)
- FULL (no limit)
- Smart Summarization: Generates concise one-line summaries
- Streaming Support: Handles large datasets in chunks
- 70-90% reduction in response size for large results
Memory-efficient processing of large files with automatic threshold detection.
- Automatic Detection: Files >10MB automatically use streaming
- Backpressure Handling: Prevents memory exhaustion during large operations
- Memory Monitoring: Built-in memory usage tracking and reporting
- Smart Fallback: Seamless fallback to regular processing for small files
- 88% memory reduction for files >50MB compared to regular processing
Converts natural language descriptions into CodeQL queries.
- Intent Recognition: Identifies vulnerability, pattern, dataflow, metric, and antipattern queries
- Condition Extraction: Parses natural language conditions
- Query Refinement: Suggests improvements to queries
- 85% accuracy in intent recognition
Example:
Input: "Find all functions with complexity greater than 10"
Output: CodeQL query with proper syntax and optimizations
Provides structured error responses with recovery strategies.
- Error Classification: 10 error types with specific handling
- Recovery Strategies: Retry, fallback, timeout, circuit breaker patterns
- Actionable Suggestions: Context-aware recovery recommendations
- 3x retry with exponential backoff
Tracks file changes and performs smart incremental analysis.
- File Change Detection: SHA-256 based content hashing
- Smart Analysis Decision: Incremental for <10 files, full for larger changes
- Results Caching: Persistent cache with TTL
- 10x faster for small changes (<10 files)
Once installed, simply ask Claude:
"Analyze this project for security vulnerabilities"
"Find all SQL injection risks in the Java code"
"Generate a query to find functions with complexity > 10"
"Search for hardcoded passwords"
"Find unused variables in Python code"
"Show me all public APIs in this codebase"
"Check GitHub Actions workflows for security issues"
"Find hardcoded secrets in workflow files"
"Detect command injection vulnerabilities in GitHub Actions"
"Review workflow permissions for excessive access"
"Analyze .github/workflows for security best practices"
"Analyze security across all languages in this project"
"Find cross-language dependencies and interactions"
"Search for TODO comments in all supported languages"
"Generate security report for Python, JavaScript and Java code"
"Find similar code patterns across different languages"
mcp-server/
├── src/
│ ├── index.ts # Main server entry point
│ ├── config/ # Modular configuration (refactored)
│ │ ├── index.ts # Main config exports
│ │ ├── database.ts # Database configurations
│ │ ├── performance.ts # Performance & caching settings
│ │ ├── languages.ts # Language configurations
│ │ └── validation.ts # Config validation utilities
│ ├── server/ # Server setup and orchestration
│ │ └── setup.ts # Server initialization logic
│ ├── handlers/ # MCP request and tool handlers
│ ├── schemas/ # Tool parameter schemas
│ ├── tools/ # Modularized CodeQL tools
│ │ ├── analyze/ # Code analysis (modular)
│ │ │ ├── index.ts # Main analysis exports
│ │ │ ├── scanner.ts # Vulnerability scanning
│ │ │ ├── reporter.ts # Report generation
│ │ │ ├── processor.ts # Result processing
│ │ │ ├── cache.ts # Analysis caching
│ │ │ └── types.ts # Analysis type definitions
│ │ ├── query/ # Query execution (modular)
│ │ │ ├── index.ts # Main query exports
│ │ │ ├── executor.ts # Query execution engine
│ │ │ ├── builder.ts # Query construction
│ │ │ ├── validator.ts # Query validation
│ │ │ ├── naturalLanguage.ts # NL to CodeQL conversion
│ │ │ ├── optimizer.ts # Query optimization
│ │ │ └── types.ts # Query type definitions
│ │ ├── sarif/ # SARIF processing (modular)
│ │ │ ├── index.ts # Main SARIF exports
│ │ │ ├── processor.ts # Core SARIF processing
│ │ │ ├── filter.ts # Result filtering
│ │ │ ├── merger.ts # Multi-file merging
│ │ │ ├── converter.ts # Format conversion
│ │ │ ├── types.ts # SARIF type definitions
│ │ │ └── constants.ts # SARIF constants
│ │ ├── search/ # Pattern searching (modular)
│ │ │ ├── index.ts # Main search exports
│ │ │ ├── patterns.ts # Pattern matching
│ │ │ ├── ast.ts # AST-based search
│ │ │ ├── dataflow.ts # Dataflow analysis
│ │ │ ├── regex.ts # Regex search
│ │ │ ├── types.ts # Search type definitions
│ │ │ └── constants.ts # Search constants
│ │ ├── metrics/ # Metrics collection (modular)
│ │ │ ├── index.ts # Main metrics exports
│ │ │ ├── collector.ts # Data collection
│ │ │ ├── analyzer.ts # Metrics analysis
│ │ │ ├── formatter.ts # Output formatting
│ │ │ └── types.ts # Metrics type definitions
│ │ ├── base.ts # Shared tool utilities
│ │ ├── database.ts # Database management
│ │ ├── structure.ts # Structure extraction
│ │ └── languages.ts # Language detection
│ ├── types/ # TypeScript definitions
│ │ ├── index.ts # Main type exports
│ │ ├── errors.ts # Error type definitions
│ │ ├── metrics.ts # Metrics type definitions
│ │ └── validation.ts # Validation type definitions
│ ├── utils/ # Shared utilities
│ │ ├── logger.ts # Logging utilities
│ │ ├── validation-wrapper.ts # Validation helpers
│ │ ├── database-helpers.ts # Database utilities
│ │ └── stream-helpers.ts # Stream processing utilities
│ ├── middleware/ # Request middleware
│ │ ├── rateLimiter.ts # Rate limiting
│ │ ├── rateLimiterConfig.ts # Rate limit configuration
│ │ └── requestId.ts # Request tracking
│ └── security/ # Security utilities
│ └── sanitizer.ts # Input sanitization
├── tests/ # Comprehensive test suites
│ ├── unit/ # Unit tests (80%+ coverage)
│ │ ├── tools/ # Tool-specific tests
│ │ ├── concurrency.test.ts # Concurrency testing
│ │ ├── property-based-final.test.ts # Property-based tests
│ │ ├── stream-helpers.test.ts # Streaming utilities tests
│ │ └── snapshots/ # Test snapshots
│ ├── integration/ # Integration tests
│ │ ├── workflows/ # Workflow integration tests
│ │ ├── streaming-sarif.test.ts # SARIF streaming tests
│ │ └── streaming-metrics.test.ts # Metrics streaming tests
│ └── security/ # Security testing
├── docs/ # Complete documentation
│ ├── API.md # API reference
│ ├── ARCHITECTURE.md # System architecture
│ ├── FEATURES.md # Feature documentation
│ ├── SECURITY.md # Security guidelines
│ ├── TESTING.md # Testing strategy
│ ├── WORKFLOWS.md # Usage workflows
│ └── STREAMING.md # Stream processing guide
├── config/ # Configuration files
├── scripts/ # Build and setup scripts
│ └── benchmark-streaming.js # Performance benchmarking
├── examples/ # Usage examples
└── dist/ # Compiled output
Major Architectural Improvements (Completed):
- ✅ Modular Configuration: Split monolithic
config.tsinto focused modules - ✅ Tool Modularization: Large tool files (1000+ lines) split into logical modules
- ✅ Enhanced Error Handling: Centralized error factories and validation
- ✅ Consolidated Utilities: Eliminated code duplication through shared utilities
- ✅ Improved Separation: Clear boundaries between tools, handlers, and configuration
- ✅ Better Testing: Comprehensive test coverage with property-based and integration tests
- ✅ Dependency Updates: Updated to latest MCP SDK and modern TypeScript tooling
- ✅ Performance Optimizations: Enhanced caching and validation strategies
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
# Run integration tests
npm run test:integration
# Build
npm run build
# Type checking
npm run typecheck
# Linting
npm run lintThe server can be configured through environment variables:
claude mcp add codeql "node" "/path/to/dist/index.js" \
-e CODEQL_BIN=/usr/local/bin/codeql \
-e CODEQL_CACHE_DIR=~/.codeql/cache \
-e CODEQL_RAM=8192 \
-e CODEQL_THREADS=4See docs/CONFIGURATION.md for all options.
- Use caching - Enable
useCachefor repeated analyses - Set appropriate timeouts - Adjust based on query complexity
- Use appropriate detail levels - Choose appropriate response detail for your needs
- Handle errors gracefully - Check
recoverableflag - Use incremental analysis - For iterative development
- Batch operations - Process multiple files together
- Monitor performance - Track cache statistics and query execution times
- Choose appropriate detail levels - Based on token budget
- 10x faster incremental analysis for iterative development workflows
- Smart caching with TTL-based persistence and intelligent invalidation
- Parallel query execution with automatic concurrency management
- Memory optimization through streaming and modular architecture
- 70-90% token reduction observed in production environments
- Intelligent response sizing with 4-tier detail levels (SUMMARY/ESSENTIAL/DETAILED/FULL)
- Streaming support for large datasets to prevent timeouts
- Natural language query generation for improved accessibility
- Modular architecture reduces memory footprint by 30-40%
- Consolidated utilities eliminate code duplication across 8+ files
- Enhanced error recovery with exponential backoff and circuit breaker patterns
- Rate limiting prevents resource exhaustion under heavy load
- Hot-path optimization for frequently used operations
- Comprehensive test coverage (80%+) with property-based testing
- TypeScript strict mode catches errors at compile time
- Automated dependency management with security scanning
# Install dependencies
npm install
# Build TypeScript to JavaScript
npm run build
# Run type checking
npm run typecheck
# Run linting
npm run lint
# Run unit tests (fast, with mocking)
npm test
# Run tests in watch mode for development
npm run test:watch
# Run tests with coverage report
npm run test:coverage
# Run integration tests (requires build first)
npm run build && npm run test:integration
# Run specific test file
npm test -- tests/tools/analyze.test.ts
# Run tests matching a pattern
npm test -- --grep "database"
# Open Vitest UI (interactive test runner)
npx vitest --ui
# Development mode with auto-reload
npm run devThis project uses Vitest as the test runner, providing fast and modern testing capabilities with 95.7% test coverage.
Available Test Commands:
# Run all tests once
npm test
# Run tests in watch mode (auto-rerun on file changes)
npm run test:watch
# Run tests with coverage report
npm run test:coverage
# Run only unit tests
npm run test:unit
# Run only integration tests (requires CodeQL CLI)
npm run test:integration
# Run streaming performance benchmarks
npm run benchmark:streaming
# Run specific test file
npm test -- tests/tools/analyze.test.ts
# Run tests matching a pattern
npm test -- --grep "database"
# Open interactive Vitest UI
npx vitest --uiTest Types:
- Unit Tests: Run with mocked dependencies, no CodeQL CLI required (95.7% coverage)
- Integration Tests: Require CodeQL CLI to be installed and
npm run buildto be run first - Mutation Tests: Advanced testing with Stryker (run with
npm run test:mutation) - Performance Tests: Benchmarking and load testing for optimization
Coverage Reports:
Vitest generates coverage reports in the coverage/ directory. View the HTML report by opening coverage/index.html in your browser after running npm run test:coverage.
Watch Mode:
For development, use npm run test:watch to automatically re-run tests when files change. This provides instant feedback during development.
Known Testing Limitations:
- Some Vitest mock implementations require careful setup for file system operations
- Integration tests require actual CodeQL CLI installation
- Rate limiting tests may experience occasional timing-based failures in CI environments
- Mock state isolation requires comprehensive cleanup patterns (see TESTING.md)
Troubleshooting Test Issues: For detailed troubleshooting guides, including mock setup patterns and common issues, see the comprehensive Testing Guide.
- Node.js 18.0.0 or higher
- CodeQL CLI (auto-installed if not present)
- Claude Code MCP client
MIT
See CONTRIBUTING.md for development setup and guidelines.