Döküm Aracıları ile MCP araçlarını kullanma

Microsoft Foundry aracınızı uzak Model Bağlam Protokolü (MCP) sunucularında barındırılan araçlara bağlayarak (kendi MCP sunucu uç noktanızı getirin) özelliklerini genişletebilirsiniz.

Model Bağlam Protokolü aracını kullanma

Bu bölümde barındırılan Model Bağlam Protokolü (MCP) sunucu tümleştirmesi ile Microsoft Foundry destekli Python aracısının nasıl oluşturulacağı açıklanmaktadır. Aracı, Foundry hizmeti tarafından yönetilen ve yürütülen MCP araçlarını kullanarak dış kaynaklara güvenli ve denetimli erişim sağlayabilir.

Önemli Özellikler    

  • Barındırılan MCP Sunucusu: MCP sunucusu Foundry tarafından barındırılır ve yönetilir, böylece sunucu altyapısını yönetme gereksinimi ortadan kaldırılır
  • Kalıcı Aracılar: Aracılar oluşturulur ve sunucu tarafında depolanır ve durum bilgisi olan konuşmalara olanak sağlar
  • Araç Onayı İş Akışı: MCP araç çağrıları için yapılandırılabilir onay mekanizmaları

Nasıl Çalışır?

1. Ortam Kurulumu

Örnek için iki ortam değişkeni gerekir:

  • AZURE_FOUNDRY_PROJECT_ENDPOINT: Dökümhane proje uç noktası URL'niz
  • AZURE_FOUNDRY_PROJECT_MODEL_ID: Model dağıtım adı (varsayılan olarak "gpt-4.1-mini" olarak adlandırılır)
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. Aracı Yapılandırması

Aracı belirli yönergeler ve meta verilerle yapılandırılır:

const string AgentName = "MicrosoftLearnAgent";
const string AgentInstructions = "You answer questions by searching the Microsoft Learn content only.";

Bu, Microsoft Learn belgelerini kullanarak soruları yanıtlamak için özelleştirilmiş bir aracı oluşturur.

3. MCP Araç Tanımı

Örnek, barındırılan bir MCP sunucusuna işaret eden bir MCP araç tanımı oluşturur:

var mcpTool = new MCPToolDefinition(
    serverLabel: "microsoft_learn",
    serverUrl: "https://learn.microsoft.com/api/mcp");
mcpTool.AllowedTools.Add("microsoft_docs_search");

Temel Bileşenler:

  • serverLabel: MCP sunucu örneği için benzersiz bir tanımlayıcı
  • serverUrl: Barındırılan MCP sunucusunun URL'si
  • AllowedTools: Aracının MCP sunucusundan hangi araçları kullanabileceğini belirtir

4. Aracı Oluşturma

Aracı, Azure AI Projeleri SDK'sı kullanılarak sunucu tarafında oluşturulur:

var aiProjectClient = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential());

var agentVersion = await aiProjectClient.AgentAdministrationClient.CreateAgentVersionAsync(
    AgentName,
    new ProjectsAgentVersionCreationOptions(
        new DeclarativeAgentDefinition(model)
        {
            Instructions = AgentInstructions,
            Tools = { mcpTool }
        }));

Uyarı

DefaultAzureCredential geliştirme için uygundur ancak üretimde dikkatli bir şekilde dikkate alınması gerekir. Üretimde gecikme sorunları, istenmeyen kimlik bilgisi yoklama ve geri dönüş mekanizmalarından kaynaklanan olası güvenlik risklerini önlemek için belirli bir kimlik bilgisi (ör ManagedIdentityCredential. ) kullanmayı göz önünde bulundurun.

Bu, şu sürüme sahip bir aracı oluşturur:

  • Foundry hizmetinde yaşıyor
  • Belirtilen MCP araçlarına erişimi var
  • Birden çok etkileşimde konuşma durumunu koruyabilir

5. Aracı Alma ve Yürütme

Oluşturulan aracı bir AIAgent örnek olarak alınır:

AIAgent agent = aiProjectClient.AsAIAgent(agentVersion);

6. Araç Kaynağı Yapılandırması

Örnek, araç kaynaklarını onay ayarlarıyla yapılandırıyor:

var runOptions = new ChatClientAgentRunOptions()
{
    ChatOptions = new()
    {
        RawRepresentationFactory = (_) => new ThreadAndRunOptions()
        {
            ToolResources = new MCPToolResource(serverLabel: "microsoft_learn")
            {
                RequireApproval = new MCPApproval("never"),
            }.ToToolResources()
        }
    }
};

