Skip to main content
Glama

swap_tokens

Execute token swaps on SailFish DEX by specifying input/output token addresses, amounts, slippage tolerance, and fees using the sender's private key for secure transactions.

Instructions

Swap tokens on SailFish DEX (token to token)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
amountInYesAmount of input token to swap
feeNoFee tier (100=0.01%, 500=0.05%, 3000=0.3%, 10000=1%)
privateKeyYesPrivate key of the sender wallet
slippagePercentageNoSlippage tolerance percentage (default: 0.5)
tokenInYesAddress of the input token
tokenOutYesAddress of the output token

Implementation Reference

  • MCP tool handler for 'swap_tokens': validates input parameters and calls the swapExactTokensForTokens helper function from swap module, returning the transaction result as JSON.
    case 'swap_tokens': {
      if (!args.privateKey || typeof args.privateKey !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Private key is required');
      }
      
      if (!args.tokenIn || typeof args.tokenIn !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Input token address is required');
      }
      
      if (!args.tokenOut || typeof args.tokenOut !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Output token address is required');
      }
      
      if (!args.amountIn || typeof args.amountIn !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'Input amount is required');
      }
      
      const slippagePercentage = typeof args.slippagePercentage === 'number' ? args.slippagePercentage : 0.5;
      const fee = typeof args.fee === 'number' ? args.fee : 3000; // Default to 0.3%
      
      const result = await swap.swapExactTokensForTokens(
        args.privateKey,
        args.tokenIn,
        args.tokenOut,
        args.amountIn,
        slippagePercentage
      );
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • src/index.ts:517-549 (registration)
    Registration of the 'swap_tokens' tool in the MCP server's list of tools, including name, description, and input schema definition.
    {
      name: 'swap_tokens',
      description: 'Swap tokens on SailFish DEX (token to token)',
      inputSchema: {
        type: 'object',
        properties: {
          privateKey: {
            type: 'string',
            description: 'Private key of the sender wallet',
          },
          tokenIn: {
            type: 'string',
            description: 'Address of the input token',
          },
          tokenOut: {
            type: 'string',
            description: 'Address of the output token',
          },
          amountIn: {
            type: 'string',
            description: 'Amount of input token to swap',
          },
          slippagePercentage: {
            type: 'number',
            description: 'Slippage tolerance percentage (default: 0.5)',
          },
          fee: {
            type: 'number',
            description: 'Fee tier (100=0.01%, 500=0.05%, 3000=0.3%, 10000=1%)',
          },
        },
        required: ['privateKey', 'tokenIn', 'tokenOut', 'amountIn'],
      },
  • Input schema definition for the 'swap_tokens' tool, specifying parameters like privateKey, token addresses, amount, slippage, and fee.
    inputSchema: {
      type: 'object',
      properties: {
        privateKey: {
          type: 'string',
          description: 'Private key of the sender wallet',
        },
        tokenIn: {
          type: 'string',
          description: 'Address of the input token',
        },
        tokenOut: {
          type: 'string',
          description: 'Address of the output token',
        },
        amountIn: {
          type: 'string',
          description: 'Amount of input token to swap',
        },
        slippagePercentage: {
          type: 'number',
          description: 'Slippage tolerance percentage (default: 0.5)',
        },
        fee: {
          type: 'number',
          description: 'Fee tier (100=0.01%, 500=0.05%, 3000=0.3%, 10000=1%)',
        },
      },
      required: ['privateKey', 'tokenIn', 'tokenOut', 'amountIn'],
    },
  • Core helper function swapExactTokensForTokens that implements the token swap logic: gets quote, approves tokens, executes swap on Uniswap V3 router (direct or multi-hop), returns tx details.
    export async function swapExactTokensForTokens(
      privateKey: string,
      tokenIn: string,
      tokenOut: string,
      amountIn: string,
      slippagePercentage: number = 0.5 // Default 0.5% slippage
    ): Promise<{
      hash: string;
      from: string;
      amountIn: string;
      amountOut: string;
      tokenIn: string;
      tokenOut: string;
      tokenInSymbol: string;
      tokenOutSymbol: string;
      route: routes.RouteInfo;
    }> {
      try {
        const provider = blockchain.getProvider();
        const wallet = new ethers.Wallet(privateKey, provider);
        const fromAddress = wallet.address;
        
        // Get quote and route information
        const quote = await getSwapQuote(tokenIn, tokenOut, amountIn, slippagePercentage);
        const route = quote.route;
        
        // Convert amount to token units
        const amountInWei = ethers.parseUnits(amountIn, quote.tokenInDecimals);
        const minAmountOut = ethers.getBigInt(quote.minimumAmountOut);
        
        // Approve router to spend tokens
        const tokenContract = new ethers.Contract(tokenIn, ERC20_ABI, wallet);
        const approveTx = await tokenContract.approve(CONTRACTS.SwapRouter, amountInWei);
        await approveTx.wait();
        
        // Create swap router contract
        const swapRouter = new ethers.Contract(CONTRACTS.SwapRouter, SWAP_ROUTER_ABI, wallet);
        
        // Execute swap based on route type
        const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // 20 minutes from now
        let tx;
        
        if (route.type === 'direct') {
          // Direct route (single hop)
          const fee = parseInt(route.path[0].feeTier);
          
          const swapParams = {
            tokenIn,
            tokenOut,
            fee,
            recipient: fromAddress,
            deadline,
            amountIn: amountInWei,
            amountOutMinimum: minAmountOut,
            sqrtPriceLimitX96: 0 // No price limit
          };
          
          tx = await swapRouter.exactInputSingle(swapParams);
        } else {
          // Indirect route (multi-hop)
          const intermediaryToken = route.intermediaryToken!;
          
          // Encode the path for multi-hop swap
          const path = ethers.solidityPacked(
            ['address', 'uint24', 'address', 'uint24', 'address'],
            [
              tokenIn,
              parseInt(route.path[0].feeTier),
              intermediaryToken.address,
              parseInt(route.path[1].feeTier),
              tokenOut
            ]
          );
          
          const swapParams = {
            path,
            recipient: fromAddress,
            deadline,
            amountIn: amountInWei,
            amountOutMinimum: minAmountOut
          };
          
          tx = await swapRouter.exactInput(swapParams);
        }
        
        const receipt = await tx.wait();
        
        if (!receipt) {
          throw new Error('Transaction failed');
        }
        
        return {
          hash: tx.hash,
          from: fromAddress,
          amountIn,
          amountOut: quote.formattedMinimumAmountOut,
          tokenIn,
          tokenOut,
          tokenInSymbol: quote.tokenInSymbol,
          tokenOutSymbol: quote.tokenOutSymbol,
          route
        };
      } catch (error) {
        console.error('Error swapping tokens:', error);
        throw error;
      }
    }
Behavior2/5

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

With no annotations, the description carries full burden but only states the action without behavioral details. It doesn't mention that this executes a transaction (implied by 'swap'), requires blockchain interaction, involves gas fees, risk of slippage, or returns a transaction hash. This leaves critical gaps for a financial 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 a single, efficient sentence with zero waste—it directly states the tool's purpose. It's appropriately sized and front-loaded, making it easy to parse quickly.

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 financial tool with 6 parameters, no annotations, and no output schema, the description is inadequate. It lacks details on execution behavior, error handling, return values, and risk factors like slippage or fees, leaving the agent under-informed for safe operation.

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 parameters are well-documented in the schema itself. The description adds no additional meaning beyond implying token-to-token swapping, which aligns with parameters like tokenIn and tokenOut. 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.

Purpose4/5

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

The description clearly states the action ('swap tokens') and specifies the platform ('on SailFish DEX'), with the parenthetical clarifying it's a token-to-token operation. It distinguishes from siblings like 'swap_edu_for_tokens' and 'swap_tokens_for_edu' by not mentioning EDU specifically, but doesn't explicitly contrast them.

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 'swap_edu_for_tokens', 'swap_tokens_for_edu', or 'get_swap_quote'. The description lacks context about prerequisites, such as needing token addresses or a private key, or when a quote might be needed first.

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/SailFish-Finance/educhain-ai-agent-kit'

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