Sponsored by Deepsite.site

MCP サーバー/クライアント サンプル

Created By
ykitaza9 months ago
Content

MCP サーバー/クライアント サンプル

🔍 Model Context Protocol(MCP)の実装サンプルプロジェクト

💡 プロジェクトの背景

このプロジェクトは以下の目的で作成されました:

  • MCPの基礎学習: Model Context Protocolの基本概念を理解するための最小限の実装例を提供
  • シンプルな実装: 必要最小限の機能に絞ったMCPサーバーの実装により、プロトコルの本質的な部分に焦点を当てる
  • 独立した実装: Claude Desktop Appなどの特定のクライアントに依存せず、MCPサーバーを自前で実装する方法を示す
  • コストをかけず検証: Google Gemini 経由で MCP を利用することで、コストをかけず(無料枠等の活用可)検証を行うことが可能

このサンプルプロジェクトを通じて、MCPの基本的な仕組みとツール連携の実装方法を学ぶことができます。

🎯 機能概要

このプロジェクトは以下の主要機能を提供します:

MCPサーバー機能

  • 数値比較ツールの提供
    • 2つの数字の大小比較を行うツールを実装します。とても単純ですが、AIが間違えやすい比較問題(9.11と9.9の大小比較等)を解決します。
  • ツールの登録・実行管理

ツール使用前

通常のチャット画面

ツール使用後

数値比較ツールの実行結果

MCPクライアント機能

  • サーバーとの双方向通信
  • 設定ファイルによる接続管理
  • エラーハンドリングとリトライ処理

チャットインターフェース

  • Google Gemini APIによる自然言語処理
  • MCPツールとの連携機能

チャットCLIの利用イメージ

📋 必要要件

  • Bun ランタイム(v1.0.0以上)
  • MCP対応クライアント(例:Claude Desktop App、Cline、Cursor)
  • Gemini API キー(チャットCLI利用時)

🚀 クイックスタート

1. プロジェクトのセットアップ

# 依存関係のインストール
bun install

# 環境変数ファイルの作成
cp .env.example .env

# .envファイルにGemini APIキーを設定
# Google Cloud ConsoleからAPIキーを取得して設定
GEMINI_API_KEY="your-api-key-here"

2. サーバー設定

// server-config.jsonを作成
{
    "my-simple-tool": {
        "command": "bun",
        "args": [
            "run",
            "/absolute/path/to/mcp-server/index.ts"
        ]
    }
}

※ パスは環境に合わせて適切な絶対パスに変更してください。

3. 実行

# チャットCLIの起動
bun run chat

🏗️ システム構成

ディレクトリ構造

src/
├── index.ts                 # チャットCLIのエントリーポイント
├── llm-clients/            # LLMクライアント実装
│   └── gemini.ts           # Google Gemini APIクライアント
├── mcp-client/            # MCPクライアントモジュール
│   ├── client.ts          # MCPツールクライアント実装
│   └── config.ts          # クライアント設定ローダー
└── mcp-server/           # MCPサーバーモジュール
    ├── index.ts          # サーバーのエントリーポイント
    └── tools/            # MCPツール実装
        └── compare-numbers.ts  # 数値比較ツール

コンポーネントの説明

MCPサーバー

  • src/mcp-server/: Model Context Protocol準拠のサーバー実装
  • ツールの登録と実行を管理
  • 数値比較などのツールを提供

MCPクライアント

  • src/mcp-client/: MCPサーバーとの通信を行うクライアントライブラリ
  • サーバー設定の読み込みと接続管理
  • ツールの呼び出しとレスポンス処理

LLMクライアント

  • src/llm-clients/: 言語モデルとの対話を管理
  • Google Gemini APIを使用した自然言語処理
  • MCPツールとの連携機能を実装

データフロー

  1. ユーザーがチャットCLIに入力

    • 質問やコマンドをテキストで入力
    • 入力は日本語で自然な形式が可能
  2. Geminiクライアントが入力を処理

    • 入力テキストを分析
    • ツール使用の必要性を判断
    • 適切なツールとパラメータを選択
  3. 必要に応じてMCPツールを呼び出し

    • MCPクライアントを通じてサーバーと通信
    • ツールに必要なパラメータを渡す
    • 実行結果を受け取る
  4. ツールの実行結果をGeminiに渡して応答を生成

    • ツールの出力を自然言語に変換
    • コンテキストに応じた適切な説明を生成
    • エラー発生時は分かりやすいメッセージを作成
  5. 結果をユーザーに表示

    • 処理結果を日本語で分かりやすく表示
    • エラーが発生した場合は対処方法も提示

⚙️ 設定ガイド

サーバー設定

サーバーの設定は以下の2つのファイルで管理します:

1. 環境変数(.env)

# Google Cloud ConsoleからAPIキーを取得して設定
GEMINI_API_KEY="your-api-key-here"

2. サーバー設定(server-config.json)

// server-config.jsonを作成
{
    "my-simple-tool": {
        "command": "bun",
        "args": [
            "run",
            "/absolute/path/to/mcp-server/index.ts"
        ]
    }
}
設定項目必須デフォルト値説明
command-サーバー実行コマンド(bun/node等)
args-実行引数(サーバーファイルパス等)
disabled-falseサーバーの無効化フラグ
autoApprove-[]自動承認するツールのリスト
timeout-30000ツール実行のタイムアウト時間(ミリ秒)

⚠️ 重要な注意点

  • サーバーファイルのパスは必ず絶対パスを使用
  • 設定変更後はクライアントの再起動が必要
  • autoApproveの使用は必要最小限に
  • 環境変数は.envファイルで管理し、.gitignoreに追加

基本的な使い方

# チャットの開始
bun run chat

# チャットの終了方法
exit    # 終了
quit    # 終了
終了     # 終了
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
WindsurfThe new purpose-built IDE to harness magic
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.
DeepChatYour AI Partner on Desktop
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Tavily Mcp
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.
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
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.
CursorThe AI Code Editor
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Serper MCP ServerA Serper MCP Server
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"
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright McpPlaywright MCP server
Amap Maps高德地图官方 MCP Server
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
ChatWiseThe second fastest AI chatbot™
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.