Skip to main content
Glama

simulate_transaction

Preview transaction outcomes on a forked chain to detect reverts, gas issues, and risks before execution.

Instructions

Simulate a transaction on a forked chain WITHOUT actually executing it. Detects reverts, abnormal gas usage, and other red flags. Use this to preview what will happen before sending a real transaction.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
chainIdNoChain ID to simulate on
fromYesSender address
toYesTarget contract address
dataYesTransaction calldata (hex)
valueNoETH value to send (in wei)0

Implementation Reference

  • The handler function for `simulate_transaction` which simulates a transaction on a forked chain using viem, estimates gas, checks for gas anomalies, and captures revert reasons.
    export async function simulateTransaction(req: SimulationRequest): Promise<SimulationResult> {
      const chainConfig = CHAIN_MAP[req.chainId];
      if (!chainConfig) {
        return {
          success: false,
          gasUsed: 0n,
          gasAnomaly: false,
          revertReason: `Unsupported chain ID: ${req.chainId}`,
          riskIndicators: ["unsupported_chain"],
          estimatedCostEth: "0",
        };
      }
    
      const client = createPublicClient({
        chain: chainConfig.chain,
        transport: http(chainConfig.rpcUrl),
      });
    
      const riskIndicators: string[] = [];
    
      try {
        // Estimate gas
        const gasEstimate = await client.estimateGas({
          account: req.from,
          to: req.to,
          data: req.data,
          value: req.value || 0n,
        });
    
        // Check for gas anomalies
        const gasAnomaly = gasEstimate > GAS_THRESHOLDS.suspicious;
        if (gasAnomaly) {
          riskIndicators.push("high_gas_usage");
        }
        if (gasEstimate > GAS_THRESHOLDS.dangerous) {
          riskIndicators.push("extremely_high_gas");
        }
    
        // Simulate the call
        const result = await client.call({
          account: req.from,
          to: req.to,
          data: req.data,
          value: req.value || 0n,
        });
    
        // Get gas price for cost estimation
        const gasPrice = await client.getGasPrice();
        const costWei = gasEstimate * gasPrice;
        const costEth = Number(costWei) / 1e18;
    
        return {
          success: true,
          gasUsed: gasEstimate,
          gasAnomaly,
          returnData: result.data,
          riskIndicators,
          estimatedCostEth: costEth.toFixed(6),
        };
      } catch (error: any) {
        const revertReason = extractRevertReason(error);
        riskIndicators.push("transaction_reverts");
    
        return {
          success: false,
          gasUsed: 0n,
          gasAnomaly: false,
          revertReason,
          riskIndicators,
          estimatedCostEth: "0",
        };
      }
    }
  • Input (SimulationRequest) and Output (SimulationResult) interfaces for the `simulate_transaction` tool.
    export interface SimulationRequest {
      /** Chain to simulate on */
      chainId: number;
      /** The sender address (agent's wallet) */
      from: Address;
      /** Target contract address */
      to: Address;
      /** Calldata */
      data: Hex;
      /** ETH value to send (in wei) */
      value?: bigint;
      /** Optional block number to fork from */
      blockNumber?: bigint;
    }
    
    export interface SimulationResult {
      success: boolean;
      /** Gas used by the transaction */
      gasUsed: bigint;
      /** Whether gas usage is abnormally high */
      gasAnomaly: boolean;
      /** Revert reason if the transaction failed */
      revertReason?: string;
      /** Return data from the call */
      returnData?: Hex;
      /** Risk indicators from simulation */
      riskIndicators: string[];
      /** Estimated gas cost in ETH */
      estimatedCostEth: string;
    }
  • Registration and tool execution handler within the MCP server implementation.
    },
    async ({ chainId, from, to, data, value }) => {
      const result = await simulateTransaction({
        chainId,
        from: from as Address,
        to: to as Address,
        data: data as Hex,
        value: BigInt(value),
      });
    
      return {
        content: [{
          type: "text" as const,
          text: JSON.stringify({
            ...result,
            gasUsed: result.gasUsed.toString(),
          }, null, 2),
        }],
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: it's a simulation (non-destructive), detects specific issues (reverts, abnormal gas usage, red flags), and operates on a forked chain. It doesn't mention rate limits, authentication needs, or detailed output format, but covers essential safety and scope.

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?

Two sentences with zero waste: first defines the tool's purpose and key features, second provides usage guidance. Every phrase adds value, and it's front-loaded with the core functionality.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description does well by explaining the tool's behavior, safety profile (non-execution), and use case. It could improve by hinting at return values (e.g., simulation results), but for a 5-parameter tool with good schema coverage, it's largely complete.

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 parameters thoroughly. The description adds no additional parameter semantics beyond implying the simulation context, which aligns with the schema. Baseline 3 is appropriate as the schema does the heavy lifting.

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

Purpose5/5

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

The description clearly states the specific action ('simulate a transaction'), the resource ('on a forked chain'), and the key distinction from actual execution ('WITHOUT actually executing it'). It differentiates from siblings like 'assess_risk' or 'scan_contract' by focusing on transaction simulation rather than general risk assessment or contract scanning.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly states when to use this tool: 'to preview what will happen before sending a real transaction.' This provides clear context for usage versus alternatives, indicating it's for pre-execution testing rather than live operations.

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/StanleytheGoat/aegis'

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