Labsco
yangweijie logo

CGM MCP Server

β˜… 1

from yangweijie

A server for CodeFuse-CGM, a graph-integrated large language model designed for repository-level software engineering tasks.

πŸ”₯πŸ”₯πŸ”₯βœ“ VerifiedAccount requiredAdvanced setup

CGM MCP Server

A Model Context Protocol (MCP) server implementation of CodeFuse-CGM (Code Graph Model), providing graph-integrated large language model capabilities for repository-level software engineering tasks.

πŸš€ Features

🎯 Two Deployment Modes

1. Full CGM Pipeline (with LLM integration)

  • Repository-level Code Analysis: Analyze entire codebases using graph-based representations
  • Issue Resolution: Automatically generate code patches to fix bugs and implement features
  • Four-Stage Pipeline: Rewriter β†’ Retriever β†’ Reranker β†’ Reader architecture
  • Multi-LLM Support: Works with OpenAI, Anthropic, Ollama, Ollama Cloud, LM Studio

2. Model-agnostic Tools (pure analysis, no LLM required) ⭐

  • Pure Code Analysis: Extract code structure without LLM dependencies
  • Universal Integration: Works with ANY AI model or IDE
  • No API Keys Required: Zero external dependencies
  • High Performance: Cached analysis results for speed

⚑ Performance & GPU Acceleration

Multi-Platform GPU Support 🎯

  • Apple Silicon (M1/M2/M3): Native MPS acceleration (42x cache speedup!)
  • NVIDIA GPU: Full CUDA support with cuPy integration
  • AMD GPU: ROCm (Linux) and DirectML (Windows) support
  • CPU Fallback: Automatic fallback ensures universal compatibility

☁️ Ollama Cloud Support

Ollama Cloud Provider 🌐

  • Cloud-based Ollama Models: Run Ollama-compatible models in the cloud
  • API Compatibility: Compatible with Ollama API format
  • Easy Configuration: Works with standard Ollama model names
  • Secure Access: Supports API key authentication

Advanced Caching System πŸ—„οΈ

  • Multi-level Caching: TTL cache (1hr) + LRU cache (500 entries) + AST cache
  • Smart Cache Keys: MD5-based cache keys for efficient lookups
  • Memory Management: Real-time monitoring with automatic cleanup
  • Performance Stats: Detailed hit/miss ratios and timing metrics

Concurrent Processing πŸ”„

  • Async File I/O: Non-blocking file operations with aiofiles
  • Batch Processing: Concurrent analysis of multiple files
  • GPU-Accelerated: Entity matching and text processing on GPU
  • Intelligent Scheduling: Semaphore-controlled concurrency limits

πŸ”§ Common Features

  • MCP Integration: Compatible with Claude Desktop, VS Code, Cursor, and other MCP clients
  • Graph-based Context: Leverages code structure and relationships for better understanding
  • Multiple Output Formats: Structured JSON, Markdown, and Prompt formats
  • Real-time Monitoring: GPU usage, memory consumption, and performance metrics

πŸ“‹ Table of Contents

πŸ— Architecture

CGM follows a four-stage pipeline:

graph LR
    A[Issue] --> B[Rewriter]
    B --> C[Retriever]
    C --> D[Reranker]
    D --> E[Reader]
    E --> F[Code Patches]
    
    G[Code Graph] --> C
    G --> D
    G --> E

Components

  1. Rewriter: Analyzes issues and extracts relevant entities and keywords
  2. Retriever: Locates relevant code subgraphs based on extracted information
  3. Reranker: Ranks files by relevance to focus analysis
  4. Reader: Generates specific code patches to resolve issues

Graph Builder

Constructs repository-level code graphs by analyzing:

  • File structure and dependencies
  • Class and function definitions
  • Import relationships
  • Code semantics and documentation

πŸ“š API Reference

Core Models

CGMRequest

class CGMRequest(BaseModel):
    task_type: TaskType
    repository_name: str
    issue_description: str
    repository_context: Optional[Dict[str, Any]] = None

