CLAUDE.md•7.95 kB
# 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 集成