Skip to main content
Glama
guangxiangdebizi

FinanceMCP

index_data

Retrieve historical data for specific stock indices, such as the Shanghai or Shenzhen Index, using the MCP protocol. Input index code and date range to access financial data.

Instructions

获取指定股票指数的数据,例如上证指数、深证成指等

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes指数代码,如'000001.SH'表示上证指数,'399001.SZ'表示深证成指
end_dateYes结束日期,格式为YYYYMMDD,如'20230131'
start_dateYes起始日期,格式为YYYYMMDD,如'20230101'

Implementation Reference

  • Full implementation of the 'index_data' tool including name, description, input schema, and the async run handler that fetches index data from Tushare API, processes it, analyzes trend, and formats output.
    export const indexData = {
        name: "index_data",
        description: "获取指定股票指数的数据,例如上证指数、深证成指等",
        parameters: {
            type: "object",
            properties: {
                code: {
                    type: "string",
                    description: "指数代码,如'000001.SH'表示上证指数,'399001.SZ'表示深证成指"
                },
                start_date: {
                    type: "string",
                    description: "起始日期,格式为YYYYMMDD,如'20230101'"
                },
                end_date: {
                    type: "string",
                    description: "结束日期,格式为YYYYMMDD,如'20230131'"
                }
            },
            required: ["code", "start_date", "end_date"]
        },
        async run(args) {
            try {
                console.log(`使用Tushare API获取指数${args.code}的数据`);
                // 使用全局配置中的Tushare API设置
                const TUSHARE_API_KEY = TUSHARE_CONFIG.API_TOKEN;
                const TUSHARE_API_URL = TUSHARE_CONFIG.API_URL;
                // 默认参数设置
                const today = new Date();
                const defaultEndDate = today.toISOString().slice(0, 10).replace(/-/g, '');
                const oneMonthAgo = new Date();
                oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
                const defaultStartDate = oneMonthAgo.toISOString().slice(0, 10).replace(/-/g, '');
                // 构建请求参数
                const params = {
                    api_name: "index_daily",
                    token: TUSHARE_API_KEY,
                    params: {
                        ts_code: args.code,
                        start_date: args.start_date || defaultStartDate,
                        end_date: args.end_date || defaultEndDate
                    },
                    fields: "ts_code,trade_date,open,high,low,close,pre_close,change,pct_chg,vol,amount"
                };
                // 设置请求超时
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), TUSHARE_CONFIG.TIMEOUT);
                try {
                    console.log(`请求Tushare API: ${params.api_name},参数:`, params.params);
                    // 发送请求
                    const response = await fetch(TUSHARE_API_URL, {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json"
                        },
                        body: JSON.stringify(params),
                        signal: controller.signal
                    });
                    if (!response.ok) {
                        throw new Error(`Tushare API请求失败: ${response.status}`);
                    }
                    const data = await response.json();
                    // 处理响应数据
                    if (data.code !== 0) {
                        throw new Error(`Tushare API错误: ${data.msg}`);
                    }
                    // 确保data.data和data.data.items存在
                    if (!data.data || !data.data.items || data.data.items.length === 0) {
                        throw new Error(`未找到指数${args.code}的数据`);
                    }
                    // 获取字段名
                    const fields = data.data.fields;
                    // 将数据转换为对象数组
                    const indexData = data.data.items.map((item) => {
                        const result = {};
                        fields.forEach((field, index) => {
                            result[field] = item[index];
                        });
                        return result;
                    });
                    // 收集涨跌数据用于生成趋势分析
                    const closePrices = indexData.map((item) => parseFloat(item.close));
                    let trend = "持平";
                    let trendAnalysis = "";
                    if (closePrices.length > 1) {
                        const firstPrice = closePrices[closePrices.length - 1]; // 最早的收盘价
                        const lastPrice = closePrices[0]; // 最近的收盘价
                        const change = ((lastPrice - firstPrice) / firstPrice * 100).toFixed(2);
                        if (lastPrice > firstPrice) {
                            trend = `上涨 ${change}%`;
                            trendAnalysis = `在此期间,${args.code}整体呈上涨趋势,累计涨幅达${change}%。`;
                        }
                        else if (lastPrice < firstPrice) {
                            trend = `下跌 ${Math.abs(parseFloat(change))}%`;
                            trendAnalysis = `在此期间,${args.code}整体呈下跌趋势,累计跌幅达${Math.abs(parseFloat(change))}%。`;
                        }
                    }
                    // 格式化输出日期范围
                    const startDate = indexData[indexData.length - 1]?.trade_date || args.start_date || defaultStartDate;
                    const endDate = indexData[0]?.trade_date || args.end_date || defaultEndDate;
                    // 格式化输出
                    const formattedData = indexData.map((data) => {
                        return `## ${data.trade_date}\n开盘: ${data.open}  最高: ${data.high}  最低: ${data.low}  收盘: ${data.close}\n涨跌: ${data.change}  涨跌幅: ${data.pct_chg}%  成交量: ${data.vol}  成交额: ${data.amount}\n`;
                    }).join('\n---\n\n');
                    return {
                        content: [
                            {
                                type: "text",
                                text: `# ${args.code}指数数据 (${startDate} 至 ${endDate})\n\n` +
                                    `## 期间走势: ${trend}\n${trendAnalysis}\n\n---\n\n${formattedData}`
                            }
                        ]
                    };
                }
                finally {
                    clearTimeout(timeoutId);
                }
            }
            catch (error) {
                console.error("获取指数数据失败:", error);
                return {
                    content: [
                        {
                            type: "text",
                            text: `# 获取指数${args.code}数据失败\n\n无法从Tushare API获取数据:${error instanceof Error ? error.message : String(error)}\n\n请检查指数代码是否正确,常用指数代码:\n- 上证指数: 000001.SH\n- 深证成指: 399001.SZ\n- 创业板指: 399006.SZ\n- 沪深300: 000300.SH\n- 中证500: 000905.SH`
                        }
                    ]
                };
            }
        }
    };
  • Input schema definition for the index_data tool specifying required parameters: code, start_date, end_date.
    parameters: {
        type: "object",
        properties: {
            code: {
                type: "string",
                description: "指数代码,如'000001.SH'表示上证指数,'399001.SZ'表示深证成指"
            },
            start_date: {
                type: "string",
                description: "起始日期,格式为YYYYMMDD,如'20230101'"
            },
            end_date: {
                type: "string",
                description: "结束日期,格式为YYYYMMDD,如'20230131'"
            }
        },
        required: ["code", "start_date", "end_date"]
    },
  • build/index.js:228-232 (registration)
    Registration and call handler for index_data tool in the MCP stdio server switch statement.
    case "index_data": {
        const code = String(request.params.arguments?.code);
        const start_date = request.params.arguments?.start_date ? String(request.params.arguments.start_date) : undefined;
        const end_date = request.params.arguments?.end_date ? String(request.params.arguments.end_date) : undefined;
        return await indexData.run({ code, start_date, end_date });
  • build/index.js:129-131 (registration)
    Tool listing registration in ListToolsRequestSchema handler for MCP stdio server.
    name: indexData.name,
    description: indexData.description,
    inputSchema: indexData.parameters
  • Tool call handler registration for index_data in the HTTP server MCP tools/call endpoint.
    case 'index_data':
        return await indexData.run({
            code: String(args?.code),
            start_date: args?.start_date ? String(args.start_date) : undefined,
            end_date: args?.end_date ? String(args.end_date) : undefined,
        });
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool retrieves data but doesn't describe what kind of data (e.g., historical prices, volumes), the format of the response, potential rate limits, authentication needs, or error conditions. For a data retrieval tool with zero annotation coverage, this is a significant gap.

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 a single, efficient sentence that directly states the tool's purpose with relevant examples. It's front-loaded with the core functionality and wastes no words. Every part of the sentence earns its place by clarifying the scope.

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?

Given the complexity of financial data retrieval, no annotations, and no output schema, the description is incomplete. It doesn't explain what data is returned (e.g., OHLC prices, volumes), the response format, or any behavioral aspects like pagination or errors. For a tool with three parameters and no structured output documentation, more context is needed.

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 (code, start_date, end_date) with clear descriptions and examples. The description adds no additional parameter semantics beyond what's in the schema, such as date range constraints or code validation rules. Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the tool's purpose: '获取指定股票指数的数据' (get data for specified stock indices). It specifies the resource (stock indices) and provides examples (上证指数, 深证成指). However, it doesn't explicitly distinguish this tool from sibling tools like 'stock_data' or 'fund_data', which might handle similar financial data but for different asset classes.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'stock_data' (for individual stocks) or 'fund_data' (for funds), nor does it specify prerequisites or exclusions. The agent must infer usage from the tool name and description alone.

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

Related 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/guangxiangdebizi/FinanceMCP'

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