Skip to content
This repository was archived by the owner on Apr 21, 2026. It is now read-only.

feat(web): Add roadmap gate metrics and MCP-first fallback policy#451

Closed
LucasSantana-Dev wants to merge 1 commit intomainfrom
feature/roadmap-gate-metrics-gateway
Closed

feat(web): Add roadmap gate metrics and MCP-first fallback policy#451
LucasSantana-Dev wants to merge 1 commit intomainfrom
feature/roadmap-gate-metrics-gateway

Conversation

@LucasSantana-Dev
Copy link
Copy Markdown
Member

@LucasSantana-Dev LucasSantana-Dev commented Mar 11, 2026

Summary

  • add roadmap-aligned telemetry in GET /api/metrics for:
    • 50-user gate readiness (adoption.gate50)
    • core-flow adoption rates (onboarding/project/generation)
    • generation quality metrics (success, satisfaction, revisions)
    • MCP routing coverage (routing.mcp)
  • enforce MCP-first generation path by default:
    • add ENABLE_MCP_DIRECT_PROVIDER_FALLBACK feature flag
    • default it to false
    • in MCP mode, return explicit error instead of silent direct-provider fallback unless explicitly enabled
  • update MCP error guidance text to remove direct-provider assumption
  • document behavior in README and CHANGELOG

Why

Roadmap priorities require validation/adoption metrics and completion of WebApp->Gateway integration with MCP as the primary flow before broader Phase 2 expansion.

Testing

  • npm run lint
  • npm run type-check
  • npm run test
  • npm run build
  • targeted suites:
    • npm --workspace @siza/web test -- src/app/api/metrics/__tests__/route.test.ts src/__tests__/lib/services/provider-router.test.ts src/__tests__/lib/features/flags.test.ts

Summary by CodeRabbit

  • New Features

    • Added feature flag to control MCP failure fallback behavior
    • Enhanced metrics collection for usage analytics including user adoption and routing insights
  • Tests

    • Expanded test coverage for MCP fallback scenarios and metrics calculation

@vercel
Copy link
Copy Markdown

vercel Bot commented Mar 11, 2026

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

Project Deployment Actions Updated (UTC)
siza-web Ready Ready Preview, Comment Mar 11, 2026 8:11pm

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 11, 2026

Walkthrough

Introduces a new feature flag ENABLE_MCP_DIRECT_PROVIDER_FALLBACK that controls whether MCP generation failures fallback to direct providers. When disabled, failures produce errors instead. Affects routing logic, integration points, comprehensive test coverage, and adds expansive metrics calculations.

Changes

Cohort / File(s) Summary
Feature Flag Definitions
apps/web/src/lib/features/flags.ts, apps/web/src/lib/features/types.ts
Added new feature flag ENABLE_MCP_DIRECT_PROVIDER_FALLBACK with default value false, and extended FeatureFlagName union type to include the new flag.
Routing Logic Updates
apps/web/src/lib/services/provider-router.ts, apps/web/src/app/api/generate/route.ts
Modified RouteGenerationOptions interface to include optional allowDirectProviderFallback parameter. Updated routeViaMcp to emit error when fallback is disabled instead of defaulting to fallback. Added helper function to read feature flag and pass it through API routes (POST and GET).
Routing Tests
apps/web/src/__tests__/lib/services/provider-router.test.ts, apps/web/src/__tests__/lib/features/flags.test.ts
Expanded test coverage to verify both fallback-enabled and fallback-disabled scenarios. Added test asserting ENABLE_MCP_DIRECT_PROVIDER_FALLBACK defaults to false and updated flag count assertions to include new entry.
Metrics Route & Tests
apps/web/src/app/api/metrics/route.ts, apps/web/src/app/api/metrics/__tests__/route.test.ts
Significantly expanded metrics computation with new helpers (asRows, toIdSet, roundRate, countActiveUsers, intersectionCount), multi-source data fetching from profiles/projects/generations, and complex adoption/routing analytics. Updated test fixtures and assertions to cover new response shape including revisions, satisfaction, adoption, and MCP routing data.
MCP Client Error Message
apps/web/src/lib/mcp/client.ts
Updated error message text in listTools when MCP gateway is unavailable from generation fallback indication to gateway health guidance.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API as Generate API
    participant Router as Provider Router
    participant MCP as MCP Gateway
    participant Provider as Direct Provider

    Client->>API: POST /api/generate
    API->>API: Read ENABLE_MCP_DIRECT_PROVIDER_FALLBACK flag
    API->>Router: routeGeneration(allowDirectProviderFallback: bool)
    
    alt MCP Enabled
        Router->>MCP: routeViaMcp()
        MCP-->>Router: MCP fails (no output)
        
        alt Fallback Enabled (flag=true)
            Router->>Provider: fallback to direct provider
            Provider-->>Router: result
            Router-->>API: success
        else Fallback Disabled (flag=false)
            Router-->>API: error (MCP failure, no fallback)
        end
    else MCP Disabled
        Router->>Provider: route directly
        Provider-->>Router: result
        Router-->>API: success
    end
    
    API-->>Client: response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the two main changes: adding roadmap gate metrics and implementing MCP-first fallback policy with the feature flag. Both aspects are explicitly mentioned and align with the substantial changes across metrics computation and provider routing logic.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/roadmap-gate-metrics-gateway

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 OpenGrep (1.16.3)
apps/web/src/__tests__/lib/features/flags.test.ts

┌──────────────┐
│ Opengrep CLI │
└──────────────┘

