Skip to content

Commit e4e42ce

Browse files
author
LittleCoinCoin
committed
docs(dev): enhance MCP host configuration extension guidance
Improve developer documentation for adding new MCP host platforms based on Kiro MCP integration experience. Addresses critical gap where backup system integration was missed during initial planning. Key improvements: - Add integration point checklist to prevent planning oversights - Emphasize backup system integration as mandatory (frequently missed) - Clarify backup integration patterns across different host types - Add comprehensive task breakdown template with all integration points - Include CLI integration planning guidance for host-specific arguments - Add test categories table showing required test types - Enhance host-specific model documentation with implementation steps - Add implementation summary checklist for verification Architecture document updates: - Add Kiro to supported hosts list with accurate details - Clarify independent strategies section with configuration paths - Add backup integration code example to Integration Points section - Add Model Registry and CLI Integration requirements - Replace simple extension example with integration point table Implementation guide updates: - Add 'Before You Start' integration checklist with lesson learned callout - Add dedicated 'Integrate Backup System' section (Step 4) - Clarify backup integration patterns (inherited vs explicit) - Enhance host-specific model section with implementation steps - Add CLI integration planning section - Add test categories table with locations - Add backup integration test examples - Add implementation summary checklist These enhancements ensure future MCP host implementations achieve complete integration point coverage in initial planning, preventing the backup system oversight that occurred with Kiro.
1 parent 068a856 commit e4e42ce

File tree

2 files changed

+234
-53
lines changed

2 files changed

+234
-53
lines changed

docs/articles/devs/architecture/mcp_host_configuration.md

Lines changed: 60 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ This article is about:
99

1010
## Overview
1111

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.
12+
The MCP host configuration system provides centralized management of Model Context Protocol server configurations across multiple host platforms (Claude Desktop, VS Code, Cursor, Kiro, etc.). It uses a decorator-based architecture with inheritance patterns for clean code organization and easy extension.
13+
14+
> **Adding a new host?** See the [Implementation Guide](../implementation_guides/mcp_host_configuration_extension.md) for step-by-step instructions.
1315
1416
## Core Architecture
1517

@@ -45,8 +47,9 @@ Host strategies are organized into families for code reuse:
4547
- **Implementations**: Cursor, LM Studio
4648

4749
#### Independent Strategies
48-
- **VSCode**: Nested configuration structure (`mcp.servers`)
50+
- **VSCode**: User-wide configuration (`~/.config/Code/User/mcp.json`), uses `servers` key
4951
- **Gemini**: Official configuration path (`~/.gemini/settings.json`)
52+
- **Kiro**: User-level configuration (`~/.kiro/settings/mcp.json`), full backup manager integration
5053

5154
### Consolidated Data Model
5255

@@ -111,15 +114,51 @@ class MCPHostStrategy(ABC):
111114

112115
## Integration Points
113116

114-
### Backup System Integration
117+
Every host strategy must integrate with these systems. Missing any integration point will result in incomplete functionality.
118+
119+
### Backup System Integration (Required)
115120

116-
All configuration operations integrate with the backup system:
121+
All configuration write operations **must** integrate with the backup system via `MCPHostConfigBackupManager` and `AtomicFileOperations`:
117122

123+
```python
124+
from .backup import MCPHostConfigBackupManager, AtomicFileOperations
125+
126+
def write_configuration(self, config: HostConfiguration, no_backup: bool = False) -> bool:
127+
# ... prepare data ...
128+
backup_manager = MCPHostConfigBackupManager()
129+
atomic_ops = AtomicFileOperations()
130+
atomic_ops.atomic_write_with_backup(
131+
file_path=config_path,
132+
data=existing_data,
133+
backup_manager=backup_manager,
134+
hostname="your-host", # Must match MCPHostType value
135+
skip_backup=no_backup
136+
)
137+
```
138+
139+
**Key requirements:**
118140
- **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
141+
- **Rollback capability**: Failed operations can be reverted automatically
142+
- **Hostname identification**: Each host uses its `MCPHostType` value for backup tracking
121143
- **Timestamped retention**: Backup files include timestamps for tracking
122144

