本教學課程說明如何將遠端開發人員知識 MCP 伺服器,連結至以 LangChain、LlamaIndex 和 AutoGen 建構的自訂 AI 代理程式架構。
將自訂 AI 代理連結至遠端 Model Context Protocol (MCP) 伺服器,代理就能動態搜尋及擷取涵蓋 Google Cloud、Firebase、Android、Google 地圖平台、Chrome 等項目的最新 Google 開發人員說明文件。
必要條件
開始前,請先完成下列必要條件:
- 產生 Developer Knowledge API 金鑰:按照 API 金鑰設定指南的說明,在 Google Cloud 雲端專案中啟用 Developer Knowledge API 並建立 API 金鑰。
- 產生 Gemini API 金鑰:在 Google AI Studio 中建立 API 金鑰,驗證 Gemini 模型,或重複使用 Google Cloud API 金鑰 (如果已啟用 Generative Language API)。
設定環境變數:在終端機中將 API 金鑰設為環境變數:
export DEVELOPERKNOWLEDGE_API_KEY="YOUR_API_KEY" export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"安裝 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 代理
以下範例會將 Developer Knowledge 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 Developers 官方開發人員說明文件。
安裝依附元件
安裝 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從說明文件集直接取得答案,並避免使用get_documents要求完整頁面內容,除非search_documents中的程式碼片段詳細資料不足。 - 保護 API 金鑰:將 Developer Knowledge API 和 Gemini API 金鑰儲存在環境變數或標準 Secret Manager 系統中,切勿在程式碼中硬式編碼憑證。
後續步驟
如要進一步瞭解 Developer Knowledge MCP 伺服器,請參閱下列資源:
- 請參閱完整的 Developer Knowledge MCP 伺服器安裝指南。
- 查看可用的語料庫網域。
- 瞭解如何從說明文件生成答案。