Skip to main content
Glama

buy-token

Purchase Solana meme tokens on Pump.fun by specifying the token address and desired SOL amount. Execute trades with configurable slippage tolerance using your preferred account.

Instructions

Buy a Pump.fun token

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
accountNameNoName of the account to usedefault
buyAmountYesAmount to buy in SOL
slippageBasisPointsNoSlippage tolerance in basis points (1% = 100)
tokenAddressYesThe token's mint address

Implementation Reference

  • The core handler function that implements the logic for buying tokens on Pump.fun. It handles account management, balance checks, executes the buy transaction using PumpFunSDK.buy(), and returns the result including tokens purchased and transaction signature.
    export async function buyToken( tokenAddress: string, buyAmount: number, accountName: string = "default", slippageBasisPoints: number = 100 ) { try { const { sdk, connection } = initializeSDK(); const keysFolder = path.resolve(rootDir, ".keys"); if (!fs.existsSync(keysFolder)) { try { fs.mkdirSync(keysFolder, { recursive: true }); } catch (mkdirError: any) { console.error(`Error creating keys folder:`, mkdirError); return { success: false, error: `Error creating keys folder: ${ mkdirError.message || JSON.stringify(mkdirError) }`, }; } } const account = getOrCreateKeypair(keysFolder, accountName); console.log(`Using account: ${account.publicKey.toString()}`); const balance = await connection.getBalance(account.publicKey); console.log(`Account balance: ${balance / LAMPORTS_PER_SOL} SOL`); const requiredBalance = buyAmount * LAMPORTS_PER_SOL + 0.001 * LAMPORTS_PER_SOL; console.log(`Required balance: ${requiredBalance / LAMPORTS_PER_SOL} SOL`); if (balance < requiredBalance) { const errorMessage = `Insufficient SOL balance. Account ${account.publicKey.toString()} has ${ balance / LAMPORTS_PER_SOL } SOL, but needs at least ${ requiredBalance / LAMPORTS_PER_SOL } SOL. Please send SOL to this address and try again.`; console.error(errorMessage); return { success: false, error: errorMessage }; } const mintPublicKey = new PublicKey(tokenAddress); console.log(`Token address: ${tokenAddress}`); const initialTokenBalance = (await getSPLBalance(connection, mintPublicKey, account.publicKey)) || 0; console.log(`Initial token balance: ${initialTokenBalance}`); console.log(`Buying ${buyAmount} SOL worth of tokens...`); const result = await sdk.buy( account, mintPublicKey, BigInt(buyAmount * LAMPORTS_PER_SOL), BigInt(slippageBasisPoints), DEFAULT_PRIORITY_FEES ); if (!result.success) { console.error(`Failed to buy token:`, result.error); return { success: false, error: result.error ? typeof result.error === "object" ? JSON.stringify(result.error) : result.error : "Unknown error", }; } console.log(`Transaction successful: ${result.signature}`); const newTokenBalance = (await getSPLBalance(connection, mintPublicKey, account.publicKey)) || 0; console.log(`New token balance: ${newTokenBalance}`); const tokensPurchased = newTokenBalance - initialTokenBalance; console.log(`Tokens purchased: ${tokensPurchased}`); return { success: true, tokenAddress, amountSpent: buyAmount, tokensPurchased, newBalance: newTokenBalance, signature: result.signature, pumpfunUrl: `https://pump.fun/${tokenAddress}`, }; } catch (error: any) { console.error("Error buying token:", error); console.error("Error stack:", error.stack); let errorMessage = "Unknown error"; if (error) { if (typeof error === "object") { if (error.message) { errorMessage = error.message; } else { try { errorMessage = JSON.stringify(error); } catch (e) { errorMessage = "Error object could not be stringified"; } } } else { errorMessage = String(error); } } return { success: false, error: errorMessage }; } }
  • Zod schema defining the input parameters for the buy-token tool: tokenAddress, buyAmount, accountName (default 'default'), and slippageBasisPoints (default 100).
    tokenAddress: z.string().describe("The token's mint address"), buyAmount: z.number().min(0.0001).describe("Amount to buy in SOL"), accountName: z .string() .default("default") .describe("Name of the account to use"), slippageBasisPoints: z .number() .default(100) .describe("Slippage tolerance in basis points (1% = 100)"), },
  • src/index.ts:152-193 (registration)
    Registration of the 'buy-token' MCP tool using server.tool(), including name, description, input schema, and a wrapper handler that invokes the core buyToken function and formats the MCP response.
    server.tool( "buy-token", "Buy a Pump.fun token", { tokenAddress: z.string().describe("The token's mint address"), buyAmount: z.number().min(0.0001).describe("Amount to buy in SOL"), accountName: z .string() .default("default") .describe("Name of the account to use"), slippageBasisPoints: z .number() .default(100) .describe("Slippage tolerance in basis points (1% = 100)"), }, async ({ tokenAddress, buyAmount, accountName, slippageBasisPoints }) => { try { console.error(`Buying token: ${tokenAddress}, amount: ${buyAmount} SOL`); const result = await buyToken( tokenAddress, buyAmount, accountName, slippageBasisPoints ); const formattedResult = formatBuyResult(result); return createMcpResponse(formattedResult); } catch (error: any) { console.error("Error buying token:", error); return { content: [ { type: "text" as const, text: `Error buying token: ${error?.message || "Unknown error"}`, }, ], }; } } );
  • Helper function to format the output of the buyToken function into a human-readable string for MCP responses.
    export function formatBuyResult( result: ReturnType<typeof buyToken> extends Promise<infer T> ? T : never ) { if (!result.success) { return `Error buying token: ${result.error}`; } return [ `Successfully bought token!`, `Token Address: ${result.tokenAddress}`, `Amount Spent: ${result.amountSpent} SOL`, `Tokens Purchased: ${result.tokensPurchased}`, `New Balance: ${result.newBalance}`, `Transaction Signature: ${result.signature}`, `Pump.fun URL: ${result.pumpfunUrl}`, ].join("\n"); }

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/dexoryn/pumpfun-mcp-server'

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