145+
### Model Registry Integration (Required for host-specific fields)
146+
147+
If your host has unique configuration fields (like Kiro's `disabled`, `autoApprove`, `disabledTools`):
148+
149+
1. Create host-specific model class in `models.py`
150+
2. Register in `HOST_MODEL_REGISTRY`
151+
3. Extend `MCPServerConfigOmni` with new fields
152+
4. Implement `from_omni()` conversion method
153+
154+
### CLI Integration (Required for host-specific arguments)
155+
156+
If your host has unique CLI arguments:
157+
158+
1. Extend `handle_mcp_configure()` function signature in `cli_hatch.py`
159+
2. Add argument parser entries for new flags
160+
3. Update omni model population logic
161+
123162
### Environment Manager Integration
124163

125164
The system integrates with environment management through corrected data structures:
@@ -132,27 +171,31 @@ The system integrates with environment management through corrected data structu
132171

133172
### Adding New Host Platforms
134173

135-
To add support for a new host platform:
174+
To add support for a new host platform, complete these integration points:
136175

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
176+
| Integration Point | Required? | Files to Modify |
177+
|-------------------|-----------|-----------------|
178+
| Host type enum | Always | `models.py` |
179+
| Strategy class | Always | `strategies.py` |
180+
| Backup integration | Always | `strategies.py` (in `write_configuration`) |
181+
| Host-specific model | If unique fields | `models.py`, `HOST_MODEL_REGISTRY` |
182+
| CLI arguments | If unique fields | `cli_hatch.py` |
183+
| Test infrastructure | Always | `tests/` |
142184

143-
Example:
185+
**Minimal implementation** (standard host, no unique fields):
144186

145187
```python
146188
@register_host_strategy(MCPHostType.NEW_HOST)
147-
class NewHostStrategy(MCPHostStrategy):
189+
class NewHostStrategy(ClaudeHostStrategy): # Inherit backup integration
148190
def get_config_path(self) -> Optional[Path]:
149191
return Path.home() / ".new_host" / "config.json"
150192

151-
def validate_server_config(self, server_config: MCPServerConfig) -> bool:
152-
# Host-specific validation logic
153-
return True
193+
def is_host_available(self) -> bool:
194+
return self.get_config_path().parent.exists()
154195
```
155196

197+
**Full implementation** (host with unique fields): See [Implementation Guide](../implementation_guides/mcp_host_configuration_extension.md).
198+
156199
### Extending Validation Rules
157200

158201
Host strategies can implement custom validation:

docs/articles/devs/implementation_guides/mcp_host_configuration_extension.md

Lines changed: 174 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,21 @@
22

33
**Quick Start:** Copy an existing strategy, modify configuration paths and validation, add decorator. Most strategies are 50-100 lines.
44

5+
## Before You Start: Integration Checklist
6+
7+
Use this checklist to plan your implementation. Missing integration points cause incomplete functionality.
8+
9+
| Integration Point | Required? | When Needed |
10+
|-------------------|-----------|-------------|
11+
| ☐ Host type enum | Always | All hosts |
12+
| ☐ Strategy class | Always | All hosts |
13+
| ☐ Backup integration | Always | All hosts - **commonly missed** |
14+
| ☐ Host-specific model | Sometimes | Host has unique config fields |
15+
| ☐ CLI arguments | Sometimes | Host has unique config fields |
16+
| ☐ Test infrastructure | Always | All hosts |
17+
18+
> **Lesson learned:** The backup system integration is frequently overlooked during planning but is mandatory for all hosts. Plan for it upfront.
19+
520
## When You Need This
621

722
You want Hatch to configure MCP servers on a new host platform:
@@ -59,6 +74,7 @@ class YourHostStrategy(MCPHostStrategy):
5974
- `CURSOR` - Cursor IDE
6075
- `LMSTUDIO` - LM Studio
6176
- `GEMINI` - Google Gemini CLI
77+
- `KIRO` - Kiro IDE
6278

6379
### 2. Add Host Type
6480

@@ -194,9 +210,65 @@ class YourHostStrategy(MCPHostStrategy):
194210
return False
195211
```
196212

197-
### 4. Handle Configuration Format
213+
### 4. Integrate Backup System (Required)
214+
215+
All host strategies must integrate with the backup system for data safety. This is **mandatory** - don't skip it.
216+
217+
**Current implementation status:**
218+
- Family base classes (`ClaudeHostStrategy`, `CursorBasedHostStrategy`) use atomic temp-file writes but not the full backup manager
219+
- `KiroHostStrategy` demonstrates full backup manager integration with `MCPHostConfigBackupManager` and `AtomicFileOperations`
220+
221+
**For new implementations**: Add backup integration to `write_configuration()`:
222+
223+
```python
224+
from .backup import MCPHostConfigBackupManager, AtomicFileOperations
225+
226+
def write_configuration(self, config: HostConfiguration, no_backup: bool = False) -> bool:
227+
config_path = self.get_config_path()
228+
if not config_path:
229+
return False
230+
231+
try:
232+
config_path.parent.mkdir(parents=True, exist_ok=True)
233+
234+
# Read existing config to preserve non-MCP settings
235+
existing_data = {}
236+
if config_path.exists():
237+
with open(config_path, 'r', encoding='utf-8') as f:
238+
existing_data = json.load(f)
239+
240+
# Update MCP servers section
241+
servers_data = {
242+
name: server.model_dump(exclude_unset=True)
243+
for name, server in config.servers.items()
244+
}
245+
existing_data[self.get_config_key()] = servers_data
246+
247+
# Use atomic write with backup support
248+
backup_manager = MCPHostConfigBackupManager()
249+
atomic_ops = AtomicFileOperations()
250+
atomic_ops.atomic_write_with_backup(
251+
file_path=config_path,
252+
data=existing_data,
253+
backup_manager=backup_manager,
254+
hostname="your-host", # Must match your MCPHostType value
255+
skip_backup=no_backup
256+
)
257+
return True
258+
259+
except Exception as e:
260+
logger.error(f"Failed to write configuration: {e}")
261+
return False
262+
```
263+
264+
**Key points:**
265+
- `hostname` parameter must match your `MCPHostType` enum value (e.g., `"kiro"` for `MCPHostType.KIRO`)
266+
- `skip_backup` respects the `no_backup` parameter passed to `write_configuration()`
267+
- Atomic operations ensure config file integrity even if the process crashes
268+
269+
### 5. Handle Configuration Format (Optional)
198270

199-
Implement configuration reading/writing for your host's format:
271+
Override configuration reading/writing only if your host has a non-standard format:
200272

201273
```python
202274
def read_configuration(self) -> HostConfiguration:
@@ -393,17 +465,25 @@ def get_config_path(self) -> Optional[Path]:
393465

394466
## Testing Your Strategy
395467

396-
### 1. Add Unit Tests
468+
### Test Categories
397469

398-
Create tests in `tests/test_mcp_your_host_strategy.py`. **Important:** Import strategies to trigger registration:
470+
Your implementation needs tests in these categories:
471+
472+
| Category | Purpose | Location |
473+
|----------|---------|----------|
474+
| Strategy tests | Registration, paths, validation | `tests/regression/test_mcp_yourhost_host_strategy.py` |
475+
| Backup tests | Backup creation, restoration | `tests/regression/test_mcp_yourhost_backup_integration.py` |
476+
| Model tests | Field validation (if host-specific model) | `tests/regression/test_mcp_yourhost_model_validation.py` |
477+
| CLI tests | Argument handling (if host-specific args) | `tests/regression/test_mcp_yourhost_cli_integration.py` |
478+
| Integration tests | End-to-end workflows | `tests/integration/test_mcp_yourhost_integration.py` |
479+
480+
### 1. Strategy Tests (Required)
399481

400482
```python
401483
import unittest
402484
from pathlib import Path
403485
from hatch.mcp_host_config import MCPHostRegistry, MCPHostType, MCPServerConfig, HostConfiguration
404-
405-
# Import strategies to trigger registration
406-
import hatch.mcp_host_config.strategies
486+
import hatch.mcp_host_config.strategies # Triggers registration
407487

408488
class TestYourHostStrategy(unittest.TestCase):
409489
def test_strategy_registration(self):
@@ -414,43 +494,32 @@ class TestYourHostStrategy(unittest.TestCase):
414494
def test_config_path(self):
415495
"""Test configuration path detection."""
416496
strategy = MCPHostRegistry.get_strategy(MCPHostType.YOUR_HOST)
417-
config_path = strategy.get_config_path()
418-
self.assertIsNotNone(config_path)
419-
420-
def test_is_host_available(self):
421-
"""Test host availability detection."""
422-
strategy = MCPHostRegistry.get_strategy(MCPHostType.YOUR_HOST)
423-
# This may return False if host isn't installed
424-
is_available = strategy.is_host_available()
425-
self.assertIsInstance(is_available, bool)
497+
self.assertIsNotNone(strategy.get_config_path())
426498

427499
def test_server_validation(self):
428500
"""Test server configuration validation."""
429501
strategy = MCPHostRegistry.get_strategy(MCPHostType.YOUR_HOST)
430-
431-
# Test valid config with command
432502
valid_config = MCPServerConfig(command="python", args=["server.py"])
433503
self.assertTrue(strategy.validate_server_config(valid_config))
434-
435-
# Test valid config with URL
436-
valid_url_config = MCPServerConfig(url="http://localhost:8000")
437-
self.assertTrue(strategy.validate_server_config(valid_url_config))
438-
439-
# Test invalid config (neither command nor URL)
440-
with self.assertRaises(ValueError):
441-
MCPServerConfig() # Will fail validation
442-
443-
def test_read_configuration(self):
444-
"""Test reading configuration."""
445-
strategy = MCPHostRegistry.get_strategy(MCPHostType.YOUR_HOST)
446-
config = strategy.read_configuration()
447-
self.assertIsInstance(config, HostConfiguration)
448-
self.assertIsInstance(config.servers, dict)
449504
```
450505

451-
### 2. Integration Testing
506+
### 2. Backup Integration Tests (Required)
507+
508+
```python
509+
class TestYourHostBackupIntegration(unittest.TestCase):
510+
def test_write_creates_backup(self):
511+
"""Test that write_configuration creates backup when no_backup=False."""
512+
# Setup temp config file
513+
# Call write_configuration(config, no_backup=False)
514+
# Verify backup file was created
515+
516+
def test_write_skips_backup_when_requested(self):
517+
"""Test that write_configuration skips backup when no_backup=True."""
518+
# Call write_configuration(config, no_backup=True)
519+
# Verify no backup file was created
520+
```
452521

453-
Test with the configuration manager:
522+
### 3. Integration Testing
454523

455524
```python
456525
def test_configuration_manager_integration(self):
@@ -507,8 +576,65 @@ Different hosts have different validation rules. The codebase provides host-spec
507576
- `MCPServerConfigCursor` - Cursor/LM Studio
508577
- `MCPServerConfigVSCode` - VS Code
509578
- `MCPServerConfigGemini` - Google Gemini
579+
- `MCPServerConfigKiro` - Kiro IDE (with `disabled`, `autoApprove`, `disabledTools`)
580+
581+
**When to create a host-specific model:** Only if your host has unique configuration fields not present in other hosts.
582+
583+
**Implementation steps** (if needed):
584+
585+
1. **Add model class** in `models.py`:
586+
```python
587+
class MCPServerConfigYourHost(MCPServerConfigBase):
588+
your_field: Optional[str] = None
589+
590+
@classmethod
591+
def from_omni(cls, omni: "MCPServerConfigOmni") -> "MCPServerConfigYourHost":
592+
return cls(**omni.model_dump(exclude_unset=True))
593+
```
594+
595+
2. **Register in `HOST_MODEL_REGISTRY`**:
596+
```python
597+
HOST_MODEL_REGISTRY = {
598+
# ... existing entries ...
599+
MCPHostType.YOUR_HOST: MCPServerConfigYourHost,
600+
}
601+
```
602+
603+
3. **Extend `MCPServerConfigOmni`** with your fields (for CLI integration)
604+
605+
4. **Add CLI arguments** in `cli_hatch.py` (see next section)
606+
607+
For most cases, the generic `MCPServerConfig` works fine - only add a host-specific model if truly needed.
608+
609+
### CLI Integration for Host-Specific Fields
510610

511-
If your host has unique requirements, you can create a host-specific model and register it in `HOST_MODEL_REGISTRY` (in `models.py`). However, for most cases, the generic `MCPServerConfig` works fine.
611+
If your host has unique configuration fields, extend the CLI to support them:
612+
613+
1. **Update function signature** in `handle_mcp_configure()`:
614+
```python
615+
def handle_mcp_configure(
616+
# ... existing params ...
617+
your_field: Optional[str] = None, # Add your field
618+
):
619+
```
620+
621+
2. **Add argument parser entry**:
622+
```python
623+
configure_parser.add_argument(
624+
'--your-field',
625+
help='Description of your field'
626+
)
627+
```
628+
629+
3. **Update omni model population**:
630+
```python
631+
omni_config_data = {
632+
# ... existing fields ...
633+
'your_field': your_field,
634+
}
635+
```
636+
637+
The conversion reporting system automatically handles new fields - no additional changes needed there.
512638

513639
### Multi-File Configuration
514640

@@ -721,3 +847,15 @@ hatch mcp remove my-server --host your-host
721847
2. The CLI imports `hatch.mcp_host_config.strategies` (which it does)
722848

723849
The CLI automatically discovers your strategy through the `@register_host_strategy` decorator registration system.
850+
851+
## Implementation Summary
852+
853+
After completing your implementation, verify all integration points:
854+
855+
- [ ] Host type added to `MCPHostType` enum
856+
- [ ] Strategy class implemented with `@register_host_strategy` decorator
857+
- [ ] Backup integration working (test with `no_backup=False` and `no_backup=True`)
858+
- [ ] Host-specific model created (if needed) and registered in `HOST_MODEL_REGISTRY`
859+
- [ ] CLI arguments added (if needed) with omni model population
860+
- [ ] All test categories implemented and passing
861+
- [ ] Strategy exported from `__init__.py` (if in separate file)

0 commit comments

Comments
 (0)