다음을 통해 공유


Azure MCP Server 시작

Azure MCP 서버는 MCP(모델 컨텍스트 프로토콜)를 사용하여 AI 앱과 외부 도구 및 데이터 원본 간의 통합을 표준화하여 AI 시스템이 Azure 리소스에 대한 컨텍스트 인식 작업을 수행할 수 있도록 합니다.

이 문서에서는 다음 작업을 완료하는 방법을 알아봅니다.

  • Azure MCP Server 설치 및 인증
  • Visual Studio Code에서 GitHub Copilot 에이전트 모드를 사용하여 Azure MCP 서버에 연결
  • 프롬프트를 실행하여 Azure MCP 서버 작업을 테스트하고 Azure 리소스와 상호 작용

필수 조건

비고

Azure MCP Server를 사용하여 액세스하려는 Azure 리소스는 Azure 구독 내에 이미 있어야 합니다. 또한 사용자 계정에는 해당 리소스에 대해 할당된 필요한 RBAC 역할 및 권한이 있어야 합니다.

Azure MCP 서버 설치

Visual Studio Code에서 Azure MCP Server를 설치하려면 다음 옵션 중 하나를 선택합니다.

  1. 사용자 설정에서 Visual Studio Code용 Azure MCP Server를 설치하려면 다음 링크를 선택합니다.

    Visual Studio Code에서 NPX를 사용하여 설치

    Visual Studio Code 내에서 설치 옵션 목록이 열립니다. 서버 설치를 선택하여 사용자 설정에 서버 구성을 추가합니다.

    Azure MCP Server 설치 옵션을 보여 주는 스크린샷.

  2. GitHub Copilot를 열고 에이전트 모드를 선택합니다. 에이전트 모드에 대한 자세한 내용은 Visual Studio Code 설명서를 참조하세요.

  3. 도구 목록을 새로 고쳐 Azure MCP Server를 사용 가능한 옵션으로 확인합니다.

    Azure MCP Server를 GitHub Copilot 도구로 보여 주는 스크린샷

프롬프트를 사용하여 Azure MCP 서버 테스트

  1. GitHub Copilot를 열고 에이전트 모드를 선택합니다.

  2. 에이전트가 Azure MCP Server 도구를 사용할 수 있도록 내 Azure 리소스 그룹 나열과 같은 프롬프트를 입력합니다.

  3. Azure MCP Server를 인증하기 위해 Copilot는 브라우저를 사용하여 Azure에 로그인하라는 메시지를 표시합니다.

    비고

    이미 Azure CLI와 같은 다른 로컬 도구를 통해 인증된 경우 Copilot는 Azure에 로그인하라는 메시지를 표시하지 않습니다.

  4. Copilot는 프롬프트에 필요한 Azure MCP 서버 작업을 실행할 수 있는 권한을 요청합니다. 계속을 선택하거나 화살표를 사용하여 보다 구체적인 동작을 선택합니다.

    • 현재 세션 은 항상 현재 GitHub Copilot 에이전트 모드 세션에서 작업을 실행합니다.
    • 현재 작업 영역은 항상 현재 Visual Studio Code 작업 영역에 대한 명령을 실행합니다.
    • 항상 모든 GitHub Copilot 에이전트 모드 세션 또는 Visual Studio Code 작업 영역에 대해 작업을 실행하도록 항상 허용합니다.

    Azure MCP Server 작업을 실행하는 데 사용할 수 있는 옵션을 보여 주는 스크린샷

    이전 프롬프트의 출력은 다음 텍스트와 유사합니다.

    The following resource groups are available for your subscription:
    
    1. **DefaultResourceGroup-EUS** (Location: `eastus`)
    2. **rg-testing** (Location: `centralus`)
    3. **rg-azd** (Location: `eastus2`)
    4. **msdocs-sample** (Location: `southcentralus`)
    14. **ai-testing** (Location: `eastus2`)
    
    Let me know if you need further details or actions related to any of these resource groups!
    
  5. 다음과 같은 다른 관련 프롬프트를 사용하여 Azure MCP 작업을 탐색하고 테스트합니다.

    List all of the storage accounts in my subscription
    Get the available tables in my storage accounts
    

이 문서에서는 다음 작업을 완료하는 방법을 알아봅니다.

  • Azure MCP Server 설치 및 인증
  • 사용자 지정 .NET 클라이언트를 사용하여 Azure MCP Server에 연결
  • 프롬프트를 실행하여 Azure MCP Server 작업 테스트 및 Azure 리소스 관리

