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");
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed2 schema fields changedv1.0.0
    • addedInput schema / $schema
      Added value: +"http://json-schema.org/draft-07/schema#"
    • addedInput schema / additionalProperties
      Added value: +false
  2. First observed

TDQS

C2.9/5.0
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 disclosing behavioral traits like required permissions, transaction costs, rate limits, or what happens on failure. 'Buy' implies a financial transaction, but critical details like confirmation steps or irreversible effects are missing.

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, front-loading the core action. It's appropriately sized for the tool's complexity, 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?

Given no annotations, no output schema, and a financial transaction tool with 4 parameters, the description is incomplete. It lacks essential context like return values, error handling, or behavioral nuances, leaving significant gaps for safe and effective use.

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. The description adds no additional meaning beyond implying token purchase, which aligns with schema but doesn't enhance understanding of parameter interactions or usage context.

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 resource ('a Pump.fun token'), providing specific purpose. However, it doesn't differentiate from sibling 'sell-token' beyond the verb direction, missing explicit distinction about when each is appropriate.

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 on when to use this tool versus alternatives like 'sell-token' or 'create-token' is provided. The description assumes context but offers no explicit usage context, prerequisites, or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.