Skip to main content
Glama
Xxx00xxX33

FinanceMCP

by Xxx00xxX33

money_flow

Analyze capital flow data for stocks, markets, and sectors to track fund movements by investor type and size.

Instructions

获取个股、大盘和板块资金流向数据,包括主力资金、超大单、大单、中单、小单的净流入净额和净占比数据

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
query_typeNo查询类型:stock=个股,market=大盘,sector=板块。默认根据ts_code自动判断
ts_codeNo股票代码或板块代码。个股如'000001.SZ',板块如'BK0447'(东财板块代码)。不填写则查询大盘资金流向
start_dateYes起始日期,格式为YYYYMMDD,如'20240901'
end_dateYes结束日期,格式为YYYYMMDD,如'20240930'
content_typeNo板块资金类型,仅在查询板块时有效。可选:行业、概念、地域
trade_dateNo单独查询某个交易日的数据,格式为YYYYMMDD。如填写则忽略start_date和end_date

Implementation Reference

  • Core handler function that executes the money_flow tool. Parses arguments, determines query type (stock/market/sector), fetches data from Tushare API using specialized functions, processes and formats the data into a markdown report with statistics, tables, and trends.
    async run(args: { 
      query_type?: string;
      ts_code?: string; 
      start_date: string; 
      end_date: string;
      content_type?: string;
      trade_date?: string;
    }) {
      try {
        console.log('资金流向数据查询参数:', args);
        
        const TUSHARE_API_KEY = TUSHARE_CONFIG.API_TOKEN;
        const TUSHARE_API_URL = TUSHARE_CONFIG.API_URL;
        
        if (!TUSHARE_API_KEY) {
          throw new Error('请配置TUSHARE_TOKEN环境变量');
        }
    
        // 判断查询类型
        let queryType = args.query_type;
        if (!queryType) {
          // 自动判断:没有ts_code=大盘,有BK开头=板块,否则=个股
          if (!args.ts_code || args.ts_code.trim() === '') {
            queryType = 'market';
          } else if (args.ts_code.startsWith('BK')) {
            queryType = 'sector';
          } else {
            queryType = 'stock';
          }
        }
        
        let result;
        let targetName = '';
        
        if (queryType === 'market') {
          // 查询大盘资金流向
          targetName = '大盘';
          result = await fetchMarketMoneyFlow(
            args.trade_date || args.start_date,
            args.trade_date || args.end_date,
            TUSHARE_API_KEY,
            TUSHARE_API_URL
          );
        } else if (queryType === 'sector') {
          // 查询板块资金流向
          targetName = `板块${args.ts_code || ''}`;
          result = await fetchSectorMoneyFlow(
            args.ts_code,
            args.trade_date,
            args.start_date,
            args.end_date,
            args.content_type,
            TUSHARE_API_KEY,
            TUSHARE_API_URL
          );
        } else {
          // 查询个股资金流向
          targetName = `股票${args.ts_code}`;
          result = await fetchStockMoneyFlow(
            args.ts_code!,
            args.trade_date || args.start_date,
            args.trade_date || args.end_date,
            TUSHARE_API_KEY,
            TUSHARE_API_URL
          );
        }
    
        if (!result.data || result.data.length === 0) {
          throw new Error(`未找到${targetName}在指定时间范围内的资金流向数据`);
        }
    
        // 格式化输出
        const formattedOutput = formatMoneyFlowData(
          result.data, 
          result.fields, 
          queryType, 
          args.ts_code
        );
        
        return {
          content: [{ type: "text", text: formattedOutput }]
        };
    
      } catch (error) {
        console.error('资金流向数据查询错误:', error);
        return {
          content: [{ 
            type: "text", 
            text: `查询资金流向数据时发生错误: ${error instanceof Error ? error.message : '未知错误'}` 
          }]
        };
      }
    }
  • JSON Schema defining the input parameters for the money_flow tool, including query_type, ts_code, date ranges, etc.
    parameters: {
      type: "object",
      properties: {
        query_type: {
          type: "string",
          description: "查询类型:stock=个股,market=大盘,sector=板块。默认根据ts_code自动判断"
        },
        ts_code: {
          type: "string",
          description: "股票代码或板块代码。个股如'000001.SZ',板块如'BK0447'(东财板块代码)。不填写则查询大盘资金流向"
        },
        start_date: {
          type: "string",
          description: "起始日期,格式为YYYYMMDD,如'20240901'"
        },
        end_date: {
          type: "string",
          description: "结束日期,格式为YYYYMMDD,如'20240930'"
        },
        content_type: {
          type: "string",
          description: "板块资金类型,仅在查询板块时有效。可选:行业、概念、地域"
        },
        trade_date: {
          type: "string",
          description: "单独查询某个交易日的数据,格式为YYYYMMDD。如填写则忽略start_date和end_date"
        }
      },
      required: ["start_date", "end_date"]
    },
  • src/index.ts:225-227 (registration)
    Tool registration in the MCP server's ListToolsRequestSchema handler, adding money_flow to the list of available tools.
    name: moneyFlow.name,
    description: moneyFlow.description,
    inputSchema: moneyFlow.parameters
  • src/index.ts:350-357 (registration)
    Dispatch logic in the MCP server's CallToolRequestSchema handler, parsing arguments and invoking the moneyFlow.run method.
    case "money_flow": {
      const query_type = request.params.arguments?.query_type ? String(request.params.arguments.query_type) : undefined;
      const ts_code = request.params.arguments?.ts_code ? String(request.params.arguments.ts_code) : undefined;
      const start_date = String(request.params.arguments?.start_date);
      const end_date = String(request.params.arguments?.end_date);
      const content_type = request.params.arguments?.content_type ? String(request.params.arguments.content_type) : undefined;
      const trade_date = request.params.arguments?.trade_date ? String(request.params.arguments.trade_date) : undefined;
      return normalizeResult(await moneyFlow.run({ query_type, ts_code, start_date, end_date, content_type, trade_date }));
  • Helper utility that makes authenticated POST requests to Tushare Pro API, handles timeouts, converts response data from arrays to keyed objects, and includes logging.
    async function callTushareAPI(params: any, apiUrl: string) {
      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(apiUrl, {
          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}`);
        }
        
        if (!data.data || !data.data.items) {
          throw new Error(`未找到资金流向数据`);
        }
        
        // 获取字段名
        const fields = data.data.fields;
        
        // 将数据转换为对象数组
        const convertedData = data.data.items.map((item: any) => {
          const result: Record<string, any> = {};
          fields.forEach((field: string, index: number) => {
            result[field] = item[index];
          });
          return result;
        });
        
        console.log(`成功获取到${convertedData.length}条资金流向数据记录`);
        
        return {
          data: convertedData,
          fields: fields
        };
        
      } finally {
        clearTimeout(timeoutId);
      }
    }
Behavior2/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 mentions the types of data retrieved but lacks critical behavioral details: it doesn't specify if this is a read-only operation (implied by '获取' but not explicit), any rate limits, authentication requirements, or how the data is returned (e.g., format, pagination). For a tool with 6 parameters and no annotations, this is a significant gap in transparency.

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

Conciseness4/5

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

The description is a single, efficient sentence in Chinese that front-loads the core purpose and lists key data points without unnecessary details. It could be slightly more structured by separating use cases, but it avoids redundancy and wastes no words, making it appropriately concise for the tool's complexity.

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 tool's complexity (6 parameters, no annotations, no output schema), the description is incomplete. It lacks information on behavioral traits (e.g., read-only status, error handling), output format, and practical usage guidelines. Without annotations or an output schema, the description should provide more context to help an agent invoke the tool correctly, but it falls short, leaving gaps in understanding how the tool behaves and what it returns.

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?

The schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema—it doesn't explain parameter interactions, default behaviors (e.g., automatic judgment based on ts_code), or usage examples. Given the high schema coverage, a baseline score of 3 is appropriate as the description doesn't compensate but also doesn't detract.

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 action ('获取' meaning 'get' or 'retrieve') and specifies the exact resource: '资金流向数据' (money flow data) for stocks, markets, and sectors. It distinguishes itself from siblings by focusing on money flow metrics like net inflow amounts and percentages across different order sizes (main force, ultra-large, large, medium, small), which is not covered by other tools like stock_data or index_data.

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 usage by listing the data types (stocks, markets, sectors) and metrics, but does not explicitly state when to use this tool versus alternatives. For example, it doesn't compare to stock_data (which might provide general stock info) or specify scenarios where money flow data is preferred over other financial metrics. This leaves some ambiguity in 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/Xxx00xxX33/FinanceMCP'

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