개발자 지식 MCP 서버를 맞춤 AI 에이전트와 통합

이 튜토리얼에서는 원격 개발자 지식 MCP 서버를 LangChain, LlamaIndex, AutoGen으로 빌드된 맞춤 AI 에이전트 프레임워크에 연결하는 방법을 보여줍니다.

맞춤 AI 에이전트를 원격 모델 컨텍스트 프로토콜 (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 모델을 인증하거나, Google Cloud API 키에 Generative Language 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 서버 통합을 지원하므로 검색 에이전트가 추론 중에 개발자 지식 문서를 쿼리할 수 있습니다.

종속 항목 설치

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())

에이전트 통합 권장사항

개발자 지식 MCP 서버로 맞춤 AI 에이전트를 빌드할 때는 다음 가이드라인을 따르세요.

  • 검색어 다듬기: search_documents 및 answer_query 도구는 검색어 의미에 따라 일치하므로 일반적인 용어 대신 자연어 검색어에 특정 제품 이름과 관련 키워드를 포함합니다.
  • 컨텍스트 윈도우 토큰 관리: 문서 말뭉치에서 가져온 직접적인 답변에는 answer_query를 사용하고, search_documents의 스니펫 세부정보가 충분하지 않은 경우를 제외하고는 get_documents로 전체 페이지 콘텐츠를 요청하지 마세요.
  • API 키 보안: 환경 변수 또는 표준 Secret Manager 시스템에 Developer Knowledge API 및 Gemini API 키를 저장하고 코드에 사용자 인증 정보를 하드코딩하지 마세요.

다음 단계

다음 리소스를 통해 개발자 지식 MCP 서버에 대해 자세히 알아보세요.