원격 MCP(모델 컨텍스트 프로토콜) 서버(사용자 고유의 MCP 서버 엔드포인트 가져오기)에서 호스트되는 도구에 연결하여 Azure AI Foundry 에이전트의 기능을 확장할 수 있습니다.
모델 컨텍스트 프로토콜 도구를 사용하는 방법
이 섹션에서는 호스트된 MCP(모델 컨텍스트 프로토콜) 서버 통합과 함께 Azure AI(Azure Foundry)를 사용하여 AI 에이전트를 만드는 방법을 설명합니다. 에이전트는 Azure Foundry 서비스에서 관리하고 실행하는 MCP 도구를 활용하여 외부 리소스에 대한 안전하고 제어된 액세스를 허용합니다.
주요 기능
- 호스트된 MCP 서버: MCP 서버는 Azure AI Foundry에서 호스트되고 관리되므로 서버 인프라를 관리할 필요가 없습니다.
- 영구 에이전트: 에이전트가 만들어지고 서버 쪽에 저장되어 상태 저장 대화를 허용합니다.
- 도구 승인 워크플로: MCP 도구 호출을 위한 구성 가능한 승인 메커니즘
작동 방식
1. 환경 설정
샘플에는 다음 두 가지 환경 변수가 필요합니다.
-
AZURE_FOUNDRY_PROJECT_ENDPOINT: Azure AI Foundry 프로젝트 엔드포인트 URL -
AZURE_FOUNDRY_PROJECT_MODEL_ID: 모델 배포 이름(기본값: "gpt-4.1-mini")
var endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT")
?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set.");
var model = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_MODEL_ID") ?? "gpt-4.1-mini";
2. 에이전트 구성
에이전트는 특정 지침 및 메타데이터를 사용하여 구성됩니다.
const string AgentName = "MicrosoftLearnAgent";
const string AgentInstructions = "You answer questions by searching the Microsoft Learn content only.";
이렇게 하면 Microsoft Learn 설명서를 사용하여 질문에 대답하기 위한 특수 에이전트가 만들어집니다.
3. MCP 도구 정의
샘플은 호스트된 MCP 서버를 가리키는 MCP 도구 정의를 만듭니다.
var mcpTool = new MCPToolDefinition(
serverLabel: "microsoft_learn",
serverUrl: "https://learn.microsoft.com/api/mcp");
mcpTool.AllowedTools.Add("microsoft_docs_search");
핵심 구성 요소:
- serverLabel: MCP 서버 인스턴스에 대한 고유 식별자입니다.
- serverUrl: 호스트된 MCP 서버의 URL
- AllowedTools: 에이전트가 사용할 수 있는 MCP 서버의 도구를 지정합니다.
4. 영구 에이전트 만들기
에이전트는 Azure AI Foundry 영구 에이전트 SDK를 사용하여 서버 쪽에서 만들어집니다.
var persistentAgentsClient = new PersistentAgentsClient(endpoint, new DefaultAzureCredential());
var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
model: model,
name: AgentName,
instructions: AgentInstructions,
tools: [mcpTool]);
경고
DefaultAzureCredential 은 개발에 편리하지만 프로덕션 환경에서 신중하게 고려해야 합니다. 프로덕션 환경에서는 특정 자격 증명(예: ManagedIdentityCredential)을 사용하여 대기 시간 문제, 의도하지 않은 자격 증명 검색 및 대체 메커니즘의 잠재적인 보안 위험을 방지하는 것이 좋습니다.
그러면 다음과 같은 영구 에이전트가 만들어집니다.
- Azure AI Foundry 서비스에 거주
- 지정된 MCP 도구에 대한 액세스 권한이 있습니다.
- 여러 상호 작용에서 대화 상태를 유지할 수 있습니다.
5. 에이전트 검색 및 실행
만든 에이전트는 인스턴스로 검색됩니다.AIAgent
AIAgent agent = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);
6. 도구 리소스 구성
이 샘플은 승인 설정을 사용하여 도구 리소스를 구성합니다.
var runOptions = new ChatClientAgentRunOptions()
{
ChatOptions = new()
{
RawRepresentationFactory = (_) => new ThreadAndRunOptions()
{
ToolResources = new MCPToolResource(serverLabel: "microsoft_learn")
{
RequireApproval = new MCPApproval("never"),
}.ToToolResources()
}
}
};
키 구성:
- MCPToolResource: MCP 서버 인스턴스를 에이전트 실행에 연결
-
RequireApproval: 도구 호출에 대한 사용자 승인이 필요한 시기를 제어합니다.
-
"never": 승인 없이 도구가 자동으로 실행됩니다. -
"always": 모든 도구 호출에는 사용자 승인이 필요합니다. - 사용자 지정 승인 규칙을 구성할 수도 있습니다.
-
7. 에이전트 실행
에이전트는 질문으로 호출되고 구성된 MCP 도구를 사용하여 실행됩니다.
AgentSession session = await agent.CreateSessionAsync();
var response = await agent.RunAsync(
"Please summarize the Azure AI Agent documentation related to MCP Tool calling?",
session,
runOptions);
Console.WriteLine(response);
8. 정리
샘플은 적절한 리소스 정리를 보여 줍니다.
await persistentAgentsClient.Administration.DeleteAgentAsync(agent.Id);
팁 (조언)
실행 가능한 전체 예제는 .NET 샘플을 참조하세요.
Azure AI Foundry는 Python 에이전트 프레임워크를 통해 MCP(모델 컨텍스트 프로토콜) 서버와 원활하게 통합됩니다. 이 서비스는 MCP 서버 호스팅 및 실행을 관리하므로 외부 도구에 대한 안전하고 제어된 액세스를 제공하면서 인프라 관리를 제거합니다.
환경 설정
환경 변수를 통해 Azure AI Foundry 프로젝트 자격 증명을 구성합니다.
import os
from azure.identity.aio import AzureCliCredential
from agent_framework.azure import AzureAIAgentClient
# Required environment variables
os.environ["AZURE_AI_PROJECT_ENDPOINT"] = "https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"] = "gpt-4o-mini" # Optional, defaults to this
기본 MCP 통합
호스트된 MCP 도구를 사용하여 Azure AI Foundry 에이전트를 만듭니다.
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def basic_foundry_mcp_example():
"""Basic example of Azure AI Foundry agent with hosted MCP tools."""
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(async_credential=credential) as client,
):
# Create a hosted MCP tool using the client method
learn_mcp = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
)
# Create agent with hosted MCP tool
agent = client.as_agent(
name="MicrosoftLearnAgent",
instructions="You answer questions by searching Microsoft Learn content only.",
tools=learn_mcp,
)
# Simple query without approval workflow
result = await agent.run(
"Please summarize the Azure AI Agent documentation related to MCP tool calling?"
)
print(result)
if __name__ == "__main__":
asyncio.run(basic_foundry_mcp_example())
다중 도구 MCP 구성
단일 에이전트에서 여러 호스트된 MCP 도구를 사용합니다.
async def multi_tool_mcp_example():
"""Example using multiple hosted MCP tools."""
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(async_credential=credential) as client,
):
# Create multiple MCP tools using the client method
learn_mcp = client.get_mcp_tool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
approval_mode="never_require", # Auto-approve documentation searches
)
github_mcp = client.get_mcp_tool(
name="GitHub MCP",
url="https://api.github.com/mcp",
approval_mode="always_require", # Require approval for GitHub operations
headers={"Authorization": "Bearer github-token"},
)
# Create agent with multiple MCP tools
agent = client.as_agent(
name="MultiToolAgent",
instructions="You can search documentation and access GitHub repositories.",
tools=[learn_mcp, github_mcp],
)
result = await agent.run(
"Find Azure documentation and also check the latest commits in microsoft/semantic-kernel"
)
print(result)
if __name__ == "__main__":
asyncio.run(multi_tool_mcp_example())
Python 에이전트 프레임워크는 Azure AI Foundry의 호스트된 MCP 기능과 원활하게 통합되어 프로덕션 애플리케이션에 필요한 유연성과 제어를 유지하면서 외부 도구에 안전하고 확장 가능한 액세스를 가능하게 합니다.
전체 예제
# Copyright (c) Microsoft. All rights reserved.
import asyncio
import os
from agent_framework import Agent
from agent_framework.openai import OpenAIResponsesClient
from dotenv import load_dotenv
"""
MCP GitHub Integration with Personal Access Token (PAT)
This example demonstrates how to connect to GitHub's remote MCP server using a Personal Access
Token (PAT) for authentication. The agent can use GitHub operations like searching repositories,
reading files, creating issues, and more depending on how you scope your token.
Prerequisites:
1. A GitHub Personal Access Token with appropriate scopes
- Create one at: https://github.com/settings/tokens
- For read-only operations, you can use more restrictive scopes
2. Environment variables:
- GITHUB_PAT: Your GitHub Personal Access Token (required)
- OPENAI_API_KEY: Your OpenAI API key (required)
- OPENAI_RESPONSES_MODEL_ID: Your OpenAI model ID (required)
"""
async def github_mcp_example() -> None:
"""Example of using GitHub MCP server with PAT authentication."""
# 1. Load environment variables from .env file if present
load_dotenv()
# 2. Get configuration from environment
github_pat = os.getenv("GITHUB_PAT")
if not github_pat:
raise ValueError(
"GITHUB_PAT environment variable must be set. Create a token at https://github.com/settings/tokens"
)
# 3. Create authentication headers with GitHub PAT
auth_headers = {
"Authorization": f"Bearer {github_pat}",
}
# 4. Create agent with the GitHub MCP tool using instance method
# The MCP tool manages the connection to the MCP server and makes its tools available
# Set approval_mode="never_require" to allow the MCP tool to execute without approval
client = OpenAIResponsesClient()
github_mcp_tool = client.get_mcp_tool(
name="GitHub",
url="https://api.githubcopilot.com/mcp/",
headers=auth_headers,
approval_mode="never_require",
)
# 5. Create agent with the GitHub MCP tool
async with Agent(
client=client,
name="GitHubAgent",
instructions=(
"You are a helpful assistant that can help users interact with GitHub. "
"You can search for repositories, read file contents, check issues, and more. "
"Always be clear about what operations you're performing."
),
tools=github_mcp_tool,
) as agent:
# Example 1: Get authenticated user information
query1 = "What is my GitHub username and tell me about my account?"
print(f"\nUser: {query1}")
result1 = await agent.run(query1)
print(f"Agent: {result1.text}")
# Example 2: List my repositories
query2 = "List all the repositories I own on GitHub"
print(f"\nUser: {query2}")
result2 = await agent.run(query2)
print(f"Agent: {result2.text}")
if __name__ == "__main__":
asyncio.run(github_mcp_example())