MCPLEARNING
MCP + LangChain デモ
これは、MCP(モデルコンテキストプロトコル)サーバーを構築し、LangChainとLangGraphを使用してLLMエージェントに接続する方法を示す初心者向けのプロジェクトです。
MCPとは?
MCP(モデルコンテキストプロトコル) は、カスタムツール(関数)を標準化された方法でLLMに公開できるオープンプロトコルです。AIモデルのためのユニバーサルプラグインシステムと考えてください。
主要な概念:
用語 | 定義 |
MCPサーバー | トランスポート(stdioまたはHTTP)を介してツール(関数)を公開するプロセス。LLMはこれらのツールを呼び出すことができます。 |
MCPクライアント | 1つ以上のMCPサーバーに接続し、そのツールを発見してLLMに転送するプロセス。 |
ツール |
|
トランスポート | クライアントとサーバー間の通信方法。 |
FastMCP |
|
Related MCP server: Model Context Protocol Multi-Agent Server
プロジェクト構造
MCPLEARNING/
├── mathserver.py # MCP Server 1 - Math tools (stdio transport)
├── weather.py # MCP Server 2 - Weather tool (HTTP transport)
├── client.py # LangChain agent that connects to both servers
├── .env # API keys (NOT pushed to GitHub)
├── .gitignore
├── requirements.txt
└── pyproject.toml仕組み(ステップバイステップ)
ステップ 1: MCPサーバー — mathserver.py
このファイルは、「Math」 という名前のMCPサーバーを作成し、2つのツールを公開します:
add(a, b)— 2つの整数の合計を返します。multiply(a, b)— 2つの整数の積を返します。
これはstdioトランスポートで実行されます。つまり、クライアントがそれをサブプロセスとして起動し、標準入出力を介して通信します。ポートは必要ありません。
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Math")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Addition of two numbers"""
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiplication of two numbers"""
return a * b
if __name__ == "__main__":
mcp.run(transport="stdio")ステップ 2: MCPサーバー — weather.py
このファイルは、「Weather」 という名前のMCPサーバーを作成し、1つのツールを公開します:
get_weather(location)— 指定された場所の天気情報を返します。
これはstreamable-httpトランスポートで実行されます。つまり、http://127.0.0.1:8000/mcp でWebサーバーを起動します。クライアントはHTTPを介して接続します。
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Weather")
@mcp.tool()
async def get_weather(location: str) -> str:
"""Get the weather"""
return "It's always raining in California"
if __name__ == "__main__":
mcp.run(transport="streamable-http")ステップ 3: クライアントエージェント — client.py
これはプロジェクトの頭脳です。以下のことを行います:
両方のMCPサーバーに接続します(
MultiServerMCPClientを使用)。両方のサーバーからすべてのツールを発見します(
add、multiply、get_weather)。Groq LLM(ホスト型オープンソースモデル)を作成し、ツールをそれにバインドします。
LangGraphエージェントを構築します。これは以下のようなステートマシンです:
LLMは、ツールを呼び出すか直接応答するかを決定します。
ツールが呼び出された場合、その結果は最終的な回答のためにLLMにフィードバックされます。
2つのクエリをテストします:
「3 + 5は何ですか?」 →
addツールを使用します。「カリフォルニアの天気はどうですか?」 →
get_weatherツールを使用します。
前提条件
Python 3.13+
uv パッケージマネージャー(推奨)または pip
Groq APIキー — console.groq.com から無料で取得できます
セットアップ
1. リポジトリをクローンする
git clone https://github.com/<YOUR_USERNAME>/MCPLEARNING.git
cd MCPLEARNING2. 仮想環境を作成してアクティブ化する
# Using uv (recommended)
uv venv
uv pip install -r requirements.txt
# Or using pip
python -m venv .venv
.venv\Scripts\activate # Windows
source .venv/bin/activate # Mac/Linux
pip install -r requirements.txt3. APIキーを設定する
プロジェクトルートに .env ファイルを作成します:
GROQ_API_KEY=your_groq_api_key_here重要:
.envファイルは絶対にコミットしないでください。.gitignoreによって除外されています。
プロジェクトの実行
2つのターミナルを開く必要があります:
ターミナル 1 — Weather MCPサーバーを起動する
python weather.py次のように表示されるはずです:
INFO: Uvicorn running on http://127.0.0.1:8000注:
weather.pyのみ手動で起動する必要があります。mathserver.pyはクライアントによって自動的に起動されます(stdioトランスポート)。
ターミナル 2 — クライアントを実行する
python client.py期待される出力
Available MCP tools:
- add
- multiply
- get_weather
==============================
Testing Math MCP
==============================
Math Response: 3 + 5 = 8.
==============================
Testing Weather MCP
==============================
Weather Response: It's always raining in California.独自のMCPサーバーを作成する方法
MCPライブラリをインストールします:
pip install mcp新しいPythonファイルを作成します(例:
myserver.py):
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("MyServer")
@mcp.tool()
def my_tool(param: str) -> str:
"""Description of what this tool does."""
return f"Result: {param}"
if __name__ == "__main__":
mcp.run(transport="stdio") # For stdio transport
# mcp.run(transport="streamable-http") # For HTTP transportクライアントで接続します。
MultiServerMCPClient設定に追加します:
client = MultiServerMCPClient({
"myserver": {
"command": "python",
"args": ["myserver.py"],
"transport": "stdio",
},
})トランスポートの比較
トランスポート | 仕組み | いつ使用するか |
stdio | クライアントがサーバーをサブプロセスとして起動します。標準入出力を介して通信します。 | ローカルツール、シンプルなセットアップ、ネットワーク不要。 |
streamable-http | サーバーがWebサーバーとして実行されます。クライアントはHTTPを介して接続します。 | リモートツール、複数クライアント、マシン間アクセス。 |
使用されている主要なライブラリ
ライブラリ | 目的 |
|
|
| MCPサーバーとLangChainツール間のブリッジ。 |
| Groqホスト型LLMのためのLangChain統合。 |
| エージェントワークフローをグラフとして構築(エージェント ↔ ツールループ)。 |
|
|
注意すべき重要な点
クライアントの前にWeatherサーバーが実行されている必要があります — HTTPトランスポートを使用するため、サーバープロセスを最初に起動する必要があります。Mathサーバー(stdio)はクライアントによって自動的に起動されます。
Groq APIキーが必要です — これがないと、LLM呼び出しは失敗します。console.groq.com から無料のキーを取得してください。
.envをコミットしないでください — コードをプッシュする前に、必ず.gitignoreに.envを追加してください。ポートの競合 — Weatherサーバーはデフォルトでポート8000を使用します。別のプロセスがそのポートを使用している場合、サーバーは起動に失敗します。
Windowsのエンコーディングの問題 — Windowsでは、コンソールがLLMから返されるUTF-8文字をサポートしない場合があります。
client.pyはsys.stdout.reconfigure(encoding="utf-8")でこれを処理します。モデルの可用性 — Groqモデル名(
openai/gpt-oss-120b)は、Groqプラットフォーム上で有効で利用可能である必要があります。現在のオプションについては、Groqのモデルリスト を確認してください。
This server cannot be deployed
Maintenance
Related MCP Connectors
LLM Orchestration Agent (Mcp)
MCP server connecting AI agents to 100+ apps (Gmail, Slack, Notion, GitHub) via one-click OAuth.
MCP server for langchain documentation, generated by doc2mcp.
Nifty's MCP server — exposes tasks, projects, messages, and files as tools for AI agents.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA Model Context Protocol (MCP) server that demonstrates mathematical capabilities through a LangChain integration, allowing clients to perform math operations via the MCP protocol.-
- FlicenseNot gradedqualityDmaintenanceDemonstrates custom MCP servers for math and weather operations, enabling multi-agent orchestration using LangChain, Groq, and MCP adapters for both local and remote tool integration.1-
- FlicenseNot gradedqualityDmaintenanceA demonstration MCP server that provides math (add/multiply) and weather tools, connecting via stdio and streamable HTTP, and integrates with LangChain and LangGraph for agentic workflows.-
- FlicenseNot gradedqualityDmaintenanceA collection of MCP servers demonstrating math operations, weather data, and LangGraph workflows.1-