# cplusplus_mcp **Repository Path**: white0o0/cplusplus_mcp ## Basic Information - **Project Name**: cplusplus_mcp - **Description**: No description available - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-02-02 - **Last Updated**: 2026-03-05 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # C++ MCP Server [![Tests](https://github.com/anthropics/cplusplus-mcp/actions/workflows/test.yml/badge.svg)](https://github.com/anthropics/cplusplus-mcp/actions/workflows/test.yml) [![Code Quality](https://github.com/anthropics/cplusplus-mcp/actions/workflows/code-quality.yml/badge.svg)](https://github.com/anthropics/cplusplus-mcp/actions/workflows/code-quality.yml) [![codecov](https://codecov.io/gh/anthropics/cplusplus-mcp/branch/main/graph/badge.svg)](https://codecov.io/gh/anthropics/cplusplus-mcp) **High-performance semantic C++ code analysis with pure C++ implementation (v4.0.0)** An MCP (Model Context Protocol) server for analyzing C++ codebases using libclang with a pure C++ implementation via pybind11 for maximum performance. ## Why Use This? Instead of having Claude grep through your C++ codebase trying to understand the structure, this server provides semantic understanding of your code. Claude can instantly find classes, functions, and their relationships without getting lost in thousands of files. It understands C++ syntax, inheritance hierarchies, and call graphs - giving Claude the ability to navigate your codebase like an IDE would. ## v4.0.0 Architecture **Major Changes from v3.x:** - **Pure C++ Implementation**: All analysis logic now runs in C++ via pybind11 bindings - **Automatic Project Indexing**: `index_project()` now automatically discovers and indexes C++ files from compile_commands.json - **Removed Python Fallback**: The Python implementation has been completely removed - **28,857 Lines Removed**: Cleaner, faster, more maintainable codebase - **RPATH Configuration**: Automatic library path resolution for local dependencies ## Performance Highlights | Metric | v3.x (Python) | v4.0.0 (C++) | Improvement | |--------|---------------|--------------|-------------| | **Indexing Speed** | 150 files/sec | 200+ files/sec | **+33%** | | **Query Latency (p95)** | 0.013ms | 0.008ms | **-38%** | | **Memory Usage** | 100-300MB | 50-150MB | **-50%** | | **Large Projects** | ~2 min | ~1.5 min | **-25%** | *Note: v4.0.0 requires the C++ extension to be properly built and installed.* ## Features ### 12 Core APIs (v5.0.0 Ultimate API Design) #### Project Management (2 APIs) - **set_project_directory** - Set project path with automatic indexing (200+ files/second) - **refresh_project** - Refresh project index with incremental updates #### Understanding Layer (4 APIs) - **get_project_overview** - Get project statistics, structure, and core symbols - **get_file_context** - Get file-level context including symbols and dependencies - **search_symbols** - Unified symbol search with type filtering (replaces search_classes, search_functions, etc.) - **get_symbol_context** - Get comprehensive symbol context (replaces get_class_info, get_function_signature, etc.) #### Analysis Layer (4 APIs) - **analyze_relationship** - Analyze relationships between symbols (inheritance, calls, references, dependencies) - **analyze_impact** - Analyze impact of symbol changes with testing suggestions - **analyze_code_path** - Find code paths between symbols (call paths, data flow, inheritance) - **analyze_dependencies** - Analyze dependencies with cycle detection and visualization #### Configuration Layer (2 APIs) - **get_completion** - Get code completion suggestions at cursor position - **get_diagnostics** - Get diagnostics (errors, warnings) with fix suggestions ### Migration from Old APIs The new unified API design replaces 45+ scattered APIs with 12 carefully designed interfaces: | Old APIs | New API | |----------|---------| | search_classes, search_functions, search_variables, find_in_file | search_symbols(type=...) | | get_class_info, get_function_signature, get_class_hierarchy | get_symbol_context(mode=...) | | find_callers, find_callees, get_call_path | get_symbol_context(mode=DETAILED) or analyze_relationship() | | find_symbol_references, get_symbol_dependencies | analyze_relationship() or analyze_dependencies() | See [docs/MIGRATION.md](docs/MIGRATION.md) for detailed migration guide. ## Standalone Library Usage The `cpp_analyzer` package can be used independently as a standalone library: ```python from cpp_analyzer import CppAnalyzer from pathlib import Path # Initialize analyzer for your project # Supports both string and pathlib.Path objects analyzer = CppAnalyzer("/path/to/project") # Or using pathlib.Path (recommended for better cross-platform compatibility) analyzer = CppAnalyzer(Path("/path/to/project")) # Index the codebase # Note: index_project() now automatically discovers and indexes all C++ files # from compile_commands.json. No manual file specification required. analyzer.index_project() # For detailed information about project setup, indexing performance, # error handling, and response formats, see the # [set_project_directory API documentation](docs/FEATURES/set_project_directory.md) # Search for classes classes = analyzer.search_classes("MyClass") for cls in classes: print(f"Found {cls['name']} in {cls['file']}:{cls['line']}") # Get detailed class information info = analyzer.get_class_info("MyClass") print(f"Methods: {info['methods']}") print(f"Base classes: {info['base_classes']}") # Analyze call graphs callers = analyzer.find_callers("myFunction") for caller in callers: print(f"{caller['name']} calls myFunction") ``` **Automatic Indexing**: `index_project()` now automatically discovers C++ files from `compile_commands.json` and performs complete indexing. No manual file specification or configuration needed. **Path Handling**: The C++ extension automatically handles both string paths and `pathlib.Path` objects, with automatic path separator normalization for cross-platform compatibility (Windows backslashes → POSIX forward slashes). ## Prerequisites - Python 3.9 or higher - pip (Python package manager) - Git (for cloning the repository) - LLVM's libclang (the setup scripts will attempt to download a portable build) - **compile_commands.json**: Your C++ project MUST generate this file for accurate parsing - **Optional C++ Compiler**: For native extension compilation - Clang 14+ with C++20 support (recommended) - GCC 11+ with C++20 support - MSVC 19+ with C++20 support ### Build Requirements (for C++ extension) - CMake 3.10 or higher - pybind11 (included in setup) - make/ninja build system - C++ standard library: libc++ (recommended) or libstdc++ ### What is compile_commands.json? `compile_commands.json` is a JSON database that contains exact compiler commands for every source file in your project. This is **REQUIRED** for the C++ analyzer to work correctly. **Without `compile_commands.json`, the analyzer will fail to start.** > **Detailed compilation configuration instructions (including generation methods for various build systems), see [docs/COMPILE_COMMANDS.md](docs/COMPILE_COMMANDS.md)** ## Setup 1. Clone the repository: ```bash git clone cd CPlusPlus-MCP-Server ``` 2. Run the setup script for your platform (this creates a virtual environment, installs dependencies, and fetches libclang if possible): - **Windows** ```bash setup-dev.bat --dev ``` - **Linux/macOS** ```bash ./setup-dev.sh --dev ``` 3. Test the installation (recommended): ```bash # Activate the virtual environment first source mcp_env/bin/activate # Linux/macOS mcp_env\Scripts\activate # Windows # Run the installation test python scripts/setup/test_installation.py ``` This will verify that all components are properly installed and working. 4. **Generate compile_commands.json for your C++ project** (REQUIRED): The C++ analyzer **requires** `compile_commands.json` to parse your code correctly. **Quick generation** (using the unified test script): ```bash python scripts/test.py --generate-compile-commands ``` **Or with CMake directly**: ```bash cmake -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_CXX_FLAGS="-stdlib=libc++" \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -B cpp_test_project/build ln -s cpp_test_project/build/compile_commands.json . ``` **Other build systems** (Meson, Bazel, Bear, etc.) detailed instructions, see [docs/COMPILE_COMMANDS.md](docs/COMPILE_COMMANDS.md) ## Configuring Claude Code To use this MCP server with Claude Code, you need to add it to your Claude configuration file. 1. Find and open your Claude configuration file. Common locations include: ``` C:\Users\\.claude.json C:\Users\\AppData\Roaming\Claude\.claude.json %APPDATA%\Claude\.claude.json ``` The exact location may vary depending on your Claude installation. 2. Add the C++ MCP server to the `mcpServers` section: ```json { "mcpServers": { "cpp-analyzer": { "command": "python", "args": [ "-m", "mcp_server.cpp_mcp_server" ], "cwd": "YOUR_INSTALLATION_PATH_HERE", "env": { "PYTHONPATH": "YOUR_INSTALLATION_PATH_HERE" } } } } ``` **IMPORTANT:** Replace `YOUR_INSTALLATION_PATH_HERE` with the actual path where you cloned this repository. 3. Restart Claude Desktop for the changes to take effect. ### Performance Configuration (Optional) For optimal performance with C++ extension, you can add these environment variables: ```json { "env": { "PYTHONPATH": "YOUR_INSTALLATION_PATH_HERE", "CPP_MCP_ENABLE_CXX_EXTENSION": "1", "CPP_MCP_MAX_WORKERS": "8", "CPP_MCP_CACHE_DIR": "/custom/cache/path" } } ``` ### Virtual Environment Activation The MCP server will automatically detect and use the virtual environment (`mcp_env/`) created during setup. Ensure your Claude Code configuration has the correct paths to the virtual environment's Python executable. ## Configuring Codex CLI To use this MCP server inside the OpenAI Codex CLI: 1. Make sure the virtual environment is created (see setup above). 2. Create a `.mcp.json` file in the project you open with Codex. The CLI reads this file to discover MCP servers. 3. Add an entry that points to the Python module inside the virtual environment. Replace `YOUR_REPO_PATH` with the absolute path to this repository. ```json { "mcpServers": { "cpp-analyzer": { "type": "stdio", "command": "YOUR_REPO_PATH/mcp_env/bin/python", "args": [ "-m", "mcp_server.cpp_mcp_server" ], "env": { "PYTHONPATH": "YOUR_REPO_PATH" } } } } ``` On Windows change `command` to `YOUR_REPO_PATH\\mcp_env\\Scripts\\python.exe`. 4. Restart the Codex CLI (or run `codex reload`) so it picks up the new server definition. 5. Inside Codex, use the MCP palette or prompt instructions (for example, "use the cpp-analyzer tool to set the project directory to ...") to start indexing your C++ project. If you keep the `.mcp.json` file inside this repository you can also add a `"cwd": "YOUR_REPO_PATH"` entry so Codex launches the server from the correct directory. ## Usage with Claude Once configured, you can use the C++ analyzer in your conversations with Claude: ### 1. Set Project Directory First, ask Claude to set your project directory using the MCP tool: ``` "Use the cpp-analyzer tool to set the project directory to C:\path\to\your\cpp\project" ``` **Automatic Indexing**: When you set the project directory, the analyzer automatically: - Discovers all C++ files from `compile_commands.json` - Indexes the entire project (200+ files/second with C++ extension) - Builds symbol indices for fast queries - Caches results for subsequent use **Note:** The initial indexing might take a long time for very large projects (several minutes for codebases with thousands of files). The server will cache the results for faster subsequent queries. ### 2. Basic Analysis Then you can ask questions like: - "Find all classes containing 'Actor'" - "Show me the Component class details" - "What's the signature of BeginPlay function?" - "Search for physics-related functions" - "Show me the inheritance hierarchy for GameObject" - "Find all functions that call Update()" - "What functions does Render() call?" ### 3. Performance-Intensive Queries (v2.7.0) For better performance on large codebases, use the native C++ tools: - "Use search_classes_native to find all GUI classes" - "Use find_callers_native to find all callers of processFrame" - "Get performance metrics for the last 100 queries" ### 4. Performance Monitoring Monitor system performance: - "Show me the current performance dashboard" - "What's the cache hit rate?" - "How many concurrent queries are being processed?" - "What's the average query latency?" ### 5. Advanced Features - "Find all template functions with template parameters" - "Show me lambda functions with capture information" - "Get symbol dependencies for MyClass" - "Export call graph to DOT format" ## Architecture ### Current Architecture (v2.7.0 - 2026-02-24) **Core Features**: - **Hybrid Architecture** - C++ QueryOrchestrator with Python MCP adapter (v2.7.0) - **Ultra-high Performance** - 352K concurrent QPS, < 0.2ms query latency - **Advanced C++20 Optimizations** - Heterogeneous lookup, atomic statistics, cache warmup - **Zero-copy Data Transfer** - Move semantics between C++ and Python layers - **Intelligent Fallback** - Automatic fallback to Python when C++ extension unavailable - **Enhanced Caching** - SmartLRUCache with >98% hit rate and cache warmup - **Thread-safe Design** - Lock-free statistics and concurrent query support ### Architecture Diagram ``` ┌─────────────────────────────────────────────────────────────┐ │ MCP Client (Claude/Codex) │ └─────────────────────────────────┬───────────────────────────┘ │ ┌─────────────────────────────────▼───────────────────────────┐ │ cpp_mcp_server.py (Python) │ │ - Lightweight MCP protocol adapter │ │ - Tool registration and routing │ │ - Error handling and response formatting │ └─────────────────────────────────┬───────────────────────────┘ │ C++ Extension Available? ▲ │ ▼ │ │ │ ┌─────────┘ │ └─────────┐ │ Yes │ No │ │ │ │ ┌───────────────▼──────────┐ ┌───┴─────────────────▼───────────┐ │ C++ QueryOrchestrator │ │ Python QueryOrchestrator │ │ (cpp_orchestrator) │ │ (query_orchestrator.py) │ │ │ │ │ │ • Zero-copy operations │ │ • Full feature parity │ │ • Heterogeneous lookup │ │ • Graceful fallback │ │ • Atomic statistics │ │ • Pure Python implementation │ │ • Cache warmup │ │ │ │ • GIL release │ │ │ └───────────────┬──────────┘ └─────────────────┬─────────────┘ │ │ └─────────────┬─────────────────┘ │ ┌─────────────────────▼─────────────────────────────┐ │ C++ Core Library │ │ (cpp_analyzer/src) │ │ │ │ • Symbol Parser (libclang wrapper) │ │ • Index Manager (O(1) lookup) │ │ • SmartLRUCache (thread-safe) │ │ • Parallel Parser (thread pool) │ │ • Concurrency Abstraction │ └─────────────────────────────────────────────────────┘ ``` ### Key Architecture Components - Uses libclang for accurate C++ parsing - Caches parsed AST for improved performance - Supports incremental analysis and project-wide search - Provides detailed symbol information including: - Function signatures with parameter types and names - Class members, methods, and inheritance - Call graph analysis for understanding code flow - File locations for easy navigation ## Configuration Options The server behavior can be configured via `cpp-analyzer-config.json`: ```json { "exclude_directories": [".git", ".svn", "node_modules", "build", "Build", "vcpkg_installed", "third_party"], "exclude_patterns": ["*.generated.h", "*.generated.cpp", "*_test.cpp"], "max_file_size_mb": 10, "compile_commands_path": "build/compile_commands.json" } ``` - **exclude_directories**: Directories to skip during project scanning - **exclude_patterns**: File patterns to exclude from analysis - **max_file_size_mb**: Maximum file size to analyze (larger files are skipped) - **compile_commands_path**: (Optional) Explicit path to compile_commands.json if auto-detection fails **Note**: Compile commands are automatically loaded from `compile_commands.json`. The analyzer searches for this file in common locations (project root, `build/`, `out/`, etc.). Use `compile_commands_path` only if the file is in a non-standard location. ## Troubleshooting ### Common Issues 1. **"compile_commands.json not found" error** - **This is the most common issue** - the analyzer requires compile_commands.json to function - Ensure you've generated compile_commands.json for your C++ project (see Setup step 4) - Verify the file exists: `ls compile_commands.json` or `dir compile_commands.json` - Check that it contains your source files: `cat compile_commands.json | grep ".cpp"` - The analyzer automatically searches for compile_commands.json in: - Project root directory - `build/` directory - `out/` directory - `cmake-build-*/` directories - If your file is in a non-standard location, specify it in `cpp-analyzer-config.json`: ```json { "compile_commands_path": "path/to/your/compile_commands.json" } ``` 2. **"libclang not found" error** - Run `server_setup.bat` (Windows) or `./server_setup.sh` (Linux/macOS) to let the project download libclang automatically - If automatic download fails, manually download libclang: 1. Go to: https://github.com/llvm/llvm-project/releases 2. Download the appropriate file for your system: - **Windows**: `clang+llvm-*-x86_64-pc-windows-msvc.tar.xz` - **macOS**: `clang+llvm-*-x86_64-apple-darwin.tar.xz` - **Linux**: `clang+llvm-*-x86_64-linux-gnu-ubuntu-*.tar.xz` 3. Extract and copy the libclang library to the appropriate location: - **Windows**: Copy `bin\libclang.dll` to `lib\windows\libclang.dll` - **macOS**: Copy `lib\libclang.dylib` to `lib\macos\libclang.dylib` - **Linux**: Copy `lib\libclang.so.*` to `lib\linux\libclang.so` 3. **Server fails to start** - Check that Python 3.9+ is installed: `python --version` - Verify all dependencies are installed: `pip install -r requirements.txt` - Run the installation test to identify issues: ```bash mcp_env\Scripts\activate python -m mcp_server.test_installation ``` 4. **Claude doesn't recognize the server** - Ensure the paths in `.claude.json` are absolute paths - Restart Claude Desktop after modifying the configuration 5. **Claude uses grep/glob instead of the C++ analyzer** - Be explicit in prompts: Say "use the cpp-analyzer to..." when asking about C++ code - Add instructions to your project's `CLAUDE.md` file telling Claude to prefer the cpp-analyzer for C++ symbol searches - The cpp-analyzer is much faster than grep for finding classes, functions, and understanding code structure ## Usage Examples ### Basic Usage ```python # Set the project directory (must contain compile_commands.json) set_project_directory("/path/to/your/cpp/project") # Search for classes search_classes(".*Manager") # Get detailed class information get_class_info("UserManager") # Find function callers find_callers("processData") ``` **Note**: The `set_project_directory` API automatically discovers and indexes all C++ files from `compile_commands.json`. See [set_project_directory API documentation](docs/FEATURES/set_project_directory.md) for detailed response formats, error codes, and performance expectations. ## Documentation ### Quick Start - [Quick Start Guide](docs/GETTING_STARTED.md) - Environment setup and basic usage - [Deployment Guide](docs/DEPLOYMENT_GUIDE.md) - Production deployment and optimization - [Compile Commands Guide](docs/COMPILE_COMMANDS.md) - compile_commands.json detailed guide - [Configuration Guide](docs/CONFIGURATION.md) - Project configuration file and tools - [set_project_directory API](docs/FEATURES/set_project_directory.md) - Detailed project setup and indexing ### Feature Details - [set_project_directory API](docs/FEATURES/set_project_directory.md) - Enhanced project setup with automatic indexing - [Symbol Reference Analysis](docs/FEATURES/reference_analysis.md) - Symbol usage tracking - [Advanced Search Features](docs/FEATURES/advanced_search.md) - Advanced search features - [Function Signatures](docs/FEATURES/function_signatures.md) - Function signatures and parameter information - [C++20 Support](docs/FEATURES/cpp20_support.md) - C++20 features support ### Development Guide - [Migration Guide](docs/developer/guides/migration.md) - Version migration notes - [Performance Optimization Guide](docs/developer/guides/optimization.md) - Performance optimization suggestions - [Testing Guide](docs/developer/guides/testing.md) - Testing strategies and coverage - [C++ Coverage Guide](docs/testing/guides/cpp_coverage_guide.md) - C++ test coverage collection with gcov/lcov ### Production Deployment - [Production Checklist](docs/PRODUCTION_CHECKLIST.md) - Pre-deployment verification checklist