Skip to main content
Glama
kukapay

blocknative-mcp

estimate_gas_cost

Estimate transaction gas costs by analyzing gas limit, confidence level, and blockchain network to predict accurate fee requirements.

Instructions

Estimate gas cost for a transaction based on gas limit, confidence level, and chain.

Parameters:
- gas_limit (int): The gas limit for the transaction (e.g., 21000 for a simple transfer).
- confidence (int): The confidence level for gas price prediction (0-100).
- chain_id (int): The ID of the blockchain network (e.g., 1 for Ethereum Mainnet). Default: 1.
- ctx (Optional[Context]): The MCP context object. Default: None.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
gas_limitYes
confidenceNo
chain_idNo
ctxNo

Implementation Reference

  • The handler function for the 'estimate_gas_cost' tool, decorated with @mcp.tool() for registration. It validates inputs, fetches gas prices using the helper, selects the closest confidence prediction, calculates the total gas cost in Gwei and ETH, and returns a formatted string.
    @mcp.tool()
    async def estimate_gas_cost(gas_limit: int, confidence: int = 99, chain_id: int = 1, ctx: Optional[Context] = None) -> str:
        """
        Estimate gas cost for a transaction based on gas limit, confidence level, and chain.
    
        Parameters:
        - gas_limit (int): The gas limit for the transaction (e.g., 21000 for a simple transfer).
        - confidence (int): The confidence level for gas price prediction (0-100).
        - chain_id (int): The ID of the blockchain network (e.g., 1 for Ethereum Mainnet). Default: 1.
        - ctx (Optional[Context]): The MCP context object. Default: None.
        """
        if not (0 <= confidence <= 100):
            return "Error: Confidence must be between 0 and 100"
        if gas_limit <= 0:
            return "Error: Gas limit must be positive"
        
        data = await fetch_gas_prices(chain_id)
        if "error" in data:
            return data["error"]
        
        # Find the closest confidence level
        predictions = data["estimatedPrices"]
        closest_prediction = min(
            predictions,
            key=lambda p: abs(p.get("confidence", 0) - confidence),
            default={}
        )
        
        if not closest_prediction:
            return "Error: No matching gas price prediction found"
        
        max_fee = closest_prediction.get("maxFeePerGas", 0)
        total_cost_gwei = max_fee * gas_limit
        total_cost_eth = total_cost_gwei / 1e9  # Convert Gwei to ETH
        
        return (
            f"Estimated Gas Cost (Confidence {confidence}%, Chain ID {chain_id}):\n"
            f"- Gas Limit: {gas_limit}\n"
            f"- Max Fee Per Gas: {max_fee} Gwei\n"
            f"- Total Cost: {total_cost_gwei} Gwei ({total_cost_eth:.6f} ETH)"
        )
  • Supporting helper function that fetches gas price data from the Blocknative API, extracts predictions and base fee, and handles errors. Used by the estimate_gas_cost handler.
    async def fetch_gas_prices(chain_id: int = 1) -> Dict:
        """Fetch gas price predictions from Blocknative API for a given chain."""
        try:
            headers = {"Authorization": BLOCKNATIVE_API_KEY} if BLOCKNATIVE_API_KEY else {}
            async with httpx.AsyncClient() as client:
                response = await client.get(
                    BLOCKNATIVE_GAS_API_URL,
                    headers=headers,
                    params={"chainid": chain_id}
                )
                response.raise_for_status()
                data = response.json()
            
            # Extract relevant fields from the response
            block_prices = data.get("blockPrices", [])
            if not block_prices:
                return {"error": "No block prices found in API response"}
            
            # Use the first block's data
            first_block = block_prices[0]
            return {
                "baseFeePerGas": first_block.get("baseFeePerGas", 0),
                "estimatedPrices": first_block.get("estimatedPrices", []),
                "unit": data.get("unit", "gwei"),
                "system": data.get("system", "unknown"),
                "network": data.get("network", "unknown")
            }
        except httpx.HTTPError as e:
            return {"error": f"Failed to fetch gas prices for chain ID {chain_id}: {str(e)}"}
  • Function signature with type annotations and docstring defining the input parameters and return type, serving as the tool schema.
    async def estimate_gas_cost(gas_limit: int, confidence: int = 99, chain_id: int = 1, ctx: Optional[Context] = None) -> str:
        """
        Estimate gas cost for a transaction based on gas limit, confidence level, and chain.
    
        Parameters:
        - gas_limit (int): The gas limit for the transaction (e.g., 21000 for a simple transfer).
        - confidence (int): The confidence level for gas price prediction (0-100).
        - chain_id (int): The ID of the blockchain network (e.g., 1 for Ethereum Mainnet). Default: 1.
        - ctx (Optional[Context]): The MCP context object. Default: None.
        """
  • The @mcp.tool() decorator registers the estimate_gas_cost function as an MCP tool.
    @mcp.tool()
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 estimates gas cost but doesn't explain how the estimation works (e.g., based on historical data, network conditions), whether it's a read-only operation, potential rate limits, or error conditions. For a tool with financial implications, this is a significant gap.

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: a clear purpose statement followed by a bulleted list of parameters with explanations. Every sentence adds value, and there's no redundant information. It could be slightly more front-loaded with usage context, 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 complexity (financial estimation tool), lack of annotations, and no output schema, the description is moderately complete. It covers parameters well but misses behavioral details like estimation methodology, error handling, or return format. For a tool that could impact transaction costs, more context on reliability and limitations would be beneficial.

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 context beyond the schema, which has 0% description coverage. It explains each parameter's purpose with examples (e.g., '21000 for a simple transfer', '0-100' for confidence, '1 for Ethereum Mainnet'), clarifying their roles in gas cost estimation. This compensates well for the schema's lack of descriptions.

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: 'Estimate gas cost for a transaction based on gas limit, confidence level, and chain.' It specifies the verb ('estimate'), resource ('gas cost'), and key inputs. However, it doesn't explicitly differentiate from sibling tools like 'predict_gas_price', which might be related but serves a different purpose.

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_supported_chains' or 'predict_gas_price', nor does it specify prerequisites, scenarios, or exclusions for usage. The agent must infer context from tool names alone.

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/kukapay/blocknative-mcp'

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