MCP Server
March 9, 2026 ยท View on GitHub
Model Context Protocol implementation for AI agent integration
Overview
This directory contains Code Scalpel's MCP server implementation. It provides:
- Tool Registration - Expose Code Scalpel capabilities as MCP tools
- Protocol Implementation - Standardized communication with AI agents
- Tool Discovery - Agent discovery and capability broadcasting
- Request Handling - Process and respond to tool calls
- Result Marshaling - Convert internal results to MCP format
Core Module (1)
| Module | Purpose | Key Classes | Status |
|---|---|---|---|
| server.py | MCP protocol server (~800 lines) | MCPServer, ToolRegistry | โ Stable |
Available Tools (19 Stable + 4 Experimental)
Code Extraction & Analysis (5)
- Graph-oriented tools remain Python-first overall, with initial local
JavaScript/TypeScript parity in
get_call_graph,get_graph_neighborhood, andget_cross_file_dependencies. JS/TS method-node neighborhoods currently rely on advanced resolution. extract_code- Surgical symbol extraction with dependenciesanalyze_code- Parse and extract code structureget_file_context- Quick file overviewget_symbol_references- Find all symbol usagesget_cross_file_dependencies- Analyze Python-first import/dependency chains with an initial local JS/TS graph-backed slice
Project Analysis (4)
get_call_graph- Build and trace Python-first function calls with initial JS/TS parityget_project_map- Generate project structure mapget_graph_neighborhood- Extract Python-first k-hop subgraph with initial JS/TS function parity and JS/TS method neighborhoods via advanced resolutioncrawl_project- Project-wide analysis
Security (5)
security_scan- Taint-based vulnerability detectioncross_file_security_scan- Multi-file vulnerability trackingscan_dependencies- OSV database vulnerability checkunified_sink_detect- Polyglot sink detectiontype_evaporation_scan- Type system boundary vulnerabilities
Refactoring & Verification (3)
simulate_refactor- Verify code changes safelyupdate_symbol- Apply safe symbol replacementsgenerate_unit_tests- Symbolic execution test generation
Advanced Analysis (2)
symbolic_execute- Explore execution pathsvalidate_paths- Check path accessibility
Usage
With Claude/Copilot/Cursor
# Start MCP server
mcp_server = MCPServer()
mcp_server.start()
# Claude connects via MCP protocol
# Claude calls tools: extract_code, security_scan, etc.
# Server returns results
Direct Python Usage
from code_scalpel.mcp.server import MCPServer
server = MCPServer()
tool = server.get_tool("security_scan")
result = tool.execute(file_path="src/app.py")
Tool Registration
from code_scalpel.mcp.server import MCPServer
server = MCPServer()
# Register custom tool
server.register_tool(
name="my_custom_tool",
description="Custom analysis tool",
handler=my_handler_function,
input_schema={...}
)
Tool Categories
๐ Discovery & Analysis
Used to understand code structure before modifications:
get_file_context- Get file overviewanalyze_code- Parse structureget_symbol_references- Find usagesget_call_graph- Trace callsget_project_map- Overall structure
๐ง Extraction & Modification
Safely extract and modify code:
extract_code- Get code with dependenciesget_cross_file_dependencies- Analyze importssimulate_refactor- Test changesupdate_symbol- Apply safelygenerate_unit_tests- Create tests
๐ Security
Scan for vulnerabilities:
security_scan- Find issues in filecross_file_security_scan- Multi-file scanscan_dependencies- Check CVEsunified_sink_detect- Find dangerous sinks
๐ Advanced
Specialized analysis:
symbolic_execute- Path explorationget_graph_neighborhood- Subgraph extractioncrawl_project- Full project analysisvalidate_paths- Path checking
Tool Invocation Pattern
All tools follow this pattern:
# 1. Agent discovers tool
tool = server.get_tool("extract_code")
# 2. Agent calls with parameters
result = tool.execute(
file_path="src/handlers.py",
target_type="function",
target_name="process_request"
)
# 3. Server returns structured result
# {
# "code": "def process_request(...): ...",
# "dependencies": [...],
# "metadata": {...}
# }
Configuration
from code_scalpel.mcp.server import MCPServer
server = MCPServer(
host="127.0.0.1", # Listen address
port=5000, # Listen port
enable_caching=True, # Cache results
cache_ttl=3600, # Cache duration (seconds)
max_workers=4, # Parallel execution
timeout_seconds=300, # Tool timeout
enable_telemetry=True, # Log usage
log_level="INFO" # Log verbosity
)
Integration Points
With Agents
MCP server is used by agents to perform analysis:
Agent.execute_ooda_loop()
โ
Agent calls MCP tools
โโ observe_file() โ get_file_context()
โโ find_usages() โ get_symbol_references()
โโ analyze_security() โ security_scan()
โโ test_change() โ simulate_refactor()
โ
Agent makes decisions
With External Frameworks
Integrations expose MCP tools in external frameworks:
Claude/Copilot
โ (MCP Protocol)
MCPServer
โ
Code Scalpel Tools
โ
Real Code Analysis
Tool Result Format
All tool results follow this structure:
{
"success": bool, # Tool succeeded
"status": str, # Tool status
"result": dict, # Tool-specific result
"metadata": {
"execution_time_ms": int, # How long tool took
"cached": bool, # Was result cached
"warnings": list, # Warnings
"errors": list # Errors if failed
}
}
File Structure
mcp/
โโโ README.md [This file]
โโโ __init__.py [Exports]
โโโ server.py [MCP protocol server]
Data Flow
MCP Tool Request Processing
AI Agent / Claude / Copilot
โ
MCP Client
โโ Tool discovery (list_tools)
โโ Get schema (describe_tool)
โโ Call tool (call_tool)
โ
MCP Server
โโ Validate request
โโ Check permissions (policies)
โโ Route to handler
โโ Invoke Code Scalpel module
โ
Code Scalpel Modules
โโ AST Tools (ast_tools/)
โโ Security (security/)
โโ Code Parser (code_parser/)
โโ Autonomy (autonomy/)
โโ Agents (agents/)
โ
Analysis Results
โ
Result Marshaling
โโ Convert to JSON
โโ Attach context
โโ Format for MCP
โ
MCP Response
โ
AI Agent (receives results)
Tool Discovery & Registration
Server Startup
โ
MCPServer.__init__()
โโ Register security tools
โโ Register analysis tools
โโ Register extraction tools
โโ Register refactoring tools
โโ Register testing tools
โโ Register autonomy tools
โ
Tool Registry Built
โโ 19 stable tools
โโ 4 experimental tools
โโ Tool schemas & docs
โ
AI Agent Requests Tool Discovery
โ
Server Responds with Capabilities
โโ Available tools
โโ Tool schemas (inputs/outputs)
โโ Tool descriptions
โโ Usage examples
Debugging Tools
# Get all available tools
tools = server.list_tools()
# Check tool schema
schema = server.get_tool_schema("security_scan")
# Get tool statistics
stats = server.get_statistics()
print(f"Total calls: {stats['total_calls']}")
print(f"Cache hit rate: {stats['cache_hit_rate']}")
Development Roadmap
Phase 1: Tool Expansion (In Progress ๐)
New Analysis Tools (8 TODOs)
- Variable tracking & dependency analysis
- Memory usage profiler
- Thread safety analyzer
- API surface analyzer
- Documentation coverage analyzer
- Test mutation analyzer
- Configuration validator
- Performance bottleneck detector
Tool Enhancements (10 TODOs)
- Caching layer for repeated calls
- Result streaming support
- Progress reporting
- Cancellation support
- Timeout handling
- Batch processing
- Incremental analysis
- Result filtering
- Evidence attachment
- Confidence scoring
Protocol Improvements (8 TODOs)
- Tool chaining/piping
- Result post-processing
- Error recovery
- Partial result handling
- Webhook notifications
- Event streaming
- Subscription support
- Rate limiting per tool
Phase 2: Advanced Features (Planned)
Intelligent Orchestration (12 TODOs)
- Automatic tool selection
- Chain multiple tools
- Cross-tool result sharing
- Conflict resolution
- Recommendation ranking
- Result deduplication
- Evidence combination
- Confidence aggregation
- Multi-agent coordination
- Feedback loops
- Learning from corrections
- Auto-tuning parameters
Integration Expansion (9 TODOs)
- IDE plugin support (VS Code, IntelliJ)
- Git hooks integration
- CI/CD pipeline integration
- Chat interface (Slack, Discord)
- Web UI dashboard
- REST API gateway
- GraphQL endpoint
- WebSocket support
- Webhook system
Monitoring & Analytics (10 TODOs)
- Tool usage analytics
- Performance metrics
- Cache hit rates
- Error tracking
- Latency monitoring
- Cost tracking (API usage)
- User analytics
- Quality metrics
- Trend analysis
- SLA monitoring
Phase 3: Enterprise Features (Future)
Security & Governance (11 TODOs)
- Multi-tenant isolation
- Fine-grained permissions
- API key management
- Rate limiting
- Request signing
- Audit logging
- Compliance reporting
- Data retention policies
- Encryption at rest
- Encryption in transit
- Security scanning of tools
Scalability (9 TODOs)
- Distributed tool execution
- Load balancing
- Result caching strategies
- Database persistence
- Queue-based processing
- Horizontal scaling
- Worker pool management
- Failure recovery
- Health checking
Last Updated: December 21, 2025
Version: v3.0.0
Status: 19 Tools Stable โ
+ 4 Experimental ๐งช (Total TODOs: 77)