Skip to content

MCP: compact default responses for list_traces, list_structured_logs, list_console_logs and list_resources - #22580

Open
Sébastien Ros (sebastienros) wants to merge 10 commits into
mainfrom
sebros/mcp-compact-telemetry-tools
Open

Sébastien Ros (sebastienros) wants to merge 10 commits into
mainfrom
sebros/mcp-compact-telemetry-tools

Conversation

@sebastienros

Copy link
Copy Markdown
Contributor

Description

The CLI MCP telemetry tools filled the 8k-token list budget on every call (list_traces {} ≈ 32 KB, list_structured_logs {} ≈ 33 KB, list_console_logs up to ≈ 35 KB, list_resources ≈ 10 KB), and search only changed which items filled the budget. Common agent harnesses spill tool results over ~20 KB to a file (Copilot CLI shows only the first 500 characters), so agents read these responses through extra file reads. This PR makes default responses compact and lets agents ask for less.

Part of epic #22511.

User-facing usage (MCP tool arguments)

  • list_traces: defaults to one summary per trace: traceId, title, timestamp, durationMs, spanCount, resources, hasError, rootSpan, slowestSpan (the child span with the most self time, plus its db.query.text/db.statement), firstErrorSpan (with status message and exception.type: exception.message), and dashboardUrl. New arguments:
    • limit (1–800, default 20): number of most recent traces to return.
    • traceId: returns every span of one trace from /api/telemetry/traces/{id}. Other filters are ignored.
    • format: summary (default) or full. full returns the previous per-span shape and keeps the previous 8k-token budget.
  • list_structured_logs: severity (minimum level: Trace…Critical, passed to the Dashboard API) and limit (1–800, default 50).
  • list_console_logs: limit (1–2000, default 100) and from: tail (default) or head for startup failures. head reads the whole stream, so it can report how many later lines it skipped.
  • list_resources: by default, commands are listed as { "state": ..., "has_arguments": true? }. The new includeCommandDetails: true argument restores descriptions and argument_inputs.

Example summary entry (from the new snapshot test):

{"traceId":"0af7…319c","title":"GET /orders","durationMs":1200,"spanCount":4,"resources":["frontend","api"],"hasError":true,
 "rootSpan":{"name":"GET /orders","kind":"Server","source":"frontend","durationMs":1200,"status":"Error","httpStatus":"500 Internal Server Error"},
 "slowestSpan":{"name":"postgres","kind":"Client","source":"api","durationMs":900,"status":"Ok","statement":"SELECT * FROM orders WHERE customer_id = $1"},
 "firstErrorSpan":{"name":"postgres","source":"api","durationMs":70,"status":"Error","statusMessage":"permission denied","statement":"UPDATE orders SET status = 'seen'","exception":"Npgsql.PostgresException: 25006: cannot execute UPDATE in a read-only transaction"}}

The default list responses (trace summaries, structured logs and console logs) now use a 4,096-token (~16 KB) budget, SharedAIHelpers.CompactListTokenLength. Tests check that 300 large traces and 800 large logs each stay under 20 KB. An invalid limit, format, severity, from or includeCommandDetails value returns InvalidParams instead of being silently ignored. SharedAIHelpers is compiled only into the CLI, so this does not affect the Dashboard. list_trace_structured_logs keeps its current limits.

Behavior changes

Validation

  • dotnet test --project tests/Aspire.Cli.Tests/Aspire.Cli.Tests.csproj --no-launch-profile -- --filter-namespace "Aspire.Cli.Tests.Mcp" --filter-not-trait "quarantined=true" --filter-not-trait "outerloop=true": passed (278 tests).
  • dotnet test --project tests/Aspire.Cli.Tests/Aspire.Cli.Tests.csproj --no-launch-profile -- --filter-class "*.Telemetry*" --filter-not-trait "quarantined=true" --filter-not-trait "outerloop=true": passed (636 tests).
  • Not run: a live measurement against a running app.

Fixes #22507

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
      • If yes, did you have an API Review for it?
        • Yes
        • No
      • Did you add <remarks /> and <code /> elements on your triple slash comments?
        • Yes
        • No
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
      • If yes, have you done a threat model and had a security review?
        • Yes
        • No
    • No

list_traces now returns one summary per trace (root span, slowest span by
self time with its database statement, first failed span) and accepts limit,
traceId and format: full. list_structured_logs accepts limit and severity,
list_console_logs accepts limit and from (tail/head), and list_resources
omits command descriptions and argument inputs unless includeCommandDetails
is set. Default list responses use a ~16 KB token budget so they stay under
common agent harness spill limits.