Anahtar Yapılandırması:

  • MCPToolResource: MCP sunucu örneğini aracı yürütmeye bağlar
  • RequireApproval: Araç çağrıları için kullanıcı onayının ne zaman gerekli olduğunu denetler
    • "never": Araçlar onay olmadan otomatik olarak yürütülür
    • "always": Tüm araç çağrıları için kullanıcı onayı gerekir
    • Özel onay kuralları da yapılandırılabilir

7. Aracı Yürütme

Aracı bir soruyla çağrılır ve yapılandırılan MCP araçları kullanılarak yürütülür:

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. Temizleme

Örnek doğru kaynak temizlemeyi gösterir:

await aiProjectClient.AgentAdministrationClient.DeleteAgentAsync(agent.Id);

Tip

Tam bir çalıştırılabilir örnek için .NET Foundry Aracısı Tarafından Barındırılan MCP Örneğine bakın.

Foundry, Python Aracı Çerçevesi aracılığıyla Model Bağlam Protokolü (MCP) sunucularıyla sorunsuz tümleştirme sağlar. Hizmet, MCP sunucusu barındırma ve yürütmeyi yöneterek dış araçlara güvenli ve denetimli erişim sağlarken altyapı yönetimini de ortadan kaldırır.

Ortam Kurulumu

Ortam değişkenleri aracılığıyla Foundry proje kimlik bilgilerinizi yapılandırın:

import os
from azure.identity.aio import AzureCliCredential
from agent_framework.foundry import FoundryChatClient

# Required environment variables
os.environ["FOUNDRY_PROJECT_ENDPOINT"] = "https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
os.environ["FOUNDRY_MODEL"] = "gpt-4o-mini"

Temel MCP Tümleştirmesi

Barındırılan MCP araçlarıyla bir Foundry aracısı oluşturun:

import asyncio
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity.aio import AzureCliCredential

async def basic_foundry_mcp_example():
    """Basic example of Foundry agent with hosted MCP tools."""
    async with AzureCliCredential() as credential:
        client = FoundryChatClient(credential=credential)
        # 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
        async with Agent(
            client=client,
            name="MicrosoftLearnAgent",
            instructions="You answer questions by searching Microsoft Learn content only.",
            tools=[learn_mcp],
        ) as agent:
            # Simple query without approval workflow
            result = await agent.run(
                "Please summarize the Azure AI Agent documentation related to MCP tool calling?"
            )
            print(result.text)

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

Çok Araçlı MCP Yapılandırması

Tek bir aracıyla birden çok barındırılan MCP aracısı kullanın:

async def multi_tool_mcp_example():
    """Example using multiple hosted MCP tools."""
    async with AzureCliCredential() as credential:
        client = FoundryChatClient(credential=credential)
        # 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.githubcopilot.com/mcp/",
            approval_mode="always_require",  # Require approval for GitHub operations
            headers={"Authorization": "Bearer github-token"},
        )

        # Create agent with multiple MCP tools
        async with Agent(
            client=client,
            name="MultiToolAgent",
            instructions="You can search documentation and access GitHub repositories.",
            tools=[learn_mcp, github_mcp],
        ) as agent:
            result = await agent.run(
                "Find Azure documentation and also check the latest commits in microsoft/semantic-kernel"
            )
            print(result.text)

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

Python Agent Framework, Foundry'nin barındırılan MCP özellikleriyle sorunsuz tümleştirme sağlayarak dış araçlara güvenli ve ölçeklenebilir erişim sağlarken üretim uygulamaları için gereken esnekliği ve denetimi de korur.

Tip

MCP araçları, barındırılan araç yapılandırmalarının sunucu tarafı koleksiyonları olarak adlandırılan Dökümhane araç kutularına da paketlenebilir. Araç kutuları, araç yapılandırmasını bir kez yönetmenize ve aracılar arasında yeniden kullanmanıza olanak tanır. Araç kutularını getirme ve MCP tüketim yolu hakkında ayrıntılı bilgi için Microsoft Foundry sağlayıcısı sayfasındaki Araç Kutuları bölümüne bakın.

Tam örnek

# Copyright (c) Microsoft. All rights reserved.

import asyncio
import os

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
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)
   - FOUNDRY_PROJECT_ENDPOINT: Your Foundry project endpoint (required)
   - FOUNDRY_MODEL: Your Foundry model deployment name (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 = FoundryChatClient(credential=AzureCliCredential())
    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())

Sonraki Adımlar