필수 조건

비고

Azure MCP Server를 사용하여 액세스하려는 Azure 리소스는 Azure 구독 내에 이미 있어야 합니다. 또한 사용자 계정에는 해당 리소스에 대해 할당된 필요한 RBAC 역할 및 권한이 있어야 합니다.

로컬 개발을 위한 로그인

Azure MCP Server는 Microsoft Entra ID를 통해 토큰 기반 인증을 사용하여 원활한 인증 환경을 제공합니다. 내부적으로 Azure MCP Server는 DefaultAzureCredential에서 사용자를 인증하는 데 사용합니다.

Azure MCP Server를 사용하려면 Azure 계정으로 로컬에서 지원하는 DefaultAzureCredential 도구 중 하나에 로그인해야 합니다. Visual Studio Code 터미널과 같은 터미널 창을 사용하여 로그인합니다.

az login

이전 도구 중 하나에 성공적으로 로그인하면 Azure MCP Server에서 자격 증명을 자동으로 검색하고 이를 사용하여 Azure 서비스에 대한 작업을 인증하고 수행할 수 있습니다.

비고

Visual Studio를 통해 Azure에 로그인할 수도 있습니다. Azure MCP Server는 로그인한 사용자에게 수행할 권한이 있는 작업만 실행할 수 있습니다.

.NET 호스트 앱 만들기

다음 단계를 완료하여 .NET 콘솔 앱을 만듭니다. 앱은 AI 모델에 연결하고 Azure MCP 서버에 연결하는 MCP 클라이언트의 호스트 역할을 합니다.

프로젝트를 만듭니다.

  1. 프로젝트를 만들려는 빈 폴더에 터미널을 엽니다.

  2. 다음 명령을 실행하여 새 .NET 콘솔 애플리케이션을 만듭니다.

    dotnet new console -n MCPHostApp
    
  3. 새로 만든 프로젝트 폴더로 이동합니다.

    cd MCPHostApp
    
  4. Visual Studio Code와 같이 선택한 편집기에서 프로젝트 폴더를 엽니다.

    code .
    

종속성 추가

  1. 터미널에서 다음 명령을 실행하여 필요한 NuGet 패키지를 추가합니다.

    dotnet add package Azure.AI.OpenAI --prerelease
    dotnet add package Azure.Identity
    dotnet add package Microsoft.Extensions.AI --prerelease
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package ModelContextProtocol --prerelease
    
  2. 파일을 확인하여 패키지가 추가되었는지 확인합니다 MCPHostApp.csproj .

  3. 다음 명령을 실행하여 프로젝트를 빌드하고 모든 것이 올바르게 설정되었는지 확인합니다.

    dotnet build
    

앱 코드 추가

Program.cs의 내용을 다음 코드로 바꿉니다.

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;

// Create an IChatClient
IChatClient client =
    new ChatClientBuilder(
        new AzureOpenAIClient(new Uri("<your-Azure-OpenAI-endpoint>"), 
        new DefaultAzureCredential())
        .GetChatClient("gpt-4o").AsIChatClient())
    .UseFunctionInvocation()
    .Build();

// Create the MCP client
var mcpClient = await McpClientFactory.CreateAsync(
    new StdioClientTransport(new()
    {
        Command = "npx",
        Arguments = ["-y", "@azure/mcp@latest", "server", "start"],
        Name = "Azure MCP",
    }));

// Get all available tools from the MCP server
Console.WriteLine("Available tools:");
var tools = await mcpClient.ListToolsAsync();
foreach (var tool in tools)
{
    Console.WriteLine($"{tool}");
}
Console.WriteLine();

// Conversational loop that can utilize the tools
List<ChatMessage> messages = [];
while (true)
{
    Console.Write("Prompt: ");
    messages.Add(new(ChatRole.User, Console.ReadLine()));

    List<ChatResponseUpdate> updates = [];
    await foreach (var update in client
        .GetStreamingResponseAsync(messages, new() { Tools = [.. tools] }))
    {
        Console.Write(update);
        updates.Add(update);
    }
    Console.WriteLine();

    messages.AddMessages(updates);
}