Fixes #22507

Co-authored-by: Copilot App <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 22580

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 22580"

@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Log and trace limits can discard the newest records or earlier replica startup failures because trimming follows grouping or arrival order rather than timestamp order.

5 open issues
What changed in this PR

This PR makes Aspire CLI MCP telemetry responses more compact, reducing the need for agent harnesses to spill results to files. It addresses #22507 within the agent-facing improvements tracked by #22511.

Changes:

  • Defaults trace listings to summaries, with explicit full-format and single-trace detail options.
  • Adds count limits, structured-log severity filtering, console-log head/tail selection, and smaller default response budgets.
  • Makes resource command details opt-in and adds behavior tests and snapshots.
File Description
tests/​Aspire.Cli.Tests/​Snapshots/​ListTracesToolTests.ListTracesTool_SummarizesEachTrace_ByDefault.verified.txt Captures the default trace summary shape.
tests/​Aspire.Cli.Tests/​Snapshots/​ListResourcesToolTests.ListResourcesTool_ReturnsOnlyBoundedResourceDataAndSanitizedUrls.verified.json Reflects compact command metadata.
tests/​Aspire.Cli.Tests/​Snapshots/​ListResourcesToolTests.ListResourcesTool_PreservesCrossPageRelationshipsAndHiddenReplicaIdentity.verified.txt Adds command-detail opt-in guidance.
tests/​Aspire.Cli.Tests/​Snapshots/​ListResourcesToolTests.ListResourcesTool_DescribesPaginationInputs.verified.json Records the new command-details argument.
tests/​Aspire.Cli.Tests/​Mcp/​ListTracesToolTests.cs Tests summaries, limits, detail retrieval, and validation.
tests/​Aspire.Cli.Tests/​Mcp/​ListStructuredLogsToolTests.cs Tests severity filtering, limits, and response size.
tests/​Aspire.Cli.Tests/​Mcp/​ListResourcesToolTests.cs Tests compact and detailed command listings.
tests/​Aspire.Cli.Tests/​Mcp/​ListConsoleLogsToolTests.cs Tests head/tail selection, limits, and validation.
src/​Shared/​ConsoleLogs/​SharedAIHelpers.cs Adds trace summaries and configurable response budgets.
src/​Aspire.Cli/​Mcp/​Tools/​McpToolHelpers.cs Adds shared argument parsing and validation.
src/​Aspire.Cli/​Mcp/​Tools/​ListTraceStructuredLogsTool.cs Preserves existing limits through explicit arguments.
src/​Aspire.Cli/​Mcp/​Tools/​ListTracesTool.cs Adds summary/full modes, limits, and trace-ID lookup.
src/​Aspire.Cli/​Mcp/​Tools/​ListStructuredLogsTool.cs Adds severity and count controls with compact output.
src/​Aspire.Cli/​Mcp/​Tools/​ListResourcesTool.cs Makes command descriptions and inputs opt-in.
src/​Aspire.Cli/​Mcp/​Tools/​ListConsoleLogsTool.cs Adds bounded head/tail responses.

Review effort: Balanced

@sebastienros
Sébastien Ros (sebastienros) marked this pull request as draft November 23, 2026 21:09
@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

… time

- list_structured_logs and list_traces sort records/traces by time before
  applying limits, so interleaved resources don't drop the newest items.
- list_console_logs from: head keeps the earliest lines by parsed timestamp
  across interleaved replica streams.
- Trace summary self time subtracts the union of child intervals, and the
  summary title is length-limited like rootSpan.name.

Co-authored-by: Copilot App <[email protected]>
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The reduced budget can cause an attribute-rich newest log to yield an empty result and hide earlier logs, requiring bounded optional attributes and a regression test.

1 open issue
5 resolved since last review

Review effort: Balanced

A single log with many large attributes could exceed the list budget and
hide every log. Attribute values of such entries are shortened and extra
attributes dropped, keeping message, severity and identifiers, and the
entry is marked attributesTruncated.

Co-authored-by: Copilot App <[email protected]>
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Unresolved budget and log-selection defects can exceed response size limits, suppress valid entries, misorder filtered logs, and leave dangling duplicate references.

No open issues 🎉

5 previously missed issues

In code that hasn't changed since last review

Medium severity Preserve timestamp context when filtering lines for head results

