Skip to content

mcp server and mcp browser for testing#821

Merged
madster456 merged 10 commits intodevfrom
mcp-server
Aug 11, 2025
Merged

mcp server and mcp browser for testing#821
madster456 merged 10 commits intodevfrom
mcp-server

Conversation

@madster456
Copy link
Copy Markdown
Collaborator

@madster456 madster456 commented Jul 31, 2025


Important

Introduces an interactive documentation browser and MCP server for testing, with new API handling and enriched API spec display.

  • New Features:
    • Adds route.ts to handle API requests for listing and retrieving documentation using MCP.
    • Implements McpBrowserPage in page.tsx for interactive documentation browsing.
    • Displays full documentation content and enriched API specs for API pages.
  • Dependencies:
    • Adds @modelcontextprotocol/sdk, @vercel/mcp-adapter, and posthog-node to package.json.
  • Misc:
    • Integrates PostHog for analytics in route.ts.

This description was created by Ellipsis for a80967c. You can customize this summary. It will automatically update as commits are pushed.


Summary by CodeRabbit

  • New Features

    • Interactive documentation browser with list and detail panes, selection, loading states, and user-friendly error messages.
    • Shows full documentation content and, for API pages, enriched OpenAPI details when available.
  • Chores

    • Added dependencies to enable the documentation browser, MCP backend integration, and analytics (PostHog).

@vercel
Copy link
Copy Markdown

vercel bot commented Jul 31, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Project Deployment Preview Comments Updated (UTC)
stack-backend Ready Preview 💬 Add feedback Aug 11, 2025 10:03pm
stack-dashboard Ready Preview 💬 Add feedback Aug 11, 2025 10:03pm
stack-demo Ready Preview 💬 Add feedback Aug 11, 2025 10:03pm
stack-docs Ready Preview 1 resolved Aug 11, 2025 10:03pm

Copy link
Copy Markdown
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Summary

This PR introduces Model Context Protocol (MCP) functionality to the Stack Auth documentation system. The changes add experimental MCP server support and a browser interface for testing documentation retrieval through the MCP protocol.

The implementation consists of two main components:

  1. New Dependencies: Three new packages are added to the docs package.json:

    • @modelcontextprotocol/sdk (^1.12.0) - Core MCP protocol implementation
    • @vercel/mcp-adapter (^1.0.0) - Vercel-specific MCP integration adapter
    • posthog-node (^4.1.0) - Server-side analytics tracking to complement existing client-side PostHog
  2. MCP Browser Interface: A new React component (docs/src/app/mcp-browser/page.tsx) that provides a web UI for browsing Stack Auth documentation via MCP. The component features a two-panel layout with a document list and content viewer, handling Server-Sent Events (SSE) communication with the MCP server at /api/mcp.

The MCP browser implements custom text parsing logic to handle structured responses from the MCP server, including special handling for different document types like OpenAPI specifications. This suggests the MCP server returns documentation in a structured text format rather than JSON, requiring client-side parsing to extract metadata and content.

This integration allows Stack Auth's documentation to be accessed through the Model Context Protocol, which is commonly used by AI tools and language models to retrieve contextual information from external sources. The testing interface provides a way to validate the MCP implementation before broader deployment.

Confidence score: 3/5

  • This appears to be experimental/testing functionality that's relatively safe to merge for development purposes
  • The main risk is potential performance issues from the MCP browser's API call handling and lack of error boundaries
  • The docs/src/app/mcp-browser/page.tsx file needs attention for potential race conditions and error handling improvements

2 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

@recurseml
Copy link
Copy Markdown

recurseml bot commented Jul 31, 2025

😱 Found 4 issues. Time to roll up your sleeves! 😱

🗒️ View all ignored comments in this repo
  • The constraint 'TokenStoreType extends string' is too restrictive. It should likely be 'TokenStoreType extends string | object' to match the condition check in line 113 where TokenStoreType is checked against {}
  • Return type mismatch - the interface declares useUsers() returning ServerUser[] but the Team interface that this extends declares useUsers() returning TeamUser[]
  • There is a syntax error in the super constructor call due to the ellipsis operator used incorrectly. Objects aren't being merged correctly. This syntax usage can lead to runtime errors when trying to pass the merged object to 'super()'. Verify that the intended alterations to the object occur before or outside of the super() call if needed.
  • Throwing an error when no active span is found is too aggressive. The log function should gracefully fallback to console.log or another logging mechanism when there's no active span, since not all execution contexts will have an active span. This makes the code less resilient and could break functionality in non-traced environments.

