Skip to main content
Glama
Bankless

Bankless Onchain MCP Server

Official
by Bankless

read_contract

Extract and decode blockchain contract states by specifying contract address, method, and expected output types. Ensures accurate data retrieval for nested structures and tuples.

Instructions

Read contract state from a blockchain. important:

            In case of a tuple, don't use type tuple, but specify the inner types (found in the source) in order. For nested structs, include the substructs types.

Example: 
struct DataTypeA {
DataTypeB b;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
}

struct DataTypeB {
address token;
}

results in outputs for function with return type DataTypeA (tuple in abi): outputs: [{"type": "address"}, {"type": "uint128"}]

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contractYesThe contract address
inputsYesInput parameters for the method call
methodYesThe contract method to call
networkYesThe blockchain network (e.g., "ethereum", "base")
outputsYesExpected output types for the method call. In case of a tuple, don't use type tuple, but specify the inner types (found in the source) in order. For nested structs, include the substructs types. Example: struct DataTypeA { DataTypeB b; //the liquidity index. Expressed in ray uint128 liquidityIndex; } struct DataTypeB { address token; } results in outputs for function with return type DataTypeA (tuple in abi): outputs: [{"type": "address"}, {"type": "uint128"}]

Implementation Reference

  • src/index.ts:63-81 (registration)
    Registration of the 'read_contract' tool in the MCP server's list of tools, specifying name, description, and input schema.
                name: "read_contract",
                description: `Read contract state from a blockchain. important:  
                
                In case of a tuple, don't use type tuple, but specify the inner types (found in the source) in order. For nested structs, include the substructs types.
    
    Example: 
    struct DataTypeA {
    DataTypeB b;
    //the liquidity index. Expressed in ray
    uint128 liquidityIndex;
    }
    
    struct DataTypeB {
    address token;
    }
    
    results in outputs for function with return type DataTypeA (tuple in abi): outputs: [{"type": "address"}, {"type": "uint128"}]`,
                inputSchema: zodToJsonSchema(contracts.ReadContractSchema),
            },
  • Zod schema defining the input structure for the read_contract tool, including network, contract, method, inputs, and outputs.
    export const ReadContractSchema = z.object({
        network: z.string().describe('The blockchain network (e.g., "ethereum", "base")'),
        contract: z.string().describe('The contract address'),
        method: z.string().describe('The contract method to call'),
        inputs: z.array(InputSchema).describe('Input parameters for the method call'),
        outputs: z.array(OutputSchema).describe(`Expected output types for the method call. 
        In case of a tuple, don't use type tuple, but specify the inner types (found in the source) in order. For nested structs, include the substructs types.
        
        Example: 
        struct DataTypeA {
        DataTypeB b;
        //the liquidity index. Expressed in ray
        uint128 liquidityIndex;
        }
        
        struct DataTypeB {
        address token;
        }
        
        results in outputs for function with return type DataTypeA (tuple in abi): outputs: [{"type": "address"}, {"type": "uint128"}]
      `)
    });
  • MCP CallToolRequest handler case for 'read_contract', parses arguments, calls the implementation function, and formats response.
    case "read_contract": {
        const args = contracts.ReadContractSchema.parse(request.params.arguments);
        const result = await contracts.readContractState(
            args.network,
            args.contract,
            args.method,
            args.inputs,
            args.outputs
        );
        return {
            content: [{type: "text", text: JSON.stringify(result, null, 2)}],
        };
    }
  • Core implementation of the read_contract tool: processes outputs, authenticates with API token, makes POST request to Bankless API to read contract state, handles various errors.
    export async function readContractState(
        network: string,
        contract: string,
        method: string,
        inputs: z.infer<typeof InputSchema>[],
        outputs: z.infer<typeof OutputSchema>[]
    ): Promise<ContractCallResult[]> {
        const token = process.env.BANKLESS_API_TOKEN;
    
        if (!token) {
            throw new BanklessAuthenticationError('BANKLESS_API_TOKEN environment variable is not set');
        }
    
        const endpoint = `${BASE_URL}/chains/${network}/contract/read`;
    
        const cleanedOutputs = processOutputs(outputs);
    
        try {
            const response = await axios.post(
                endpoint,
                {
                    contract,
                    method,
                    inputs,
                    outputs: cleanedOutputs
                },
                {
                    headers: {
                        'Content-Type': 'application/json',
                        'X-BANKLESS-TOKEN': `${token}`
                    }
                }
            );
    
            return response.data;
        } catch (error) {
            if (axios.isAxiosError(error)) {
                const statusCode = error.response?.status || 'unknown';
                const errorMessage = error.response?.data?.message || error.message;
    
                if (statusCode === 401 || statusCode === 403) {
                    throw new BanklessAuthenticationError(`Authentication Failed: ${errorMessage}`);
                } else if (statusCode === 404) {
                    throw new BanklessResourceNotFoundError(`Not Found: ${errorMessage}`);
                } else if (statusCode === 422) {
                    throw new BanklessValidationError(`Validation Error: ${errorMessage}`, error.response?.data);
                } else if (statusCode === 429) {
                    // Extract reset timestamp or default to 60 seconds from now
                    const resetAt = new Date();
                    resetAt.setSeconds(resetAt.getSeconds() + 60);
                    throw new BanklessRateLimitError(`Rate Limit Exceeded: ${errorMessage}`, resetAt);
                }
    
                throw new Error(`Bankless API Error (${statusCode}): ${errorMessage}`);
            }
            throw new Error(`Failed to read contract state: ${error instanceof Error ? error.message : String(error)}`);
        }
    }
  • Helper function to process output schemas, flattening tuples recursively for the API request.
    export function processOutputs(outputs: OutputSchemaType[]) {
        if (!outputs || !Array.isArray(outputs)) {
            return [];
        }
    
        const result: OutputSchemaType[] = [];
    
        for (const output of outputs) {
            const processed = processOutput(output);
            result.push(...processed);
        }
    
        return result;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It only mentions that this is a 'read' operation, but doesn't cover important aspects like whether it requires authentication, rate limits, network availability, error handling, or what the return format looks like. The example focuses on output formatting but doesn't explain the tool's operational behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness2/5

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

The description is poorly structured - it starts with a purpose statement but immediately dives into complex formatting rules with a lengthy example. The formatting guidance should be in the parameter documentation, not the main description. The description is front-loaded with technical details rather than clear usage information.

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?

For a 5-parameter tool with no annotations and no output schema, the description is inadequate. It should explain what kind of data is returned, error conditions, network requirements, and how this differs from sibling tools. The current description focuses narrowly on output formatting while missing broader contextual information needed for effective tool selection and use.

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?

Schema description coverage is 100%, so the schema already documents all 5 parameters thoroughly. The description adds no meaningful parameter semantics beyond what's in the schema - it only provides formatting rules for the 'outputs' parameter through an example, which is already covered in the schema's description field. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description starts with 'Read contract state from a blockchain' which clearly states the verb ('read') and resource ('contract state'), but it's vague about what 'contract state' entails compared to siblings like 'get_abi' or 'get_source'. It doesn't specify that this is for calling read-only contract methods, which would help distinguish it from other blockchain query tools.

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 like 'get_abi' or 'get_events'. The description focuses entirely on technical formatting requirements for outputs, with no mention of use cases, prerequisites, or comparisons to sibling tools.

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/Bankless/onchain-mcp'

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