Sponsored by Deepsite.site

Defi Copilot

Created By
fxjrin24 days ago
Pay-per-decision DeFi intelligence for AI agents on Stellar. Built with x402 protocol - agents buy decisions, not subscriptions. Auto-creates agent wallet, real Blend Finance APY, DEX comparison, deposit/withdraw Blend Finance via Soroban.
Overview

DeFi Copilot

npm version npm downloads License: MIT Node.js Stellar

Pay-per-decision DeFi intelligence for AI agents on Stellar. Built with x402 protocol — agents buy decisions, not subscriptions.

Overview

DeFi Copilot is a Stellar-native DeFi intelligence layer that allows AI agents to autonomously query DeFi data, execute swaps, and interact with DeFi protocols — paying per request using the x402 protocol. No API keys. No subscriptions. No human approval required.

Two ways to use:

  • MCP Server — install in Claude Desktop or any MCP-compatible AI, agents query and pay automatically
  • REST API — standard HTTP with x402 payment protocol, works with any HTTP client

Live backend: https://api.fxjrin.com


How It Works

User / AI Agent
      |
      | (natural language or direct API call)
      v
MCP Server (defi-copilot-mcp)
      |
      | GET /defi/yield/best
      v
Backend API (port 3000)
      |
      | 402 Payment Required
      v
Agent builds + signs Stellar USDC tx
      |
      | x-payment header
      v
Facilitator verifies + settles (port 4022)
      |
      | on-chain settlement on Stellar
      v
Return DeFi intelligence

Project Structure

defi-copilot/
  src/
    server.ts                  # Express server
    routes/
      yield.ts                 # GET /defi/yield/best
      swap.ts                  # GET /defi/swap/best
    services/
      scorer.ts                # Market data + Blend on-chain APY + DEX quotes
    utils/
      x402-middleware.ts       # x402 payment verification
      network.ts               # Network config (testnet/mainnet)
      http.ts                  # IPv4-forced HTTP client (undici)
      init.ts                  # Server wallet setup script
    facilitator/
      index.ts                 # Local x402 facilitator (port 4022)
    agent/
      client.ts                # Agent payment client with auto-create wallet
      demo.ts                  # Demo script
  mcp-server/
    src/
      index.ts                 # MCP tools + auto-create wallet
      network.ts               # Network config for MCP
      http.ts                  # IPv4-forced HTTP client (undici)

Prerequisites

  • Node.js v18+
  • npm v9+
  • Git

Installation

1. Clone the repository

git clone https://github.com/fxjrin/defi-copilot.git
cd defi-copilot

2. Install backend dependencies

npm install

3. Install MCP server dependencies

cd mcp-server
npm install
cd ..

Configuration

Backend .env

The .env file is generated automatically by npm run init. If you prefer to set it up manually, create .env in the defi-copilot/ root:

# Stellar network: testnet or mainnet
STELLAR_NETWORK=testnet

# Server wallet — receives x402 payments
# Generated automatically by: npm run init
SERVER_SECRET_KEY=
SERVER_PUBLIC_KEY=

PORT=3000

Quick Start

Step 1 — Initialize server wallet

Run the setup script to automatically generate and fund a server wallet:

npm run init

This will:

  1. Generate a new Stellar keypair for the server
  2. Fund with XLM via Friendbot (testnet only)
  3. Set up USDC trustline
  4. Save credentials to .env

Expected output:

DeFi Copilot — Initial Setup
Network: testnet
Generating server wallet...
  Public key : GXXXX...
  Secret key : SXXX*...XXXX (saved to .env)
  Credentials saved to .env
  Funding via Friendbot...
  XLM funded successfully
  Waiting for account activation...
Setting up USDC trustline...
  USDC trustline created
Final balances:
  USDC: 0.0000
  XLM: 10000.0000
Setup complete!
Run: npm start

Step 2 — Start the server

npm start

This starts both the API server (port 3000) and the x402 facilitator (port 4022) simultaneously.

Expected output:

[api]          🚀 DeFi Copilot API running on port 3000
[api]             Network : testnet
[api]             Wallet  : GXXXX...
[facilitator]  ⚡ Local x402 Facilitator running on port 4022

Step 3 — Run the demo

Make sure npm start is running in another terminal, then:

npm run demo

The demo agent will auto-create its own wallet, fund it with USDC, and make payments automatically.

Expected output:

