Sponsored by Deepsite.site

自作の Model Context Protocol (MCP) クライアントとサーバー

Created By
okikusan-public7 months ago
Content

自作の Model Context Protocol (MCP) クライアントとサーバー

このリポジトリは、Model Context Protocol (MCP)のクライアントとサーバーを自作で実装したものです。AnthropicのClaudeモデルとのインタラクションを通じて、MCPの実装方法と活用例を示しています。

概要

Model Context Protocol (MCP)は、AIアシスタントと様々なデータソースを接続するためのオープンスタンダードです。このプロジェクトでは、MCPの基本的な概念を理解し、実際に動作するクライアントとサーバーの両方を実装しています。

主な機能

  • MCPサーバー:

    • Express.jsを使用したRESTful APIサーバー
    • AnthropicのAPIと連携したAI処理エンジン
    • メッセージングとコンテキスト管理機能
  • WebSocketサポート:

    • リアルタイムストリーミングレスポンス
    • 双方向通信によるインタラクティブな対話
    • イベントベースの非同期通信
  • MCPクライアント:

    • HTTPとWebSocketの両方をサポートする統合クライアント
    • シンプルで使いやすいAPI
    • 複数の通信方式に対応
  • デモアプリケーション:

    • HTTP通信の基本デモ
    • WebSocketストリーミングデモ
    • インタラクティブチャットコンソール

技術スタック

  • バックエンド: Node.js, Express, WebSocket (ws)
  • フロントエンド: TypeScript, Axios
  • AI連携: Anthropic Claude API
  • その他: dotenv(環境変数管理), TypeScript(型安全な開発)

プロジェクト構造

mcp-client-server/
├── client/               # MCPクライアント実装
│   ├── http-client.ts    # HTTP通信クライアント
│   ├── ws-client.ts      # WebSocket通信クライアント
│   ├── mcp-client.ts     # 統合クライアント
│   ├── types.ts          # 型定義
│   └── index.ts          # エントリーポイント
├── server/               # MCPサーバー実装
│   ├── controllers/      # APIコントローラー
│   ├── routes/           # APIルート定義
│   ├── services/         # MCPサービス
│   ├── websocket/        # WebSocketサポート
│   ├── types.ts          # 型定義
│   └── index.ts          # サーバーエントリーポイント
├── examples/             # サンプルアプリケーション
│   ├── http-demo.ts      # HTTPデモ
│   ├── websocket-demo.ts # WebSocketデモ
│   └── chat-demo.ts      # チャットデモ
├── MCP_DOCUMENTATION.md  # MCPに関する詳細資料
├── dist/                 # ビルド出力ディレクトリ
└── .env                  # 環境変数設定

セットアップ方法

前提条件

  • Node.js 14以上
  • Anthropic API Key (Claude APIにアクセスするため)

インストール手順

  1. リポジトリをクローンまたはダウンロードします

  2. 依存関係をインストールします

npm install
  1. 環境変数ファイルを設定します
# .envファイルを作成し、以下の内容を設定
PORT=3000
HOST=localhost
ANTHROPIC_API_KEY=your_anthropic_api_key_here
MODEL_NAME=claude-3-opus-20240229
MAX_TOKENS=1000

使い方

サーバーの起動

npm run start:server

サーバーはデフォルトで http://localhost:3000 で起動します。 WebSocketサーバーも同時に ws://localhost:3000 で利用可能になります。

デモアプリケーションの実行

1. HTTPデモの実行

サーバーが起動していることを確認してから実行します。

npm run demo:http

このデモはHTTP APIを使用してMCPサーバーと通信し、以下を行います:

  • サーバーのヘルスチェック
  • シンプルなプロンプトの送信と応答の表示
  • 完全なメッセージリクエストの送信とレスポンスの解析

2. WebSocketストリーミングデモの実行

npm run demo:ws

