Skip to main content
Glama
qqzhangyanhua

MCP Stock Assistant

get-stock-info

Retrieve real-time stock data including current price, percentage changes, and trading volume for Chinese A-shares and US stocks by entering a stock code or name.

Instructions

获取单个股票的实时当前信息,包括当前价格、涨跌幅、成交量等实时数据

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
stock_codeYes股票代码或名称 (例如: 600519 或 贵州茅台)

Implementation Reference

  • src/index.ts:16-47 (registration)
    Registration of the 'get-stock-info' tool using McpServer.tool(), including description, input schema, and inline handler function.
    server.tool(
      "get-stock-info",
      "获取单个股票的实时当前信息,包括当前价格、涨跌幅、成交量等实时数据",
      {
        stock_code: z
          .string()
          .describe("股票代码或名称 (例如: 600519 或 贵州茅台)"),
      },
      async ({ stock_code }) => {
        const stockData = await fetchStockData(stock_code);
    
        if (!stockData) {
          return {
            content: [
              {
                type: "text",
                text: `无法获取股票 ${stock_code} 的数据。请检查输入是否正确。`,
              },
            ],
          };
        }
    
        return {
          content: [
            {
              type: "text",
              text: formatStockInfo(stockData),
            },
          ],
        };
      }
    );
  • Inline handler function for the tool that calls fetchStockData, handles errors, and returns formatted text content.
    async ({ stock_code }) => {
      const stockData = await fetchStockData(stock_code);
    
      if (!stockData) {
        return {
          content: [
            {
              type: "text",
              text: `无法获取股票 ${stock_code} 的数据。请检查输入是否正确。`,
            },
          ],
        };
      }
    
      return {
        content: [
          {
            type: "text",
            text: formatStockInfo(stockData),
          },
        ],
      };
    }
  • Zod input schema defining the 'stock_code' parameter as a string with description.
    {
      stock_code: z
        .string()
        .describe("股票代码或名称 (例如: 600519 或 贵州茅台)"),
    },
  • Core helper function fetchStockData that resolves stock code, makes API request to quote endpoint, parses response, constructs buy/sell orders, and returns structured StockData.
    export async function fetchStockData(stockInput: string): Promise<StockData | null> {
      try {
        let stockCode = stockInput;
        let stockName = "";
    
        if (!stockInput.match(/^\d{6}$/)) {
          const searchResult = await searchStock(stockInput);
          if (!searchResult) {
            console.error(`未找到股票:${stockInput}`);
            return null;
          }
          [stockCode, stockName] = searchResult;
          console.error(`找到股票:${stockName}(${stockCode})`);
        }
    
        const [market, fullCode] = getStockMarket(stockCode);
    
        const params = {
          secid: fullCode,
          fields:
            "f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f206,f207,f208,f209,f210,f211,f212,f213,f214,f215,f86,f107,f111,f86,f177,f78,f110",
        };
    
        const response = await makeRequest(QUOTE_API, params);
        const data = (await response.json()) as QuoteResponse;
    
        if (data.rc !== 0 || !data.data) {
          throw new Error(data.msg || "获取数据失败");
        }
    
        const quote = data.data;
    
        const buyOrders = [];
        const sellOrders = [];
    
        for (let i = 1; i <= 5; i++) {
          const buyPrice = quote[`f${18 + i * 2}`];
          const buyVolume = quote[`f${17 + i * 2}`];
          const sellPrice = quote[`f${10 + i * 2}`];
          const sellVolume = quote[`f${9 + i * 2}`];
    
          if (typeof buyPrice === "number" && typeof buyVolume === "number") {
            buyOrders.push({
              price: buyPrice / 100,
              volume: buyVolume / 100,
            });
          }
    
          if (typeof sellPrice === "number" && typeof sellVolume === "number") {
            sellOrders.push({
              price: sellPrice / 100,
              volume: sellVolume / 100,
            });
          }
        }
    
        return {
          code: stockCode,
          name: quote.f58,
          price: quote.f43 / 100,
          change: quote.f169 / 100,
          changePercent: quote.f170 / 100,
          volume: quote.f47 / 100,
          amount: quote.f48 / 10000,
          high: quote.f44 / 100,
          low: quote.f45 / 100,
          open: quote.f46 / 100,
          lastClose: quote.f60 / 100,
          turnoverRate: quote.f168 / 100,
          peRatio: quote.f162,
          amplitude: quote.f171 ? quote.f171 / 100 : 0,
          time: new Date().toLocaleTimeString(),
          buyOrders,
          sellOrders,
        };
      } catch (error) {
        console.error("Error fetching stock data:", error);
        return null;
      }
    }
  • Helper function formatStockInfo that converts StockData object into a formatted multi-line text string for display, including prices, changes, volume, and order book.
    export function formatStockInfo(data: StockData): string {
      let result = `
    股票信息: ${data.code} (${data.name})
    
    当前价格: ${formatPrice(data.price)}
    ${
      data.change >= 0
        ? `涨幅: +${data.changePercent}%`
        : `跌幅: ${data.changePercent}%`
    }
    涨跌额: ${data.change > 0 ? "+" : ""}${formatPrice(data.change)}
    开盘价: ${formatPrice(data.open)}
    最高价: ${formatPrice(data.high)}
    最低价: ${formatPrice(data.low)}
    昨收价: ${formatPrice(data.lastClose)}
    成交量: ${formatVolume(data.volume)}手
    成交额: ${formatVolume(data.amount)}万
    换手率: ${data.turnoverRate}%
    市盈率(动态): ${data.peRatio}
    振幅: ${data.amplitude}%
    更新时间: ${data.time}
    
    买卖盘口:
    `;
    
      for (let i = 4; i >= 0; i--) {
        const order = data.sellOrders[i];
        result += `卖${i + 1}: ${formatPrice(order.price)} / ${formatVolume(
          order.volume
        )}手\n`;
      }
    
      for (let i = 0; i < 5; i++) {
        const order = data.buyOrders[i];
        result += `买${i + 1}: ${formatPrice(order.price)} / ${formatVolume(
          order.volume
        )}手\n`;
      }
    
      return result;
    }
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 provides '实时当前信息' (real-time current information), which implies it's a read-only operation with fresh data, but it doesn't disclose critical traits like rate limits, authentication needs, data freshness guarantees, error handling, or whether it's a safe operation. For a tool with zero annotation coverage, this leaves significant gaps in behavioral understanding.

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 front-loads the core purpose ('获取单个股票的实时当前信息') and lists key data points without unnecessary elaboration. Every word earns its place, making it highly concise and well-structured for quick comprehension.

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?

Given the tool's low complexity (one parameter, no nested objects) and lack of annotations or output schema, the description is minimally adequate. It covers the basic purpose and data scope, but it doesn't address behavioral aspects (e.g., safety, performance) or provide usage guidance relative to siblings. For a simple read tool, this is borderline viable, but it could be more complete by adding context on limitations or alternatives.

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% (the single parameter 'stock_code' is fully documented in the schema with a clear description and examples). The description adds no additional meaning about parameters beyond what the schema provides—it doesn't explain parameter semantics, constraints, or usage nuances. With high schema coverage, the 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.

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 real-time current information for a single stock). It specifies the verb (获取/get) and resource (股票/stock), and lists key data points like price, change percentage, and volume. However, it doesn't explicitly distinguish this tool from its sibling 'get-stock-history' (which likely provides historical data), so it doesn't fully achieve sibling differentiation.

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 the sibling tools 'get-market-index' (for market indices) or 'get-stock-history' (for historical data), nor does it specify any prerequisites, exclusions, or contextual cues for selection. Usage is implied by the description's focus on '实时当前信息' (real-time current information), but this is insufficient for explicit guidance.

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/qqzhangyanhua/mcp-stock'

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