Skip to content

LLM MCP Flow#1321

Merged
aadesh18 merged 52 commits intodevfrom
llm-mcp-flow
Apr 15, 2026
Merged

LLM MCP Flow#1321
aadesh18 merged 52 commits intodevfrom
llm-mcp-flow

Conversation

@aadesh18
Copy link
Copy Markdown
Contributor

@aadesh18 aadesh18 commented Apr 10, 2026

Summary by CodeRabbit

  • New Features

    • Automated AI QA review pipeline and human-verified knowledge base consulted first
    • Internal MCP review tool: call log viewer, conversation replay, add/edit/publish Q&A, knowledge editor, and analytics
    • Docs search now preserves follow-up conversation context
  • Documentation

    • Added “Ask DeepWiki” badge to README
  • Chores

    • Added local SpacetimeDB background service and internal-tool app scaffolding

mantrakp04 and others added 15 commits March 23, 2026 10:48
- Added new internal API endpoint for documentation tools, allowing actions such as listing available docs, searching, and fetching specific documentation by ID.
- Updated environment configuration to support optional internal secret for enhanced security.
- Refactored existing search functionality to utilize the new docs tools API instead of the previous MCP server.
- Improved error handling and response parsing for documentation-related requests.
- Expanded documentation to clarify the relationship between the new tools and existing API functionalities.

This update streamlines the documentation access process and enhances the overall developer experience.
- Introduced error capturing for failed HTTP requests in the docs tools API, improving debugging capabilities.
- Updated the API response for unsupported methods to include an 'Allow' header, clarifying the expected request type.

These changes enhance the robustness of the documentation tools integration and improve developer experience.
- Updated the key name in the capabilities section of the API documentation to follow a consistent naming convention, improving clarity and maintainability.
The .gitmodules was updated in d22593d to point at
apps/backend/src/private/implementation, but the gitlink entry (mode
160000) was never added to the tree. This caused
`git clone --recurse-submodules` to silently skip the private submodule.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…on for docs tools

- Added `STACK_DOCS_INTERNAL_BASE_URL` to backend `.env` and `.env.development` files for AI tool bundle configuration.
- Removed references to `STACK_INTERNAL_DOCS_TOOLS_SECRET` from backend and docs environment files and validation logic from the docs tools API route.
- Introduced a new `.env` file for the docs app with essential configuration variables.
@vercel
Copy link
Copy Markdown

vercel bot commented Apr 10, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
3 Building Building Preview, Comment Apr 15, 2026 5:27pm
3-1776188452445-5Jus Canceled Canceled Apr 15, 2026 5:27pm
stack-auth-hosted-components Ready Ready Preview, Comment Apr 15, 2026 5:27pm
stack-backend Ready Ready Preview, Comment Apr 15, 2026 5:27pm
stack-dashboard Ready Ready Preview, Comment Apr 15, 2026 5:27pm
stack-demo Ready Ready Preview, Comment Apr 15, 2026 5:27pm
stack-docs Ready Ready Preview, Comment Apr 15, 2026 5:27pm
stack-preview-backend Ready Ready Preview, Comment Apr 15, 2026 5:27pm
stack-preview-dashboard Ready Ready Preview, Comment Apr 15, 2026 5:27pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 10, 2026

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

Adds SpacetimeDB-backed MCP call logging and review: backend logging, async automated QA review, verified-QA prompt augmentation, SpacetimeDB schema/reducers, admin APIs, and a new internal Next.js MCP-review app with bindings and tooling.

Changes

