# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Development Commands
### Testing
```bash
# Run all tests with coverage
pytest
# Run specific test files
pytest tests/test_models.py
pytest tests/test_storage.py
pytest tests/test_integration.py
# Run tests by markers
pytest -m unit
pytest -m integration
pytest -m e2e
# Generate HTML coverage report
pytest --cov=accounting_mcp --cov-report=html
```
### Code Quality
```bash
# Format code
black accounting_mcp/ tests/
# Check import sorting
isort --check-only accounting_mcp/ tests/
# Type checking
mypy accounting_mcp/
# Lint code
flake8 accounting_mcp/ tests/
```
### Running the MCP Server
```bash
# Start MCP server (stdio mode)
python -m accounting_mcp.server
# Interactive test client
python test_client.py
# Simple demo
python simple_demo.py
```
## Architecture Overview
This is a Model Context Protocol (MCP) server implementation for personal accounting/bookkeeping functionality.
### Core Architecture
**MCP Layer** (`accounting_mcp/server.py`):
- Standard MCP server using stdio transport
- Registers 4 tools and 3 resources
- Handles JSON-RPC 2.0 protocol communication
- Integrates with Claude Desktop and other MCP clients
**Domain Models** (`accounting_mcp/models.py`):
- `Transaction`: Core transaction record with amount, category, description, date
- `Account`: Account aggregation with balance and transaction count
- `Category`: Expense/income categorization with validation
- Uses `Decimal` for precise financial calculations
**Storage Layer** (`accounting_mcp/storage.py`):
- JSON file-based persistence with atomic writes
- `StorageManager`: Unified interface managing all storage operations
- `TransactionStorage`, `AccountStorage`, `CategoryStorage`: Specialized storage handlers
- Thread-safe operations with file locking
- Automatic backup and corruption recovery
**MCP Tools** (`accounting_mcp/tools.py`):
- `add_transaction`: Create new income/expense records
- `get_balance`: Query current account balance
- `list_transactions`: Retrieve transactions with filtering/pagination
- `monthly_summary`: Generate monthly financial summaries
**MCP Resources** (`accounting_mcp/resources.py`):
- `transactions://all`: All transaction data
- `categories://list`: Available expense categories
- `summary://current`: Current account summary
### Key Design Patterns
**TDD Development**: Comprehensive test suite (47 tests) with 85%+ coverage requirement
**Atomic Operations**: All storage operations use atomic file writes with backup/rollback
**Validation Layer**: Strict input validation at model and tool boundaries
**Error Handling**: Graceful error recovery with detailed logging
**Type Safety**: Full mypy type checking with strict configuration
### Data Flow
1. MCP client sends tool call via stdio/JSON-RPC
2. Server validates and routes to appropriate tool handler
3. Tool handler validates inputs and calls storage layer
4. Storage layer performs atomic file operations
5. Response formatted and returned via MCP protocol
### Testing Strategy
Tests are organized by layer:
- `test_models.py`: Domain model validation and business logic
- `test_storage.py`: Persistence layer, concurrency, error recovery
- `test_integration.py`: End-to-end MCP server functionality
Use TDD workflow: write failing test first, minimal implementation, then refactor.
### Configuration Files
- `pytest.ini`: Test configuration with coverage thresholds
- `pyproject.toml`: Code formatting (black, isort) and type checking (mypy) settings
- `requirements*.txt`: Production and development dependencies
- `data/categories.json`: Default expense/income categories
### MCP Integration
The server follows MCP 1.0 specification and can be integrated with:
- Claude Desktop (via `claude_desktop_config.json`)
- Other MCP-compatible clients
- Custom applications using MCP protocol
Data persists in `data/` directory as JSON files, supporting concurrent access and automatic backup/recovery.
## MCP Development Best Practices & Troubleshooting
### 🚨 Critical MCP Protocol Requirements
**1. Handler Return Types (最容易踩的坑)**
```python
# ❌ WRONG - 會導致工具不顯示
@server.list_tools()
async def list_tools() -> ListToolsResult:
return ListToolsResult(tools=tools)
# ✅ CORRECT - 直接回傳清單
@server.list_tools()
async def list_tools() -> List[Tool]:
return tools
```
**2. Server Capabilities Declaration**
```python
# ✅ 必須正確宣告伺服器能力
InitializationOptions(
server_name="your-mcp-server",
server_version="1.0.0",
capabilities=ServerCapabilities(
tools=ToolsCapability(), # 不要使用 listChanged=True
resources=ResourcesCapability(), # 某些版本不相容
),
)
```
**3. Tool Annotations (影響工具顯示)**
```python
# ✅ 正確新增工具註解
for tool_def in tool_definitions:
annotations = ToolAnnotations(
readOnlyHint=tool_def.get("readOnly", False),
destructiveHint=tool_def.get("destructive", False)
)
tools.append(Tool(
name=tool_def["name"],
description=tool_def["description"],
inputSchema=tool_def["inputSchema"],
annotations=annotations # 必須加入
))
```
### 🔧 MCP Configuration & Environment
**專案級 `.mcp.json` 設定**
```json
{
"mcpServers": {
"your-server": {
"command": "/full/path/to/python", // 使用完整路徑
"args": ["-m", "your_package.server"]
}
}
}
```
**環境路徑注意事項**:
- 使用完整的 conda/virtual env Python 路徑
- 避免相對路徑和環境變數依賴
- 確保路徑在 Claude Code 環境中可存取
### 🐛 常見問題診斷
**問題**: MCP 伺服器顯示 "Capabilities: none"
- **原因**: 回傳型別錯誤或 ServerCapabilities 設定問題
- **解決**: 檢查 handler 回傳型別,使用 `List[Tool]` 而非 `ListToolsResult`
**問題**: 無法查看工具清單 ("View tools" 不可用)
- **原因**: 缺少 ToolAnnotations 或工具註冊不正確
- **解決**: 為每個工具新增 ToolAnnotations
**問題**: 伺服器連線失敗
- **原因**: Python 路徑問題或模組匯入錯誤
- **解決**: 使用絕對路徑,檢查依賴安裝
### 📝 MCP 開發偵錯技巧
**1. 伺服器初始化測試**
```python
# 快速驗證伺服器可以正常建立
async def test():
server = YourMCPServer()
print('✅ MCP Server 建立成功')
return True
asyncio.run(test())
```
**2. 工具註冊驗證**
```python
# 驗證工具定義與註冊流程
from your_package.tools import get_tool_definitions
from mcp.types import Tool, ToolAnnotations
tool_definitions = get_tool_definitions()
for tool_def in tool_definitions:
# 驗證每個工具定義的完整性
assert "name" in tool_def
assert "description" in tool_def
assert "inputSchema" in tool_def
```
**3. 日誌與錯誤處理**
```python
# 新增詳細日誌便於偵錯
logging.basicConfig(
level=logging.DEBUG, # 開發時使用 DEBUG 級別
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
```
### 🎯 與現有 MCP 伺服器對比學習
**參考實作**: 分析運作正常的 MCP 伺服器 (如 zen-mcp-server)
- 對比 handler 回傳型別
- 檢查 ServerCapabilities 設定
- 驗證 ToolAnnotations 使用
**驗證步驟**:
1. 確保伺服器可以正常初始化
2. 驗證工具清單可以正確回傳
3. 檢查工具呼叫是否正常回應
4. 測試錯誤處理與異常情況
### 💡 開發流程建議
1. **先實作最小可行版本**: 1 個工具 + 基本 server 結構
2. **逐步驗證**: 每新增一個功能就測試 MCP 連線
3. **參考成功案例**: 對比其他運作正常的 MCP 伺服器實作
4. **詳細日誌**: 開發階段保留詳細的偵錯資訊
5. **增量測試**: 每次修改後都重新測試 MCP 整合