Content
# Amap Address Parsing Service
Intelligent address parsing service based on Claude AI and Amap MCP, providing powerful address parsing, geocoding, and location information query functions.
## 🚀 Features
- **Intelligent Address Parsing**: Use Claude AI to understand natural language address queries
- **Amap Integration**: Integrate Amap API through MCP protocol
- **Multiple Query Methods**: Supports address to coordinates, coordinates to address, POI search, etc.
- **Multi-turn Tool Calls**: Supports complex multi-turn tool calls to complete continuous tasks
- **Multiple LLM Support**: Supports large models such as Claude and OpenAI
- **RESTful API**: Provides complete HTTP API interface
- **Asynchronous Processing**: High-performance asynchronous architecture, supports concurrent requests
- **Health Monitoring**: Complete health check and monitoring mechanism
- **Error Handling**: Complete exception handling and error recovery mechanism
## 📋 System Requirements
- Python 3.10+
- Node.js 16+ (for Amap MCP Server)
- Amap API Key
- Claude API Key
## 🛠️ Installation and Configuration
### 1. Clone the Project
```bash
git clone <repository-url>
cd address-parser-service
```
### 2. Create a Python Environment
#### Method 1: Using pip (Recommended)
```bash
# Create a virtual environment
python -m venv address-parser-env
# Activate the virtual environment
# Windows:
address-parser-env\Scripts\activate
# macOS/Linux:
source address-parser-env/bin/activate
# Install dependencies
pip install -r requirements.txt
```
#### Method 2: Using conda
```bash
# Method 1: Use the environment.yml file (Recommended)
conda env create -f environment.yml
conda activate address-parser
# Method 2: Manually create the environment
conda create -n address-parser python=3.11
conda activate address-parser
# Install dependencies
pip install -r requirements.txt
# Or use conda to install some dependencies
conda install fastapi uvicorn pydantic
pip install mcp anthropic structlog pydantic-settings
```
### 3. Configure Environment Variables
Copy the environment variable template:
```bash
cp .env.example .env
```
Edit the `.env` file and fill in your API keys:
```env
# Claude API Configuration
ANTHROPIC_API_KEY=your_anthropic_api_key_here
# Amap API Configuration
AMAP_MAPS_API_KEY=your_amap_api_key_here
# Keep other configurations as default
```
### 4. Get API Keys
#### Amap API Key
1. Visit [Amap Open Platform](https://lbs.amap.com/)
2. Register an account and create an application
3. Get the Web service API key
#### Claude API Key
1. Visit [Anthropic Console](https://console.anthropic.com/)
2. Create an account and get the API key
## 🚀 Quick Start
### Method 1: Using the Example Script
```bash
# Activate the environment (if using a virtual environment)
# pip environment:
source address-parser-env/bin/activate # macOS/Linux
# Or
address-parser-env\Scripts\activate # Windows
# conda environment:
conda activate address-parser
# Run the basic usage example
python examples/basic_usage.py
```
### Method 2: Start the API Service
```bash
# Start the FastAPI service
python api/main.py
```
After the service starts, visit:
- API Documentation: http://localhost:8000/docs
- Health Check: http://localhost:8000/api/v1/health
### Method 3: Directly Use the MCP Client
```python
import asyncio
from src.mcp_client import AmapMCPClient, ClaudeHandler
async def main():
# Create an MCP client
async with AmapMCPClient() as amap_client:
# Create a Claude handler
claude_handler = ClaudeHandler(amap_client)
# Process the query
result = await claude_handler.process_query(
"Please help me parse this address: Sanlitun Taikoo Li, Chaoyang District, Beijing"
)
print(result["final_answer"])
asyncio.run(main())
```
## 📖 API Documentation
### Address Parsing Interface
**POST** `/api/v1/address/parse`
Request Body:
```json
{
"address": "北京市朝阳区三里屯太古里",
"context": {
"city": "北京",
"preferences": "详细地址信息"
},
"system_prompt": "请提供详细的地址解析结果"
}
```
Response:
```json
{
"success": true,
"request_id": "1642123456789_abc12345",
"data": {
"formatted_address": "北京市朝阳区三里屯太古里",
"location": "116.397428,39.90923",
"province": "北京市",
"city": "北京市",
"district": "朝阳区"
},
"response": "根据您提供的地址,我已经成功解析出详细信息...",
"tool_calls": [...],
"processing_time": 2.5
}
```
### Health Check Interface
**GET** `/api/v1/health`
Response:
```json
{
"status": "healthy",
"mcp_connected": true,
"claude_available": true,
"tools_count": 5,
"uptime": 3600.0
}
```
### Tool List Interface
**GET** `/api/v1/tools`
Response:
```json
{
"success": true,
"tools": [
{
"name": "geocode",
"description": "地理编码,将地址转换为坐标",
"input_schema": {...}
}
],
"count": 1
}
```
## 🔧 Advanced Configuration
### MCP Server Management
Use the built-in server management script:
```bash
# Start the Amap MCP server
python scripts/start_amap_server.py start
# Stop the server
python scripts/start_amap_server.py stop
# Restart the server
python scripts/start_amap_server.py restart
# View the status
python scripts/start_amap_server.py status
# Monitor mode (automatic restart)
python scripts/start_amap_server.py monitor
```
### Configuration Parameter Description
| Parameter | Default Value | Description |
| ------------------------------ | ------------------------- | ----------------------------------------- |
| `LLM_PROVIDER` | claude | Large language model provider (claude or openai) |
| `ANTHROPIC_API_KEY` | Required | Claude API key |
| `CLAUDE_MODEL` | claude-3-7-sonnet-20250219 | Claude model version |
| `CLAUDE_MAX_TOKENS` | 1000 | Maximum Claude output tokens |
| `ENABLE_TOKEN_EFFICIENT_TOOLS` | false | Whether to enable Claude token-efficient tool calls |
| `TOOL_MAX_ITERATIONS` | 10 | Maximum number of tool call iterations |
| `OPENAI_API_KEY` | Optional | OpenAI API key |
| `OPENAI_MODEL` | gpt-4 | OpenAI model version |
| `OPENAI_MAX_TOKENS` | 1000 | Maximum OpenAI output tokens |
| `MCP_SERVER_TIMEOUT` | 30 | MCP server timeout (seconds) |
| `MCP_RETRY_COUNT` | 3 | Number of retries |
| `MCP_RETRY_DELAY` | 1.0 | Retry delay (seconds) |
| `LOG_LEVEL` | INFO | Log level |
| `API_HOST` | 127.0.0.1 | API service host |
| `API_PORT` | 8000 | API service port |
## 🧪 Testing
### Run Unit Tests
```bash
# Run all tests
pytest tests/
# Run a specific test file
pytest tests/test_mcp_client.py -v
# Run integration tests (requires API keys)
pytest tests/ -m integration
# Run multi-turn tool call tests
python tests/run_tests.py --claude # Run Claude tests only
python tests/run_tests.py --openai # Run OpenAI tests only
python tests/run_tests.py --complex # Run complex multi-turn tests only
python tests/run_tests.py --all # Run all tests
```
### Test Coverage
```bash
# Generate a test coverage report
pytest --cov=src tests/
```
## 📁 Project Structure
```
address-parser-service/
├── src/ # Core source code
│ ├── mcp_client/ # MCP client module
│ │ ├── amap_client.py # Amap MCP client
│ │ ├── claude_handler.py # Claude handler
│ │ └── openai_handler.py # OpenAI handler
│ ├── core/ # Core module
│ │ ├── config.py # Configuration management
│ │ ├── logger.py # Log configuration
│ │ └── exceptions.py # Exception definitions
│ └── utils/ # Utility functions
│ └── helpers.py # Helper functions
├── api/ # API service module
│ ├── main.py # FastAPI main application
│ ├── routes/ # API routes
│ └── schemas/ # Data models
├── tests/ # Test code
│ ├── test_mcp_client.py # MCP client tests
│ ├── test_multi_tool_calls.py # Multi-turn tool call tests
│ ├── test_complex_multi_tool_calls.py # Complex multi-turn tool call tests
│ └── test_openai_multi_tool_calls.py # OpenAI multi-turn tool call tests
├── scripts/ # Script files
├── examples/ # Usage examples
├── logs/ # Log files
├── requirements.txt # Python dependencies
├── .env.example # Environment variable template
└── README.md # Project documentation
```
## 🔍 Usage Examples
### Basic Address Parsing
```python
# Address to coordinates
query = "北京市朝阳区三里屯太古里"
result = await claude_handler.process_query(query)
# Coordinates to address
query = "116.397428,39.90923 What is the address corresponding to these coordinates?"
result = await claude_handler.process_query(query)
# POI search
query = "Help me find the geographic coordinates of Peking University"
result = await claude_handler.process_query(query)
```
### Multi-turn Tool Call Example
```python
# Multi-turn tool call example - weather comparison
query = "Check the weather in Beijing and Shanghai today, and tell me which city is more suitable for outdoor activities?"
result = await claude_handler.process_query(query)
# Complex multi-turn tool call - travel planning
query = """Please help me plan a trip from Beijing to Shanghai:
1. First check the weather conditions in Beijing and Shanghai
2. Then check the driving route from downtown Beijing to downtown Shanghai
3. Then check the famous attractions in Hangzhou, a city along the way
4. Finally, give me a detailed travel plan suggestion that comprehensively considers the weather and route
"""
result = await claude_handler.process_query(query)
```
### Batch Processing
```bash
curl -X POST "http://localhost:8000/api/v1/address/batch" \
-H "Content-Type: application/json" \
-d '[
{"address": "北京市朝阳区三里屯"},
{"address": "上海市浦东新区陆家嘴"},
{"address": "广州市天河区珠江新城"}
]'
```
## 🐛 Troubleshooting
### Common Issues
1. **MCP Connection Failed**
- Check if `AMAP_MAPS_API_KEY` is set correctly
- Confirm that the network connection is normal
- View the log file for detailed error information
2. **Claude API Call Failed**
- Check if `ANTHROPIC_API_KEY` is set correctly
- Confirm that the API key has sufficient quota
- Check the network connection
3. **Tool Call Timeout**
- Increase the `MCP_SERVER_TIMEOUT` configuration value
- Check the status of the Amap API service
4. **Dependency Package Conflicts**
- Use a virtual environment to isolate dependencies: `python -m venv address-parser-env`
- Or use a conda environment: `conda create -n address-parser python=3.11`
- Clear the pip cache: `pip cache purge`
5. **Conda Environment Issues**
- Make sure the correct environment is activated: `conda activate address-parser`
- If you encounter dependency conflicts, try mixed installation:
```bash
conda install fastapi uvicorn pydantic
pip install mcp anthropic structlog pydantic-settings
```
### Log Viewing
```bash
# View application logs
tail -f logs/app.log
# View API access logs
tail -f logs/api.log
```
## 🤝 Contribution Guide
1. Fork the project
2. Create a feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## 📄 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## 🙏 Acknowledgments
- [Anthropic](https://www.anthropic.com/) - Claude AI API
- [Amap](https://lbs.amap.com/) - Map Service API
- [Model Context Protocol](https://modelcontextprotocol.io/) - MCP Protocol
- [FastAPI](https://fastapi.tiangolo.com/) - Web Framework
## 📞 Support
If you encounter problems or have suggestions, please:
1. Check the [FAQ](#-故障排除)
2. Search existing [Issues](../../issues)
3. Create a new [Issue](../../issues/new)
---
**Note**: This project is for learning and research purposes only. Please comply with the terms of use of the relevant API services.
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.