Bags SDK — MCP Server

Launch a Solana token from your terminal in three steps. 46 MCP tools cover trading, fee configuration, claims, Dexscreener listing, and agent authentication — the AI client does the work.

46 Tools 4 Resources 8 Prompts npm bags-sdk-mcp API Key @ dev.bags.fm

What is this?

bags-sdk-mcp is an MCP (Model Context Protocol) server that exposes the entire Bags.fm API as tools, resources, and prompts. Any MCP-compatible AI client — Claude Desktop, Claude Code, Cursor, or custom agents — can interact with the Bags.fm ecosystem through natural language.

Key Features

  • 46 MCP tools — trading, token launches, fee management, claiming, analytics, Dexscreener, signing, scout, and more
  • Fee Config Composer — fluent builder for multi-party fee splits without raw BPS math
  • Tiered caching — 5-level TTL cache to stay within the 1,000 req/hr rate limit
  • Zero-custody — no private keys stored; all transactions returned unsigned
  • Browser wallet signing — localhost signing page connects Phantom, Solflare, Backpack, or Coinbase
  • Autonomous agent mode — dual-model orchestration with Hermes 4 + Claude Sonnet
  • Dual transport — stdio for desktop clients, Streamable HTTP for remote connections

Who is this for?

  • Token creators wanting to launch and manage tokens through conversational AI
  • Fee earners who want to track and claim fees hands-free
  • Partners building on top of Bags.fm's fee infrastructure
  • Developers integrating Bags.fm into AI-powered applications
💡 Built for the Bags.fm Hackathon. This server wraps @bagsfm/bags-sdk and the Bags.fm REST API into a single MCP interface.

Beginner's Guide

Never used MCP before? Never heard of Bags.fm? Start here.

What is MCP?

Model Context Protocol is an open standard that lets AI clients (like Claude Desktop, Claude Code, or Cursor) use external tools. Think of it as a plugin system for AI — instead of the AI only being able to chat, MCP lets it call APIs, read data, and execute actions on your behalf.

When you install an MCP server, your AI client gains new abilities. Install this server and your AI can launch tokens, check wallets, claim fees, and more — all through natural language.

What is Bags.fm?

Bags.fm is a Solana token launch and fee-share platform. Creators launch tokens with built-in fee splits — every trade generates fees that get distributed to creators, team members, and holders automatically. The platform handles the on-chain complexity so you don't have to.

Prerequisites

  • Node.js 18+ and npm 9+download here
  • A Bags.fm API key — free at dev.bags.fm
  • An MCP client — Claude Desktop, Claude Code, or Cursor
  • A Solana wallet — Phantom, Solflare, Backpack, or Coinbase Wallet (browser extension)

Your First 5 Minutes

  1. Get your API key from dev.bags.fm
  2. Run npx bags-sdk-mcp --setup (or see Installation for other options)
  3. Restart your client
  4. Type: "What's trending on Bags?"
  5. The AI calls bags_top_tokens and bags_launch_feed — you see live data from the Bags.fm ecosystem
You: "What's trending on Bags?"
Agent: calls bags_top_tokens, bags_launch_feed
Agent: Here are the top tokens by lifetime fees and recent launches...

Common Gotchas

  • Restart after config changes — MCP servers load at startup. After editing your config file, you must restart the client.
  • Wallet addresses are Base58 — Solana addresses look like 83xQKBYR4eN8..., not hex. Copy them exactly.
  • SOL vs lamports — 1 SOL = 1,000,000,000 lamports. Most tools accept SOL amounts and convert internally, but some low-level tools use lamports.
  • Two signatures per launch — launching a token requires signing the fee config transaction first, then the launch transaction. The signing page handles both.
  • No private keys needed — the server never asks for or stores your keys. You sign in your browser wallet.

Installation

One command

bashnpx bags-sdk-mcp --setup

Get your API key at dev.bags.fm. The wizard detects your MCP clients, asks for your key, and writes the config. Restart your client and you're live.

Claude Code alternative
bashclaude mcp add bags-sdk-mcp -e BAGS_API_KEY=your-key -- npx bags-sdk-mcp

Uninstall

bashnpx bags-sdk-mcp --uninstall
From source
bashgit clone https://github.com/outerheaven199X/Bags-SDK-hackathon.git
cd Bags-SDK-hackathon
cp .env.example .env   # add your BAGS_API_KEY
npm install && npm run build
npm start

Verify

bashbags-sdk-mcp --help

Configuration

The recommended way is to run npx bags-sdk-mcp --setup — it handles everything below automatically.

