Skip to main content
Glama
sleepysoong

Stock Price MCP Server

by sleepysoong

get_stock_price

Retrieve real-time stock price data including current price, market state, timestamp, and currency for any ticker symbol.

Instructions

Get real-time stock price information for a given ticker symbol. Returns last price, timestamp, market state (PRE/REGULAR/AFTER/POST/CLOSED), and currency.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tickerYesStock ticker symbol (e.g., AAPL, TSLA, 005930.KS)

Implementation Reference

  • MCP CallTool handler for 'get_stock_price': validates ticker argument, calls StockAPIClient.getStockPrice(), returns JSON result or error response.
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name !== 'get_stock_price') {
        throw new Error(`Unknown tool: ${request.params.name}`);
      }
    
      const ticker = request.params.arguments?.ticker;
      if (!ticker || typeof ticker !== 'string') {
        throw new Error('Ticker parameter is required and must be a string');
      }
    
      try {
        const stockData = await stockClient.getStockPrice(ticker);
        
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(stockData, null, 2),
            },
          ],
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                error: errorMessage,
                ticker: ticker,
              }, null, 2),
            },
          ],
          isError: true,
        };
      }
    });
  • src/index.ts:26-45 (registration)
    Registers the 'get_stock_price' tool in ListToolsRequestSchema handler with name, description, and input schema.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'get_stock_price',
            description: 'Get real-time stock price information for a given ticker symbol. Returns last price, timestamp, market state (PRE/REGULAR/AFTER/POST/CLOSED), and currency.',
            inputSchema: {
              type: 'object',
              properties: {
                ticker: {
                  type: 'string',
                  description: 'Stock ticker symbol (e.g., AAPL, TSLA, 005930.KS)',
                },
              },
              required: ['ticker'],
            },
          },
        ],
      };
    });
  • Input schema definition for the 'get_stock_price' tool requiring a 'ticker' string.
    inputSchema: {
      type: 'object',
      properties: {
        ticker: {
          type: 'string',
          description: 'Stock ticker symbol (e.g., AAPL, TSLA, 005930.KS)',
        },
      },
      required: ['ticker'],
    },
  • Core implementation of getStockPrice in StockAPIClient: fetches real-time stock data from Yahoo Finance API with retry logic, normalizes market state, returns StockPriceResponse.
    async getStockPrice(ticker: string): Promise<StockPriceResponse> {
      if (!ticker || ticker.trim() === '') {
        throw new Error('Ticker symbol is required');
      }
    
      const normalizedTicker = ticker.trim().toUpperCase();
      let lastError: Error | null = null;
    
      for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
        try {
          const url = `${this.baseUrl}/${normalizedTicker}`;
          const response = await fetch(url, {
            headers: {
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
          });
    
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
    
          const data = await response.json() as YahooFinanceChart;
    
          if (data.chart.error) {
            throw new Error(`Yahoo Finance API error: ${data.chart.error.description}`);
          }
    
          if (!data.chart.result || data.chart.result.length === 0) {
            throw new Error(`Invalid ticker symbol: ${normalizedTicker}`);
          }
    
          const result = data.chart.result[0];
          const meta = result.meta;
    
          return {
            ticker: meta.symbol,
            last_price: meta.regularMarketPrice,
            timestamp: new Date(meta.regularMarketTime * 1000).toISOString(),
            market_state: this.normalizeMarketState(meta.marketState),
            currency: meta.currency
          };
    
        } catch (error) {
          lastError = error as Error;
          
          if (attempt < this.maxRetries) {
            await this.sleep(this.retryDelay * attempt);
            continue;
          }
        }
      }
    
      throw new Error(`Failed to fetch stock price after ${this.maxRetries} attempts: ${lastError?.message}`);
    }
  • Type definition for StockPriceResponse returned by getStockPrice.
    export interface StockPriceResponse {
      ticker: string;
      last_price: number;
      timestamp: string;
      market_state: MarketState;
      currency: string;
    }
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/sleepysoong/stock-price-mcp'

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