📚 Relevant Docs

  • Function sets backendContext with a new configuration but doesn't pass 'defaultProjectKeys'. Since defaultProjectKeys is required in the type definition and cannot be updated (throws error if tried to set), this will cause a type error.
  • The schema is using array syntax for pick() which is incorrect for Yup schemas. The pick() method in Yup expects individual arguments, not an array. Should be changed to: emailConfigSchema.pick('type', 'host', 'port', 'username', 'sender_name', 'sender_email')

📚 Relevant Docs

  • Creating a refresh token with current timestamp as expiration means it expires immediately. Should set a future date for token expiration.
  • The 'tools' object is initialized as an empty object, even though 'tools' is presumably expected to contain tool definitions. This could cause the server capabilities to lack necessary tool configurations, thus potentially impacting functionalities that depend on certain tool setups.

📚 Relevant Docs

  • 'STACK_SECRET_SERVER_KEY' is potentially being included in every request header without checking its existence again here. Although it's checked during initialization, this could lead to security issues as it's exposed in all communications where the header is logged or captured.

📚 Relevant Docs

  • When adding 'use client' directive at the beginning, it doesn't check if file.text already contains the 'use client' directive. This could lead to duplicate 'use client' directives if the file already has one.

📚 Relevant Docs

Need help? Join our Discord for support!
https://discord.gg/qEjHQk64Z9

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jul 31, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds three dependencies to docs/package.json; implements an MCP API route that lists and returns docs (including OpenAPI extraction for API pages) with PostHog tracking; and adds a React MCP browser page that fetches and displays docs via MCP JSON‑RPC/SSE calls.

Changes

Cohort / File(s) Change Summary
Dependency Additions
docs/package.json
Added dependencies: @modelcontextprotocol/sdk (^1.12.0), @vercel/mcp-adapter (^1.0.0), and posthog-node (^4.1.0). No other modifications.
API Route: MCP Handler
docs/src/app/api/[transport]/route.ts
New API route using @vercel/mcp-adapter creating an MCP handler exposing list_available_docs and get_docs_by_id. Performs multi-path content lookup, extracts OpenAPI details from pages containing <EnhancedAPIPage>, reads referenced OpenAPI JSON, returns SSE-style JSON responses, records PostHog events if configured, and maps DELETE/GET/POST to the handler with verbose logging and 60s timeout.
UI: MCP Browser Page
docs/src/app/mcp-browser/page.tsx
New default-exported React component McpBrowserPage. Calls MCP tools via JSON-RPC POSTs to /api/mcp, parses SSE-style streamed responses to obtain summaries and document content (including OpenAPI payloads), manages loading/error state, and renders a two-column selectable list and content view with basic formatting and navigation.

Sequence Diagram(s)

MCP Browser Page: Document Fetch Flow

sequenceDiagram
    participant User
    participant Client as McpBrowserPage
    participant API as /api/mcp
    participant Storage as Docs Storage

    User->>Client: Open page
    Client->>API: POST JSON-RPC list_available_docs
    API->>Storage: Read doc summaries (content/, content/docs/, content/api/)
    Storage-->>API: Summaries
    API-->>Client: SSE/stream JSON with summaries
    Client-->>User: Render list

    User->>Client: Select doc
    Client->>API: POST JSON-RPC get_docs_by_id (id)
    API->>Storage: Read doc content (try multiple paths)
    alt API page with <EnhancedAPIPage>
        API->>Storage: Read referenced OpenAPI JSON file
        Storage-->>API: OpenAPI JSON
        API-->>API: Extract endpoint details
    end
    API-->>Client: SSE/stream JSON with doc content (and OpenAPI info if present)
    Client-->>User: Render content
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐇
I nudged three packages into the nest,
spun a handler to serve docs at request.
Streams of titles, content in view,
OpenAPI endpoints peek through.
A rabbit hops off with a tiny, happy zest.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch mcp-server

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@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.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d573acd and 4994056.

📒 Files selected for processing (3)
  • docs/package.json (3 hunks)
  • docs/src/app/api/[transport]/route.ts (1 hunks)
  • docs/src/app/mcp-browser/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: TypeScript with strict types, prefer type over interface
