다음을 통해 공유


에이전트와 함께 MCP 도구 사용

모델 컨텍스트 프로토콜은 애플리케이션이 LLM(대규모 언어 모델)에 도구 및 컨텍스트 데이터를 제공하는 방법을 정의하는 개방형 표준입니다. 이를 통해 일관되고 확장 가능한 외부 도구를 모델 워크플로에 통합할 수 있습니다.

Microsoft Agent Framework는 MCP(모델 컨텍스트 프로토콜) 서버와의 통합을 지원하여 에이전트가 외부 도구 및 서비스에 액세스할 수 있도록 합니다. 이 가이드에서는 MCP 서버에 연결하고 에이전트 내에서 해당 도구를 사용하는 방법을 보여 줍니다.

타사 MCP 서버 사용에 대한 고려 사항

모델 컨텍스트 프로토콜 서버를 사용하는 경우 사용자와 서비스 공급자 간의 조건이 적용됩니다. Microsoft가 아닌 서비스에 연결하면 일부 데이터(예: 프롬프트 콘텐츠)가 비 Microsoft 서비스에 전달되거나 애플리케이션이 비 Microsoft 서비스에서 데이터를 받을 수 있습니다. Microsoft가 아닌 서비스 및 데이터의 사용과 해당 사용과 관련된 모든 요금에 대한 책임은 귀하에게 있습니다.

이 문서에 설명된 MCP 도구와 함께 사용하기로 결정한 원격 MCP 서버는 Microsoft가 아닌 타사에서 만들었습니다. Microsoft는 이러한 서버를 테스트하거나 확인하지 않았습니다. Microsoft는 원격 MCP 서버 사용과 관련하여 귀하 또는 다른 사람에게 책임을지지 않습니다.

에이전트 프레임워크 기반 애플리케이션에 추가하는 MCP 서버를 신중하게 검토하고 추적하는 것이 좋습니다. 또한 프록시가 아닌 신뢰할 수 있는 서비스 공급자가 호스트하는 서버에 의존하는 것이 좋습니다.

MCP 도구를 사용하면 원격 MCP 서버에 필요할 수 있는 인증 키 또는 스키마와 같은 사용자 지정 헤더를 전달할 수 있습니다. 원격 MCP 서버와 공유되고 감사 목적으로 데이터를 기록하는 모든 데이터를 검토하는 것이 좋습니다. 데이터의 보존 및 위치에 대한 비 Microsoft 사례를 인식해야 합니다.

중요합니다

각 실행 시 tool_resources 헤더를 포함해야만 헤더를 지정할 수 있습니다. 이러한 방식으로 API 키, OAuth 액세스 토큰 또는 기타 자격 증명을 요청에 직접 넣을 수 있습니다. 전달한 헤더는 현재 실행에만 사용할 수 있으며 유지되지 않습니다.

MCP 보안에 대한 자세한 내용은 다음을 참조하세요.

에이전트 프레임워크의 .NET 버전을 공식 MCP C# SDK 와 함께 사용하여 에이전트가 MCP 도구를 호출할 수 있도록 할 수 있습니다.

다음 샘플에서는 다음 방법을 보여줍니다.

  1. 설정 및 MCP 서버
  2. MCP 서버에서 사용 가능한 도구 목록 검색
  3. 에이전트에 추가할 수 있도록 MCP 도구를 AIFunction's'로 변환
  4. 함수 호출을 사용하여 에이전트에서 도구 호출

MCP 클라이언트 설정

먼저 원하는 MCP 서버에 연결하는 MCP 클라이언트를 만듭니다.

// Create an MCPClient for the GitHub server
await using var mcpClient = await McpClientFactory.CreateAsync(new StdioClientTransport(new()
{
    Name = "MCPServer",
    Command = "npx",
    Arguments = ["-y", "--verbose", "@modelcontextprotocol/server-github"],
}));

이 예제에서:

  • 이름: MCP 서버 연결에 대한 친숙한 이름
  • 명령: MCP 서버를 실행하는 실행 파일(여기서 npx를 사용하여 Node.js 패키지 실행)
  • 인수: MCP 서버에 전달된 명령줄 인수

사용 가능한 도구 검색

연결되면 MCP 서버에서 사용할 수 있는 도구 목록을 검색합니다.

// Retrieve the list of tools available on the GitHub server
var mcpTools = await mcpClient.ListToolsAsync().ConfigureAwait(false);

이 메서드는 ListToolsAsync() MCP 서버에서 노출하는 도구 컬렉션을 반환합니다. 이러한 도구는 에이전트에서 사용할 수 있는 AITool 개체로 자동으로 변환됩니다.

MCP 도구를 사용하여 에이전트 만들기

에이전트를 만들고 초기화하는 동안 MCP 도구를 제공합니다.

AIAgent agent = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
     .GetChatClient(deploymentName)
     .AsAIAgent(
         instructions: "You answer questions related to GitHub repositories only.",
         tools: [.. mcpTools.Cast<AITool>()]);

