Skip to main content
Glama
noahgsolomon

Pump.fun MCP Server

by noahgsolomon

sell-token

Execute token sales on the Pump.fun platform by specifying the token address, amount, and slippage tolerance through the MCP server for Solana-based transactions.

Instructions

Sell a Pump.fun token

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
accountNameNoName of the account to usedefault
sellAmountYesAmount of tokens to sell (0 for all)
slippageBasisPointsNoSlippage tolerance in basis points (1% = 100)
tokenAddressYesThe token's mint address

Implementation Reference

  • The core handler function that executes the sell token logic: initializes SDK, handles keypairs, checks balances, calls sdk.sell, and returns transaction results.
    export async function sellToken(
      tokenAddress: string,
      sellAmount: number = 0,
      accountName: string = "default",
      slippageBasisPoints: number = 100
    ) {
      try {
        console.error("Starting sellToken function");
        const { sdk, connection } = initializeSDK();
        console.error("SDK initialized");
    
        const keysFolder = path.resolve(rootDir, ".keys");
        console.error(`Using keys folder path relative to script: ${keysFolder}`);
    
        console.error(
          `Checking if keys folder exists: ${fs.existsSync(keysFolder)}`
        );
        if (!fs.existsSync(keysFolder)) {
          console.error(`Creating keys folder: ${keysFolder}`);
          try {
            fs.mkdirSync(keysFolder, { recursive: true });
            console.error(`Keys folder created successfully`);
          } catch (mkdirError: any) {
            console.error(`Error creating keys folder:`, mkdirError);
            return {
              success: false,
              error: `Error creating keys folder: ${
                mkdirError.message || JSON.stringify(mkdirError)
              }`,
            };
          }
        }
    
        console.error(`Getting or creating keypair from folder: ${keysFolder}`);
        const account = getOrCreateKeypair(keysFolder, accountName);
        console.log(`Using account: ${account.publicKey.toString()}`);
    
        const mintPublicKey = new PublicKey(tokenAddress);
        console.log(`Token address: ${tokenAddress}`);
    
        const tokenBalance = await getSPLBalance(
          connection,
          mintPublicKey,
          account.publicKey
        );
        console.log(`Current token balance: ${tokenBalance}`);
    
        if (!tokenBalance || tokenBalance === 0) {
          const errorMessage = `No tokens to sell. Account ${account.publicKey.toString()} has 0 tokens of ${tokenAddress}.`;
          console.error(errorMessage);
          return { success: false, error: errorMessage };
        }
    
        const amountToSell =
          sellAmount === 0 ? tokenBalance : Math.min(sellAmount, tokenBalance);
        console.log(`Amount to sell: ${amountToSell}`);
    
        const initialSolBalance = await connection.getBalance(account.publicKey);
        console.log(
          `Initial SOL balance: ${initialSolBalance / LAMPORTS_PER_SOL} SOL`
        );
    
        console.log(`Selling ${amountToSell} tokens...`);
        const result = await sdk.sell(
          account,
          mintPublicKey,
          BigInt(amountToSell * Math.pow(10, 6)),
          BigInt(slippageBasisPoints),
          DEFAULT_PRIORITY_FEES
        );
    
        if (!result.success) {
          console.error(`Failed to sell 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 newSolBalance = await connection.getBalance(account.publicKey);
        console.log(`New SOL balance: ${newSolBalance / LAMPORTS_PER_SOL} SOL`);
    
        const solReceived = (newSolBalance - initialSolBalance) / LAMPORTS_PER_SOL;
        console.log(`SOL received: ${solReceived} SOL`);
    
        const newTokenBalance =
          (await getSPLBalance(connection, mintPublicKey, account.publicKey)) || 0;
        console.log(`New token balance: ${newTokenBalance}`);
    
        return {
          success: true,
          tokenAddress,
          tokensSold: amountToSell,
          solReceived,
          newTokenBalance,
          signature: result.signature,
          pumpfunUrl: `https://pump.fun/${tokenAddress}`,
        };
      } catch (error: any) {
        console.error("Error selling 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 };
      }
    }
  • src/index.ts:195-242 (registration)
    Registers the 'sell-token' tool with MCP server, including input schema, description, and wrapper handler that calls the core sellToken function.
    server.tool(
      "sell-token",
      "Sell a Pump.fun token",
      {
        tokenAddress: z.string().describe("The token's mint address"),
        sellAmount: z
          .number()
          .min(0)
          .describe("Amount of tokens to sell (0 for all)"),
        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, sellAmount, accountName, slippageBasisPoints }) => {
        try {
          console.error(
            `Selling token: ${tokenAddress}, amount: ${
              sellAmount === 0 ? "ALL" : sellAmount
            }`
          );
    
          const result = await sellToken(
            tokenAddress,
            sellAmount,
            accountName,
            slippageBasisPoints
          );
    
          const formattedResult = formatSellResult(result);
    
          return createMcpResponse(formattedResult);
        } catch (error: any) {
          console.error("Error selling token:", error);
          return {
            content: [
              {
                type: "text" as const,
                text: `Error selling token: ${error?.message || "Unknown error"}`,
              },
            ],
          };
        }
      }
  • Zod schema defining input parameters for the sell-token tool.
    {
      tokenAddress: z.string().describe("The token's mint address"),
      sellAmount: z
        .number()
        .min(0)
        .describe("Amount of tokens to sell (0 for all)"),
      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)"),
    },
  • Helper function to format the sell token result into a human-readable string.
    export function formatSellResult(
      result: ReturnType<typeof sellToken> extends Promise<infer T> ? T : never
    ) {
      if (!result.success) {
        return `Error selling token: ${result.error}`;
      }
    
      return [
        `Successfully sold token!`,
        `Token Address: ${result.tokenAddress}`,
        `Tokens Sold: ${result.tokensSold}`,
        `SOL Received: ${result.solReceived} SOL`,
        `Remaining Token Balance: ${result.newTokenBalance}`,
        `Transaction Signature: ${result.signature}`,
        `Pump.fun URL: ${result.pumpfunUrl}`,
      ].join("\n");
    }
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/noahgsolomon/pumpfun-mcp-server'

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