Manual configuration (if the wizard doesn't work)

Add this block to your MCP client's config file:

JSON{
  "mcpServers": {
    "bags-sdk-mcp": {
      "command": "npx",
      "args": ["bags-sdk-mcp"],
      "env": {
        "BAGS_API_KEY": "your-key-here"
      }
    }
  }
}

Config file locations

ClientPath
Claude Desktop (macOS)~/Library/Application Support/Claude/claude_desktop_config.json
Claude Desktop (Windows)%APPDATA%/Claude/claude_desktop_config.json
Cursor.cursor/mcp.json in project root
Claude Code.mcp.json in project root

Restart your client after saving.

💡 After setup, restart your client. The 46 tools, 4 resources, and 8 prompts appear automatically.

Quick Start

Once configured, talk to your AI naturally. Here are some things to try:

Launch a coin

You: "Launch a coin called bori, symbol BOOL, 0.001 SOL initial buy"
Agent: shows summary, asks for confirmation
You: "Go"
Agent: opens signing page → connect wallet → sign twice → live

Check your portfolio

"What's my portfolio look like? My wallet is ABC123..."

Calls bags_wallet_balance, bags_token_holdings, and bags_claimable_positions for a complete overview.

Claim your fees

"Claim all my fees above 0.01 SOL"

Calls bags_claim_all_fees with a dust threshold. Returns unsigned transactions for each position.

More examples

Say thisGet this
"What's trending on Bags?"Recent launches and top tokens
"Check my wallet"Balance, holdings, claimable fees
"Set up a 50/50 fee split"Fee config built and signed
"List on Dexscreener"Profile boost order placed
"Show pool data for $TOKEN"Reserves, config, migration status
⚠️ You always sign transactions yourself. Every transaction-generating tool returns unsigned data. You sign with your own wallet before broadcasting.

Architecture

Project Structure

textbags-sdk-mcp/
├── src/
│   ├── index.ts              # Server creation, tool/resource/prompt registration
│   ├── transport/
│   │   ├── stdio.ts          # Default transport (Claude Desktop)
│   │   └── http.ts           # Streamable HTTP transport (Express)
│   ├── client/
│   │   ├── bags-sdk-wrapper.ts  # Singleton BagsSDK instance
│   │   ├── bags-rest.ts      # Direct REST client for undocumented endpoints
│   │   ├── cache.ts          # Tiered TTL cache (5 levels)
│   │   └── types.ts          # TypeScript types for API responses
│   ├── tools/                # 46 MCP tools organized by domain
│   │   ├── trading/          # quote, swap
│   │   ├── launch/           # feed, create-info, create-tx, launch-full
│   │   ├── fees/             # resolve-wallet, resolve-bulk, create-config, ...
│   │   ├── claiming/         # positions, claim, claim-all
│   │   ├── partner/          # stats, claim, config
│   │   ├── dexscreener/      # availability, order, payment
│   │   ├── agent/            # auth-init, login, wallets, keys, bootstrap
│   │   ├── state/            # pools, pool, pool-config
│   │   ├── analytics/        # creators, lifetime-fees, claim-stats, top-tokens
│   │   ├── solana/           # send-tx, balance, holdings
│   │   ├── signing/          # open-signing-page, open-launch-page
│   │   └── _registry.ts      # Imports and registers all 46 tools
│   ├── resources/            # 4 MCP resources
│   ├── prompts/              # 8 MCP prompts
│   ├── composer/             # Fee Config Builder + templates + validator
│   ├── agent/                # Autonomous agent mode
│   └── utils/                # Constants, errors, formatting
├── bin/
│   └── bags-sdk-mcp.ts       # CLI entry point
└── docs/
    └── index.html            # This documentation

Two Client Layers

LayerWhen UsedExamples
SDK (@bagsfm/bags-sdk)Typed methods existQuotes, swaps, claiming, creators, lifetime fees
REST (bags-rest.ts)No SDK method availableLaunch feed, pools, fee admin, agent auth, dexscreener

SDK Service Mapping

ServicePropertyKey Methods
Tradingsdk.tradegetQuote(), createSwapTransaction()
Fees/Claimingsdk.feegetAllClaimablePositions(), getClaimTransaction()
Statesdk.stategetTokenCreators(), getTokenLifetimeFees()
Configsdk.configcreateBagsFeeShareConfig()
Token Launchsdk.tokenLaunchcreateTokenInfoAndMetadata(), createLaunchTransaction()
Partnersdk.partnergetPartnerConfig(), getPartnerConfigClaimTransactions()
Dexscreenersdk.dexscreenercheckOrderAvailability(), createOrder()
💡 PublicKey conversion: Most SDK methods require PublicKey objects, not raw strings. Every tool handles this conversion internally — you always pass plain Base58 strings.

Zero-Custody Model

BagsSDK MCP never touches your private keys. The architecture ensures:

  • Transaction-generating tools (swap, claim, launch, fee config) return unsigned base64-encoded VersionedTransaction objects
  • You sign externally using your browser wallet (Phantom, Solflare, Backpack, Coinbase)
  • You broadcast using bags_send_transaction after signing, or the signing page handles it automatically

Transaction Flow

text┌──────────────┐    ┌───────────┐    ┌──────────┐    ┌──────────┐
│ AI requests  │ -> │ BagsSDK   │ -> │ You sign │ -> │ On-chain │
│ bags_swap    │    │ returns   │    │ with     │    │ via      │
│              │    │ unsigned  │    │ Phantom  │    │ send_tx  │
│              │    │ base64 tx │    │          │    │          │
└──────────────┘    └───────────┘    └──────────┘    └──────────┘

The Signing Page

For token launches, the server opens a local page on localhost:3141. This page connects directly to your browser wallet extension — the MCP server never sees your keys. Connect your wallet, approve the transactions, and the page broadcasts them to Solana.

🔒 Security guarantee: No private key, seed phrase, or signing capability ever passes through this server. The bags_agent_wallet_export tool only exports public key information.

Signing Server Hardening

The localhost signing server includes multiple layers of protection:

  • High-entropy session IDs — 32-byte crypto.randomBytes (64 hex chars) instead of UUIDs
  • CSRF tokens — per-session tokens embedded in the page and validated on every POST
  • Origin validation — POST requests from foreign origins are rejected (prevents cross-site attacks)
  • SRI integrity hashes — CDN-loaded @solana/web3.js verified with SHA-384 subresource integrity
  • XSS prevention — all dynamic content rendered via textContent, never innerHTML
  • Race-safe sessions — file-backed session store serialized behind an async mutex

Tiered Caching

The Bags.fm API has a 1,000 requests/hour rate limit. The cache protects against hitting it with five TTL tiers:

TierTTLWhat Gets Cached
ImmutableForeverSocial-to-wallet resolution (never changes)
Stable10 minCreators, pool configs, partner configs
Moderate5 minLifetime fees, claim stats, token feed, pools
Volatile2 minClaimable positions
None0Quotes, transactions, auth, send-tx

The cache is in-memory (Map-based) with no external dependencies. Entries auto-expire on read.

💡 Real-time data is never cached. Quotes, transaction building, and on-chain broadcasts always hit the API directly.

Error Handling

Every tool wraps its handler in try/catch and maps HTTP status codes to actionable messages:

StatusMessage
401Check your BAGS_API_KEY. Get one at dev.bags.fm
429Rate limited. BagsSDK caches responses. Retry in 60 seconds.
404Resource not found. Verify addresses and mints are correct.
Connection errorCannot reach Bags API. Check network and BAGS_API_BASE.

Errors are returned as MCP isError: true responses so the AI client can explain what went wrong and suggest fixes.

Trading Tools

bags_quote

Get a swap quote without creating a transaction. Read-only price check.

Inputs: tokenMint, side ("buy"|"sell"), amount, slippageBps?

Returns: inAmount, outAmount, minOutAmount, priceImpactPct

bags_swap

Create an unsigned swap transaction. Gets a quote first, then builds the transaction.

Inputs: tokenMint, side, amount, walletAddress, slippageBps?

Returns: unsigned base64 VersionedTransaction + quote details

⚠️ SOL Mint: So11111111111111111111111111111111111111112 is used automatically as the counterpart for all swaps.

Launch Tools

bags_launch_feed

Fetch the live token launch feed. Cached for 5 minutes.

Inputs: limit?, offset?

Returns: array of recent launches with status, metadata, creator info

bags_create_token_info

Step 1: Upload token metadata to IPFS via Bags API.

Inputs: name, symbol, description, imageUrl, telegram?, twitter?, website?

Returns: tokenMint, tokenMetadata, uri, status

bags_create_launch_tx

Step 3: Build the launch transaction (after fee config is created).

Inputs: ipfs (URI), tokenMint, wallet, initialBuyLamports, configKey

Returns: unsigned base64 transaction

bags_launch_token

Composed: Full launch flow in one call — metadata + fee config + launch transaction.

Inputs: all token info fields + wallet, claimersArray, basisPointsArray, initialBuyLamports?

Returns: all unsigned transactions in signing order

Fee Tools

bags_resolve_wallet

Resolve a social media handle to a Bags.fm Solana wallet. Cached permanently.

Inputs: provider (twitter, tiktok, kick, instagram, github, email, solana), username

bags_resolve_wallets_bulk

Resolve multiple handles at once. Partial failure tolerant.

Inputs: entries (array of {provider, username})

bags_create_fee_config

Create an on-chain fee share configuration. Validates BPS sum to 10000.

Inputs: payer, baseMint, claimersArray, basisPointsArray, partner?

Returns: meteoraConfigKey, feeShareAuthority, unsigned transactions

bags_compose_fee_config

Build and validate a fee config without submitting. Preview mode.

Inputs: mode ("custom"|"template"), template?, creator?, recipients?

bags_fee_admin_list

List all fee share configs you administer. Cached 10 minutes.

Inputs: walletAddress

bags_fee_admin_transfer

Transfer fee share admin rights to another wallet. Irreversible.

Inputs: currentAdmin, newAdmin, configKey

bags_fee_admin_update

Update claimers and BPS on an existing fee config.

Inputs: admin, configKey, claimersArray, basisPointsArray

bags_claim_events

Fetch claim event history. Supports pagination and time-range queries.

Inputs: tokenMint, mode?, limit, offset, from, to

Claiming Tools

bags_claimable_positions

View all your unclaimed fee positions with SOL amounts. Cached 2 minutes.

Inputs: walletAddress

Returns: array of positions with baseMint, claimableSol

bags_claim_fees

Claim fees for a specific token. May return multiple transactions.

Inputs: walletAddress, tokenMint

Returns: array of unsigned base64 transactions

bags_claim_all_fees

Composed: Claim all positions above a dust threshold in one call.

Inputs: walletAddress, minClaimLamports?

Partner Tools

bags_partner_stats

View your partner fee earnings. Cached 10 minutes.

Inputs: partnerWallet

bags_partner_claim

Claim accumulated partner fees.

Inputs: partnerWallet

bags_partner_config

Create or retrieve a partner configuration.

Inputs: partnerWallet, feeBps? (default 2500 = 25%)

Dexscreener Tools

bags_dexscreener_check

Check if Dexscreener profile boosting is available for a token.

Inputs: tokenMint

bags_dexscreener_order

Create a Dexscreener boost order. Must pay before activation.

Inputs: tokenMint, wallet

bags_dexscreener_payment

Confirm payment after signing the payment transaction.

Inputs: orderId, txSignature

Agent Auth Tools

bags_agent_auth_init

Step 1: Start the agent authentication flow.

Inputs: email?, provider?

bags_agent_auth_login

Step 2: Complete authentication with verification code.

Inputs: token (from auth_init), code?

bags_agent_wallet_list

List all wallets associated with authenticated agent.

Inputs: none

bags_agent_wallet_export

Export public key details for a wallet. Never exposes private keys.

Inputs: walletId

bags_agent_keys_list

List all API keys for the authenticated agent.

Inputs: none

bags_agent_keys_create

Create a new API key. Shown once — save it immediately.

Inputs: name?

bags_agent_bootstrap

Composed: Full agent setup — auth, verify, login, wallets, API key.

Inputs: none

State Tools

bags_pools

List all active liquidity pools.

Inputs: none

bags_pool

Get details for a specific pool — reserves, fee config, migration status.

Inputs: tokenMint

bags_pool_config_keys

Get Meteora pool config key addresses from fee claimer vaults.

Inputs: feeClaimerVaults (string[])

Analytics Tools

bags_token_creators

Get creator info for a token — wallets, social profiles, royalty BPS.

Inputs: tokenMint

bags_lifetime_fees

Get total lifetime trading fees collected by a token.

Inputs: tokenMint

bags_claim_stats

Aggregate claim statistics for a wallet or token.

Inputs: walletAddress?, tokenMint?

bags_top_tokens

Leaderboard of tokens ranked by lifetime trading fees.

Inputs: none

Solana Tools

bags_send_transaction

Broadcast a signed transaction to Solana. The only tool that sends anything on-chain.

Inputs: signedTransaction (base64)

Returns: transaction signature + Solscan URL

bags_wallet_balance

Check SOL balance for any wallet. Direct RPC call, never cached.

Inputs: walletAddress

bags_token_holdings

List all SPL token holdings for a wallet. Filters to non-zero balances.

Inputs: walletAddress

Signing Tools

bags_open_signing_page

Open a localhost signing page for arbitrary unsigned transactions. Connects to your browser wallet for approval.

Inputs: unsignedTransaction (base64)

Opens: localhost:3141 with wallet connector

bags_open_launch_page

Open the launch signing page with both fee config and launch transactions pre-loaded. Handles the two-signature flow automatically.

Inputs: feeConfigTx, launchTx, tokenMint, metadata

Opens: localhost:3141/launch with full context

Meta Tools

bags_tool_catalog

Returns a structured catalog of all available tools with descriptions, inputs, and groupings. Useful for discovery and help.

Inputs: none

Returns: categorized list of all 46 tools

Scout Tools

bags_scout_scan

Run one scout scan cycle. Fetches live headlines from Reddit, Hacker News, and Bags.fm, ranks them by meme potential, and assembles complete launch packages with AI-generated names, tickers, descriptions, and logos. Returns packages for review — does not launch anything.

Inputs: sources (string[], default ["bags","news"]), maxIdeas (number 1–10, default 3)

Returns: array of LaunchPackage objects with name, symbol, description, imageUrl, feeConfig, source, and reasoning

Annotations: readOnlyHint: true

bags_scout_launch

Launch a token from a scout package. Creates token metadata on IPFS, configures fee sharing, and opens a signing page where you connect your wallet and sign. Accepts a full or modified LaunchPackage from bags_scout_scan.

Inputs: package (LaunchPackage), walletAddress (string), initialBuyLamports (number, optional)

Returns: tokenMint, metadata URI, signing page URL

bags_generate_token_image

Generate a token logo image from a text prompt using fal.ai (Nano Banana Pro) or Replicate (Nano Banana 2). Returns a public image URL ready for use in token launches. Works as a standalone tool outside of scout mode.

Inputs: prompt (string), provider ("fal" | "replicate", optional)

Returns: image URL and provider used

Annotations: openWorldHint: true

Resources

MCP resources provide browsable context that AI clients can read without making a tool call.

ResourceURITypeDescription
launch-feedbags://launchesStaticLive token launch feed, cached 5 min
poolsbags://poolsStaticAll active liquidity pools, cached 5 min
tokenbags://token/{mint}TemplateComposite view: pool + creators + lifetime fees
portfoliobags://portfolio/{wallet}TemplateAll claimable positions with SOL amounts

Static resources have a fixed URI. Template resources accept a parameter in the URI path and fetch data dynamically.

Prompts

Prompts are guided workflows that structure multi-tool operations. Select a prompt and the AI receives pre-built instructions for executing a complex multi-step flow.

bags_launch_token

Solo token launch workflow.

Flow: resolve_wallet → compose_fee_config → create_token_info → create_fee_config → create_launch_tx

bags_launch_team_token

Team launch with multi-party fee splits.

Flow: resolve_wallet ×N → compose_fee_config → create_token_info → create_fee_config → create_launch_tx → dexscreener_check

bags_analyze_fees

Fee earnings analysis for a token or wallet.

Token: lifetime_fees → claim_events → token_creators → claim_stats

Wallet: claimable_positions → claim_stats

bags_setup_partner

Partner configuration setup guide.

Flow: partner_config → partner_stats → explain usage

bags_claim_all

Batch fee claiming with dust threshold.

Flow: claimable_positions → filter → claim_all_fees → return unsigned txs

bags_portfolio_overview

Full portfolio summary — balances, holdings, fees, stats.

Flow (parallel): wallet_balance + token_holdings + claimable_positions + claim_stats

bags_getting_started

Interactive onboarding for new users. Shows available capabilities and guides them to a starting point.

Flow: presents menu of actions → guides through chosen workflow step by step

bags_create_custom_tool

Scaffold a new MCP tool from a plain-English description. Generates TypeScript tool files using Bags SDK services.

Flow: accepts description → generates complete tool file with registration instructions

Guide: Check Your Portfolio

The fastest way to see everything about your wallet in one shot.

Step 1 — Check SOL balance

"What's my SOL balance? Wallet: ABC123..."

Tool: bags_wallet_balance

Step 2 — View token holdings

"What tokens do I hold?"

Tool: bags_token_holdings — returns all SPL tokens with non-zero balances.

Step 3 — Check unclaimed fees

"Do I have any unclaimed fees?"

Tool: bags_claimable_positions — shows each position with claimable SOL.

Or use the prompt

Select bags_portfolio_overview and provide your wallet address. It runs all three steps in parallel.

Guide: Claim Your Creator Fees

Every token launched via Bags.fm accumulates trading fees for the creator. Here is how to collect them.

Step 1 — Check what you are owed

"Show my claimable positions for wallet ABC123..."

Tool: bags_claimable_positions — returns each token with unclaimed SOL amount.

Step 2 — Claim fees for one token

"Claim my fees from token XYZ..."

Tool: bags_claim_fees — builds the unsigned transaction and opens a signing page at localhost:3141.

Step 3 — Sign in your browser

Open the signing URL. Connect the same wallet that launched the token (Phantom, Solflare, etc.). Sign the transaction. Your SOL is deposited immediately.

💡 Claim everything at once: Use bags_claim_all_fees with an optional dust filter (e.g. skip positions under 0.01 SOL). All claim transactions are batched into a single signing page.

How it works under the hood

The SDK fetches your claimable positions, builds claim transactions via the Bags API, and routes them through the local signing server. Your private key never leaves your wallet — the MCP server only handles unsigned transactions.

⚠️ Important: You must sign with the wallet that launched the token. If you launched from Phantom, connect Phantom on the signing page. A Bags.fm custodial wallet cannot sign browser-side.

Guide: Launch a Token

Step 1 — Prepare metadata

"Create token info: name MOON, symbol $MOON, description 'To the moon', image https://..."

Tool: bags_create_token_info — uploads to IPFS, returns tokenMint and URI.

Step 2 — Open the launch page

"Launch it with 0.1 SOL initial buy, my wallet is ABC123..."

Tool: bags_open_launch_page — opens localhost:3141 with both transactions ready.

Step 3 — Sign in your browser

Connect your wallet on the signing page. Approve the fee config transaction first, then the launch transaction. Your token is live.

💡 One-shot alternative: Use the bags_launch_token composed tool or prompt to do all steps in a single call.

Guide: Team Token Launch

Step 1 — Resolve all team members

"Resolve these wallets:
- twitter:alice (50%)
- twitter:bob (30%)
- twitter:charlie (20%)"

Tool: bags_resolve_wallets_bulk

Step 2 — Compose fee config

"Compose a team fee split with those percentages"

Tool: bags_compose_fee_config — validates BPS, checks for duplicates, shows preview.

Step 3 — Upload metadata + launch

Same as solo launch — bags_create_token_info then bags_open_launch_page.

Step 4 — Optional: Dexscreener boost

"Check if we can boost this token on Dexscreener"

Tools: bags_dexscreener_checkbags_dexscreener_order → sign → bags_dexscreener_payment

Guide: Analyze a Token

Step 1 — Lifetime fees

"How much in fees has token XYZ generated?"

Tool: bags_lifetime_fees

Step 2 — Creators

"Who are the creators of token XYZ?"

Tool: bags_token_creators

Step 3 — Claim history

"Show recent claim events for token XYZ"

Tool: bags_claim_events

Step 4 — Aggregate stats

"What are the claim stats for this token?"

Tool: bags_claim_stats

💡 Select the bags_analyze_fees prompt with targetType "token" to run all four steps automatically.

Guide: Partner Setup

Step 1 — Create partner config

"Set up a partner config with 25% fee for wallet ABC123"

Tool: bags_partner_config with feeBps: 2500

Step 2 — Share with creators

Give token creators your partner wallet and config address. When they include it in bags_create_fee_config, you earn a cut of trading fees.

Step 3 — Check earnings and claim

"How much have I earned as a partner?"

Tools: bags_partner_statsbags_partner_claim → sign → bags_send_transaction

Fee Config Composer

The FeeConfigBuilder provides a fluent API for composing fee splits without dealing with raw BPS math.

Fluent API

TypeScriptFeeConfigBuilder.create()
  .addRecipient("twitter", "alice", 5000)    // 50%
  .addRecipient("twitter", "bob", 3000)      // 30%
  .addDividendsBot(2000)                      // 20% to holders
  .validate()  // { valid: true, errors: [] }

Template Presets

TemplateDescriptionDefault Split
soloCreator100% to one person10000 BPS
creatorPlusDividendsCreator + DividendsBot50/50
teamSplitEven split across membersAuto-calculated
influencerLaunchCreator + influencers + dividends30% / split / 20%
daoDAO treasury + dividendsConfigurable

Validation Rules

  • At least 1 recipient, max 100
  • All BPS must be positive integers
  • BPS must sum to exactly 10000 (100%)
  • No duplicate provider:username pairs
  • Warns when >15 claimers (needs lookup tables)

Agent Mode

Activated with the --agent flag. Runs autonomous strategies using dual-model AI orchestration.

⚠️ Agent mode requires NOUS_API_KEY (Hermes 4) and ANTHROPIC_API_KEY (Claude Sonnet) in your environment.

Dual-Model Routing

ModelHandlesTrigger Patterns
Hermes 4 (fast)Routine tasksclaim, balance, check, list, monitor, status
Claude Sonnet (strategic)Complex decisionsevaluate, analyze, recommend, optimize, compare, strategy

Strategies

auto-claim

Checks positions every 5 minutes. Claims fees above 0.01 SOL threshold.

bashbags-sdk-mcp --agent --auto-claim

launch-monitor

Watches the launch feed every 30 seconds. Tracks seen mints. Escalates interesting launches to Sonnet for analysis.

bashbags-sdk-mcp --agent --monitor

scout

A global trend radar that scans live news headlines from across the internet, identifies the most memeable topics, and assembles complete token launch packages. You review the ideas and decide what ships — the agent never launches autonomously.

bashbags-sdk-mcp --agent --scout

How Scout Works

Every scan cycle (default 30 minutes), Scout runs a four-stage pipeline:

StageWhat HappensModel
1. GatherFetches live headlines from Reddit (7 subreddits), Hacker News, and the Bags.fm feed
2. RankFilters for virality, meme potential, emotional charge, and timelinessHermes 4
3. CreateGenerates token name, ticker, description, and logo for each top ideaSonnet + fal.ai
4. PresentShows packages to you with launch / edit / skip commands

News Sources

Scout pulls real-time headlines from diverse sources — not just crypto. Any trending topic can become a token:

SourceCategoryWhy
r/worldnewsWorld eventsBreaking geopolitical news, international drama
r/newsBreaking newsUS and general breaking stories
r/politicsPoliticsGovernment moves, elections, policy changes
r/memesMemesViral internet culture, trending formats
r/technologyTechAI announcements, product launches, tech drama
r/wallstreetbetsFinance memesMarket sentiment, retail trader culture
r/CryptoCurrencyCryptoToken news, protocol updates, market moves
Hacker NewsTech / scienceDeep tech, startups, science breakthroughs
Bags.fm feedPlatformActive launches and top tokens on-platform
💡 Image generation is optional. Set FAL_API_KEY (fal.ai) or REPLICATE_API_KEY (Replicate) for auto-generated logos. Without one, packages come without images and you add one before launching.

Scout Configuration

Env VariableDefaultDescription
IMAGE_GEN_PROVIDERfalImage provider: fal or replicate
FAL_API_KEYfal.ai API key (uses Nano Banana Pro for token logo generation)
REPLICATE_API_KEYReplicate API key (alternative to fal.ai)
SCOUT_INTERVAL1800Seconds between scan cycles (set to 60 for testing)
SCOUT_SOURCESbags,newsComma-separated: bags, news
SCOUT_MAX_IDEAS3Max launch packages per cycle (1–10)

Scout Setup Guide

  1. Add your image gen key to .env: FAL_API_KEY=your-key
  2. Run bags-sdk-mcp --agent --scout
  3. Wait for the first scan (or set SCOUT_INTERVAL=60 for testing)
  4. Review the packages — each shows name, ticker, image status, fee split, and source
  5. Type launch 1 to execute, edit 1 to modify, or skip to wait
  6. Sign the returned transactions in your wallet

Interactive Commands

CommandAction
launch NLaunch package N — creates token metadata, fee config, and returns unsigned transactions
edit NEnter edit mode for package N — modify name, symbol, or description inline
details NShow full package details including image prompt and reasoning
skipSkip all packages and wait for next cycle
doneExit edit mode and show updated packages

Using Scout via MCP (Claude Desktop / Cursor)

When connected as an MCP server, Scout exposes three tools you can invoke with natural language:

  • "Scan for trending token ideas" → calls bags_scout_scan — returns launch packages from live headlines
  • "Launch the first one with my wallet" → calls bags_scout_launch — creates token info, fee config, and opens signing page
  • "Generate a token logo for a space cat coin" → calls bags_generate_token_image — returns an image URL via fal.ai or Replicate

Example Flow

text# Scout finds trending headlines across Reddit, HN, and Bags.fm
# Hermes ranks them by meme potential and timeliness
# Sonnet generates creative token packages
# fal.ai generates logos

┌──────────────────────────────────────┐
│  SCOUT FOUND 2 IDEAS                │
├──────────────────────────────────────┤
│  1. LNGBOOM ($LNG)                  │
│     "Qatar's LNG plant got hit,     │
│      energy markets in shambles"     │
│     Image: ✓ generated              │
│     Source: reddit/world news        │
│                                      │
│  2. NOTOURWAR ($NOW)                │
│     "Europe tells Trump: not our     │
│      war, handle it yourself"        │
│     Image: ✓ generated              │
│     Source: reddit/world news        │
├──────────────────────────────────────┤
│  launch 1 — launch LNGBOOM         │
│  edit 1   — modify before launch    │
│  skip     — wait for next cycle     │
└──────────────────────────────────────┘
⚠️ Scout does NOT launch tokens autonomously. All packages require your explicit approval. It does not store private keys, and all transactions are returned unsigned for you to sign in your wallet.

Combined

bashbags-sdk-mcp --agent --scout --auto-claim --monitor

HTTP Transport

For remote connections and non-desktop integrations, use the Streamable HTTP transport.

bashbags-sdk-mcp --http              # Port 3000
bags-sdk-mcp --http --port=8080  # Custom port

Endpoints

MethodPathDescription
POST/mcpMCP protocol endpoint
GET/healthHealth check

Each request creates a fresh server + transport pair (stateless), making it suitable for serverless deployments.

CLI Reference

Setup

bashbags-sdk-mcp --setup               # Interactive installer for Claude Desktop, Cursor, etc.
bags-sdk-mcp --uninstall            # Remove from all detected MCP client configs

# Claude Code (one command):
claude mcp add bags-sdk-mcp -e BAGS_API_KEY=xxx -- npx bags-sdk-mcp

Server

bashbags-sdk-mcp                        # Start stdio server (default)
bags-sdk-mcp --http                 # Start HTTP server on port 3000
bags-sdk-mcp --http --port=8080     # HTTP on custom port

Agent

bashbags-sdk-mcp --agent --auto-claim   # Claim fees above threshold every 5 min
bags-sdk-mcp --agent --monitor      # Watch launches, flag interesting ones
bags-sdk-mcp --agent --scout        # Scan trends, propose token launches
bags-sdk-mcp --agent --scout --auto-claim --monitor   # All strategies

One-Shot Tools

bashbags-sdk-mcp --fee-optimize         # Analyze fee configs, suggest improvements
bags-sdk-mcp --rebalance            # Analyze positions, recommend claim strategy

Diagnostics

bashbags-sdk-mcp --doctor               # Check everything: env, API, RPC, configs, ports
bags-sdk-mcp --info                 # Show current config and capabilities (no network)
bags-sdk-mcp --whoami               # Test API key and show wallet stats
bags-sdk-mcp --test-key             # Validate API key only
bags-sdk-mcp --version              # Print version
bags-sdk-mcp --clear-sessions       # Wipe expired signing sessions

Troubleshooting

If something isn't working, start with --doctor. It checks your env vars, API key, RPC connectivity, MCP client configs, signing port, and sessions — then tells you exactly what's wrong.

ProblemFix
BAGS_API_KEY is missingRun npx bags-sdk-mcp --setup or set the key in your MCP config
Key validation failsGet a new key at dev.bags.fm, then npx bags-sdk-mcp --test-key
Signing page won't loadPort 3141 may be in use — --doctor will check
Stale signing sessionsRun npx bags-sdk-mcp --clear-sessions
Agent mode crashesCheck NOUS_API_KEY and ANTHROPIC_API_KEY — --doctor flags these

Technology Stack

LayerChoiceVersion
LanguageTypeScript (strict mode)5.8+
MCP SDK@modelcontextprotocol/sdk^1.12.0
Bags SDK@bagsfm/bags-sdk^1.2.7
Solana@solana/web3.js^1.95.0
Schemazod^3.25.0
HTTPexpress^4.21.0
Testvitest^3.0.0

Writing New Tools

Want to extend the MCP server with your own tools? Here's how.

File Structure

Each tool lives in src/tools/{domain}/ with its own file. One tool per file, one responsibility per tool.

textsrc/tools/
├── trading/
│   ├── quote.ts          # bags_quote
│   └── swap.ts           # bags_swap
├── your-domain/
│   └── your-tool.ts      # bags_your_tool
└── _registry.ts          # imports all tools

Anatomy of a Tool

Every tool has four parts: a name, a description, a Zod input schema, and a handler function.

TypeScriptimport { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { getClient } from "../../client/bags-sdk-wrapper.js";
import { cache, CacheTier } from "../../client/cache.js";

/** Register the example tool on the MCP server. */
export function registerMyTool(server: McpServer): void {
  server.tool(
    "bags_my_tool",
    "One-sentence description of what this tool does.",
    {
      tokenMint: z.string().describe("Base58 token mint address"),
      limit: z.number().optional().describe("Max results to return"),
    },
    async ({ tokenMint, limit }) => {
      try {
        const cacheKey = `my-tool:${tokenMint}`;
        const cached = cache.get(cacheKey);
        if (cached) return cached;

        const sdk = getClient();
        const result = await sdk.state.getSomeData(tokenMint);

        const response = {
          content: [{
            type: "text" as const,
            text: JSON.stringify(result, null, 2),
          }],
        };

        cache.set(cacheKey, response, CacheTier.MODERATE);
        return response;
      } catch (error: unknown) {
        const message = error instanceof Error
          ? error.message
          : "Unknown error";
        return {
          content: [{ type: "text" as const, text: message }],
          isError: true,
        };
      }
    }
  );
}

Registration

Import your tool in src/tools/_registry.ts and call the register function:

TypeScriptimport { registerMyTool } from "./your-domain/your-tool.js";

export function registerAllTools(server: McpServer): void {
  // ... existing tools ...
  registerMyTool(server);
}

Cache Tier Selection

Use This TierWhen
CacheTier.IMMUTABLEData that never changes (wallet resolution)
CacheTier.STABLEChanges rarely (creator info, configs)
CacheTier.MODERATEChanges occasionally (fee stats, pools)
CacheTier.VOLATILEChanges frequently (positions)
No cacheReal-time data (quotes, transactions)

Testing

bashnpm run build          # compile your changes
npm run inspect        # open MCP Inspector in browser
npm test               # run test suite

The MCP Inspector lets you call your tool interactively and see the raw response.

Guidelines

  • Use the SDK wrapper (getClient()) when a typed method exists
  • Fall back to the REST client (bags-rest.ts) for endpoints not covered by the SDK
  • Always return isError: true on failures so the AI can explain what went wrong
  • Cache appropriately — never cache transactions or quotes
  • Keep descriptions concise — the AI reads them to decide which tool to call
🚀 Contribute! This project is open source. We welcome new tools — trading strategies, analytics dashboards, notification integrations, portfolio trackers. Fork it, build something, and open a PR at github.com/outerheaven199X/Bags-SDK-hackathon.

Environment Variables

Variables are loaded from .env automatically.

VariableRequiredDefault
BAGS_API_KEYYes
SOLANA_RPC_URLNomainnet-beta
BAGS_API_BASENohttps://public-api-v2.bags.fm/api/v1
NOUS_API_KEYAgent mode
ANTHROPIC_API_KEYAgent mode
AGENT_WALLET_PUBKEYAgent mode

FAQ

Is this safe? Can it steal my funds?

No. The server uses a zero-custody model. It never sees your private keys. Every transaction is returned unsigned — you sign in your own browser wallet (Phantom, Solflare, Backpack, Coinbase). Keys never leave your device.

What wallets are supported?

Any Solana wallet with a browser extension: Phantom, Solflare, Backpack, and Coinbase Wallet. The signing page auto-detects installed wallets.

What's the API rate limit?

1,000 requests per hour. The built-in tiered cache keeps you well under this limit during normal use. Real-time data (quotes, transactions) bypasses the cache but these are infrequent.

Can I run this headless / on a server?

Yes. Use HTTP transport mode: bags-sdk-mcp --http. It exposes a stateless MCP endpoint suitable for serverless or load-balanced deployments.

Does this work with Cursor / other MCP clients?

Yes. Any MCP-compatible client works — Claude Desktop, Claude Code, Cursor, or custom agents built with the MCP SDK. Just add the config block to your client's config file.

How do I get an API key?

Go to dev.bags.fm, sign in, and create a key. Each account can create up to 10 keys.

What's the signing page?

A lightweight local web server on localhost:3141 that the SDK spins up when you need to sign transactions. It connects directly to your browser wallet extension — the MCP server is not involved in signing. The page shows transaction details and handles the approve/reject flow.

Why two signatures for a token launch?

Launching a token on Bags.fm requires two on-chain transactions: (1) creating the fee share configuration, and (2) the actual token launch. The signing page handles both in sequence — approve the first, then approve the second.

Can I use a custom RPC endpoint?

Yes. Set SOLANA_RPC_URL in your environment or .env file. Helius and other premium RPC providers are recommended for production use.