DeFi Copilot Agent Demo
Initializing agent wallet...
  No wallet found — creating new agent wallet on Stellar testnet...
  Funding with XLM via Friendbot...
  XLM funded successfully
  Setting up USDC trustline...
  Swapping XLM to USDC...
  USDC funded successfully
  Agent wallet ready: GXXXX...

DEMO 1: Where should I put my USDC?
  Agent requesting: http://localhost:3000/defi/yield/best
  Payment required: 0.0010 USDC
  Payment accepted!
  Strategy   : Deposit to Fixed V2 on Blend Finance
  APY        : 9.47% (live on-chain)
  Risk       : low
  Confidence : 95%

DEMO 2: Best route to swap 500 XLM to USDC?
  Agent requesting: http://localhost:3000/defi/swap/best
  Payment accepted!
  Route          : SDEX Orderbook
  Expected output: 75.88 USDC
  Slippage       : 0.005%
  Confidence     : 99%

API Reference

GET /health

Free. Returns server status.

{
  "status": "ok",
  "network": "testnet",
  "server_wallet": "GXXXX..."
}

GET /defi/yield/best

Cost: 0.001 USDC via x402

Query params:

  • assetUSDC or XLM (default: USDC)
  • amount — number (default: 1000)

Response:

{
  "strategy": "Deposit to Fixed V2 on Blend Finance",
  "protocol": "Blend Finance",
  "apy": "9.47%",
  "risk": "low",
  "reasoning": "Live Blend Finance on-chain APY. Pool comparison: Fixed V2: USDC 9.47% | YieldBlox V2: USDC 0.07%",
  "confidence": 0.95,
  "marketData": {
    "xlmPrice": "0.1518 USDC",
    "spread": "0.3945%",
    "volume24h": "4531.6K XLM",
    "source": "Blend Finance (on-chain Soroban) + Stellar mainnet DEX"
  },
  "alternatives": [...]
}

GET /defi/swap/best

Cost: 0.001 USDC via x402

Query params:

  • from — source asset (default: XLM)
  • to — target asset (default: USDC)
  • amount — number (default: 100)

Response:

{
  "from": "XLM",
  "to": "USDC",
  "amount": 500,
  "route": ["SDEX Orderbook"],
  "expectedOutput": "75.88 USDC",
  "slippage": "0.005%",
  "priceImpact": "low",
  "marketPrice": "1 XLM = 0.1518 USDC",
  "confidence": 0.99,
  "reasoning": "DEX comparison: SDEX Orderbook: 75.88 USDC | Stellar DEX: 75.80 USDC | Stellar AMM: 75.70 USDC"
}

x402 Payment Flow

1. Client → GET /defi/yield/best
2. Server ← 402 Payment Required
   {
     "x402Version": 1,
     "accepts": [{
       "scheme": "exact",
       "network": "stellar-testnet",
       "maxAmountRequired": "10000",
       "asset": "CBIELTK6...",
       "payTo": "GXXXX..."
     }]
   }
3. Client builds + signs Stellar USDC payment tx
4. Client → GET /defi/yield/best
           x-payment: <base64-encoded-payload>
5. Facilitator verifies transaction
6. Facilitator settles on Stellar
7. Server → 200 OK with DeFi intelligence

MCP Server

The MCP server allows AI agents (Claude, Cursor, etc.) to use DeFi Copilot tools directly in conversation, with automatic payment handling.

Install via Claude Code

claude mcp add defi-copilot -- npx -y defi-copilot-mcp

Install via Claude Desktop config

Add to your claude_desktop_config.json:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

Windows: %APPDATA%\Claude\claude_desktop_config.json

Linux: ~/.config/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "defi-copilot": {
      "command": "npx",
      "args": ["-y", "defi-copilot-mcp"],
      "env": {
        "STELLAR_NETWORK": "testnet"
      }
    }
  }
}

Note: DEFI_COPILOT_API defaults to https://api.fxjrin.com — no need to set it unless you run your own backend.

Available Tools

