加密货币价格MCP服务器

一个提供实时加密货币价格数据的MCP服务器,支持标准MCP接口和HTTP端点,适用于AI代理和金融应用集成。

  • by AdI-70
  • HTML
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 AdI-70/realtime-cryptoprice-MCP

使用说明

🚀 实时加密价格MCP服务器

全面 模型上下文协议(MCP) 通过CoinGecko API提供实时加密货币价格数据的服务器实现。该项目演示了传统的MCP stdio传输和现代HTTP端点,以增强测试和集成能力。

📋 目录

🎯 概述

该项目实现了 模型上下文协议(MCP) 服务器,充当人工智能代理和实时加密货币市场数据之间的桥梁。它提供:

  • 标准MCP接口:与任何符合MCP的客户端兼容
  • HTTP Web仪表板:用于测试和监控的漂亮、响应迅速的界面
  • 实时数据:CoinGecko API的实时加密货币价格
  • 双重运输:stdio(标准MCP)和HTTP端点

什么是MCP?

模型上下文协议(MCP)是一种标准化协议,使AI代理能够以安全、一致的方式访问外部数据源和工具。该服务器通过人工智能代理可以调用的MCP工具公开加密货币市场数据。

✨ 特性

🔥 核心功能

  • 实时价格数据:实时加密货币价格和市场数据
  • 多种加密货币支持比特币,以太坊和1000多个硬币
  • 货币灵活性:价格以美元、欧元、日元、英镑、加元、澳元计
  • 顶级加密货币排名:基于市值的加密货币列表
  • 清洁API设计:带有JSON响应的RESTful端点

🎨 Web界面功能

  • 响应式仪表板:美观、移动友好的界面
  • 实时状态监控:实时服务器健康检查
  • 交互式表单:轻松查找加密货币价格
  • 市场概述:24小时变化的顶级加密货币
  • 错误处理:优美的错误消息和加载状态

🔧 技术特性

  • MCP协议:用于AI代理集成的标准stdio传输
  • Express.js服务器:用于web界面和API访问的HTTP端点
  • TypeScript支持:使用Zod进行完整的类型定义和验证
  • 差错恢复:全面的错误处理和恢复
  • 生产就绪:针对部署和扩展进行了优化

🏗️ 建筑

graph TB
    A[AI Agent/Client] --> B[MCP Server - stdio]
    C[Web Browser] --> D[Express HTTP Server]
    B --> E[CoinGecko API]
    D --> E
    E --> F[Real-time Price Data]
    
    subgraph "MCP Tools"
        G[getCryptoPrice]
        H[listTopCryptos]
    end
    
    B --> G
    B --> H
    D --> G
    D --> H

组件体系结构

  1. 协议层:用于AI代理通信的MCP stdio传输
  2. 服务层:加密货币数据处理的业务逻辑
  3. 数据层:CoinGecko API集成和缓存
  4. 表示层:带web仪表板的HTTP服务器

🚀 快速开始

先决条件

  • 已安装Node.js 18+
  • Git已安装
  • 终端/命令提示符访问

安装

# Clone the repository
git clone https://github.com/AdI-70/realtime-cryptoprice-MCP.git
cd realtime-cryptoprice-MCP

# Install dependencies
npm install

# Start the web server
npm run web

打开http://localhost:3000在浏览器中查看仪表板!

测试MCP服务器

# In a separate terminal, test the MCP client
npm run client

📖 分步教程:从头开始构建

步骤1:项目设置

  1. 创建项目目录

    mkdir crypto-mcp-server
    cd crypto-mcp-server
    
  2. 初始化Node.js项目

    npm init -y
    
  3. 配置ES模块

    // Add to package.json
    {
      "type": "module",
      "scripts": {
        "start": "node server.js",
        "client": "node client.js",
        "web": "node web-server.js"
      }
    }
    

步骤2:安装依赖项

# Core MCP dependencies
npm install @modelcontextprotocol/sdk zod node-fetch

# Web server dependencies
npm install express

步骤3:创建MCP服务器(server.js)

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import fetch from "node-fetch";

// Create MCP server instance
const server = new McpServer({
  name: "CryptoPrice",
  version: "1.0.0"
});