src/​Aspire.Cli/​Mcp/​Tools/​ListConsoleLogsTool.cs:117

With from: "head" and a search filter, dropping nonmatching lines before InsertSorted loses the timestamp anchors needed to order untimestamped continuation lines. For example, an unmatched 00:00:03 line followed by a matching untimestamped line from replica A is retained ahead of replica B's matching 00:00:01 failure when limit: 1. Preserve the nonmatching ordering context while selecting the earliest matches, and add a mixed-timestamp, interleaved-replica regression test.

Medium severity Prevent dangling duplicate references in compact responses

src/​Aspire.Cli/​Mcp/​Tools/​ListStructuredLogsTool.cs:133

The compact budget can return dangling Duplicate of ... references because GetLimitFromEndWithSummary deduplicates entries before removing older entries to meet the token limit. Nine distinct 2,048-character messages followed by a repeat of the first fit the old budget, but the compact budget drops the original while retaining the newest message's reference to it. Coordinate entry selection with deduplication, or regenerate retained entries with a fresh context and recheck their size; add a regression where the referenced entry falls outside the budget.

Medium severity Enforce the response budget using serialized UTF-8 bytes

src/​Shared/​ConsoleLogs/​SharedAIHelpers.cs:38

This budget still uses EstimateTokenCount, which counts UTF-16 characters rather than UTF-8 bytes. With relaxed JSON escaping, nine distinct 1,500-character CJK log messages fit within the 4,096-token estimate but produce roughly 42 KB of UTF-8 output, exceeding the advertised 20 KB target. Add a serialized-byte limit alongside the token budget, and cover non-ASCII payloads with Encoding.UTF8.GetByteCount assertions; the current ASCII-only text.Length checks cannot catch this.

Medium severity Bound summary resources without dropping older traces

src/​Shared/​ConsoleLogs/​SharedAIHelpers.cs:248

The summary's resource array is unbounded: 300 distinct 64-character resource names exceed the compact budget by themselves. If that trace is newest, GetLimitFromEndWithSummary stops immediately and returns an empty list, hiding older traces too—even with limit: 1. Bound the resource list's serialized size and report omitted resources while retaining the trace ID and diagnostic summary so callers can request full detail.

Medium severity Budget attributes by their escaped serialized size

src/​Shared/​ConsoleLogs/​SharedAIHelpers.cs:1070

The attribute budget counts unescaped strings, but the list budget counts serialized JSON: seven distinct 512-character values containing control characters can bypass attribute truncation yet serialize beyond the compact budget. When that log is newest, the entire list becomes [], although the entry fit the previous budget. Measure escaped attribute keys and values using the output serializer, and add a compact-response regression test for this case.

1 resolved since last review

Review effort: Balanced

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

- Budget by serialized UTF-8 bytes, including JSON escapes, so non-ASCII
  and control characters can't exceed the ~16 KB compact budget.
- Convert newest items first so deduplication references always point to
  an entry that is returned.
- Bound trace summary resources (reporting resourcesOmitted) and span
  summary strings, and bound log message/exception/attributes by
  serialized size, so the newest item can't empty the list.
- list_console_logs from: head anchors untimestamped lines to their
  replica's previous timestamp before applying search.

Co-authored-by: Copilot App <[email protected]>
@sebastienros

Copy link
Copy Markdown
Contributor Author

Addressed the five findings from review 6044739693 in 0e01939:

  • Head results with search (ListConsoleLogsTool): every line now gets its sort key before filtering. An untimestamped line uses the latest timestamp from the same replica, and ties keep arrival order. Only the limit earliest matches are kept, so memory is bounded. Added the mixed-timestamp, interleaved-replica regression.
  • Dangling duplicate references: GetLimitFromEndWithSummary now converts items newest to oldest. A repeated value is written in full in the newest entry that has it, and older entries refer to that newer entry. Because the returned entries are always the newest ones, the referenced entry is always returned. Added a regression where the original entry falls outside the budget.
  • UTF-8 budget: EstimateTokenCount and EstimateSerializedJsonTokenSize now count serialized UTF-8 bytes. Log message and exception are each bounded by their serialized size. The tests use Encoding.UTF8.GetByteCount with CJK payloads for logs and traces.
  • Summary resources: capped at 16 names of at most 128 bytes, with resourcesOmitted reporting how many were dropped. Span source and destination are bounded as well, so a summary stays well under the budget. Trace and span IDs are kept whole so callers can request full detail. Added a 300-resource regression.
  • Escaped attribute size: attributes are measured by their escaped, serialized size with the output encoder, both when deciding whether to truncate and when adding up the budget. Added a control-character regression.

