Skip to main content
Glama

write_contract

Interact with smart contracts on BNB Chain by calling state-changing functions. Specify contract address, ABI, function name, arguments, and network to execute write operations securely.

Instructions

Write data to a smart contract by calling a state-changing function

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
abiYesThe ABI of the smart contract function, as a JSON array
argsYesThe arguments to pass to the function
contractAddressYesThe address of the smart contract to interact with
functionNameYesThe name of the function to call on the contract
networkNoNetwork name (e.g. 'bsc', 'opbnb', 'ethereum', 'base', etc.) or chain ID. Supports others main popular networks. Defaults to BSC mainnet.bsc
privateKeyNoPrivate key of the sending account. Used only for transaction signing.0x5a2b7e4d9c8f1a3e6b0d2c5f4e3d2a1b0c9f8e7d6a5b4c3d2e1f0a9b8c7d6e5f4

Implementation Reference

  • Complete registration of the 'write_contract' MCP tool, including description, Zod input schema, and the async handler function that parses ABI, invokes the underlying writeContract service using the provided private key, and returns the transaction hash or formatted error.
    server.tool(
      "write_contract",
      "Write data to a smart contract by calling a state-changing function",
      {
        contractAddress: z
          .string()
          .describe("The address of the smart contract to interact with"),
        abi: z
          .array(z.any())
          .describe("The ABI of the smart contract function, as a JSON array"),
        functionName: z
          .string()
          .describe("The name of the function to call on the contract"),
        args: z.array(z.any()).describe("The arguments to pass to the function"),
        privateKey: z
          .string()
          .describe(
            "Private key of the sending account. Used only for transaction signing."
          )
          .default(process.env.PRIVATE_KEY as string),
        network: defaultNetworkParam
      },
      async ({
        contractAddress,
        abi,
        functionName,
        args,
        privateKey,
        network = "bsc"
      }) => {
        try {
          // Parse ABI if it's a string
          const parsedAbi = typeof abi === "string" ? JSON.parse(abi) : abi
    
          const contractParams: Record<string, any> = {
            address: contractAddress as Address,
            abi: parsedAbi,
            functionName,
            args
          }
    
          const txHash = await services.writeContract(
            privateKey as Hex,
            contractParams,
            network
          )
    
          return mcpToolRes.success({
            contractAddress,
            functionName,
            args,
            transactionHash: txHash,
            message: "Contract write transaction sent successfully"
          })
        } catch (error) {
          return mcpToolRes.error(error, "writing to contract")
        }
      }
    )
  • Helper service function 'writeContract' that creates a wallet client from private key and network, then calls viem's writeContract to execute the transaction and return the hash.
    export async function writeContract(
      privateKey: Hex,
      params: Record<string, any>,
      network = "ethereum"
    ): Promise<Hash> {
      const client = getWalletClient(privateKey, network)
      return await client.writeContract(params as any)
    }
  • Module-level registration function that calls registerContractTools(server), thereby registering the 'write_contract' tool among others.
    export function registerContracts(server: McpServer) {
      registerContractPrompts(server)
      registerContractTools(server)
    }
  • src/evm/index.ts:13-13 (registration)
    EVM module registration that includes the contracts module, invoking the chain of registrations for 'write_contract' tool.
    registerContracts(server)
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 mentions 'state-changing function' which implies mutation, but doesn't cover critical aspects: transaction costs (gas), network confirmation times, irreversible nature of blockchain writes, authentication requirements (private key usage), or error handling. For a high-stakes write operation, this is insufficient transparency.

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 a single, efficient sentence that communicates the core purpose without unnecessary words. It's appropriately front-loaded with the essential action and target. Every word earns its place in this compact formulation.

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 complex blockchain write operation with 6 parameters, no annotations, and no output schema, the description is inadequate. It doesn't address transaction lifecycle, error scenarios, cost implications, or return values. Given the high-stakes nature of smart contract interactions and the rich sibling tool ecosystem, more contextual information is needed for safe and effective 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%, providing complete parameter documentation. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain relationships between parameters (e.g., how ABI matches functionName), format requirements, or practical examples. With full schema coverage, the baseline of 3 is appropriate as the description doesn't enhance parameter 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 clearly states the action ('write data') and target ('smart contract') with the specific mechanism ('calling a state-changing function'), which distinguishes it from read-only operations like 'read_contract'. However, it doesn't explicitly differentiate from other state-changing tools like 'transfer_erc20' or 'approve_token_spending', which are more specific implementations of contract writes.

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 prerequisites (e.g., needing a private key for signing), contrast with 'read_contract' for non-state-changing calls, or explain when to use more specialized tools like 'transfer_erc20' instead. This leaves the agent without contextual decision-making help.

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/bnb-chain/bnbchain-mcp'

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