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");
    }
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. 'Sell a Pump.fun token' implies a financial transaction with potential consequences, but doesn't disclose critical behaviors like whether this is irreversible, requires authentication, has rate limits, or what happens on failure. The description mentions no behavioral traits beyond the basic action, leaving significant gaps for a financial tool.

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 exactly what the tool does without any wasted words. It's appropriately sized for a straightforward financial transaction tool and is perfectly front-loaded with the core action. Every word earns its place in conveying the essential purpose.

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 happens after selling (e.g., where funds go, confirmation process), error conditions, or return values. The combination of a potentially destructive financial operation with minimal contextual information creates 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 the schema already fully documents all 4 parameters. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain parameter relationships, provide examples, or clarify edge cases. This meets the baseline for high schema coverage but doesn't add value beyond the structured data.

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 ('sell') and resource ('Pump.fun token'), making the purpose immediately understandable. It distinguishes this from sibling tools like 'buy-token' and 'create-token' by specifying the opposite financial transaction. However, it doesn't specify what type of token (e.g., cryptocurrency) or platform context beyond 'Pump.fun', which slightly limits specificity.

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 tokens to sell, account setup, or market conditions. While the tool name implies it's for selling tokens, there's no explicit context about when this operation is appropriate versus using 'buy-token' or other financial tools.

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

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