Skip to main content
Glama
cfocoder

Banxico MCP Server

get_date_range_data

Retrieve historical USD/MXN exchange rate data from Banxico for specific date ranges to analyze currency trends and financial performance.

Instructions

Get exchange rate data for a specific date range.

Args: start_date: Start date in YYYY-MM-DD format end_date: End date in YYYY-MM-DD format series_id: The series ID (default: SF63528 for USD/MXN)

Returns: Exchange rate data for the specified date range

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
start_dateYes
end_dateYes
series_idNoSF63528

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function for the 'get_date_range_data' tool. Decorated with @mcp.tool() for automatic registration in FastMCP. Fetches Banxico API data for a given date range and series ID, handles token and request errors, and returns formatted data using helper functions.
    @mcp.tool()
    async def get_date_range_data(start_date: str, end_date: str, series_id: str = "SF63528") -> str:
        """
        Get exchange rate data for a specific date range.
        
        Args:
            start_date: Start date in YYYY-MM-DD format
            end_date: End date in YYYY-MM-DD format
            series_id: The series ID (default: SF63528 for USD/MXN)
            
        Returns:
            Exchange rate data for the specified date range
        """
        if not BANXICO_TOKEN:
            return "Error: BANXICO_API_TOKEN environment variable not set. Please configure your API token."
        
        endpoint = f"series/{series_id}/datos/{start_date}/{end_date}"
        data = await make_banxico_request(endpoint, BANXICO_TOKEN)
        
        if not data:
            return f"Failed to retrieve data for {series_id} from {start_date} to {end_date}. Please check your API token and network connection."
        
        return format_exchange_rate_data(data)
  • Helper function used by get_date_range_data to make authenticated HTTP requests to the Banxico SIE API with comprehensive error handling.
    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
  • Helper function used by get_date_range_data to format the raw JSON data from Banxico API into a human-readable string, showing series info and data points.
    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)
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 mentions the tool retrieves data (implied read-only) and specifies a default series_id, but lacks details on permissions, rate limits, error handling, or response format beyond a vague 'Exchange rate data.' For a data-fetching tool with no annotations, this is insufficient.

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 appropriately sized and front-loaded, with the purpose stated first. The Args and Returns sections are structured but slightly verbose; every sentence adds value, though 'Returns:' could be more concise. Overall, it's efficient with minimal waste.

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 3 parameters with 0% schema coverage and an output schema (implied by 'Has output schema: true'), the description is moderately complete. It explains parameters well but lacks behavioral context (e.g., authentication, errors). The output schema should cover return values, so the vague 'Exchange rate data' is acceptable, but overall gaps remain.

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

Parameters4/5

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

Schema description coverage is 0%, so the description must compensate. It adds meaning by explaining each parameter: start_date and end_date formats (YYYY-MM-DD) and series_id's default value (SF63528 for USD/MXN). This clarifies beyond the bare schema, though it doesn't detail what series_id represents or list alternatives.

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 exchange rate data for a specific date range.' It specifies the verb ('Get'), resource ('exchange rate data'), and scope ('date range'). However, it doesn't explicitly differentiate from siblings like 'get_usd_mxn_historical_data' or 'get_latest_usd_mxn_rate', which appear related.

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?

No guidance is provided on when to use this tool versus alternatives. The description doesn't mention sibling tools, prerequisites, or exclusions. It simply states what the tool does without contextual usage information.

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