mcpField
M
MCP to LangChain/LangGraph Adapter

MCP to LangChain/LangGraph Adapter

ローカル
github.com/SDCalvoAI・エージェント082 週間前に更新

MCP to LangChain/LangGraph Adapter について

MCPサーバーに接続し、ツールを検出してLangChainやLangGraphで使える形式に変換するアダプターです。MCPツールを使うエージェントやワークフローを開発する人向けです。

主な機能

  1. 01MCPサーバーへの接続
  2. 02利用可能なツールの検出
  3. 03LangChain用ツールへの変換
  4. 04LangGraphエージェント対応
  5. 05サーバープロセス環境変数の設定

活用シーン

  1. 01LangChainエージェントでMCPツールを利用
  2. 02MCPツールを使ったLangGraphエージェントの構築
  3. 03名前を指定したツールの選択
  4. 04サーバーへの環境変数の受け渡し

MCP 対応

MCPサーバーに接続してツールを取得し、LangChainやLangGraphで使える形式に変換します。

設定

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

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

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

リポジトリ

ツール

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

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

詳細

MCP から LangChain/LangGraph へのアダプター

このプロジェクトは、LangChain および LangGraph アプリケーションで MCP(Multi-modal Conversational Procedure)サーバーのツールを使用できるようにするアダプターを提供します。このアダプターを使うと、MCP のツールを AI アプリケーションのパイプラインにシームレスに統合できます。

目次

はじめに

MCP から LangChain/LangGraph へのアダプターは、標準化されたインターフェースを通じてさまざまなツールを提供する MCP サーバーと、LLM を使ったアプリケーションの構築に広く使われているフレームワークである LangChain/LangGraph の間をつなぎます。このアダプターを使うと、次のことができます。

  • MCP サーバーに接続する
  • 利用可能なツールを見つける
  • MCP ツールを LangChain 互換のツールに変換する
  • LangChain エージェント、チェーン、LangGraph エージェントでこれらのツールを使用する

インストール

このアダプターを使用するには、必要なパッケージをインストールしてください。

# If using pipenv (recommended)
pipenv install mcp langchain langchain-openai langgraph python-dotenv

# If using pip
pip install mcp langchain langchain-openai langgraph python-dotenv

API キーの設定

OpenAI モデルを使う例では、OpenAI API キーが必要です。推奨される設定方法は、.env ファイルを使うことです。

  1. プロジェクトのルートに、.env.example をもとにした .env ファイルを作成します。
OPENAI_API_KEY=your_actual_api_key_here
  1. コード内で環境変数を読み込みます。
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

または、API キーを環境変数またはコードに直接設定することもできます。

import os
os.environ["OPENAI_API_KEY"] = "your_api_key_here"

はじめ方

MCP サーバーのセットアップ

アダプターを使用する前に、MCP サーバーを実行しておく必要があります。このアダプターは、用意した MCP サーバースクリプトと連携するように設計されています。

  1. 基本的な MCP サーバースクリプト(例:simple_server.py)を作成します。
import mcp
from mcp.server import expose

@expose()
def add(a: int, b: int) -> int:
    """Add two numbers and return the result."""
    return a + b

@expose()
def get_weather(city: str) -> str:
    """
    Get the current weather for a city.

    Args:
        city: The name of the city to get weather for
    """
    # In a real application, you'd call a weather API here
    return f"Weather in {city}: Sunny +11°C"

if __name__ == "__main__":
    mcp.run(transport='stdio')

このサーバーの例では、2 つのツールを公開します。

  • add:2 つの整数を受け取り、その合計を返します
  • get_weather:都市名を受け取り、シミュレートした天気予報を返します
MCP サーバーへの接続

アダプターが MCP サーバーへの接続を自動的に管理します。

from mcp_langchain_adapter import MCPAdapter

# Create an adapter instance, pointing to your MCP server script
adapter = MCPAdapter("simple_server.py")

# Initialize the connection and get the list of available tools
tools = adapter.get_tools()

# Print the available tools
print(f"Found {len(tools)} tools:")
for tool in tools:
    print(f"- {tool.name}: {tool.description}")
LangChain で MCP ツールを使用する

ツールを取得したら、LangChain アプリケーションで使用できます。

from langchain.agents import AgentExecutor, create_react_agent
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI

# Initialize the language model
llm = ChatOpenAI(model="gpt-3.5-turbo")

# Create a prompt template for the agent
template = """Answer the following questions as best you can using the provided tools.

Available tools:
{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought: """

prompt_template = PromptTemplate.from_template(template)

# Create a LangChain agent with the MCP tools
agent = create_react_agent(llm, tools, prompt_template)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# Run the agent
result = agent_executor.invoke({"input": "What is 5 + 7?"})
print(result["output"])
LangGraph で MCP ツールを使用する

LangGraph は、エージェントを構築するための、よりモダンで柔軟な方法を提供します。LangGraph で MCP ツールを使用する方法は次のとおりです。

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver

# Initialize the language model
llm = ChatOpenAI(model="gpt-3.5-turbo")

# Create a memory saver for conversation history
memory = MemorySaver()

# Create a LangGraph react agent with the MCP tools
agent = create_react_agent(
    llm,
    tools,
    prompt="You are a helpful AI assistant that can use tools to solve problems.",
    checkpointer=memory
)

