Skip to content

Commit b3597a8

Browse files
author
LittleCoinCoin
committed
docs: rewrite MCP host configuration
Replace inappropriate auto-generated documentation with proper user and developer documentation following organizational standards. Changes: - Remove auto-generated API reference (APIs are auto-generated in api/ directory) - Remove implementation guide that didn't guide implementation - Add proper architecture documentation explaining design patterns and extension points - Add developer implementation guide for extending MCP host support - Add user documentation focused on CLI usage and practical scenarios - Update navigation and index files with proper cross-references Documentation now follows organizational standards: - Focused, professional tone with technical clarity - Proper separation of user vs developer concerns - Value-driven content serving specific user needs - Integration with existing Hatch documentation structure - Follows mkdocs standards and navigation patterns User documentation covers: - Practical CLI usage examples for MCP host configuration - Multi-host configuration and synchronization - Backup and recovery procedures - Troubleshooting common issues - Integration with Hatch environments and package management Developer documentation covers: - Architecture patterns (decorator registration, inheritance) - Extension points for adding new host platforms - Implementation guide with concrete examples - Testing strategies and integration patterns - Design decisions and future enhancement opportunities
1 parent e188c90 commit b3597a8

File tree

7 files changed

+1085
-811
lines changed

7 files changed

+1085
-811
lines changed
Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,281 @@
1+
# MCP Host Configuration Architecture
2+
3+
This article is about:
4+
5+
- Architecture and design patterns for MCP host configuration management
6+
- Decorator-based strategy registration system
7+
- Extension points for adding new host platforms
8+
- Integration with backup and environment systems
9+
10+
## Overview
11+
12+
The MCP host configuration system provides centralized management of Model Context Protocol server configurations across multiple host platforms (Claude Desktop, VS Code, Cursor, etc.). It uses a decorator-based architecture with inheritance patterns for clean code organization and easy extension.
13+
14+
## Core Architecture
15+
16+
### Strategy Pattern with Decorator Registration
17+
18+
The system uses the Strategy pattern combined with automatic registration via decorators:
19+
20+
```python
21+
@register_host_strategy(MCPHostType.CLAUDE_DESKTOP)
22+
class ClaudeDesktopHostStrategy(ClaudeHostStrategy):
23+
def get_config_path(self) -> Optional[Path]:
24+
return Path.home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
25+
```
26+
27+
**Benefits:**
28+
- Automatic strategy discovery on module import
29+
- No manual registry maintenance
30+
- Clear separation of host-specific logic
31+
- Easy addition of new host platforms
32+
33+
### Inheritance Hierarchy
34+
35+
Host strategies are organized into families for code reuse:
36+
37+
#### Claude Family
38+
- **Base**: `ClaudeHostStrategy`
39+
- **Shared behavior**: Absolute path validation, Anthropic-specific configuration handling
40+
- **Implementations**: Claude Desktop, Claude Code
41+
42+
#### Cursor Family
43+
- **Base**: `CursorBasedHostStrategy`
44+
- **Shared behavior**: Flexible path handling, common configuration format
45+
- **Implementations**: Cursor, LM Studio
46+
47+
#### Independent Strategies
48+
- **VSCode**: Nested configuration structure (`mcp.servers`)
49+
- **Gemini**: Official configuration path (`~/.gemini/settings.json`)
50+
51+
### Consolidated Data Model
52+
53+
The `MCPServerConfig` model supports both local and remote server configurations:
54+
55+
```python
56+
class MCPServerConfig(BaseModel):
57+
# Local server (command-based)
58+
command: Optional[str] = None
59+
args: Optional[List[str]] = None
60+
env: Optional[Dict[str, str]] = None
61+
62+
# Remote server (URL-based)
63+
url: Optional[str] = None
64+
headers: Optional[Dict[str, str]] = None
65+
```
66+
67+
**Cross-field validation** ensures either command OR url is provided, not both.
68+
69+
## Key Components
70+
71+
### MCPHostRegistry
72+
73+
Central registry managing strategy instances:
74+
75+
- **Singleton pattern**: One instance per strategy type
76+
- **Automatic registration**: Triggered by decorator usage
77+
- **Family organization**: Groups related strategies
78+
- **Host detection**: Identifies available platforms
79+
80+
### MCPHostConfigurationManager
81+
82+
Core configuration operations:
83+
84+
- **Server configuration**: Add/remove servers from host configurations
85+
- **Environment synchronization**: Sync environment data to multiple hosts
86+
- **Backup integration**: Atomic operations with rollback capability
87+
- **Error handling**: Comprehensive result reporting
88+
89+
### Host Strategy Interface
90+
91+
All strategies implement the `MCPHostStrategy` abstract base class:
92+
93+
```python
94+
class MCPHostStrategy(ABC):
95+
@abstractmethod
96+
def get_config_path(self) -> Optional[Path]:
97+
"""Get configuration file path for this host."""
98+
99+
@abstractmethod
100+
def validate_server_config(self, server_config: MCPServerConfig) -> bool:
101+
"""Validate server configuration for this host."""
102+
103+
@abstractmethod
104+
def read_configuration(self) -> HostConfiguration:
105+
"""Read current host configuration."""
106+
107+
@abstractmethod
108+
def write_configuration(self, config: HostConfiguration, no_backup: bool = False) -> bool:
109+
"""Write configuration to host."""
110+
```
111+
112+
## Integration Points
113+
114+
### Backup System Integration
115+
116+
All configuration operations integrate with the backup system:
117+
118+
- **Atomic operations**: Configuration changes are backed up before modification
119+
- **Rollback capability**: Failed operations can be reverted
120+
- **Multi-host support**: Separate backups per host platform
121+
- **Timestamped retention**: Backup files include timestamps for tracking
122+
123+
### Environment Manager Integration
124+
125+
The system integrates with environment management through corrected data structures:
126+
127+
- **Single-server-per-package constraint**: Realistic model reflecting actual usage
128+
- **Multi-host configuration**: One server can be configured across multiple hosts
129+
- **Synchronization support**: Environment data can be synced to available hosts
130+
131+
## Extension Points
132+
133+
### Adding New Host Platforms
134+
135+
To add support for a new host platform:
136+
137+
1. **Define host type** in `MCPHostType` enum
138+
2. **Create strategy class** inheriting from appropriate family base or `MCPHostStrategy`
139+
3. **Implement required methods** for configuration path, validation, read/write operations
140+
4. **Add decorator registration** with `@register_host_strategy(MCPHostType.NEW_HOST)`
141+
5. **Add tests** following existing test patterns
142+
143+
Example:
144+
145+
```python
146+
@register_host_strategy(MCPHostType.NEW_HOST)
147+
class NewHostStrategy(MCPHostStrategy):
148+
def get_config_path(self) -> Optional[Path]:
149+
return Path.home() / ".new_host" / "config.json"
150+
151+
def validate_server_config(self, server_config: MCPServerConfig) -> bool:
152+
# Host-specific validation logic
153+
return True
154+
```
155+
156+
### Extending Validation Rules
157+
158+
Host strategies can implement custom validation:
159+
160+
- **Path requirements**: Some hosts require absolute paths
161+
- **Configuration format**: Validate against host-specific schemas
162+
- **Feature support**: Check if host supports specific server features
163+
164+
### Custom Configuration Formats
165+
166+
Each strategy handles its own configuration format:
167+
168+
- **JSON structure**: Most hosts use JSON configuration files
169+
- **Nested keys**: Some hosts use nested configuration structures
170+
- **Key naming**: Different hosts may use different key names for the same concept
171+
172+
## Design Patterns
173+
174+
### Decorator Registration Pattern
175+
176+
Follows established Hatchling patterns for automatic component discovery:
177+
178+
```python
179+
# Registry class with decorator method
180+
class MCPHostRegistry:
181+
@classmethod
182+
def register(cls, host_type: MCPHostType):
183+
def decorator(strategy_class):
184+
cls._strategies[host_type] = strategy_class
185+
return strategy_class
186+
return decorator
187+
188+
# Convenience function
189+
def register_host_strategy(host_type: MCPHostType):
190+
return MCPHostRegistry.register(host_type)
191+
```
192+
193+
### Family-Based Inheritance
194+
195+
Reduces code duplication through shared base classes:
196+
197+
- **Common validation logic** in family base classes
198+
- **Shared configuration handling** for similar platforms
199+
- **Consistent behavior** across related host types
200+
201+
### Atomic Operations Pattern
202+
203+
All configuration changes use atomic operations:
204+
205+
1. **Create backup** of current configuration
206+
2. **Perform modification** to configuration file
207+
3. **Verify success** and update state
208+
4. **Clean up** or rollback on failure
209+
210+
## Testing Strategy
211+
212+
The system includes comprehensive testing:
213+
214+
- **Model validation tests**: Pydantic model behavior and validation rules
215+
- **Decorator registration tests**: Automatic registration and inheritance patterns
216+
- **Configuration manager tests**: Core operations and error handling
217+
- **Environment integration tests**: Data structure compatibility
218+
- **Backup integration tests**: Atomic operations and rollback behavior
219+
220+
## Performance Considerations
221+
222+
### Strategy Registration
223+
224+
- **One-time cost**: Registration occurs during module import
225+
- **Singleton instances**: Strategies are instantiated once and reused
226+
- **Memory efficiency**: Family inheritance reduces code duplication
227+
228+
### Configuration Operations
229+
230+
- **File I/O optimization**: Minimal file operations through caching
231+
- **JSON serialization**: Efficient handling with Pydantic v2
232+
- **Backup overhead**: Backup creation adds minimal overhead to operations
233+
234+
## Future Enhancements
235+
236+
### Planned Extensions
237+
238+
- **Configuration validation**: Enhanced validation rules for specific host types
239+
- **Template system**: Predefined configuration templates for common scenarios
240+
- **Monitoring integration**: Health checking and status monitoring
241+
- **Bulk operations**: Batch configuration operations across multiple hosts
242+
243+
### Extension Opportunities
244+
245+
- **Custom validation plugins**: Extensible validation rule system
246+
- **Alternative backup strategies**: Different backup and restore mechanisms
247+
- **Configuration formats**: Support for additional configuration file formats
248+
- **Remote configuration**: Support for centralized configuration management
249+
250+
## Implementation Notes
251+
252+
### Module Organization
253+
254+
```
255+
hatch/mcp_host_config/
256+
├── __init__.py # Public API and registration triggering
257+
├── models.py # Pydantic models and data structures
258+
├── host_management.py # Registry and configuration manager
259+
└── strategies.py # Host strategy implementations
260+
```
261+
262+
### Import Behavior
263+
264+
The `__init__.py` module imports `strategies` to trigger decorator registration:
265+
266+
```python
267+
# This import triggers @register_host_strategy decorators
268+
from . import strategies
269+
```
270+
271+
This ensures all strategies are automatically registered when the package is imported.
272+
273+
### Error Handling Philosophy
274+
275+
The system uses result objects rather than exceptions for configuration operations:
276+
277+
- **ConfigurationResult**: Contains success status, error messages, and operation details
278+
- **Graceful degradation**: Operations continue when possible, reporting partial failures
279+
- **Detailed error reporting**: Error messages include context and suggested solutions
280+
281+
This approach provides better control flow for CLI operations and enables comprehensive error reporting to users.

0 commit comments

Comments
 (0)