CGMResponse

class CGMResponse(BaseModel):
    task_id: str
    status: str
    rewriter_result: Optional[RewriterResponse]
    retriever_result: Optional[RetrieverResponse]
    reranker_result: Optional[RerankerResponse]
    reader_result: Optional[ReaderResponse]
    processing_time: float

CodePatch

class CodePatch(BaseModel):
    file_path: str
    original_code: str
    modified_code: str
    line_start: int
    line_end: int
    explanation: str

πŸ’‘ Examples

Basic Issue Resolution

import asyncio
from cgm_mcp.server import CGMServer
from cgm_mcp.models import CGMRequest, TaskType

async def resolve_issue():
    server = CGMServer(config)
    
    request = CGMRequest(
        task_type=TaskType.ISSUE_RESOLUTION,
        repository_name="my-app",
        issue_description="Login fails with special characters",
        repository_context={"path": "./my-app"}
    )
    
    response = await server._process_issue(request.dict())
    
    for patch in response.reader_result.patches:
        print(f"File: {patch.file_path}")
        print(f"Changes: {patch.explanation}")

Integration with Claude Desktop

Add to your Claude Desktop MCP configuration:

{
  "mcpServers": {
    "cgm": {
      "command": "python",
      "args": ["/path/to/cgm-mcp/main.py"],
      "env": {
        "CGM_LLM_API_KEY": "your-api-key"
      }
    }
  }
}

πŸ“Š Performance Monitoring

Real-time Metrics

GPU Statistics

{
  "memory": {
    "gpu_available": true,
    "platform": "Apple Silicon",
    "backend": "Metal Performance Shaders",
    "gpu_memory_allocated": 0.6
  },
  "performance": {
    "gpu_entity_matches": 15,
    "cache_hit_rate": 94.2
  }
}

Cache Performance

{
  "analysis_cache": {"size": 45, "maxsize": 100},
  "file_cache": {"size": 234, "maxsize": 500},
  "stats": {"hits": 156, "misses": 23, "hit_rate": 87.2}
}

Performance Testing

# Check GPU acceleration status
python check_gpu_dependencies.py

# Run performance tests
python gpu_verification.py
python test_multiplatform_gpu.py

πŸ§ͺ Testing

# Run tests
pytest tests/

# Run with coverage
pytest tests/ --cov=cgm_mcp

# Run specific test
pytest tests/test_components.py::TestRewriterComponent

# Performance tests
python test_gpu_acceleration.py
python gpu_verification.py

πŸš€ Performance Features Summary

⚑ GPU Acceleration

  • Apple Silicon: Native MPS support with 42x cache speedup
  • NVIDIA GPU: Full CUDA support with cuPy integration
  • AMD GPU: ROCm (Linux) and DirectML (Windows) support
  • Auto-detection: Intelligent platform detection and fallback

πŸ—„οΈ Smart Caching

  • Multi-level: TTL (1hr) + LRU (500 files) + AST (200 trees)
  • Intelligent: MD5-based cache keys with hit rate monitoring
  • Memory-aware: Automatic cleanup at 80% memory usage
  • Performance: 85-95% cache hit rates in production

πŸ”„ Concurrent Processing

  • Async I/O: Non-blocking file operations with aiofiles
  • Batch Processing: Concurrent analysis of multiple files
  • Semaphore Control: Configurable concurrency limits (default: 10)
  • GPU Queuing: Intelligent GPU task scheduling

πŸ“Š Real-time Monitoring

  • GPU Stats: Memory usage, platform detection, performance metrics
  • Cache Analytics: Hit/miss ratios, size monitoring, cleanup events
  • System Metrics: Memory usage, CPU utilization, processing times
  • MCP Resources: cgm://gpu, cgm://cache, cgm://performance

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

πŸ“ž Support


CGM MCP Server - Bringing graph-integrated code intelligence to your development workflow! πŸš€