경고

DefaultAzureCredential 은 개발에 편리하지만 프로덕션 환경에서 신중하게 고려해야 합니다. 프로덕션 환경에서는 특정 자격 증명(예: ManagedIdentityCredential)을 사용하여 대기 시간 문제, 의도하지 않은 자격 증명 검색 및 대체 메커니즘의 잠재적인 보안 위험을 방지하는 것이 좋습니다.

주요 정보:

  • 지침: MCP 도구의 기능에 맞는 명확한 지침 제공
  • 도구: MCP 도구를 개체로 AITool 캐스팅하고 도구 배열로 분산
  • 에이전트는 MCP 서버에서 제공하는 모든 도구에 자동으로 액세스할 수 있습니다.

에이전트 사용

구성되면 에이전트는 MCP 도구를 자동으로 사용하여 사용자 요청을 처리할 수 있습니다.

// Invoke the agent and output the text result
Console.WriteLine(await agent.RunAsync("Summarize the last four commits to the microsoft/semantic-kernel repository?"));

에이전트는 다음을 수행합니다.

  1. 사용자의 요청 분석
  2. 필요한 MCP 도구 확인
  3. MCP 서버를 통해 적절한 도구 호출
  4. 결과를 일관된 응답으로 합성

환경 구성

필요한 환경 변수를 설정해야 합니다.

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ??
    throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

리소스 관리

MCP 클라이언트 리소스를 항상 적절하게 삭제합니다.

await using var mcpClient = await McpClientFactory.CreateAsync(...);

MCP 클라이언트 연결을 사용하면 await using 범위를 벗어날 때 MCP 클라이언트 연결이 제대로 닫힙니다.

일반 MCP 서버

인기 있는 MCP 서버는 다음과 같습니다.

  • @modelcontextprotocol/server-github: GitHub 리포지토리 및 데이터에 액세스
  • @modelcontextprotocol/server-filesystem: 파일 시스템 작업
  • @modelcontextprotocol/server-sqlite: SQLite 데이터베이스 액세스

각 서버는 에이전트의 기능을 확장하는 다양한 도구와 기능을 제공합니다. 이 통합을 통해 에이전트는 모델 컨텍스트 프로토콜의 보안 및 표준화 이점을 유지하면서 외부 데이터 및 서비스에 원활하게 액세스할 수 있습니다.

이 샘플을 실행하는 전체 소스 코드 및 지침은 .에서 https://github.com/microsoft/agent-framework/tree/main/dotnet/samples/GettingStarted/ModelContextProtocol/Agent_MCP_Server사용할 수 있습니다.

팁 (조언)

실행 가능한 전체 예제는 .NET 샘플을 참조하세요.

이렇게 하면 에이전트가 외부 도구 및 서비스에 원활하게 액세스할 수 있습니다.

MCP 도구 형식

에이전트 프레임워크는 다음 세 가지 유형의 MCP 연결을 지원합니다.

MCPStdioTool - 로컬 MCP 서버

표준 입력/출력을 사용하여 로컬 프로세스로 실행되는 MCP 서버에 연결하는 데 사용합니다 MCPStdioTool .

import asyncio
from agent_framework import Agent, MCPStdioTool
from agent_framework.openai import OpenAIChatClient

async def local_mcp_example():
    """Example using a local MCP server via stdio."""
    async with (
        MCPStdioTool(
            name="calculator",
            command="uvx",
            args=["mcp-server-calculator"]
        ) as mcp_server,
        Agent(
            chat_client=OpenAIChatClient(),
            name="MathAgent",
            instructions="You are a helpful math assistant that can solve calculations.",
        ) as agent,
    ):
        result = await agent.run(
            "What is 15 * 23 + 45?",
            tools=mcp_server
        )
        print(result)

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

MCPStreamableHTTPTool - HTTP/SSE MCP 서버

Server-Sent 이벤트를 사용하여 HTTP를 통해 MCP 서버에 연결하는 데 사용합니다 MCPStreamableHTTPTool .

import asyncio
from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def http_mcp_example():
    """Example using an HTTP-based MCP server."""
    async with (
        AzureCliCredential() as credential,
        MCPStreamableHTTPTool(
            name="Microsoft Learn MCP",
            url="https://learn.microsoft.com/api/mcp",
            headers={"Authorization": "Bearer your-token"},
        ) as mcp_server,
        Agent(
            chat_client=AzureAIAgentClient(async_credential=credential),
            name="DocsAgent",
            instructions="You help with Microsoft documentation questions.",
        ) as agent,
    ):
        result = await agent.run(
            "How to create an Azure storage account using az cli?",
            tools=mcp_server
        )
        print(result)

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

MCPWebsocketTool - WebSocket MCP 서버

WebSocket 연결을 통해 MCP 서버에 연결하는 데 사용합니다 MCPWebsocketTool .

