8.2 KiB
Hanzo MCP Developer Guide
Project Overview
Hanzo MCP is a Model Context Protocol server that enables AI models like Claude to interact with file systems, execute commands, analyze projects, and manage code in a secure, controlled manner. This document captures the key architectural patterns, implementation details, and development guidelines for the project.
Architecture
Core Components
- HanzoMCPServer: Main server class that initializes all components and registers tools
- PermissionManager: Security layer controlling file system access through path validation
- DocumentContext: Tracks and manages file content for context preservation
- CommandExecutor: Handles shell command and script execution
- ProjectAnalyzer/ProjectManager: Analyzes projects, detects languages and frameworks
- FileOperations: Core file system interaction functionality
- ThinkingTool: Structured thinking space for planning without making changes
- JupyterNotebookTools: Tools for working with Jupyter notebooks
Directory Structure
hanzo_mcp/
├── __init__.py
├── cli.py # Command-line interface
├── server.py # HanzoMCPServer implementation
└── tools/ # Tool implementations
├── __init__.py # Tool registration
├── common/ # Shared functionality
│ ├── context.py # Document context
│ ├── permissions.py # Permission system
│ ├── thinking.py # Think tool
│ └── validation.py # Parameter validation
├── filesystem/ # File operations
│ └── file_operations.py # File and directory operations
├── jupyter/ # Notebook operations
│ └── notebook_operations.py # Jupyter notebook tools
├── project/ # Project analysis
│ └── analysis.py # Project structure analysis
└── shell/ # Command execution
└── command_executor.py # Enhanced command execution
Tool Registration Pattern
All tools follow a consistent registration pattern:
- Tool classes define a
register_tools(mcp_server)method - Individual tools are implemented as async functions with standardized error handling
- Tools validate inputs, check permissions, perform operations, and return formatted results
- Progress reporting is implemented for long-running operations
Security Model
The permission system is based on:
- Explicitly allowed paths (allowlisting)
- Excluded paths and patterns for sensitive directories/files
- Path normalization and validation before operations
- Per-operation permission checks
Security exclusions include:
- Sensitive directories (
.ssh,.gnupg, etc.) - Credential files (
.env,*.key, etc.) - Database files and logs
Implemented Tools
Filesystem Tools
read_files: Read contents of one or multiple fileswrite_file: Create or overwrite filesedit_file: Make line-based edits with diff generationdirectory_tree: Generate structured directory viewget_file_info: Retrieve file metadatasearch_content: Search for patterns (like grep)content_replace: Find and replace across files
Shell Tools
run_command: Execute shell commandsrun_script: Execute scripts with specified interpretersscript_tool: Run code in different languages
Project Analysis
project_analyze_tool: Analyze project structure and dependencies- Detects programming languages
- Identifies frameworks and libraries
- Analyzes file types and code statistics
- Examines dependencies
Jupyter Notebook Tools
read_notebook: Extract cells and outputsedit_notebook: Modify notebook cells
Thinking Tool
think: Structured space for reasoning and planning
Vector Store Tools
vector_index: Index files or directories for semantic searchvector_search: Search indexed content with semantic and full-text filteringvector_delete: Remove documents from the vector storevector_list: List indexed documentsgit_ingest: Ingest and index entire git repositories
Vector Search Implementation
The vector search functionality is implemented using ChromaDB and provides the following capabilities:
Vector Store Architecture
- Persistent Storage: Vector embeddings are stored persistently in a local database at
~/.hanzo/vector_db/{project_hash}for each indexed project - Multiple Modalities: Support for indexing and searching:
- Text files and source code (with syntax highlighting)
- Document files (PDF, DOCX, etc.)
- Image files (when available)
- Full-Text Search: Combined vector similarity search with full-text filtering
- Metadata Filtering: Filter search results by file types, paths, and custom metadata
Search Patterns
Full-text search is implemented using Chroma's document filtering capabilities:
# Example with full-text filtering
collection.query(
query_texts=["find important functions"],
where_document={"$contains": "def process_data"}
)
# Example with metadata filtering
collection.query(
query_texts=["authorization code"],
where={"file_extension": ".py"},
where_document={"$contains": "auth"}
)
Git Repository Indexing
The git_ingest tool enables seamless indexing of entire git repositories:
- Clones the repository to a temporary directory
- Indexes all files based on configurable filters
- Extracts metadata like branch, commit hash, and dates
- Cleans up temporary files after indexing
Best Practices and Patterns
Error Handling Pattern
The error handling pattern includes:
- Parameter validation at the beginning of each tool
- Consistent error message formatting with descriptive details
- Proper exception handling with specific error messaging
- Progress tracking and status updates for user feedback
Permission Checking Pattern
- Path normalization using
normalize_path - Path validation using
permission_manager.is_path_allowed() - Permission checks before any file system operations
- Error handling for permission violations
Command Execution Pattern
- Command validation and sanitization
- Working directory checks
- Execution with proper environment setup
- Output and error capture with timeout handling
System Requirements
- Python 3.13+
- Dependencies:
- mcp>=1.3.0
- httpx>=0.27.0
- uvicorn>=0.23.1
- pytest
Development Guidelines
Adding New Tools
When implementing new tools:
- Create a class in the appropriate module under
tools/ - Implement
register_tools(mcp_server)with tool functions - Use
create_tool_context(ctx)for logging and progress reporting - Validate all input parameters
- Check permissions for any file system operations
- Handle exceptions with specific error messages
- Return formatted results with appropriate status information
Permission System
When working with the permission system:
- Always use
permission_manager.is_path_allowed()before file operations - Add path validation for any new tool that accesses the file system
- Consider security implications for new functionality
- Don't bypass permission checks even for seemingly safe operations
Tool Implementation Best Practices
- Start with parameter validation
- Log operation start with
await tool_ctx.info() - Check permissions before file system access
- Use try/except blocks for error handling
- Report progress for long-running operations
- Return clear success/failure messages
- Include relevant metadata in responses
Using the Think Tool
The Think Tool is designed for structured reasoning and planning:
- Use it to analyze information without making changes
- Plan complex multi-step operations
- Evaluate different approaches
- Document your thought process
Configuration
The server can be configured through:
- Command-line arguments to
hanzo-mcp - Claude Desktop configuration for MCP servers
- Programmatic API through
HanzoMCPServerinitialization
Key configuration options:
--allow-path: Paths the server can access--name: Name of the MCP server--transport: Transport protocol (stdio, sse)--install: Install configuration in Claude Desktop
Change History
- March 25, 2025: Updated with additional component details and best practices