Cohort / File(s) Summary
README
README.md
Inserted "Ask DeepWiki" badge link in README header.
Backend env & deps
apps/backend/.env, apps/backend/.env.development, apps/backend/package.json
Added SpacetimeDB & MCP log environment variables and added spacetimedb dependency.
AI query flow & prompts
apps/backend/src/app/api/latest/ai/query/[mode]/route.ts, apps/backend/src/lib/ai/prompts.ts, apps/backend/src/lib/ai/schema.ts
Augmented query handler to include verified-QA context, compute/return conversationId, schedule async logging/review for generate mode, and added mcpCallMetadata to request schema; updated docs-ask-ai prompt to prefer verified QA.
MCP logging & reviewer libs
apps/backend/src/lib/ai/mcp-logger.ts, apps/backend/src/lib/ai/qa-reviewer.ts, apps/backend/src/lib/ai/verified-qa.ts
Added SpacetimeDB connection manager, logMcpCall, reviewMcpCall (OpenRouter Claude flow), and verified-QA context collector.
SpacetimeDB bindings (backend)
apps/backend/src/lib/ai/spacetimedb-bindings/*
Generated table and reducer TypeScript bindings for mcp_call_log and reducers (log/update/mark/add/delete/etc.), plus typed connection/subscription builders and types.
Internal MCP-review API routes
apps/backend/src/app/api/latest/internal/mcp-review/*/route.ts
Added hidden POST endpoints (add-manual, delete, mark-reviewed, update-correction) with dev gating and non-dev auth check (approved===true), calling SpacetimeDB reducers.
Docs tooling change
apps/backend/src/lib/ai/tools/docs.ts, docs/src/app/api/internal/[transport]/route.ts
Switched docs tool dev base URL and updated MCP tool to accept userPrompt and optional conversationId, propagating mcpCallMetadata and returning responseConversationId.
Internal tool app scaffold
apps/internal-tool/* (env, configs, package.json, scripts, spacetime module, tsconfigs)
New Next.js internal app with envs, scripts, SpacetimeDB module, token injection/publish scripts, Tailwind/PostCSS, and packaging.
SpacetimeDB module & reducers (internal-tool)
apps/internal-tool/spacetimedb/src/index.ts, apps/internal-tool/spacetimedb/*
New SpacetimeDB schema and reducers implementing token-guarded log_mcp_call, update_mcp_qa_review, mark_human_reviewed, update_human_correction, add_manual_qa, delete_qa_entry, and init.
Internal tool UI & bindings
apps/internal-tool/src/app/..., apps/internal-tool/src/components/*, apps/internal-tool/src/hooks/*, apps/internal-tool/src/module_bindings/*, apps/internal-tool/src/lib/*, apps/internal-tool/src/stack.ts, apps/internal-tool/src/utils.ts
Full admin UI and pages (list/detail/replay/knowledge/analytics), live SpacetimeDB subscription hook, MCP-review API client, module bindings/types, Stack client config, utilities, and global styles.
Dev launch & infra
docker/dependencies/docker.compose.yaml, apps/dev-launchpad/public/index.html
Added SpacetimeDB service to docker-compose (port suffix 39) and registered Internal Tool tile (port suffix 41) in dev launchpad.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client (AI request)
    participant Backend as Backend (AI query route)
    participant Logger as McpLogger
    participant DB as SpacetimeDB
    participant Reviewer as QA Reviewer (OpenRouter)

    Client->>Backend: POST /api/latest/ai/query (body + mcpCallMetadata)
    activate Backend
    Backend->>Backend: getVerifiedQaContext()
    Backend->>Backend: call model (generate/stream)
    Backend->>Logger: logMcpCall(...) (async)
    Logger->>DB: conn.reducers.log_mcp_call(...)
    DB-->>Logger: ack
    Backend-->>Client: return/stream response (includes conversationId)
    deactivate Backend

    Backend->>Reviewer: reviewMcpCall(...) (async)
    activate Reviewer
    Reviewer->>DB: read mcp_call_log row
    Reviewer->>Reviewer: build evaluation prompt + verified QA context
    Reviewer->>Reviewer: call OpenRouter/Claude
    Reviewer->>DB: conn.reducers.update_mcp_qa_review(...)
    DB-->>Reviewer: updated
    deactivate Reviewer
Loading
sequenceDiagram
    participant Admin as Internal Tool UI
    participant API as Backend (mcp-review)
    participant Auth as Auth check
    participant DB as SpacetimeDB

    Admin->>API: POST /api/latest/internal/mcp-review/{action}
    activate API
    API->>Auth: inspect user.client_read_only_metadata.approved
    alt non-dev and not approved
        Auth-->>API: forbidden
        API-->>Admin: 403 Forbidden
    else
        Auth-->>API: authorized
        API->>DB: conn.reducers.{action}(..., token)
        DB-->>API: success
        API-->>Admin: 200 { success: true }
    end
    deactivate API
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly Related PRs

Suggested Reviewers

  • N2D4

Poem

🐇 I hopped through logs to Spacetime's den,

I nudged the QA, then hopped back again.
Models hummed answers, reviewers checked the trace,
I munched on carrots while data found its place. ✨

🚥 Pre-merge checks | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description contains only a template reminder with no actual implementation details, context, or explanation of the changes. Provide a comprehensive description including the feature overview, implementation approach, new capabilities added, and any breaking changes or migration steps required.
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive Title "LLM MCP Flow" refers to a real part of the changeset but is overly vague and does not clearly summarize the primary change. Expand the title to be more specific about the main change, such as "Add MCP flow for AI-assisted Q&A logging and review" or "Implement LLM MCP call logging with SpacetimeDB backend."

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch llm-mcp-flow

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 and usage tips.

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps bot commented Apr 10, 2026

Greptile Summary

This PR introduces a full LLM MCP observability and QA pipeline: every ask_stack_auth call is logged to SpacetimeDB, asynchronously reviewed by a secondary AI model (via OpenRouter + deepwiki MCP), and surfaced in a new internal review tool. Human-verified Q&A pairs are fed back into the system prompt so the main AI can answer from a curated knowledge base. Previous security concerns (unguarded reducers) have been addressed — all five reducers now validate the shared-secret token, and data-mutating operations are proxied through the authenticated backend.

Confidence Score: 5/5

Safe to merge — prior security issues are resolved and the two remaining findings are non-blocking quality improvements

All P0/P1 concerns from previous rounds (unguarded reducers, fixed-sleep synchronization, debug console.log) have been addressed. The two new findings are P2: the unbounded subscription is a future scalability concern not a current breakage, and the silent error swallowing only affects an internal tool's UX

apps/backend/src/lib/ai/mcp-logger.ts — subscription scope should be revisited before call log volume grows significantly

Important Files Changed

Filename Overview
apps/backend/src/lib/ai/mcp-logger.ts New singleton SpacetimeDB connection; subscribes to ALL call log rows — a scalability concern as the table grows
apps/backend/src/lib/ai/qa-reviewer.ts Async QA pipeline using deepwiki MCP + OpenRouter; correctly awaits logPromise before updating the review row; devinClient closed on both success and error paths
apps/backend/src/lib/ai/verified-qa.ts Reads published Q&A from in-memory SpacetimeDB replica and injects into system prompt; correctness relies on the subscription staying current
apps/backend/src/app/api/latest/ai/query/[mode]/route.ts Adds MCP call metadata logging and async QA review via runAsynchronously; correctly threads logPromise through to reviewMcpCall
apps/internal-tool/spacetimedb/src/index.ts SpacetimeDB schema with all five reducers now consistently token-validated; addresses previous security concern
apps/internal-tool/src/app/app-client.tsx Main review UI; action callbacks silently swallow errors contrary to their comments
apps/internal-tool/src/hooks/useSpacetimeDB.ts SpacetimeDB client hook with retry logic; handles SpacetimeDB's delete+insert update semantics correctly via onInsert dedup check
docs/src/app/api/internal/[transport]/route.ts Extends MCP tool schema with userPrompt and conversationId; appends conversationId to response text for conversation threading
apps/backend/src/app/api/latest/internal/mcp-review/add-manual/route.ts New internal route for manually adding Q&A; properly gates on approved metadata in production; calls reducer via backend

Sequence Diagram

sequenceDiagram
    participant U as User/MCP Client
    participant D as docs MCP route
    participant B as Backend /api/latest/ai/query
    participant S as SpacetimeDB
    participant QA as QA Reviewer (OpenRouter)
    participant DW as deepwiki MCP

    U->>D: ask_stack_auth(question, reason, userPrompt, conversationId?)
    D->>S: getVerifiedQaContext() — iterate publishedToQa rows
    S-->>D: verified Q&A pairs
    D->>B: POST /query/generate {messages, mcpCallMetadata}
    B-->>D: {finalText, conversationId}
    D-->>U: text + [conversationId: ...]

    Note over B,S: async (fire-and-forget)
    B->>S: logMcpCall(correlationId, question, response, ...)
    B->>QA: reviewMcpCall(logPromise, correlationId, ...)
    QA->>S: await logPromise (ensures row exists)
    QA->>DW: generateText with deepwiki tools
    DW-->>QA: QA review result (JSON)
    QA->>S: updateMcpQaReview(correlationId, score, flags, ...)

    participant IT as Internal Tool UI
    IT->>S: subscribe SELECT * FROM mcp_call_log
    S-->>IT: live rows (all logs + QA scores)
    IT->>B: POST /internal/mcp-review/update-correction
    B->>S: updateHumanCorrection(token, ..., publish=true)
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: apps/backend/src/lib/ai/mcp-logger.ts
Line: 26

Comment:
**Unbounded subscription loads all rows into memory**

The backend subscribes to `SELECT * FROM mcp_call_log`, which maintains an in-memory replica of every call log row for the lifetime of the process. `getVerifiedQaContext()` then iterates the entire replica on every `docs-ask-ai` / `command-center-ask-ai` request just to filter for `publishedToQa = true` rows. As call volume grows, both memory usage and iteration time increase proportionally — with no bound.

A narrower subscription scoped to published rows would fix the hot-path iteration, and a separate connection for the QA context read-path would avoid coupling the logging connection to it:

```ts
.subscribe("SELECT * FROM mcp_call_log WHERE publishedToQa = true");
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: apps/internal-tool/src/app/app-client.tsx
Line: 155-161

Comment:
**Silent error swallowing despite comment claiming UI feedback**

All three action callbacks (`onSaveCorrection`, `onMarkReviewed`, and `onDelete`) catch errors with `/* errors are surfaced by UI state */` but never update any state — so failures are silently dropped. Users clicking "Mark Reviewed" or "Delete" on a slow/failed backend call get no indication that the action failed.

Consider propagating the error or using a local `errorMessage` state similar to what `AddManualQa.tsx` already does.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (2): Last reviewed commit: "Merge branch 'dev' into llm-mcp-flow" | Re-trigger Greptile

Comment thread apps/internal-tool/spacetimedb/src/index.ts
Comment thread apps/backend/src/lib/ai/qa-reviewer.ts
Comment thread apps/backend/src/lib/ai/verified-qa.ts Outdated
Comment thread apps/internal-tool/spacetimedb/src/index.ts
Comment thread apps/backend/src/lib/ai/tools/docs.ts
@aadesh18 aadesh18 merged commit 5341371 into dev Apr 15, 2026
32 checks passed
@aadesh18 aadesh18 deleted the llm-mcp-flow branch April 15, 2026 17:57
@promptless
Copy link
Copy Markdown
Contributor

promptless bot commented Apr 15, 2026

Promptless prepared a documentation update related to this change.

Triggered by PR #1321 - LLM MCP Flow

Updates MCP setup documentation to highlight the new conversation context feature that preserves follow-up question context. Adds a changelog entry for the feature.

Review: Document MCP conversation context feature

@coderabbitai coderabbitai bot mentioned this pull request Apr 15, 2026
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.

4 participants