@aspire-repo-bot
aspire-repo-bot Bot requested a balanced review from Copilot November 24, 2026 20:00
…tail unbounded

- list_traces always removes spans of ExcludeFromMcp resources, including
  resource-filtered lists, since the API returns whole traces.
- traceId selects detail mode before list-only options are parsed; a
  whitespace-only or non-string traceId is rejected.
- Per-field bounding of structured log entries is opt-in, so
  list_trace_structured_logs keeps full entries.
- Bound attribute keys in compact duplicate references and truncated
  attributes so references never exceed the values they replace.

Co-authored-by: Copilot App <[email protected]>
@aspire-repo-bot
aspire-repo-bot Bot requested a balanced review from Copilot November 25, 2026 16:23
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because regression tests do not cover MCP exclusions in the new trace-detail path, leaving its privacy boundary unverified.

No open issues 🎉

Review effort: Balanced

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Attribute-key truncation can create ambiguous value references, while trace detail responses omit exception events and lack regression coverage for excluded spans.

3 open issues

Review effort: Balanced

- Attributes with keys longer than the reference cap are written as capped
  values and never deduplicated, so references always name exact keys.
- list_traces with traceId includes span events, so the full exception
  message and stack trace are available on drill-down.
- Add exclusion tests for the traceId detail path.

Co-authored-by: Copilot App <[email protected]>
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The trace-ID detail response still truncates long exception messages and stack traces through a processing PromptContext; it needs a non-processing context and a regression test exceeding 2,048 characters.

1 open issue
3 resolved since last review

Review effort: Balanced

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

Exception messages and stack traces recorded as span events are written
without the prompt context's length cap and duplicate-line removal, so
drilling down from a truncated summary returns the full exception.

Co-authored-by: Copilot App <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

Tests selector

2 / 101 PR test projects · 4 PR jobs, from 17 changed files.

Selected PR test projects (2 / 101)

Aspire.Cli.EndToEnd.Tests, Aspire.Cli.Tests

Selected PR jobs (4)

cli-starter-validation, extension-e2e, polyglot, typescript-api-compat


How these were chosen — grouped by what changed

📦 affected project Aspire.Cli
→ 1 test: Aspire.Cli.EndToEnd.Tests

🧪 tests/Aspire.Cli.Tests/Mcp/ExcludeFromMcpTests.cs (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Mcp/ListConsoleLogsToolTests.cs (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Mcp/ListResourcesToolTests.cs (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Mcp/ListStructuredLogsToolTests.cs (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Mcp/ListTraceStructuredLogsToolTests.cs (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Mcp/ListTracesToolTests.cs (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Snapshots/ListResourcesToolTests.ListResourcesTool_DescribesPaginationInputs.verified.json (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Snapshots/ListResourcesToolTests.ListResourcesTool_PreservesCrossPageRelationshipsAndHiddenReplicaIdentity.verified.txt (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Snapshots/ListResourcesToolTests.ListResourcesTool_ReturnsOnlyBoundedResourceDataAndSanitizedUrls.verified.json (changed test)
→ 1 directly: Aspire.Cli.Tests

🧪 tests/Aspire.Cli.Tests/Snapshots/ListTracesToolTests.ListTracesTool_SummarizesEachTrace_ByDefault.verified.txt (changed test)
→ 1 directly: Aspire.Cli.Tests

Job reasons

Job Triggered by
cli-starter-validation affected project Aspire.Cli
extension-e2e • src/Aspire.Cli/Mcp/Tools/ListConsoleLogsTool.cs, src/Aspire.Cli/Mcp/Tools/ListResourcesTool.cs, src/Aspire.Cli/Mcp/Tools/ListStructuredLogsTool.cs, src/Aspire.Cli/Mcp/Tools/ListTraceStructuredLogsTool.cs, src/Aspire.Cli/Mcp/Tools/ListTracesTool.cs, src/Aspire.Cli/Mcp/Tools/McpToolHelpers.cs
• affected project Aspire.Cli
polyglot affected project Aspire.Cli
typescript-api-compat affected project Aspire.Cli

Selection computed for commit 7973b04.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because deduplication can undermine size checks and hide older logs, while truncation at emoji boundaries can fail the entire tool call.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP: list_traces and list_structured_logs fill the 8k-token budget on every call, and search does not shrink them

3 participants