このデモはWebSocketを使用して以下を実演します:

  • WebSocket接続の確立
  • シンプルなプロンプトの送信
  • リアルタイムのストリーミングレスポンスの受信
  • ストリーミングの進行状況の表示

3. インタラクティブチャットデモの実行

npm run demo:chat

コマンドライン上でリアルタイムにMCPと会話できるインタラクティブなデモです:

  • 「exit」と入力するまで会話を継続
  • WebSocketを使用したストリーミングレスポンス
  • 会話履歴の保持と文脈を考慮した応答

APIリファレンス

HTTP API

エンドポイントメソッド説明
/api/healthGETサーバーのヘルスチェック
/api/messagePOST完全なMCPメッセージを送信
/api/promptPOSTシンプルなテキストプロンプトを送信

WebSocket API

WebSocketエンドポイント: ws://localhost:3000

クライアントからサーバーへのメッセージタイプ

  • message - 完全なMCPメッセージを送信
  • prompt - シンプルなテキストプロンプトを送信
  • stream - ストリーミングレスポンスをリクエスト

サーバーからクライアントへのイベントタイプ

  • connection - 接続状態の通知
  • message_response - メッセージへの応答
  • prompt_response - プロンプトへの応答
  • stream_start - ストリーミング開始通知
  • stream_chunk - ストリーミングデータチャンク
  • stream_end - ストリーミング終了通知
  • error - エラー通知

プログラム例

クライアントAPIの使用例

import { createMCPClient, createPromptRequest, MCPRole } from './client';

// クライアントの作成
const client = createMCPClient({
  apiBaseUrl: 'http://localhost:3000',
  wsBaseUrl: 'ws://localhost:3000'
});

// HTTP APIを使用した例
async function httpExample() {
  // サーバーの状態確認
  const health = await client.healthCheck();
  console.log('サーバー状態:', health.status);
  
  // シンプルなプロンプト送信
  const response = await client.sendPrompt('AIの未来について教えてください');
  console.log('応答:', response.response);
}

// WebSocketを使用した例
async function wsExample() {
  // WebSocket接続
  await client.connectWebSocket();
  
  // イベントリスナーの登録
  client.on('prompt_response', (data) => {
    console.log('応答:', data.response);
  });
  
  // プロンプトの送信
  client.sendWebSocketPrompt('量子コンピューティングの可能性は?');
  
  // ストリーミングでのリクエスト
  client.on('stream_chunk', (chunk) => {
    // リアルタイムでチャンクを処理
    process.stdout.write(chunk.content[0].text);
  });
  
  // ストリーミングリクエストの送信
  client.sendStreamRequest({
    messages: [{
      role: MCPRole.USER,
      content: [{ type: 'text', text: 'AIと人間の協調について詩を書いてください' }]
    }],
    model: 'claude-3-opus-20240229'
  });
}

拡張と貢献

このプロジェクトは基本的な実装を提供していますが、以下のような拡張が可能です:

  • マルチモーダル機能の追加(画像処理など)
  • 会話履歴の永続化
  • 認証機能の強化
  • ユーザーインターフェースの実装
  • より高度なエラーハンドリング

関連資料

詳細な技術資料は MCP_DOCUMENTATION.md を参照してください。このドキュメントには以下の情報が含まれています:

  • MCPの概念と原理
  • アーキテクチャの詳細
  • 実装パターン
  • ベストプラクティス
  • 性能最適化のヒント

ライセンス

MIT

注意事項

  • このプロジェクトは教育・研究目的で提供されています
  • 本番環境で使用する場合は、セキュリティやエラー処理などを強化してください
  • APIキーなどの機密情報を適切に管理してください
  • Anthropic APIの利用規約に従ってください
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Playwright McpPlaywright MCP server
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
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.
Serper MCP ServerA Serper MCP Server
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
WindsurfThe new purpose-built IDE to harness magic
Amap Maps高德地图官方 MCP Server
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.
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"
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Tavily Mcp
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
CursorThe AI Code Editor
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
ChatWiseThe second fastest AI chatbot™