Skip to main content
Glama
cfocoder

Banxico MCP Server

get_usd_mxn_historical_data

Retrieve historical USD/MXN exchange rate data from the Bank of Mexico (Banxico) for analysis and tracking currency trends over time.

Instructions

Get historical USD/MXN exchange rate data from Banxico.

Args: limit: Maximum number of recent data points to return (default: 30)

Returns: Historical USD/MXN exchange rate data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function decorated with @mcp.tool(), which registers and implements the tool. Fetches historical USD/MXN exchange rates (series SF63528) from Banxico API, optionally limits to recent N points, and formats the output using helper functions.
    @mcp.tool()
    async def get_usd_mxn_historical_data(limit: Optional[int] = 30) -> str:
        """
        Get historical USD/MXN exchange rate data from Banxico.
        
        Args:
            limit: Maximum number of recent data points to return (default: 30)
            
        Returns:
            Historical USD/MXN exchange rate data
        """
        if not BANXICO_TOKEN:
            return "Error: BANXICO_API_TOKEN environment variable not set. Please configure your API token."
        
        endpoint = "series/SF63528/datos"
        data = await make_banxico_request(endpoint, BANXICO_TOKEN)
        
        if not data:
            return "Failed to retrieve historical exchange rate data. Please check your API token and network connection."
        
        # If limit is specified, truncate the data
        if limit and data.get("bmx", {}).get("series"):
            for series in data["bmx"]["series"]:
                if "datos" in series and len(series["datos"]) > limit:
                    # Keep the most recent data points
                    series["datos"] = series["datos"][-limit:]
        
        return format_exchange_rate_data(data)
  • Helper function to format the raw Banxico API response for exchange rate data into a human-readable string, handling multiple series and truncating long lists.
    def format_exchange_rate_data(data: dict[str, Any]) -> str:
        """
        Format exchange rate data into a readable string.
        
        Args:
            data: Raw JSON response from Banxico API
            
        Returns:
            Formatted string with exchange rate information
        """
        if not data or "bmx" not in data:
            return "No data available"
        
        series_list = data["bmx"].get("series", [])
        if not series_list:
            return "No series data found"
        
        result = []
        for series in series_list:
            series_title = series.get("titulo", "Unknown Series")
            series_id = series.get("idSerie", "Unknown ID")
            result.append(f"Series: {series_title} (ID: {series_id})")
            
            datos = series.get("datos", [])
            if not datos:
                result.append("  No data points available")
            else:
                result.append(f"  Total data points: {len(datos)}")
                # Show first few and last few data points
                if len(datos) <= 10:
                    for dato in datos:
                        fecha = dato.get("fecha", "Unknown date")
                        valor = dato.get("dato", "N/A")
                        result.append(f"  {fecha}: {valor}")
                else:
                    # Show first 5
                    for i, dato in enumerate(datos[:5]):
                        fecha = dato.get("fecha", "Unknown date")
                        valor = dato.get("dato", "N/A")
                        result.append(f"  {fecha}: {valor}")
                    
                    result.append(f"  ... ({len(datos) - 10} more data points) ...")
                    
                    # Show last 5
                    for dato in datos[-5:]:
                        fecha = dato.get("fecha", "Unknown date")
                        valor = dato.get("dato", "N/A")
                        result.append(f"  {fecha}: {valor}")
            
            result.append("")  # Empty line between series
        
        return "\n".join(result)
  • Helper function that makes authenticated async HTTP requests to the Banxico SIE API, handles errors, and returns parsed JSON or None.
    async def make_banxico_request(endpoint: str, token: str) -> dict[str, Any] | None:
        """
        Make a request to the Banxico SIE API with proper error handling.
        
        Args:
            endpoint: The API endpoint to call (without base URL)
            token: The Banxico API token
            
        Returns:
            JSON response data or None if request failed
        """
        url = f"{BANXICO_API_BASE}/{endpoint}"
        headers = {"User-Agent": USER_AGENT}
        params = {"token": token}
        
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(url, headers=headers, params=params, timeout=30.0)
                response.raise_for_status()
                return response.json()
        except httpx.HTTPError as e:
            logger.error(f"HTTP error occurred: {e}")
            return None
        except Exception as e:
            logger.error(f"An error occurred: {e}")
            return None
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 the tool fetches historical data but lacks details on rate limits, authentication needs, data freshness, error handling, or pagination. For a data-fetching 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.

Conciseness4/5

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

The description is well-structured and concise, with a clear purpose statement followed by brief Arg and Returns sections. Every sentence adds value, and there's no redundant information. It could be slightly more front-loaded by integrating the parameter explanation into the main description, but it's efficient overall.

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 moderate complexity (1 parameter, no annotations, but with an output schema), the description is minimally adequate. The output schema existence means return values needn't be explained, but the description lacks context on data format, time periods, or error cases. It meets basic requirements but leaves room for improvement in completeness.

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 minimal semantics for the 'limit' parameter, explaining it as 'Maximum number of recent data points to return (default: 30)'. With 0% schema description coverage, this partially compensates by clarifying the parameter's purpose and default. However, it doesn't detail constraints like valid ranges or what 'recent' means, leaving gaps in understanding.

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: 'Get historical USD/MXN exchange rate data from Banxico.' It specifies the verb ('Get'), resource ('historical USD/MXN exchange rate data'), and source ('from Banxico'). However, it doesn't explicitly differentiate from sibling tools like 'get_latest_usd_mxn_rate' or 'get_date_range_data', which would require a 5.

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 sibling tools like 'get_latest_usd_mxn_rate' for current rates or 'get_date_range_data' for date-based queries, nor does it specify use cases or exclusions. This leaves the agent without context for tool selection.

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/cfocoder/banxico_mcp'

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