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;
    }

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