Skip to main content
Glama

get_latest_ethereum_block

Retrieve details of the most recent Ethereum block, including block number, using the Cryo MCP Server. Query blockchain data efficiently for analysis or integration.

Instructions

Get information about the latest Ethereum block

Returns:
    Information about the latest block including block number

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The handler function for 'get_latest_ethereum_block' tool, decorated with @mcp.tool() for MCP registration. It retrieves the latest Ethereum block number via RPC, downloads block data using the 'cryo blocks' CLI command, and returns file paths to the generated JSON data.
    @mcp.tool()
    def get_latest_ethereum_block() -> Dict[str, Any]:
        """
        Get information about the latest Ethereum block
        
        Returns:
            Information about the latest block including block number
        """
        latest_block = get_latest_block_number()
        
        if latest_block is None:
            return {"error": "Failed to get the latest block number from the RPC endpoint"}
        
        # Get block data using cryo
        rpc_url = os.environ.get("ETH_RPC_URL", DEFAULT_RPC_URL)
        block_range = f"{latest_block}:{latest_block+1}"  # +1 to make it inclusive
        
        data_dir = Path(os.environ.get("CRYO_DATA_DIR", DEFAULT_DATA_DIR))
        latest_dir = data_dir / "latest"
        latest_dir.mkdir(parents=True, exist_ok=True)
        
        # Always clean up the latest directory for latest block
        print("Cleaning latest directory for current block")
        existing_files = list(latest_dir.glob("*blocks*.*"))
        for file in existing_files:
            try:
                file.unlink()
                print(f"Removed existing file: {file}")
            except Exception as e:
                print(f"Warning: Could not remove file {file}: {e}")
        
        cmd = [
            "cryo", "blocks", 
            "-b", block_range,
            "-r", rpc_url,
            "--json", 
            "-o", str(latest_dir)
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode != 0:
            return {
                "block_number": latest_block,
                "error": "Failed to get detailed block data",
                "stderr": result.stderr
            }
        
        # Try to find the report file which contains info about generated files
        report_dir = latest_dir / ".cryo" / "reports"
        if report_dir.exists():
            # Get the most recent report file
            report_files = sorted(report_dir.glob("*.json"), key=lambda x: x.stat().st_mtime, reverse=True)
            if report_files:
                with open(report_files[0], 'r') as f:
                    report_data = json.load(f)
                    # Get the list of completed files from the report
                    if "results" in report_data and "completed_paths" in report_data["results"]:
                        completed_files = report_data["results"]["completed_paths"]
                        print(f"Found {len(completed_files)} files in Cryo report: {completed_files}")
                        
                        return {
                            "block_number": latest_block,
                            "files": completed_files,
                            "count": len(completed_files)
                        }
        
        # Fallback to glob search if report file not found
        output_files = list(latest_dir.glob("*blocks*.json"))
        
        if not output_files:
            return {
                "block_number": latest_block,
                "error": "No output files generated"
            }
        
        # Convert Path objects to strings for JSON serialization
        file_paths = [str(file_path) for file_path in output_files]
        
        return {
            "block_number": latest_block,
            "files": file_paths,
            "count": len(file_paths)
        }
  • Supporting helper function that queries the Ethereum RPC endpoint using eth_blockNumber to retrieve the latest block number, used by the main tool handler.
    def get_latest_block_number() -> Optional[int]:
        """Get the latest block number from the Ethereum node"""
        rpc_url = os.environ.get("ETH_RPC_URL", DEFAULT_RPC_URL)
        
        payload = {
            "jsonrpc": "2.0",
            "method": "eth_blockNumber",
            "params": [],
            "id": 1
        }
        
        try:
            response = requests.post(rpc_url, json=payload)
            response_data = response.json()
            
            if 'result' in response_data:
                # Convert hex to int
                latest_block = int(response_data['result'], 16)
                print(f"Latest block number: {latest_block}")
                return latest_block
            else:
                print(f"Error fetching latest block: {response_data.get('error', 'Unknown error')}")
                return None
        except Exception as e:
            print(f"Exception when fetching latest block: {e}")
            return None
  • The @mcp.tool() decorator registers the get_latest_ethereum_block function as an MCP tool.
    @mcp.tool()
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 includes 'block number,' but doesn't specify other behavioral traits such as rate limits, error conditions, data freshness, or whether it's a read-only operation. This leaves significant gaps in understanding how the tool behaves beyond its basic function.

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 concise and well-structured, with two sentences that efficiently convey the tool's purpose and return value. There's no wasted language, and it's front-loaded with the main function. However, it could be slightly more polished by integrating the return information into the first sentence for better flow.

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 of blockchain data retrieval and the lack of annotations and output schema, the description is incomplete. It mentions returning 'information about the latest block including block number,' but doesn't detail other returned fields (e.g., timestamp, transactions), error handling, or performance considerations. This leaves the agent with insufficient context for effective use.

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 tool has 0 parameters, and the schema description coverage is 100%, so there are no parameters to document. The description doesn't need to add parameter semantics, and it appropriately doesn't mention any. A baseline of 4 is applied since no parameters exist, and the description doesn't introduce confusion about them.

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 information about the latest Ethereum block.' It specifies the verb ('get') and resource ('latest Ethereum block'), making the function unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'get_transaction_by_hash' or 'query_blockchain_sql,' 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 when this tool is appropriate (e.g., for real-time block data) or when to use other tools like 'query_blockchain_sql' for more complex queries. This lack of contextual direction leaves the agent without usage instructions.

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

Related 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/z80dev/cryo-mcp'

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