// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
using Aspire.Cli.Backchannel;
using Aspire.Cli.Mcp.Tools;
using Aspire.Cli.Tests.TestServices;
using Aspire.Cli.Tests.Utils;
using Aspire.Dashboard.Model;
using Aspire.Dashboard.Otlp.Model;
using Aspire.Otlp.Serialization;
using Microsoft.AspNetCore.InternalTesting;
using Microsoft.Extensions.Logging.Abstractions;
using ModelContextProtocol;
using ModelContextProtocol.Protocol;
namespace Aspire.Cli.Tests.Mcp;
public class ExcludeFromMcpTests
{
private const string ApiServiceName = "api-service";
private const string AppHostPath = "/repo/TestAppHost/TestAppHost.csproj";
private const string SecretServiceName = "secret-service";
private static readonly TestHttpClientFactory s_httpClientFactory = new();
[Fact]
public void IsExcludedFromMcp_ReturnsFalse_WhenPropertyNotSet()
{
var snapshot = new ResourceSnapshot
{
Name = "test",
Properties = []
};
Assert.False(McpToolHelpers.IsExcludedFromMcp(snapshot));
}
[Fact]
public void IsExcludedFromMcp_ReturnsTrue_WhenPropertyIsBoolTrue()
{
var snapshot = new ResourceSnapshot
{
Name = "test",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = JsonValue.Create(true)
}
};
Assert.True(McpToolHelpers.IsExcludedFromMcp(snapshot));
}
[Fact]
public void IsExcludedFromMcp_ReturnsFalse_WhenPropertyIsBoolFalse()
{
var snapshot = new ResourceSnapshot
{
Name = "test",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = JsonValue.Create(false)
}
};
Assert.False(McpToolHelpers.IsExcludedFromMcp(snapshot));
}
[Fact]
public void IsExcludedFromMcp_ReturnsTrue_WhenPropertyIsStringTrue()
{
var snapshot = new ResourceSnapshot
{
Name = "test",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = JsonValue.Create("true")
}
};
Assert.True(McpToolHelpers.IsExcludedFromMcp(snapshot));
}
[Fact]
public void IsExcludedFromMcp_ReturnsFalse_WhenPropertyIsNull()
{
var snapshot = new ResourceSnapshot
{
Name = "test",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = null
}
};
Assert.False(McpToolHelpers.IsExcludedFromMcp(snapshot));
}
[Fact]
public async Task ListResourcesTool_ExcludesResourceWithExcludeFromMcp()
{
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
AppHostInfo = CreateAppHostInfo(),
ResourceSnapshots =
[
new ResourceSnapshot
{
Name = ApiServiceName,
DisplayName = "API Service",
ResourceType = "Project",
State = "Running",
WaitingFor = [SecretServiceName],
Relationships =
[
new ResourceSnapshotRelationship
{
ResourceName = "Secret Service",
Type = "Reference"
}
]
},
new ResourceSnapshot
{
Name = SecretServiceName,
DisplayName = "Secret Service",
ResourceType = "Project",
State = "Running",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = JsonValue.Create(true)
}
}
],
DashboardUrlsState = new DashboardUrlsState { BaseUrlWithLoginToken = "http://localhost:18888" }
};
monitor.AddConnection("socket.hash1", connection);
var tool = new ListResourcesTool(monitor, s_httpClientFactory, NullLogger<ListResourcesTool>.Instance);
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(), CancellationToken.None).DefaultTimeout();
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
const string marker = "# RESOURCE DATA";
var markerIndex = textContent.Text.IndexOf(marker, StringComparison.Ordinal);
Assert.True(markerIndex >= 0, "Response should contain the resource data marker.");
var jsonText = textContent.Text[(markerIndex + marker.Length)..].Trim();
using var json = JsonDocument.Parse(jsonText);
var resource = json.RootElement[0];
Assert.Equal(ApiServiceName, resource.GetProperty("name").GetString());
Assert.Equal("[]", resource.GetProperty("waiting_for").GetRawText());
Assert.Empty(resource.GetProperty("relationships").EnumerateArray());
}
[Fact]
public async Task ListResourcesTool_ReturnsNoResourcesFound_WhenAllExcluded()
{
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
AppHostInfo = CreateAppHostInfo(),
ResourceSnapshots =
[
new ResourceSnapshot
{
Name = SecretServiceName,
DisplayName = "Secret Service",
ResourceType = "Project",
State = "Running",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = JsonValue.Create(true)
}
}
],
DashboardUrlsState = new DashboardUrlsState { BaseUrlWithLoginToken = "http://localhost:18888" }
};
monitor.AddConnection("socket.hash1", connection);
var tool = new ListResourcesTool(monitor, s_httpClientFactory, NullLogger<ListResourcesTool>.Instance);
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(), CancellationToken.None).DefaultTimeout();
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
const string marker = "# RESOURCE DATA";
var markerIndex = textContent.Text.IndexOf(marker, StringComparison.Ordinal);
Assert.True(markerIndex >= 0, "Response should contain the resource data marker.");
var jsonText = textContent.Text[(markerIndex + marker.Length)..].Trim();
Assert.StartsWith("[", jsonText, StringComparison.Ordinal);
using var json = JsonDocument.Parse(jsonText);
Assert.Empty(json.RootElement.EnumerateArray());
}
private static AppHostInformation CreateAppHostInfo()
=> new()
{
AppHostPath = AppHostPath,
ProcessId = 4242
};
[Fact]
public async Task ListConsoleLogsTool_ReturnsError_WhenResourceIsExcluded()
{
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
ResourceSnapshots =
[
new ResourceSnapshot
{
Name = SecretServiceName,
DisplayName = "Secret Service",
ResourceType = "Project",
State = "Running",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = JsonValue.Create(true)
}
}
],
LogLines = [new ResourceLogLine { Content = "secret log", IsError = false, ResourceName = SecretServiceName, LineNumber = 1 }]
};
monitor.AddConnection("socket.hash1", connection);
var tool = new ListConsoleLogsTool(monitor, NullLogger<ListConsoleLogsTool>.Instance);
var arguments = new Dictionary<string, JsonElement>
{
["resourceName"] = JsonDocument.Parse($"\"{SecretServiceName}\"").RootElement
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Equal(McpToolHelpers.GetResourceNotAvailableMessage(SecretServiceName), textContent.Text);
}
[Fact]
public async Task ListConsoleLogsTool_ReturnsLogs_WhenResourceIsNotExcluded()
{
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
ResourceSnapshots =
[
new ResourceSnapshot
{
Name = ApiServiceName,
DisplayName = "API Service",
ResourceType = "Project",
State = "Running"
}
],
LogLines = [new ResourceLogLine { Content = "Application started", IsError = false, ResourceName = ApiServiceName, LineNumber = 1 }]
};
monitor.AddConnection("socket.hash1", connection);
var tool = new ListConsoleLogsTool(monitor, NullLogger<ListConsoleLogsTool>.Instance);
var arguments = new Dictionary<string, JsonElement>
{
["resourceName"] = JsonDocument.Parse($"\"{ApiServiceName}\"").RootElement
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Contains("Application started", textContent.Text);
}
[Fact]
public async Task ExecuteResourceCommandTool_ReturnsError_WhenResourceIsExcluded()
{
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
ResourceSnapshots =
[
new ResourceSnapshot
{
Name = SecretServiceName,
DisplayName = "Secret Service",
ResourceType = "Project",
State = "Running",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = JsonValue.Create(true)
}
}
],
ExecuteResourceCommandResult = new ExecuteResourceCommandResponse { Success = true }
};
monitor.AddConnection("socket.hash1", connection);
var tool = new ExecuteResourceCommandTool(monitor, NullLogger<ExecuteResourceCommandTool>.Instance);
using var doc = JsonDocument.Parse($$"""{"resourceName": "{{SecretServiceName}}", "commandName": "restart"}""");
var arguments = doc.RootElement.EnumerateObject()
.ToDictionary(p => p.Name, p => p.Value.Clone());
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Equal(McpToolHelpers.GetResourceNotAvailableMessage(SecretServiceName), textContent.Text);
}
[Fact]
public async Task ListStructuredLogsTool_ReturnsError_WhenSpecificResourceIsExcluded()
{
var monitor = CreateMonitorWithDashboardAndExcludedResource();
var (mockHttpClientFactory, _) = CreateMockHttpWithLogs(SecretServiceName);
var tool = CreateStructuredLogsTool(monitor, mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["resourceName"] = JsonDocument.Parse($"\"{SecretServiceName}\"").RootElement
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Equal(McpToolHelpers.GetResourceNotAvailableMessage(SecretServiceName), textContent.Text);
}
[Fact]
public async Task ListStructuredLogsTool_FiltersExcludedResourceLogs_WhenNoResourceSpecified()
{
var monitor = CreateMonitorWithDashboardAndExcludedResource();
var (mockHttpClientFactory, _) = CreateMockHttpWithLogs(ApiServiceName, SecretServiceName);
var tool = CreateStructuredLogsTool(monitor, mockHttpClientFactory);
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Contains(ApiServiceName, textContent.Text);
Assert.DoesNotContain(SecretServiceName, textContent.Text);
}
[Fact]
public async Task ListTracesTool_ReturnsError_WhenSpecificResourceIsExcluded()
{
var monitor = CreateMonitorWithDashboardAndExcludedResource();
var (mockHttpClientFactory, _) = CreateMockHttpWithTraces(SecretServiceName);
var tool = CreateTracesTool(monitor, mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["resourceName"] = JsonDocument.Parse($"\"{SecretServiceName}\"").RootElement
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Equal(McpToolHelpers.GetResourceNotAvailableMessage(SecretServiceName), textContent.Text);
}
[Fact]
public async Task ListTracesTool_FiltersExcludedResourceSpans_WhenNoResourceSpecified()
{
var monitor = CreateMonitorWithDashboardAndExcludedResource();
var (mockHttpClientFactory, _) = CreateMockHttpWithTraces(ApiServiceName, SecretServiceName);
var tool = CreateTracesTool(monitor, mockHttpClientFactory);
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Contains(ApiServiceName, textContent.Text);
Assert.DoesNotContain(SecretServiceName, textContent.Text);
}
[Theory]
[InlineData(ListTracesTool.SummaryFormat)]
[InlineData(ListTracesTool.FullFormat)]
public async Task ListTracesTool_FiltersExcludedResourceSpans_WhenResourceSpecified(string format)
{
// The dashboard returns whole traces that contain the requested resource, so a trace for the included
// resource can still carry a failing span, with exception details, from the excluded resource.
var resourceSpans = CreateTraceWithExcludedFailingSpan();
var resources = new[] { ApiServiceName, SecretServiceName }
.Select(name => new ResourceInfoJson { Name = name, HasLogs = true, HasTraces = true, HasMetrics = true })
.ToArray();
var (mockHttpClientFactory, _) = CreateMockHttp(resources, new TelemetryApiResponse
{
Data = new OtlpTelemetryDataJson { ResourceSpans = resourceSpans },
TotalCount = 1,
ReturnedCount = 1
});
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["resourceName"] = JsonSerializer.SerializeToElement(ApiServiceName),
["format"] = JsonSerializer.SerializeToElement(format)
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
var trace = Assert.Single(JsonNode.Parse(text[text.IndexOf('[')..(text.LastIndexOf(']') + 1)])!.AsArray())!;
if (format == ListTracesTool.SummaryFormat)
{
Assert.Equal(1, trace["spanCount"]!.GetValue<int>());
Assert.Equal([ApiServiceName], trace["resources"]!.AsArray().Select(resource => resource!.GetValue<string>()));
Assert.False(trace["hasError"]!.GetValue<bool>());
Assert.Equal("api-span", trace["rootSpan"]!["spanId"]!.GetValue<string>());
Assert.Null(trace["firstErrorSpan"]);
}
else
{
var span = Assert.Single(trace["spans"]!.AsArray())!;
Assert.Equal("api-span", span["spanId"]!.GetValue<string>());
}
}
[Fact]
public async Task ListTracesTool_FiltersExcludedResourceSpans_WhenTraceIdProvided()
{
// Requesting a trace by ID skips the list-mode resource checks, so the detail response, which includes span
// events, must still drop the excluded resource's failing span and its exception details.
var (result, requestedPaths) = await GetTraceByIdAsync(CreateTraceWithExcludedFailingSpan()).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.Equal(["/api/telemetry/resources", "/api/telemetry/traces/abc123def456"], requestedPaths);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
var trace = JsonNode.Parse(text[text.IndexOf('{')..(text.LastIndexOf('}') + 1)])!.AsObject();
Assert.False(trace["hasError"]!.GetValue<bool>());
var span = Assert.Single(trace["spans"]!.AsArray())!;
Assert.Equal("api-span", span["spanId"]!.GetValue<string>());
Assert.Equal(ApiServiceName, span["source"]!.GetValue<string>());
Assert.Null(span["events"]);
}
[Fact]
public async Task ListTracesTool_ReturnsNotFound_WhenTraceIdProvidedAndAllSpansAreExcluded()
{
// Keep only the excluded resource's span so every span of the trace is filtered out.
var (result, requestedPaths) = await GetTraceByIdAsync(CreateTraceWithExcludedFailingSpan()[1..]).DefaultTimeout();
Assert.True(result.IsError);
Assert.Equal(["/api/telemetry/resources", "/api/telemetry/traces/abc123def456"], requestedPaths);
Assert.Equal("Trace 'abc123def456' not found.", Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text);
}
[Fact]
public async Task ListTraceStructuredLogsTool_FiltersExcludedResourceLogs()
{
var monitor = CreateMonitorWithDashboardAndExcludedResource();
var (mockHttpClientFactory, _) = CreateMockHttpWithLogs(ApiServiceName, SecretServiceName);
var tool = CreateTraceStructuredLogsTool(monitor, mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["traceId"] = JsonDocument.Parse("\"abc123def456\"").RootElement
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Contains(ApiServiceName, textContent.Text);
Assert.DoesNotContain(SecretServiceName, textContent.Text);
}
[Fact]
public async Task ListTraceStructuredLogsTool_ReturnsAllLogs_WhenNoResourcesExcluded()
{
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
DashboardInfoResponse = new GetDashboardInfoResponse
{
ApiBaseUrl = "http://localhost:5000",
ApiToken = "test-token",
DashboardUrls = ["http://localhost:18888"]
},
ResourceSnapshots =
[
new ResourceSnapshot
{
Name = ApiServiceName,
DisplayName = "API Service",
ResourceType = "Project",
State = "Running"
},
new ResourceSnapshot
{
Name = SecretServiceName,
DisplayName = "Secret Service",
ResourceType = "Project",
State = "Running"
}
]
};
monitor.AddConnection("socket.hash1", connection);
var (mockHttpClientFactory, _) = CreateMockHttpWithLogs(ApiServiceName, SecretServiceName);
var tool = CreateTraceStructuredLogsTool(monitor, mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["traceId"] = JsonDocument.Parse("\"abc123def456\"").RootElement
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
var textContent = result.Content![0] as TextContentBlock;
Assert.NotNull(textContent);
Assert.Contains(ApiServiceName, textContent.Text);
Assert.Contains(SecretServiceName, textContent.Text);
}
[Fact]
public async Task ListTracesTool_QueriesOnlyResourcesNotExcluded_WhenNoResourceSpecified()
{
// The dashboard returns the latest traces for the requested resources. If the excluded resource were part of
// the query, its newer traces would fill the limit and hide the older traces of the other resources.
Uri? tracesRequestUri = null;
var resources = new[]
{
new ResourceInfoJson { Name = ApiServiceName, InstanceId = "abc", HasLogs = true, HasTraces = true, HasMetrics = true },
new ResourceInfoJson { Name = ApiServiceName, InstanceId = "def", HasLogs = true, HasTraces = true, HasMetrics = true },
new ResourceInfoJson { Name = SecretServiceName, HasLogs = true, HasTraces = true, HasMetrics = true }
};
var (mockHttpClientFactory, _) = CreateMockHttp(
resources,
new TelemetryApiResponse
{
Data = new OtlpTelemetryDataJson
{
ResourceSpans =
[
CreateResourceSpans(ApiServiceName,
new OtlpSpanJson { Name = "GET /first", TraceId = "trace1", SpanId = "span1", StartTimeUnixNano = 1706540400000000001, EndTimeUnixNano = 1706540400100000000 },
new OtlpSpanJson { Name = "GET /second", TraceId = "trace2", SpanId = "span2", StartTimeUnixNano = 1706540400000000002, EndTimeUnixNano = 1706540400100000000 })
]
},
TotalCount = 7,
ReturnedCount = 2
},
request =>
{
if (!request.RequestUri!.AbsolutePath.EndsWith("/resources", StringComparison.Ordinal))
{
tracesRequestUri = request.RequestUri;
}
});
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["limit"] = JsonSerializer.SerializeToElement(2)
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.NotNull(tracesRequestUri);
Assert.Equal($"?resource={ApiServiceName}-abc&resource={ApiServiceName}-def&limit=2", tracesRequestUri.Query);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.StartsWith("Returned latest 2 traces. Earlier 5 traces not returned because of the limit of 2.", text, StringComparison.Ordinal);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ListTracesTool_FetchesEveryTraceAndFiltersResponse_WhenResourcesCannotBeListedInQuery(bool tooManyResources)
{
// When the resources that are not excluded can't be listed in the request, the tool falls back to fetching
// every trace and filtering the excluded resource out of the response:
// - A dashboard that has seen many resource instances can't take every instance in the request URL.
// - A service that sent telemetry both with and without service.instance.id has a resource without an
// instance ID whose name also matches its other instances, and the dashboard rejects an ambiguous name.
Uri? tracesRequestUri = null;
var apiResources = tooManyResources
? Enumerable.Range(0, 200).Select(i => new ResourceInfoJson { Name = ApiServiceName, InstanceId = $"instance-{i:000}", HasLogs = true, HasTraces = true, HasMetrics = true })
: [new ResourceInfoJson { Name = ApiServiceName, HasLogs = true, HasTraces = true, HasMetrics = true }, new ResourceInfoJson { Name = ApiServiceName, InstanceId = "instance-000", HasLogs = true, HasTraces = true, HasMetrics = true }];
var resources = apiResources
.Append(new ResourceInfoJson { Name = SecretServiceName, HasLogs = true, HasTraces = true, HasMetrics = true })
.ToArray();
var (mockHttpClientFactory, _) = CreateMockHttp(
resources,
new TelemetryApiResponse
{
Data = new OtlpTelemetryDataJson
{
ResourceSpans =
[
CreateResourceSpans(ApiServiceName,
new OtlpSpanJson { Name = "GET /first", TraceId = "trace1", SpanId = "span1", StartTimeUnixNano = 1706540400000000001, EndTimeUnixNano = 1706540400100000000 },
new OtlpSpanJson { Name = "GET /second", TraceId = "trace2", SpanId = "span2", StartTimeUnixNano = 1706540400000000002, EndTimeUnixNano = 1706540400100000000 }),
CreateResourceSpans(SecretServiceName,
new OtlpSpanJson { Name = "GET /secret", TraceId = "trace3", SpanId = "span3", StartTimeUnixNano = 1706540400000000003, EndTimeUnixNano = 1706540400100000000 })
]
},
// The total includes the excluded resource's trace, so the tool must count the traces it keeps instead.
TotalCount = 3,
ReturnedCount = 3
},
request =>
{
if (!request.RequestUri!.AbsolutePath.EndsWith("/resources", StringComparison.Ordinal))
{
tracesRequestUri = request.RequestUri;
}
});
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["limit"] = JsonSerializer.SerializeToElement(1)
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.NotNull(tracesRequestUri);
Assert.Equal($"?limit={int.MaxValue}", tracesRequestUri.Query);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.StartsWith("Returned latest 1 trace. Earlier 1 trace not returned because of the limit of 1.", text, StringComparison.Ordinal);
Assert.Equal(["trace2"], GetTraceIds(text));
}
[Theory]
[InlineData(null)]
[InlineData(ApiServiceName)]
public async Task ListTracesTool_FetchesEveryTrace_WhenExcludedTraceTakesPlaceInLimit(string? resourceName)
{
// The dashboard also matches a trace to the resource that a client span calls, so a trace with only spans from
// the excluded resource is selected when it calls the API service and the API service recorded no span.
var peerOnlyTrace = CreateResourceSpans(SecretServiceName,
new OtlpSpanJson { Name = "GET /health", TraceId = "trace3", SpanId = "span3", StartTimeUnixNano = 1706540400000000003, EndTimeUnixNano = 1706540400100000000 });
var apiTraces = CreateResourceSpans(ApiServiceName,
new OtlpSpanJson { Name = "GET /first", TraceId = "trace1", SpanId = "span1", StartTimeUnixNano = 1706540400000000001, EndTimeUnixNano = 1706540400100000000 },
new OtlpSpanJson { Name = "GET /second", TraceId = "trace2", SpanId = "span2", StartTimeUnixNano = 1706540400000000002, EndTimeUnixNano = 1706540400100000000 });
var (factory, queries) = CreateMockHttpWithTelemetryResponses(
[CreateResourceInfo(ApiServiceName), CreateResourceInfo(SecretServiceName)],
CreateTracesResponse(totalCount: 3, peerOnlyTrace),
CreateTracesResponse(totalCount: 3, apiTraces, peerOnlyTrace));
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), factory);
var arguments = new Dictionary<string, JsonElement>
{
["limit"] = JsonSerializer.SerializeToElement(1)
};
if (resourceName is not null)
{
arguments["resourceName"] = JsonSerializer.SerializeToElement(resourceName);
}
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
// A resource the caller requested is still part of the second query.
var secondQuery = resourceName is null ? $"?limit={int.MaxValue}" : $"?resource={ApiServiceName}&limit={int.MaxValue}";
Assert.Equal([$"?resource={ApiServiceName}&limit=1", secondQuery], queries);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.StartsWith("Returned latest 1 trace. Earlier 1 trace not returned because of the limit of 1.", text, StringComparison.Ordinal);
Assert.Equal(["trace2"], GetTraceIds(text));
}
[Fact]
public async Task ListTracesTool_DoesNotRepeatQuery_WhenReturnedTraceLosesOnlyItsExcludedSpans()
{
var (factory, queries) = CreateMockHttpWithTelemetryResponses(
[CreateResourceInfo(ApiServiceName), CreateResourceInfo(SecretServiceName)],
CreateTracesResponse(totalCount: 4, CreateTraceWithExcludedFailingSpan()));
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), factory);
var arguments = new Dictionary<string, JsonElement>
{
["limit"] = JsonSerializer.SerializeToElement(1)
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.Equal([$"?resource={ApiServiceName}&limit=1"], queries);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.StartsWith("Returned latest 1 trace. Earlier 3 traces not returned because of the limit of 1.", text, StringComparison.Ordinal);
}
[Fact]
public async Task ListTracesTool_FetchesEveryTrace_WhenDashboardRejectsListedResources()
{
// A new instance of the API service sent telemetry after the resources were read, so its name without an
// instance ID is ambiguous when the dashboard resolves it.
var (factory, queries) = CreateMockHttpWithTelemetryResponses(
[CreateResourceInfo(ApiServiceName), CreateResourceInfo(SecretServiceName)],
null,
CreateTracesResponse(
totalCount: 2,
CreateResourceSpans(ApiServiceName, new OtlpSpanJson { Name = "GET /first", TraceId = "trace1", SpanId = "span1", StartTimeUnixNano = 1706540400000000001, EndTimeUnixNano = 1706540400100000000 }),
CreateResourceSpans(SecretServiceName, new OtlpSpanJson { Name = "GET /secret", TraceId = "trace2", SpanId = "span2", StartTimeUnixNano = 1706540400000000002, EndTimeUnixNano = 1706540400100000000 })));
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), factory);
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.Equal([$"?resource={ApiServiceName}&limit={ListTracesTool.DefaultLimit}", $"?limit={int.MaxValue}"], queries);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.Equal(["trace1"], GetTraceIds(text));
}
[Fact]
public async Task ListTracesTool_ReportsError_WhenDashboardRejectsRequestedResource()
{
var (factory, queries) = CreateMockHttpWithTelemetryResponses(
[CreateResourceInfo(ApiServiceName), CreateResourceInfo(SecretServiceName)],
[null]);
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), factory);
var arguments = new Dictionary<string, JsonElement>
{
["resourceName"] = JsonSerializer.SerializeToElement(ApiServiceName)
};
await Assert.ThrowsAsync<McpProtocolException>(() => tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).AsTask()).DefaultTimeout();
Assert.Equal([$"?resource={ApiServiceName}&limit={ListTracesTool.DefaultLimit}"], queries);
}
[Fact]
public async Task ListTracesTool_DoesNotQueryTraces_WhenEveryResourceIsExcluded()
{
// An empty resource filter means every resource to the dashboard, so the tool must not send one.
var requestedPaths = new List<string>();
var (mockHttpClientFactory, _) = CreateMockHttp(
[new ResourceInfoJson { Name = SecretServiceName, HasLogs = true, HasTraces = true, HasMetrics = true }],
new TelemetryApiResponse
{
Data = new OtlpTelemetryDataJson { ResourceSpans = CreateTraceWithExcludedFailingSpan()[1..] },
TotalCount = 1,
ReturnedCount = 1
},
request => requestedPaths.Add(request.RequestUri!.AbsolutePath));
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), mockHttpClientFactory);
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.Equal(["/api/telemetry/resources"], requestedPaths);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.StartsWith("Returned 0 traces.", text, StringComparison.Ordinal);
Assert.Empty(GetTraceIds(text));
}
[Fact]
public async Task ListStructuredLogsTool_QueriesOnlyResourcesNotExcluded_WhenNoResourceSpecified()
{
// The dashboard returns the latest logs for the requested resources. If the excluded resource were part of
// the query, its newer logs would fill the limit and hide the older logs of the other resources.
Uri? logsRequestUri = null;
var (mockHttpClientFactory, _) = CreateMockHttpWithLogs(
[ApiServiceName, SecretServiceName],
returnedServiceNames: [ApiServiceName],
totalCount: 4,
onRequest: request =>
{
if (!request.RequestUri!.AbsolutePath.EndsWith("/resources", StringComparison.Ordinal))
{
logsRequestUri = request.RequestUri;
}
});
var tool = CreateStructuredLogsTool(CreateMonitorWithDashboardAndExcludedResource(), mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["limit"] = JsonSerializer.SerializeToElement(1)
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.NotNull(logsRequestUri);
Assert.Equal($"?resource={ApiServiceName}&limit=1", logsRequestUri.Query);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.StartsWith("Returned latest 1 log entry. Earlier 3 log entries not returned because of the limit of 1.", text, StringComparison.Ordinal);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ListStructuredLogsTool_FetchesEveryLog_WhenQueryIsNotLimitedToResourcesNotExcluded(bool rejected)
{
// The resources changed after they were read. Either the dashboard rejects a name that became ambiguous, or
// the excluded resource first sent telemetry, so the query had no filter and its log takes a place in the limit.
ResourceInfoJson[] resources = rejected
? [CreateResourceInfo(ApiServiceName), CreateResourceInfo(SecretServiceName)]
: [CreateResourceInfo(ApiServiceName)];
var (factory, queries) = CreateMockHttpWithTelemetryResponses(
resources,
rejected ? null : CreateLogsResponse(totalCount: 2, SecretServiceName),
CreateLogsResponse(totalCount: 2, ApiServiceName, SecretServiceName));
var tool = CreateStructuredLogsTool(CreateMonitorWithDashboardAndExcludedResource(), factory);
var arguments = new Dictionary<string, JsonElement>
{
["limit"] = JsonSerializer.SerializeToElement(1)
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.Equal([rejected ? $"?resource={ApiServiceName}&limit=1" : "?limit=1", $"?limit={int.MaxValue}"], queries);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.StartsWith("Returned 1 log entry.", text, StringComparison.Ordinal);
Assert.Contains($"Log from {ApiServiceName}", text);
}
[Fact]
public async Task ListStructuredLogsTool_DoesNotQueryLogs_WhenEveryResourceIsExcluded()
{
// An empty resource filter means every resource to the dashboard, so the tool must not send one.
var requestedPaths = new List<string>();
var (mockHttpClientFactory, _) = CreateMockHttpWithLogs(
[SecretServiceName],
returnedServiceNames: [SecretServiceName],
totalCount: 1,
onRequest: request => requestedPaths.Add(request.RequestUri!.AbsolutePath));
var tool = CreateStructuredLogsTool(CreateMonitorWithDashboardAndExcludedResource(), mockHttpClientFactory);
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(), CancellationToken.None).DefaultTimeout();
Assert.True(result.IsError is null or false);
Assert.Equal(["/api/telemetry/resources"], requestedPaths);
var text = Assert.IsType<TextContentBlock>(Assert.Single(result.Content!)).Text;
Assert.StartsWith("Returned 0 log entries.", text, StringComparison.Ordinal);
Assert.Empty(JsonNode.Parse(text[text.LastIndexOf('[')..])!.AsArray());
}
private static IEnumerable<string> GetTraceIds(string text)
{
return JsonNode.Parse(text[text.IndexOf('[')..(text.LastIndexOf(']') + 1)])!.AsArray()
.Select(trace => trace!["traceId"]!.GetValue<string>());
}
private static TestAuxiliaryBackchannelMonitor CreateMonitorWithDashboardAndExcludedResource()
{
var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
DashboardInfoResponse = new GetDashboardInfoResponse
{
ApiBaseUrl = "http://localhost:5000",
ApiToken = "test-token",
DashboardUrls = ["http://localhost:18888"]
},
ResourceSnapshots =
[
new ResourceSnapshot
{
Name = ApiServiceName,
DisplayName = "API Service",
ResourceType = "Project",
State = "Running"
},
new ResourceSnapshot
{
Name = SecretServiceName,
DisplayName = "Secret Service",
ResourceType = "Project",
State = "Running",
Properties = new Dictionary<string, JsonNode?>
{
[KnownProperties.Resource.ExcludeFromMcp] = JsonValue.Create(true)
}
}
]
};
monitor.AddConnection("socket.hash1", connection);
return monitor;
}
private static (MockHttpClientFactory factory, MockHttpMessageHandler handler) CreateMockHttpWithLogs(params string[] serviceNames)
{
return CreateMockHttpWithLogs(serviceNames, returnedServiceNames: serviceNames, totalCount: serviceNames.Length, onRequest: null);
}
private static (MockHttpClientFactory factory, MockHttpMessageHandler handler) CreateMockHttpWithLogs(
string[] serviceNames,
string[] returnedServiceNames,
int totalCount,
Action<HttpRequestMessage>? onRequest)
{
var resources = serviceNames.Select(CreateResourceInfo).ToArray();
return CreateMockHttp(resources, CreateLogsResponse(totalCount, returnedServiceNames), onRequest);
}
private static ResourceInfoJson CreateResourceInfo(string name)
{
return new ResourceInfoJson { Name = name, HasLogs = true, HasTraces = true, HasMetrics = true };
}
private static TelemetryApiResponse CreateTracesResponse(int totalCount, params OtlpResourceSpansJson[] resourceSpans)
{
return new TelemetryApiResponse
{
Data = new OtlpTelemetryDataJson { ResourceSpans = resourceSpans },
TotalCount = totalCount,
ReturnedCount = totalCount
};
}
private static TelemetryApiResponse CreateLogsResponse(int totalCount, params string[] serviceNames)
{
var resourceLogs = serviceNames.Select(name => new OtlpResourceLogsJson
{
Resource = new OtlpResourceJson
{
Attributes = [new OtlpKeyValueJson { Key = "service.name", Value = new OtlpAnyValueJson { StringValue = name } }]
},
ScopeLogs =
[
new OtlpScopeLogsJson
{
Scope = new OtlpInstrumentationScopeJson { Name = "Microsoft.Extensions.Logging" },
LogRecords =
[
new OtlpLogRecordJson
{
TimeUnixNano = 1706540400000000000,
SeverityNumber = 9,
SeverityText = "Information",
Body = new OtlpAnyValueJson { StringValue = $"Log from {name}" },
Attributes = [new OtlpKeyValueJson { Key = OtlpHelpers.AspireLogIdAttribute, Value = new OtlpAnyValueJson { IntValue = 1 } }]
}
]
}
]
}).ToArray();
return new TelemetryApiResponse
{
Data = new OtlpTelemetryDataJson { ResourceLogs = resourceLogs },
TotalCount = totalCount,
ReturnedCount = resourceLogs.Length
};
}
private static (MockHttpClientFactory factory, MockHttpMessageHandler handler) CreateMockHttpWithTraces(params string[] serviceNames)
{
var resourceSpans = serviceNames.Select(name => new OtlpResourceSpansJson
{
Resource = new OtlpResourceJson
{
Attributes = [new OtlpKeyValueJson { Key = "service.name", Value = new OtlpAnyValueJson { StringValue = name } }]
},
ScopeSpans =
[
new OtlpScopeSpansJson
{
Scope = new OtlpInstrumentationScopeJson { Name = "TestScope" },
Spans =
[
new OtlpSpanJson
{
Name = $"GET /{name}",
TraceId = "abc123def456",
SpanId = "span123",
StartTimeUnixNano = 1706540400000000000,
EndTimeUnixNano = 1706540400100000000,
Kind = 2 // Server
}
]
}
]
}).ToArray();
var resources = serviceNames.Select(name => new ResourceInfoJson
{
Name = name,
InstanceId = null,
HasLogs = true,
HasTraces = true,
HasMetrics = true
}).ToArray();
return CreateMockHttp(resources, new TelemetryApiResponse
{
Data = new OtlpTelemetryDataJson { ResourceSpans = resourceSpans },
TotalCount = resourceSpans.Length,
ReturnedCount = resourceSpans.Length
});
}
private static OtlpResourceSpansJson[] CreateTraceWithExcludedFailingSpan()
{
return
[
CreateResourceSpans(ApiServiceName, new OtlpSpanJson
{
Name = "GET /orders",
TraceId = "abc123def456",
SpanId = "api-span",
StartTimeUnixNano = 1706540400000000000,
EndTimeUnixNano = 1706540400100000000,
Kind = 2
}),
CreateResourceSpans(SecretServiceName, new OtlpSpanJson
{
Name = "GET /secret",
TraceId = "abc123def456",
SpanId = "secret-span",
ParentSpanId = "api-span",
StartTimeUnixNano = 1706540400010000000,
EndTimeUnixNano = 1706540400090000000,
Kind = 2,
Status = new OtlpSpanStatusJson { Code = 2, Message = "secret failure" },
Events =
[
new OtlpSpanEventJson
{
Name = "exception",
TimeUnixNano = 1706540400090000000,
Attributes =
[
new OtlpKeyValueJson { Key = "exception.type", Value = new OtlpAnyValueJson { StringValue = "System.InvalidOperationException" } },
new OtlpKeyValueJson { Key = "exception.message", Value = new OtlpAnyValueJson { StringValue = "connection string contains a secret" } }
]
}
]
})
];
}
private static async Task<(CallToolResult result, List<string> requestedPaths)> GetTraceByIdAsync(OtlpResourceSpansJson[] resourceSpans)
{
var resources = new[] { ApiServiceName, SecretServiceName }
.Select(name => new ResourceInfoJson { Name = name, HasLogs = true, HasTraces = true, HasMetrics = true })
.ToArray();
var requestedPaths = new List<string>();
var (mockHttpClientFactory, _) = CreateMockHttp(
resources,
new TelemetryApiResponse
{
Data = new OtlpTelemetryDataJson { ResourceSpans = resourceSpans },
TotalCount = 1,
ReturnedCount = 1
},
request => requestedPaths.Add(request.RequestUri!.AbsolutePath));
var tool = CreateTracesTool(CreateMonitorWithDashboardAndExcludedResource(), mockHttpClientFactory);
var arguments = new Dictionary<string, JsonElement>
{
["traceId"] = JsonSerializer.SerializeToElement("abc123def456")
};
var result = await tool.CallToolAsync(CallToolContextTestHelper.Create(arguments), CancellationToken.None);
return (result, requestedPaths);
}
private static OtlpResourceSpansJson CreateResourceSpans(string serviceName, params OtlpSpanJson[] spans)
{
return new OtlpResourceSpansJson
{
Resource = new OtlpResourceJson
{
Attributes = [new OtlpKeyValueJson { Key = "service.name", Value = new OtlpAnyValueJson { StringValue = serviceName } }]
},
ScopeSpans = [new OtlpScopeSpansJson { Scope = new OtlpInstrumentationScopeJson { Name = "TestScope" }, Spans = spans }]
};
}
private static (MockHttpClientFactory factory, MockHttpMessageHandler handler) CreateMockHttp(
ResourceInfoJson[] resources,
TelemetryApiResponse apiResponseObj,
Action<HttpRequestMessage>? onRequest = null)
{
var apiResponse = JsonSerializer.Serialize(apiResponseObj, OtlpJsonSerializerContext.Default.TelemetryApiResponse);
var resourcesResponse = JsonSerializer.Serialize(resources, OtlpJsonSerializerContext.Default.ResourceInfoJsonArray);
var handler = new MockHttpMessageHandler(request =>
{
onRequest?.Invoke(request);
if (request.RequestUri?.AbsolutePath.Contains("/resources") == true)
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(resourcesResponse, System.Text.Encoding.UTF8, "application/json")
};
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(apiResponse, System.Text.Encoding.UTF8, "application/json")
};
});
return (new MockHttpClientFactory(handler), handler);
}
/// <summary>
/// Creates a dashboard that answers successive telemetry queries with <paramref name="responses"/>, where
/// <see langword="null"/> is a 404 response, and records the query string of each one.
/// </summary>
private static (MockHttpClientFactory factory, List<string> queries) CreateMockHttpWithTelemetryResponses(
ResourceInfoJson[] resources,
params TelemetryApiResponse?[] responses)
{
var queries = new List<string>();
var handler = new MockHttpMessageHandler(request =>
{
string json;
if (request.RequestUri!.AbsolutePath.EndsWith("/resources", StringComparison.Ordinal))
{
json = JsonSerializer.Serialize(resources, OtlpJsonSerializerContext.Default.ResourceInfoJsonArray);
}
else
{
queries.Add(request.RequestUri.Query);
if (responses[queries.Count - 1] is not { } response)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
json = JsonSerializer.Serialize(response, OtlpJsonSerializerContext.Default.TelemetryApiResponse);
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};
});
return (new MockHttpClientFactory(handler), queries);
}
private static ListStructuredLogsTool CreateStructuredLogsTool(
TestAuxiliaryBackchannelMonitor monitor,
IHttpClientFactory httpClientFactory)
{
IDashboardInfoProvider dashboardInfoProvider = new BackchannelDashboardInfoProvider(monitor, NullLogger<BackchannelDashboardInfoProvider>.Instance);
return new ListStructuredLogsTool(
dashboardInfoProvider,
monitor,
httpClientFactory,
NullLogger<ListStructuredLogsTool>.Instance);
}
private static ListTracesTool CreateTracesTool(
TestAuxiliaryBackchannelMonitor monitor,
IHttpClientFactory httpClientFactory)
{
IDashboardInfoProvider dashboardInfoProvider = new BackchannelDashboardInfoProvider(monitor, NullLogger<BackchannelDashboardInfoProvider>.Instance);
return new ListTracesTool(
dashboardInfoProvider,
monitor,
httpClientFactory,
NullLogger<ListTracesTool>.Instance);
}
private static ListTraceStructuredLogsTool CreateTraceStructuredLogsTool(
TestAuxiliaryBackchannelMonitor monitor,
IHttpClientFactory httpClientFactory)
{
IDashboardInfoProvider dashboardInfoProvider = new BackchannelDashboardInfoProvider(monitor, NullLogger<BackchannelDashboardInfoProvider>.Instance);
return new ListTraceStructuredLogsTool(
dashboardInfoProvider,
monitor,
httpClientFactory,
NullLogger<ListTraceStructuredLogsTool>.Instance);
}
}