Skip to main content
Glama
berlinbra

AlphaVantage-MCP

get-crypto-monthly

Retrieve monthly cryptocurrency price data for analysis and tracking. Specify a cryptocurrency symbol and market currency to access historical time series information.

Instructions

Get monthly time series data for a cryptocurrency

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
symbolYesCryptocurrency symbol (e.g., BTC, ETH)
marketNoMarket currency (e.g., USD, EUR)USD

Implementation Reference

  • The handler logic for executing the 'get-crypto-monthly' tool. It validates input, makes an API request to Alpha Vantage's DIGITAL_CURRENCY_MONTHLY endpoint, formats the response using format_crypto_time_series, and returns the formatted monthly cryptocurrency time series data.
    elif name == "get-crypto-monthly":
        symbol = arguments.get("symbol")
        market = arguments.get("market", "USD")
        
        if not symbol:
            return [types.TextContent(type="text", text="Missing symbol parameter")]
    
        symbol = symbol.upper()
        market = market.upper()
    
        async with httpx.AsyncClient() as client:
            crypto_data = await make_alpha_request(
                client,
                "DIGITAL_CURRENCY_MONTHLY",
                symbol,
                {"market": market}
            )
    
            if isinstance(crypto_data, str):
                return [types.TextContent(type="text", text=f"Error: {crypto_data}")]
    
            formatted_data = format_crypto_time_series(crypto_data, "monthly")
            data_text = f"Monthly cryptocurrency time series for {symbol} in {market}:\n\n{formatted_data}"
    
            return [types.TextContent(type="text", text=data_text)]
  • Registration of the 'get-crypto-monthly' tool in the list_tools() function, including its name, description, and input schema definition.
    types.Tool(
        name="get-crypto-monthly",
        description="Get monthly time series data for a cryptocurrency",
        inputSchema={
            "type": "object",
            "properties": {
                "symbol": {
                    "type": "string",
                    "description": "Cryptocurrency symbol (e.g., BTC, ETH)",
                },
                "market": {
                    "type": "string",
                    "description": "Market currency (e.g., USD, EUR)",
                    "default": "USD"
                }
            },
            "required": ["symbol"],
        },
    ),
  • JSON schema for input validation of the 'get-crypto-monthly' tool, requiring 'symbol' and optional 'market' parameters.
    inputSchema={
        "type": "object",
        "properties": {
            "symbol": {
                "type": "string",
                "description": "Cryptocurrency symbol (e.g., BTC, ETH)",
            },
            "market": {
                "type": "string",
                "description": "Market currency (e.g., USD, EUR)",
                "default": "USD"
            }
        },
        "required": ["symbol"],
    },
  • Helper function that formats the raw API response for cryptocurrency time series data, specifically selecting the 'Time Series (Digital Currency Monthly)' key for monthly data and formatting the most recent data points.
    def format_crypto_time_series(time_series_data: Dict[str, Any], series_type: str) -> str:
        """Format cryptocurrency time series data into a concise string.
        
        Args:
            time_series_data: The response data from Alpha Vantage Digital Currency endpoints
            series_type: Type of time series (daily, weekly, monthly)
            
        Returns:
            A formatted string containing the cryptocurrency time series information
        """
        try:
            # Determine the time series key based on series_type
            time_series_key = ""
            if series_type == "daily":
                time_series_key = "Time Series (Digital Currency Daily)"
            elif series_type == "weekly":
                time_series_key = "Time Series (Digital Currency Weekly)"
            elif series_type == "monthly":
                time_series_key = "Time Series (Digital Currency Monthly)"
            else:
                return f"Unknown series type: {series_type}"
                
            # Get the time series data
            time_series = time_series_data.get(time_series_key, {})
            if not time_series:
                all_keys = ", ".join(time_series_data.keys())
                return f"No cryptocurrency time series data found with key: '{time_series_key}'.\nAvailable keys: {all_keys}"
    
            # Get metadata
            metadata = time_series_data.get("Meta Data", {})
            crypto_symbol = metadata.get("2. Digital Currency Code", "Unknown")
            crypto_name = metadata.get("3. Digital Currency Name", "Unknown")
            market = metadata.get("4. Market Code", "Unknown")
            market_name = metadata.get("5. Market Name", "Unknown")
            last_refreshed = metadata.get("6. Last Refreshed", "Unknown")
            time_zone = metadata.get("7. Time Zone", "Unknown")
    
            # Format the header
            formatted_data = [
                f"{series_type.capitalize()} Time Series for {crypto_name} ({crypto_symbol})",
                f"Market: {market_name} ({market})",
                f"Last Refreshed: {last_refreshed} {time_zone}",
                ""
            ]
    
            # Format the most recent 5 data points
            for date, values in list(time_series.items())[:5]:
                # Get price information - based on the API response, we now know the correct field names
                open_price = values.get("1. open", "N/A")
                high_price = values.get("2. high", "N/A")
                low_price = values.get("3. low", "N/A")
                close_price = values.get("4. close", "N/A")
                volume = values.get("5. volume", "N/A")
                
                formatted_data.append(f"Date: {date}")
                formatted_data.append(f"Open: {open_price} {market}")
                formatted_data.append(f"High: {high_price} {market}")
                formatted_data.append(f"Low: {low_price} {market}")
                formatted_data.append(f"Close: {close_price} {market}")
                formatted_data.append(f"Volume: {volume}")
                formatted_data.append("---")
            
            return "\n".join(formatted_data)
        except Exception as e:
            return f"Error formatting cryptocurrency time series data: {str(e)}"
  • Utility function used by the handler to make the HTTP request to Alpha Vantage API, specifically called with function='DIGITAL_CURRENCY_MONTHLY', handling errors, rate limits, and parsing JSON/CSV responses.
    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 add context beyond that—missing details like rate limits, authentication needs, data freshness, error handling, or what 'monthly time series data' entails (e.g., format, date range). For a tool with zero annotation coverage, this is a significant gap in transparency.

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 a single, efficient sentence that front-loads the core purpose without unnecessary words. It's appropriately sized for a simple tool, with zero waste or redundancy, making it easy to parse quickly.

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 complexity (a data retrieval tool with no annotations and no output schema), the description is incomplete. It doesn't explain the return values, data format, or any behavioral traits, leaving gaps for an AI agent to understand how to interpret results. With 100% schema coverage but missing output details, it falls short of being fully helpful.

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 description adds no meaning beyond what the input schema provides. Schema description coverage is 100%, with clear documentation for 'symbol' and 'market' parameters, so the baseline is 3. The description doesn't elaborate on parameter usage, constraints, or examples, but the schema adequately covers the semantics.

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 verb ('Get') and resource ('monthly time series data for a cryptocurrency'), making the purpose immediately understandable. It distinguishes from siblings like get-crypto-daily and get-crypto-weekly by specifying the monthly frequency. However, it doesn't explicitly differentiate from get-time-series, which might also handle cryptocurrency data, leaving minor ambiguity.

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. It doesn't mention siblings like get-crypto-daily or get-crypto-weekly for different frequencies, or get-crypto-exchange-rate for real-time data, nor does it specify prerequisites or exclusions. Usage is implied only by the tool name and description, lacking explicit context.

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