Ten samouczek pokazuje, jak połączyć zdalny serwer MCP Developer Knowledge z niestandardowymi platformami agentów AI utworzonymi za pomocą LangChain, LlamaIndex i AutoGen.
Po połączeniu niestandardowych agentów AI ze zdalnym serwerem MCP (Model Context Protocol) mogą oni dynamicznie wyszukiwać i pobierać autorytatywną, aktualną dokumentację dla programistów Google dotyczącą Google Cloud, Firebase, Androida, Google Maps Platform, Chrome i innych usług.
Wymagania wstępne
Zanim zaczniesz, spełnij te wymagania wstępne:
- Wygeneruj klucz interfejsu Developer Knowledge API: włącz interfejs Developer Knowledge API i utwórz klucz interfejsu API w projekcie Google Cloud, postępując zgodnie z przewodnikiem konfiguracji klucza interfejsu API.
- Wygeneruj klucz interfejsu Gemini API: utwórz klucz interfejsu API w Google AI Studio, aby uwierzytelniać modele Gemini, lub użyj ponownie klucza interfejsu Google Cloud API, jeśli jest na nim włączony interfejs Generative Language API.
Ustaw zmienne środowiskowe: ustaw klucze interfejsu API jako zmienne środowiskowe w terminalu:
export DEVELOPERKNOWLEDGE_API_KEY="YOUR_API_KEY" export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"Zainstaluj Pythona: sprawdź, czy środowisko programistyczne używa Pythona 3.10 lub nowszego.
Łączenie się za pomocą LangChain
Aplikacje LangChain mogą łączyć się ze zdalnymi serwerami MCP HTTP za pomocą pakietu langchain-mcp-adapters lub standardowych transportów klienta MCP.
Instalowanie zależności
Zainstaluj wymagane pakiety Pythona dla LangChain, Gemini i MCP:
pip install langgraph langchain-google-genai langchain-mcp-adapters mcp
Konfigurowanie agenta LangChain
W tym przykładzie serwer MCP Developer Knowledge jest połączony z agentem LangChain ReAct opartym na Gemini. Skrypt tworzy instancję MultiServerMCPClient za pomocą transportu streamable_http, dołącza nagłówek HTTP X-Goog-Api-Key i wczytuje narzędzia zdalne do 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())
Łączenie za pomocą LlamaIndex
LlamaIndex obsługuje integrację serwera MCP za pomocą specyfikacji narzędzi, co umożliwia agentom pobierania wysyłanie zapytań do dokumentów Developer Knowledge podczas wnioskowania.
Instalowanie zależności
Zainstaluj podstawowe pakiety LlamaIndex, model LLM Gemini i integrację narzędzi MCP:
pip install llama-index llama-index-tools-mcp llama-index-llms-google-genai
Konfigurowanie agenta LlamaIndex
W tym przykładzie łączymy się ze zdalnym serwerem MCP za pomocą BasicMCPClient, opakowujemy go za pomocą McpToolSpec i łączymy pobrane narzędzia z LlamaIndex FunctionAgent obsługiwanym przez Gemini:
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())
Łączenie się za pomocą AutoGen
Agenci Microsoft AutoGen mogą komunikować się ze zdalnymi serwerami MCP za pomocą autogen-extrozszerzenia MCP, co umożliwia współpracę wielu agentów z dostępem do oficjalnej dokumentacji dla deweloperów Google.
Instalowanie zależności
Zainstaluj pakiety podstawowe AutoGen i rozszerzenia MCP:
pip install autogen-agentchat "autogen-ext[mcp,openai]"
Konfigurowanie agenta AutoGen
W tym przykładzie połączymy się ze zdalnym serwerem MCP za pomocą StreamableHttpServerParams i zarejestrujemy narzędzia Developer Knowledge w usłudze AutoGenAssistantAgent opartej na Gemini:
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())
Sprawdzone metody integracji agenta
Podczas tworzenia niestandardowych agentów AI za pomocą serwera MCP Developer Knowledge postępuj zgodnie z tymi wytycznymi:
- Uściślij zapytania: w zapytaniu w języku naturalnym używaj konkretnych nazw produktów i odpowiednich słów kluczowych zamiast ogólnych terminów, ponieważ narzędzia
search_documentsianswer_querydopasowują się do semantyki zapytania. - Zarządzaj tokenami okna kontekstu: używaj
answer_queryw przypadku bezpośrednich odpowiedzi pochodzących z korpusu dokumentacji i unikaj żądania pełnej zawartości strony za pomocąget_documents, chyba że szczegóły fragmentu zsearch_documentssą niewystarczające. - Zabezpiecz klucze interfejsu API: przechowuj klucze interfejsu Developer Knowledge API i Gemini API w zmiennych środowiskowych lub standardowych systemach zarządzania obiektami tajnymi i nigdy nie umieszczaj na stałe danych logowania w kodzie.
Co dalej?
Aby dowiedzieć się więcej o serwerze MCP Developer Knowledge, zapoznaj się z tymi materiałami:
- Przeczytaj pełny przewodnik instalacji serwera MCP w Developer Knowledge.
- Sprawdź dostępne domeny korpusu.
- Dowiedz się, jak generować odpowiedzi na podstawie dokumentacji.