Skip to content

feat(mcp): expose AI agent sessions on the MCP - #867

Merged
JeremyFunk merged 1 commit into
feat/ai-session-readsfrom
feat/mcp-agent-sessions
Sep 13, 2026
Merged

feat(mcp): expose AI agent sessions on the MCP#867
JeremyFunk merged 1 commit into
feat/ai-session-readsfrom
feat/mcp-agent-sessions

Conversation

@JeremyFunk

@JeremyFunk JeremyFunk commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator

Summary

Second of three PRs splitting the original version of this PR. Stacked on #875 (the reads lift); tool health follows in #876.

Two read-only MCP tools over the Agent Sessions page's model, plus an AI decode inside the existing inspect_span:

  • list_agent_sessions — the ranked list with the page's filters (vendor/service/environment/model/agent/tool, id search, error/duration/cost/token/call ranges), sort and paging. Bounds accept numbers or numeric strings and reject out-of-range values as parameter errors; limit/offset are clamped like every other tool; a full page says which offset continues it. Each row's next-step line prints the padded window get_agent_session should be given.
  • get_agent_session — the Overview: verdict and findings, wall clock/active/idle, agent time and peak parallelism, tokens, cost, models, tools, failure groups, turns. Reads the same padded window the page reads, so its numbers match the page. Loads up to 10 000 spans, clipping each span's captured content as it is mapped (message histories keep the newest user message and the last message, strings cut to 500 chars, tool payloads keep their shape with strings cut to 1 000). On a 413 it halves the page and retries down to 125 spans; if it still cannot load, it says which spans it has and prints the timestamp to resume from. Past the cap it says so.
  • inspect_span decodes an AI span above its raw attributes: the messages it captured and the tool calls it made or executed, results resolved from the rest of its trace. A timestamp hint skips the trace-window lookup and reads an hour back and a day ahead; a longer trace pages and says so. Decode failures are contained: the raw attributes are always returned.

Both new tools return text only. No __maple_ui mirror: nothing renders one yet, and the mirror is a second copy of the answer in the model's context.

