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;
    }
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. It discloses the return data (price, timestamp, market state, currency) but does not mention behavioral traits like rate limits, error handling, data freshness, or authentication needs. This is a significant gap for a tool with no annotation coverage.

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 appropriately sized and front-loaded, with two concise sentences that efficiently convey the tool's purpose and return values without any wasted words. Every sentence earns its place.

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 (1 parameter, no output schema, no annotations), the description is complete enough for basic use. However, it lacks details on behavioral aspects like rate limits or error handling, which are important for a real-time data tool with no annotation coverage.

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 the single parameter ('ticker'). The description adds marginal value by specifying the resource ('stock price information') and implying the ticker's purpose, but does not provide additional syntax or format details beyond what the schema provides.

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 specific action ('Get real-time stock price information') and resource ('for a given ticker symbol'), with no siblings to differentiate from. It precisely explains what the tool does without being vague or tautological.

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 context (real-time stock price lookup) but does not explicitly state when to use this tool versus alternatives, nor does it provide exclusions or prerequisites. With no sibling tools, this is adequate but lacks 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/sleepysoong/stock-price-mcp'

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