Skip to main content
Glama

get-interline-tickets

Search for interline ticket availability on 12306, specifying date, departure, and arrival stations. Optionally filter by train type, time range, and sort order. Returns up to 10 results.

Instructions

查询12306中转余票信息。尚且只支持查询前十条。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dateYes查询日期,格式为 "yyyy-MM-dd"。如果用户提供的是相对日期(如“明天”),请务必先调用 `get-current-date` 接口获取当前日期,并计算出目标日期。
fromStationYes出发地的中文名或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)
toStationYes到达地的中文名或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)
middleStationNo中转地的中文或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)。该参数可选。
showWZNo是否显示无座车,默认不显示无座车。
trainFilterFlagsNo车次筛选条件,默认为空。从以下标志中选取多个条件组合[G(高铁/城际),D(动车),Z(直达特快),T(特快),K(快速),O(其他),F(复兴号),S(智能动车组)]
earliestStartTimeNo最早出发时间(0-24),默认为0。
latestStartTimeNo最迟出发时间(0-24),默认为24。
sortFlagNo排序方式,默认为空,即不排序。仅支持单一标识。可选标志:[startTime(出发时间从早到晚), arriveTime(抵达时间从早到晚), duration(历时从短到长)]
sortReverseNo是否逆向排序结果,默认为false。仅在设置了sortFlag时生效。
limitedNumNo返回的中转余票数量限制,默认为10。
formatNo返回结果格式,默认为text,建议使用text。可选标志:[text, json]text

