Skip to main content
Glama
guangxiangdebizi

FinanceMCP

margin_trade

Access margin trading data including target stocks, trade summaries, details, and securities lending information. Retrieve specific data by stock code, date range, or exchange for financial analysis.

Instructions

获取融资融券相关数据,支持多种数据类型:标的股票、交易汇总、交易明细、转融券汇总等

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
data_typeYes数据类型,可选值:margin_secs(融资融券标的股票)、margin(融资融券交易汇总)、margin_detail(融资融券交易明细)、slb_len_mm(做市借券交易汇总)
end_dateNo结束日期,格式YYYYMMDD,如'20240131'(可选,默认为当前日期)
exchangeNo交易所代码,可选值:SSE(上海证券交易所)、SZSE(深圳证券交易所)、BSE(北京证券交易所),仅margin_secs接口使用
start_dateYes起始日期,格式YYYYMMDD,如'20240101'
ts_codeNo股票代码,如'000001.SZ'、'600000.SH'等(部分接口可选)

Implementation Reference

  • The async run method that implements the core handler logic for the 'margin_trade' tool. It validates inputs, calls appropriate Tushare API fetch functions based on data_type, formats the response, and handles errors.
    async run(args: { 
      data_type: string;
      ts_code?: string;
      start_date: string;
      end_date?: string;
      exchange?: 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 data;
        let formattedOutput;
    
        switch (args.data_type) {
          case 'margin_secs':
            // 融资融券标的(盘前更新)
            data = await fetchMarginSecs(args, TUSHARE_API_KEY, TUSHARE_API_URL);
            formattedOutput = formatMarginSecs(data, args);
            break;
            
          case 'margin':
            // 融资融券交易汇总
            if (!args.ts_code) {
              throw new Error('融资融券交易汇总查询需要提供股票代码(ts_code)');
            }
            data = await fetchMarginSummary(args, TUSHARE_API_KEY, TUSHARE_API_URL);
            formattedOutput = formatMarginSummary(data, args);
            break;
            
          case 'margin_detail':
            // 融资融券交易明细
            if (!args.ts_code) {
              throw new Error('融资融券交易明细查询需要提供股票代码(ts_code)');
            }
            data = await fetchMarginDetail(args, TUSHARE_API_KEY, TUSHARE_API_URL);
            formattedOutput = formatMarginDetail(data, args);
            break;
            
          case 'slb_len_mm':
            // 做市借券交易汇总
            data = await fetchSlbLenMm(args, TUSHARE_API_KEY, TUSHARE_API_URL);
            formattedOutput = formatSlbLenMm(data, args);
            break;
            
          default:
            throw new Error(`不支持的数据类型: ${args.data_type}`);
        }
    
        if (!data || data.length === 0) {
          throw new Error(`未找到相关融资融券数据`);
        }
        
        return {
          content: [{ type: "text", text: formattedOutput }]
        };
    
      } catch (error) {
        console.error('融资融券数据查询错误:', error);
        return {
          content: [{ 
            type: "text", 
            text: `查询融资融券数据时发生错误: ${error instanceof Error ? error.message : '未知错误'}` 
          }]
        };
      }
    }
  • The input schema (parameters) defining the expected arguments for the margin_trade tool, including data_type, ts_code, dates, and exchange.
    parameters: {
      type: "object",
      properties: {
        data_type: {
          type: "string",
          description: "数据类型,可选值:margin_secs(融资融券标的股票)、margin(融资融券交易汇总)、margin_detail(融资融券交易明细)、slb_len_mm(做市借券交易汇总)"
        },
        ts_code: {
          type: "string",
          description: "股票代码,如'000001.SZ'、'600000.SH'等(部分接口可选)"
        },
        start_date: {
          type: "string",
          description: "起始日期,格式YYYYMMDD,如'20240101'"
        },
        end_date: {
          type: "string",
          description: "结束日期,格式YYYYMMDD,如'20240131'(可选,默认为当前日期)"
        },
        exchange: {
          type: "string",
          description: "交易所代码,可选值:SSE(上海证券交易所)、SZSE(深圳证券交易所)、BSE(北京证券交易所),仅margin_secs接口使用"
        }
      },
      required: ["data_type", "start_date"]
  • src/index.ts:319-325 (registration)
    Tool dispatch/registration in the stdio MCP server's CallToolRequestHandler switch statement, extracting args and calling marginTrade.run().
    case "margin_trade": {
      const data_type = String(request.params.arguments?.data_type);
      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 = request.params.arguments?.end_date ? String(request.params.arguments.end_date) : undefined;
      const exchange = request.params.arguments?.exchange ? String(request.params.arguments.exchange) : undefined;
      return await marginTrade.run({ data_type, ts_code, start_date, end_date, exchange });
  • Tool dispatch/registration in the HTTP MCP server's tools/call handler switch statement, extracting args and calling marginTrade.run().
    case 'margin_trade':
      return await marginTrade.run({
        data_type: String(args?.data_type),
        ts_code: args?.ts_code ? String(args.ts_code) : undefined,
        start_date: String(args?.start_date),
        end_date: args?.end_date ? String(args.end_date) : undefined,
        exchange: args?.exchange ? String(args.exchange) : undefined,
      });
  • Helper function callTushareAPI used by all fetch functions in margin_trade to make authenticated POST requests to Tushare API, parse responses, and handle timeouts/errors.
    async function callTushareAPI(params: any, apiUrl: string, apiName: string) {
      console.log(`请求${apiName}数据,参数:`, params.params);
    
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), TUSHARE_CONFIG.TIMEOUT);
    
      try {
        const response = await fetch(apiUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(params),
          signal: controller.signal
        });
    
        clearTimeout(timeoutId);
    
        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 || data.data.items.length === 0) {
          return [];
        }
    
        const fieldsArray = data.data.fields;
        const resultData = data.data.items.map((item: any) => {
          const result: Record<string, any> = {};
          fieldsArray.forEach((field: string, index: number) => {
            result[field] = item[index];
          });
          return result;
        });
    
        console.log(`成功获取到${resultData.length}条${apiName}数据记录`);
        return resultData;
    
      } catch (error) {
        clearTimeout(timeoutId);
        throw error;
      }
    }
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 '获取' (gets/retrieves) data, implying a read-only operation, but doesn't clarify if it's real-time or historical, requires authentication, has rate limits, or returns paginated results. For a data retrieval tool with 5 parameters and no annotation coverage, 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 that front-loads the core purpose ('获取融资融券相关数据') and enumerates data types. There's no wasted text, but it could be slightly more structured (e.g., bullet points for data types). It earns its place by clarifying scope, though it lacks depth in usage or behavior.

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 (5 parameters, no annotations, no output schema), the description is incomplete. It doesn't explain return values, error conditions, or data freshness. While the schema covers parameters well, the description fails to compensate for missing behavioral context, making it inadequate for a multi-parameter data retrieval tool without structured support.

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 parameters thoroughly (e.g., data_type options, date formats, exchange codes). The description adds minimal value by listing data types in Chinese, but doesn't explain parameter interactions (e.g., ts_code is optional for some data_types) or provide examples beyond what's in the schema. Baseline 3 is appropriate when 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 margin trading related data) and lists specific data types like margin_secs, margin, margin_detail, and slb_len_mm. It distinguishes itself from siblings by focusing on margin trading data, unlike tools for stock_data, index_data, or macro_econ. However, it doesn't explicitly differentiate from all siblings (e.g., money_flow could overlap in financial data).

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 lists data types but doesn't explain which to choose for specific scenarios (e.g., margin_secs for eligible stocks vs. margin for summary data). No exclusions, prerequisites, or comparisons to sibling tools are mentioned, leaving the agent to infer usage from parameter descriptions 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