// Define getCryptoPrice tool
server.tool("getCryptoPrice", {
  id: z.string().describe("Cryptocurrency ID (e.g., bitcoin, ethereum)"),
  currency: z.string().default("usd").describe("Currency (usd, eur, etc.)")
}, async ({ id, currency }) => {
  try {
    const response = await fetch(
      `https://api.coingecko.com/api/v3/simple/price?ids=${id}&vs_currencies=${currency}`
    );
    const data = await response.json();
    
    if (!data[id]) {
      return { content: [{ type: "text", text: `Cryptocurrency '${id}' not found.` }] };
    }
    
    const price = data[id][currency];
    return {
      content: [{ type: "text", text: `${id}: ${price} ${currency.toUpperCase()}` }]
    };
  } catch (error) {
    return {
      content: [{ type: "text", text: `Error: ${error.message}` }]
    };
  }
});

// Define listTopCryptos tool
server.tool("listTopCryptos", {
  limit: z.number().default(10).describe("Number of top cryptocurrencies")
}, async ({ limit }) => {
  try {
    const response = await fetch(
      `https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=${limit}&page=1`
    );
    const data = await response.json();
    
    const cryptoList = data.map(crypto => 
      `${crypto.name} (${crypto.symbol}): $${crypto.current_price}`
    ).join('\n');
    
    return { content: [{ type: "text", text: cryptoList }] };
  } catch (error) {
    return {
      content: [{ type: "text", text: `Error: ${error.message}` }]
    };
  }
});

// Start server with stdio transport
const transport = new StdioServerTransport();
console.log("Starting CryptoPrice MCP server...");
await server.connect(transport);
console.log("CryptoPrice MCP server running");

步骤4:创建MCP客户端(client.js)

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function main() {
  // Create transport to connect to server
  const transport = new StdioClientTransport({
    command: "node",
    args: ["server.js"]
  });

  // Create client
  const client = new Client({
    name: "crypto-price-client",
    version: "1.0.0"
  });

  // Connect and test
  await client.connect(transport);
  
  try {
    console.log("Connected to CryptoPrice MCP server\n");

    // Test Bitcoin price
    const bitcoinPrice = await client.callTool({
      name: "getCryptoPrice",
      arguments: { id: "bitcoin", currency: "usd" }
    });
    console.log("Bitcoin Price:", bitcoinPrice.content[0].text);

    // Test top cryptocurrencies
    const topCryptos = await client.callTool({
      name: "listTopCryptos",
      arguments: { limit: 5 }
    });
    console.log("\nTop 5 Cryptocurrencies:");
    console.log(topCryptos.content[0].text);
    
  } catch (error) {
    console.error("Error:", error.message);
  }
}

main().catch(console.error);

步骤5:创建Web服务器(web-server.js)

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import fetch from 'node-fetch';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3000;

// Middleware
app.use(express.json());
app.use(express.static('public'));

// API Routes
app.get('/api/crypto/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { currency = 'usd' } = req.query;
    
    const response = await fetch(
      `https://api.coingecko.com/api/v3/simple/price?ids=${id}&vs_currencies=${currency}`
    );
    const data = await response.json();
    
    if (!data[id]) {
      return res.status(404).json({ error: `Cryptocurrency '${id}' not found` });
    }
    
    res.json({
      id,
      currency: currency.toUpperCase(),
      price: data[id][currency],
      formatted: `${id}: ${data[id][currency]} ${currency.toUpperCase()}`
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/top-cryptos', async (req, res) => {
  try {
    const { limit = 10 } = req.query;
    
    const response = await fetch(
      `https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=${limit}&page=1`
    );
    const data = await response.json();
    
    const cryptoList = data.map(crypto => ({
      id: crypto.id,
      name: crypto.name,
      symbol: crypto.symbol.toUpperCase(),
      price: crypto.current_price,
      change_24h: crypto.price_change_percentage_24h
    }));
    
    res.json({ cryptos: cryptoList, count: cryptoList.length });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Health check
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'healthy', 
    server: 'CryptoPrice MCP Web Server',
    timestamp: new Date().toISOString()
  });
});

app.listen(PORT, () => {
  console.log(`🚀 Server running at http://localhost:${PORT}`);
});

步骤6:创建Web仪表板

  1. 创建公共目录

    mkdir public
    
  2. 创建 public/index.html (漂亮的响应式仪表板)

    • 带有CSS样式的完整HTML
    • 用于API交互的JavaScript
    • 实时更新和错误处理

