Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
10 changes: 8 additions & 2 deletions src/Aspire.Cli/Commands/TelemetryCommandHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ public static async Task<DashboardApiResult> GetDashboardApiAsync(
var loginToken = McpToolHelpers.ExtractLoginToken(dashboardUrl);

// Normalize login URLs (e.g., http://localhost:18888/login?t=abc) to base URL
dashboardUrl = McpToolHelpers.StripLoginPath(dashboardUrl) ?? dashboardUrl;
dashboardUrl = McpToolHelpers.NormalizeDashboardUrl(McpToolHelpers.StripLoginPath(dashboardUrl) ?? dashboardUrl);

if (!UrlHelper.IsHttpUrl(dashboardUrl))
{
Expand Down Expand Up @@ -282,10 +282,16 @@ public static async Task<DashboardApiResult> GetDashboardApiAsync(
return new DashboardApiResult(true, connection, null, null, null, 0);
}

var apiBaseUrl = McpToolHelpers.NormalizeDashboardUrl(dashboardInfo.ApiBaseUrl);

// Extract dashboard base URL (without /login path) for hyperlinks
var extractedDashboardUrl = ExtractDashboardBaseUrl(dashboardInfo.DashboardUrls?.FirstOrDefault());
if (extractedDashboardUrl is not null)
{
extractedDashboardUrl = McpToolHelpers.NormalizeDashboardUrl(extractedDashboardUrl);
}

return new DashboardApiResult(true, connection, dashboardInfo.ApiBaseUrl, dashboardInfo.ApiToken, extractedDashboardUrl, 0);
return new DashboardApiResult(true, connection, apiBaseUrl, dashboardInfo.ApiToken, extractedDashboardUrl, 0);
}

/// <summary>
Expand Down
29 changes: 28 additions & 1 deletion src/Aspire.Cli/Mcp/Tools/McpToolHelpers.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.Web;
using Aspire.Cli.Backchannel;
using Microsoft.Extensions.Logging;
Expand All @@ -26,9 +27,14 @@ internal static class McpToolHelpers
throw new McpProtocolException(McpErrorMessages.DashboardNotAvailable, McpErrorCode.InternalError);
}

var apiBaseUrl = NormalizeDashboardUrl(dashboardInfo.ApiBaseUrl);
var dashboardBaseUrl = StripLoginPath(dashboardInfo.DashboardUrls.FirstOrDefault());
if (dashboardBaseUrl is not null)
{
dashboardBaseUrl = NormalizeDashboardUrl(dashboardBaseUrl);
}

return (dashboardInfo.ApiToken, dashboardInfo.ApiBaseUrl, dashboardBaseUrl);
return (dashboardInfo.ApiToken, apiBaseUrl, dashboardBaseUrl);
}

/// <summary>
Expand Down Expand Up @@ -59,6 +65,27 @@ internal static class McpToolHelpers
return url;
}

/// <summary>
/// Replaces AppHost-scoped <c>*.dev.localhost</c> dashboard hostnames with <c>localhost</c>.
/// </summary>
internal static string NormalizeDashboardUrl(string url)
{
if (Uri.TryCreate(url, UriKind.Absolute, out var uri) && IsDevLocalhost(uri.Host))
{
var port = uri.IsDefaultPort ? string.Empty : ":" + uri.Port.ToString(CultureInfo.InvariantCulture);
var pathAndQuery = uri.PathAndQuery == "/" ? string.Empty : uri.PathAndQuery;
return $"{uri.Scheme}://localhost{port}{pathAndQuery}{uri.Fragment}";
}

return url;
}

private static bool IsDevLocalhost(string host)
{
return host.Equals("dev.localhost", StringComparison.OrdinalIgnoreCase) ||
host.EndsWith(".dev.localhost", StringComparison.OrdinalIgnoreCase);
}

/// <summary>
/// Extracts the browser token (<c>t</c> query parameter) from a dashboard login URL.
/// Returns <c>null</c> if the URL does not contain a login token.
Expand Down
69 changes: 69 additions & 0 deletions tests/Aspire.Cli.Tests/Commands/TelemetryLogsCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Globalization;
using System.Net;
using System.Text.Json;
using Aspire.Cli.Backchannel;
using Aspire.Cli.Commands;
using Aspire.Cli.Resources;
using Aspire.Cli.Tests.TestServices;
Expand Down Expand Up @@ -34,6 +35,74 @@ public async Task TelemetryLogsCommand_WhenNoAppHostRunning_ReturnsSuccess()
Assert.Equal(ExitCodeConstants.Success, exitCode);
}

[Fact]
public async Task TelemetryLogsCommand_WithDevLocalhostDashboardApiUrl_UsesLocalhost()
{
using var workspace = TemporaryWorkspace.Create(outputHelper);
var outputWriter = new TestOutputTextWriter(outputHelper);
var requestedHosts = new List<string>();
var resourcesJson = JsonSerializer.Serialize(
new ResourceInfoJson[] { new() { Name = "redis", InstanceId = null } },
OtlpJsonSerializerContext.Default.ResourceInfoJsonArray);
var logsJson = BuildLogsJson(("redis", null, 9, "Information", "Ready to accept connections", s_testTime));

var monitor = new TestAuxiliaryBackchannelMonitor();
var connection = new TestAppHostAuxiliaryBackchannel
{
IsInScope = true,
AppHostInfo = new AppHostInformation
{
AppHostPath = Path.Combine(workspace.WorkspaceRoot.FullName, "TestAppHost", "TestAppHost.csproj"),
ProcessId = 1234
},
DashboardInfoResponse = new GetDashboardInfoResponse
{
ApiBaseUrl = "https://nextapp1.dev.localhost:64876",
ApiToken = "test-token",
DashboardUrls = ["https://nextapp1.dev.localhost:64876/login?t=test"],
IsHealthy = true
}
};
monitor.AddConnection("hash1", "socket.hash1", connection);

var handler = new MockHttpMessageHandler(request =>
{
requestedHosts.Add(request.RequestUri!.Host);

return request.RequestUri.AbsolutePath switch
{
"/api/telemetry/resources" => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(resourcesJson, System.Text.Encoding.UTF8, "application/json")
},
"/api/telemetry/logs" => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(logsJson, System.Text.Encoding.UTF8, "application/json")
},
_ => new HttpResponseMessage(HttpStatusCode.NotFound)
};
});

var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.AuxiliaryBackchannelMonitorFactory = _ => monitor;
options.OutputTextWriter = outputWriter;
options.DisableAnsi = true;
});
services.AddSingleton(handler);
services.Replace(ServiceDescriptor.Singleton<IHttpClientFactory>(new MockHttpClientFactory(handler)));

using var provider = services.BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("otel logs -n 5");

var exitCode = await result.InvokeAsync().DefaultTimeout();

Assert.Equal(ExitCodeConstants.Success, exitCode);
Assert.All(requestedHosts, host => Assert.Equal("localhost", host));
Assert.Contains(outputWriter.Logs, line => line.Contains("redis", StringComparison.Ordinal));
}

[Theory]
[InlineData(-1)]
[InlineData(0)]
Expand Down