ToolCostDescription
get_best_yield0.001 USDCBest yield strategy — live from Blend Finance on-chain (Soroban)
get_best_swap0.001 USDCOptimal swap route — compares SDEX Orderbook, Stellar DEX, AMM
execute_swapFREEExecute real swap on Stellar DEX
deposit_blendFREEDeposit USDC to Blend Finance to earn yield (mainnet)
withdraw_blendFREEWithdraw USDC + interest from Blend Finance (mainnet)
get_blend_positionFREECheck your Blend Finance deposit + interest earned (mainnet)
transferFREESend XLM or USDC to any Stellar address
get_market_dataFREELive XLM price, volume, spread from Stellar mainnet DEX
get_agent_walletFREECheck or create agent wallet
fund_walletFREEShow wallet address + QR code URL for funding
set_networkFREESwitch between testnet and mainnet
get_transaction_historyFREEView recent wallet transaction history
get_api_infoFREEAPI info and pricing

Agent Wallet Behavior

On first use, the MCP server automatically:

  1. Generates a new Stellar keypair
  2. Funds with XLM via Friendbot (testnet only)
  3. Sets up USDC trustline
  4. Swaps 50 XLM to USDC for payment capability
  5. Saves wallet to ~/.defi-copilot/wallet-testnet.json

Each user's wallet is stored locally on their own machine. Private keys never leave the user's device.

On mainnet, the wallet is created but not auto-funded — users must deposit XLM manually. This is intentional: mainnet uses real funds.

Network Switching

Switch networks within a conversation:

User: "Switch to mainnet"
Claude: calls set_network(network="mainnet")

User: "Deposit 10 USDC to Blend Finance"
Claude: calls deposit_blend(amount=10, confirmed=true)

Or set via environment variable (persists across sessions):

"env": {
  "STELLAR_NETWORK": "mainnet"
}

Data Sources

DataSourceNetwork
Yield APYBlend Finance smart contracts (Soroban)Mainnet (on-chain)
Swap quotesSDEX Orderbook + Stellar DEX pathfinder + AMM poolMainnet (real quotes)
XLM priceStellar Horizon trade aggregationsMainnet (real prices)
Orderbook spreadStellar Horizon order bookMainnet
24h volumeStellar Horizon trade aggregationsMainnet
Paymentsx402 protocolTestnet or Mainnet

All price and yield data comes directly from Stellar mainnet for accuracy, regardless of which network is used for payments.


Environment Variables

Backend (defi-copilot/.env)

VariableRequiredDescription
STELLAR_NETWORKNotestnet or mainnet (default: testnet)
SERVER_SECRET_KEYYesSecret key for server wallet (receives payments)
SERVER_PUBLIC_KEYYesPublic key for server wallet
PORTNoServer port (default: 3000)

MCP Server (via config or shell env)

VariableRequiredDescription
STELLAR_NETWORKNotestnet or mainnet (default: testnet)
DEFI_COPILOT_APINoBackend API URL (default: https://api.fxjrin.com)

npm Scripts

Backend (defi-copilot/)

npm run init        # Generate and fund server wallet
npm start           # Start API + facilitator together
npm run dev         # Start API only (port 3000)
npm run facilitator # Start facilitator only (port 4022)
npm run demo        # Run agent payment demo
npm run build       # Compile TypeScript

MCP Server (defi-copilot/mcp-server/)

npm run build       # Compile TypeScript
npm run dev         # Run without compiling (tsx)

Deployment

Backend on VPS

git clone https://github.com/fxjrin/defi-copilot.git
cd defi-copilot
npm install

# Initialize server wallet
npm run init

# Install pm2 for process management
npm install -g pm2

# Start both api and facilitator
pm2 start npm --name defi-copilot -- start
pm2 save
pm2 startup

After deploying, nginx reverse proxy + SSL via certbot is recommended:

apt install -y nginx certbot python3-certbot-nginx
# configure nginx to proxy port 3000
certbot --nginx -d your-domain.com

License

MIT

Server Config

{
  "mcpServers": {
    "defi-copilot": {
      "command": "npx",
      "args": [
        "-y",
        "defi-copilot-mcp"
      ],
      "env": {
        "STELLAR_NETWORK": "testnet"
      }
    }
  }
}
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
WindsurfThe new purpose-built IDE to harness magic
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
Y GuiA web-based graphical interface for AI chat interactions with support for multiple AI models and MCP (Model Context Protocol) servers.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
ChatWiseThe second fastest AI chatbot™
CursorThe AI Code Editor
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Tavily Mcp
Playwright McpPlaywright MCP server
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
RedisA Model Context Protocol server that provides access to Redis databases. This server enables LLMs to interact with Redis key-value stores through a set of standardized tools.
Amap Maps高德地图官方 MCP Server
DeepChatYour AI Partner on Desktop
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Serper MCP ServerA Serper MCP Server
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.