mcpField
R
RealTime-CryptoPrice-MCP

RealTime-CryptoPrice-MCP

本地服务
github.com/AdI-70金融数据158 周前更新

关于 RealTime-CryptoPrice-MCP

RealTime-CryptoPrice-MCP 是通过 CoinGecko 获取加密货币实时价格和市场数据的 MCP 服务,适用于需要查询行情的 AI Agent。它同时提供 stdio 接口、HTTP API 和用于测试与监控的网页仪表板。

主要功能

  1. 01获取实时加密货币价格
  2. 02支持多种币种与计价货币
  3. 03按市值列出加密货币
  4. 04提供 HTTP API 与网页仪表板
  5. 05支持 stdio 与 HTTP 传输

适用场景

  1. 01查询指定加密货币的当前价格
  2. 02查看主流加密货币及 24 小时变动
  3. 03在网页仪表板测试价格查询
  4. 04通过 MCP 将行情数据提供给 AI Agent

MCP 相关

该 MCP 服务通过工具向 MCP 客户端提供 CoinGecko 加密货币行情数据,并支持标准 stdio 传输;另有 HTTP 端点。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

暂未收录安装方式

我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。

代码仓库

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

🚀 RealTime CryptoPrice MCP 服务

这是一个全面的 Model Context Protocol(MCP) 服务实现,通过 CoinGecko API 提供实时加密货币价格数据。该项目同时展示了传统的 MCP stdio 传输方式和现代 HTTP 端点,以增强测试和集成能力。

Node.js MCP License API

📋 目录

🎯 概述

该项目实现了一个 Model Context Protocol(MCP) 服务,作为 AI Agent 与实时加密货币市场数据之间的桥梁。它提供:

  • 标准 MCP 接口:兼容任何符合 MCP 标准的客户端
  • HTTP Web 仪表板:美观、响应式的界面,用于测试和监控
  • 实时数据:来自 CoinGecko API 的实时加密货币价格
  • 双重传输方式:支持 stdio(标准 MCP)和 HTTP 端点
什么是 MCP?

Model Context Protocol(MCP)是一种标准化协议,使 AI Agent 能够以安全、一致的方式访问外部数据源和工具。该服务通过 MCP 工具公开加密货币市场数据,供 AI Agent 调用。

✨ 功能

🔥 核心功能
  • 实时价格数据:实时加密货币价格和市场数据
  • 多种加密货币:支持 Bitcoin、Ethereum 和 1000 多种币种
  • 货币选择灵活:支持以 USD、EUR、JPY、GBP、CAD、AUD 显示价格
  • 加密货币排行榜:按市值列出加密货币
  • 简洁的 API 设计:提供 JSON 响应的 RESTful 端点
🎨 Web 界面功能
  • 响应式仪表板:美观、适配移动设备的界面
  • 实时状态监控:实时检查服务运行状况
  • 交互式表单:轻松查询加密货币价格
  • 市场概览:展示热门加密货币及其 24 小时涨跌情况
  • 错误处理:提供友好的错误消息和加载状态
🔧 技术特性
  • MCP 协议:通过标准 stdio 传输方式集成 AI Agent
  • 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 Agent 通信的 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. 创建 public 目录

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

    • 完整的 HTML 和 CSS 样式
    • 用于 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/:idGET获取指定加密货币的价格currency(可选)
/api/top-cryptosGET获取排名靠前的加密货币limit(可选)
/api/healthGET检查服务健康状态无
响应示例

GET /api/crypto/bitcoin

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

GET /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
  • Vercel:部署为无服务器函数
  • Railway:直接通过 Git 部署
  • DigitalOcean:使用 App Platform

🤝 参与贡献

  1. Fork 此仓库
  2. 创建功能分支(git checkout -b feature/amazing-feature)
  3. 提交更改(git commit -m 'Add amazing feature')
  4. 推送到分支(git push origin feature/amazing-feature)
  5. 创建 Pull Request
开发指南
  • 遵循 ES6+ 标准
  • 为函数添加 JSDoc 注释
  • 测试所有新功能
  • 更新文档

📄 许可证

本项目采用 MIT 许可证,详情请参阅 LICENSE 文件。


🔗 链接


由 AdI-70 倾心打造 ❤️

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。