Skip to main content
Glama

approve_token_spending

Authorize a DeFi protocol or exchange to spend your ERC20 tokens by specifying the token address, spender address, and amount. Essential for enabling token interactions in decentralized applications.

Instructions

Approve another address (like a DeFi protocol or exchange) to spend your ERC20 tokens. This is often required before interacting with DeFi protocols.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
amountYesThe amount of tokens to approve in token units, not wei (e.g., '1000' to approve spending 1000 tokens). Use a very large number for unlimited approval.
networkNoNetwork name (e.g., 'ethereum', 'optimism', 'arbitrum', 'base', 'polygon') or chain ID. Defaults to Ethereum mainnet.
privateKeyYesPrivate key of the token owner account in hex format (with or without 0x prefix). SECURITY: This is used only for transaction signing and is not stored.
spenderAddressYesThe contract address being approved to spend your tokens (e.g., a DEX or lending protocol)
tokenAddressYesThe contract address of the ERC20 token to approve for spending (e.g., '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' for USDC on Ethereum)

Implementation Reference

  • Registration of the 'approve_token_spending' MCP tool, including input schema, annotations, and handler function that delegates to services.approveERC20
    server.registerTool(
      "approve_token_spending",
      {
        description: "Approve a spender (contract) to spend tokens on your behalf. Required before interacting with DEXes, lending protocols, etc.",
        inputSchema: {
          tokenAddress: z.string().describe("The ERC20 token contract address"),
          spenderAddress: z.string().describe("The address that will be allowed to spend tokens (usually a contract)"),
          amount: z.string().describe("Amount to approve (in token units). Use '0' to revoke approval."),
          network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
        },
        annotations: {
          title: "Approve Token Spending",
          readOnlyHint: false,
          destructiveHint: false,
          idempotentHint: false,
          openWorldHint: true
        }
      },
      async ({ tokenAddress, spenderAddress, amount, network = "ethereum" }) => {
        try {
          const privateKey = getConfiguredPrivateKey();
          const senderAddress = getWalletAddressFromKey();
          const txHash = await services.approveERC20(tokenAddress as Address, spenderAddress as Address, amount, privateKey, network);
          return {
            content: [{
              type: "text",
              text: JSON.stringify({
                network,
                tokenAddress,
                owner: senderAddress,
                spender: spenderAddress,
                approvalAmount: amount,
                txHash,
                message: "Approval transaction sent. Use get_transaction_receipt to check confirmation."
              }, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{ type: "text", text: `Error approving token spending: ${error instanceof Error ? error.message : String(error)}` }],
            isError: true
          };
        }
      }
  • Core implementation of ERC20 approve logic: resolves addresses, fetches token decimals/symbol, parses amount, and sends approve transaction using viem walletClient.writeContract
    export async function approveERC20(
      tokenAddressOrEns: string,
      spenderAddressOrEns: string,
      amount: string,
      privateKey: string | `0x${string}`,
      network: string = 'ethereum'
    ): Promise<{
      txHash: Hash;
      amount: {
        raw: bigint;
        formatted: string;
      };
      token: {
        symbol: string;
        decimals: number;
      };
    }> {
      // Resolve ENS names to addresses if needed
      const tokenAddress = await resolveAddress(tokenAddressOrEns, network) as Address;
      const spenderAddress = await resolveAddress(spenderAddressOrEns, network) as Address;
      
      // Ensure the private key has 0x prefix
      const formattedKey = typeof privateKey === 'string' && !privateKey.startsWith('0x')
        ? `0x${privateKey}` as `0x${string}`
        : privateKey as `0x${string}`;
      
      // Get token details
      const publicClient = getPublicClient(network);
      const contract = getContract({
        address: tokenAddress,
        abi: erc20TransferAbi,
        client: publicClient,
      });
      
      // Get token decimals and symbol
      const decimals = await contract.read.decimals();
      const symbol = await contract.read.symbol();
      
      // Parse the amount with the correct number of decimals
      const rawAmount = parseUnits(amount, decimals);
      
      // Create wallet client for sending the transaction
      const walletClient = getWalletClient(formattedKey, network);
      
      // Send the transaction
      const hash = await walletClient.writeContract({
        address: tokenAddress,
        abi: erc20TransferAbi,
        functionName: 'approve',
        args: [spenderAddress, rawAmount],
        account: walletClient.account!,
        chain: walletClient.chain
      });
      
      return {
        txHash: hash,
        amount: {
          raw: rawAmount,
          formatted: amount
        },
        token: {
          symbol,
          decimals
        }
      };
    }
  • Zod input schema for the approve_token_spending tool parameters
      tokenAddress: z.string().describe("The ERC20 token contract address"),
      spenderAddress: z.string().describe("The address that will be allowed to spend tokens (usually a contract)"),
      amount: z.string().describe("Amount to approve (in token units). Use '0' to revoke approval."),
      network: z.string().optional().describe("Network name or chain ID. Defaults to Ethereum mainnet.")
    },
  • ERC20 ABI snippet used for approve, decimals, and symbol reads/writes in the approveERC20 function
    const erc20TransferAbi = [
      {
        inputs: [
          { type: 'address', name: 'to' },
          { type: 'uint256', name: 'amount' }
        ],
        name: 'transfer',
        outputs: [{ type: 'bool' }],
        stateMutability: 'nonpayable',
        type: 'function'
      },
      {
        inputs: [
          { type: 'address', name: 'spender' },
          { type: 'uint256', name: 'amount' }
        ],
        name: 'approve',
        outputs: [{ type: 'bool' }],
        stateMutability: 'nonpayable',
        type: 'function'
      },
      {
        inputs: [],
        name: 'decimals',
        outputs: [{ type: 'uint8' }],
        stateMutability: 'view',
        type: 'function'
      },
      {
        inputs: [],
        name: 'symbol',
        outputs: [{ type: 'string' }],
        stateMutability: 'view',
        type: 'function'
      }
    ] as const;
Behavior3/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 explains the purpose and context but doesn't mention security implications beyond what's in the schema, potential gas costs, transaction finality, or what happens if the approval fails. It does add useful context about DeFi protocol requirements, but lacks comprehensive behavioral details for a sensitive operation.

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 perfectly concise with two sentences that each earn their place. The first sentence states the core purpose, and the second provides crucial usage context. There's zero waste or redundancy, and it's front-loaded with the essential information.

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

Completeness3/5

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

For a sensitive blockchain transaction tool with 5 parameters, no annotations, and no output schema, the description provides adequate purpose and usage context but lacks details about transaction behavior, security warnings beyond the schema, or expected outcomes. It's complete enough for basic understanding but insufficient for comprehensive agent guidance given the tool's complexity and sensitivity.

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?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description doesn't add specific parameter semantics beyond what's in the schema, but it provides important context about unlimited approval ('Use a very large number for unlimited approval' is in the schema, not description). Baseline would be 3, but the description's DeFi context helps interpret parameter usage, warranting a 4.

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 ('Approve another address to spend your ERC20 tokens') and distinguishes it from sibling tools by specifying this is for token spending approvals rather than transfers, balances, or other blockchain operations. It explicitly mentions the resource (ERC20 tokens) and verb (approve spending).

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?

The description provides explicit usage context: 'This is often required before interacting with DeFi protocols.' This gives clear guidance on when to use this tool versus alternatives like transfer operations or balance checks, and it explains the prerequisite nature of token approvals for DeFi interactions.

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/mcpdotdirect/evm-mcp-server'

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