### Example Development Authentication Request Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/authentication-authorization.md An example HTTP GET request demonstrating the required headers for development authentication in MCP Gateway. ```http GET /adapters X-Dev-User-Id: user@contoso.com X-Dev-User-Name: John Doe X-Dev-User-Email: user@contoso.com ``` -------------------------------- ### Development Configuration Example Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/configuration.md Example configuration for a development environment, including debug logging, bypassing Entra authentication, and local service endpoints. ```json { "Logging": { "LogLevel": { "Default": "Debug" } }, "Authentication": { "BypassEntra": true }, "PublicOrigin": "http://localhost:8000", "Redis": { "ConnectionString": "localhost:6379" }, "Storage": { "UseInMemoryStores": null }, "ContainerRegistrySettings": { "Endpoint": "localhost:5000" } } ``` -------------------------------- ### Install and Run Portal Locally Source: https://github.com/microsoft/mcp-gateway/blob/main/portal/README.md Steps to install dependencies and run the portal in development mode. The Vite development server proxies API requests to the gateway. ```bash cd portal npm install npm run dev ``` -------------------------------- ### Production Configuration Example Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/configuration.md Example configuration for a production environment, specifying production logging levels, Azure AD authentication details, and cloud service endpoints. ```json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning" } }, "Authentication": { "BypassEntra": false }, "AzureAd": { "TenantId": "YOUR_TENANT_ID", "ClientId": "YOUR_API_CLIENT_ID" }, "PublicOrigin": "https://mcpgateway.contoso.com", "CosmosSettings": { "AccountEndpoint": "https://mcpgateway-db.documents.azure.com:443/", "DatabaseName": "mcpgateway" }, "ContainerRegistrySettings": { "Endpoint": "myregistry.azurecr.io" }, "FoundrySettings": { "Endpoint": "https://myai.openai.azure.com/", "DeploymentName": "gpt-4o" }, "BuiltinToolSettings": { "RequiredRoles": ["mcp.engineer"] } } ``` -------------------------------- ### Example Server-Sent Events Stream Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md An example demonstrating the sequence of events during a session run, including 'Started', 'TokenDelta', and 'Completed' events. ```text event: Started data: {"type":"Started","sessionId":"sess-abc123","iteration":0} event: TokenDelta data: {"type":"TokenDelta","sessionId":"sess-abc123","iteration":0,"deltaText":"The"} event: TokenDelta data: {"type":"TokenDelta","sessionId":"sess-abc123","iteration":0,"deltaText":" weather"} event: Completed data: {"type":"Completed","sessionId":"sess-abc123","iteration":0,"answer":"The weather in Seattle is clear"} ``` -------------------------------- ### Run Local Docker Registry Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Starts a local Docker registry service. Ensure Docker Desktop is installed and running. ```sh docker run -d -p 5000:5000 --name registry registry:2.7 ``` -------------------------------- ### Get Adapter Logs using GET /adapters/{name}/logs Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve container logs for a specific adapter instance. You can specify the instance index using the `instance` query parameter. Authentication with a Bearer token is required. ```text Plain text container log output. ``` -------------------------------- ### Run Streaming Session Example Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/service-interfaces.md Demonstrates how to create and execute a session, streaming events as they occur. This is useful for interactive or long-running operations where intermediate results are needed. ```csharp var service = serviceProvider.GetRequiredService(); await foreach (var evt in service.RunStreamingAsync( HttpContext.User, new SessionData { AgentName = "my-agent", Input = "Hello" }, cancellationToken)) { Console.WriteLine($"{evt.Type}: {evt.SessionId}"); } ``` -------------------------------- ### Create Agent and Run Session Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/README.md This example demonstrates how to define a new agent with specific model and tools, and then initiate a streaming session with that agent. Remember to substitute $TOKEN with your authentication token. ```bash # Create agent curl -X POST http://localhost:8000/agents \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name":"my-agent", "model":"gpt-4o", "system":"You help users.", "tools":["mcp:my-tool"] }' ``` ```bash # Run session with streaming curl -X POST http://localhost:8000/sessions/run \ -H "Authorization: Bearer $TOKEN" \ -H "Accept: text/event-stream" \ -d '{ "agentName":"my-agent", "input":"Hello!" }' ``` -------------------------------- ### Create Adapter Example Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/service-interfaces.md Demonstrates how to create and deploy a new adapter using the IAdapterManagementService. Requires obtaining an instance of the service and providing user claims, adapter data, and a cancellation token. ```csharp var service = serviceProvider.GetRequiredService(); var adapter = await service.CreateAsync( HttpContext.User, new AdapterData { Name = "my-adapter", ImageName = "mcp-example", ImageVersion = "1.0.0" }, cancellationToken); Console.WriteLine($"Created: {adapter.Id}"); ``` -------------------------------- ### Role Normalization Example Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/errors.md Demonstrates how role names are normalized by trimming whitespace, removing duplicates, and performing case-insensitive comparisons. ```json { "requiredRoles": [" mcp.engineer ", "MCP.ADMIN", "mcp.engineer"] } ``` -------------------------------- ### Authorization Log Examples Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/authentication-authorization.md Illustrates different log entries for authorization events, including successful authentication, denied access, and granted access. ```log [auth] User user@contoso.com authenticated via Entra ID ``` ```log [authz] User user@contoso.com denied write access to adapter mcp-example (not owner, lacks mcp.admin) ``` ```log [authz] User user@contoso.com granted read access to adapter mcp-example (creator) ``` -------------------------------- ### Deploy MCP Gateway with PowerShell (Basic) Source: https://github.com/microsoft/mcp-gateway/blob/main/deployment/infra/README.md Use this command to deploy the MCP Gateway infrastructure with basic configuration. Ensure Azure CLI is installed and authenticated. ```powershell .\Deploy-McpGateway.ps1 -ResourceGroupName "rg-mcpgateway-dev" -ClientId "" ``` -------------------------------- ### GET /adapters/{name}/logs — Get Adapter Logs Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieves container logs for a specific instance of an adapter. Supports filtering by instance index. Requires Bearer token authentication. ```APIDOC ## GET /adapters/{name}/logs — Get Adapter Logs ### Description Fetch container logs from a specific pod instance. ### Method GET ### Endpoint /adapters/{name}/logs ### Parameters #### Path Parameters - **name** (string) - Required - Adapter name #### Query Parameters - **instance** (integer) - Optional - Default: 0 - Pod instance index (0 for the first replica) ### Response #### Success Response (200 OK) Returns plain text container log output. #### Error Responses - 200: Pod is still starting; returns placeholder message - 401: Missing or invalid Bearer token - 403: User lacks read permission - 404: Adapter or instance not found ``` -------------------------------- ### Example MCP Request with Session ID Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/data-plane-routing.md Demonstrates how to include a session ID in the `mcp-session-id` header for requests to an adapter, enabling session affinity. ```http POST /adapters/mcp-example/mcp mcp-session-id: my-session-123 Content-Type: application/json ``` -------------------------------- ### Get Adapter Logs Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/errors.md Retrieve logs for a specific adapter instance. Specify the adapter name and instance number. Replace '$TOKEN' with your actual authorization token. ```bash curl -X GET http://localhost:8000/adapters/my-adapter/logs?instance=0 \ -H "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Get Adapter Status Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/errors.md Use this command to check the deployment status of an adapter. Ensure you replace 'my-adapter' with the actual adapter name and provide a valid authorization token. ```bash curl -X GET http://localhost:8000/adapters/my-adapter/status \ -H "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Session Affinity Header Example Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/data-plane-routing.md Demonstrates how to include a session ID in the request header to enable session affinity. ```APIDOC ## POST /adapters/mcp-example/mcp with Session Affinity ### Description This example shows how to send a request to an adapter while maintaining session affinity using the `mcp-session-id` header. ### Method POST ### Endpoint /adapters/mcp-example/mcp ### Headers - **mcp-session-id**: (string) - Required - The unique identifier for the session. - **Content-Type**: (string) - Required - `application/json` ### Request Example ```http POST /adapters/mcp-example/mcp mcp-session-id: my-session-123 Content-Type: application/json { "jsonrpc": "2.0", "method": "someMethod", "params": [], "id": 1 } ``` ### Response Example ```http HTTP/1.1 200 OK mcp-session-id: my-session-123 Content-Type: application/json { "jsonrpc": "2.0", "result": null, "id": 1 } ``` ``` -------------------------------- ### Get Access Token Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/authentication-authorization.md Use this command to retrieve an access token for authentication. Ensure the resource ID is correctly specified. ```bash az account get-access-token --resource YOUR_CLIENT_ID ``` -------------------------------- ### Get Adapter Status Async Signature Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/service-interfaces.md Signature for fetching the Kubernetes deployment status of an adapter. Use this to query the current state of an adapter. ```csharp Task GetAdapterStatusAsync( string adapterName, CancellationToken cancellationToken = default) ``` -------------------------------- ### List Adapters using GET /adapters Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve a list of all adapters accessible by the authenticated user. This endpoint requires a valid Bearer token. ```json [ { "id": "mcp-example", "name": "mcp-example", "imageName": "mcp-example", "imageVersion": "1.0.0", "description": "Example MCP server", "replicaCount": 2, "environmentVariables": {}, "useWorkloadIdentity": false, "requiredRoles": [], "createdBy": "user@contoso.com", "createdAt": "2024-01-15T10:30:00Z", "lastUpdatedAt": "2024-01-15T10:30:00Z" } ] ``` -------------------------------- ### Verify Tool Deployment Status Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Send a GET request to check the deployment status of a registered tool. This requires an authorization header with a bearer token. ```http GET http://..cloudapp.azure.com/tools/weather/status Authorization: Bearer ``` -------------------------------- ### GET /adapters — List Adapters Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieves a list of all adapters that the authenticated user has read access to. Requires Bearer token authentication. ```APIDOC ## GET /adapters — List Adapters ### Description Retrieve all adapters the authenticated user can read. ### Method GET ### Endpoint /adapters ### Response #### Success Response (200 OK) Returns a JSON array of `AdapterResource` objects. ```json [ { "id": "mcp-example", "name": "mcp-example", "imageName": "mcp-example", "imageVersion": "1.0.0", "description": "Example MCP server", "replicaCount": 2, "environmentVariables": {}, "useWorkloadIdentity": false, "requiredRoles": [], "createdBy": "user@contoso.com", "createdAt": "2024-01-15T10:30:00Z", "lastUpdatedAt": "2024-01-15T10:30:00Z" } ] ``` #### Error Responses - 401: Missing or invalid Bearer token ``` -------------------------------- ### Development Authentication Handler Example Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/authentication-authorization.md This C# code implements a custom authentication handler for development environments, extracting user identity from specific request headers. ```csharp public class DevelopmentAuthenticationHandler : AuthenticationHandler { public const string SchemeName = "Development"; protected override Task HandleAuthenticateAsync() { var userId = context.Request.Headers["X-Dev-User-Id"].ToString(); var userName = context.Request.Headers["X-Dev-User-Name"].ToString(); var userEmail = context.Request.Headers["X-Dev-User-Email"].ToString(); if (string.IsNullOrEmpty(userId)) return Task.FromResult(AuthenticateResult.Fail("Missing X-Dev-User-Id header")); var claims = new List { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.Email, userEmail) }; var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName)); var ticket = new AuthenticationTicket(principal, SchemeName); return Task.FromResult(AuthenticateResult.Success(ticket)); } } ``` -------------------------------- ### Check Tool Deployment Status Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Sends a GET request to check the deployment status of a registered tool. Replace 'weather' with the tool's name. ```http GET http://localhost:8000/tools/weather/status ``` -------------------------------- ### Get New Session Target Async C# Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/service-interfaces.md Select a pod for a new session based on the adapter name and HttpContext. Returns the pod address or null if no pods are ready. A CancellationToken is also required. ```csharp Task GetNewSessionTargetAsync( string adapterName, HttpContext context, CancellationToken cancellationToken = default) ``` -------------------------------- ### Agent and Session Management (Preview) Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md APIs for CRUD operations on agent definitions and sessions, starting sessions, and continuing existing sessions. Available when FoundrySettings:Endpoint is configured. ```APIDOC ## POST /agents, GET /agents, GET|PUT|DELETE /agents/{name} ### Description CRUD operations for agent definitions. ### Method POST, GET, PUT, DELETE ### Endpoint /agents, /agents/{name} ``` ```APIDOC ## POST /sessions, GET /sessions, GET|DELETE /sessions/{id} ### Description CRUD operations for sessions. ### Method POST, GET, DELETE ### Endpoint /sessions, /sessions/{id} ``` ```APIDOC ## POST /sessions/run ### Description Start a session and stream events (SSE). ### Method POST ### Endpoint /sessions/run ``` ```APIDOC ## POST /sessions/{id}/messages ### Description Continue an existing session with a new user message; streams events (SSE). ### Method POST ### Endpoint /sessions/{id}/messages ``` -------------------------------- ### Get Adapter Logs Async Signature Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/service-interfaces.md Signature for fetching container logs from a specific adapter instance. Useful for debugging and monitoring adapter behavior. ```csharp Task GetAdapterLogsAsync( string adapterName, int instanceIndex = 0, CancellationToken cancellationToken = default) ``` -------------------------------- ### Redis Session Store Debugging Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/data-plane-routing.md Commands for interacting with the Redis session store. Use `redis-cli` to connect, `KEYS` to list session mappings, and `GET` to retrieve a specific session. ```bash # Connect to Redis redis-cli # List all session mappings KEYS "mcpgateway:*" # Get a specific session mapping GET "mcpgateway:user1#mcp-example#session-id-123" ``` -------------------------------- ### Launch Bridged Azure Local MCP Server Source: https://github.com/microsoft/mcp-gateway/blob/main/sample-servers/mcp-proxy/README.md Example payload to launch a bridged Azure local MCP server. Configures environment variables for the MCP command and Azure credentials. ```json { "name": "azure-remote", "imageName": "mcp-proxy", "imageVersion": "1.0.0", "environmentVariables": { "MCP_COMMAND": "npx", "MCP_ARGS": "-y @azure/mcp@latest server start", "AZURE_MCP_INCLUDE_PRODUCTION_CREDENTIALS": "true", "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT": "1" }, "description": "Bridged Azure local MCP server" } ``` -------------------------------- ### GET /portal/config Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/types.md Retrieves the runtime configuration for the portal. This includes settings related to development mode, public origin, agent enablement, and Azure AD authentication details. ```APIDOC ## GET /portal/config ### Description Retrieves the runtime configuration for the portal. This includes settings related to development mode, public origin, agent enablement, and Azure AD authentication details. ### Method GET ### Endpoint /portal/config ### Response #### Success Response (200) - **isDevelopment** (boolean) - If true, portal uses dev auth headers instead of MSAL - **publicOrigin** (string) - Base URL for SPA redirects and public links - **agentsEnabled** (boolean) - Whether agent/session features are enabled - **azureAd** (object | null) - Entra ID config (null in dev mode); contains tenantId, clientId, scopes array #### Response Example { "isDevelopment": false, "publicOrigin": "https://example.com", "agentsEnabled": true, "azureAd": { "tenantId": "your-tenant-id", "clientId": "your-client-id", "scopes": ["scope1", "scope2"] } } ``` -------------------------------- ### Launch Bridged Azure AI Foundry MCP Server Source: https://github.com/microsoft/mcp-gateway/blob/main/sample-servers/mcp-proxy/README.md Example payload to launch a bridged Azure AI Foundry MCP server. Uses 'uvx' for the MCP command and enables workload identity. ```json { "name": "foundry-remote", "imageName": "mcp-proxy", "imageVersion": "1.0.0", "environmentVariables": { "MCP_COMMAND": "uvx", "MCP_ARGS": "--prerelease=allow --from git+https://github.com/azure-ai-foundry/mcp-foundry.git run-azure-ai-foundry-mcp" }, "useWorkloadIdentity": true, "description": "Bridged Azure AI Foundry Local MCP Server" } ``` -------------------------------- ### Handle HttpOperationException for Kubernetes API Failures Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/errors.md Catch HttpOperationException to handle failures when interacting with the Kubernetes API. This example specifically checks for a 400 Bad Request status code, which can indicate a pod is still starting. ```csharp catch (HttpOperationException ex) when (ex.Response?.StatusCode == System.Net.HttpStatusCode.BadRequest) { // Kubernetes returns 400 while pod is still starting return Ok($ ``` -------------------------------- ### GET /adapters/{name} — Get Adapter Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieves details for a specific adapter identified by its name. Requires Bearer token authentication. ```APIDOC ## GET /adapters/{name} — Get Adapter ### Description Retrieve a single adapter by name. ### Method GET ### Endpoint /adapters/{name} ### Parameters #### Path Parameters - **name** (string) - Required - Adapter name ### Response #### Success Response (200 OK) Returns a single `AdapterResource` object. #### Error Responses - 401: Missing or invalid Bearer token - 403: User lacks read permission - 404: Adapter not found ``` -------------------------------- ### Build Portal for Production Source: https://github.com/microsoft/mcp-gateway/blob/main/portal/README.md Commands to build the React application for production deployment. The output is placed in a location suitable for serving by the gateway service. ```bash cd portal npm install npm run build ``` -------------------------------- ### Create Adapter using POST /adapters Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Use this endpoint to register and deploy a new MCP server. Ensure you provide all required fields in the request body and include a valid Bearer token for authentication. ```bash curl -X POST http://localhost:8000/adapters \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "mcp-example", "imageName": "mcp-example", "imageVersion": "1.0.0", "description": "Example MCP server", "replicaCount": 2 }' ``` -------------------------------- ### Create Tool with Definition Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Register and deploy a tool with MCP tool definition metadata. The request body extends AdapterData with tool-specific details like input schema and execution path. ```json { "name": "weather", "imageName": "weather-tool", "imageVersion": "1.0.0", "description": "Weather lookup tool", "toolDefinition": { "tool": { "name": "weather", "description": "Gets current weather for a location", "inputSchema": { "type": "object", "properties": { "location": { "type": "string", "description": "City, State" } }, "required": ["location"] } }, "port": 8000, "path": "/score" }, "requiredRoles": [] } ``` -------------------------------- ### GET /adapters/{name}/status — Get Adapter Status Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Fetches the current Kubernetes deployment status for a specified adapter, including replica counts and image information. Requires Bearer token authentication. ```APIDOC ## GET /adapters/{name}/status — Get Adapter Status ### Description Retrieve the Kubernetes deployment status (replicas, image, pod health). ### Method GET ### Endpoint /adapters/{name}/status ### Parameters #### Path Parameters - **name** (string) - Required - Adapter name ### Response #### Success Response (200 OK) Returns the adapter's status information. ```json { "readyReplicas": 2, "updatedReplicas": 2, "availableReplicas": 2, "image": "localhost:5000/mcp-example:1.0.0", "replicaStatus": "Ready" } ``` #### Error Responses - 401: Missing or invalid Bearer token - 403: User lacks read permission - 404: Adapter not found ``` -------------------------------- ### Deploy Adapter Async C# Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/service-interfaces.md Use this method to deploy a new adapter to Kubernetes. Ensure an AdapterResource object and a CancellationToken are provided. ```csharp Task DeployAdapterAsync( AdapterResource adapter, CancellationToken cancellationToken = default) ``` -------------------------------- ### Get Agent Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve a specific agent by its name. ```APIDOC ## GET /agents/{name} — Get Agent ### Description Retrieve a single agent by name. ### Method GET ### Endpoint /agents/{name} ``` -------------------------------- ### Build and Push Tool Server Image Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Builds and pushes a tool server Docker image to the local registry. Replace '1.0.0' with the desired version. ```sh docker build -f sample-servers/tool-example/Dockerfile sample-servers/tool-example -t localhost:5000/weather-tool:1.0.0 docker push localhost:5000/weather-tool:1.0.0 ``` -------------------------------- ### Get Tool Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve a single tool by its name. ```APIDOC ## GET /tools/{name} — Get Tool ### Description Retrieve a single tool by name. ### Method GET ### Endpoint /tools/{name} ### Parameters #### Path Parameters - **name** (string) - Required - Tool name ### Response #### Success Response (200 OK) Single `ToolResource` object with tool definition. ``` -------------------------------- ### Get Adapter Status using GET /adapters/{name}/status Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Fetch the Kubernetes deployment status for a specific adapter, including replica counts, image information, and pod health. Requires a valid Bearer token and the adapter's name. ```json { "readyReplicas": 2, "updatedReplicas": 2, "availableReplicas": 2, "image": "localhost:5000/mcp-example:1.0.0", "replicaStatus": "Ready" } ``` -------------------------------- ### Configuration Structure Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/configuration.md Overview of the top-level configuration sections available in appsettings.json. ```json { "Authentication": { ... }, "AzureAd": { ... }, "PublicOrigin": "...", "CosmosSettings": { ... }, "Redis": { ... }, "Storage": { ... }, "ContainerRegistrySettings": { ... }, "FoundrySettings": { ... }, "BuiltinToolSettings": { ... } } ``` -------------------------------- ### Get Tool Status Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve the deployment status of a tool. ```APIDOC ## GET /tools/{name}/status — Get Tool Status ### Description Retrieve tool deployment status (same structure as adapters). ### Method GET ### Endpoint /tools/{name}/status ### Parameters #### Path Parameters - **name** (string) - Required - Tool name ``` -------------------------------- ### Create Adapter and Access MCP Server Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/README.md Use this sequence of cURL commands to create a new adapter, wait for it to become ready, and then send MCP JSON-RPC requests to its server. Ensure you replace $TOKEN with your actual authentication token. ```bash # Create curl -X POST http://localhost:8000/adapters \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"my-server","imageName":"my-image","imageVersion":"1.0"}' ``` ```bash # Wait for ready curl http://localhost:8000/adapters/my-server/status \ -H "Authorization: Bearer $TOKEN" ``` ```bash # Use curl -X POST http://localhost:8000/adapters/my-server/mcp \ -H "Authorization: Bearer $TOKEN" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{...}}' ``` -------------------------------- ### IAdapterManagementService.CreateAsync Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/service-interfaces.md Creates and deploys a new adapter. It takes the authenticated user, adapter configuration, and a cancellation token as input, returning the created adapter resource. ```APIDOC ## CreateAsync ### Description Create and deploy a new adapter. ### Method Task ### Parameters #### Path Parameters - user (ClaimsPrincipal) - Required - Authenticated user context - request (AdapterData) - Required - Adapter configuration - cancellationToken (CancellationToken) - Optional - Cancellation token ### Response #### Success Response - AdapterResource - Created adapter with metadata ### Throws - ArgumentException - Invalid name format, duplicate name, or malformed request - UnauthorizedAccessException - User lacks write permission ``` -------------------------------- ### Get Agent Request Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve a specific agent by its name. Authorization is required. ```http GET /agents/{name} Authorization: Bearer {token} ``` -------------------------------- ### Get Tool Logs Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve container logs from a specific instance of a tool pod. ```APIDOC ## GET /tools/{name}/logs — Get Tool Logs ### Description Retrieve container logs from a tool pod instance. ### Method GET ### Endpoint /tools/{name}/logs ### Parameters #### Path Parameters - **name** (string) - Required - Tool name #### Query Parameters - **instance** (string) - Optional - The instance number of the tool pod (e.g., 0) ``` -------------------------------- ### Run an Agent Session Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Initiate a new session with an agent using `POST /sessions/run`. The response is a Server-Sent Events stream detailing the session's progress. Ensure `Accept` header is set to `text/event-stream`. ```http POST /sessions/run Authorization: Bearer Content-Type: application/json Accept: text/event-stream ``` ```json { "agentName": "weather-helper", "input": "What's the weather in Seattle?" } ``` -------------------------------- ### Get Session Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieves a single session by its unique ID, including its full message history. ```APIDOC ## GET /sessions/{id} — Get Session ### Description Retrieve a single session by ID. ### Method GET ### Endpoint /sessions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Session ID (format: `sess-`) ### Response #### Success Response (200 OK) Single `SessionResource` object with full message history. ``` -------------------------------- ### Get Tool Status Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve the deployment status of a specific tool by its name. The status structure is identical to that of adapters. ```http GET /tools/{name}/status Authorization: Bearer {token} ``` -------------------------------- ### Get Current User Information Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/authentication-authorization.md Fetch details about the currently logged-in user, including their name, for role verification. ```bash az account show | jq .user.name ``` -------------------------------- ### Create an adapter and access its MCP server Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/README.md This operation involves creating a new adapter, waiting for it to become ready, and then interacting with its MCP server via JSON-RPC. ```APIDOC ## Create Adapter ### Description Creates a new adapter with the specified image and configuration. ### Method POST ### Endpoint /adapters ### Parameters #### Request Body - **name** (string) - Required - The name of the adapter. - **imageName** (string) - Required - The name of the Docker image for the adapter. - **imageVersion** (string) - Required - The version of the Docker image. ### Request Example ```bash curl -X POST http://localhost:8000/adapters \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"name":"my-server","imageName":"my-image","imageVersion":"1.0"}' ``` ## Get Adapter Status ### Description Checks the status of a specific adapter. ### Method GET ### Endpoint /adapters/{name}/status ### Parameters #### Path Parameters - **name** (string) - Required - The name of the adapter. ### Request Example ```bash curl http://localhost:8000/adapters/my-server/status \ -H "Authorization: Bearer $TOKEN" ``` ## Interact with Adapter MCP Server ### Description Sends a JSON-RPC request to the adapter's MCP server. ### Method POST ### Endpoint /adapters/{name}/mcp ### Parameters #### Path Parameters - **name** (string) - Required - The name of the adapter. #### Request Body - **jsonrpc** (string) - Required - The JSON-RPC version. - **id** (integer) - Required - The request ID. - **method** (string) - Required - The method to call. - **params** (object) - Optional - Parameters for the method. ### Request Example ```bash curl -X POST http://localhost:8000/adapters/my-server/mcp \ -H "Authorization: Bearer $TOKEN" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{...}}' ``` ``` -------------------------------- ### Deploy an MCP Server (Adapter) Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/README.md Deploys a new MCP server (adapter) to the system. It returns an AdapterResource object detailing the deployment status. ```APIDOC ## POST /adapters ### Description Deploys a new MCP server (adapter). ### Method POST ### Endpoint /adapters ### Request Body - **name** (string) - Required - The name of the adapter. - **imageName** (string) - Required - The name of the Docker image to use. - **imageVersion** (string) - Required - The version of the Docker image. - **replicaCount** (integer) - Required - The number of replicas to deploy. ### Request Example ```json { "name": "mcp-example", "imageName": "mcp-example", "imageVersion": "1.0.0", "replicaCount": 2 } ``` ### Response #### Success Response (200) Returns `AdapterResource` with deployment status. ``` -------------------------------- ### Get Single Tool by Name Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve details for a specific tool, including its definition, by providing its name. Requires authentication. ```http GET /tools/{name} Authorization: Bearer {token} ``` -------------------------------- ### Run Session Request (Streaming) Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Initiate a session and stream its results in real-time using Server-Sent Events. Ensure the 'Accept' header is set to 'text/event-stream'. ```http POST /sessions/run Authorization: Bearer {token} Content-Type: application/json Accept: text/event-stream ``` -------------------------------- ### Create Tool Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Register and deploy a tool with MCP tool definition metadata. ```APIDOC ## POST /tools — Create Tool ### Description Register and deploy a tool with MCP tool definition. ### Method POST ### Endpoint /tools ### Request Body (`ToolData`) Extends `AdapterData` with: | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | toolDefinition | ToolDefinition | Yes | MCP tool metadata (name, description, input schema, execution endpoint) | ### Request Example ```json { "name": "weather", "imageName": "weather-tool", "imageVersion": "1.0.0", "description": "Weather lookup tool", "toolDefinition": { "tool": { "name": "weather", "description": "Gets current weather for a location", "inputSchema": { "type": "object", "properties": { "location": { "type": "string", "description": "City, State" } }, "required": ["location"] } }, "port": 8000, "path": "/score" }, "requiredRoles": [] } ``` ### Response #### Success Response (201 Created) Returns the created `ToolResource`. ``` -------------------------------- ### Obtain Bearer Token with Node.js/JavaScript Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/authentication-authorization.md Use the @azure/identity library to obtain a token for the specified API client ID. This example uses DefaultAzureCredential. ```javascript import { DefaultAzureCredential } from "@azure/identity"; const credential = new DefaultAzureCredential(); const token = await credential.getToken(`api://{API_CLIENT_ID}/.default`); console.log(token.token); ``` -------------------------------- ### Deploy MCP Server (Adapter) Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/README.md Use this endpoint to deploy a new MCP server, specifying its name, image, version, and replica count. Returns an AdapterResource with deployment status. ```http POST /adapters Authorization: Bearer {token} Content-Type: application/json { "name": "mcp-example", "imageName": "mcp-example", "imageVersion": "1.0.0", "replicaCount": 2 } ``` -------------------------------- ### Configure Azure Cosmos DB Environment Variables Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/configuration.md Set up cloud storage for adapters, tools, agents, and sessions in production mode using environment variables. Requires the account endpoint and database name. ```bash CosmosSettings__AccountEndpoint=https://mcpgateway-db.documents.azure.com:443/ CosmosSettings__DatabaseName=mcpgateway ``` -------------------------------- ### Create an agent and run a session Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/README.md This operation involves defining an agent and then initiating a session with it, which can be streamed. ```APIDOC ## Create Agent ### Description Defines a new agent with the specified model, system prompt, and tools. ### Method POST ### Endpoint /agents ### Parameters #### Request Body - **name** (string) - Required - The name of the agent. - **model** (string) - Required - The model to use for the agent. - **system** (string) - Required - The system prompt for the agent. - **tools** (array) - Optional - A list of tools the agent can use. ### Request Example ```bash curl -X POST http://localhost:8000/agents \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name":"my-agent", "model":"gpt-4o", "system":"You help users.", "tools":["mcp:my-tool"] }' ``` ## Run Session ### Description Initiates a new session with a specified agent and provides input. Supports streaming responses. ### Method POST ### Endpoint /sessions/run ### Parameters #### Request Body - **agentName** (string) - Required - The name of the agent to run the session with. - **input** (string) - Required - The input for the session. ### Request Example ```bash curl -X POST http://localhost:8000/sessions/run \ -H "Authorization: Bearer $TOKEN" \ -H "Accept: text/event-stream" \ -d '{ "agentName":"my-agent", "input":"Hello!" }' ``` ``` -------------------------------- ### Health Check Endpoint Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md A simple GET request to `/ping` to verify the health status of the gateway. Expects a plain text 'Pong' response. ```http GET /ping ``` ```text Pong ``` -------------------------------- ### Get Tool Logs Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Retrieve container logs from a specific instance of a tool pod. The instance can be specified using the `instance` query parameter. ```http GET /tools/{name}/logs?instance=0 Authorization: Bearer {token} ``` -------------------------------- ### POST /adapters — Create Adapter Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Registers and deploys a new MCP server (adapter) by providing its configuration details. Requires Bearer token authentication. ```APIDOC ## POST /adapters — Create Adapter ### Description Registers and deploys a new MCP server. ### Method POST ### Endpoint /adapters ### Parameters #### Request Body - **name** (string) - Required - Adapter name; lowercase alphanumeric and dashes only. Must be unique. - **imageName** (string) - Required - Container image path (e.g., `mcp-example`). - **imageVersion** (string) - Required - Image tag (e.g., `1.0.0`). - **description** (string) - Optional - Human-readable description. - **replicaCount** (integer) - Optional - Number of pod replicas to deploy (≥1). - **environmentVariables** (object) - Optional - Key-value pairs of environment variables passed to the container. - **useWorkloadIdentity** (boolean) - Optional - Use Workload Identity for credential-less Kubernetes auth. - **requiredRoles** (array[string]) - Optional - List of Entra ID roles (e.g., `["mcp.engineer"]`) that grant read access. Creator and `mcp.admin` always have access. ### Request Example ```bash curl -X POST http://localhost:8000/adapters \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d { "name": "mcp-example", "imageName": "mcp-example", "imageVersion": "1.0.0", "description": "Example MCP server", "replicaCount": 2 } ``` ### Response #### Success Response (201 Created) Returns the created `AdapterResource` with auto-populated metadata: `id`, `createdBy`, `createdAt`, `lastUpdatedAt`. #### Error Responses - 400: Name/image validation failed; duplicate name; invalid image format - 401: Missing or invalid Bearer token - 403: Insufficient permissions ``` -------------------------------- ### Check Required Roles for Adapter Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/authentication-authorization.md Inspect the required roles for an adapter to understand access control. Compare this with your assigned roles. ```bash GET /adapters/my-adapter | jq .requiredRoles ``` -------------------------------- ### Acquire Bearer Token Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Use this command to obtain a bearer token for authenticating API requests. Ensure you have the Azure CLI installed and are logged in. ```sh az account get-access-token --resource $clientId ``` -------------------------------- ### Build and Push MCP Server Image Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Builds the MCP server Docker image and pushes it to the local Docker registry. Replace '1.0.0' with the desired version. ```sh docker build -f sample-servers/mcp-example/Dockerfile sample-servers/mcp-example -t localhost:5000/mcp-example:1.0.0 docker push localhost:5000/mcp-example:1.0.0 ``` -------------------------------- ### Deploy MCP Gateway with Bicep (Basic) Source: https://github.com/microsoft/mcp-gateway/blob/main/deployment/infra/README.md Deploy the MCP Gateway using Bicep directly with the Azure CLI. Requires the `azure-deployment.bicep` file and an Entra ID client ID. ```bash az deployment group create \ --name mcpgateway-deployment \ --resource-group rg-mcpgateway-dev \ --template-file azure-deployment.bicep \ --parameters clientId= ``` -------------------------------- ### Run an Agent Session (Streaming) Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/README.md Initiates a session to run an agent, providing input and receiving responses as a stream of Server-Sent Events. This allows for real-time interaction. ```APIDOC ## POST /sessions/run ### Description Runs an agent session and streams the response. ### Method POST ### Endpoint /sessions/run ### Headers - **Accept**: `text/event-stream` ### Request Body - **agentName** (string) - Required - The name of the agent to run. - **input** (string) - Required - The input query for the agent. ### Response #### Success Response Server-Sent Events stream with events like `Started`, `ToolCallStarted`, `ToolCallCompleted`, `TokenDelta`, `Completed`. ``` -------------------------------- ### IToolResourceStore Methods Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/service-interfaces.md Methods for the IToolResourceStore interface, mirroring IAdapterResourceStore but for tool metadata. Supports retrieval, listing, upserting, and deletion of tool resources. ```csharp Task TryGetAsync(string name, CancellationToken) ``` ```csharp Task> ListAsync(CancellationToken) ``` ```csharp Task UpsertAsync(ToolResource resource, CancellationToken) ``` ```csharp Task DeleteAsync(string name, CancellationToken) ``` -------------------------------- ### Kubernetes ConfigMap for Non-Sensitive Settings Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/configuration.md Use a Kubernetes ConfigMap to manage non-sensitive configuration settings. This example shows how to set Authentication, PublicOrigin, ContainerRegistrySettings, and FoundrySettings. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: mcpgateway-config data: Authentication__BypassEntra: "false" PublicOrigin: "https://mcpgateway.contoso.com" ContainerRegistrySettings__Endpoint: "myregistry.azurecr.io" FoundrySettings__Endpoint: "https://myai.openai.azure.com/" FoundrySettings__DeploymentName: "gpt-4o" ``` -------------------------------- ### Run Session (Streaming) Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Creates and immediately executes a session, streaming results over Server-Sent Events. This is useful for real-time agent interaction. ```APIDOC ## POST /sessions/run — Run Session (Streaming) ### Description Create and immediately execute a session, streaming results over Server-Sent Events. ### Method POST ### Endpoint /sessions/run ### Parameters #### Request Body - **agentName** (string) - Required - Name of the agent to execute - **input** (string) - Required - Initial user prompt/task - **title** (string) - Optional - Optional human-readable title - **requiredRoles** (array[string]) - Optional - Entra ID roles granting read access ### Response #### Success Response (200 OK) Server-Sent Events stream with content-type `text/event-stream`. Each event has the format: ``` event: {EventType} data: {JSON payload} ``` **Event Types** - `Started`: Agent run has begun. - `ToolCallStarted`: Model invoked a tool. - `ToolCallCompleted`: Tool returned a result. - `TokenDelta`: Incremental assistant text chunk. - `Completed`: Run completed with final answer. - `Failed`: Run failed with error message. - `error`: Stream initialization error. ``` -------------------------------- ### HTTP 503 Service Unavailable Response Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/data-plane-routing.md This is an example of a 503 Service Unavailable response when no healthy pods are available for an adapter. It includes details about the error condition. ```http HTTP/1.1 503 Service Unavailable Content-Type: application/problem+json { "type": "https://tools.ietf.org/html/rfc7231#section-6.6.3", "title": "Service Unavailable", "status": 503, "detail": "No healthy replicas available for this adapter" } ``` -------------------------------- ### Register a Tool Server Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Send a POST request to register a tool with its definition. This includes the tool's name, image details, and a schema for its input. ```http POST http://..cloudapp.azure.com/tools Authorization: Bearer Content-Type: application/json ``` ```json { "name": "weather", "imageName": "weather-tool", "imageVersion": "1.0.0", "useWorkloadIdentity": true, "description": "Weather tool for getting current weather information", "requiredRoles": [], // Only creator and mcp.admin can access. Add roles (e.g. ["mcp.engineer"]) to grant read access to other principals. "toolDefinition": { "tool": { "name": "weather", "title": "Weather Information", "description": "Gets the current weather for a specified location.", "type": "http", "inputSchema": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" } }, "required": ["location"] }, "annotations": { "readOnly": true } }, "port": 8000 } } ``` -------------------------------- ### Build and Publish Tool Server Image Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Builds a tool server image using Azure Container Registry (ACR) and tags it for deployment. ```sh az acr build -r "mgreg$resourceLabel" -f sample-servers/tool-example/Dockerfile sample-servers/tool-example -t "mgreg$resourceLabel.azurecr.io/weather-tool:1.0.0" ``` -------------------------------- ### Get Session Request Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/endpoints.md Fetch a specific session's details, including its complete message history, using its unique ID. The ID is a path parameter. ```http GET /sessions/{id} Authorization: Bearer {token} ``` -------------------------------- ### Obtain Bearer Token with Azure CLI Source: https://github.com/microsoft/mcp-gateway/blob/main/_autodocs/api-reference/authentication-authorization.md Use the Azure CLI to get an access token for a specified resource. Ensure you have the correct API client ID. ```bash az account get-access-token --resource {API_CLIENT_ID} ``` -------------------------------- ### Configure VS Code for MCP Server Connection Source: https://github.com/microsoft/mcp-gateway/blob/main/README.md Sample `.vscode/mcp.json` configuration to connect VS Code to a deployed MCP server. Authentication is handled by VS Code. ```json { "servers": { "mcp-example": { "url": "http://..cloudapp.azure.com/adapters/mcp-example/mcp" } } } ```