Skip to main content
Glama

buy-token

Purchase Pump.fun meme tokens on Solana by specifying the token address and SOL amount. Execute transactions with configurable slippage tolerance and account selection.

Instructions

Buy a Pump.fun token

Input Schema

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

Implementation Reference

  • Core handler function that performs the token buy operation using PumpFunSDK, handles account management, balance checks, and transaction execution.
    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 input parameters for the buy-token tool.
    {
      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)
    MCP tool registration for 'buy-token', including description, input schema, and wrapper handler that delegates to buyToken function.
    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 result of a buyToken operation into a human-readable string.
    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");
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. 'Buy' implies a financial transaction with real-world consequences, but the description doesn't mention critical behaviors: that this likely spends real SOL, requires wallet authorization, may have transaction fees, or what happens on failure. For a financial tool with zero annotation coverage, this is a significant gap in safety and operational transparency.

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 that states the core purpose without any wasted words. It's appropriately sized for a tool with a clear primary function and doesn't bury important information. Every word earns its place in communicating the essential action.

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 financial transaction tool with no annotations and no output schema, the description is insufficiently complete. It doesn't explain what the tool returns (transaction hash? success status?), error conditions, authorization requirements, or financial implications. The combination of high-stakes operation with minimal behavioral disclosure creates significant gaps for an AI agent.

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 what's in the schema. The baseline score of 3 reflects adequate parameter documentation through the schema alone, with no value added by the description.

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 ('Buy') and target resource ('a Pump.fun token'), making the purpose immediately understandable. It distinguishes from siblings like 'sell-token' by specifying the opposite action, but doesn't differentiate from 'create-token' which is also a token-related operation. The description is specific enough to understand what the tool does without being tautological.

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 no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (like needing sufficient SOL balance), when not to use it (e.g., for tokens that aren't on Pump.fun), or how it relates to sibling tools like 'sell-token' or 'create-token'. The agent must infer usage context from the tool name alone.

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

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