Skip to content

Commit fba075a

Browse files
Copilotsouvikghosh04Copilot
authored
Add MCP probe to comprehensive health endpoint (#3685)
## Why make this change? - Closes #2843 - The comprehensive `/health` report advertised whether MCP was enabled in its `configuration` block but never actually probed the MCP endpoint, so MCP outages were invisible to health monitoring. ## What is this change? - **`HealthCheckHelper`** — New `UpdateMcpHealthCheckResultsAsync`, wired into `UpdateHealthCheckDetailsAsync` alongside the data-source/entity/embeddings checks. Runs only when `IsMcpEnabled`; emits a `HealthCheckResultEntry` named `mcp`, tagged `["mcp"]`, comparing response time against the default 1000 ms threshold. - **`HttpUtilities.ExecuteMcpQueryAsync`** — POSTs a JSON-RPC `initialize` request to `runtimeConfig.McpPath` with `Accept: application/json, text/event-stream`, reusing the existing `CheckSanityOfUrl` SSRF guard and role-header propagation. `initialize` is used because `tools/list` requires an active session under the Streamable HTTP transport. - **`Utilities.CreateHttpMcpQuery`** — Builds the minimal initialize payload. - **`HealthCheckConstants`** — Adds the `mcp` tag. Single `mcp` tag (mirroring the data-source check's single `data-source` tag) rather than reusing `endpoint`, which is reserved for per-entity REST/GraphQL checks. The check is gated solely on `IsMcpEnabled` with a default threshold — no new config surface. ## How was this tested? - [x] Integration Tests — extended `ComprehensiveHealthEndpoint_ValidateContents` to assert the `mcp` tag appears iff MCP is enabled. - [x] Unit Tests — `TestHealthCheckMcpResponseAsync` / `TestFailureHealthCheckMcpResponseAsync` cover success and non-2xx responses. ## Sample Request(s) ```http GET /health ``` Resulting check entry when MCP is enabled: ```json { "name": "mcp", "status": "Healthy", "tags": ["mcp"], "data": { "duration-ms": 12, "threshold-ms": 1000 } } ``` --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Souvik Ghosh <souvikofficial04@gmail.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
1 parent b2cf224 commit fba075a

6 files changed

Lines changed: 239 additions & 1 deletion

File tree

‎src/Config/HealthCheck/HealthCheckConstants.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public static class HealthCheckConstants
1212
public const string DATASOURCE = "data-source";
1313
public const string REST = "rest";
1414
public const string GRAPHQL = "graphql";
15+
public const string MCP = "mcp";
1516
public const string EMBEDDING = "embedding";
1617
public const int ERROR_RESPONSE_TIME_MS = -1;
1718
public const int DEFAULT_THRESHOLD_RESPONSE_TIME_MS = 1000;

‎src/Service.Tests/Configuration/HealthEndpointTests.cs‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ public async Task ComprehensiveHealthEndpoint_ValidateContents(
110110
ValidateConfigurationDetailsHealthCheckResponse(responseProperties, enableGlobalRest, enableGlobalGraphql, enableGlobalMcp);
111111
ValidateIfAttributePresentInResponse(responseProperties, enableDatasourceHealth, HealthCheckConstants.DATASOURCE);
112112
ValidateIfAttributePresentInResponse(responseProperties, enableEntityHealth, HealthCheckConstants.ENDPOINT);
113+
ValidateIfAttributePresentInResponse(responseProperties, enableGlobalMcp, HealthCheckConstants.MCP);
113114
if (enableEntityHealth)
114115
{
115116
ValidateEntityRestAndGraphQLResponse(responseProperties, enableEntityRest, enableEntityGraphQL, enableGlobalRest, enableGlobalGraphql);
@@ -223,6 +224,52 @@ public async Task TestFailureHealthCheckGraphQLResponseAsync()
223224
Assert.IsNotNull(errorMessageFromGraphQL);
224225
}
225226

227+
/// <summary>
228+
/// Simulates the function call to HttpUtilities.ExecuteMcpQueryAsync.
229+
/// while setting up mock HTTP client to simulate the response from the server to send OK code.
230+
/// Validates the response to ensure no error message is received.
231+
/// </summary>
232+
[TestMethod]
233+
public async Task TestHealthCheckMcpResponseAsync()
234+
{
235+
// Arrange
236+
RuntimeConfig runtimeConfig = SetupCustomConfigFile(true, true, true, true, true, true, true, true);
237+
HttpUtilities httpUtilities = SetupMcpTest(runtimeConfig);
238+
239+
// Act
240+
// Simulate an MCP initialize POST request to the endpoint.
241+
// Response should be null as error message is not expected to be returned.
242+
string errorMessageFromMcp = await httpUtilities.ExecuteMcpQueryAsync(
243+
mcpUriSuffix: runtimeConfig.McpPath,
244+
incomingRoleHeader: string.Empty,
245+
incomingRoleToken: string.Empty);
246+
247+
// Assert
248+
Assert.IsNull(errorMessageFromMcp);
249+
}
250+
251+
/// <summary>
252+
/// Simulates the function call to HttpUtilities.ExecuteMcpQueryAsync.
253+
/// while setting up mock HTTP client to simulate the response from the server to send InternalServerError code.
254+
/// Validates the response to ensure error message is received.
255+
/// </summary>
256+
[TestMethod]
257+
public async Task TestFailureHealthCheckMcpResponseAsync()
258+
{
259+
// Arrange
260+
RuntimeConfig runtimeConfig = SetupCustomConfigFile(true, true, true, true, true, true, true, true);
261+
HttpUtilities httpUtilities = SetupMcpTest(runtimeConfig, HttpStatusCode.InternalServerError);
262+
263+
// Act
264+
string errorMessageFromMcp = await httpUtilities.ExecuteMcpQueryAsync(
265+
mcpUriSuffix: runtimeConfig.McpPath,
266+
incomingRoleHeader: string.Empty,
267+
incomingRoleToken: string.Empty);
268+
269+
// Assert
270+
Assert.IsNotNull(errorMessageFromMcp);
271+
}
272+
226273
/// <summary>
227274
/// Tests the serialization behavior of <see cref="RuntimeHealthCheckConfig"/> for the <see cref="RuntimeHealthCheckConfig.MaxQueryParallelism"/> property."
228275
/// </summary>
@@ -366,6 +413,51 @@ private static HttpUtilities SetupGraphQLTest(RuntimeConfig runtimeConfig, HttpS
366413
mockHttpClientFactory.Object);
367414
}
368415

416+
private static HttpUtilities SetupMcpTest(RuntimeConfig runtimeConfig, HttpStatusCode httpStatusCode = HttpStatusCode.OK)
417+
{
418+
// Arrange
419+
// Create a mock entity map with a single entity for testing and load in RuntimeConfigProvider
420+
MockFileSystem fileSystem = new();
421+
fileSystem.AddFile(FileSystemRuntimeConfigLoader.DEFAULT_CONFIG_FILE_NAME, new MockFileData(runtimeConfig.ToJson()));
422+
FileSystemRuntimeConfigLoader loader = new(fileSystem);
423+
RuntimeConfigProvider provider = new(loader);
424+
Mock<IMetadataProviderFactory> metadataProviderFactory = new();
425+
string expectedMcpPayload = Azure.DataApiBuilder.Service.HealthCheck.Utilities.CreateHttpMcpQuery();
426+
427+
// Mock the handler to return the supplied status code for the MCP initialize POST request.
428+
Mock<HttpMessageHandler> mockHandler = new();
429+
mockHandler.Protected()
430+
.Setup<Task<HttpResponseMessage>>(
431+
"SendAsync",
432+
ItExpr.Is<HttpRequestMessage>(req =>
433+
req.Method == HttpMethod.Post &&
434+
req.RequestUri == new Uri($"{BASE_DAB_URL}{runtimeConfig.McpPath}") &&
435+
req.Content != null &&
436+
req.Content.ReadAsStringAsync().Result.Equals(expectedMcpPayload) &&
437+
req.Headers.Accept.Any(v => v.MediaType == "application/json") &&
438+
req.Headers.Accept.Any(v => v.MediaType == "text/event-stream")),
439+
ItExpr.IsAny<CancellationToken>())
440+
.ReturnsAsync(new HttpResponseMessage(httpStatusCode)
441+
{
442+
Content = new StringContent("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}")
443+
});
444+
445+
Mock<IHttpClientFactory> mockHttpClientFactory = new();
446+
mockHttpClientFactory.Setup(x => x.CreateClient("ContextConfiguredHealthCheckClient"))
447+
.Returns(new HttpClient(mockHandler.Object)
448+
{
449+
BaseAddress = new Uri($"{BASE_DAB_URL}")
450+
});
451+
452+
Mock<ILogger<HttpUtilities>> logger = new();
453+
454+
return new(
455+
logger.Object,
456+
metadataProviderFactory.Object,
457+
provider,
458+
mockHttpClientFactory.Object);
459+
}
460+
369461
private static void ValidateEntityRestAndGraphQLResponse(
370462
Dictionary<string, JsonElement> responseProperties,
371463
bool enableEntityRest,

‎src/Service.Tests/UnitTests/EmbeddingsHealthCheckTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -622,7 +622,7 @@ private static RuntimeConfig CreateRuntimeConfig(
622622
RuntimeOptions runtimeOptions = new(
623623
Rest: new RestRuntimeOptions(Enabled: true),
624624
GraphQL: new GraphQLRuntimeOptions(Enabled: true),
625-
Mcp: new McpRuntimeOptions(Enabled: true),
625+
Mcp: new McpRuntimeOptions(Enabled: false),
626626
Host: new HostOptions(Cors: null, Authentication: null, Mode: HostMode.Development),
627627
Health: new RuntimeHealthCheckConfig(enabled: true),
628628
Embeddings: embeddingsOptions);

‎src/Service/HealthCheck/HealthCheckHelper.cs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ private async Task UpdateHealthCheckDetailsAsync(ComprehensiveHealthCheckReport
169169
comprehensiveHealthCheckReport.Checks = new List<HealthCheckResultEntry>();
170170
await UpdateDataSourceHealthCheckResultsAsync(comprehensiveHealthCheckReport, runtimeConfig);
171171
await UpdateEntityHealthCheckResultsAsync(comprehensiveHealthCheckReport, runtimeConfig, roleHeader, roleToken);
172+
await UpdateMcpHealthCheckResultsAsync(comprehensiveHealthCheckReport, runtimeConfig, roleHeader, roleToken);
172173
await UpdateEmbeddingsHealthCheckResultsAsync(comprehensiveHealthCheckReport, runtimeConfig);
173174
}
174175

@@ -213,6 +214,51 @@ private async Task UpdateDataSourceHealthCheckResultsAsync(ComprehensiveHealthCh
213214
return (HealthCheckConstants.ERROR_RESPONSE_TIME_MS, errorMessage);
214215
}
215216

217+
// Updates the MCP Health Check Result in the response.
218+
// The check verifies that the MCP endpoint is reachable and responds within the threshold.
219+
// It runs only when MCP is enabled in the runtime configuration.
220+
private async Task UpdateMcpHealthCheckResultsAsync(ComprehensiveHealthCheckReport comprehensiveHealthCheckReport, RuntimeConfig runtimeConfig, string roleHeader, string roleToken)
221+
{
222+
if (comprehensiveHealthCheckReport.Checks is null || !runtimeConfig.IsMcpEnabled)
223+
{
224+
return;
225+
}
226+
227+
(int, string?) response = await ExecuteMcpQueryAsync(runtimeConfig.McpPath, roleHeader, roleToken);
228+
bool isResponseTimeWithinThreshold = response.Item1 >= 0 && response.Item1 < HealthCheckConstants.DEFAULT_THRESHOLD_RESPONSE_TIME_MS;
229+
230+
comprehensiveHealthCheckReport.Checks.Add(new HealthCheckResultEntry
231+
{
232+
Name = HealthCheckConstants.MCP,
233+
ResponseTimeData = new ResponseTimeData
234+
{
235+
ResponseTimeMs = response.Item1,
236+
ThresholdMs = HealthCheckConstants.DEFAULT_THRESHOLD_RESPONSE_TIME_MS
237+
},
238+
Tags = [HealthCheckConstants.MCP],
239+
Exception = response.Item2 ?? (!isResponseTimeWithinThreshold ? TIME_EXCEEDED_ERROR_MESSAGE : null),
240+
Status = isResponseTimeWithinThreshold ? HealthStatus.Healthy : HealthStatus.Unhealthy
241+
});
242+
}
243+
244+
// Executes the MCP Query and keeps track of the response time and error message.
245+
private async Task<(int, string?)> ExecuteMcpQueryAsync(string mcpUriSuffix, string roleHeader, string roleToken)
246+
{
247+
if (string.IsNullOrEmpty(mcpUriSuffix))
248+
{
249+
return (HealthCheckConstants.ERROR_RESPONSE_TIME_MS, "MCP is enabled but no MCP path is configured.");
250+
}
251+
252+
Stopwatch stopwatch = new();
253+
stopwatch.Start();
254+
string? errorMessage = await _httpUtility.ExecuteMcpQueryAsync(mcpUriSuffix, roleHeader, roleToken);
255+
stopwatch.Stop();
256+
257+
return string.IsNullOrEmpty(errorMessage)
258+
? ((int)stopwatch.ElapsedMilliseconds, errorMessage)
259+
: (HealthCheckConstants.ERROR_RESPONSE_TIME_MS, errorMessage);
260+
}
261+
216262
// Updates the Entity Health Check Results in the response.
217263
// Goes through the entities one by one and executes the rest and graphql checks (if enabled).
218264
// Stored procedures are excluded from health checks because they require parameters and are not guaranteed to be deterministic.

‎src/Service/HealthCheck/HttpUtilities.cs‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,82 @@ public HttpUtilities(
136136
}
137137
}
138138

139+
// Executes the MCP query by sending an initialize JSON-RPC POST request to the MCP endpoint.
140+
public async Task<string?> ExecuteMcpQueryAsync(string mcpUriSuffix, string incomingRoleHeader, string incomingRoleToken)
141+
{
142+
string? errorMessage = null;
143+
try
144+
{
145+
if (string.IsNullOrWhiteSpace(mcpUriSuffix))
146+
{
147+
const string msg = "MCP path is not configured.";
148+
_logger.LogError(msg);
149+
return msg;
150+
}
151+
152+
if (_httpClient.BaseAddress is null)
153+
{
154+
const string msg = "Health check HTTP client BaseAddress is not configured.";
155+
_logger.LogError(msg);
156+
return msg;
157+
}
158+
159+
// Ensure the configured MCP path cannot override the host (e.g. absolute URIs).
160+
if (!Uri.TryCreate(mcpUriSuffix, UriKind.Relative, out _))
161+
{
162+
_logger.LogError("Blocked outbound request due to invalid or unsafe URI.");
163+
return "Blocked outbound request due to invalid or unsafe URI.";
164+
}
165+
166+
Uri requestUri = new(_httpClient.BaseAddress, mcpUriSuffix);
167+
168+
if (!Program.CheckSanityOfUrl(requestUri.AbsoluteUri))
169+
{
170+
_logger.LogError("Blocked outbound request due to invalid or unsafe URI.");
171+
return "Blocked outbound request due to invalid or unsafe URI.";
172+
}
173+
174+
string jsonPayload = Utilities.CreateHttpMcpQuery();
175+
HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, Utilities.JSON_CONTENT_TYPE);
176+
177+
HttpRequestMessage message = new(method: HttpMethod.Post, requestUri: requestUri)
178+
{
179+
Content = content
180+
};
181+
182+
// The MCP Streamable HTTP transport requires the client to accept both
183+
// JSON and SSE responses.
184+
message.Headers.Add("Accept", "application/json, text/event-stream");
185+
186+
if (!string.IsNullOrEmpty(incomingRoleToken))
187+
{
188+
message.Headers.Add(AuthenticationOptions.CLIENT_PRINCIPAL_HEADER, incomingRoleToken);
189+
}
190+
191+
if (!string.IsNullOrEmpty(incomingRoleHeader))
192+
{
193+
message.Headers.Add(AuthorizationResolver.CLIENT_ROLE_HEADER, incomingRoleHeader);
194+
}
195+
196+
HttpResponseMessage response = await _httpClient.SendAsync(message);
197+
if (response.IsSuccessStatusCode)
198+
{
199+
_logger.LogTrace($"The MCP HealthEndpoint query executed successfully with code {response.StatusCode}.");
200+
}
201+
else
202+
{
203+
errorMessage = $"The MCP HealthEndpoint query failed with code: {response.StatusCode}.";
204+
}
205+
206+
return errorMessage;
207+
}
208+
catch (Exception ex)
209+
{
210+
_logger.LogError($"An exception occurred while executing the health check MCP query: {ex.Message}");
211+
return ex.Message;
212+
}
213+
}
214+
139215
// Executes the GraphQL query by sending a POST request to the API.
140216
// Internally calls the metadata provider to fetch the column names to create the graphql payload.
141217
public async Task<string?> ExecuteGraphQLQueryAsync(string graphqlUriSuffix, string entityName, Entity entity, string incomingRoleHeader, string incomingRoleToken)

‎src/Service/HealthCheck/Utilities.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Data.Common;
77
using System.Text.Json;
88
using Azure.DataApiBuilder.Config.ObjectModel;
9+
using Azure.DataApiBuilder.Mcp.Core;
910
using Microsoft.Data.SqlClient;
1011
using Microsoft.Extensions.Logging;
1112
using MySqlConnector;
@@ -72,6 +73,28 @@ public static string CreateHttpRestQuery(string entityName, int first)
7273
return $"/{entityName}?$first={first}";
7374
}
7475

76+
public static string CreateHttpMcpQuery()
77+
{
78+
// Create a minimal MCP request (initialize) as a valid JSON-RPC request.
79+
// 'initialize' is used because other methods (e.g. 'tools/list') require an active
80+
// session in the MCP Streamable HTTP transport.
81+
string protocolVersion = McpProtocolDefaults.ResolveProtocolVersion(configuration: null);
82+
var payload = new
83+
{
84+
jsonrpc = "2.0",
85+
id = 1,
86+
method = "initialize",
87+
@params = new
88+
{
89+
protocolVersion,
90+
capabilities = new { },
91+
clientInfo = new { name = "dab-health-check", version = "1.0.0" }
92+
}
93+
};
94+
95+
return JsonSerializer.Serialize(payload);
96+
}
97+
7598
public static string NormalizeConnectionString(string connectionString, DatabaseType dbType, ILogger? logger = null)
7699
{
77100
try

0 commit comments

Comments
 (0)