위의 코드는 다음 작업을 수행합니다.

  • IChatClient 추상화를 Microsoft.Extensions.AI 라이브러리를 사용하여 초기화합니다.
  • 표준 I/O 전송을 사용하여 Azure MCP 서버와 상호 작용하는 MCP 클라이언트를 만듭니다. 제공된 npx 명령 및 해당 인수는 Azure MCP Server를 다운로드하고 시작합니다.
  • 표준 MCP 함수인 MCP 서버에서 사용 가능한 도구 목록을 검색하고 표시합니다.
  • 사용자 프롬프트를 처리하고 응답에 대한 도구를 활용하는 대화형 루프를 구현합니다.

앱 실행 및 테스트

다음 단계를 완료하여 .NET 호스트 앱을 테스트합니다.

  1. 프로젝트의 루트에 열려 있는 터미널 창에서 다음 명령을 실행하여 앱을 시작합니다.

    dotnet run
    
  2. 앱이 실행되면 다음 테스트 프롬프트를 입력합니다.

    List all of the resource groups in my subscription
    

    이전 프롬프트의 출력은 다음 텍스트와 유사합니다.

    The following resource groups are available for your subscription:
    
    1. **DefaultResourceGroup-EUS** (Location: `eastus`)
    2. **rg-testing** (Location: `centralus`)
    3. **rg-azd** (Location: `eastus2`)
    4. **msdocs-sample** (Location: `southcentralus`)
    14. **ai-testing** (Location: `eastus2`)
    
    Let me know if you need further details or actions related to any of these resource groups!
    
  3. 다음과 같은 다른 관련 프롬프트를 사용하여 Azure MCP 작업을 탐색하고 테스트합니다.

    List all of the storage accounts in my subscription
    Get the available tables in my storage accounts
    

이 문서에서는 다음 작업을 완료하는 방법을 알아봅니다.

  • Azure MCP Server 설치 및 인증
  • 사용자 지정 Python 클라이언트를 사용하여 Azure MCP 서버에 연결
  • 프롬프트를 실행하여 Azure MCP Server 작업 테스트 및 Azure 리소스 관리

필수 조건

비고

Azure MCP Server를 사용하여 액세스하려는 Azure 리소스는 Azure 구독 내에 이미 있어야 합니다. 또한 사용자 계정에는 해당 리소스에 대해 할당된 필요한 RBAC 역할 및 권한이 있어야 합니다.

로컬 개발을 위한 로그인

Azure MCP Server는 Microsoft Entra ID를 통해 토큰 기반 인증을 사용하여 원활한 인증 환경을 제공합니다. 내부적으로 Azure MCP Server는 DefaultAzureCredential에서 사용자를 인증하는 데 사용합니다.

Azure MCP Server를 사용하려면 Azure 계정으로 로컬에서 지원하는 DefaultAzureCredential 도구 중 하나에 로그인해야 합니다. Visual Studio Code 터미널과 같은 터미널 창을 사용하여 로그인합니다.

az login

이전 도구 중 하나에 성공적으로 로그인하면 Azure MCP Server에서 자격 증명을 자동으로 검색하고 이를 사용하여 Azure 서비스에 대한 작업을 인증하고 수행할 수 있습니다.

비고

Visual Studio를 통해 Azure에 로그인할 수도 있습니다. Azure MCP Server는 로그인한 사용자에게 수행할 권한이 있는 작업만 실행할 수 있습니다.

Python 앱 만들기

다음 단계를 완료하여 Python 앱을 만듭니다. 앱은 AI 모델에 연결하고 Azure MCP 서버에 연결하는 MCP 클라이언트의 호스트 역할을 합니다.

프로젝트를 만듭니다.

  1. 선택한 편집기 내에서 빈 폴더를 엽니다.

  2. 명명된 requirements.txt 새 파일을 만들고 다음 라이브러리 종속성을 추가합니다.

    mcp
    azure-identity
    openai
    logging
    
  3. 동일한 폴더에서 명명된 .env 새 파일을 만들고 다음 환경 변수를 추가합니다.

    AZURE_OPENAI_ENDPOINT=<your-azure-openai-endpoint>
    AZURE_OPENAI_MODEL=<your-model-deployment-name>
    
  4. 앱에 대한 코드를 저장할 빈 파일을 만듭니다 main.py .

환경 만들기 및 종속성 설치

  1. 새 폴더에서 터미널을 열고 앱에 대한 Python 가상 환경을 만듭니다.

    python -m venv venv
    
  2. 가상 환경을 활성화합니다.

    venv\Scripts\activate
    
  3. 다음의 requirements.txt에서 종속성을 설치하세요.

    pip install -r requirements.txt
    