Avoid casting to any; Prefer making changes to the API so that any casts are unnecessary to access a property or method

Files:

  • docs/src/app/api/[transport]/route.ts
  • docs/src/app/mcp-browser/page.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: 2-space indentation, spaces in braces, semicolons required
Return promises with return await, no floating promises
Proper error handling for async code with try/catch
Use helper functions: yupXyz() for validation, getPublicEnvVar() for env
Switch cases must use blocks

Files:

  • docs/src/app/api/[transport]/route.ts
  • docs/src/app/mcp-browser/page.tsx
**/*.{jsx,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{jsx,tsx}: React Server Components preferred where applicable
No direct 'use' imports from React (use React.use instead)

Files:

  • docs/src/app/mcp-browser/page.tsx
🧠 Learnings (5)
📚 Learning: applies to **/*.{jsx,tsx} : no direct 'use' imports from react (use react.use instead)...
Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{jsx,tsx} : No direct 'use' imports from React (use React.use instead)

Applied to files:

  • docs/package.json
  • docs/src/app/api/[transport]/route.ts
  • docs/src/app/mcp-browser/page.tsx
📚 Learning: applies to **/*.{js,jsx,ts,tsx} : use helper functions: `yupxyz()` for validation, `getpublicenvvar(...
Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Use helper functions: `yupXyz()` for validation, `getPublicEnvVar()` for env

Applied to files:

  • docs/package.json
📚 Learning: applies to **/*.{js,jsx,ts,tsx} : proper error handling for async code with try/catch...
Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Proper error handling for async code with try/catch

Applied to files:

  • docs/src/app/api/[transport]/route.ts
📚 Learning: applies to **/*.{js,jsx,ts,tsx} : return promises with `return await`, no floating promises...
Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{js,jsx,ts,tsx} : Return promises with `return await`, no floating promises

Applied to files:

  • docs/src/app/api/[transport]/route.ts
📚 Learning: applies to **/*.{jsx,tsx} : react server components preferred where applicable...
Learnt from: CR
PR: stack-auth/stack-auth#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-28T23:25:51.701Z
Learning: Applies to **/*.{jsx,tsx} : React Server Components preferred where applicable

Applied to files:

  • docs/src/app/mcp-browser/page.tsx
🧬 Code Graph Analysis (1)
docs/src/app/mcp-browser/page.tsx (2)
docs/src/components/layouts/shared-content-layout.tsx (1)
  • SharedContentLayout (16-40)
docs/src/components/icons.tsx (1)
  • FileText (207-219)
🪛 GitHub Actions: Run setup tests
docs/package.json

[error] 1-1: pnpm install failed due to outdated pnpm-lock.yaml not matching package.json dependencies. Use 'pnpm install --no-frozen-lockfile' to bypass.

🪛 GitHub Actions: Runs E2E API Tests with external source of truth
docs/package.json

[error] 1-1: pnpm install failed with exit code 1 due to outdated pnpm-lock.yaml. The lockfile is not up to date with package.json dependencies, causing a mismatch in specifiers.

🪛 GitHub Actions: Dev Environment Test
docs/package.json

[error] 1-1: pnpm install failed due to outdated pnpm-lock.yaml not matching package.json specs. Use 'pnpm install --no-frozen-lockfile' to bypass frozen-lockfile restriction.

🪛 GitHub Actions: Runs E2E API Tests
docs/package.json

[error] 1-1: pnpm install failed with exit code 1 due to outdated pnpm-lock.yaml not matching package.json dependencies. Run 'pnpm install' without --frozen-lockfile to update the lockfile.

🪛 Biome (2.1.2)
docs/src/app/api/[transport]/route.ts

[error] 36-36: Unexpected empty object pattern.

(lint/correctness/noEmptyPattern)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: docker
  • GitHub Check: all-good
  • GitHub Check: Security Check
🔇 Additional comments (1)
docs/src/app/mcp-browser/page.tsx (1)

28-77: Well-implemented MCP tool caller

The callMcpTool function properly handles SSE response parsing and error cases.

@madster456 madster456 requested a review from N2D4 August 4, 2025 21:23
@N2D4 N2D4 removed their assignment Aug 8, 2025
@claude
Copy link
Copy Markdown
Contributor

claude bot commented Aug 11, 2025

Claude finished @madster456's task —— View job


Comprehensive Code Review

I've analyzed this MCP server implementation that adds documentation browsing capabilities through the Model Context Protocol. Here's my detailed feedback:

🚨 Critical Issues

1. Build Pipeline Failure (BLOCKER)

  • Issue: pnpm-lock.yaml is outdated, causing all CI builds to fail
  • Impact: Prevents deployment and testing
  • Fix: Run pnpm install to regenerate the lockfile

2. Race Condition in Error Handling (docs/src/app/mcp-browser/page.tsx:133-136)

loadDocs().catch(err => {
  setError(err instanceof Error ? err.message : 'Failed to load docs');
  setLoading(false); // ⚠️ Sets loading after async operation completes
});
  • Issue: Error handling outside loadDocs() can race with the finally block
  • Impact: UI state inconsistencies, loading spinner may persist
  • Fix: Remove external catch block, handle all errors inside loadDocs()

3. Bounds Check Missing (docs/src/app/mcp-browser/page.tsx:172-174)

const titleDescEnd = textContent.indexOf('\n\n');
if (titleDescEnd !== -1 && titleDescEnd + 2 < textContent.length) {
  content = textContent.substring(titleDescEnd + 2); // ⚠️ No bounds checking
  • Issue: When indexOf returns -1, titleDescEnd + 2 becomes 1, not caught by length check
  • Impact: Runtime errors when parsing certain document formats
  • Fix: Add explicit -1 check before using titleDescEnd

⚠️ Significant Issues

4. Inconsistent Error Handling (docs/src/app/api/[transport]/route.ts:147, 183)

try {
  return await extractOpenApiDetails(content, page);
} catch {
  return { /* fallback */ }; // ⚠️ Silent failure
}
  • Issue: OpenAPI extraction failures are silently ignored
  • Impact: Degraded UX with no indication of partial failures
  • Fix: Log errors or provide user feedback about parsing issues