import asyncio
from agent_framework import Agent, MCPWebsocketTool
from agent_framework.openai import OpenAIChatClient

async def websocket_mcp_example():
    """Example using a WebSocket-based MCP server."""
    async with (
        MCPWebsocketTool(
            name="realtime-data",
            url="wss://api.example.com/mcp",
        ) as mcp_server,
        Agent(
            chat_client=OpenAIChatClient(),
            name="DataAgent",
            instructions="You provide real-time data insights.",
        ) as agent,
    ):
        result = await agent.run(
            "What is the current market status?",
            tools=mcp_server
        )
        print(result)

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

Python 에이전트 프레임워크에서 사용할 수 있는 일반적인 MCP 서버:

  • 계산기: uvx mcp-server-calculator - 수학 계산
  • 파일 시스템: uvx mcp-server-filesystem - 파일 시스템 작업
  • GitHub: npx @modelcontextprotocol/server-github - GitHub 리포지토리 액세스
  • SQLite: uvx mcp-server-sqlite - 데이터베이스 작업

각 서버는 모델 컨텍스트 프로토콜의 보안 및 표준화 이점을 유지하면서 에이전트의 기능을 확장하는 다양한 도구와 기능을 제공합니다.

전체 예제

# Copyright (c) Microsoft. All rights reserved.

import os

from agent_framework import Agent, MCPStreamableHTTPTool
from agent_framework.openai import OpenAIResponsesClient
from httpx import AsyncClient

"""
MCP Authentication Example

This example demonstrates how to authenticate with MCP servers using API key headers.

For more authentication examples including OAuth 2.0 flows, see:
- https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/clients/simple-auth-client
- https://github.com/modelcontextprotocol/python-sdk/tree/main/examples/servers/simple-auth
"""


async def api_key_auth_example() -> None:
    """Example of using API key authentication with MCP server."""
    # Configuration
    mcp_server_url = os.getenv("MCP_SERVER_URL", "your-mcp-server-url")
    api_key = os.getenv("MCP_API_KEY")

    # Create authentication headers
    # Common patterns:
    # - Bearer token: "Authorization": f"Bearer {api_key}"
    # - API key header: "X-API-Key": api_key
    # - Custom header: "Authorization": f"ApiKey {api_key}"
    auth_headers = {
        "Authorization": f"Bearer {api_key}",
    }

    # Create HTTP client with authentication headers
    http_client = AsyncClient(headers=auth_headers)

    # Create MCP tool with the configured HTTP client
    async with (
        MCPStreamableHTTPTool(
            name="MCP tool",
            description="MCP tool description",
            url=mcp_server_url,
            http_client=http_client,  # Pass HTTP client with authentication headers
        ) as mcp_tool,
        Agent(
            client=OpenAIResponsesClient(),
            name="Agent",
            instructions="You are a helpful assistant.",
            tools=mcp_tool,
        ) as agent,
    ):
        query = "What tools are available to you?"
        print(f"User: {query}")
        result = await agent.run(query)
        print(f"Agent: {result.text}")

에이전트를 MCP 서버로 노출

에이전트를 MCP 서버로 노출하여 MCP 호환 클라이언트(예: VS Code GitHub Copilot 에이전트 또는 기타 에이전트)에서 도구로 사용할 수 있습니다. 에이전트의 이름과 설명은 MCP 서버 메타데이터가 됩니다.

다음을 사용하여 .AsAIFunction()함수 도구에서 에이전트를 래핑하고, 만들고 McpServerTool, MCP 서버에 등록합니다.

using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;

// Create the agent
AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
        .GetChatClient("gpt-4o-mini")
        .AsAIAgent(instructions: "You are good at telling jokes.", name: "Joker");

// Convert the agent to an MCP tool
McpServerTool tool = McpServerTool.Create(agent.AsAIFunction());

// Set up the MCP server over stdio
HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(settings: null);
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithTools([tool]);

await builder.Build().RunAsync();

필요한 NuGet 패키지를 설치합니다.

dotnet add package Microsoft.Extensions.Hosting --prerelease
dotnet add package ModelContextProtocol --prerelease

에이전트를 호출 .as_mcp_server() 하여 MCP 서버로 노출합니다.

from agent_framework.openai import OpenAIResponsesClient
from typing import Annotated

def get_specials() -> Annotated[str, "Returns the specials from the menu."]:
    return "Special Soup: Clam Chowder, Special Salad: Cobb Salad"

# Create an agent with tools
agent = OpenAIResponsesClient().as_agent(
    name="RestaurantAgent",
    description="Answer questions about the menu.",
    tools=[get_specials],
)

# Expose the agent as an MCP server
server = agent.as_mcp_server()

표준 입력/출력을 수신 대기하도록 MCP 서버를 설정합니다.

import anyio
from mcp.server.stdio import stdio_server

async def run():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream, server.create_initialization_options())

if __name__ == "__main__":
    anyio.run(run)

다음 단계: