Content
# 12306-MCP
[](LICENSE)
[](https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html)
[](https://spring.io/projects/spring-boot)
[](https://spring.io/projects/spring-ai)
[](https://modelcontextprotocol.io/)
A 12306 train information query service based on Spring Boot and Spring AI, providing interaction capabilities with large language models through the MCP (Model Context Protocol) protocol.
## Features
- **Station Information Query**: Query city stations, station codes, etc.
- **Ticket Information Query**: Query direct ticket information, support filtering by train type
- **Train Route Query**: Query complete train route and stop information
- **Transfer Query**: Query transfer schemes between two stations
- **Train Screening**: Support screening by train type (high-speed rail,动车, special express, etc.)
- **MCP Protocol Support**: Allow large language models to call service functions through standard protocols
## Environment Requirements
- JDK 17 or higher
- Maven 3.6 or higher
- Spring Boot 3.4.3 or higher
- Spring AI 1.0.0-M6 or higher
- Network connection (for accessing 12306 API)
## Quick Start
### 1. Clone Project
```bash
git clone https://github.com/xiaonieli7/12306-mcp-java.git
cd 12306-mcp
```
### 2. Configure Parameters
Default project configuration is set in `src/main/resources/application.yml`:
```yaml
server:
port: 8080
spring:
application:
name: 12306-mcp-java
ai:
mcp-server:
endpoint: /see
# Optional configuration, by default, all methods annotated with @Tool will be automatically registered as tools
tools:
include:
packages: com.mcp
logging:
level:
org.springframework.ai: INFO
com.mcp: DEBUG
```
### 3. Build Project
```bash
mvn clean package
```
### 4. Run Application
```bash
java -jar target/jcai-0.0.1-SNAPSHOT.jar
```
The service will display startup information and registered tool list in the console.
## MCP Service Configuration
This project supports the MCP (Model Context Protocol) protocol, allowing large language models to directly call service functions.
Large models can access through the following configuration:
```json
{
"mcpServers": {
"12306-mcp": {
"url": "http://localhost:8080/see"
}
}
}
```
## Project Structure
```
src/main/java/com/jcai/
├── Application.java # Application entry class
├── constants/
│ └── RailwayConstants.java # Railway-related constants
├── model/
│ ├── InterlineInfo.java # Transfer route information model
│ ├── Price.java # Ticket price information model
│ ├── RouteStationData.java # Route station data model
│ ├── RouteStationInfo.java # Formatted route station information
│ ├── StationData.java # Station data model
│ ├── TicketData.java # Ticket data model
│ └── TicketInfo.java # Formatted ticket information
├── service/
│ ├── DateService.java # Date service
│ ├── InterlineService.java # Transfer query service
│ ├── RouteService.java # Route query service
│ ├── StationService.java # Station query service
│ └── TicketService.java # Ticket query service
└── utils/
├── DateUtils.java # Date utility class
└── HttpUtils.java # HTTP request utility class
```
## API Interface Description
This project exposes the following tool functions through the MCP protocol:
### 1. Date Service (DateService)
| Interface Name | Description | Parameters | Return Value |
|---------|------|------|--------|
| getCurrentDate | Get current date | None | Current date string (yyyy-MM-dd) |
| isValidDate | Verify if date string is valid | dateStr: date string | Boolean value |
| isValidFutureDate | Verify if date is current or future date | dateStr: date string | Boolean value |
| formatDate | Format date string | dateStr: date string | Formatted date string |
### 2. Station Service (StationService)
| Interface Name | Description | Parameters | Return Value |
|---------|------|------|--------|
| getStationsCodeInCity | Get all station information in a specified city | cityName: city name | JSON string of city station information |
| getStationCodeByName | Get station code by station name | stationName: station name | JSON string of station code information |
| getStationCodeByNames | Get station codes by multiple station names | stationNames: multiple station names (comma-separated) | JSON string of multiple station code information |
| getStationNameByCode | Get station name by station code | stationCode: station code | Station name |
| searchStations | Fuzzy query stations by keyword | keyword: keyword | Matching station list JSON string |
| getTotalStationCount | Get total number of stations in the system | None | Total number of stations |
### 3. Ticket Service (TicketService)
| Interface Name | Description | Parameters | Return Value |
|---------|------|------|--------|
| getTickets | Query ticket information between two stations | date: date<br>fromStation: departure station code<br>toStation: arrival station code<br>trainTypes: train type filtering (optional) | JSON string of ticket information |
### 4. Route Service (RouteService)
| Interface Name | Description | Parameters | Return Value |
|---------|------|------|--------|
| getTrainRoute | Query complete train route information | date: date<br>trainCode: train code<br>fromStation: departure station code<br>toStation: arrival station code | JSON string of train route information |
### 5. Transfer Service (InterlineService)
| Interface Name | Description | Parameters | Return Value |
|---------|------|------|--------|
| getInterlineRoutes | Query transfer route schemes between two stations | date: date<br>fromStation: departure station code<br>toStation: arrival station code<br>trainTypes: train type filtering (optional) | JSON string of transfer route information |
## Example
### Query Station Code
```json
// Request parameters
{
"stationName": "Beijing South"
}
// Return result
{
"Beijing South": {
"station_code": "VNP",
"station_name": "Beijing South"
}
}
```
### Query Ticket Information
```json
// Request parameters
{
"date": "2023-05-01",
"fromStation": "VNP",
"toStation": "AOH",
"trainTypes": "G"
}
// Return result (simplified)
[
{
"trainNo": "24000000G10Q",
"startTrainCode": "G1",
"startTime": "06:36",
"arriveTime": "12:38",
"lishi": "06:02",
"fromStation": "Beijing South",
"toStation": "Shanghai Hongqiao",
"fromStationTelecode": "VNP",
"toStationTelecode": "AOH",
"prices": [
{
"seatName": "Business Seat",
"shortName": "swz",
"seatTypeCode": "9",
"num": "Available"
},
{
"seatName": "First Class Seat",
"shortName": "zy",
"seatTypeCode": "M",
"num": "Available"
}
],
"dwFlag": ["Fuxing Hao"]
}
]
```
### Query Train Route
```json
// Request parameters
{
"date": "2023-05-01",
"trainCode": "G1",
"fromStation": "VNP",
"toStation": "AOH"
}
// Return result (simplified)
[
{
"arriveTime": "06:36",
"stationName": "Beijing South",
"stopoverTime": "3 minutes",
"stationNo": 1
},
{
"arriveTime": "08:15",
"stationName": "Jinan West",
"stopoverTime": "2 minutes",
"stationNo": 2
},
{
"arriveTime": "12:38",
"stationName": "Shanghai Hongqiao",
"stopoverTime": "Terminal",
"stationNo": 3
}
]
```
### Query Transfer Route
```json
// Request parameters
{
"date": "2023-05-01",
"fromStation": "ZDW",
"toStation": "ZYN",
"trainTypes": "G"
}
// Return result (simplified)
[
{
"from_station": "Chengdu East",
"middle_station": "Xi'an North",
"to_station": "Zhengzhou",
"first_train": "G89",
"second_train": "G507",
"start_time": "08:45",
"arrive_time": "16:58",
"total_time": "08:13",
"wait_time": "00:45",
"same_station": true
}
]
```
## Integration with Large Language Models
This project integrates with large language models based on Spring AI's MCP protocol, allowing models to call service functions:
1. Models can discover all available tools through MCP protocol
2. Choose suitable tools based on user natural language requests
3. Call tools and get results
4. Format results and return to users
Example dialogue:
- User: What is the high-speed rail ticket price from Beijing to Shanghai tomorrow?
- Model: (After calling tools through MCP) The high-speed rail ticket price from Beijing to Shanghai tomorrow is 553 yuan for second-class seat and 933 yuan for first-class seat. The earliest train G1 departs from Beijing South Station at 06:36 and arrives at Shanghai Hongqiao Station at 12:38.
## Supported Train Type Screening
The following train types can be used for ticket query and transfer query screening:
- `G` - High-speed rail / Intercity (G/C train number)
- `D` -动车 (D train number)
- `Z` - Direct express (Z train number)
- `T` - Express (T train number)
- `K` - Fast (K train number)
- `F` - Fuxing Hao (train number with "Fuxing Hao" logo)
- `S` - Smart动车组 (train number with "Smart动车组" logo)
- `O` - Other (train numbers not of the above types)
## Technical Implementation
- Use Hutool HTTP and OkHttp client to access 12306 API
- Use FastJSON for JSON data parsing and generation
- Implement tool exposure based on Spring AI's MCP protocol
- Use Spring Boot as application framework
- Use Lombok to simplify code
## Contribution Guide
Welcome to contribute code, report issues, or propose new features. Before submitting PR, please ensure to follow these guidelines:
1. Code style consistent with the project
2. Add appropriate tests
3. Update documentation to explain new features
## Acknowledgments
- [Spring Boot](https://spring.io/projects/spring-boot)
- [Spring AI](https://spring.io/projects/spring-ai)
- [Model Context Protocol](https://modelcontextprotocol.io/)
- [Hutool](https://hutool.cn/)
- [FastJSON](https://github.com/alibaba/fastjson)
- [Lombok](https://projectlombok.org/)
## Log Management
This project uses SLF4J and Logback for log management, providing multi-level log recording:
- **ERROR**: Record severe errors, such as API request failures, data parsing exceptions, etc.
- **WARN**: Record warning information, such as parameter verification failures, no matching data found, etc.
- **INFO**: Record key business processes, such as query start, completion, result statistics, etc.
- **DEBUG**: Record detailed operation steps, such as parameter construction, API requests, data parsing, etc.
- **TRACE**: Record the most detailed debugging information, usually used in development environment
### Log Configuration
Log level can be configured in `application.yml`:
```yaml
logging:
level:
org.springframework.ai: INFO
com.mcp: DEBUG # Can be modified to INFO, WARN, ERROR, etc.
```
### Log Example
```
2023-05-01 12:34:56.789 INFO [main] c.j.s.StationService - Station data loaded, total 2574 stations
2023-05-01 12:35:01.234 INFO [http-nio-8080-exec-1] c.j.s.TicketService - Query ticket information: 2023-05-03 from VNP to AOH
2023-05-01 12:35:03.456 INFO [http-nio-8080-exec-1] c.j.s.TicketService - Found 35 ticket information
2023-05-01 12:35:03.567 INFO [http-nio-8080-exec-1] c.j.s.TicketService - Query completed, return 25 ticket information
```
### Log File
Log files are saved in the `logs/` directory under the application running directory by default:
- `12306-mcp.log` - Current log file
- `12306-mcp.log.yyyy-MM-dd` - Historical log files
Log file location and rolling strategy can be modified by adding the following configuration in `application.yml`:
```yaml
logging:
file:
name: /path/to/your/logs/12306-mcp.log
logback:
rollingpolicy:
max-file-size: 10MB
max-history: 30
```
This project is for learning purposes only.
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
No recommendations available