步骤7:配置Git

  1. 创建 .gitignore

    node_modules/
    *.log
    .env
    .DS_Store
    
  2. 初始化Git存储库

    git init
    git add .
    git commit -m "Initial commit: CryptoPrice MCP server"
    

步骤8:创建MCP配置

创建 mcpserver.json

{
  "servers": [{
    "name": "CryptoPrice",
    "command": "node",
    "args": ["server.js"],
    "description": "Cryptocurrency price data from CoinGecko",
    "metadata": {
      "version": "1.0.0",
      "tools": [
        {
          "name": "getCryptoPrice",
          "description": "Get current price of a cryptocurrency"
        },
        {
          "name": "listTopCryptos", 
          "description": "List top cryptocurrencies by market cap"
        }
      ]
    }
  }]
}

🔧 用法

MCP服务器(stdio传输)

# Start MCP server
npm start

# Test with client
npm run client

web界面

# Start web server
npm run web

# Open browser
open http://localhost:3000

API集成

// Get Bitcoin price
fetch('http://localhost:3000/api/crypto/bitcoin')
  .then(response => response.json())
  .then(data => console.log(data));

// Get top 5 cryptocurrencies
fetch('http://localhost:3000/api/top-cryptos?limit=5')
  .then(response => response.json())
  .then(data => console.log(data));

📡 API终点

端点 方法 描述 参数
/api/crypto/:id 获取特定的加密货币价格 currency (可选)
/api/top-cryptos GET 获取顶级加密货币 limit (可选)
/api/health GET 服务器健康检查 无

示例响应

获取 /api/crypto/bitcoin

{
  "id": "bitcoin",
  "currency": "USD",
  "price": 43250.50,
  "formatted": "bitcoin: 43250.50 USD"
}

获取 /api/top-cryptos?limit=3

{
  "cryptos": [
    {
      "id": "bitcoin",
      "name": "Bitcoin",
      "symbol": "BTC",
      "price": 43250.50,
      "change_24h": 2.5
    }
  ],
  "count": 3
}

🛠️ 发展

项目结构

crypto-mcp-server/
├── server.js              # MCP server (stdio transport)
├── client.js              # MCP client for testing
├── web-server.js          # HTTP server with API endpoints
├── package.json           # Dependencies and scripts
├── mcpserver.json         # MCP server configuration
├── .gitignore            # Git ignore rules
├── public/
│   └── index.html        # Web dashboard
└── README.md             # This file

添加新功能

  1. 添加新的MCP工具

    server.tool("newTool", {
      param: z.string().describe("Parameter description")
    }, async ({ param }) => {
      // Implementation
      return { content: [{ type: "text", text: "Result" }] };
    });
    
  2. 添加新的API终结点

    app.get('/api/new-endpoint', async (req, res) => {
      // Implementation
      res.json({ result: "data" });
    });
    

环境变量

创建 .env 配置文件:

PORT=3000
API_BASE_URL=https://api.coingecko.com/api/v3
CACHE_DURATION=60000

🧪 测试

手动测试

# Test MCP server
npm run client

# Test web server
curl http://localhost:3000/api/crypto/bitcoin
curl http://localhost:3000/api/top-cryptos?limit=5

自动化测试

# Install testing dependencies
npm install --save-dev jest supertest

# Run tests
npm test

🚀 部署

本地部署

# Install PM2 for process management
npm install -g pm2

# Start with PM2
pm2 start web-server.js --name "crypto-mcp-web"
pm2 start server.js --name "crypto-mcp-server"

Docker部署

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "run", "web"]

云部署

  • Heroku:使用 Procfile 随着 web: node web-server.js
  • 维塞尔:部署为无服务器功能
  • 铁路:直接Git部署
  • 数字海洋:使用应用平台

🤝 贡献

  1. 分叉存储库
  2. 创建特征分支(git checkout -b feature/amazing-feature)
  3. 提交更改(git commit -m 'Add amazing feature')
  4. 推送到分支(git push origin feature/amazing-feature)
  5. 打开拉取请求

开发指南

  • 遵循ES6+标准
  • 为函数添加JSDoc注释
  • 测试所有新功能
  • 更新文档

📄 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。


🔗 链接


内置于❤️ 靠近 AdI-70