How

  • packages/agent-sessions (@maple/agent-sessions): the session derivations the page runs client-side (turns, summary, findings, transcript, span detail, the read-window padding) lifted out of apps/web/src/lib/agent-sessions/ so the API renders the same model the page does. Move plus the lint conversions packages/* requires (no non-null assertions, no try/catch); 225 package tests moved with it. Test-only span builders and the lab fixture ship behind a ./testing subpath.
  • The four formatters those derivations bake into their output (formatDuration, formatNumber, formatSessionDuration, formatCurrency) move to @maple/domain/format; @maple/ui re-exports them and the web imports them directly. Locale handling is unchanged from main.
  • The three browser-replay session tools now say they are browser replays and point at list_agent_sessions.

Dropped from the original version on review: list_agent_session_spans (for trace-keyed sessions it was inspect_trace with a flat table; the other sessions are covered by get_agent_session + inspect_span), the retained-content budget and the exact-totals second read behind it, the structured mirrors and their 290 lines of domain types.

Test plan

  • bun run --cwd packages/agent-sessions test (225)
  • bun run --cwd apps/ai test src/mcp (418, includes registry invariants, the inspect_span decode/containment regressions, cap and 413-retry cases through get_agent_session)
  • bun run --cwd packages/ui test src/lib/__tests__/format (33)
  • bun run --cwd apps/web test src/components/agent-sessions src/lib/agent-sessions src/routes/agent-sessions src/lab src/hooks/use-session-spans.test.tsx (276)
  • tsc --noEmit in apps/ai, packages/domain, packages/agent-sessions
  • Effect v4 review (7 reviewers), adversarial review, simplification pass; findings applied
  • CI (runs once refactor(api): lift the AI session reads into @maple/backend #875 merges and this retargets to main)

@coderabbitai

coderabbitai Bot commented Sep 12, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change adds a shared agent-session package, tenant-scoped warehouse reads, five MCP tools, AI span decoding, tool analytics, structured outputs, tests, documentation, and application integrations.

Changes

AI agent observability

Layer / File(s) Summary
Shared session model and contracts
packages/agent-sessions/*, packages/domain/src/mcp-structured-types.ts
Adds shared formatting, span parsing, turn analysis, findings, summaries, transcripts, fixtures, tests, and structured MCP output types.
Tenant-scoped warehouse reads
apps/api/src/services/ai-sessions/ai-session-reads.ts, apps/api/src/routes/internal/ai-sessions.http.ts
Moves session, span, summary, tool, and error reads into reusable tenant-scoped service functions used by HTTP and MCP callers.
Agent session MCP tools
apps/api/src/mcp/tools/list-agent-sessions.ts, apps/api/src/mcp/tools/get-agent-session.ts, apps/api/src/mcp/tools/list-agent-session-spans.ts, apps/api/src/mcp/tools/inspect-span.ts, apps/api/src/mcp/lib/agent-sessions.ts
Adds session listing, session details, span listing, and AI span inspection with window resolution, pagination, payload clipping, truncation handling, and follow-up guidance.
AI span decoding
apps/api/src/mcp/lib/render-ai-span.ts, apps/api/src/mcp/tools/inspect-span.ts, apps/api/src/mcp/__evals__/*
Detects AI spans, decodes messages and tool calls, returns structured AI data, and tests decoded, ordinary, and partially read traces.

Agent tool analytics

Layer / File(s) Summary
Analytics contracts and shared rendering
apps/api/src/mcp/lib/agent-tool-analytics.ts, packages/domain/src/mcp-structured-types.ts
Adds shared selection, window, formatting, bucket, and trend-grid helpers plus structured analytics data types.
Overview and failure detail tools
apps/api/src/mcp/tools/get-agent-tools-overview.ts, apps/api/src/mcp/tools/get-agent-tool-error.ts
Adds aggregate tool-health metrics, failure groups, trends, error details, samples, payload limits, pagination, and next-step suggestions.
Analytics validation and fixtures
apps/api/src/mcp/tools/__tests__/agent-tools.test.ts, apps/api/src/mcp/__evals__/fake-warehouse.ts
Adds warehouse fixtures and coverage for registration, validation, metrics, trends, pagination, payload clipping, filtering, and empty results.

Application integration

Layer / File(s) Summary
Tool registration and guidance
apps/api/src/mcp/tools/registry.ts, apps/api/src/mcp/resources/instructions.ts, apps/landing/src/content/docs/mcp.md, apps/slack-agent/agent/lib/action-status.ts
Registers the five tools and updates MCP guidance, documentation, and Slack status phrases.
Shared package consumers
apps/api/package.json, apps/web/package.json, apps/web/src/components/agent-sessions/*, apps/web/src/lib/agent-sessions/*, apps/web/src/lab/*, apps/web/src/routes/agent-sessions/$sessionId.tsx
Adds workspace dependencies and repoints web agent-session imports to @maple/agent-sessions.
Tool metadata and browser-session descriptions
apps/web/src/components/ai-elements/tool-metadata.ts, apps/api/src/mcp/tools/get-session-traces.ts, apps/api/src/mcp/tools/get-session-transcript.ts, apps/api/src/mcp/tools/search-sessions.ts
Removes metadata for retired agent-session tools and distinguishes browser session replay tools from AI agent-session tools.

Priority: ➖ Normal

Estimated code review effort: 5 (Critical) | ~90 minutes

Change: Feature

Merge Risk: 🟡 Moderate · up to e7307

Oversized sessions can lose useful span output or consume excessive worker memory, while some analytics output can be incomplete or malformed. The lint failure and material runtime concerns should be resolved before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 56.10% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 41 functions across 60 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the primary change: exposing AI agent sessions through the MCP server. It is concise and specific.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/mcp-agent-sessions

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@JeremyFunk
JeremyFunk marked this pull request as ready for review September 12, 2026 02:28
coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@JeremyFunk
JeremyFunk force-pushed the feat/mcp-agent-sessions branch from 57979e6 to 17a502c Compare September 13, 2026 13:23
@JeremyFunk JeremyFunk changed the title feat(mcp): expose AI agent sessions and agent tool health on the MCP feat(mcp): expose AI agent sessions on the MCP Sep 13, 2026
@JeremyFunk
JeremyFunk changed the base branch from main to feat/ai-session-reads September 13, 2026 13:23
@JeremyFunk
JeremyFunk force-pushed the feat/mcp-agent-sessions branch from 17a502c to aceed9e Compare September 13, 2026 13:24

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Devin Review found 2 potential issues.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

Comment on lines +160 to +161
const lines: string[] = [
`## AI agent sessions (showing ${offset + 1}–${offset + sessions.length})`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Full pages hide remaining sessions

When list_agent_sessions fills limit, its response provides no next offset or continuation signal. Agents cannot discover later matching sessions.

Learn more

The tool accepts offset and describes itself as paged, but its result only prints the current range. A full page is ambiguous because the list read returns at most limit rows and exposes no total. Other MCP list tools explicitly tell the agent when and how to continue.

Example: With limit=25 and 40 matches, the first response says showing 1–25 but never supplies offset=25. An agent can treat those 25 sessions as the complete result and omit the remaining 15.

Recommended fix: Fetch or expose enough paging metadata to detect another row, then append a continuation message containing offset + page.ranked. Keep the paging calculation based on ranked, matching the ListAiSessionsResponse contract.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread apps/ai/src/mcp/lib/agent-sessions.ts Outdated
Comment on lines +82 to +84
genAi[field] = Array.isArray(value)
? keptMessages(value).map((message) => clipStrings(message, MESSAGE_TEXT_CHARS))
: clipStrings(value, PAYLOAD_TEXT_CHARS)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Array payloads lose most entries

When any JSON payload is an array, clipSpanContent keeps only message-history entries. Tool results and other array payloads lose earlier entries.

Learn more

The JSON field catalog includes message histories and unrelated payloads such as toolCallResult, toolDefinitions, retrievalDocuments, and memoryRecords. keptMessages is valid only for message-history fields. Applying it based solely on Array.isArray changes the semantic shape of every other array payload before session findings run.

Example: A failed tool result captured as [{"error":"first failure"},{"retry":"also failed"}] becomes only {"retry":"also failed"}. The session report can omit the actual failure even though it was loaded.

Recommended fix: Apply keptMessages only to the catalog fields that represent message histories. Preserve every element of other JSON arrays and recursively clip their strings with the payload budget.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@JeremyFunk
JeremyFunk force-pushed the feat/mcp-agent-sessions branch from aceed9e to 1370556 Compare September 13, 2026 13:52
@JeremyFunk
JeremyFunk force-pushed the feat/mcp-agent-sessions branch 3 times, most recently from 0d3fb9e to 0e648f5 Compare September 13, 2026 14:59
@JeremyFunk
JeremyFunk added this pull request to stack #880 September 13, 2026 17:57
Comment thread apps/ai/src/mcp/lib/format.ts Fixed
@JeremyFunk
JeremyFunk force-pushed the feat/mcp-agent-sessions branch from 0e648f5 to 4590a84 Compare September 13, 2026 18:31
Two read-only tools over the Agent Sessions page's model, plus an AI decode
inside inspect_span:

- list_agent_sessions: the ranked list with the page's filters, sort and paging.
- get_agent_session: the Overview — verdict and findings, wall clock/active/idle,
  agent time and peak parallelism, tokens, cost, models, tools, failure groups,
  turns. Loads up to 10 000 spans with each span's captured content clipped
  (newest user message + last message, strings cut to 500 chars, tool payloads
  to 1 000 per string); past the cap or a 413 it says so and covers what loaded.
- inspect_span decodes an AI span above its raw attributes: the messages it
  captured and the tool calls it made or executed, results resolved from the
  rest of its trace.

The session derivations the page runs client-side (turns, summary, findings,
transcript, span detail) move from apps/web/src/lib/agent-sessions into
packages/agent-sessions so the API renders the same model the page does; the
four formatters they bake into their output move to @maple/domain/format with
@maple/ui and the web re-exporting them. Test-only span builders and the lab
fixture ship behind a ./testing subpath.

The browser-replay session tools now say so and point at list_agent_sessions.
@JeremyFunk
JeremyFunk force-pushed the feat/mcp-agent-sessions branch from 4590a84 to bbb4515 Compare September 13, 2026 18:40
@JeremyFunk
JeremyFunk merged commit 2981fc0 into main Sep 13, 2026
48 checks passed
@JeremyFunk
JeremyFunk deleted the feat/mcp-agent-sessions branch September 13, 2026 18:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants