Skip to main content
Glama
qubaomingg

@qubaomingg/stock-mcp

get-stock-data

Retrieve historical stock price data for analysis by providing a stock symbol and specifying time intervals and data volume.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesStock symbol (e.g., IBM, AAPL)
intervalNoTime interval between data points (default: 5min)
outputsizeNoAmount of data to return (compact: latest 100 data points, full: up to 20 years of data)

Implementation Reference

  • The MCP tool handler function for 'get-stock-data'. It receives input parameters, calls the getStockData helper, formats the response as MCP content, and handles errors.
    async ({ symbol, interval = '5min', outputsize = 'compact' }) => {
      try {
        const data = await getStockData(symbol, interval, outputsize);
        return {
          content: [{ type: 'text', text: data }],
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Error fetching stock data: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
          isError: true,
        };
      }
    },
  • Zod schema for input validation of the 'get-stock-data' tool: symbol (string), interval (optional enum), outputsize (optional enum).
    {
      symbol: z.string().describe('Stock symbol (e.g., IBM, AAPL)'),
      interval: z
        .enum(['1min', '5min', '15min', '30min', '60min'])
        .optional()
        .describe('Time interval between data points (default: 5min)'),
      outputsize: z
        .enum(['compact', 'full'])
        .optional()
        .describe(
          'Amount of data to return (compact: latest 100 data points, full: up to 20 years of data)',
        ),
    },
  • src/index.ts:49-84 (registration)
    Registration of the 'get-stock-data' tool on the MCP server, including schema and handler function.
    server.tool(
      'get-stock-data',
      {
        symbol: z.string().describe('Stock symbol (e.g., IBM, AAPL)'),
        interval: z
          .enum(['1min', '5min', '15min', '30min', '60min'])
          .optional()
          .describe('Time interval between data points (default: 5min)'),
        outputsize: z
          .enum(['compact', 'full'])
          .optional()
          .describe(
            'Amount of data to return (compact: latest 100 data points, full: up to 20 years of data)',
          ),
      },
      async ({ symbol, interval = '5min', outputsize = 'compact' }) => {
        try {
          const data = await getStockData(symbol, interval, outputsize);
          return {
            content: [{ type: 'text', text: data }],
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `Error fetching stock data: ${
                  error instanceof Error ? error.message : String(error)
                }`,
              },
            ],
            isError: true,
          };
        }
      },
    );
  • Core helper function getStockData that fetches intraday or daily stock data from Alpha Vantage API using axios, handles daily vs intraday endpoints, extracts time series, and formats using formatTimeSeriesData.
    export async function getStockData(symbol: string | string[], interval: string | string[] | 'daily', outputsize: string = 'compact'): Promise<string> {
        try {
            // Ensure parameters are strings, not arrays
            const symbolStr = Array.isArray(symbol) ? symbol[0] : symbol;
            const intervalStr = Array.isArray(interval) ? interval[0] : interval;
            const outputsizeStr = Array.isArray(outputsize) ? outputsize[0] : outputsize;
    
            let url: string;
            let timeSeriesKey: string;
    
            if (intervalStr === 'daily') {
                // Use TIME_SERIES_DAILY endpoint
                url = `${BASE_URL}?function=TIME_SERIES_DAILY&symbol=${symbolStr}&outputsize=${outputsizeStr}&apikey=${API_KEY}`;
                timeSeriesKey = 'Time Series (Daily)';
            } else {
                // Use TIME_SERIES_INTRADAY endpoint
                url = `${BASE_URL}?function=TIME_SERIES_INTRADAY&symbol=${symbolStr}&interval=${intervalStr}&outputsize=${outputsizeStr}&apikey=${API_KEY}`;
                timeSeriesKey = `Time Series (${intervalStr})`;
            }
    
            const response = await axios.get(url);
    
            // Check for error messages from Alpha Vantage
            if (response.data['Error Message']) {
                throw new Error(response.data['Error Message']);
            }
    
            if (response.data['Note']) {
                console.warn('API Usage Note:', response.data['Note']);
            }
    
            // Extract the time series data
            const timeSeries = response.data[timeSeriesKey];
    
            if (!timeSeries) {
                throw new Error('No time series data found in the response');
            }
    
            // Format the data
            const formattedData = formatTimeSeriesData(timeSeries, symbolStr, intervalStr);
            return formattedData;
        } catch (error) {
            if (axios.isAxiosError(error)) {
                throw new Error(`API request failed: ${error.message}`);
            }
            throw error;
        }
    }
  • Helper function to format the raw time series data from Alpha Vantage into a readable string, showing OHLCV for the most recent 10 data points.
    function formatTimeSeriesData(timeSeries: any, symbol: string, interval: string | 'daily'): string {
        const dates = Object.keys(timeSeries).sort().reverse(); // Most recent first
    
        let result = `Stock data for ${symbol.toUpperCase()} (${interval === 'daily' ? 'Daily' : interval} intervals):\n\n`;
    
        // Limit to 10 data points to avoid overwhelming responses
        const limitedDates = dates.slice(0, 10);
    
        for (const date of limitedDates) {
            const data = timeSeries[date];
            result += `${date}:\n`;
            result += `  Open: ${data['1. open']}\n`;
            result += `  High: ${data['2. high']}\n`;
            result += `  Low: ${data['3. low']}\n`;
            result += `  Close: ${data['4. close']}\n`;
            result += `  Volume: ${data['5. volume']}\n\n`;
        }
    
        if (dates.length > 10) {
            result += `... and ${dates.length - 10} more data points available.\n`;
        }
    
        return result;
    }
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

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

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