GRAPH_VISUALIZATION.md•9.65 kB
# Graph Visualization Guide
This guide explains how to use the graph visualization features in SCS-MCP to understand and analyze your codebase structure.
## Overview
The `generate_dependency_graph` tool creates visual representations of code dependencies without requiring external graphing libraries. It generates text-based formats that can be rendered by various tools or directly in markdown.
## Quick Start
### Generate a Simple Dependency Graph
```json
{
"tool": "generate_dependency_graph",
"arguments": {
"output_format": "mermaid",
"graph_type": "imports"
}
}
```
This generates a Mermaid diagram showing import dependencies for all Python files in your project.
## Output Formats
### 1. Mermaid Format
**Best for**: GitHub/GitLab documentation, README files, web documentation
Mermaid diagrams render automatically in:
- GitHub markdown files
- GitLab markdown files
- Many documentation tools (MkDocs, Docusaurus)
- VS Code with Mermaid preview extensions
**Example Output**:
```mermaid
graph TD
%% Import dependencies
node_server["server.py"]
node_clean_search["clean_search.py"]
node_db_wrapper["db_wrapper.py"]
node_server --> node_clean_search
node_clean_search --> node_db_wrapper
```
**Advantages**:
- No external tools needed
- Renders directly in markdown
- Interactive in supporting viewers
- Easy to edit manually
### 2. DOT Format (Graphviz)
**Best for**: Professional documentation, large graphs, print materials
DOT files can be rendered using:
- Graphviz command-line tools (`dot`, `neato`, `fdp`)
- Online tools (webgraphviz.com, dreampuf.github.io/GraphvizOnline)
- IDE plugins (VS Code, IntelliJ)
**Example Output**:
```dot
digraph "Import Dependency Graph" {
rankdir=LR;
node [shape=box, style=rounded];
// Import dependencies
"server.py" -> "clean_search.py";
"clean_search.py" -> "db_wrapper.py";
"server.py" -> "dependency_analyzer.py";
}
```
**Rendering DOT files**:
```bash
# Generate PNG image
dot -Tpng graph.dot -o graph.png
# Generate SVG (scalable)
dot -Tsvg graph.dot -o graph.svg
# Generate PDF
dot -Tpdf graph.dot -o graph.pdf
```
**Advantages**:
- Industry standard format
- Highly customizable
- Excellent layout algorithms
- Supports large graphs
### 3. JSON Format
**Best for**: Custom visualization tools, programmatic analysis, web applications
**Example Output**:
```json
{
"type": "imports",
"nodes": [
{"id": 0, "label": "server.py", "type": "file"},
{"id": 1, "label": "clean_search.py", "type": "file"},
{"id": 2, "label": "db_wrapper.py", "type": "file"}
],
"edges": [
{"source": 0, "target": 1, "type": "imports"},
{"source": 1, "target": 2, "type": "imports"}
],
"metadata": {
"total_nodes": 3,
"total_edges": 2,
"graph_type": "imports",
"max_out_degree": 1,
"max_in_degree": 1
}
}
```
**Using JSON output**:
- D3.js for interactive web visualizations
- Cytoscape.js for complex network analysis
- Custom Python scripts with NetworkX
- Data analysis in Jupyter notebooks
**Advantages**:
- Machine-readable
- Includes metadata
- Easy to process programmatically
- Flexible for custom tools
## Graph Types
### 1. Import Graph (`imports`)
Shows file and module dependencies.
**Use cases**:
- Understanding project structure
- Identifying tightly coupled modules
- Finding unused files
- Refactoring planning
**Example**:
```json
{
"graph_type": "imports",
"file_pattern": "src/**/*.py"
}
```
### 2. Call Graph (`calls`)
Shows function call relationships.
**Use cases**:
- Understanding execution flow
- Identifying hot paths
- Finding dead code
- Performance optimization
**Example**:
```json
{
"graph_type": "calls",
"file_pattern": "src/core/*.py"
}
```
### 3. Inheritance Tree (`inheritance`)
Shows class hierarchy and inheritance relationships.
**Use cases**:
- Understanding OOP structure
- Identifying deep inheritance chains
- Planning refactoring
- Documentation generation
**Example**:
```json
{
"graph_type": "inheritance",
"file_pattern": "**/*.py"
}
```
## Circular Dependency Detection
Enable circular dependency detection to identify problematic dependencies:
```json
{
"tool": "generate_dependency_graph",
"arguments": {
"output_format": "mermaid",
"graph_type": "imports",
"detect_cycles": true
}
}
```
**Output includes**:
- Visual graph with all dependencies
- List of circular dependency paths
- Severity assessment
**Example circular dependency report**:
```
⚠️ Circular Dependencies Detected:
• module_a → module_b → module_c → module_a
• service_x → service_y → service_x
```
## File Patterns
Control which files are analyzed using glob patterns:
### Common Patterns
| Pattern | Description |
|---------|-------------|
| `*.py` | All Python files in current directory |
| `**/*.py` | All Python files recursively |
| `src/**/*.py` | All Python files under src/ |
| `**/test_*.py` | All test files |
| `src/**/[!_]*.py` | Non-private Python files in src/ |
### Examples
**Analyze specific module**:
```json
{
"file_pattern": "src/auth/**/*.py"
}
```
**Exclude tests**:
```json
{
"file_pattern": "src/**/[!test_]*.py"
}
```
**Multiple extensions** (currently single pattern only):
```json
{
"file_pattern": "**/*.py"
}
```
## Practical Examples
### 1. Document Your Architecture
Generate a high-level architecture diagram for your README:
```json
{
"tool": "generate_dependency_graph",
"arguments": {
"output_format": "mermaid",
"graph_type": "imports",
"file_pattern": "src/core/*.py"
}
}
```
Copy the output directly into your README.md.
### 2. Find Circular Dependencies
Check for circular dependencies before deployment:
```json
{
"tool": "generate_dependency_graph",
"arguments": {
"output_format": "json",
"graph_type": "imports",
"detect_cycles": true,
"file_pattern": "**/*.py"
}
}
```
Parse the JSON to fail CI/CD if cycles are detected.
### 3. Analyze Test Coverage
Understand which modules are tested:
```json
{
"tool": "generate_dependency_graph",
"arguments": {
"output_format": "dot",
"graph_type": "calls",
"file_pattern": "tests/**/*.py"
}
}
```
### 4. Refactoring Planning
Identify tightly coupled components:
```json
{
"tool": "generate_dependency_graph",
"arguments": {
"output_format": "mermaid",
"graph_type": "imports",
"file_pattern": "src/**/*.py",
"detect_cycles": true
}
}
```
## Tips and Best Practices
### 1. Start Small
Begin with specific modules rather than the entire codebase:
- Easier to understand
- Faster generation
- Clearer visualization
### 2. Use Appropriate Formats
- **Mermaid**: Documentation and quick analysis
- **DOT**: Detailed analysis and presentations
- **JSON**: Automated processing and custom tools
### 3. Regular Analysis
- Run circular dependency detection in CI/CD
- Generate graphs for documentation updates
- Track complexity growth over time
### 4. Combine with Other Tools
Use graphs alongside:
- `analyze_symbol` for detailed component analysis
- `find_dependencies` for specific dependency queries
- `instant_review` for quality assessment
### 5. Layer Your Analysis
1. Start with high-level module dependencies
2. Drill down into specific components
3. Analyze call graphs for performance
4. Check inheritance for OOP structure
## Limitations
### Current Limitations
- Single file pattern per request (no multiple patterns yet)
- Python-focused (other languages have basic support)
- Text-based output only (no binary images)
- No interactive features in base output
### Workarounds
- Run multiple queries for different patterns
- Use external tools to render graphs
- Combine with other analysis tools for full picture
## Integration Examples
### GitHub Actions
Add to `.github/workflows/deps.yml`:
```yaml
- name: Check Circular Dependencies
run: |
# Generate dependency graph with cycle detection
result=$(claude-cli run generate_dependency_graph \
--output_format json \
--detect_cycles true)
# Fail if cycles detected
if echo "$result" | grep -q "Circular Dependencies Detected"; then
echo "❌ Circular dependencies found!"
exit 1
fi
```
### Pre-commit Hook
Add to `.pre-commit-config.yaml`:
```yaml
- repo: local
hooks:
- id: check-dependencies
name: Check circular dependencies
entry: scripts/check_dependencies.sh
language: script
files: \.py$
```
### Documentation Generation
Add to your documentation build:
```python
# docs/generate_graphs.py
import subprocess
import json
def generate_architecture_diagram():
result = subprocess.run([
'claude-cli', 'generate_dependency_graph',
'--output_format', 'mermaid',
'--graph_type', 'imports'
], capture_output=True, text=True)
with open('docs/architecture.md', 'w') as f:
f.write("# Architecture\n\n")
f.write(result.stdout)
```
## Troubleshooting
### No files found
- Check your file pattern syntax
- Ensure you're in the correct directory
- Verify files exist matching the pattern
### Graph too complex
- Use more specific file patterns
- Filter by module or directory
- Consider JSON output for processing
### Cycles not detected
- Ensure Python files are syntactically correct
- Check that imports are at module level
- Try with simpler test case first
## Future Enhancements
Planned improvements:
- Multiple file pattern support
- Interactive HTML output
- Better multi-language support
- Customizable node clustering
- Diff-based dependency changes
- Real-time graph updates