MCP Gateway

repository·main·Indexed 20 days ago

https://github.com/microsoft/mcp-gateway

A reverse proxy and management layer for Model Context Protocol (MCP) servers designed for Kubernetes. It provides scalable, session-aware routing, authorization, and lifecycle management through a Data Plane for traffic handling and a Control Plane for adapter and tool management. The project includes the mcp-gateway-portal (v0.1.0), a React and TypeScript SPA for management, and supports deployment via PowerShell or Bicep on Azure infrastructure including AKS, ACR, and Cosmos DB.

Tokens
16.4K
Snippets
39
Records
64
Agent score
72%

What's inside MCP Gateway

  1. Overview of MCP Gateway

    main

    MCP Gateway is a reverse proxy and management layer designed for Model Context Protocol (MCP) servers. It is specifically built for Kubernetes environments to provide scalable, session-aware routing, authorization, and lifecycle management.

    It consists of two primary functional areas:

    1. Data Plane: Handles routing traffic to MCP servers with session affinity.
    2. Control Plane: Manages the MCP server lifecycle, including deployment, updates, and deletion.
  2. Overview of Deployed Azure Resources

    main

    The MCP Gateway deployment creates a multi-layered architecture in Azure consisting of the following components:

    Core Infrastructure

    • Azure Kubernetes Service (AKS): A 2-node cluster using D4ds_v5 VMs with Azure RBAC, OIDC issuer, and Workload Identity enabled.
    • Azure Container Registry (ACR): Standard SKU for container image storage, integrated with AKS.
    • Azure Cosmos DB: Document database for gateway state (AdapterContainer, CacheContainer, ToolContainer) using session consistency.

    Networking

    • Virtual Network (VNet): Includes subnets for AKS (10.0.1.0/24), Application Gateway (10.0.2.0/24), and Private Endpoints (10.0.3.0/24).
    • Application Gateway: Standard_v2 SKU acting as a Layer 7 load balancer on port 80.
    • Public IP: Static public IP with a DNS label.

    Identity & Access

    • Managed Identities: Includes Gateway service identity (Cosmos DB contributor), Admin identity (AKS operations), and Workload identity (pod-level auth).
    • Federated Credentials: Enables Kubernetes service account integration.

    Monitoring

    • Application Insights: Provides application monitoring and telemetry.
  3. Route MCP Requests via the Data Plane

    main

    The Data Plane handles the actual execution and routing of MCP requests. There are two primary ways to access MCP functionality:

    1. Direct MCP Server Access: Connect directly to a specific deployed adapter using POST /adapters/{name}/mcp. This establishes a streamable HTTP connection.
    2. Dynamic Tool Routing: Use the Tool Gateway Router by sending requests to POST /mcp. The gateway routes these requests to a specialized router that dynamically identifies and forwards the request to the appropriate registered tool server based on the tool definition.
  4. Key Concepts in MCP Gateway

    main

    To use MCP Gateway effectively, you should understand its core abstractions:

    • MCP Server: A server implementing the Model Context Protocol, typically exposed as a streamable HTTP endpoint.
    • Adapters: Logical resources representing MCP servers within the gateway, managed under the /adapters scope. They allow MCP servers to coexist with other resource types like /agents.
    • Tools: Registered resources containing MCP tool definitions. These can be dynamically routed via the tool gateway router and include metadata for execution endpoints and input schemas.
    • Tool Gateway Router: An MCP server that acts as an intelligent router. It directs tool execution requests to the correct registered tool servers based on their definitions. Multiple instances can run for session affinity.
    • Session-Aware Stateful Routing: A mechanism that ensures all requests sharing a specific session_id are consistently routed to the same MCP server instance.
    • Agents & Sessions (Preview): Opt-in features for running LLM-driven agents.
      • Agents are metadata consisting of a system prompt, a model, and an allowed tool list.
      • Sessions are individual runs that stream events via Server-Sent Events (SSE).
      • Note: These are disabled unless FoundrySettings:Endpoint is configured.
  5. Understand MCP Gateway Portal authentication modes

    main

    The portal automatically adjusts its authentication behavior based on the configuration returned from the GET /portal/config endpoint.

    Local / Dev Mode

    When isDevelopment: true is returned:

    • The portal skips MSAL (Microsoft Authentication Library).
    • It uses a DevelopmentAuthenticationHandler on the gateway which uses a synthetic dev principal.
    • Users can optionally select a synthetic identity (user ID, display name, roles). These are forwarded to the gateway via the following headers:
      • X-Dev-UserId
      • X-Dev-Name
      • X-Dev-Roles

    Cloud / Production Mode

    When running in production:

    • The portal initializes @azure/msal-browser using the tenant and client ID provided by /portal/config.
    • Users sign in via a redirect flow.
    • The portal acquires an access token with the api://<clientId>/.default scope.
    • Every API call includes the token in the Bearer authorization header.
  6. Configure Authentication and Authorization

    main

    The gateway uses Azure Entra ID for authentication and application role authorization.

    Access Rules:

    • Read Access: Granted to the resource creator, principals with configured requiredRoles (e.g., mcp.engineer), and anyone with the mcp.admin role. If requiredRoles is empty/omitted, only the creator and mcp.admin can read.
    • Write Access: Restricted to the resource creator or principals holding the mcp.admin role.

    For detailed configuration of Entra ID roles, see docs/entra-app-roles.md.

  7. MCP Gateway Architecture

    main

    The MCP Gateway architecture separates management (Control Plane) from traffic handling (Data Plane) and interacts with a Kubernetes cluster.

    Data Plane

    • Adapter Routing: Accessible via /adapters/{name}/mcp.
    • Tool Router Gateway: Accessible via /mcp.
    • Both planes support Authentication & Authorization using Bearer Tokens and RBAC.

    Control Plane

    • Adapter Management: CRUD operations for /adapters.
    • Tool Management: CRUD operations for /tools.

    Backend & Infrastructure

    • Deployment Manager: Handles deploying and monitoring workloads in the Kubernetes cluster.
    • Metadata Manager: Manages server and tool information in a Metadata Store.
    • Routing: Uses session affinity to route requests to specific MCP server pods or Tool Gateway Router instances, which then perform dynamic routing to registered Tool Servers.
  8. Apply Required Roles to Adapters or Tools

    main

    When creating adapters or tools via management APIs or the CLI, you can restrict access by populating the requiredRoles collection with the exact Value strings defined in Azure Entra ID.

    Authorization Logic (SimplePermissionProvider):

    • Read Access: Granted if the caller is the resource creator, holds the mcp.admin role, or matches one of the entries in requiredRoles.
    • Write Access: Granted if the caller is the resource creator or holds the mcp.admin role.

    Note: If requiredRoles is not configured, the gateway defaults to ALLOW ALL READ access.

    Example Payload:

    {
      "name": "sample-adapter",
      "requiredRoles": ["mcp.engineer", "mcp.scientist"]
    }
  9. Define and Run an Agent Session

    main

    Once FoundrySettings is configured, you can define agents and run interactive sessions.

    Defining an Agent: Agents are created via POST /agents. Tools in the tools array are namespaced:

    • mcp:<tool-name>: Routes to a tool registered via /tools.
    • agent:<agent-name>: Delegates to another agent (subagent/Task pattern).
    • builtin:bash, builtin:read_file, builtin:write_file: In-process built-in tools.
    POST /agents
    Authorization: Bearer <token>
    Content-Type: application/json
    
    {
      "name": "weather-helper",
      "model": "gpt-4o",
      "system": "You answer weather questions concisely.",
      "tools": ["mcp:weather"],
      "description": "Demo agent backed by the weather MCP tool."
    }

    Running a Session: Start a session using POST /sessions/run. This returns a Server-Sent Events (SSE) stream. Event types include Started, ToolCallStarted, ToolCallCompleted, TokenDelta, Completed, and Failed.

    POST /sessions/run
    Authorization: Bearer <token>
    Content-Type: application/json
    Accept: text/event-stream
    
    { "agentName": "weather-helper", "input": "What's the weather in Seattle?" }

    Continuing a Session: To send a follow-up message to an existing session, use POST /sessions/{id}/messages.

    POST /sessions/{id}/messages
    Content-Type: application/json
    
    { "input": "And in Portland?" }
  10. Deploy MCP Gateway using Bicep (Legacy)

    main

    You can deploy the infrastructure directly using Bicep via the Azure CLI. This method is considered legacy compared to the PowerShell script.

    Deployment Steps

    1. Create a resource group:
      az group create --name rg-mcpgateway-dev --location eastus
    2. Deploy the Bicep template:
      az deployment group create \
        --name mcpgateway-deployment \
        --resource-group rg-mcpgateway-dev \
        --template-file azure-deployment.bicep \
        --parameters clientId=<your-entra-client-id>

    Additional Bicep Parameters

    • resourceLabel: Alphanumeric suffix for naming.
    • location: Azure region.
    • enablePrivateEndpoints: Set to true to enable private endpoints.
    • enableKubernetesDeploymentScript: Set to false to disable the embedded Kubernetes deployment script.
    # Deploy using Bicep with additional parameters
    az deployment group create \
      --name mcpgateway-deployment \
      --resource-group rg-mcpgateway-dev \
      --template-file azure-deployment.bicep \
      --parameters \
        clientId=<your-entra-client-id> \
        resourceLabel=mcpdev \
        location=westus2 \
        enablePrivateEndpoints=true
  11. Run the MCP Gateway Portal locally

    main

    To run the portal in development mode, you must first have the MCP Gateway deployed and running (e.g., on http://localhost:8000). The portal uses Vite to proxy API requests to the gateway to avoid CORS issues.

    1. Navigate to the portal directory.
    2. Install dependencies.
    3. Start the development server.
    4. Access the app at http://localhost:5173/portal/. Note that the app uses a /portal router basename, so the root path (/) will appear blank.

    If your gateway is running on a different host, override the proxy target using the VITE_GATEWAY_URL environment variable.

    # from the repo root, after deploying the gateway to localhost:8000
    cd portal
    npm install
    npm run dev
    
    # To override the gateway target:
    VITE_GATEWAY_URL=http://example:8000 npm run dev