�[32m✔�[39m �[1mOpengrep OSS�[0m
�[32m✔�[39m Basic security coverage for first-party code vulnerabilities.

�[1m Loading rules from local config...�[0m

apps/web/src/app/api/generate/route.ts

┌──────────────┐
│ Opengrep CLI │
└──────────────┘

�[32m✔�[39m �[1mOpengrep OSS�[0m
�[32m✔�[39m Basic security coverage for first-party code vulnerabilities.

�[1m Loading rules from local config...�[0m

apps/web/src/app/api/metrics/route.ts

┌──────────────┐
│ Opengrep CLI │
└──────────────┘

�[32m✔�[39m �[1mOpengrep OSS�[0m
�[32m✔�[39m Basic security coverage for first-party code vulnerabilities.

�[1m Loading rules from local config...�[0m

  • 6 others

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.

@LucasSantana-Dev
Copy link
Copy Markdown
Member Author

Code review (mandatory pass):

Findings

  • No blocking findings.

Assumptions/Open questions

  • MCP-first behavior is intentional for production paths: with ENABLE_MCP_GATEWAY=true and gateway configured, failures now return explicit MCP guidance unless ENABLE_MCP_DIRECT_PROVIDER_FALLBACK=true is explicitly enabled.
  • /api/metrics expanded contract is consumed by internal dashboards/automation that can tolerate additive fields.

Summary

  • Scope is focused and coherent: roadmap gate telemetry + MCP fallback policy + test/docs updates.

@sonarqubecloud
Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@github-actions
Copy link
Copy Markdown

Project Scorecard


Scorecard: 84/100 (B)
────────────────────────────────────────
  security: 100/100 (A)
  quality: 80/100 (B) — 1 violations
  performance: 67/100 (D) — 1 violations
  compliance: 75/100 (C) — 1 violations
  dependency: 100/100 (A)

Recommendations:
  - Increase test coverage to meet the 80% threshold
  - Extend log retention to at least 90 days for compliance

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
apps/web/src/__tests__/lib/services/provider-router.test.ts (1)

100-120: Consider verifying error capture consistency.

The test correctly validates the core fallback-disabled behavior: no fallback event, no fallback chunk, error returned, and generateWithProvider not called. The eslint-disable comment on line 104 appropriately addresses the static analysis warning about the intentionally non-yielding generator.

However, the fallback-enabled test (line 94) asserts that captureServerError is called when MCP fails. If the implementation also logs errors to Sentry when fallback is disabled, consider adding that assertion here for consistency and to verify error observability is maintained regardless of fallback behavior.

💡 Optional: Add captureServerError assertion
 it('returns an error on MCP failure when direct-provider fallback is disabled', async () => {
   const { generateComponentStream: mcpStream } = require('@/lib/mcp/client');
   const { generateWithProvider } = require('@/lib/services/generation');
+  const { captureServerError } = require('@/lib/sentry/server');

   // eslint-disable-next-line require-yield
   mcpStream.mockImplementation(async function* () {
     throw new Error('Gateway down');
   });
   generateWithProvider.mockImplementation(async function* () {
     yield { type: 'chunk', content: 'fallback-code', timestamp: 11 };
   });

   const events = await collectEvents(
     routeGeneration({ ...baseOpts, mcpEnabled: true, accessToken: 'tok-123' })
   );

+  expect(captureServerError).toHaveBeenCalled();
   expect(events.find((e) => e.type === 'fallback')).toBeUndefined();
   expect(events.some((e) => e.type === 'chunk' && e.content === 'fallback-code')).toBe(false);
   expect(events.some((e) => e.type === 'error')).toBe(true);
   expect(generateWithProvider).not.toHaveBeenCalled();
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/src/__tests__/lib/services/provider-router.test.ts` around lines 100
- 120, The test for "returns an error on MCP failure when direct-provider
fallback is disabled" is missing an assertion that the error telemetry function
captureServerError is invoked when the MCP stream throws; update the test to
mock/spy on captureServerError (the same spy used in the fallback-enabled test)
and assert it was called after calling routeGeneration with mcpEnabled: true and
accessToken set, while keeping the existing mcpStream and generateWithProvider
mocks and the other expectations unchanged so error observability is verified
even when fallback is disabled.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/web/src/__tests__/lib/services/provider-router.test.ts`:
- Around line 100-120: The test for "returns an error on MCP failure when
direct-provider fallback is disabled" is missing an assertion that the error
telemetry function captureServerError is invoked when the MCP stream throws;
update the test to mock/spy on captureServerError (the same spy used in the
fallback-enabled test) and assert it was called after calling routeGeneration
with mcpEnabled: true and accessToken set, while keeping the existing mcpStream
and generateWithProvider mocks and the other expectations unchanged so error
observability is verified even when fallback is disabled.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 81fff63e-dc60-4bcd-bed2-70d8dd3bcfb7

📥 Commits

Reviewing files that changed from the base of the PR and between b514e3c and 2f5a75e.

⛔ Files ignored due to path filters (2)
  • CHANGELOG.md is excluded by !**/*.md
  • README.md is excluded by !**/*.md
📒 Files selected for processing (9)
  • apps/web/src/__tests__/lib/features/flags.test.ts
  • apps/web/src/__tests__/lib/services/provider-router.test.ts
  • apps/web/src/app/api/generate/route.ts
  • apps/web/src/app/api/metrics/__tests__/route.test.ts
  • apps/web/src/app/api/metrics/route.ts
  • apps/web/src/lib/features/flags.ts
  • apps/web/src/lib/features/types.ts
  • apps/web/src/lib/mcp/client.ts
  • apps/web/src/lib/services/provider-router.ts

@LucasSantana-Dev
Copy link
Copy Markdown
Member Author

Superseded by #452 due branch ruleset GH013 preventing updates to this PR branch.

@LucasSantana-Dev LucasSantana-Dev deleted the feature/roadmap-gate-metrics-gateway branch March 15, 2026 21:29
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant