mcpField
S
solana-agent-kit

solana-agent-kit

github.com/sendaifunAgent 工作流130236 次安装13 周前更新
代码仓库

关于 solana-agent-kit

用于构建 Solana 区块链 AI Agent 的开源工具包,可通过模块化插件执行代币、NFT、DeFi、质押和跨链等操作。支持 LangChain、Vercel AI SDK 等框架,也提供面向 Claude 的 MCP 服务。

主要功能

  1. 01插件式组合 Solana 操作
  2. 02代币、NFT 与 DeFi 功能
  3. 03支持多种 Agent 框架
  4. 04交互式或自主执行模式
  5. 05提供 Claude MCP 服务

适用场景

  1. 01构建代币管理 Agent
  2. 02自动执行 NFT 创建或交易
  3. 03将 Solana 工具接入 Claude

MCP 相关

附带 solana-mcp 服务,向 MCP 客户端提供资产查询、代币部署、余额检查、转账、NFT 铸造和交易等工具。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sendaifun/skills --skill solana-agent-kit

安装后在 Claude Code 中输入/solana-agent-kit确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

docs/
custom-actions.md
troubleshooting.md
examples/autonomous-agent/
README.md
examples/langchain/
README.md
examples/mcp-server/
README.md
examples/vercel-ai/
README.md
resources/
actions-reference.md
templates/
agent-template.ts

详细介绍

Solana Agent Kit 开发指南

使用 SendAI 的开源工具包,构建可自主执行 60+ 项 Solana 区块链操作的 AI Agent。兼容 LangChain、Vercel AI SDK,以及通过 MCP 接入的 Claude。

概述

Solana Agent Kit 支持任何 AI 模型执行以下操作:

  • 部署和管理代币(SPL 和 Token-2022)
  • 通过 Metaplex 创建和交易 NFT
  • 执行 DeFi 操作(Jupiter、Raydium、Orca、Meteora)
  • 质押 SOL、跨链桥接代币、注册域名
  • 以交互模式或完全自主模式运行
主要功能
功能描述
60+ 项操作代币、NFT、DeFi、质押和跨链桥接操作
插件架构模块化设计——仅使用所需功能
多框架支持LangChain、Vercel AI SDK、MCP、Eliza
模型无关支持 OpenAI、Claude、Llama、Gemini
自主模式无需人工干预地执行,并支持错误恢复

快速开始

安装
# Core package
npm install solana-agent-kit

# With plugins (recommended)
npm install solana-agent-kit \
  @solana-agent-kit/plugin-token \
  @solana-agent-kit/plugin-nft \
  @solana-agent-kit/plugin-defi \
  @solana-agent-kit/plugin-misc \
  @solana-agent-kit/plugin-blinks
环境设置
# .env file
OPENAI_API_KEY=your_openai_api_key
RPC_URL=https://api.mainnet-beta.solana.com  # or devnet
SOLANA_PRIVATE_KEY=your_base58_private_key

# Optional API keys for enhanced features
COINGECKO_API_KEY=your_coingecko_key
HELIUS_API_KEY=your_helius_key
Agent 基本设置
import {
  SolanaAgentKit,
  createVercelAITools,
  KeypairWallet,
} from "solana-agent-kit";
import { Keypair } from "@solana/web3.js";
import bs58 from "bs58";

// Import plugins
import TokenPlugin from "@solana-agent-kit/plugin-token";
import NFTPlugin from "@solana-agent-kit/plugin-nft";
import DefiPlugin from "@solana-agent-kit/plugin-defi";
import MiscPlugin from "@solana-agent-kit/plugin-misc";
import BlinksPlugin from "@solana-agent-kit/plugin-blinks";

// Create wallet from private key
const privateKey = bs58.decode(process.env.SOLANA_PRIVATE_KEY!);
const keypair = Keypair.fromSecretKey(privateKey);
const wallet = new KeypairWallet(keypair);

// Initialize agent with plugins
const agent = new SolanaAgentKit(
  wallet,
  process.env.RPC_URL!,
  {
    OPENAI_API_KEY: process.env.OPENAI_API_KEY!,
  }
)
  .use(TokenPlugin)
  .use(NFTPlugin)
  .use(DefiPlugin)
  .use(MiscPlugin)
  .use(BlinksPlugin);

// Create tools for AI framework
const tools = createVercelAITools(agent, agent.actions);

插件和操作

代币插件(@solana-agent-kit/plugin-token)
操作描述
deployToken部署新的 SPL 代币或 Token-2022
transfer转移 SOL 或 SPL 代币
getBalance查看代币余额
stake通过 Jupiter/Solayer 质押 SOL
bridge通过 Wormhole 跨链桥接代币
rugCheck分析代币安全性
// Deploy a new token
const result = await agent.methods.deployToken({
  name: "My Token",
  symbol: "MTK",
  decimals: 9,
  initialSupply: 1000000,
});

// Transfer tokens
await agent.methods.transfer({
  to: "recipient_address",
  amount: 100,
  mint: "token_mint_address", // optional, defaults to SOL
});

// Check balance
const balance = await agent.methods.getBalance({
  tokenAddress: "token_mint_address", // optional
});
NFT 插件(@solana-agent-kit/plugin-nft)
操作描述
createCollection通过 Metaplex 创建 NFT 收藏集
mintNFT向收藏集铸造 NFT
listNFT在市场上挂牌出售 NFT
updateMetadata更新 NFT 元数据
// Create collection
const collection = await agent.methods.createCollection({
  name: "My Collection",
  symbol: "MYCOL",
  uri: "https://arweave.net/metadata.json",
});

// Mint NFT to collection
const nft = await agent.methods.mintNFT({
  collectionMint: collection.collectionAddress,
  name: "NFT #1",
  uri: "https://arweave.net/nft1.json",
});
DeFi 插件(@solana-agent-kit/plugin-defi)
操作描述
trade通过 Jupiter 兑换代币
createRaydiumPool创建 Raydium AMM 池
createOrcaPool创建 Orca Whirlpool
createMeteoraPool创建 Meteora DLMM 池
limitOrder通过 Manifest 下限价单
lend通过 Lulo 出借资产
perpetualTrade通过 Adrena/Drift 交易永续合约
// Swap tokens via Jupiter
const swap = await agent.methods.trade({
  outputMint: "target_token_mint",
  inputAmount: 1.0,
  inputMint: "So11111111111111111111111111111111111111112", // SOL
  slippageBps: 50, // 0.5%
});

// Create Raydium CPMM pool
const pool = await agent.methods.createRaydiumCpmm({
  mintA: "token_a_mint",
  mintB: "token_b_mint",
  configId: "config_id",
  mintAAmount: 1000,
  mintBAmount: 1000,
});
杂项插件(@solana-agent-kit/plugin-misc)
操作描述
airdrop通过 Helius 执行 ZK 压缩空投
getPrice通过 CoinGecko 获取代币价格
registerDomain注册 .sol 域名
resolveDomain将域名解析为地址
getTPS获取网络 TPS
// Compressed airdrop (cost-efficient)
const airdrop = await agent.methods.sendCompressedAirdrop({
  mintAddress: "token_mint",
  amount: 100,
  recipients: ["addr1", "addr2", "addr3"],
  priorityFeeInLamports: 10000,
});

// Get token price
const price = await agent.methods.getPrice({
  tokenId: "solana", // CoinGecko ID
});
Blinks 插件(@solana-agent-kit/plugin-blinks)

直接执行 Solana Actions/Blinks:

// Execute a Blink
const result = await agent.methods.executeBlink({
  blinkUrl: "https://example.com/blink",
  params: { /* blink-specific params */ },
});

集成模式

LangChain 集成
import { SolanaAgentKit, createSolanaTools } from "solana-agent-kit";
import { ChatOpenAI } from "@langchain/openai";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { MemorySaver } from "@langchain/langgraph";
import { HumanMessage } from "@langchain/core/messages";

async function createLangChainAgent() {
  // Initialize LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4-turbo-preview",
    temperature: 0.7,
  });

  // Initialize Solana Agent Kit
  const solanaKit = new SolanaAgentKit(
    wallet,
    process.env.RPC_URL!,
    { OPENAI_API_KEY: process.env.OPENAI_API_KEY! }
  )
    .use(TokenPlugin)
    .use(DefiPlugin);

  // Create LangChain tools
  const tools = createSolanaTools(solanaKit);

  // Create agent with memory
  const memory = new MemorySaver();
  const agent = createReactAgent({
    llm,
    tools,
    checkpointSaver: memory,
  });

  return agent;
}

// Run agent
async function chat(agent: any, message: string) {
  const config = { configurable: { thread_id: "solana-agent" } };

  const stream = await agent.stream(
    { messages: [new HumanMessage(message)] },
    config
  );

  for await (const chunk of stream) {
    if ("agent" in chunk) {
      console.log(chunk.agent.messages[0].content);
    }
  }
}
Vercel AI SDK 集成
import { SolanaAgentKit, createVercelAITools } from "solana-agent-kit";
import { openai } from "@ai-sdk/openai";
import { generateText } from "ai";

async function runVercelAgent(prompt: string) {
  const agent = new SolanaAgentKit(wallet, rpcUrl, options)
    .use(TokenPlugin)
    .use(DefiPlugin);

  const tools = createVercelAITools(agent, agent.actions);

  const result = await generateText({
    model: openai("gpt-4-turbo"),
    tools,
    maxSteps: 10,
    prompt,
  });

  return result.text;
}

// Usage
const response = await runVercelAgent(
  "Swap 0.1 SOL for USDC using the best rate"
);
用于 Claude 的 MCP 服务

为 Claude Desktop 安装并配置 MCP 服务:

# Install globally
npm install -g solana-mcp

# Or run directly
npx solana-mcp

将以下内容添加到 Claude Desktop 配置(~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "solana": {
      "command": "npx",
      "args": ["solana-mcp"],
      "env": {
        "RPC_URL": "https://api.mainnet-beta.solana.com",
        "SOLANA_PRIVATE_KEY": "your_base58_private_key",
        "OPENAI_API_KEY": "your_openai_key"
      }
    }
  }
}

可用的 MCP 工具:

  • GET_ASSET - 获取代币/资产信息
  • DEPLOY_TOKEN - 创建新代币
  • GET_PRICE - 获取代币价格
  • WALLET_ADDRESS - 获取钱包地址
  • BALANCE - 查看余额
  • TRANSFER - 发送代币
  • MINT_NFT - 创建 NFT
  • TRADE - 执行兑换
  • REQUEST_FUNDS - 获取 devnet SOL
  • RESOLVE_DOMAIN - 查询 .sol 域名
  • GET_TPS - 获取网络吞吐量

自主模式

以完全自主模式运行 Agent:

import { SolanaAgentKit } from "solana-agent-kit";

const agent = new SolanaAgentKit(wallet, rpcUrl, options)
  .use(TokenPlugin)
  .use(DefiPlugin);

// Configure autonomous behavior
const autonomousConfig = {
  intervalMs: 60000,        // Check every minute
  maxActions: 100,          // Max actions per session
  errorRecovery: true,      // Auto-retry on failures
  dryRun: false,            // Set true for testing
};

// Start autonomous loop
async function runAutonomous() {
  while (true) {
    try {
      // Agent decides what to do based on market conditions
      const decision = await agent.analyze({
        context: "Monitor my portfolio and rebalance if needed",
        constraints: [
          "Keep at least 1 SOL for gas",
          "Max 10% allocation per token",
        ],
      });

      if (decision.shouldAct) {
        await agent.execute(decision.action);
      }

      await sleep(autonomousConfig.intervalMs);
    } catch (error) {
      if (autonomousConfig.errorRecovery) {
        console.error("Error, recovering:", error);
        await sleep(5000);
      } else {
        throw error;
      }
    }
  }
}

创建自定义操作

通过自定义操作扩展 Agent:

import { Action, Tool, SolanaAgentKit } from "solana-agent-kit";

// Define the Tool (tells LLM HOW to use it)
const myCustomTool: Tool = {
  name: "my_custom_action",
  description: "Does something custom on Solana",
  parameters: {
    type: "object",
    properties: {
      param1: {
        type: "string",
        description: "First parameter",
      },
      param2: {
        type: "number",
        description: "Second parameter",
      },
    },
    required: ["param1"],
  },
};