# Create the configuration with thread ID for memory
config = {"configurable": {"thread_id": "example-thread"}}

# Run the agent with a question
result = agent.invoke(
    {"messages": [HumanMessage(content="What is 5 + 7?")]},
    config
)

# Get the final answer
final_answer = result["messages"][-1].content
print(final_answer)

# Continue the conversation with a follow-up question
state = memory.get("example-thread")
messages = state["messages"] + [HumanMessage(content="What's the weather in London?")]
result = agent.invoke({"messages": messages}, config)
print(result["messages"][-1].content)

API リファレンス

MCPAdapter

MCPAdapter クラスは、MCP サーバーへの接続を管理し、MCP ツールを LangChain ツールに変換します。

コンストラクター
MCPAdapter(server_script_path: str, env: Dict[str, str] = None)
  • server_script_path:実行する MCP サーバースクリプトのパス
  • env:サーバープロセス用のオプションの環境変数
メソッド
  • initialize():MCP サーバーへの接続を同期的に初期化します
  • get_tools() -> List[BaseTool]:利用可能なすべてのツールを LangChain ツールとして取得します
  • get_tool_names() -> List[str]:利用可能なすべてのツールの名前を取得します
  • get_tool_by_name(name: str) -> Optional[BaseTool]:名前を指定して特定のツールを取得します
  • close() -> None:リソースをクリーンアップします(非同期メソッド)
MCPToolWrapper

MCPToolWrapper クラスは、MCP ツールをラップするために LangChain の BaseTool を拡張します。

MCPToolWrapper(
    name: str,
    description: str,
    server_script_path: str,
    env: Optional[Dict[str, str]] = None,
    args_schema: Optional[Type[BaseModel]] = None
)
  • name:ツールの名前
  • description:ツールの説明
  • server_script_path:MCP サーバースクリプトのパス
  • env:サーバープロセス用のオプションの環境変数
  • args_schema:ツール引数用のオプションの Pydantic モデル
ユーティリティ関数
  • get_langchain_tools(server_script_path: str, env: Dict[str, str] = None) -> List[BaseTool]: MCP サーバーから LangChain ツールを取得するための便利な関数

使用例

基本的な使い方

アダプターの使用方法を示す完全な例を紹介します。

from mcp_langchain_adapter import MCPAdapter

# Create an adapter instance
adapter = MCPAdapter("simple_server.py")

# Get all tools
tools = adapter.get_tools()

# Print information about the tools
print(f"Found {len(tools)} tools:")
for tool in tools:
    print(f"- {tool.name}: {tool.description}")

# Use a specific tool
add_tool = adapter.get_tool_by_name("add")
if add_tool:
    result = add_tool.run({"a": 5, "b": 7})
    print(f"Result of add(5, 7): {result}")

# Use another tool
weather_tool = adapter.get_tool_by_name("get_weather")
if weather_tool:
    result = weather_tool.run({"city": "London"})
    print(f"Result of get_weather('London'): {result}")
LangChain エージェントとの統合

LangChain エージェントとの統合例全体については、example_agent_integration.py ファイルを参照してください。

主な機能:

  • MCP サーバーに接続します
  • 利用可能なツールを取得します
  • ツールを使って LangChain エージェントを作成します
  • さまざまな種類のクエリでエージェントを実行します
LangGraph エージェントとの統合

LangGraph エージェントとの統合例全体については、example_langgraph_integration.py ファイルを参照してください。

主な機能:

  • MCP サーバーに接続します
  • 利用可能なツールを取得します
  • ツールを使って LangGraph の ReAct エージェントを作成します
  • チェックポイントを使って会話履歴を管理します
  • さまざまな種類のクエリでエージェントを実行します
  • エージェントの思考プロセスをストリーミングする方法を示します

トラブルシューティング

よくある問題
  1. MCP サーバーの接続に関する問題

    • MCP サーバーのスクリプトへのパスが正しいことを確認してください
    • サーバースクリプトに実行権限があることを確認してください
    • サーバースクリプトが MCP プロトコルを適切に実装していることを確認してください
  2. ツールの実行エラー

    • ツールの入力形式が正しいことを確認してください
    • MCP サーバーでツールが適切に定義されていることを確認してください
    • ツールの応答にエラーメッセージがないか確認してください
  3. LangChain/LangGraph との統合に関する問題

    • ツールが LangChain 形式に適切に変換されていることを確認してください
    • エージェントが正しく設定されていることを確認してください
    • エージェントに適切な形式の入力を渡していることを確認してください
    • LangGraph に関する問題の場合は、スレッド ID とメモリの設定を確認してください
デバッグ

接続の問題をデバッグするには、MCP サーバーのスクリプトにログを追加できます。

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("mcp_server.log"),
        logging.StreamHandler()
    ]
)

# Rest of your MCP server code...

コントリビューション

アダプターの改善に向けたコントリビューションを歓迎します。以下の方法で参加できます。

  • バグや問題を報告する
  • 新機能を追加する、または既存の機能を改善する
  • ドキュメントを改善する
  • テストを作成する
  • さまざまな LangChain/LangGraph コンポーネントとの統合例を共有する

コントリビューションの際は、次の手順に従ってください。

  1. リポジトリをフォークします
  2. 機能追加用のブランチを作成します
  3. 変更を加えます
  4. プルリクエストを送信します

コメント

MCP は初めてですか?

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

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