File: Mcp\Tools\ListStructuredLogsTool.cs
Web Access
Project: src\src\Aspire.Cli\Aspire.Cli.csproj (aspire)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using System.Text.Json;
using Aspire.Cli.Backchannel;
using Aspire.Cli.Commands;
using Aspire.Dashboard.Otlp.Model;
using Aspire.Dashboard.Utils;
using Aspire.Shared.ConsoleLogs;
using Microsoft.Extensions.Logging;
using ModelContextProtocol;
using ModelContextProtocol.Protocol;
 
namespace Aspire.Cli.Mcp.Tools;
 
/// <summary>
/// MCP tool for listing structured logs.
/// Gets log data directly from the Dashboard telemetry API.
/// </summary>
internal sealed class ListStructuredLogsTool(IDashboardInfoProvider dashboardInfoProvider, IAuxiliaryBackchannelMonitor? auxiliaryBackchannelMonitor, IHttpClientFactory httpClientFactory, ILogger<ListStructuredLogsTool> logger) : CliMcpTool
{
    internal const int DefaultLimit = 50;
 
    // Minimum severities accepted by the Dashboard telemetry API, which parses them as Microsoft.Extensions.Logging.LogLevel.
    private static readonly string[] s_severities = ["Trace", "Debug", "Information", "Warning", "Error", "Critical"];
 
    private static readonly JsonElement s_inputSchema = JsonDocument.Parse(
        $$"""
        {
          "type": "object",
          "properties": {
            "resourceName": {
              "type": "string",
              "description": "The resource name. This limits logs returned to the specified resource. If no resource name is specified then structured logs for all resources are returned."
            },
            "search": {
              "type": "string",
              "description": "Full-text search to filter logs. Searches across log text, attribute values, names, source, IDs, and other fields."
            },
            "severity": {
              "type": "string",
              "enum": [{{string.Join(", ", s_severities.Select(static s => $"\"{s}\""))}}],
              "description": "Minimum severity of the logs to return. For example, 'Warning' returns Warning, Error and Critical logs."
            },
            "limit": {
              "type": "integer",
              "minimum": 1,
              "maximum": {{SharedAIHelpers.StructuredLogsLimit}},
              "default": {{DefaultLimit}},
              "description": "Maximum number of the most recent log entries to return. Responses are also capped by size."
            }
          }
        }
        """).RootElement;
 
    public override string Name => KnownMcpTools.ListStructuredLogs;
 
    public override string Description => "List structured logs for resources. Returns the most recent log entries; use severity, search, resourceName and limit to narrow the results.";
 
    public override JsonElement GetInputSchema()
    {
        return s_inputSchema;
    }
 
    public override async ValueTask<CallToolResult> CallToolAsync(CallToolContext context, CancellationToken cancellationToken)
    {
        var arguments = context.Arguments;
 
        // Validate arguments before contacting the dashboard so invalid input is reported as such.
        var resourceName = McpToolHelpers.GetOptionalString(arguments, "resourceName");
        var search = McpToolHelpers.GetOptionalString(arguments, "search");
        var severity = McpToolHelpers.GetOptionalChoice(arguments, "severity", s_severities, defaultValue: null);
        var limit = McpToolHelpers.GetOptionalInt32(arguments, "limit", minimum: 1, maximum: SharedAIHelpers.StructuredLogsLimit, defaultValue: DefaultLimit);
 
        var (apiToken, apiBaseUrl, dashboardBaseUrl) = await dashboardInfoProvider.GetDashboardInfoAsync(cancellationToken).ConfigureAwait(false);
 
        try
        {
            using var client = TelemetryCommandHelpers.CreateApiClient(httpClientFactory, apiToken);
 
            // Resolve resource name to specific instances (handles replicas)
            var resources = await TelemetryCommandHelpers.GetAllResourcesAsync(client, apiBaseUrl, cancellationToken).ConfigureAwait(false);
            var excludedNames = auxiliaryBackchannelMonitor is not null
                ? await McpToolHelpers.GetExcludedResourceNamesAsync(auxiliaryBackchannelMonitor, cancellationToken).ConfigureAwait(false)
                : [];
 
            // If a specific resource was requested, check if it's excluded from MCP.
            if (!string.IsNullOrEmpty(resourceName) && McpToolHelpers.CheckResourceExcluded(excludedNames, resourceName) is { } excludedResult)
            {
                return excludedResult;
            }
 
            // If a resource was specified but not found, return error
            if (!TelemetryCommandHelpers.TryResolveResourceNames(resourceName, resources, out var resolvedResources))
            {
                return new CallToolResult
                {
                    Content = [new TextContentBlock { Text = $"Resource '{resourceName}' not found." }],
                    IsError = true
                };
            }
 
            // Without a requested resource, query only the resources that are not excluded from MCP, so the
            // dashboard applies the limit to the logs that can be returned.
            var query = McpToolHelpers.GetTelemetryListQuery(resolvedResources, resources, excludedNames, limit);
 
            // Only the requested number of the latest logs is fetched. The response size budget is applied below, and
            // the API's total count of matching logs reports how many were not returned.
            var (resourceLogs, totalCount) = await McpToolHelpers.GetTelemetryListAsync(
                client,
                query,
                "structured logs",
                (queryResources, queryLimit) => DashboardUrls.TelemetryLogsApiUrl(apiBaseUrl, queryResources, severity: severity, limit: queryLimit, search: search),
                data => data?.ResourceLogs,
                // The query already left out excluded resources. Filter the response as well so logs from an excluded
                // resource are never returned, for example from a resource that first sent telemetry after the
                // resources were listed, when the query had no resource filter.
                logs => logs is not null && string.IsNullOrEmpty(resourceName) && excludedNames.Count > 0
                    ? logs.Where(rl => rl.Resource?.GetServiceName() is not { } name || !excludedNames.Contains(name)).ToArray()
                    : logs,
                // Every log of a removed resource is removed with it, so counting the resources detects a removed log.
                logs => logs?.Count ?? 0,
                logger,
                cancellationToken).ConfigureAwait(false);
 
            var (logsData, limitMessage) = SharedAIHelpers.GetStructuredLogsJson(
                resourceLogs,
                totalCount,
                limit,
                SharedAIHelpers.CompactListTokenLength,
                boundEntryFields: true,
                getResourceName: s => OtlpHelpers.GetResourceName(s, resources.Select(r => new SimpleOtlpResource(r.Name, r.InstanceId)).ToList()),
                dashboardBaseUrl: dashboardBaseUrl);
 
            var text = $"""
                {limitMessage}
 
                # STRUCTURED LOGS DATA
 
                {logsData}
                """;
 
            return new CallToolResult
            {
                Content = [new TextContentBlock { Text = text }]
            };
        }
        catch (HttpRequestException ex)
        {
            logger.LogError("Failed to fetch structured logs from Dashboard API");
            var errorMessage = dashboardInfoProvider.IsDirectConnection
                ? await TelemetryCommandHelpers.GetDashboardApiErrorMessageAsync(ex, apiBaseUrl, httpClientFactory, logger, cancellationToken)
                : "Failed to fetch structured logs from the Dashboard API.";
            throw new McpProtocolException(errorMessage, McpErrorCode.InternalError);
        }
    }
}