{ "cells": [ { "cell_type": "markdown", "id": "14db6a8f", "metadata": {}, "source": [ "# 🔌 Model Context Protocol (MCP) Integration with Azure AI Foundry (Python)\n", "\n", "## 📋 MCP Enterprise Integration Tutorial\n", "\n", "This notebook demonstrates advanced **Model Context Protocol (MCP)** integration using Azure AI Foundry and the Microsoft Agent Framework. You'll learn how to connect AI agents to external data sources and services through standardized MCP interfaces for enterprise-grade integrations.\n", "\n", "## 🎯 Learning Objectives\n", "\n", "### 🔗 **MCP Protocol Understanding**\n", "- **Protocol Architecture**: Learn the MCP specification and communication patterns\n", "- **Server Integration**: Connect to MCP-enabled services and data sources\n", "- **Streaming Operations**: Handle real-time data streams through MCP\n", "- **Tool Orchestration**: Coordinate multiple MCP tools within agent workflows\n", "\n", "### 🏢 **Enterprise MCP Applications**\n", "- **Knowledge Base Integration**: Connect agents to corporate knowledge repositories\n", "- **API Service Mesh**: Integrate with existing enterprise APIs through MCP\n", "- **Real-Time Data Feeds**: Stream live data from business systems\n", "- **Multi-Modal Content**: Access diverse content types through standardized protocols\n", "\n", "### 🛡️ **Security & Compliance**\n", "- **Azure Identity Integration**: Enterprise-grade authentication and authorization\n", "- **Secure Connections**: Encrypted communication with MCP servers\n", "- **Access Control**: Role-based permissions for MCP resource access\n", "- **Audit Logging**: Complete traceability of MCP interactions\n", "\n", "## ⚙️ Prerequisites & Setup\n", "\n", "### 📦 **Required Dependencies**\n", "\n", "Install Agent Framework with MCP support:\n", "\n", "```bash\n", "pip install agent-framework-azure-ai -U\n", "```\n", "\n", "### 🔑 **Azure Configuration**\n", "\n", "**Required Azure Resources:**\n", "- Azure AI Foundry workspace\n", "- Appropriate RBAC permissions for AI services\n", "- Network access to MCP endpoints\n", "\n", "**Authentication Setup:**\n", "```bash\n", "# Azure CLI authentication\n", "az login\n", "az account set --subscription \"your-subscription-id\"\n", "```\n", "\n", "## 🏗️ **MCP Architecture Overview**\n", "\n", "### Core Components\n", "```mermaid\n", "graph LR\n", " A[AI Agent] --> B[MCP Client]\n", " B --> C[MCP Protocol]\n", " C --> D[MCP Server]\n", " D --> E[Data Source]\n", " \n", " F[Azure Identity] --> A\n", " G[Tool Registry] --> A\n", " H[Streaming Handler] --> B\n", "```\n", "\n", "**Key Integration Points:**\n", "- **AzureAIAgentClient**: Enterprise AI agent with Azure integration\n", "- **MCPStreamableHTTPTool**: HTTP-based MCP tool for external services\n", "- **AzureCliCredential**: Secure Azure authentication\n", "- **Tool Orchestration**: Coordinated multi-tool operations\n", "\n", "## 🌐 **MCP Use Cases**\n", "\n", "### 📚 **Knowledge Integration**\n", "- **Microsoft Learn**: Access technical documentation and learning content\n", "- **Enterprise Wikis**: Integrate corporate knowledge bases\n", "- **Documentation Systems**: Connect to internal documentation platforms\n", "- **Training Materials**: Access educational and training resources\n", "\n", "### 🔄 **Business System Integration**\n", "- **CRM Systems**: Customer relationship management data access\n", "- **ERP Integration**: Enterprise resource planning system connectivity\n", "- **Database Queries**: Direct database access through MCP protocols\n", "- **API Gateways**: Standardized access to multiple business APIs\n", "\n", "### 📊 **Real-Time Data Sources**\n", "- **Monitoring Systems**: Live system metrics and performance data\n", "- **IoT Platforms**: Internet of Things device data streams\n", "- **Market Data**: Financial and business intelligence feeds\n", "- **Social Media**: Real-time social media monitoring and analysis\n", "\n", "## 🎨 **Enterprise MCP Patterns**\n", "\n", "### 🔐 **Secure Integration Pattern**\n", "```python\n", "# Azure identity + MCP tool + AI agent coordination\n", "async with (\n", " AzureCliCredential() as credential,\n", " MCPTool(\"enterprise-api\", \"https://internal.company.com/mcp\") as mcp,\n", " ChatAgent(client, tools=[mcp]) as agent\n", "):\n", " result = await agent.run(\"Query our customer database\")\n", "```\n", "\n", "### 📊 **Multi-Source Data Pattern**\n", "```python\n", "# Multiple MCP sources in single workflow\n", "tools = [\n", " MCPTool(\"crm\", \"https://crm.company.com/mcp\"),\n", " MCPTool(\"erp\", \"https://erp.company.com/mcp\"), \n", " MCPTool(\"docs\", \"https://docs.company.com/mcp\")\n", "]\n", "```\n", "\n", "Let's explore enterprise MCP integrations! 🚀" ] }, { "cell_type": "code", "execution_count": 24, "id": "4e6efa87", "metadata": {}, "outputs": [], "source": [ "\n", "# ! pip install -r ../../../../requirements.txt -U" ] }, { "cell_type": "code", "execution_count": 25, "id": "64afe447", "metadata": {}, "outputs": [], "source": [ "# 🔌 Import MCP and Azure AI Foundry Components\n", "# Essential components for Model Context Protocol integration with enterprise services\n", "\n", "import os\n", "import asyncio\n", "from typing import TYPE_CHECKING, Any\n", "\n", "from agent_framework import Agent\n", "from agent_framework.foundry import FoundryChatClient\n", "from azure.identity import AzureCliCredential\n", "from dotenv import load_dotenv" ] }, { "cell_type": "code", "execution_count": 26, "id": "1c43acf5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "load_dotenv()" ] }, { "cell_type": "code", "execution_count": 27, "id": "5e12b13b", "metadata": {}, "outputs": [], "source": [ "credential = AzureCliCredential()\n", "client = FoundryChatClient(credential=credential)" ] }, { "cell_type": "code", "execution_count": 28, "id": "3df6e018", "metadata": {}, "outputs": [], "source": [ "mcp_tool = client.get_mcp_tool(\n", " name=\"Microsoft Learn MCP\",\n", " url=\"https://learn.microsoft.com/api/mcp\",\n", " # we don't require approval for any function calls\n", " # this means we will not see the approval messages,\n", " # it is fully handled by the service and a final response is returned.\n", " approval_mode=\"never_require\",\n", ")" ] }, { "cell_type": "markdown", "id": "a998c3c5", "metadata": {}, "source": [ "## 🔧 MCP Tool Integration Patterns\n", "\n", "The reference sample demonstrates **two MCP tool integration patterns**:\n", "\n", "### 🏃 **Pattern 1: Run-Level MCP Tools**\n", "- MCP tools are defined and connected **before** running the agent\n", "- Tools are passed to the `agent.run()` method directly\n", "- Best for dynamic tool selection per query\n", "\n", "### 🏗️ **Pattern 2: Agent-Level MCP Tools**\n", "- MCP tools are passed when **creating** the agent via `create_agent()`\n", "- The agent connects to MCP servers through its context manager (`async with agent`)\n", "- Best for agents with fixed tool configurations\n", "\n", "**Key Components:**\n", "- 🔐 **AzureCliCredential**: Secure Azure authentication\n", "- 🔌 **MCPStreamableHTTPTool**: HTTP-based MCP tool for external services\n", "- 🏢 **AzureAIAgentsProvider**: Azure AI Foundry agent provider\n" ] }, { "cell_type": "code", "execution_count": 29, "id": "42186988", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "User: How to create an Azure storage account using az cli?\n", "DocsAgent: Use these Azure CLI commands:\n", "\n", "```bash\n", "# Sign in\n", "az login\n", "\n", "# Create a resource group\n", "az group create \\\n", " --name storage-resource-group \\\n", " --location eastus\n", "\n", "# Create a general-purpose v2 storage account\n", "az storage account create \\\n", " --name \\\n", " --resource-group storage-resource-group \\\n", " --location eastus \\\n", " --sku Standard_RAGRS \\\n", " --kind StorageV2 \\\n", " --min-tls-version TLS1_2 \\\n", " --allow-blob-public-access false\n", "```\n", "\n", "Replace `` with a globally unique name. Storage account names must be 3–24 characters, lowercase letters and numbers only.\n", "\n", "If you want to see available regions:\n", "\n", "```bash\n", "az account list-locations \\\n", " --query \"[].{Region:name}\" \\\n", " --out table\n", "```\n", "\n", "If you want to verify the account after creation:\n", "\n", "```bash\n", "az storage account show \\\n", " --name \\\n", " --resource-group storage-resource-group \\\n", " --output table\n", "```\n", "\n", "If you want Azure Data Lake Storage Gen2 support, add:\n", "\n", "```bash\n", "--enable-hierarchical-namespace true\n", "```\n", "\n", "Official Microsoft Learn reference:\n", "https://learn.microsoft.com/azure/storage/common/storage-account-create#create-a-storage-account\n", "\n", "If you want, I can also give you:\n", "- a minimal example with `Standard_LRS`\n", "- a script that creates a unique storage account name\n", "- commands to create a blob container afterward\n", "\n" ] } ], "source": [ "async with Agent(\n", " client=client,\n", " name=\"DocsAgent\",\n", " instructions=\"You are a helpful assistant that uses your MCP tool \"\n", " \"to help with Microsoft documentation questions.\",\n", " tools=[mcp_tool],\n", " ) as agent:\n", " # First query\n", " query = \"How to create an Azure storage account using az cli?\"\n", " print(f\"User: {query}\")\n", "\n", " result = await agent.run(query)\n", " # while len(result.user_input_requests) > 0:\n", " # new_inputs: list[Any] = [query]\n", " # for user_input_needed in result.user_input_requests:\n", " # print(\n", " # f\"User Input Request for function from {agent.name}: {user_input_needed.function_call.name}\"\n", " # f\" with arguments: {user_input_needed.function_call.arguments}\"\n", " # )\n", " # new_inputs.append(Message(role=\"assistant\", contents=[user_input_needed]))\n", " # user_approval = input(\"Approve function call? (y/n): \")\n", " # new_inputs.append(\n", " # Message(\n", " # role=\"user\",\n", " # contents=[user_input_needed.to_function_approval_response(user_approval.lower() == \"y\")],\n", " # )\n", " # )\n", "\n", " # result = await agent.run(new_inputs)\n", "\n", " print(f\"{agent.name}: {result.text}\\n\")\n" ] } ], "metadata": { "kernelspec": { "display_name": "agentdev", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.10" } }, "nbformat": 4, "nbformat_minor": 5 }