Skip to main content
Glama

sell-token

Execute token sales on the Pump.fun platform by specifying token address and sell amount. Manage transactions with configurable slippage tolerance and account selection.

Instructions

Sell a Pump.fun token

Input Schema

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

Implementation Reference

  • The core handler function that executes the sell-token logic: initializes SDK, handles account keypairs, checks balances, calls sdk.sell(), and returns results including tx signature.
    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-243 (registration)
    MCP server registration of the 'sell-token' tool, including name, description, input handler wrapper 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 input schema defining 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 sellToken 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 but offers minimal behavioral insight. 'Sell' implies a destructive/mutative operation, but it doesn't disclose critical traits like authentication requirements, transaction costs, rate limits, irreversible nature, or what happens on failure. This leaves significant gaps for an agent to understand the tool's behavior safely.

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, direct sentence with zero wasted words. It front-loads the core action and resource, making it immediately scannable and efficient. Every word earns its place by conveying essential purpose without redundancy or fluff.

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 4 parameters, no annotations, and no output schema, the description is insufficient. It lacks context on safety (e.g., irreversible), expected outputs (e.g., transaction hash), error conditions, or integration with sibling tools like checking balances first. The high parameter count and mutation nature demand more completeness than provided.

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 itself. The description adds no additional meaning beyond implying 'tokenAddress' refers to a Pump.fun token and 'sellAmount' is for selling. This meets the baseline for high schema coverage but doesn't enhance understanding (e.g., explaining token standards or slippage implications).

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 ('a Pump.fun token'), making the purpose immediately understandable. It distinguishes from siblings like 'buy-token' and 'create-token' by specifying the opposite transaction type. However, it doesn't specify what 'sell' entails in this context (e.g., on-chain transaction, market order), which prevents a perfect score.

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 (e.g., needing tokens to sell), contrast with 'buy-token' for opposite actions, or indicate when other tools like 'get-account-balance' or 'get-token-info' should be consulted first. Usage is implied but not explicitly stated.

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