// Define the Action (tells agent WHEN and WHY to use it)
const myCustomAction: Action = {
  name: "my_custom_action",
  description: "Use this when you need to do something custom",
  similes: ["custom thing", "special operation"],
  examples: [
    {
      input: "Do the custom thing with value X",
      output: "Custom action executed with param1=X",
    },
  ],
  handler: async (agent: SolanaAgentKit, params: any) => {
    const { param1, param2 } = params;

    // Your custom logic here
    const connection = agent.connection;
    const wallet = agent.wallet;

    // Execute Solana operations...

    return {
      success: true,
      result: `Executed with ${param1}`,
    };
  },
};

// Register custom action
agent.registerAction(myCustomAction);
agent.registerTool(myCustomTool);

最佳实践

安全
  1. 切勿泄露私钥——使用环境变量
  2. 使用专用钱包——将 Agent 钱包与主要资金分开
  3. 设置支出限额——设置单笔交易金额上限
  4. 先在 devnet 上测试——始终在 mainnet 上线前进行测试
  5. 审计 Agent 操作——记录所有操作
性能
  1. 选择合适的 RPC——生产环境使用 Helius、Triton
  2. 批量处理操作——合并相关交易
  3. 处理速率限制——实现退避策略
  4. 尽可能缓存——价格数据、代币元数据
Agent 设计
  1. 限制插件范围 - 只加载所需插件(减少幻觉)
  2. 提供清晰的上下文 - 详细的提示词可提高准确性
  3. 添加约束 - 防止不必要的操作
  4. 监控并迭代 - 检查 Agent 的决策

指南

  • 在主网之前,始终先在 devnet 上测试
  • 设置最大交易限额
  • 监控 Agent 活动日志
  • 为 Agent 使用专用钱包
  • 实施适当的错误处理
  • 妥善保管私钥

此技能中的文件

solana-agent-kit/
├── SKILL.md                           # This file
├── resources/
│   ├── actions-reference.md           # Complete actions list
│   ├── plugins-guide.md               # Plugin deep dive
│   └── security-checklist.md          # Security best practices
├── examples/
│   ├── langchain/                     # LangChain integration
│   ├── vercel-ai/                     # Vercel AI SDK
│   ├── mcp-server/                    # Claude MCP setup
│   └── autonomous-agent/              # Autonomous patterns
├── templates/
│   └── agent-template.ts              # Starter template
└── docs/
    ├── custom-actions.md              # Creating custom actions
    └── troubleshooting.md             # Common issues

V2 亮点

Version 2 对工具包进行了全面升级,带来多项关键改进:

插件架构

V2 直接解决了 V1 的两大挑战:

  1. 安全性:输入私钥的方式并非百分之百安全
  2. 幻觉:100 多个聚合工具会让大模型感到困惑

模块化插件系统允许你只安装所需的内容,从而减少上下文膨胀和幻觉。

嵌入式钱包支持(新增)

V2 集成了安全的钱包提供商,进一步增强安全性:

import { TurnkeyWallet, PrivyWallet } from "solana-agent-kit/wallets";

// Turnkey - fine-grained rules and policies
const turnkeyWallet = new TurnkeyWallet({
  organizationId: process.env.TURNKEY_ORG_ID,
  privateKeyId: process.env.TURNKEY_PRIVATE_KEY_ID,
});

// Privy - human-in-the-loop confirmation
const privyWallet = new PrivyWallet({
  appId: process.env.PRIVY_APP_ID,
  requireConfirmation: true,
});

// Initialize agent with secure wallet
const agent = new SolanaAgentKit(turnkeyWallet, rpcUrl, options)
  .use(TokenPlugin)
  .use(DefiPlugin);
V2 的主要优势
功能V1V2
钱包安全性输入私钥嵌入式钱包(Turnkey、Privy)
工具加载全部 100 多个工具基于插件,按需加载
大模型上下文内容庞大,容易导致幻觉精简、聚焦的上下文
人工参与不支持原生支持 Privy

注意事项

  • Solana Agent Kit 正在积极维护(1,400 多次提交、800 多个 fork)
  • V2 引入了插件架构(提供迁移指南)
  • 提供 Python 版本:solana-agent-kit-py
  • MCP 服务支持与 Claude Desktop 集成
  • 下载量超过 100,000 次,GitHub 星标超过 1.6k
  • 采用 Apache-2.0 许可

评论

支持 Markdown