앱 코드 추가

다음 코드로 내용을 업데이트합니다 Main.py .

from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
import json, os, logging, asyncio
from dotenv import load_dotenv

# Setup logging and load environment variables
logger = logging.getLogger(__name__)
load_dotenv()

# Azure OpenAI configuration
AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT")
AZURE_OPENAI_MODEL = os.getenv("AZURE_OPENAI_MODEL", "gpt-4o")

# Initialize Azure credentials
token_provider = get_bearer_token_provider(
    DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)

async def run():
    # Initialize Azure OpenAI client
    client = AzureOpenAI(
            azure_endpoint=AZURE_OPENAI_ENDPOINT, 
            api_version="2024-04-01-preview", 
            azure_ad_token_provider=token_provider
        )

    # MCP client configurations
    server_params = StdioServerParameters(
        command="npx",
        args=["-y", "@azure/mcp@latest", "server", "start"],
        env=None
    )

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # List available tools
            tools = await session.list_tools()
            for tool in tools.tools: print(tool.name)

            # Format tools for Azure OpenAI
            available_tools = [{
                "type": "function",
                "function": {
                    "name": tool.name,
                    "description": tool.description,
                    "parameters": tool.inputSchema
                }
            } for tool in tools.tools]

            # Start conversational loop
            messages = []
            while True:
                try:
                    user_input = input("\nPrompt: ")
                    messages.append({"role": "user", "content": user_input})

                    # First API call with tool configuration
                    response = client.chat.completions.create(
                        model = AZURE_OPENAI_MODEL,
                        messages = messages,
                        tools = available_tools)

                    # Process the model's response
                    response_message = response.choices[0].message
                    messages.append(response_message)

                    # Handle function calls
                    if response_message.tool_calls:
                        for tool_call in response_message.tool_calls:
                                function_args = json.loads(tool_call.function.arguments)
                                result = await session.call_tool(tool_call.function.name, function_args)

                                # Add the tool response to the messages
                                messages.append({
                                    "tool_call_id": tool_call.id,
                                    "role": "tool",
                                    "name": tool_call.function.name,
                                    "content": result.content,
                                })
                    else:
                        logger.info("No tool calls were made by the model")

                    # Get the final response from the model
                    final_response = client.chat.completions.create(
                        model = AZURE_OPENAI_MODEL,
                        messages = messages,
                        tools = available_tools)

                    for item in final_response.choices:
                        print(item.message.content)
                except Exception as e:
                    logger.error(f"Error in conversation loop: {e}")
                    print(f"An error occurred: {e}")

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

위의 코드는 다음 작업을 수행합니다.

  • 로깅을 설정하고 파일에서 환경 변수를 .env 로드합니다.
  • Azure OpenAI 클라이언트 사용 azure-identityopenai 라이브러리를 구성합니다.
  • 표준 I/O 전송을 사용하여 Azure MCP 서버와 상호 작용하도록 MCP 클라이언트를 초기화합니다.
  • MCP 서버에서 사용 가능한 도구 목록을 검색하고 표시합니다.
  • 사용자 프롬프트를 처리하고 도구를 활용하며 도구 호출을 처리하는 대화형 루프를 구현합니다.

앱 실행 및 테스트

다음 단계를 완료하여 .NET 호스트 앱을 테스트합니다.

  1. 프로젝트의 루트에 열려 있는 터미널 창에서 다음 명령을 실행하여 앱을 시작합니다.

    python main.py
    
  2. 앱이 실행되면 다음 테스트 프롬프트를 입력합니다.

    List all of the resource groups in my subscription
    

    이전 프롬프트의 출력은 다음 텍스트와 유사합니다.

    The following resource groups are available for your subscription:
    
    1. **DefaultResourceGroup-EUS** (Location: `eastus`)
    2. **rg-testing** (Location: `centralus`)
    3. **rg-azd** (Location: `eastus2`)
    4. **msdocs-sample** (Location: `southcentralus`)
    14. **ai-testing** (Location: `eastus2`)
    
    Let me know if you need further details or actions related to any of these resource groups!
    
  3. 다음과 같은 다른 관련 프롬프트를 사용하여 Azure MCP 작업을 탐색하고 테스트합니다.

    List all of the storage accounts in my subscription
    Get the available tables in my storage accounts
    

다음 단계