Developer Knowledge MCP サーバーをカスタム AI エージェントと統合する

このチュートリアルでは、リモートの Developer Knowledge MCP サーバーを LangChain、LlamaIndex、AutoGen で構築されたカスタム AI エージェント フレームワークに接続する方法について説明します。

カスタム AI エージェントをリモート Model Context Protocol(MCP)サーバーに接続することで、エージェントは Google Cloud、Firebase、Android、Google Maps Platform、Chrome などを網羅する、信頼性の高い最新の Google デベロッパー ドキュメントを動的に検索して取得できます。

前提条件

始める前に、次の前提条件を満たしてください。

  1. Developer Knowledge API キーを生成する: API キーの設定ガイドに沿って、Google Cloud プロジェクトで Developer Knowledge API を有効にして API キーを作成します。
  2. Gemini API キーを生成する: Google AI Studio で API キーを作成して Gemini モデルを認証するか、Generative Language API が有効になっている場合は Google Cloud API キーを再利用します。
  3. 環境変数を設定する: ターミナルで API キーを環境変数として設定します。

    export DEVELOPERKNOWLEDGE_API_KEY="YOUR_API_KEY"
    export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
    
  4. Python をインストールする: 開発環境で Python 3.10 以降が使用されていることを確認します。

LangChain を使用して接続する

LangChain アプリケーションは、langchain-mcp-adapters パッケージまたは標準の MCP クライアント トランスポートを使用して、リモート HTTP MCP サーバーに接続できます。

依存関係のインストール

LangChain、Gemini、MCP に必要な Python パッケージをインストールします。

pip install langgraph langchain-google-genai langchain-mcp-adapters mcp

LangChain エージェントを構成する

次の例では、デベロッパー ナレッジ MCP サーバーを Gemini を搭載した LangChain ReAct エージェントに接続します。スクリプトは、streamable_http トランスポートを使用して MultiServerMCPClient をインスタンス化し、X-Goog-Api-Key HTTP ヘッダーをアタッチして、リモートツールを create_react_agent に読み込みます。

import asyncio
import os

from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent

async def run_langchain_agent():
    api_key = os.environ.get("DEVELOPERKNOWLEDGE_API_KEY")
    if not api_key:
        raise ValueError(
            "DEVELOPERKNOWLEDGE_API_KEY environment variable is required."
        )

    gemini_api_key = os.environ.get("GEMINI_API_KEY")
    if not gemini_api_key:
        raise ValueError("GEMINI_API_KEY environment variable is required.")

    # Configure remote MCP connection for Developer Knowledge
    client = MultiServerMCPClient(
        {
            "google-developer-knowledge": {
                "url": "https://developerknowledge.googleapis.com/mcp",
                "transport": "streamable_http",
                "headers": {
                    "X-Goog-Api-Key": api_key,
                },
            }
        }
    )
    tools = await client.get_tools()

    # Initialize Gemini model and ReAct agent
    llm = ChatGoogleGenerativeAI(
        model="gemini-2.5-flash",
        temperature=0,
        google_api_key=gemini_api_key,
    )
    agent = create_react_agent(llm, tools)

    # Run agent query
    response = await agent.ainvoke(
        {
            "messages": [
                (
                    "user",
                    "How do I list Google Cloud Storage buckets in Python?",
                )
            ]
        }
    )
    print("\nAgent Response:\n", response["messages"][-1].content)

if __name__ == "__main__":
    asyncio.run(run_langchain_agent())

LlamaIndex を使用して接続する

LlamaIndex は、ツール仕様を介して MCP サーバーの統合をサポートしており、推論中に取得エージェントが Developer Knowledge ドキュメントをクエリできます。

依存関係のインストール

LlamaIndex コア パッケージ、Gemini LLM、MCP ツール統合をインストールします。

pip install llama-index llama-index-tools-mcp llama-index-llms-google-genai

LlamaIndex エージェントを構成する

次の例では、BasicMCPClient を使用してリモート MCP サーバーに接続し、McpToolSpec でラップして、取得したツールを Gemini を搭載した LlamaIndex FunctionAgent にバインドします。

import asyncio
import os

from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.google_genai import GoogleGenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

