Content
# TianDiTu MCP Server
## Overview
The TianDiTu API is now fully compatible with the MCP protocol, providing a set of geographic information service interfaces that meet the MCP protocol standards.
The MCP Server provided by TianDiTu includes 6 API interfaces that comply with the MCP protocol standards, covering core map service functions such as geocoding, reverse geocoding, surrounding search, administrative area search, driving planning, and public transportation planning.
Relying on the MCP Python SDK, any intelligent agent assistant that supports the MCP protocol (such as Claude, Cursor, and Qianfan AppBuilder, etc.) can be quickly connected.
## Tool List
### Geocoding addr_to_geocode
**Description**: Resolves an address into corresponding location coordinates. The more complete the address structure and the more accurate the address content, the higher the accuracy of the resolved coordinates.
**Parameters**:
- address: The address to be resolved (e.g., No. 28, Lianhua Pool West Road, Haidian District, Beijing). The more complete the address structure, the higher the resolution accuracy.
**Output**:
- A dictionary of address latitude and longitude information, containing the following keys:
- lon (float): Longitude (gcj02ll)
- lat (float): Latitude (gcj02ll)
- score (int): Confidence score, ranging from 0-100, the higher the score, the higher the accuracy
- keyWord (str): The input address content
### Reverse Geocoding geocode_to_addr
**Description**: Obtains the address description, administrative division, roads, and related POIs of the corresponding location based on latitude and longitude coordinates.
**Parameters**:
- latitude: Latitude (gcj02ll)
- longitude: Longitude (gcj02ll)
**Output**:
- A dictionary of address latitude and longitude information, containing the following keys:
- formatted_address (str): Formatted address information
- addressComponent (dict): Address information
- nation (str): Country
- province (str): Province
- city (str): City
- county (str): District
- town (str): Town/County
- road (str): Road
- location (dict): Input latitude and longitude information
- lon (float): Longitude (gcj02ll)
- lat (float): Latitude (gcj02ll)
### Surrounding Search search_by_redius
**Description**: Sets the center and radius to search for location information within a circular area (commonly used in surrounding search scenarios).
**Parameters**:
- query: Search keyword, can directly use name or type, such as 'query=Tiananmen'
- latitude: Latitude (gcj02ll)
- longitude: Longitude (gcj02ll)
- radius: Radius (meters)
**Output**:
- A dictionary of surrounding search results, containing the following keys:
- keyWord (str): Input search keyword
- count (int): Total number of search results
- pois(list[dict]): List of POI result elements, each element contains the following keys:
- name (str): POI name
- address (str): POI address
- lonlat (str): Latitude and longitude (gcj02ll), format: longitude,latitude
- phone (str): Contact phone number
- distance (str): Distance (unit m,km), units below 1 kilometer are meters (m), units above 1 kilometer are kilometers (km)
## Resources
### Administrative Division Code Table tdt://admin-code
**Description**: Chinese administrative division codes, including provinces, cities, and districts.
### Data Classification Code Table tdt://data-type
**Description**: Data classification code table, including various POI classification codes such as restaurants, shops, and hospitals.
## Get Started
There are two main ways to use the TianDiTu MCP Server: Python and Typescript. The following describes them separately.
### Get AK
Before choosing either method, you need to create a server-side AK in the TianDiTu Open Platform console. You can only call the TianDiTu API capabilities through the AK.
For how to obtain it, please refer to: https://console.tianditu.gov.cn/api/key
### Python Access
#### Installation
Install mcp-tianditu using pip:
```bash
pip install mcp-tianditu
```
After installation, we can run it as a script using the following command:
```bash
python -m mcp_tianditu
```
#### Configuration
Add the following configuration to any MCP client (such as Claude.app). Some clients may require some formatting adjustments.
The value corresponding to TIANDITU_API_KEY needs to be replaced with your own AK.
```json
{
"mcpServers": {
"tianditu-map": {
"command": "python",
"args": [
"-m",
"mcp_tianditu"
],
"env": {
"TIANDITU_API_KEY": "Your TianDiTu API Key"
}
}
}
}
```
If using uv configuration, the configuration content is as follows:
```json
{
"mcpServers": {
"tianditu-map": {
"command": "uvx",
"args": [
"mcp-tianditu"
],
"env": {
"TIANDITU_API_KEY": "Your TianDiTu API Key"
}
}
}
}
```
## Effect
Next, you can ask questions to verify the capabilities of the travel planning assistant.
### Example 1: Address Query
```
Please help me find the location coordinates of Zhongguancun, Haidian District, Beijing
```
### Example 2: Surrounding Search
```
I am now at Tiananmen Square in Beijing (39.908823, 116.397470). Please help me find museums within 5 kilometers.
```
### Example 3: Location Information Query
```
Please tell me the address information corresponding to the coordinates (39.908823, 116.397470)
```
### Example 4: Administrative Area Query
```
Please help me find universities in Haidian District, Beijing
```
### Example 5: Driving Plan
```
Please help me plan a driving route from Zhongguancun, Haidian District, Beijing to Guomao, Chaoyang District, Beijing
```
### Example 6: Public Transportation Plan
```
Please help me plan a public transportation route from Beijing West Railway Station to Beijing Railway Station
```
## Access via Qianfan AppBuilder Platform
Qianfan platform access currently supports SDK access or API access. Build an application through AppBuilder. Each application has an independent app_id. Call the corresponding app_id in the python file, and then call the TianDiTu Python MCP Tool.
The template code can be scrolled down. Through the SDK Agent && TianDiTu MCP Server, you can get location information and surrounding POI information, and provide travel suggestions.
### Agent Configuration
Go to the Qianfan platform, create a new application, and publish it.
Adjust the Agent's thinking rounds to 6. Publish the application.
### Call
This code can be used as a template to call an App that has been built and published on the Qianfan platform in the form of an SDK, then download the MCP Server to the local machine, and write the relative path of the file into the code.
(Note: Use the actual app_id, token, query, and mcp file)
```python
import os
import asyncio
import appbuilder
from appbuilder.core.console.appbuilder_client.async_event_handler import (
AsyncAppBuilderEventHandler,
)
from appbuilder.mcp_server.client import MCPClient
class MyEventHandler(AsyncAppBuilderEventHandler):
def __init__(self, mcp_client):
super().__init__()
self.mcp_client = mcp_client
def get_current_weather(self, location=None, unit="摄氏度"):
return "{} 的温度是 {} {}".format(location, 20, unit)
async def interrupt(self, run_context, run_response):
thought = run_context.current_thought
# 绿色打印
print("\033[1;31m", "-> Agent 中间思考: ", thought, "\033[0m")
tool_output = []
for tool_call in run_context.current_tool_calls:
tool_res = ""
if tool_call.function.name == "get_current_weather":
tool_res = self.get_current_weather(**tool_call.function.arguments)
else:
print(
"\033[1;32m",
"MCP工具名称: {}, MCP参数:{}\n".format(tool_call.function.name, tool_call.function.arguments),
"\033[0m",
)
mcp_server_result = await self.mcp_client.call_tool(
tool_call.function.name, tool_call.function.arguments
)
print("\033[1;33m", "MCP结果: {}\n\033[0m".format(mcp_server_result))
for i, content in enumerate(mcp_server_result.content):
if content.type == "text":
tool_res += mcp_server_result.content[i].text
tool_output.append(
{
"tool_call_id": tool_call.id,
"output": tool_res,
}
)
return tool_output
async def success(self, run_context, run_response):
print("\n\033[1;34m", "-> Agent 非流式回答: ", run_response.answer, "\033[0m")
async def agent_run(client, mcp_client, query):
tools = mcp_client.tools
conversation_id = await client.create_conversation()
with await client.run_with_handler(
conversation_id=conversation_id,
query=query,
tools=tools,
event_handler=MyEventHandler(mcp_client),
) as run:
await run.until_done()
### 用户Token
os.environ["APPBUILDER_TOKEN"] = ""
async def main():
appbuilder.logger.setLoglevel("DEBUG")
### 发布的应用ID
app_id = ""
appbuilder_client = appbuilder.AsyncAppBuilderClient(app_id)
mcp_client = MCPClient()
### 注意这里的路径为MCP Server文件在本地的相对路径
await mcp_client.connect_to_server("./<YOUR_FILE_PATH>/main.py")
print(mcp_client.tools)
await agent_run(
appbuilder_client,
mcp_client,
'请帮我查询北京市海淀区中关村的位置坐标',
)
await appbuilder_client.http_client.session.close()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
### Effect
After the Agent's own thinking, by calling multiple tools such as the MCPServer geocoding service, reverse geocoding service, and surrounding search service, it obtains location information and surrounding POI information, and provides travel suggestions.
Actual user request: "Please help me plan a one-day tour of the Forbidden City in Beijing, and consider the surrounding dining and transportation."
## Description
Specifications of some parameters passed in the TianDiTu MCP Server:
- Administrative division codes all use the TianDiTu adcode mapping table.
- Latitude and longitude coordinates all use the National Bureau of Surveying and Mapping latitude and longitude coordinates gcj02ll.
- Chinese string parameters such as types should comply with the TianDiTu POI type standards.
## License
MIT
Connection Info
You Might Also Like
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
markitdown
Python tool for converting files and office documents to Markdown.
firecrawl
Firecrawl MCP Server enables web scraping, crawling, and content extraction.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.
TrendRadar
TrendRadar: Your hotspot assistant for real news in just 30 seconds.
mempalace
The highest-scoring AI memory system ever benchmarked. And it's free.