-
Notifications
You must be signed in to change notification settings - Fork 11
Add MCP connection-readiness gating and surface setup URL #257
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
DheerajPannala
wants to merge
3
commits into
main
Choose a base branch
from
user/kpannala/byo-mcp
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
382 changes: 382 additions & 0 deletions
382
...Agents.A365.Tooling.Core.Tests/McpToolServerConfigurationService_ConnectionGatingTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,382 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System.Net; | ||
| using System.Net.Http; | ||
| using System.Text.Json; | ||
| using FluentAssertions; | ||
| using Microsoft.Agents.A365.Tooling.Models; | ||
| using Microsoft.Agents.A365.Tooling.Services; | ||
| using Microsoft.Agents.Builder; | ||
| using Microsoft.Extensions.Configuration; | ||
| using Microsoft.Extensions.Logging; | ||
| using Moq; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Agents.A365.Tooling.Core.Tests; | ||
|
|
||
| /// <summary> | ||
| /// Tests for MCP connection gating: gateway response parsing (wrapped + legacy), aggregate/per-server | ||
| /// connection metadata, and the <see cref="McpConnectionsRequiredException"/> raised by | ||
| /// <c>ListToolServersAsync</c> when configured servers are not connection-ready. | ||
| /// </summary> | ||
| public class McpToolServerConfigurationService_ConnectionGatingTests | ||
| { | ||
| private const string WrappedPendingJson = """ | ||
| { | ||
| "mcpServers": [ | ||
| { | ||
| "mcpServerName": "mcp_Salesforce", | ||
| "id": "id-1", | ||
| "url": "https://s/mcp_Salesforce", | ||
| "scope": "McpServers.Salesforce.All", | ||
| "audience": "", | ||
| "allConnectionsUrl": "https://all/sf", | ||
| "missingConnectionsUrl": "https://missing/sf", | ||
| "connectivityStatus": "Pending" | ||
| } | ||
| ], | ||
| "allConnectionsUrl": "https://all", | ||
| "missingConnectionsUrl": "https://missing", | ||
| "connectivityStatus": "Pending" | ||
| } | ||
| """; | ||
|
|
||
| private const string WrappedReadyJson = """ | ||
| { | ||
| "mcpServers": [ | ||
| { | ||
| "mcpServerName": "s", | ||
| "id": "id-1", | ||
| "url": "https://s", | ||
| "allConnectionsUrl": "https://all", | ||
| "missingConnectionsUrl": "https://missing", | ||
| "connectivityStatus": "Ready" | ||
| } | ||
| ], | ||
| "allConnectionsUrl": "https://all", | ||
| "missingConnectionsUrl": "https://missing", | ||
| "connectivityStatus": "Ready" | ||
| } | ||
| """; | ||
|
|
||
| private const string LegacyArrayJson = """ | ||
| [ { "mcpServerName": "s", "id": "id-1", "url": "https://s" } ] | ||
| """; | ||
|
|
||
| // ─── ParseGatewayResponse ──────────────────────────────────────────────── | ||
|
|
||
| [Fact] | ||
| public void ParseGatewayResponse_Wrapped_ParsesServersAndAggregateMetadata() | ||
| { | ||
| var result = ParseGateway(WrappedPendingJson); | ||
|
|
||
| var server = result.Servers.Should().ContainSingle().Subject; | ||
| server.mcpServerName.Should().Be("mcp_Salesforce"); | ||
| server.allConnectionsUrl.Should().Be("https://all/sf"); | ||
| server.missingConnectionsUrl.Should().Be("https://missing/sf"); | ||
| server.connectivityStatus.Should().Be("Pending"); | ||
|
|
||
| result.AllConnectionsUrl.Should().Be("https://all"); | ||
| result.MissingConnectionsUrl.Should().Be("https://missing"); | ||
| result.ConnectivityStatus.Should().Be("Pending"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ParseGatewayResponse_Ready_NullsMissingConnectionsUrl() | ||
| { | ||
| var result = ParseGateway(WrappedReadyJson); | ||
|
|
||
| var server = result.Servers.Should().ContainSingle().Subject; | ||
| server.connectivityStatus.Should().Be("Ready"); | ||
| server.missingConnectionsUrl.Should().BeNull(); | ||
|
|
||
| result.ConnectivityStatus.Should().Be("Ready"); | ||
| result.MissingConnectionsUrl.Should().BeNull(); | ||
| result.AllConnectionsUrl.Should().Be("https://all"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ParseGatewayResponse_LegacyArray_ReturnsServersWithoutAggregate() | ||
| { | ||
| var result = ParseGateway(LegacyArrayJson); | ||
|
|
||
| result.Servers.Should().ContainSingle(); | ||
| result.ConnectivityStatus.Should().BeNull(); | ||
| result.AllConnectionsUrl.Should().BeNull(); | ||
| result.MissingConnectionsUrl.Should().BeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ParseGatewayResponse_EmptyMcpServers_ReturnsEmptyWithAggregate() | ||
| { | ||
| var result = ParseGateway("""{ "mcpServers": [], "connectivityStatus": "Ready" }"""); | ||
|
|
||
| result.Servers.Should().BeEmpty(); | ||
| result.ConnectivityStatus.Should().Be("Ready"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ParseGatewayResponse_UnexpectedStructure_Throws() | ||
| { | ||
| Action act = () => ParseGateway("""{ "foo": 1 }"""); | ||
|
|
||
| act.Should().Throw<InvalidOperationException>().WithMessage("*Unexpected JSON structure*"); | ||
| } | ||
|
|
||
| // ─── EnforceConnectionReadiness ────────────────────────────────────────── | ||
|
|
||
| [Fact] | ||
| public void EnforceConnectionReadiness_Pending_ThrowsWithDetails() | ||
| { | ||
| var service = CreateService(); | ||
| var discovery = new McpDiscoveryResult( | ||
| new List<MCPServerConfig> | ||
| { | ||
| new() { mcpServerName = "pending-srv", id = "id-1", url = "http://p", connectivityStatus = "Pending" }, | ||
| new() { mcpServerName = "ready-srv", id = "id-2", url = "http://r", connectivityStatus = "Ready" }, | ||
| }, | ||
| allConnectionsUrl: "https://all", | ||
| missingConnectionsUrl: "https://missing", | ||
| connectivityStatus: "Pending"); | ||
|
|
||
| var act = () => service.EnforceConnectionReadiness(discovery); | ||
|
|
||
| var ex = act.Should().Throw<McpConnectionsRequiredException>().Which; | ||
| ex.ConnectivityStatus.Should().Be("Pending"); | ||
| ex.MissingConnectionsUrl.Should().Be("https://missing"); | ||
| ex.ServerNames.Should().ContainSingle().Which.Should().Be("pending-srv"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void EnforceConnectionReadiness_Ready_DoesNotThrow() | ||
| { | ||
| var service = CreateService(); | ||
| var discovery = new McpDiscoveryResult(new List<MCPServerConfig>(), connectivityStatus: "Ready"); | ||
|
|
||
| var act = () => service.EnforceConnectionReadiness(discovery); | ||
|
|
||
| act.Should().NotThrow(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void EnforceConnectionReadiness_NullStatus_DoesNotThrow() | ||
| { | ||
| var service = CreateService(); | ||
| var discovery = new McpDiscoveryResult(new List<MCPServerConfig>(), connectivityStatus: null); | ||
|
|
||
| var act = () => service.EnforceConnectionReadiness(discovery); | ||
|
|
||
| act.Should().NotThrow(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void EnforceConnectionReadiness_UnknownStatus_Throws() | ||
| { | ||
| var service = CreateService(); | ||
| var discovery = new McpDiscoveryResult(new List<MCPServerConfig>(), connectivityStatus: "Frozen"); | ||
|
|
||
| var act = () => service.EnforceConnectionReadiness(discovery); | ||
|
|
||
| act.Should().Throw<McpConnectionsRequiredException>() | ||
| .Which.ConnectivityStatus.Should().Be("Frozen"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void EnforceConnectionReadiness_AggregateReadyButPerServerPending_DoesNotThrow() | ||
| { | ||
| // Gating is aggregate-only by design: a per-server Pending does not block the turn when the | ||
| // gateway reports the aggregate connectivity status as Ready. | ||
| var service = CreateService(); | ||
| var discovery = new McpDiscoveryResult( | ||
| new List<MCPServerConfig> | ||
| { | ||
| new() { mcpServerName = "srv", id = "id-1", url = "http://s", connectivityStatus = "Pending" }, | ||
| }, | ||
| connectivityStatus: "Ready"); | ||
|
|
||
| var act = () => service.EnforceConnectionReadiness(discovery); | ||
|
|
||
| act.Should().NotThrow(); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("READY")] | ||
| [InlineData(" ready ")] | ||
| public void EnforceConnectionReadiness_ReadyStatusVariants_DoNotThrow(string status) | ||
| { | ||
| // Pins IsReadyStatus: comparison is case-insensitive and whitespace-tolerant. | ||
| var service = CreateService(); | ||
| var discovery = new McpDiscoveryResult(new List<MCPServerConfig>(), connectivityStatus: status); | ||
|
|
||
| var act = () => service.EnforceConnectionReadiness(discovery); | ||
|
|
||
| act.Should().NotThrow(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void EnforceConnectionReadiness_PendingWithoutPerServerStatus_ThrowsWithEmptyServerNames() | ||
| { | ||
| var service = CreateService(); | ||
| var discovery = new McpDiscoveryResult( | ||
| new List<MCPServerConfig> | ||
| { | ||
| new() { mcpServerName = "srv", id = "id-1", url = "http://s" }, | ||
| }, | ||
| connectivityStatus: "Pending"); | ||
|
|
||
| var act = () => service.EnforceConnectionReadiness(discovery); | ||
|
|
||
| var ex = act.Should().Throw<McpConnectionsRequiredException>().Which; | ||
| ex.ServerNames.Should().BeEmpty(); | ||
| ex.Message.Should().Contain("(unknown)"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void EnforceConnectionReadiness_PendingWithoutMissingUrl_ThrowsWithNullUrl() | ||
| { | ||
| // Every consumer's handler must survive a null MissingConnectionsUrl. | ||
| var service = CreateService(); | ||
| var discovery = new McpDiscoveryResult( | ||
| new List<MCPServerConfig> | ||
| { | ||
| new() { mcpServerName = "srv", id = "id-1", url = "http://s", connectivityStatus = "Pending" }, | ||
| }, | ||
| connectivityStatus: "Pending"); | ||
|
|
||
| var act = () => service.EnforceConnectionReadiness(discovery); | ||
|
|
||
| act.Should().Throw<McpConnectionsRequiredException>() | ||
| .Which.MissingConnectionsUrl.Should().BeNull(); | ||
| } | ||
|
|
||
| // ─── ListToolServersAsync (end-to-end via gateway) ─────────────────────── | ||
|
|
||
| [Fact] | ||
| public async Task ListToolServersAsync_PendingGateway_ThrowsConnectionsRequired() | ||
| { | ||
| var service = CreateService(Respond(WrappedPendingJson)); | ||
|
|
||
| var ex = await Assert.ThrowsAsync<McpConnectionsRequiredException>( | ||
| () => service.ListToolServersAsync("agent-123", "tok", new ToolOptions())); | ||
|
|
||
| ex.ConnectivityStatus.Should().Be("Pending"); | ||
| ex.MissingConnectionsUrl.Should().Be("https://missing"); | ||
| ex.ServerNames.Should().Contain("mcp_Salesforce"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ListToolServersAsync_ReadyGateway_ReturnsServers() | ||
| { | ||
| var service = CreateService(Respond(WrappedReadyJson)); | ||
|
|
||
| var servers = await service.ListToolServersAsync("agent-123", "tok", new ToolOptions()); | ||
|
|
||
| var server = servers.Should().ContainSingle().Subject; | ||
| server.connectivityStatus.Should().Be("Ready"); | ||
| server.missingConnectionsUrl.Should().BeNull(); | ||
| server.allConnectionsUrl.Should().Be("https://all"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ListToolServersAsync_LegacyArrayGateway_ReturnsServersWithoutGating() | ||
| { | ||
| var service = CreateService(Respond(LegacyArrayJson)); | ||
|
|
||
| var servers = await service.ListToolServersAsync("agent-123", "tok", new ToolOptions()); | ||
|
|
||
| servers.Should().ContainSingle(); | ||
| } | ||
|
|
||
| // ─── Exception propagation through enumeration ─────────────────────────── | ||
|
|
||
| [Fact] | ||
| public async Task EnumerateToolsFromServersAsync_NoTokenProvider_PropagatesConnectionsRequired() | ||
| { | ||
| var mockService = CreatePartialMock(); | ||
| mockService | ||
| .Setup(x => x.ListToolServersAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ToolOptions>())) | ||
| .ThrowsAsync(new McpConnectionsRequiredException("https://missing", "Pending", new[] { "srv" })); | ||
|
|
||
| await Assert.ThrowsAsync<McpConnectionsRequiredException>(() => | ||
| mockService.Object.EnumerateToolsFromServersAsync( | ||
| "agent-id", "auth-token", new Mock<ITurnContext>().Object, new ToolOptions())); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task EnumerateToolsFromServersAsync_WithTokenProvider_PropagatesConnectionsRequired() | ||
| { | ||
| var mockService = CreatePartialMock(); | ||
| mockService | ||
| .Setup(x => x.ListToolServersAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ToolOptions>())) | ||
| .ThrowsAsync(new McpConnectionsRequiredException("https://missing", "Pending", new[] { "srv" })); | ||
|
|
||
| await Assert.ThrowsAsync<McpConnectionsRequiredException>(() => | ||
| mockService.Object.EnumerateToolsFromServersAsync( | ||
| "agent-id", "auth-token", new Mock<IMcpTokenProvider>().Object, | ||
| new Mock<ITurnContext>().Object, new ToolOptions())); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task EnumerateToolsFromServersAsync_GenericFailure_StillReturnsEmpty() | ||
| { | ||
| // Regression guard: non-gating failures remain swallowed (return empty) — unchanged behavior. | ||
| var mockService = CreatePartialMock(); | ||
| mockService | ||
| .Setup(x => x.ListToolServersAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ToolOptions>())) | ||
| .ThrowsAsync(new Exception("network")); | ||
|
|
||
| var (servers, toolsByServer) = await mockService.Object.EnumerateToolsFromServersAsync( | ||
| "agent-id", "auth-token", new Mock<ITurnContext>().Object, new ToolOptions()); | ||
|
|
||
| servers.Should().BeEmpty(); | ||
| toolsByServer.Should().BeEmpty(); | ||
| } | ||
|
|
||
| // ─── Helpers ───────────────────────────────────────────────────────────── | ||
|
|
||
| private static McpDiscoveryResult ParseGateway(string json) | ||
| { | ||
| using var doc = JsonDocument.Parse(json); | ||
| return McpToolServerConfigurationService.ParseGatewayResponse(doc.RootElement); | ||
| } | ||
|
|
||
| private static Mock<McpToolServerConfigurationService> CreatePartialMock() => | ||
| new Mock<McpToolServerConfigurationService>( | ||
| MockBehavior.Default, | ||
| new Mock<ILogger<IMcpToolServerConfigurationService>>().Object, | ||
| new Mock<IConfiguration>().Object, | ||
| new Mock<IServiceProvider>().Object, | ||
| new Mock<IHttpClientFactory>().Object) | ||
| { CallBase = true }; | ||
|
|
||
| private static FakeHttpMessageHandler Respond(string json) => | ||
| new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json) }); | ||
|
|
||
| private static McpToolServerConfigurationService CreateService(FakeHttpMessageHandler? handler = null) | ||
| { | ||
| var config = new Mock<IConfiguration>(); | ||
| config.Setup(c => c["MCP_PLATFORM_ENDPOINT"]).Returns("https://test.endpoint"); | ||
|
|
||
| handler ??= Respond("[]"); | ||
| var httpClient = new HttpClient(handler); | ||
|
github-code-quality[bot] marked this conversation as resolved.
Fixed
|
||
| var factory = new Mock<IHttpClientFactory>(); | ||
| factory.Setup(f => f.CreateClient(It.IsAny<string>())).Returns(httpClient); | ||
|
|
||
| return new McpToolServerConfigurationService( | ||
| new Mock<ILogger<IMcpToolServerConfigurationService>>().Object, | ||
| config.Object, | ||
| new Mock<IServiceProvider>().Object, | ||
| factory.Object); | ||
| } | ||
|
|
||
| private sealed class FakeHttpMessageHandler : HttpMessageHandler | ||
| { | ||
| private readonly Func<HttpRequestMessage, HttpResponseMessage> _responder; | ||
|
|
||
| public FakeHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> responder) => _responder = responder; | ||
|
|
||
| protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | ||
| => Task.FromResult(_responder(request)); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.