Skip to main content
Glama
lienhage

Blockchain MCP Server

by lienhage

abi encode

abi-encode

Encode Ethereum smart contract function parameters using ABI encoding. Input parameter types and values to generate encoded data for blockchain transactions.

Instructions

encode function parameters with abi

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
typesYesparameter types array, e.g. ['uint256', 'address', 'bool']
valuesYesparameter values array, corresponding to the types array

Implementation Reference

  • Executes the ABI encoding logic: validates input lengths, processes values, encodes using ethers.AbiCoder, formats output with types, values, encoded hex, and byte length.
    async ({ types, values }) => {
      try {
        if (types.length !== values.length) {
          return {
            content: [{
              type: "text",
              text: "error: parameter types and values length mismatch"
            }],
            isError: true
          };
        }
    
        const processedValues = this.processValues(types, values);
        const encoded = ethers.AbiCoder.defaultAbiCoder().encode(types, processedValues);
        
        const typeSignature = `(${types.join(',')})`;
        const readableParams = types.map((type, index) => 
          `  ${type}: ${this.formatValue(values[index])}`
        ).join('\n');
    
        return {
          content: [{
            type: "text",
            text: `abi encode result:\n\nšŸ“‹ parameter types: ${typeSignature}\nšŸ“ parameter values:\n${readableParams}\n\nšŸ”¢ encoded result: ${encoded}\n\nšŸ“ length: ${(encoded.length - 2) / 2} bytes`
          }]
        };
      } catch (error) {
        return {
          content: [{
            type: "text",
            text: `error: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    }
  • Registers the 'abi-encode' tool on the MCP server with title, description, Zod input schema for types and values arrays, and references the handler function.
    server.registerTool(
      "abi-encode",
      {
        title: "abi encode",
        description: "encode function parameters with abi",
        inputSchema: {
          types: z.array(z.string()).describe("parameter types array, e.g. ['uint256', 'address', 'bool']"),
          values: z.array(z.union([z.string(), z.number(), z.boolean()])).describe("parameter values array, corresponding to the types array")
        }
      },
      async ({ types, values }) => {
        try {
          if (types.length !== values.length) {
            return {
              content: [{
                type: "text",
                text: "error: parameter types and values length mismatch"
              }],
              isError: true
            };
          }
    
          const processedValues = this.processValues(types, values);
          const encoded = ethers.AbiCoder.defaultAbiCoder().encode(types, processedValues);
          
          const typeSignature = `(${types.join(',')})`;
          const readableParams = types.map((type, index) => 
            `  ${type}: ${this.formatValue(values[index])}`
          ).join('\n');
    
          return {
            content: [{
              type: "text",
              text: `abi encode result:\n\nšŸ“‹ parameter types: ${typeSignature}\nšŸ“ parameter values:\n${readableParams}\n\nšŸ”¢ encoded result: ${encoded}\n\nšŸ“ length: ${(encoded.length - 2) / 2} bytes`
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: "text",
              text: `error: ${error instanceof Error ? error.message : String(error)}`
            }],
            isError: true
          };
        }
      }
    );
  • Helper method to process and convert input values based on their ABI types (e.g., BigInt for integers, address validation, bool parsing, bytes hex prefixing). Called by the handler.
    private processValues(types: string[], values: (string | number | boolean)[]): any[] {
      return values.map((value, index) => {
        const type = types[index];
        
        if (type.includes('uint') || type.includes('int')) {
          return ethers.getBigInt(value.toString());
        }
        
        if (type === 'address') {
          if (typeof value !== 'string') {
            throw new Error(`address type parameter must be a string: ${value}`);
          }
          if (!ethers.isAddress(value)) {
            throw new Error(`invalid ethereum address: ${value}`);
          }
          return value;
        }
        
        if (type === 'bool') {
          if (typeof value === 'boolean') return value;
          if (typeof value === 'string') {
            const lowercaseValue = value.toLowerCase();
            if (lowercaseValue === 'true') return true;
            if (lowercaseValue === 'false') return false;
            throw new Error(`boolean value must be true or false: ${value}`);
          }
          throw new Error(`invalid boolean value: ${value}`);
        }
        
        if (type.startsWith('bytes')) {
          if (typeof value !== 'string') {
            throw new Error(`bytes type parameter must be a string: ${value}`);
          }
          return value.startsWith('0x') ? value : `0x${value}`;
        }
        
        return value;
      });
    }
  • Helper method to format parameter values for readable display in the tool output.
    private formatValue(value: string | number | boolean): string {
      if (typeof value === 'string') {
        return `"${value}"`;
      }
      return String(value);
    }
  • CastCommands class registers its AbiEncoder instance (which registers 'abi-encode') with the MCP server.
    registerWithServer(server: McpServer) {
      this.fourByteService.registerWithServer(server);
      this.abiEncoder.registerWithServer(server);
      this.utilsService.registerWithServer(server);
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states 'encode' but doesn't disclose behavioral traits such as whether this is a read-only computation, potential errors (e.g., type-value mismatch), output format (likely hex string), or domain-specific constraints (e.g., Ethereum ABI). The description is too minimal to inform the agent adequately about how the tool behaves.

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

Conciseness5/5

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

The description is extremely concise with a single sentence 'encode function parameters with abi', which is front-loaded and wastes no words. Every part earns its place by directly stating the tool's purpose without redundancy or fluff, making it efficient for quick comprehension.

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 ABI encoding (a technical Ethereum concept), no annotations, no output schema, and rich sibling tools, the description is incomplete. It doesn't explain what ABI is, the output (e.g., encoded bytes), common use cases, or how it fits with tools like 'send-transaction'. The agent lacks sufficient context to use this tool effectively without external knowledge.

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%, with clear descriptions for both parameters ('types' and 'values'). The description adds no additional meaning beyond the schema, such as examples of full encoding processes or edge cases. Since the schema does the heavy lifting, the baseline score of 3 is appropriate, but the description doesn't compensate or enhance understanding.

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 'encode function parameters with abi' clearly states the action (encode) and target (function parameters with ABI), distinguishing it from sibling tools like 'abi-decode' or 'abi-encode-with-signature'. However, it doesn't specify what ABI encoding entails (e.g., Ethereum contract interaction) or differentiate from '4byte' or 'sig' tools beyond the basic verb+resource.

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 scenarios like preparing contract calls, comparing to 'abi-encode-with-signature', or avoiding misuse with other encoding/decoding siblings. Without any context or exclusions, the agent must infer usage from the name 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

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/lienhage/blockchain-mcp'

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