MCP Integration Overview¶
The Model Context Protocol (MCP) is an open standard that enables AI assistants like Claude Desktop and VS Code extensions to connect to external tools and data sources. The Code Graph Knowledge System provides a complete MCP server implementation with 30 specialized tools.
What is MCP?¶
MCP (Model Context Protocol) is an open protocol developed by Anthropic that allows AI assistants to:
- Access External Tools: Call functions in external applications
- Retrieve Context: Fetch data from databases, APIs, and services
- Execute Actions: Perform operations on behalf of users
- Stream Responses: Receive real-time updates
Think of MCP as a standardized way for AI assistants to "talk to" your applications.
Architecture¶
┌─────────────────────────────────────────────────────┐
│ AI Assistants (MCP Clients) │
│ - Claude Desktop │
│ - Cline (VS Code) │
│ - Custom MCP Clients │
└───────────────────┬─────────────────────────────────┘
│ MCP Protocol over SSE
│ (HTTP/HTTPS)
↓
┌─────────────────────────────────────────────────────┐
│ Two-Port Architecture │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Port 8000 (PRIMARY) │ │
│ │ MCP SSE Server │ │
│ │ - GET /sse (connection) │ │
│ │ - POST /messages/* (client messages) │ │
│ └──────────────┬───────────────────────────────┘ │
│ │ │
│ ┌──────────────┴───────────────────────────────┐ │
│ │ Port 8080 (SECONDARY) │ │
│ │ Web UI + REST API │ │
│ │ - /api/v1/* (REST endpoints) │ │
│ │ - / (React SPA - monitoring) │ │
│ └──────────────┬───────────────────────────────┘ │
│ │ │
└─────────────────┼───────────────────────────────────┘
│
↓
┌─────────────────────────────────────────────────────┐
│ Shared Service Layer │
│ ┌─────────────────────────────────────────────┐ │
│ │ Knowledge RAG │ Code Graph │ │
│ │ Memory Store │ Task Queue │ │
│ │ Neo4j Database │ Git Integration │ │
│ └─────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
Key Design Principles: - Port 8000 (PRIMARY): MCP service - the core functionality for AI assistants - Port 8080 (SECONDARY): Web UI - status monitoring and management only - Shared Services: Both ports access the same service layer - Multi-Process: Two independent uvicorn processes for isolation
System Components¶
1. MCP SSE Server (Port 8000)¶
Files: main.py, core/mcp_sse.py, mcp_server.py
The PRIMARY service that: - Implements MCP protocol using official SDK - Exposes 25+ tools across 6 categories - Manages SSE connections from AI clients - Routes requests to backend services
Key Features: - ✅ Official MCP SDK (mcp>=1.1.0) - ✅ SSE Transport (mcp.server.sse.SseServerTransport) - ✅ Transport-agnostic tool layer - ✅ Session management - ✅ Streaming support - ✅ Network-accessible (Docker-friendly)
Transport Modes:
SSE Transport (Production/Docker)¶
# Used in Docker deployments
# Endpoints:
# GET http://localhost:8000/sse
# POST http://localhost:8000/messages/*
Best for: Docker, remote access, production deployments
Stdio Transport (Local Development)¶
Best for: Claude Desktop (local mode), development
2. MCP Clients¶
AI assistants that connect to the server:
Supported Clients: - Claude Desktop: Official Anthropic desktop app - VS Code: Via MCP extension - Custom Clients: Using MCP SDK
3. Backend Services¶
The actual functionality exposed via MCP: - Knowledge RAG for document Q&A - Code Graph for repository analysis - Memory Store for project knowledge - Task Queue for async operations - Git utilities for repository operations
Available Tools (30 Total)¶
Knowledge Base Tools (5)¶
Process and query documents using RAG:
- query_knowledge: Ask questions, get LLM-generated answers
- search_similar_nodes: Find similar documents via vector search
- add_document: Add document content to knowledge base
- add_file: Process single file
- add_directory: Batch process directory
Availability: Full mode only (requires LLM + embeddings)
Code Graph Tools (4)¶
Analyze code repositories:
- code_graph_ingest_repo: Index repository structure
- code_graph_fulltext_search: Search code by text
- code_graph_impact_analysis: Analyze change impact
- code_graph_pack_context: Build context for LLM
Availability: All modes
Memory Management Tools (7)¶
Store project knowledge for AI agents:
- add_memory: Save decisions, preferences, experiences
- search_memories: Find relevant memories
- get_memory: Retrieve by ID
- update_memory: Modify existing memory
- delete_memory: Remove memory (soft delete)
- supersede_memory: Replace with history preservation
- get_project_summary: Get overview
Availability: All modes
Memory Extraction Tools (5)¶
Automatically extract memories (v0.7):
- extract_from_conversation: Analyze AI conversations
- extract_from_git_commit: Mine git commits
- extract_from_code_comments: Extract TODOs, FIXMEs
- suggest_memory_from_query: Suggest from Q&A
- batch_extract_from_repository: Comprehensive extraction
Availability: Full mode only (requires LLM)
Task Management Tools (6)¶
Monitor async operations:
- get_task_status: Check task status
- watch_task: Monitor single task
- watch_tasks: Monitor multiple tasks
- list_tasks: List all tasks
- cancel_task: Cancel running task
- get_queue_stats: Get queue statistics
Availability: All modes
System Tools (3)¶
System information and management:
- get_graph_schema: Get Neo4j schema
- get_statistics: Get system statistics
- clear_knowledge_base: Clear all data
Availability: All modes
Tool Usage Pattern¶
Example: Query Knowledge Base¶
{
"tool": "query_knowledge",
"input": {
"question": "How do I configure Docker deployment?",
"mode": "hybrid"
}
}
Response:
{
"answer": "To configure Docker deployment, you need to...",
"sources": [
{"title": "Docker Guide", "score": 0.92, "content": "..."}
],
"mode": "hybrid",
"retrieval_time_ms": 150,
"generation_time_ms": 2300
}
Example: Add Memory¶
{
"tool": "add_memory",
"input": {
"project_id": "myapp",
"memory_type": "decision",
"title": "Use PostgreSQL for main database",
"content": "Selected PostgreSQL over MySQL",
"reason": "Need advanced JSON support and better performance",
"importance": 0.9,
"tags": ["database", "architecture"]
}
}
Example: Code Graph Analysis¶
{
"tool": "code_graph_ingest_repo",
"input": {
"repo_path": "/path/to/repo",
"mode": "incremental"
}
}
MCP Protocol Details¶
Transport Methods¶
MCP supports multiple transport protocols:
- stdio (Standard Input/Output)
- Used by Claude Desktop
- Process-based communication
-
Most common for desktop apps
-
SSE (Server-Sent Events)
- HTTP-based streaming
- Used by web applications
-
Good for browser-based clients
-
WebSocket
- Bidirectional streaming
- Real-time updates
- Low latency
Our Implementation: Supports all three via official MCP SDK
Message Types¶
MCP uses JSON-RPC 2.0 protocol:
Request:
{
"jsonrpc": "2.0",
"id": "req-123",
"method": "tools/call",
"params": {
"name": "query_knowledge",
"arguments": {
"question": "What is RAG?"
}
}
}
Response:
{
"jsonrpc": "2.0",
"id": "req-123",
"result": {
"content": [
{
"type": "text",
"text": "RAG (Retrieval-Augmented Generation) is..."
}
]
}
}
Session Management¶
MCP maintains sessions for: - User context preservation - State management - Resource tracking - Connection lifecycle
Deployment Modes¶
MCP server adapts to your deployment mode:
Full Mode (All Features)¶
Tools Available: 30 tools (all features)
Standard Mode (No RAG)¶
Tools Available: 20 tools (no Knowledge RAG, no auto-extraction)
Minimal Mode (Graph + Memory Only)¶
Tools Available: 17 tools (Code Graph + Memory + Tasks + System)
Configuration¶
Server Configuration¶
Configure MCP server in .env:
# MCP Server Settings
MCP_SERVER_NAME="Code Graph Knowledge System"
MCP_SERVER_VERSION="2.0"
MCP_LOG_LEVEL=INFO
# Feature Flags
ENABLE_KNOWLEDGE_RAG=true
ENABLE_AUTO_EXTRACTION=true
ENABLE_CODE_GRAPH=true
ENABLE_MEMORY_STORE=true
Starting the Server¶
# Direct execution
python -m codebase_rag --mcp
# Using uv
uv run mcp_server
# With custom config
MCP_LOG_LEVEL=DEBUG python -m codebase_rag --mcp
Client Configuration¶
Configure in Claude Desktop or VS Code settings:
Claude Desktop (claude_desktop_config.json):
{
"mcpServers": {
"knowledge-graph": {
"command": "python",
"args": ["/path/to/start_mcp.py"],
"env": {
"PYTHONPATH": "/path/to/codebase-rag"
}
}
}
}
VS Code (settings.json):
{
"mcp.servers": {
"knowledge-graph": {
"command": "python",
"args": ["/path/to/start_mcp.py"]
}
}
}
Use Cases¶
1. AI-Powered Code Assistant¶
Tools Used: - code_graph_ingest_repo: Index codebase - code_graph_fulltext_search: Find code - code_graph_impact_analysis: Analyze changes - memory_store: Remember decisions
Workflow: 1. Ingest repository 2. Ask questions about code 3. Analyze impact of changes 4. Save architectural decisions
2. Documentation Assistant¶
Tools Used: - add_directory: Index documentation - query_knowledge: Answer questions - search_similar_nodes: Find related docs - suggest_memory_from_query: Extract insights
Workflow: 1. Index documentation 2. Query for information 3. Get AI-generated answers 4. Save important findings
3. Development Memory¶
Tools Used: - add_memory: Save knowledge - search_memories: Find past decisions - extract_from_git_commit: Mine commits - batch_extract_from_repository: Auto-extract
Workflow: 1. Extract from git history 2. Mine code comments 3. Store decisions manually 4. Query when needed
4. Code Review Assistant¶
Tools Used: - code_graph_impact_analysis: Analyze changes - query_knowledge: Check documentation - search_memories: Find conventions - extract_from_conversation: Save findings
Workflow: 1. Analyze code changes 2. Check against documentation 3. Verify conventions 4. Save review insights
Benefits of MCP Integration¶
For Users¶
- Natural Language Interface: Ask questions in plain English
- Context Awareness: AI remembers project knowledge
- Automated Tasks: Background processing of large operations
- Unified Experience: Same tools across different AI assistants
For Developers¶
- Standardized Protocol: No custom API clients needed
- Tool Discovery: AI automatically discovers available tools
- Type Safety: JSON schemas for all tool inputs
- Error Handling: Structured error responses
For Organizations¶
- Vendor Independence: Works with any MCP-compatible client
- Security: Local execution, no data sent to external services
- Customization: Easy to add new tools
- Integration: Connects to existing infrastructure
Security Considerations¶
Data Privacy¶
- Local Execution: MCP server runs on your infrastructure
- No External Calls: Data stays in your network (with local LLM)
- Access Control: Implement authentication at proxy level
Tool Permissions¶
Tools have different permission levels:
Read-only tools: - query_knowledge - search_memories - code_graph_fulltext_search
Write tools: - add_document - add_memory - code_graph_ingest_repo
Destructive tools: - delete_memory - clear_knowledge_base
Best Practice: Implement tool-level access control in production
Network Security¶
# Run MCP server in isolated environment
docker run --network isolated-net mcp-server
# Use authentication proxy
nginx → (auth) → MCP server
# Restrict tool access by user
ALLOWED_TOOLS=query_knowledge,search_memories
Performance Considerations¶
Tool Execution Time¶
| Tool Category | Typical Time | Notes |
|---|---|---|
| Query | 1-5s | Depends on LLM |
| Search | 100-500ms | Vector search |
| Memory | 50-200ms | Graph queries |
| Code Graph | 200ms-2s | Varies by size |
| Ingestion | 10s-5min | Background task |
Concurrent Requests¶
The server handles concurrent requests:
Caching Strategy¶
Client-side caching: - Cache frequent queries - Store tool schemas - Cache project summaries
Server-side caching: - Embedding cache - Query result cache - Graph query cache
Monitoring and Debugging¶
Server Logs¶
# View MCP server logs
tail -f mcp_server.log
# Enable debug logging
MCP_LOG_LEVEL=DEBUG python -m codebase_rag --mcp
Tool Call Tracing¶
Monitor tool calls:
# Each tool call is logged
[INFO] Query: "How does auth work?" (mode: hybrid)
[INFO] Add memory: "Use JWT authentication" (project: myapp)
[INFO] Code ingest: /path/to/repo (mode: incremental)
Health Monitoring¶
# Check MCP server health
python -c "from mcp_server import server; print(server.health_check())"
# Check backend services
curl http://localhost:8000/api/v1/health
Limitations¶
Current Limitations¶
- Single User: No built-in multi-user support
- No Authentication: Implement at proxy level
- Tool Discovery: Static tool list (no runtime addition)
- Session Persistence: In-memory only (no database)
Planned Features¶
- Multi-user support: User-specific contexts
- Tool marketplace: Dynamically load tools
- Enhanced streaming: Progress updates for long operations
- Webhook support: External event notifications
Comparison with Alternatives¶
MCP vs REST API¶
| Feature | MCP | REST API |
|---|---|---|
| Tool Discovery | Automatic | Manual |
| Type Safety | Built-in | Manual |
| Streaming | Native | SSE/WebSocket |
| AI Integration | Optimized | Generic |
| Learning Curve | Low | Medium |
MCP vs Function Calling¶
| Feature | MCP | Function Calling |
|---|---|---|
| Protocol | Standardized | Provider-specific |
| Transport | Multiple | HTTP only |
| Session Mgmt | Built-in | Manual |
| Tool Composability | High | Medium |
Next Steps¶
- Claude Desktop Setup: Configure Claude Desktop
- VS Code Setup: Configure VS Code extension
- Deployment Guide: Deploy MCP server
- Contributing Guide: Extend with custom tools
Additional Resources¶
- MCP Documentation: https://modelcontextprotocol.io/
- MCP SDK: https://github.com/modelcontextprotocol/python-sdk
- Claude Desktop: https://claude.ai/download
- MCP Specification: https://spec.modelcontextprotocol.io/