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 comply with the MCP protocol standards.
The Tianditu MCP Server provided 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 bus planning.
With the MCP Python SDK, any intelligent assistant that supports the MCP protocol (such as Claude, Cursor, and Qianfan AppBuilder) can quickly access the service.
## Tools
### Geocoding addr_to_geocode
**Description**: Parse an address into corresponding location coordinates. The more complete the address structure, the more accurate the address content, and the higher the precision of the parsed coordinates.
**Parameters**:
- address: The address to be parsed (e.g., "28 Liangfangchi West Road, Haidian District, Beijing"). The more complete the address structure, the higher the parsing accuracy.
**Output**:
- A dictionary of address longitude and latitude information, containing the following keys:
- lon (float): Longitude (gcj02ll)
- lat (float): Latitude (gcj02ll)
- score (int): Confidence score, ranging from 0 to 100, with higher scores indicating higher precision
- keyWord (str): The input address content
### Reverse Geocoding geocode_to_addr
**Description**: Based on the latitude and longitude coordinates, obtain the corresponding address description, administrative division, road, and related POI information.
**Parameters**:
- latitude: Latitude (gcj02ll)
- longitude: Longitude (gcj02ll)
**Output**:
- A dictionary of address longitude and latitude 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 longitude and latitude information
- lon (float): Longitude (gcj02ll)
- lat (float): Latitude (gcj02ll)
### Surrounding Search search_by_redius
**Description**: Set 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, e.g., 'query=Tiantan'
- latitude: Latitude (gcj02ll)
- longitude: Longitude (gcj02ll)
- radius: Radius (meters)
**Output**:
- A dictionary of surrounding query 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 containing the following keys:
- name (str): POI name
- address (str): POI address
- lonlat (str): Longitude and latitude (gcj02ll), in the format of longitude, latitude
- phone (str): Contact phone number
- distance (str): Distance (in meters or kilometers), with units in meters for distances below 1 kilometer and kilometers for distances above 1 kilometer
## Resources
### Administrative Division Code Table tdt://admin-code
**Description**: Chinese administrative division code table, including provincial, municipal, and district codes.
### Data Classification Code Table tdt://data-type
**Description**: Data classification code table, containing classification codes for various POIs such as restaurants, shops, and hospitals.
## Getting Started
Using the Tianditu MCP Server mainly involves two forms: Python and Typescript, which are introduced below.
### Obtaining AK
Before choosing either method, you need to create a server-side AK in the Tianditu Open Platform console. The AK is required to call the Tianditu API capabilities.
Refer to https://console.tianditu.gov.cn/api/key for the acquisition method.
### Python Access
#### Installation
Install mcp-tianditu using pip:
```bash
pip install mcp-tianditu
```
After installation, you can run it as a script using the following command:
```bash
python -m mcp_tianditu
```
#### Configuration
Add the following configuration in any MCP client (such as Claude.app), and some clients may require 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"
}
}
}
}
```
## Effects
You can now ask questions and verify the capabilities of the travel planning assistant.
### Example 1: Address Query
```
Please help me query the location coordinates of Zhongguancun, Haidian District, Beijing
```
### Example 2: Surrounding Search
```
I'm currently at Tiananmen (39.908823, 116.397470), please help me find museums within a 5-kilometer radius
```
### Example 3: Location Information Query
```
Please tell me the address information corresponding to the coordinates (39.908823, 116.397470)
```
### Example 4: Administrative Area Search
```
Please help me query universities within Beijing's Haidian District
```
### Example 5: Driving Planning
```
Please help me plan a driving route from Zhongguancun, Haidian District, Beijing to Guomao, Chaoyang District, Beijing
```
### Example 6: Bus Planning
```
Please help me plan a bus route from Beijing West Railway Station to Beijing Railway Station
```
## Accessing through Qianfan AppBuilder Platform
The Qianfan platform currently supports SDK access or API access. Build an application through AppBuilder, and 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 found below. Use SDK Agent and Tianditu MCP Server to obtain location information and surrounding POI information and provide travel suggestions.
### Agent Configuration
Go to the Qianfan platform, create a new application, and release it.
Adjust the agent's thinking rounds to 6 and release the application.
### Calling
This code can be used as a template. Call the application built on the Qianfan platform using the SDK, and then download the MCP Server to the local machine. 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
# Green printing
print("\033[1;31m", "-> Agent intermediate thinking: ", 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 tool name: {}, MCP parameters: {}\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 result: {}\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_calls_id": tool_call.id,
"output": tool_res,
}
)
return tool_output
async def success(self, run_context, run_response):
print("\n\033[1;34m", "-> Agent non-streaming answer: ", 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()
### User Token
os.environ["APPBUILDER_TOKEN"] = ""
async def main():
appbuilder.logger.setLoglevel("DEBUG")
### Released application ID
app_id = ""
appbuilder_client = appbuilder.AsyncAppBuilderClient(app_id)
mcp_client = MCPClient()
### Note that the path here is the relative path of the MCP Server file on the local machine
await mcp_client.connect_to_server("./<YOUR_FILE_PATH>/main.py")
print(mcp_client.tools)
await agent_run(
appbuilder_client,
mcp_client,
'Please help me query the location coordinates of Zhongguancun, Haidian District, Beijing',
)
await appbuilder_client.http_client.session.close()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```
### Effects
Through the agent's own thinking and calling the MCP Server geocoding service, reverse geocoding service, surrounding search service, and other tools, obtain location information and surrounding POI information and provide travel suggestions.
Actual user request: "Please help me plan a one-day trip to the Forbidden City in Beijing, considering surrounding catering and transportation."
## Instructions
Some parameter specifications passed in the Tianditu MCP Server:
- Administrative division codes all adopt the Tianditu adcode mapping table.
- Latitude and longitude coordinates all adopt the GCJ02LL latitude and longitude coordinates.
- Type and other Chinese string parameters 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.
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.
mempalace
The highest-scoring AI memory system ever benchmarked. And it's free.