Skip to main content
Glama

pancakeSwap

Swap tokens on Binance Smart Chain using structured MCP integration for secure transactions with specified input and output tokens.

Instructions

Swap tokens in BSC chain via PancakeSwap

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
amountYes
inputTokenYes
outputTokenYes

Implementation Reference

  • Core handler function that executes the PancakeSwap token exchange using SmartRouter, including token resolution, approval, quote fetching, and transaction submission.
    export const pancakeSwap = async ({
      account,
      inputToken,
      outputToken,
      amount,
    }: {
      // privateKey: string;
      amount: string;
      inputToken: string;
      outputToken: string;
      account: PrivateKeyAccount;
    }): Promise<Hash> => {
    
      const chainId = ChainId.BSC
    
    
      let currencyA = await getToken(inputToken);
      let currencyB = await getToken(outputToken);
      let amountDecimal = currencyA.decimals;
    
      const parseAmountIn = parseUnits(amount, amountDecimal);
      const amountValue = CurrencyAmount.fromRawAmount(currencyA, parseAmountIn)
    
      if (!currencyA.isNative) {
        const TokenContract = getContract({
          address: currencyA.address,
          abi: erc20Abi,
          client: {
            wallet: walletClient(account),
            public: publicClient,
          },
        });
        if (
          !TokenContract.write ||
          !TokenContract.write.approve ||
          !TokenContract.read.allowance
        ) {
          throw new Error("Unable to Swap Tokens");
        }
    
        amountDecimal = await TokenContract.read.decimals();
    
        const smartRouterAddress = SMART_ROUTER_ADDRESSES[ChainId.BSC]
        const allowance = await TokenContract.read.allowance([account.address, smartRouterAddress]) as bigint
        if (allowance < parseAmountIn) {
          const approveResult = await TokenContract.write.approve([smartRouterAddress, parseAmountIn])
    
          await publicClient.waitForTransactionReceipt({
            hash: approveResult,
          });
        }
      }
    
      const quoteProvider = SmartRouter.createQuoteProvider({
        onChainProvider: () => publicClient,
      })
      const v3SubgraphClient = new GraphQLClient('https://api.thegraph.com/subgraphs/name/pancakeswap/exchange-v3-bsc1')
      const v2SubgraphClient = new GraphQLClient('https://proxy-worker-api.pancakeswap.com/bsc-exchange1')
    
      const [v2Pools, v3Pools] = await Promise.all([
        SmartRouter.getV3CandidatePools({
          onChainProvider: () => publicClient,
          // @ts-ignore
          subgraphProvider: () => v3SubgraphClient,
          currencyA: currencyA,
          currencyB: currencyB,
          subgraphFallback: false,
        }),
        SmartRouter.getV2CandidatePools({
          onChainProvider: () => publicClient,
          // @ts-ignore
          v2SubgraphProvider: () => v2SubgraphClient,
          // @ts-ignore
          v3SubgraphProvider: () => v3SubgraphClient,
          currencyA: currencyA,
          currencyB: currencyB,
        }),
      ])
    
      const pools = [...v2Pools, ...v3Pools]
      const trade = await SmartRouter.getBestTrade(amountValue, currencyB, TradeType.EXACT_INPUT, {
        gasPriceWei: () => publicClient.getGasPrice(),
        maxHops: 2,
        maxSplits: 2,
        poolProvider: SmartRouter.createStaticPoolProvider(pools),
        quoteProvider,
        quoterOptimization: true,
        
      }) as SmartRouterTrade<TradeType>
    
    
      const { value, calldata } = SwapRouter.swapCallParameters(trade, {
        recipient: account.address,
        slippageTolerance: new Percent(500, 10000),
      })
    
      const tx = {
        account: account.address,
        // @ts-ignore
        to: SMART_ROUTER_ADDRESSES[chainId],
        data: calldata,
        value: hexToBigInt(value),
      };
      const gasEstimate = await publicClient.estimateGas(tx);
    
      const calculateGasMargin = (value: bigint, margin = 1000n): bigint => {
        return (value * (10000n + margin)) / 10000n;
      };
    
      const txHash = await walletClient(account).sendTransaction({
        account: account,
        chainId,
        // @ts-ignore
        to: SMART_ROUTER_ADDRESSES[chainId],
        data: calldata,
        value: hexToBigInt(value),
        gas: calculateGasMargin(gasEstimate),
      });
      return txHash;
    };
  • Helper to resolve token symbol or address to a Token object, fetching metadata from PancakeSwap API or on-chain.
    export const getToken = async (
      token: string,
    ) => {
      if (token.toUpperCase() === "BNB") {
        return Native.onChain(ChainId.BSC)
      }
      let address = token.toLowerCase()
      let decimal;
    
      const url = "https://tokens.pancakeswap.finance/pancakeswap-extended.json";
    
      const resp = await fetch(url);
      const data = await resp.json();
      let tokens = data.tokens
      let symbol;
    
      if (!isAddress(address)) {
        const tokenInfo = tokens.find((item: any) => item.symbol.toLowerCase() === address)
        if (!tokenInfo) {
          throw new Error("Token not found");
        }
        address = tokenInfo.address
        decimal = tokenInfo.decimals
        symbol = tokenInfo.symbol
      } else {
        const tokenInfo = tokens.find((item: any) => item.address.toLowerCase() === address)
        if (!tokenInfo) {
          
          const contract = getContract({
            address: address as Address,
            abi: bep20abi,
            client: publicClient,
          });
    
          decimal = await contract.read.decimals();
          symbol = await contract.read.symbol();
        } else {
            
          decimal = tokenInfo.decimals
          symbol = tokenInfo.symbol
        }
      }
      
      return new Token(
        ChainId.BSC,
        address as Hex,
        decimal,
        symbol,
      )
    
    
    }
  • Registers the 'PancakeSwap_Token_Exchange' tool on the MCP server, providing schema and a thin wrapper around the core pancakeSwap handler.
    export function registerPancakeSwap(server: McpServer) {
      server.tool("PancakeSwap_Token_Exchange", "💱Exchange tokens on BNBChain using PancakeSwap DEX", {
          inputToken: z.string(),
          outputToken: z.string(),
          amount: z.string(),
        },
        async ({ inputToken, outputToken, amount }) => {
          let txHash = undefined;
          try {
            const account = await getAccount();
            txHash = await pancakeSwap({
              account,
              inputToken,
              outputToken,
              amount,
            });
            const txUrl = await checkTransactionHash(txHash)
            
            return {
              content: [
                {
                  type: "text",
                  text: `PancakeSwap transaction sent successfully. ${txUrl}`,
                  url: txUrl,
                },
              ],
            };
          } catch (error) {
            const errorMessage =
              error instanceof Error ? error.message : String(error);
            const txUrl = buildTxUrl(txHash);
            return {
              content: [
                {
                  type: "text",
                  text: `transaction failed: ${errorMessage}`,
                  url: txUrl,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • Input schema for the tool using Zod validation for inputToken, outputToken, and amount.
    server.tool("PancakeSwap_Token_Exchange", "💱Exchange tokens on BNBChain using PancakeSwap DEX", {
        inputToken: z.string(),
        outputToken: z.string(),
        amount: z.string(),
      },
  • src/main.ts:9-29 (registration)
    Top-level import and registration call for the PancakeSwap tool in the main server setup.
    import { registerPancakeSwap } from "./tools/pancakeSwap.js";
    import { registerGetWalletInfo } from "./tools/getWalletInfo.js";
    import { registerBuyMemeToken } from "./tools/buyMemeToken.js";
    import { registerSellMemeToken } from "./tools/sellMemeToken.js";
    import { registerPancakeAddLiquidity } from "./tools/pancakeAddLiquidity.js";
    import { registerPancakeMyPosition } from "./tools/pancakeMyPosition.js";
    import { registerPancakeRemovePosition } from "./tools/pancakeRemovePosition.js";
    import { registerGoplusSecurityCheck } from "./tools/goplusSecurityCheck.js";
    import { registerQueryMemeTokenDetails } from "./tools/queryMemeTokenDetails.js";
    
    // Main server entry
    export async function main() {
        const server = new McpServer({
            name: "bsc-mcp",
            version: "1.0.0"
        });
    
        // Register all tools
        registerTransferNativeToken(server);
        registerTransferBEP20Token(server);
        registerPancakeSwap(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 but only states what the tool does without disclosing behavioral traits. It doesn't mention whether this is a read-only or destructive operation, what permissions or authentication are needed, potential rate limits, transaction costs, or what happens on failure. The description is functional but lacks critical operational context.

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 - a single sentence that states the core functionality without any unnecessary words. It's front-loaded with the essential information and wastes no space on redundant or verbose explanations.

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 token swapping tool with 3 required parameters, no annotations, no output schema, and 0% schema description coverage, the description is insufficient. It explains what the tool does at a high level but provides no guidance on usage, no parameter explanations, no behavioral context, and no information about what the tool returns or how to interpret results.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description provides no information about parameters beyond what's implied by the tool name. With 0% schema description coverage and 3 required parameters, the description fails to explain what 'amount', 'inputToken', and 'outputToken' represent, their expected formats, or any constraints. The baseline would be lower than 3 given the complete lack of parameter documentation.

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 resource/context ('in BSC chain via PancakeSwap'), which distinguishes it from generic token transfer tools. However, it doesn't explicitly differentiate from sibling tools like 'buyMemeToken' or 'sellMemeToken' that might also involve swapping operations.

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 minimal context ('in BSC chain via PancakeSwap') but offers no guidance on when to use this tool versus alternatives like 'buyMemeToken', 'sellMemeToken', or 'transferBEP20Token'. There's no mention of prerequisites, constraints, or typical use cases.

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/TermiX-official/bsc-mcp'

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