Skip to content
Back to search

remote-mcp-apim-functions-python

Azure API Management as AI Gateway to Remote MCP servers.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/azure-samples--remote-mcp-apim-functions-python/badge.svg)](/listings/azure-samples--remote-mcp-apim-functions-python)

HTML

<a href="/listings/azure-samples--remote-mcp-apim-functions-python"><img src="/api/listings/azure-samples--remote-mcp-apim-functions-python/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 247 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <!--
  2. ---
  3. name: Remote MCP using Azure API Management
  4. description: Use Azure API Management as the AI Gateway for MCP Servers using Azure Functions
  5. page_type: sample
  6. languages:
  7. - python
  8. - bicep
  9. - azdeveloper
  10. products:
  11. - azure-api-management
  12. - azure-functions
  13. - azure
  14. urlFragment: remote-mcp-apim-functions-python
  15. ---
  16. -->
  17. # Secure Remote MCP Servers using Azure API Management (Experimental)
  18. ![Diagram](mcp-client-authorization.gif)
  19. Azure API Management acts as the [AI Gateway](https://github.com/Azure-Samples/AI-Gateway) for MCP servers.
  20. This sample implements the latest [MCP Authorization specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#2-10-third-party-authorization-flow)
  21. This is a [sequence diagram](infra/app/apim-oauth/diagrams/diagrams.md) to understand the flow.
  22. ## Deploy Remote MCP Server to Azure
  23. 1. Register `Microsoft.App` resource provider.
  24. * If you are using Azure CLI, run `az provider register --namespace Microsoft.App --wait`.
  25. * If you are using Azure PowerShell, run `Register-AzResourceProvider -ProviderNamespace Microsoft.App`. Then run `(Get-AzResourceProvider -ProviderNamespace Microsoft.App).RegistrationState` after some time to check if the registration is complete.
  26. 2. Run this [azd](https://aka.ms/azd) command to provision the api management service, function app(with code) and all other required Azure resources
  27. ```shell
  28. azd up
  29. ```
  30. ### Test with MCP Inspector
  31. 1. In a **new terminal window**, install and run MCP Inspector
  32. ```shell
  33. npx @modelcontextprotocol/inspector
  34. ```
  35. 1. CTRL click to load the MCP Inspector web app from the URL displayed by the app (e.g. http://127.0.0.1:6274/#resources)
  36. 1. Set the transport type to `SSE`
  37. 1. Set the URL to your running API Management SSE endpoint displayed after `azd up` and **Connect**:
  38. ```shell
  39. https://<apim-servicename-from-azd-output>.azure-api.net/mcp/sse
  40. ```
  41. 5. **List Tools**. Click on a tool and **Run Tool**.
  42. ## Technical Architecture Overview
  43. This solution deploys a secure MCP (Model Context Protocol) server infrastructure on Azure. The architecture implements a multi-layered security model with Azure API Management serving as an intelligent gateway that handles authentication, authorization, and request routing.
  44. ![overview diagram](overview.png)
  45. ### Deployed Azure Resources
  46. The infrastructure provisions the following Azure resources:
  47. #### Core Gateway Infrastructure
  48. - **Azure API Management (APIM)** - The central security gateway that exposes both OAuth and MCP APIs
  49. - **SKU**: BasicV2 (configurable)
  50. - **Identity**: System-assigned and user-assigned managed identities
  51. - **Purpose**: Handles authentication flows, request validation, and secure proxying to backend services
  52. #### Backend Compute
  53. - **Azure Function App** - Hosts the MCP server implementation
  54. - **Runtime**: Python 3.11 on Flex Consumption plan
  55. - **Authentication**: Function-level authentication with managed identity integration
  56. - **Purpose**: Executes MCP tools and operations (snippet management in this example)
  57. #### Storage and Data
  58. - **Azure Storage Account** - Provides multiple storage functions
  59. - **Function hosting**: Stores function app deployment packages
  60. - **Application data**: Blob container for snippet storage
  61. - **Security**: Configured with managed identity access and optional private endpoints
  62. #### Security and Identity
  63. - **User-Assigned Managed Identity** - Enables secure service-to-service authentication
  64. - **Purpose**: Allows Function App to access Storage and Application Insights without secrets
  65. - **Permissions**: Storage Blob Data Owner, Storage Queue Data Contributor, Monitoring Metrics Publisher
  66. - **Entra ID Application Registration** - OAuth2/OpenID Connect client for authentication
  67. - **Purpose**: Enables third-party authorization flow per MCP specification
  68. - **Configuration**: PKCE-enabled public client with custom redirect URIs
  69. #### Monitoring and Observability
  70. - **Application Insights** - Provides telemetry and monitoring
  71. - **Log Analytics Workspace** - Centralized logging and analytics
  72. #### Optional Network Security
  73. - **Virtual Network (VNet)** - When `vnetEnabled` is true
  74. - **Private Endpoints**: Secure connectivity to Storage Account
  75. - **Network Isolation**: Functions and storage communicate over private network
  76. ### Why These Resources?
  77. **Azure API Management** serves as the security perimeter, implementing:
  78. - OAuth 2.0/PKCE authentication flows per MCP specification
  79. - Session key encryption/decryption for secure API access
  80. - Request validation and header injection
  81. - Rate limiting and throttling capabilities
  82. - Centralized policy management
  83. **Azure Functions** provides:
  84. - Serverless, pay-per-use compute model
  85. - Native integration with Azure services
  86. - Automatic scaling based on demand
  87. - Built-in monitoring and diagnostics
  88. **Managed Identities** eliminate the need for:
  89. - Service credentials management
  90. - Secret rotation processes
  91. - Credential exposure risks
  92. ## Azure API Management Configuration Details
  93. The APIM instance is configured with two primary APIs that work together to implement the MCP authorization specification:
  94. ### OAuth API (`/oauth/*`)
  95. This API implements the complete OAuth 2.0 authorization server functionality required by the MCP specification:
  96. #### Endpoints and Operations
  97. **Authorization Endpoint** (`GET /authorize`)
  98. - **Purpose**: Initiates the OAuth 2.0/PKCE flow
  99. - **Policy Logic**:
  100. 1. Extracts PKCE parameters from MCP client request
  101. 2. Checks for existing user consent (via cookies)
  102. 3. Redirects to consent page if consent not granted
  103. 4. Generates new PKCE parameters for Entra ID communication
  104. 5. Stores authentication state in APIM cache
  105. 6. Redirects user to Entra ID for authentication
  106. **Consent Management** (`GET/POST /consent`)
  107. - **Purpose**: Handles user consent for MCP client access
  108. - **Features**: Consent persistence via secure cookies
  109. **OAuth Metadata Endpoint** (`GET /.well-known/oauth-authorization-server`)
  110. - **Purpose**: Publishes OAuth server configuration per RFC 8414
  111. - **Returns**: JSON metadata about supported endpoints, flows, and capabilities
  112. **Client Registration** (`POST /register`)
  113. - **Purpose**: Supports dynamic client registration per MCP specification
  114. **Token Endpoint** (`POST /token`)
  115. - **Purpose**: Exchanges authorization codes for access tokens
  116. - **Policy Logic**:
  117. 1. Validates authorization code and PKCE verifier from MCP client
  118. 2. Exchanges Entra ID authorization code for access tokens
  119. 3. Generates encrypted session key for MCP API access
  120. 4. Caches the access token with session key mapping
  121. 5. Returns encrypted session key to MCP client
  122. #### Named Values and Configuration
  123. The OAuth API uses several APIM Named Values for configuration:
  124. - `McpClientId` - The registered Entra ID application client ID
  125. - `EntraIDFicClientId` - Service identity client ID for token exchange
  126. - `APIMGatewayURL` - Base URL for callback and metadata endpoints
  127. - `OAuthScopes` - Requested OAuth scopes (`openid` + Microsoft Graph)
  128. - `EncryptionKey` / `EncryptionIV` - For session key encryption
  129. ### MCP API (`/mcp/*`)
  130. This API provides the actual MCP protocol endpoints with security enforcement:
  131. #### Endpoints and Operations
  132. **Server-Sent Events Endpoint** (`GET /sse`)
  133. - **Purpose**: Establishes real-time communication channel for MCP protocol
  134. - **Security**: Requires valid encrypted session token
  135. **Message Endpoint** (`POST /message`)
  136. - **Purpose**: Handles MCP protocol messages and tool invocations
  137. - **Security**: Requires valid encrypted session token
  138. #### Security Policy Implementation
  139. The MCP API applies a comprehensive security policy to all operations:
  140. 1. **Authorization Header Validation**
  141. ```xml
  142. <check-header name="Authorization" failed-check-httpcode="401"
  143. failed-check-error-message="Not authorized" ignore-case="false" />
  144. ```
  145. 2. **Session Key Decryption**
  146. - Extracts encrypted session key from Authorization header
  147. - Decrypts using AES with stored key and IV
  148. - Validates token format and structure
  149. 3. **Token Cache Lookup**
  150. ```xml
  151. <cache-lookup-value key="@($"EntraToken-{context.Variables.GetValueOrDefault("decryptedSessionKey")}")"
  152. variable-name="accessToken" />
  153. ```
  154. 4. **Access Token Validation**
  155. - Verifies cached access token exists and is valid
  156. - Returns 401 with proper WWW-Authenticate header if invalid
  157. 5. **Backend Authentication**
  158. ```xml
  159. <set-header name="x-functions-key" exists-action="override">
  160. <value>{{function-host-key}}</value>
  161. </set-header>
  162. ```
  163. ### Security Model
  164. The solution implements a sophisticated multi-layer security model:
  165. **Layer 1: OAuth 2.0/PKCE Authentication**
  166. - MCP clients must complete full OAuth flow with Entra ID
  167. - PKCE prevents authorization code interception attacks
  168. - User consent management with persistent preferences
  169. **Layer 2: Session Key Encryption**
  170. - Access tokens are never exposed to MCP clients
  171. - Encrypted session keys provide time-bounded access
  172. - AES encryption with secure key management in APIM
  173. **Layer 3: Function-Level Security**
  174. - Function host keys protect direct access to Azure Functions
  175. - Managed identity ensures secure service-to-service communication
  176. - Network isolation available via VNet integration
  177. **Layer 4: Azure Platform Security**
  178. - All traffic encrypted in transit (TLS)
  179. - Storage access via managed identities
  180. - Audit logging through Application Insights
  181. This layered approach ensures that even if one security boundary is compromised, multiple additional protections remain in place.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.