Skip to main content
Glama
berlinbra

AlphaVantage-MCP

get-stock-quote

Retrieve current stock quote information by entering a stock symbol to access real-time financial market data through the Alpha Vantage API.

Instructions

Get current stock quote information

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesStock symbol (e.g., AAPL, MSFT)

Implementation Reference

  • Handler logic for executing the get-stock-quote tool: validates symbol input, fetches real-time quote data from Alpha Vantage GLOBAL_QUOTE endpoint using make_alpha_request helper, formats the response with format_quote, and returns formatted text content.
    if name == "get-stock-quote":
        symbol = arguments.get("symbol")
        if not symbol:
            return [types.TextContent(type="text", text="Missing symbol parameter")]
    
        symbol = symbol.upper()
    
        async with httpx.AsyncClient() as client:
            quote_data = await make_alpha_request(
                client,
                "GLOBAL_QUOTE",
                symbol
            )
    
            if isinstance(quote_data, str):
                return [types.TextContent(type="text", text=f"Error: {quote_data}")]
    
            formatted_quote = format_quote(quote_data)
            quote_text = f"Stock quote for {symbol}:\n\n{formatted_quote}"
    
            return [types.TextContent(type="text", text=quote_text)]
  • Registration of the get-stock-quote tool in the MCP server.list_tools() handler, including name, description, and JSON schema for input validation (requires 'symbol' string).
    types.Tool(
        name="get-stock-quote",
        description="Get current stock quote information",
        inputSchema={
            "type": "object",
            "properties": {
                "symbol": {
                    "type": "string",
                    "description": "Stock symbol (e.g., AAPL, MSFT)",
                },
            },
            "required": ["symbol"],
        },
    ),
  • JSON Schema definition for get-stock-quote tool input: object with required 'symbol' property (string).
    inputSchema={
        "type": "object",
        "properties": {
            "symbol": {
                "type": "string",
                "description": "Stock symbol (e.g., AAPL, MSFT)",
            },
        },
        "required": ["symbol"],
    },
  • Helper function to format the raw Global Quote API response into a human-readable string displaying price, change (absolute and percent), volume, high, and low.
    def format_quote(quote_data: Dict[str, Any]) -> str:
        """Format quote data into a concise string.
        
        Args:
            quote_data: The response data from the Alpha Vantage Global Quote endpoint
            
        Returns:
            A formatted string containing the quote information
        """
        try:
            global_quote = quote_data.get("Global Quote", {})
            if not global_quote:
                return "No quote data available in the response"
    
            return (
                f"Price: ${global_quote.get('05. price', 'N/A')}\n"
                f"Change: ${global_quote.get('09. change', 'N/A')} "
                f"({global_quote.get('10. change percent', 'N/A')})\n"
                f"Volume: {global_quote.get('06. volume', 'N/A')}\n"
                f"High: ${global_quote.get('03. high', 'N/A')}\n"
                f"Low: ${global_quote.get('04. low', 'N/A')}\n"
                "---"
            )
        except Exception as e:
            return f"Error formatting quote data: {str(e)}"
  • Core helper function that makes authenticated HTTP requests to the Alpha Vantage API. Used by get-stock-quote handler with function='GLOBAL_QUOTE' and the symbol. Handles JSON/CSV parsing, rate limits, timeouts, and API errors gracefully.
    async def make_alpha_request(client: httpx.AsyncClient, function: str, symbol: Optional[str], additional_params: Optional[Dict[str, Any]] = None) -> Dict[str, Any] | str:
        """Make a request to the Alpha Vantage API with proper error handling.
        
        Args:
            client: An httpx AsyncClient instance
            function: The Alpha Vantage API function to call
            symbol: The stock/crypto symbol (can be None for some endpoints)
            additional_params: Additional parameters to include in the request
            
        Returns:
            Either a dictionary containing the API response, or a string with an error message
        """
        params = {
            "function": function,
            "apikey": API_KEY
        }
        
        if symbol:
            params["symbol"] = symbol
            
        if additional_params:
            params.update(additional_params)
    
        try:
            response = await client.get(
                ALPHA_VANTAGE_BASE,
                params=params,
                timeout=30.0
            )
    
            # Check for specific error responses
            if response.status_code == 429:
                return f"Rate limit exceeded. Error details: {response.text}"
            elif response.status_code == 403:
                return f"API key invalid or expired. Error details: {response.text}"
    
            response.raise_for_status()
    
            # Check if response is empty
            if not response.text.strip():
                return "Empty response received from Alpha Vantage API"
            
            # Special handling for EARNINGS_CALENDAR which returns CSV by default
            if function == "EARNINGS_CALENDAR":
                try:
                    # Parse CSV response
                    csv_reader = csv.DictReader(io.StringIO(response.text))
                    earnings_list = list(csv_reader)
                    return earnings_list
                except Exception as e:
                    return f"Error parsing CSV response: {str(e)}"
            
            # For other functions, expect JSON
            try:
                data = response.json()
            except ValueError as e:
                return f"Invalid JSON response from Alpha Vantage API: {response.text[:200]}"
    
            # Check for Alpha Vantage specific error messages
            if "Error Message" in data:
                return f"Alpha Vantage API error: {data['Error Message']}"
            if "Note" in data and "API call frequency" in data["Note"]:
                return f"Rate limit warning: {data['Note']}"
    
            return data
        except httpx.TimeoutException:
            return "Request timed out after 30 seconds. The Alpha Vantage API may be experiencing delays."
        except httpx.ConnectError:
            return "Failed to connect to Alpha Vantage API. Please check your internet connection."
        except httpx.HTTPStatusError as e:
            return f"HTTP error occurred: {str(e)} - Response: {e.response.text}"
        except Exception as e:
            return f"Unexpected error occurred: {str(e)}"
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 what the tool does but doesn't reveal any behavioral traits such as whether it's real-time or delayed, rate limits, authentication needs, error handling, or what format the quote information includes. This leaves significant gaps for an agent to understand how to use it effectively.

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 extremely concise with a single, clear sentence that front-loads the essential information ('Get current stock quote information'). There's no wasted words or unnecessary elaboration, making it efficient and easy to parse.

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

Completeness2/5

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

Given the lack of annotations and output schema, the description is incomplete for a tool that likely returns complex financial data. It doesn't specify what 'quote information' includes (e.g., price, volume, timestamp), nor does it address potential behavioral aspects like data freshness or error cases. For a tool in a financial context with many siblings, more context is needed.

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 input schema has 100% description coverage, with the single parameter 'symbol' clearly documented in the schema itself. The description doesn't add any additional meaning beyond what the schema provides, such as examples of valid symbols or constraints. Given the high schema coverage, the baseline score of 3 is appropriate.

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 with a specific verb ('Get') and resource ('current stock quote information'), making it immediately understandable. However, it doesn't explicitly differentiate from siblings like 'get-company-info' or 'get-time-series' which might also provide stock-related data, so it doesn't reach the highest score.

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. With siblings like 'get-company-info' and 'get-time-series' that could overlap, there's no indication of when this specific quote-fetching tool is appropriate versus other data retrieval tools in the set.

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/berlinbra/alpha-vantage-mcp'

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