Skip to main content
Glama
cfocoder

Banxico MCP Server

get_inflation_data

Retrieve inflation data from Mexico's central bank (Banxico) to analyze monthly, accumulated, or annual inflation trends with customizable data point limits.

Instructions

Get inflation data from Banxico.

Args: inflation_type: Type of inflation data ('monthly', 'accumulated', 'annual') limit: Maximum number of recent data points (default: 12)

Returns: Formatted inflation data with percentages

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
inflation_typeNomonthly
limitNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Primary handler for get_inflation_data tool. Registered via @mcp.tool() decorator. Maps inflation_type to Banxico series IDs (SP30577 monthly, SP30579 accumulated, SP30578 annual), fetches data via API, applies limit to recent points, formats output using helper.
    @mcp.tool()
    async def get_inflation_data(inflation_type: str = "monthly", limit: Optional[int] = 12) -> str:
        """
        Get inflation data from Banxico.
        
        Args:
            inflation_type: Type of inflation data ('monthly', 'accumulated', 'annual')
            limit: Maximum number of recent data points (default: 12)
            
        Returns:
            Formatted inflation data with percentages
        """
        if not BANXICO_TOKEN:
            return "Error: BANXICO_API_TOKEN environment variable not set. Please configure your API token."
        
        # Map inflation types to series IDs
        series_map = {
            "monthly": "SP30577",      # Monthly Inflation
            "accumulated": "SP30579",   # Accumulated Inflation  
            "annual": "SP30578"        # Annual Inflation
        }
        
        if inflation_type not in series_map:
            return f"Invalid inflation type: {inflation_type}. Available types: {list(series_map.keys())}"
        
        series_id = series_map[inflation_type]
        endpoint = f"series/{series_id}/datos"
        data = await make_banxico_request(endpoint, BANXICO_TOKEN)
        
        if not data:
            return f"Failed to retrieve {inflation_type} inflation data. Please check your API token and network connection."
        
        # Apply limit if specified
        if limit and data.get("bmx", {}).get("series"):
            for series in data["bmx"]["series"]:
                if "datos" in series and len(series["datos"]) > limit:
                    series["datos"] = series["datos"][-limit:]
        
        return format_inflation_data(data)
  • Helper function specifically for formatting inflation data: adds % symbols, shows recent data points (up to 10), structures output with emojis and series info.
    def format_inflation_data(data: dict[str, Any]) -> str:
        """
        Format inflation data with percentage symbols and better labeling.
        
        Args:
            data: Raw JSON response from Banxico API
            
        Returns:
            Formatted string with inflation data including percentage symbols
        """
        if not data or "bmx" not in data:
            return "No inflation data available"
        
        series_list = data["bmx"].get("series", [])
        if not series_list:
            return "No inflation series found"
        
        result = []
        for series in series_list:
            title = series.get("titulo", "Unknown Series")
            series_id = series.get("idSerie", "Unknown ID")
            result.append(f"📊 {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 recent data points with percentage formatting
                display_count = min(len(datos), 10)
                for dato in datos[-display_count:]:
                    fecha = dato.get("fecha", "Unknown date")
                    valor = dato.get("dato", "N/A")
                    # Add percentage symbol for inflation data
                    if valor != "N/A" and valor is not None:
                        try:
                            valor_num = float(valor)
                            valor = f"{valor_num}%"
                        except (ValueError, TypeError):
                            pass
                    result.append(f"  {fecha}: {valor}")
            
            result.append("")  # Empty line between series
        
        return "\n".join(result)
  • Shared async helper for making HTTP requests to Banxico SIE API, used by get_inflation_data and other tools. Handles errors, authentication via token, and returns 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?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the return format ('Formatted inflation data with percentages') but lacks critical details like data source reliability, update frequency, error handling, or rate limits. For a data-fetching tool, this is insufficient behavioral context.

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 core purpose stated first followed by parameter and return details. The structure is clear, though the 'Args' and 'Returns' sections could be integrated more smoothly into prose.

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 (2 parameters, no annotations, but with an output schema), the description is partially complete. It covers purpose and parameters adequately but lacks behavioral context and usage guidelines. The output schema existence reduces the need to detail return values, 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?

The description adds meaningful semantics for both parameters: it explains that 'inflation_type' specifies the data type (with examples) and 'limit' controls the number of recent data points. Since schema description coverage is 0%, this compensates well, though it doesn't fully document all possible values or constraints (e.g., valid ranges for 'limit').

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 action ('Get') and resource ('inflation data from Banxico'), making the purpose immediately understandable. However, it doesn't differentiate this tool from its siblings (like get_unemployment_data or get_usd_mxn_historical_data) beyond specifying the data type, which prevents a perfect 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. It doesn't mention sibling tools or contexts where other tools might be more appropriate, leaving the agent without usage direction beyond the basic purpose.

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