Skip to content
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
// 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");
}

// ─── 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);
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
Comment thread
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));
}
}
51 changes: 51 additions & 0 deletions src/Tooling/Core/Exceptions/McpConnectionsRequiredException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

namespace Microsoft.Agents.A365.Tooling
{
using System;
using System.Collections.Generic;

/// <summary>
/// Thrown when one or more configured MCP servers are not yet connection-ready.
/// The tooling gateway reports an aggregate connectivity status other than <c>Ready</c>
/// (for example, <c>Pending</c>) when the agent's MCP servers have downstream connections that the
/// user has not yet established. Callers should surface <see cref="MissingConnectionsUrl"/> to the
/// user to complete setup, then retry on a later turn once the connections are in place.
/// </summary>
public class McpConnectionsRequiredException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="McpConnectionsRequiredException"/> class.
/// </summary>
/// <param name="missingConnectionsUrl">URL the user can visit to set up the missing connections, when provided by the gateway.</param>
/// <param name="connectivityStatus">The aggregate connectivity status reported by the gateway (for example, <c>Pending</c>).</param>
/// <param name="serverNames">The names of the MCP servers that are not yet connection-ready.</param>
public McpConnectionsRequiredException(
string? missingConnectionsUrl,
string? connectivityStatus,
IReadOnlyList<string> serverNames)
: base(BuildMessage(missingConnectionsUrl, connectivityStatus, serverNames))
{
this.MissingConnectionsUrl = missingConnectionsUrl;
this.ConnectivityStatus = connectivityStatus;
this.ServerNames = serverNames;
}

/// <summary>Gets the URL the user can visit to set up the missing connections, or null when not provided.</summary>
public string? MissingConnectionsUrl { get; }

/// <summary>Gets the aggregate connectivity status reported by the gateway, or null when not provided.</summary>
public string? ConnectivityStatus { get; }

/// <summary>Gets the names of the MCP servers that are not yet connection-ready.</summary>
public IReadOnlyList<string> ServerNames { get; }

private static string BuildMessage(string? missingConnectionsUrl, string? connectivityStatus, IReadOnlyList<string> serverNames)
{
string serversText = serverNames is { Count: > 0 } ? string.Join(", ", serverNames) : "(unknown)";
return $"MCP servers [{serversText}] require connection setup (connectivityStatus={connectivityStatus}). " +
$"Set up missing connections at: {missingConnectionsUrl}";
}
}
}
20 changes: 20 additions & 0 deletions src/Tooling/Core/Models/MCPServerConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ public class MCPServerConfig
/// </summary>
public string? publisher { get; set; }

/// <summary>
/// Gets or sets the URL containing the deduped union of all connectors required for this MCP
/// server to operate. Populated by the discovery endpoint (<c>discoverMCPServers</c>); null
/// when not supplied (for example, on the basic server-list path).
/// </summary>
public string? allConnectionsUrl { get; set; }

/// <summary>
/// Gets or sets the URL containing the deduped union of only the connectors required for this
/// MCP server that the connected user has not yet set up. Null when <c>connectivityStatus</c>
/// is <c>Ready</c> (no setup needed) or when not supplied.
/// </summary>
public string? missingConnectionsUrl { get; set; }

/// <summary>
/// Gets or sets the connectivity status for this MCP server (for example, <c>Ready</c> when all
/// required connectors are already connected). Compare case-insensitively. Null when not supplied.
/// </summary>
public string? connectivityStatus { get; set; }

/// <summary>
/// Gets or sets per-server HTTP headers, including the Authorization header populated
/// by <c>AttachPerAudienceTokensAsync</c> before tool connections are established.
Expand Down
Loading
Loading