Skip to main content
Glama

get-train-route-stations

Retrieve detailed stop information including stations, arrival/departure times, and dwell durations for specific train routes on China's railway network.

Instructions

查询特定列车车次在指定区间内的途径车站、到站时间、出发时间及停留时间等详细经停信息。当用户询问某趟具体列车的经停站时使用此接口。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
trainCodeYes要查询的车次 `train_code`,例如"G1033"。
departDateYes列车出发的日期 (格式: yyyy-MM-dd)。如果用户提供的是相对日期,请务必先调用 `get-current-date` 解析。
formatNo返回结果格式,默认为text,建议使用text。可选标志:[text, json]text

Implementation Reference

  • The main handler function for the 'get-train-route-stations' tool. It searches for the train using the public API to get train_no, then queries the private 12306 API for route stations using cookies, parses the response data with parseRouteStationsInfo, formats it, and returns as text or JSON.
    async ({ trainCode, departDate, format }) => {
        const searchParams = new URLSearchParams({
            keyword: trainCode,
            date: departDate.replaceAll('-', ''),
        });
        const searchUrl = `${SEARCH_API_BASE}/search/v1/train/search`;
        const searchResponse = await make12306Request<TrainSearchResponse>(
            searchUrl,
            searchParams
        );
        if (
            searchResponse == null ||
            searchResponse.data.length == 0 ||
            searchResponse.data == undefined
        ) {
            return {
                content: [
                    {
                        type: 'text',
                        text: '很抱歉,未查询到对应车次。',
                    },
                ],
            };
        }
    
        const searchData = searchResponse.data[0];
        const queryParams = new URLSearchParams({
            'leftTicketDTO.train_no': searchData.train_no,
            'leftTicketDTO.train_date': departDate,
            rand_code: '',
        });
        const queryUrl = `${API_BASE}/otn/queryTrainInfo/query`;
        const cookies = await getCookie();
        if (cookies == null || Object.entries(cookies).length === 0) {
            return {
                content: [
                    {
                        type: 'text',
                        text: 'Error: get cookie failed. Check your network.',
                    },
                ],
            };
        }
        const queryResponse = await make12306Request<RouteQueryResponse>(
            queryUrl,
            queryParams,
            { Cookie: formatCookies(cookies) }
        );
        if (queryResponse == null || queryResponse.data == undefined) {
            return {
                content: [
                    {
                        type: 'text',
                        text: 'Error: get train route stations failed. ',
                    },
                ],
            };
        }
        const routeStationsInfo = parseRouteStationsInfo(
            queryResponse.data.data
        );
        if (routeStationsInfo.length == 0) {
            return {
                content: [{ type: 'text', text: '未查询到相关车次信息。' }],
            };
        }
        var formatedResult;
        switch (format) {
            case 'json':
                formatedResult = JSON.stringify(routeStationsInfo);
                break;
            default:
                formatedResult = formatRouteStationsInfo(routeStationsInfo);
                break;
        }
        return {
            content: [{ type: 'text', text: formatedResult }],
        };
    }
  • Zod input schema for the tool parameters: trainCode (required string), departDate (required 10-char date string), format (optional 'text' or 'json').
    {
        trainCode: z
            .string()
            .describe('要查询的车次 `train_code`,例如"G1033"。'),
        departDate: z
            .string()
            .length(10)
            .describe(
                '列车出发的日期 (格式: yyyy-MM-dd)。如果用户提供的是相对日期,请务必先调用 `get-current-date` 解析。'
            ),
        format: z
            .string()
            .regex(/^(text|json)$/i)
            .default('text')
            .optional()
            .describe(
                '返回结果格式,默认为text,建议使用text。可选标志:[text, json]'
            ),
    },
  • src/index.ts:1386-1487 (registration)
    Registers the MCP tool 'get-train-route-stations' on the server instance with name, Chinese description, input schema, and inline handler function.
    server.tool(
        'get-train-route-stations',
        '查询特定列车车次在指定区间内的途径车站、到站时间、出发时间及停留时间等详细经停信息。当用户询问某趟具体列车的经停站时使用此接口。',
        {
            trainCode: z
                .string()
                .describe('要查询的车次 `train_code`,例如"G1033"。'),
            departDate: z
                .string()
                .length(10)
                .describe(
                    '列车出发的日期 (格式: yyyy-MM-dd)。如果用户提供的是相对日期,请务必先调用 `get-current-date` 解析。'
                ),
            format: z
                .string()
                .regex(/^(text|json)$/i)
                .default('text')
                .optional()
                .describe(
                    '返回结果格式,默认为text,建议使用text。可选标志:[text, json]'
                ),
        },
        async ({ trainCode, departDate, format }) => {
            const searchParams = new URLSearchParams({
                keyword: trainCode,
                date: departDate.replaceAll('-', ''),
            });
            const searchUrl = `${SEARCH_API_BASE}/search/v1/train/search`;
            const searchResponse = await make12306Request<TrainSearchResponse>(
                searchUrl,
                searchParams
            );
            if (
                searchResponse == null ||
                searchResponse.data.length == 0 ||
                searchResponse.data == undefined
            ) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: '很抱歉,未查询到对应车次。',
                        },
                    ],
                };
            }
    
            const searchData = searchResponse.data[0];
            const queryParams = new URLSearchParams({
                'leftTicketDTO.train_no': searchData.train_no,
                'leftTicketDTO.train_date': departDate,
                rand_code: '',
            });
            const queryUrl = `${API_BASE}/otn/queryTrainInfo/query`;
            const cookies = await getCookie();
            if (cookies == null || Object.entries(cookies).length === 0) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: 'Error: get cookie failed. Check your network.',
                        },
                    ],
                };
            }
            const queryResponse = await make12306Request<RouteQueryResponse>(
                queryUrl,
                queryParams,
                { Cookie: formatCookies(cookies) }
            );
            if (queryResponse == null || queryResponse.data == undefined) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: 'Error: get train route stations failed. ',
                        },
                    ],
                };
            }
            const routeStationsInfo = parseRouteStationsInfo(
                queryResponse.data.data
            );
            if (routeStationsInfo.length == 0) {
                return {
                    content: [{ type: 'text', text: '未查询到相关车次信息。' }],
                };
            }
            var formatedResult;
            switch (format) {
                case 'json':
                    formatedResult = JSON.stringify(routeStationsInfo);
                    break;
                default:
                    formatedResult = formatRouteStationsInfo(routeStationsInfo);
                    break;
            }
            return {
                content: [{ type: 'text', text: formatedResult }],
            };
        }
    );
  • Helper function that transforms raw API RouteStationData array into formatted RouteStationInfo array, adding train class/service info to the first station.
    function parseRouteStationsInfo(
        routeStationsData: RouteStationData[]
    ): RouteStationInfo[] {
        const result: RouteStationInfo[] = [];
        routeStationsData.forEach((routeStationData, index) => {
            if (index == 0) {
                result.push({
                    train_class_name: routeStationData.train_class_name,
                    service_type: routeStationData.service_type,
                    end_station_name: routeStationData.end_station_name,
                    station_name: routeStationData.station_name,
                    station_train_code: routeStationData.station_train_code,
                    arrive_time: routeStationData.arrive_time,
                    start_time: routeStationData.start_time,
                    lishi: routeStationData.running_time,
                    arrive_day_str: routeStationData.arrive_day_str,
                });
            } else {
                result.push({
                    station_name: routeStationData.station_name,
                    station_train_code: routeStationData.station_train_code,
                    arrive_time: routeStationData.arrive_time,
                    start_time: routeStationData.start_time,
                    lishi: routeStationData.running_time,
                    arrive_day_str: routeStationData.arrive_day_str,
                });
            }
        });
        return result;
    }
  • Helper function that formats the RouteStationInfo array into a human-readable markdown table string showing train details, station sequence, times, and durations.
    function formatRouteStationsInfo(
        routeStationsInfo: RouteStationInfo[]
    ): string {
        let result = `${routeStationsInfo[0].station_train_code}次列车(${
            routeStationsInfo[0].train_class_name
        } ${
            routeStationsInfo[0].service_type == '0' ? '无空调' : '有空调'
        })\n站序|车站|车次|到达时间|出发时间|历时(hh:mm)\n`;
        routeStationsInfo.forEach((routeStationInfo, index) => {
            result += `${index + 1}|${routeStationInfo.station_name}|${
                routeStationInfo.station_train_code
            }|${routeStationInfo.arrive_time}|${routeStationInfo.start_time}|${
                routeStationInfo.arrive_day_str
            } ${routeStationInfo.lishi}\n`;
        });
        return result;
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the core functionality (querying train stop details) but doesn't mention potential limitations like rate limits, authentication requirements, error conditions, or pagination behavior. The description is accurate but lacks operational context that would be helpful for an agent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is perfectly concise with two sentences: the first states the tool's purpose and scope, the second provides clear usage guidance. Every word earns its place, and the information is front-loaded with no redundant phrasing.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a read-only query tool with no annotations and no output schema, the description adequately covers the basic purpose and usage. However, it doesn't describe the return format details (though the format parameter hints at text/json options) or potential edge cases. Given the 3 parameters and lack of output schema, more context about response structure would be beneficial.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all three parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema (e.g., it doesn't explain trainCode format beyond the schema's example or clarify departDate logic). With complete schema coverage, the baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific verb ('查询' - query) and resource ('特定列车车次在指定区间内的途径车站、到站时间、出发时间及停留时间等详细经停信息'), distinguishing it from sibling tools like get-tickets (which likely retrieves ticket availability) or get-current-date (date utility). It precisely defines what information is returned about train stops.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly states when to use this tool: '当用户询问某趟具体列车的经停站时使用此接口' (use this interface when users ask about specific train stops). It also references an alternative tool (get-current-date) in the parameter description for date parsing, providing clear guidance on tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Joooook/12306-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server