async def run_llamaindex_agent():
    api_key = os.environ.get("DEVELOPERKNOWLEDGE_API_KEY")
    if not api_key:
        raise ValueError(
            "DEVELOPERKNOWLEDGE_API_KEY environment variable is required."
        )

    gemini_api_key = os.environ.get("GEMINI_API_KEY")
    if not gemini_api_key:
        raise ValueError("GEMINI_API_KEY environment variable is required.")

    # Connect to the remote Developer Knowledge MCP endpoint
    mcp_client = BasicMCPClient(
        "https://developerknowledge.googleapis.com/mcp",
        headers={"X-Goog-Api-Key": api_key},
    )
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    # Create LlamaIndex FunctionAgent with Gemini
    llm = GoogleGenAI(model="gemini-2.5-flash", api_key=gemini_api_key)
    agent = FunctionAgent(tools=tools, llm=llm)

    # Query the agent
    response = await agent.run(
        "What are the default limits and quotas for the Developer Knowledge"
        " API?"
    )
    print("\nAgent Response:\n", str(response))

if __name__ == "__main__":
    asyncio.run(run_llamaindex_agent())

AutoGen を使用して接続する

Microsoft AutoGen エージェントは、autogen-ext MCP 拡張機能を使用してリモート MCP サーバーと連携できます。これにより、公式の Google デベロッパー ドキュメントにアクセスして、マルチエージェント コラボレーションを実現できます。

依存関係のインストール

AutoGen コア パッケージと MCP 拡張機能パッケージをインストールします。

pip install autogen-agentchat "autogen-ext[mcp,openai]"

AutoGen エージェントを構成する

次の例では、StreamableHttpServerParams を使用してリモート MCP サーバーに接続し、Gemini を搭載した AutoGen AssistantAgent にデベロッパー ナレッジ ツールを登録しています。

import asyncio
import os

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.tools.mcp import StreamableHttpServerParams, mcp_server_tools

async def run_autogen_agent():
    api_key = os.environ.get("DEVELOPERKNOWLEDGE_API_KEY")
    if not api_key:
        raise ValueError(
            "DEVELOPERKNOWLEDGE_API_KEY environment variable is required."
        )

    gemini_api_key = os.environ.get("GEMINI_API_KEY")
    if not gemini_api_key:
        raise ValueError("GEMINI_API_KEY environment variable is required.")

    # Retrieve remote MCP tools for Developer Knowledge by using Streamable HTTP
    server_params = StreamableHttpServerParams(
        url="https://developerknowledge.googleapis.com/mcp",
        headers={"X-Goog-Api-Key": api_key},
    )
    dk_tools = await mcp_server_tools(server_params)

    # Initialize model client with Gemini and assistant agent
    model_client = OpenAIChatCompletionClient(
        model="gemini-2.5-flash",
        api_key=gemini_api_key,
        base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
    )
    developer_assistant = AssistantAgent(
        name="google_docs_assistant",
        model_client=model_client,
        tools=dk_tools,
        system_message=(
            "You are a developer assistant specializing in Google APIs and"
            " SDKs. Use Developer Knowledge tools to retrieve verified"
            " documentation."
        ),
    )

    # Run query with team runner
    team = RoundRobinGroupChat([developer_assistant], max_turns=5)
    stream = team.run_stream(
        task=(
            "Explain how to configure Firebase Cloud Messaging topic"
            " subscriptions."
        )
    )

    async for message in stream:
        print(message)

if __name__ == "__main__":
    asyncio.run(run_autogen_agent())

エージェント統合のベスト プラクティス

Developer Knowledge MCP サーバーを使用してカスタム AI エージェントを構築する場合は、次のガイドラインに従ってください。

  • 検索クエリを絞り込む: search_documents ツールと answer_query ツールはクエリのセマンティクスに基づいて一致するため、一般的な用語ではなく、特定のプロダクト名と関連性の高いキーワードを自然言語クエリに含めます。
  • コンテキスト ウィンドウ トークンを管理する: ドキュメント コーパスから直接回答を得るには answer_query を使用します。search_documents のスニペットの詳細が不十分な場合を除き、get_documents でページ全体の内容をリクエストすることは避けてください。
  • API キーを保護する: Developer Knowledge API と Gemini API のキーを環境変数または標準のシークレット管理システムに保存し、コードに認証情報をハードコードしないでください。

次のステップ

Developer Knowledge MCP サーバーの詳細については、次のリソースをご覧ください。