mcpField
R
RealTime-CryptoPrice-MCP

RealTime-CryptoPrice-MCP

ローカル
github.com/AdI-70金融データ158 週間前に更新

RealTime-CryptoPrice-MCP について

RealTime-CryptoPrice-MCPは、CoinGeckoの暗号資産価格や市場データを提供するMCPサーバーです。相場を調べるAIエージェント向けに、stdio接続、HTTP API、テスト・監視用のWebダッシュボードを備えています。

主な機能

  1. 01暗号資産のリアルタイム価格取得
  2. 02複数の銘柄と表示通貨に対応
  3. 03時価総額順の銘柄一覧
  4. 04HTTP APIとWebダッシュボード
  5. 05stdioとHTTPでの接続

活用シーン

  1. 01特定の暗号資産の現在価格を確認
  2. 02主要銘柄と24時間の変動を確認
  3. 03Webダッシュボードで価格検索をテスト
  4. 04MCP経由でAIエージェントに市場データを提供

MCP 対応

MCPクライアント向けに、CoinGeckoの市場データをツールとして提供し、標準のstdioトランスポートに対応します。HTTPエンドポイントも利用できます。

設定

ローカルサーバーの設定はどのクライアントでも共通です。コピーしてクライアントの MCP 設定ファイルに貼り付けてください。

インストール方法は未掲載です

このサーバーのパッケージやリモートエンドポイントはまだ取得できていません。プロジェクトの README の手順に従ってください。

リポジトリ

ツール

ツール一覧はまだ取得されていません

ローカルサーバーのツールはマシン上で起動して初めて取得できます。メンテナーはまだツール一覧を提供していません。

詳細

🚀 RealTime CryptoPrice MCP Server

CoinGecko API からリアルタイムの暗号資産価格データを提供する、包括的な Model Context Protocol(MCP) サーバーの実装です。このプロジェクトでは、従来の MCP stdio トランスポートと最新の HTTP エンドポイントの両方を実装し、テストと統合の機能を強化しています。

Node.js MCP License API

📋 目次

🎯 概要

このプロジェクトは、AI エージェントとリアルタイムの暗号資産市場データをつなぐ役割を果たす Model Context Protocol(MCP) サーバーを実装しています。以下を提供します。

  • 標準 MCP インターフェース:MCP 準拠のあらゆるクライアントと互換性があります
  • HTTP ウェブダッシュボード:テストとモニタリングに使える、見やすくレスポンシブなインターフェース
  • リアルタイムデータ:CoinGecko API から取得したリアルタイムの暗号資産価格
  • デュアルトランスポート:stdio(標準 MCP)と HTTP エンドポイントの両方に対応
MCP とは?

Model Context Protocol(MCP)は、AI エージェントが外部のデータソースやツールに安全かつ一貫した方法でアクセスできるようにする標準プロトコルです。このサーバーは、AI エージェントが呼び出せる MCP ツールを通じて、暗号資産市場データを公開します。

✨ 特長

🔥 主な機能
  • リアルタイム価格データ:暗号資産の価格と市場データをリアルタイムで取得
  • 複数の暗号資産:Bitcoin、Ethereum、その他 1000 以上のコインに対応
  • 通貨の選択:USD、EUR、JPY、GBP、CAD、AUD での価格表示
  • 暗号資産の上位ランキング:時価総額に基づく暗号資産の一覧
  • シンプルな API 設計:JSON レスポンスを返す RESTful エンドポイント
🎨 ウェブインターフェースの機能
  • レスポンシブダッシュボード:見やすく、モバイルにも対応したインターフェース
  • 稼働状況のリアルタイム監視:サーバーの正常性をリアルタイムで確認
  • インタラクティブなフォーム:暗号資産の価格を簡単に検索
  • 市場の概要:24 時間の変動率を含む暗号資産の上位一覧
  • エラー処理:適切なエラーメッセージと読み込み状態の表示
🔧 技術的な特長
  • MCP プロトコル:AI エージェントとの統合に使える標準の stdio トランスポート
  • Express.js サーバー:ウェブインターフェースと 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. プレゼンテーション層:ウェブダッシュボードを備えた 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 Modules の設定

    // 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-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 を作成する(美しくレスポンシブなダッシュボード)

    • 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/: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:web: node web-server.js を指定した Procfile を使用します
  • Vercel:サーバーレス関数としてデプロイします
  • Railway:Git から直接デプロイします
  • DigitalOcean:App Platform を使用します

🤝 コントリビューション

  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 ライセンスの下でライセンスされています。詳細は LICENSE ファイルをご覧ください。


🔗 リンク


AdI-70 が ❤️ を込めて作成

コメント

MCP は初めてですか?

プロトコルの概要から最初のサーバーの導入まで、よくある疑問にまとめて答えます。

AI アプリケーションが外部のツールやデータソースに統一的な方法で接続するためのオープンなプロトコルです。クライアントはモデルとの対話を担い、MCP サーバーはツール・リソース・プロンプトテンプレートを提供します。標準メッセージでやり取りするため、1 つのサーバーを複数のクライアントで再利用できます。