5. PostHog Event Naming (docs/src/app/api/[transport]/route.ts:112, 127)

event: "list_available_docs", // ✅ Correct
event: "get_docs_by_id",      // ✅ Correct  
  • Status: Actually correctly named (contrary to bot review)

6. Synchronous File Operations (docs/src/app/api/[transport]/route.ts:27, 141, 177)

const specContent = await readFile(specPath, "utf-8"); // ✅ Async
const content = await readFile(filePath, "utf-8");     // ✅ Async
  • Status: Already using async operations (contrary to bot review)

🔍 Code Quality Issues

7. Unused Parameter Pattern (docs/src/app/api/[transport]/route.ts:110)

async ({}) => { // ⚠️ Empty destructuring pattern
  • Issue: Triggers linter warnings, serves no purpose
  • Fix: Change to async () => {

8. Key Prop Using Array Index (docs/src/app/mcp-browser/page.tsx:255)

{docs.map((doc) => (
  <div key={doc.id}> // ✅ Uses doc.id, not index
  • Status: Already using unique ID (contrary to bot review)

9. Duplicated OpenAPI Logic

  • Issue: OpenAPI extraction code is duplicated in lines 72-125 and 168-255
  • Impact: Maintenance burden, inconsistency risk
  • Fix: Extract into shared helper function

10. Missing JSON Import Consistency

const spec = JSON.parse(specContent); // ⚠️ Should use parseJson from stack-shared
  • Issue: Inconsistent with codebase standards requiring parseJson helper
  • Fix: Import and use parseJson from @stackframe/stack-shared/utils/json

🎯 Performance Considerations

11. File System Performance

  • Good: Uses async file operations throughout
  • Concern: Multiple file path attempts could be slow for missing files
  • Suggestion: Consider caching file existence checks

12. Client-Side Performance

  • Good: Proper loading states and error boundaries
  • Concern: No debouncing for rapid document selections
  • Impact: Could cause unnecessary API calls if users click quickly

🔒 Security Assessment

13. File Path Traversal

  • Status: ✅ SECURE - Only reads from predefined content directories
  • Good: Uses hardcoded path prefixes (content/, content/docs/, content/api/)

14. Environment Variable Exposure

  • Status: ✅ SECURE - PostHog key usage is appropriate for server-side analytics
  • Good: Proper null checking for missing environment variables

15. Input Validation

  • Status: ✅ GOOD - Uses Zod schema validation for MCP tool parameters
  • Good: MCP adapter handles request validation

🧪 Test Coverage Analysis

16. Missing Test Coverage

  • API Route: No tests for MCP tool functions, OpenAPI extraction logic
  • UI Component: No tests for SSE parsing, error states, document loading
  • Critical Paths: File reading fallbacks, error handling, content parsing
  • Recommendation: Add unit tests for parsing logic and integration tests for MCP calls

📋 Additional Observations

Architecture & Design

  • ✅ Good: Clean separation between MCP server logic and UI
  • ✅ Good: Proper use of Next.js App Router conventions
  • ✅ Good: Responsive design with proper loading states
  • ⚠️ Consider: Adding request timeout handling in the browser

Documentation & Maintainability

  • ✅ Good: Clear function names and reasonable code organization
  • ⚠️ Missing: JSDoc comments for complex parsing logic
  • ⚠️ Missing: Type definitions could be more specific (using branded types for IDs)

🏁 Summary

This MCP implementation is architecturally sound but has several issues that should be addressed:

  1. Critical: Fix the lockfile to unblock CI/CD
  2. Important: Address the race condition and bounds checking issues
  3. Quality: Clean up code duplication and linting issues
  4. Testing: Add comprehensive test coverage

The core functionality appears well-designed for its intended purpose of providing Stack Auth documentation through the Model Context Protocol.


Todo List:

  • Read and analyze all changed files
  • Review code quality and best practices
  • Identify potential bugs and issues
  • Assess performance considerations
  • Check for security concerns
  • Evaluate test coverage needs
  • Provide comprehensive feedback

@claude
Copy link
Copy Markdown
Contributor

claude bot commented Aug 11, 2025

Claude finished @madster456's task —— View job


Comprehensive Code Review

I've analyzed this MCP server implementation that adds documentation browsing capabilities through the Model Context Protocol. Here's my detailed feedback:

🚨 Critical Issues

1. Build Pipeline Failure (BLOCKER)

  • Issue: pnpm-lock.yaml is outdated, causing all CI builds to fail
  • Impact: Prevents deployment and testing
  • Fix: Run pnpm install to regenerate the lockfile

2. Race Condition in Error Handling (docs/src/app/mcp-browser/page.tsx:133-136)

loadDocs().catch(err => {
  setError(err instanceof Error ? err.message : 'Failed to load docs');
  setLoading(false); // ⚠️ Sets loading after async operation completes
});
  • Issue: Error handling outside loadDocs() can race with the finally block
  • Impact: UI state inconsistencies, loading spinner may persist
  • Fix: Remove external catch block, handle all errors inside loadDocs()

3. Bounds Check Missing (docs/src/app/mcp-browser/page.tsx:172-174)

const titleDescEnd = textContent.indexOf('\n\n');
if (titleDescEnd !== -1 && titleDescEnd + 2 < textContent.length) {
  content = textContent.substring(titleDescEnd + 2); // ⚠️ No bounds checking
  • Issue: When indexOf returns -1, titleDescEnd + 2 becomes 1, not caught by length check
  • Impact: Runtime errors when parsing certain document formats
  • Fix: Add explicit -1 check before using titleDescEnd

⚠️ Significant Issues

4. Inconsistent Error Handling (docs/src/app/api/[transport]/route.ts:147, 183)

try {
  return await extractOpenApiDetails(content, page);
} catch {
  return { /* fallback */ }; // ⚠️ Silent failure
}
  • Issue: OpenAPI extraction failures are silently ignored
  • Impact: Degraded UX with no indication of partial failures
  • Fix: Log errors or provide user feedback about parsing issues

5. PostHog Event Naming (docs/src/app/api/[transport]/route.ts:112, 127)

event: "list_available_docs", // ✅ Correct
event: "get_docs_by_id",      // ✅ Correct  
  • Status: Actually correctly named (contrary to bot review)

6. Synchronous File Operations (docs/src/app/api/[transport]/route.ts:27, 141, 177)

const specContent = await readFile(specPath, "utf-8"); // ✅ Async
const content = await readFile(filePath, "utf-8");     // ✅ Async
  • Status: Already using async operations (contrary to bot review)

🔍 Code Quality Issues

7. Unused Parameter Pattern (docs/src/app/api/[transport]/route.ts:110)

async ({}) => { // ⚠️ Empty destructuring pattern
  • Issue: Triggers linter warnings, serves no purpose
  • Fix: Change to async () => {

8. Key Prop Using Array Index (docs/src/app/mcp-browser/page.tsx:255)

{docs.map((doc) => (
  <div key={doc.id}> // ✅ Uses doc.id, not index
  • Status: Already using unique ID (contrary to bot review)

9. Duplicated OpenAPI Logic

  • Issue: OpenAPI extraction code is duplicated in lines 72-125 and 168-255
  • Impact: Maintenance burden, inconsistency risk
  • Fix: Extract into shared helper function

10. Missing JSON Import Consistency

const spec = JSON.parse(specContent); // ⚠️ Should use parseJson from stack-shared
  • Issue: Inconsistent with codebase standards requiring parseJson helper
  • Fix: Import and use parseJson from @stackframe/stack-shared/utils/json

🎯 Performance Considerations

11. File System Performance

  • Good: Uses async file operations throughout
  • Concern: Multiple file path attempts could be slow for missing files
  • Suggestion: Consider caching file existence checks

12. Client-Side Performance

  • Good: Proper loading states and error boundaries
  • Concern: No debouncing for rapid document selections
  • Impact: Could cause unnecessary API calls if users click quickly

🔒 Security Assessment

13. File Path Traversal

  • Status: ✅ SECURE - Only reads from predefined content directories
  • Good: Uses hardcoded path prefixes (content/, content/docs/, content/api/)

14. Environment Variable Exposure

  • Status: ✅ SECURE - PostHog key usage is appropriate for server-side analytics
  • Good: Proper null checking for missing environment variables

15. Input Validation

  • Status: ✅ GOOD - Uses Zod schema validation for MCP tool parameters
  • Good: MCP adapter handles request validation

🧪 Test Coverage Analysis

16. Missing Test Coverage

  • API Route: No tests for MCP tool functions, OpenAPI extraction logic
  • UI Component: No tests for SSE parsing, error states, document loading
  • Critical Paths: File reading fallbacks, error handling, content parsing
  • Recommendation: Add unit tests for parsing logic and integration tests for MCP calls

📋 Additional Observations

Architecture & Design

  • ✅ Good: Clean separation between MCP server logic and UI
  • ✅ Good: Proper use of Next.js App Router conventions
  • ✅ Good: Responsive design with proper loading states
  • ⚠️ Consider: Adding request timeout handling in the browser

Documentation & Maintainability

  • ✅ Good: Clear function names and reasonable code organization
  • ⚠️ Missing: JSDoc comments for complex parsing logic
  • ⚠️ Missing: Type definitions could be more specific (using branded types for IDs)

🏁 Summary

This MCP implementation is architecturally sound but has several issues that should be addressed:

  1. Critical: Fix the lockfile to unblock CI/CD
  2. Important: Address the race condition and bounds checking issues
  3. Quality: Clean up code duplication and linting issues
  4. Testing: Add comprehensive test coverage

The core functionality appears well-designed for its intended purpose of providing Stack Auth documentation through the Model Context Protocol.


Todo List:

  • Read and analyze all changed files
  • Review code quality and best practices
  • Identify potential bugs and issues
  • Assess performance considerations
  • Check for security concerns
  • Evaluate test coverage needs
  • Provide comprehensive feedback

Copy link
Copy Markdown
Contributor

@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.

Actionable comments posted: 1

♻️ Duplicate comments (1)
docs/package.json (1)

25-25: Update pnpm-lock.yaml to fix CI.

New deps added but lockfile is stale; run pnpm install to regenerate pnpm-lock.yaml.

Also applies to: 34-34, 50-50

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a80967c and 1c7b460.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • docs/package.json (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: build (22.x)
  • GitHub Check: restart-dev-and-test
  • GitHub Check: build (22.x)
  • GitHub Check: docker
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: docker
  • GitHub Check: all-good
  • GitHub Check: setup-tests
  • GitHub Check: claude-review
  • GitHub Check: Security Check
🔇 Additional comments (2)
docs/package.json (2)

25-25: Deps align with MCP server/browser addition.

@modelcontextprotocol/sdk is expected for MCP tools; version range looks fine.


34-34: Adapter dependency looks correct.

@vercel/mcp-adapter matches the new API route usage (createMcpHandler).

@madster456 madster456 merged commit 8abf947 into dev Aug 11, 2025
21 checks passed
@madster456 madster456 deleted the mcp-server branch August 11, 2025 22:17
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