Implementation Reference

  • src/index.ts:1167-1402 (registration)
    Registration of the 'get-interline-tickets' tool using server.tool() with schema definition (Zod) and the async handler function.
    server.tool(
        'get-interline-tickets',
        '查询12306中转余票信息。尚且只支持查询前十条。',
        {
            date: z
                .string()
                .length(10)
                .describe(
                    '查询日期,格式为 "yyyy-MM-dd"。如果用户提供的是相对日期(如“明天”),请务必先调用 `get-current-date` 接口获取当前日期,并计算出目标日期。'
                ),
            fromStation: z
                .string()
                .describe(
                    '出发地的中文名或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)'
                ),
            toStation: z
                .string()
                .describe(
                    '到达地的中文名或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)'
                ),
            middleStation: z
                .string()
                .optional()
                .default('')
                .describe(
                    '中转地的中文或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)。该参数可选。'
                ),
            showWZ: z
                .boolean()
                .optional()
                .default(false)
                .describe('是否显示无座车,默认不显示无座车。'),
            trainFilterFlags: z
                .string()
                .regex(/^[GDZTKOFS]*$/)
                .max(8)
                .optional()
                .default('')
                .describe(
                    '车次筛选条件,默认为空。从以下标志中选取多个条件组合[G(高铁/城际),D(动车),Z(直达特快),T(特快),K(快速),O(其他),F(复兴号),S(智能动车组)]'
                ),
            earliestStartTime: z
                .number()
                .min(0)
                .max(24)
                .optional()
                .default(0)
                .describe('最早出发时间(0-24),默认为0。'),
            latestStartTime: z
                .number()
                .min(0)
                .max(24)
                .optional()
                .default(24)
                .describe('最迟出发时间(0-24),默认为24。'),
            sortFlag: z
                .string()
                .optional()
                .default('')
                .describe(
                    '排序方式,默认为空,即不排序。仅支持单一标识。可选标志:[startTime(出发时间从早到晚), arriveTime(抵达时间从早到晚), duration(历时从短到长)]'
                ),
            sortReverse: z
                .boolean()
                .optional()
                .default(false)
                .describe(
                    '是否逆向排序结果,默认为false。仅在设置了sortFlag时生效。'
                ),
            limitedNum: z
                .number()
                .min(1)
                .optional()
                .default(10)
                .describe('返回的中转余票数量限制,默认为10。'),
            format: z
                .string()
                .regex(/^(text|json)$/i)
                .default('text')
                .optional()
                .describe(
                    '返回结果格式,默认为text,建议使用text。可选标志:[text, json]'
                ),
        },
        async ({
            date,
            fromStation,
            toStation,
            middleStation,
            showWZ,
            trainFilterFlags,
            earliestStartTime,
            latestStartTime,
            sortFlag,
            sortReverse,
            limitedNum,
            format,
        }) => {
            // 检查日期是否早于当前日期
            if (!checkDate(date)) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: 'Error: The date cannot be earlier than today.',
                        },
                    ],
                };
            }
            const fromStationResult = parseStationCode(fromStation);
            const toStationResult = parseStationCode(toStation);
            const middleStationResult = parseStationCode(middleStation);
            if (
                fromStationResult === null ||
                toStationResult === null ||
                (middleStation !== '' && middleStationResult === null)
            ) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: `Error: Station not found. FromStationResult: ${fromStationResult}, ToStationResult: ${toStationResult}, MiddleStationResult: ${middleStationResult}`,
                        },
                    ],
                };
            }
            fromStation = fromStationResult;
            toStation = toStationResult;
            middleStation = middleStationResult ? middleStationResult : '';
            const queryUrl = `${API_BASE}${LCQUERY_PATH}`;
            const cookies = await getCookie();
            if (cookies == null || Object.entries(cookies).length === 0) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: 'Error: get cookie failed. Check your network.',
                        },
                    ],
                };
            }
    
            var interlineData: InterlineData[] = [];
            const queryParams = new URLSearchParams({
                train_date: date,
                from_station_telecode: fromStation,
                to_station_telecode: toStation,
                middle_station: middleStation,
                result_index: '0',
                can_query: 'Y',
                isShowWZ: showWZ ? 'Y' : 'N',
                purpose_codes: '00', // 00: 成人票 0X: 学生票
                channel: 'E', // 没搞清楚什么用
            });
            while (interlineData.length < limitedNum) {
                const queryResponse =
                    await make12306Request<InterlineQueryResponse>(
                        queryUrl,
                        queryParams,
                        { Cookie: formatCookies(cookies) }
                    );
                // 处理请求错误
                if (queryResponse === null || queryResponse === undefined) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: 'Error: request interline tickets data failed. ',
                            },
                        ],
                    };
                }
                // 请求成功,但查询有误
                if (typeof queryResponse.data == 'string') {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `很抱歉,未查到相关的列车余票。(${queryResponse.errorMsg})`,
                            },
                        ],
                    };
                }
                interlineData = interlineData.concat(queryResponse.data.middleList);
                if (queryResponse.data.can_query == 'N') {
                    break;
                }
                queryParams.set(
                    'result_index',
                    queryResponse.data.result_index.toString()
                );
            }
            // 请求和查询都没问题
            let interlineTicketsInfo: InterlineInfo[];
            try {
                interlineTicketsInfo = parseInterlinesInfo(interlineData);
            } catch (error) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: `Error: parse tickets info failed. ${error}`,
                        },
                    ],
                };
            }
            const filteredInterlineTicketsInfo = filterTicketsInfo<InterlineInfo>(
                interlineTicketsInfo,
                trainFilterFlags,
                earliestStartTime,
                latestStartTime,
                sortFlag,
                sortReverse,
                limitedNum
            );
            var formatedResult;
            switch (format) {
                case 'json':
                    formatedResult = JSON.stringify(filteredInterlineTicketsInfo);
                    break;
                default:
                    formatedResult = formatInterlinesInfo(
                        filteredInterlineTicketsInfo
                    );
                    break;
            }
            return {
                content: [
                    {
                        type: 'text',
                        text: formatedResult,
                    },
                ],
            };
        }
    );
  • The async handler function that executes the logic: validates date, parses station codes, queries the 12306 interline API, processes results, filters/sorts, and formats output.
    async ({
        date,
        fromStation,
        toStation,
        middleStation,
        showWZ,
        trainFilterFlags,
        earliestStartTime,
        latestStartTime,
        sortFlag,
        sortReverse,
        limitedNum,
        format,
    }) => {
        // 检查日期是否早于当前日期
        if (!checkDate(date)) {
            return {
                content: [
                    {
                        type: 'text',
                        text: 'Error: The date cannot be earlier than today.',
                    },
                ],
            };
        }
        const fromStationResult = parseStationCode(fromStation);
        const toStationResult = parseStationCode(toStation);
        const middleStationResult = parseStationCode(middleStation);
        if (
            fromStationResult === null ||
            toStationResult === null ||
            (middleStation !== '' && middleStationResult === null)
        ) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `Error: Station not found. FromStationResult: ${fromStationResult}, ToStationResult: ${toStationResult}, MiddleStationResult: ${middleStationResult}`,
                    },
                ],
            };
        }
        fromStation = fromStationResult;
        toStation = toStationResult;
        middleStation = middleStationResult ? middleStationResult : '';
        const queryUrl = `${API_BASE}${LCQUERY_PATH}`;
        const cookies = await getCookie();
        if (cookies == null || Object.entries(cookies).length === 0) {
            return {
                content: [
                    {
                        type: 'text',
                        text: 'Error: get cookie failed. Check your network.',
                    },
                ],
            };
        }
    
        var interlineData: InterlineData[] = [];
        const queryParams = new URLSearchParams({
            train_date: date,
            from_station_telecode: fromStation,
            to_station_telecode: toStation,
            middle_station: middleStation,
            result_index: '0',
            can_query: 'Y',
            isShowWZ: showWZ ? 'Y' : 'N',
            purpose_codes: '00', // 00: 成人票 0X: 学生票
            channel: 'E', // 没搞清楚什么用
        });
        while (interlineData.length < limitedNum) {
            const queryResponse =
                await make12306Request<InterlineQueryResponse>(
                    queryUrl,
                    queryParams,
                    { Cookie: formatCookies(cookies) }
                );
            // 处理请求错误
            if (queryResponse === null || queryResponse === undefined) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: 'Error: request interline tickets data failed. ',
                        },
                    ],
                };
            }
            // 请求成功,但查询有误
            if (typeof queryResponse.data == 'string') {
                return {
                    content: [
                        {
                            type: 'text',
                            text: `很抱歉,未查到相关的列车余票。(${queryResponse.errorMsg})`,
                        },
                    ],
                };
            }
            interlineData = interlineData.concat(queryResponse.data.middleList);
            if (queryResponse.data.can_query == 'N') {
                break;
            }
            queryParams.set(
                'result_index',
                queryResponse.data.result_index.toString()
            );
        }
        // 请求和查询都没问题
        let interlineTicketsInfo: InterlineInfo[];
        try {
            interlineTicketsInfo = parseInterlinesInfo(interlineData);
        } catch (error) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `Error: parse tickets info failed. ${error}`,
                    },
                ],
            };
        }
        const filteredInterlineTicketsInfo = filterTicketsInfo<InterlineInfo>(
            interlineTicketsInfo,
            trainFilterFlags,
            earliestStartTime,
            latestStartTime,
            sortFlag,
            sortReverse,
            limitedNum
        );
        var formatedResult;
        switch (format) {
            case 'json':
                formatedResult = JSON.stringify(filteredInterlineTicketsInfo);
                break;
            default:
                formatedResult = formatInterlinesInfo(
                    filteredInterlineTicketsInfo
                );
                break;
        }
        return {
            content: [
                {
                    type: 'text',
                    text: formatedResult,
                },
            ],
        };
    }
  • Input schema (Zod) for the tool defining all parameters: date, fromStation, toStation, middleStation, showWZ, trainFilterFlags, earliestStartTime, latestStartTime, sortFlag, sortReverse, limitedNum, format.
    {
        date: z
            .string()
            .length(10)
            .describe(
                '查询日期,格式为 "yyyy-MM-dd"。如果用户提供的是相对日期(如“明天”),请务必先调用 `get-current-date` 接口获取当前日期,并计算出目标日期。'
            ),
        fromStation: z
            .string()
            .describe(
                '出发地的中文名或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)'
            ),
        toStation: z
            .string()
            .describe(
                '到达地的中文名或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)'
            ),
        middleStation: z
            .string()
            .optional()
            .default('')
            .describe(
                '中转地的中文或站点的 `station_code`(可通过 `get-station-code-by-names` 或 `get-station-code-of-citys` 接口查询得到)。该参数可选。'
            ),
        showWZ: z
            .boolean()
            .optional()
            .default(false)
            .describe('是否显示无座车,默认不显示无座车。'),
        trainFilterFlags: z
            .string()
            .regex(/^[GDZTKOFS]*$/)
            .max(8)
            .optional()
            .default('')
            .describe(
                '车次筛选条件,默认为空。从以下标志中选取多个条件组合[G(高铁/城际),D(动车),Z(直达特快),T(特快),K(快速),O(其他),F(复兴号),S(智能动车组)]'
            ),
        earliestStartTime: z
            .number()
            .min(0)
            .max(24)
            .optional()
            .default(0)
            .describe('最早出发时间(0-24),默认为0。'),
        latestStartTime: z
            .number()
            .min(0)
            .max(24)
            .optional()
            .default(24)
            .describe('最迟出发时间(0-24),默认为24。'),
        sortFlag: z
            .string()
            .optional()
            .default('')
            .describe(
                '排序方式,默认为空,即不排序。仅支持单一标识。可选标志:[startTime(出发时间从早到晚), arriveTime(抵达时间从早到晚), duration(历时从短到长)]'
            ),
        sortReverse: z
            .boolean()
            .optional()
            .default(false)
            .describe(
                '是否逆向排序结果,默认为false。仅在设置了sortFlag时生效。'
            ),
        limitedNum: z
            .number()
            .min(1)
            .optional()
            .default(10)
            .describe('返回的中转余票数量限制,默认为10。'),
        format: z
            .string()
            .regex(/^(text|json)$/i)
            .default('text')
            .optional()
            .describe(
                '返回结果格式,默认为text,建议使用text。可选标志:[text, json]'
            ),
  • parseInterlinesInfo() - Parses raw InterlineData array into InterlineInfo array, used by the handler to process API responses.
    function parseInterlinesInfo(interlineData: InterlineData[]): InterlineInfo[] {
        const result: InterlineInfo[] = [];
        for (const ticket of interlineData) {
            const interlineTickets = parseInterlinesTicketInfo(ticket.fullList);
            const lishi = extractLishi(ticket.all_lishi);
            result.push({
                lishi: lishi,
                start_time: ticket.start_time,
                start_date: ticket.train_date,
                middle_date: ticket.middle_date,
                arrive_date: ticket.arrive_date,
                arrive_time: ticket.arrive_time,
                from_station_code: ticket.from_station_code,
                from_station_name: ticket.from_station_name,
                middle_station_code: ticket.middle_station_code,
                middle_station_name: ticket.middle_station_name,
                end_station_code: ticket.end_station_code,
                end_station_name: ticket.end_station_name,
                start_train_code: interlineTickets[0].start_train_code,
                first_train_no: ticket.first_train_no,
                second_train_no: ticket.second_train_no,
                train_count: ticket.train_count,
                ticketList: interlineTickets,
                same_station: ticket.same_station == '0' ? true : false,
                same_train: ticket.same_train == 'Y' ? true : false,
                wait_time: ticket.wait_time,
            });
        }
        return result;
    }
  • formatInterlinesInfo() - Formats InterlineInfo array into a human-readable text string for the default text output format.
    function formatInterlinesInfo(interlinesInfo: InterlineInfo[]): string {
        let result =
            '出发时间 -> 到达时间 | 出发车站 -> 中转车站 -> 到达车站 | 换乘标志 |换乘等待时间| 总历时\n\n';
        interlinesInfo.forEach((interlineInfo) => {
            result += `${interlineInfo.start_date} ${interlineInfo.start_time} -> ${interlineInfo.arrive_date} ${interlineInfo.arrive_time} | `;
            result += `${interlineInfo.from_station_name} -> ${interlineInfo.middle_station_name} -> ${interlineInfo.end_station_name} | `;
            result += `${
                interlineInfo.same_train
                    ? '同车换乘'
                    : interlineInfo.same_station
                      ? '同站换乘'
                      : '换站换乘'
            } | ${interlineInfo.wait_time} | ${interlineInfo.lishi}\n\n`;
            result +=
                '\t' +
                formatTicketsInfo(interlineInfo.ticketList).replace(/\n/g, '\n\t');
            result += '\n';
        });
        return result;
    }
Behavior3/5

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

No annotations provided, so description carries full burden. It discloses the limitation of returning only the first ten results, but does not mention other behavioral traits like error handling, performance, or rate limits.

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?

Two sentences, no waste, front-loaded with purpose. Efficient and clear.

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

Completeness2/5

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

Despite having 12 parameters and no output schema, the description is too brief. It does not explain return structure, error states, or any post-processing steps.

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 description adds minimal extra meaning beyond the schema. The statement about only supporting top ten conflates with limitedNum parameter but does not provide new insight into parameter usage.

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?

Clearly states it queries 12306 transfer ticket information, and distinguishes itself from sibling tools like get-tickets by specifying 'interline' (中转). The limitation of top 10 results is also mentioned.

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

Usage Guidelines3/5

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

The description implies when to use (for transfer tickets) but does not explicitly mention when not to use or alternatives. The sibling tool get-tickets suggests direct tickets, but no direct comparison is made.

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