### Installing and Building mentor-mcp-server (Bash) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/README.md Provides the necessary bash commands to set up the mentor-mcp-server project locally. This includes cloning the repository, installing Node.js dependencies using npm, and building the project. ```bash # Clone the repository git clone git@github.com:cyanheads/mentor-mcp-server.git cd mentor-mcp-server # Install dependencies npm install # Build the project npm run build ``` -------------------------------- ### Rate Limit Configuration Example (JavaScript) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/writing-feedback.md This JavaScript object, embedded within the documentation text, shows an example configuration for a rate limiting implementation using a token bucket algorithm. It defines the maximum bucket size and the rate at which tokens are refilled. ```javascript const rateLimit = { bucketSize: 100, refillRate: 10 // tokens per second } ``` -------------------------------- ### Example 429 Rate Limit Response (JSON) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/writing-feedback.md Provides an example structure for an HTTP 429 Too Many Requests response body and relevant rate limit headers, including error details and retry information. ```JSON // 429 Response Example { "error": { "code": "rate_limit_exceeded", "message": "Maximum 100 requests per minute", "retry_after": 5.2 // seconds } } Headers: X-RateLimit-Limit: 100 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1689876543 Retry-After: 5.2 ``` -------------------------------- ### Development Scripts - Bash Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/README.md Provides essential bash commands for managing the project's development lifecycle, including building the TypeScript code, starting the server, running in development mode with watching, and cleaning build artifacts. ```bash # Build TypeScript code npm run build # Start the server npm run start # Development with watch mode npm run dev # Clean build artifacts npm run clean ``` -------------------------------- ### Returning Generic File Read Error Response Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/code-review.md Provides an example of returning a generic, user-safe error response object instead of leaking sensitive details from raw error messages, improving security. ```typescript return { content: [{ type: 'text', text: 'File read error' }], isError: true }; ``` -------------------------------- ### Example Second Opinion Tool Request (JSON) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/second-opinion.md This JSON snippet represents a user's request submitted to a 'Second Opinion Tool', asking for guidance on building a secure authentication system using OAuth2 and JWT tokens. ```json { "user_request": "Build a secure authentication system with OAuth2 and JWT tokens" } ``` -------------------------------- ### Implementing File Size Limit Check in TypeScript Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/code-review.md Shows how to define a maximum file size constant and check against it before processing a file, preventing potential memory issues with large inputs. ```typescript const MAX_FILE_SIZE = 1024 * 1024; // 1MB if (fileStats.size > MAX_FILE_SIZE) throw new Error('File too large'); ``` -------------------------------- ### Implementing Token Bucket Logic with Redis (JavaScript) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/writing-feedback.md Shows a JavaScript function using a Redis client to implement token bucket rate limiting. It fetches current state, calculates new token count based on refill rate, updates state using a multi/exec transaction, sets expiration, and checks if a token is available. ```JavaScript // Token consumption logic async function checkRateLimit(clientId) { const now = Date.now(); const key = `rate_limit:${clientId}`; const result = await redis.multi() .hgetall(key) .hmset(key, { tokens: Math.min( (current.tokens || bucketSize) + Math.floor((now - (current.lastRefill || now)) / 1000 * refillRate), bucketSize ), lastRefill: now }) .expire(key, 3600) .exec(); if(result.tokens < 1) throw new RateLimitError(); } ``` -------------------------------- ### Example Design Critique Response (Markdown) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/design-critique.md This Markdown formatted text provides a detailed critique of the described web UI design. It includes sections for overall assessment, strengths, areas for improvement (categorized by usability, visual design, technical feasibility, accessibility), and specific recommendations. ```markdown ### Comprehensive Design Critique: Cloud Monitoring Dashboard #### 1. **Overall Assessment** The design presents a functional foundation for a monitoring dashboard with logical component organization. Its dark theme aligns with industry standards for operational tools, and the real-time elements address core user needs. However, the layout risks visual clutter in high-alert scenarios, and several accessibility/technical optimizations could enhance usability and scalability. --- #### 2. **Strengths** - **Intuitive Layout**: Industry-standard top nav + left sidebar structure reduces cognitive load. - **Effective Alert Hierarchy**: Accent colors (e.g., red for critical alerts) create clear visual urgency. - **Contextual Updates**: 30-second graph refresh rate balances data recency with server load. - **Multi-Channel Notifications**: Toast + alert history provides dual awareness mechanisms. - **System Transparency**: Footer timestamp builds trust in data freshness. --- #### 3. **Areas for Improvement** **Usability** - No apparent customization options for dashboard widgets - Overloaded main content area risks "dashboard fatigue" - Missing emergency controls (e.g., manual alert suppression) **Visual Design** - Insufficient spacing between overview cards - Undifferentiated graph line colors (accessibility risk) - Status indicators lack text labels (icon-only) **Technical Feasibility** - 30-second polling may strain backend at scale - No error states for failed graph updates - Toast stacking behavior undefined **Accessibility** - Contrast ratios below WCAG 2.1 AA for secondary text - No keyboard navigation for sidebar - Missing ARIA labels for dynamic content --- #### 4. **Specific Recommendations** **A. Layout & Interaction (High Impact)** 1. Add **dashboard customization**: - Drag-and-drop widget rearrangement - Collapsible/expandable sections - User-defined thresholds for alert colors 2. Implement **progressive disclosure**: - Expandable graph tooltips with raw metrics - "Show More" pagination for alert history 3. Introduce **emergency bar** at viewport top for SEV-1 alerts **B. Visual Hierarchy (Medium Impact)** 1. Apply **8px grid system** to cards/graphs for consistent spacing 2. Use **semantic color scales**: - 3 distinct hues for CPU/Memory/Network - Pattern overlays for grayscale printing 3. Add **status badges** to overview cards (e.g., "12% ▲ from avg") **C. Technical Optimization** 1. Replace polling with **WebSocket** for real-time updates 2. Implement **client-side throttling**: - Pause updates when tab/window not active - Adaptive refresh rates (15-60s) based on connectivity 3. Create **toast queue system** with: - Auto-dismiss timers (5s info / 15s critical) - Manual "pin" capability - Batch grouping for similar alerts **D. Accessibility Compliance** 1. Achieve **4.5:1 contrast ratio** for all text (tools: Stark/Colorable) 2. Add **keyboard shortcuts**: - Ctrl+1-4 for sidebar categories - Spacebar to pause auto-refresh 3. Provide **alternative data views**: - Tabular graph data export - Sonification toggle for alert patterns --- ``` -------------------------------- ### Correct Placement of Rate Limit Check in Handler Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/code-review.md Illustrates the recommended order of operations in an API handler: perform input validation *before* checking rate limits to avoid consuming quota with invalid requests. ```typescript export async function handler(args: unknown): Promise { // Validate FIRST if (!validateArgs(args)) return invalidArgsResponse; // Then check rate limits if (!checkRateLimit()) return rateLimitResponse; } ``` -------------------------------- ### Implementing Type Guard and Path Validation in TypeScript Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/code-review.md Demonstrates using a TypeScript type guard (`isCodeReviewArgs`) for robust input validation instead of type assertion (`as`). Also includes an example of validating a file path format (`isValidPath`) before proceeding. ```typescript // Use type guard instead of assertion function isCodeReviewArgs(args: unknown): args is CodeReviewArgs { return /* detailed property checks */; } // Validate file_path format if applicable if (typedArgs.file_path && !isValidPath(typedArgs.file_path)) { return invalidPathError; } ``` -------------------------------- ### Example Request Payload (JSON) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/writing-feedback.md This JSON object represents a typical request sent to a writing feedback tool. It contains the 'text' field with the content to be analyzed and the 'writing_type' field specifying the category of the content. ```json { "text": "# Rate Limiting Implementation Guide\n\nThis document describes the implementation of rate limiting in our API service. Rate limiting prevents abuse and ensures fair resource allocation.\n\nRate limits are enforced using a token bucket algorithm. Each client gets a bucket that fills at a fixed rate. When the bucket is empty, requests are rejected.\n\nTo implement rate limiting:\n1. Configure bucket size and refill rate\n2. Store bucket state in Redis\n3. Check token availability before processing requests\n4. Update bucket state after processing.\n\nExample:\n```js\nconst rateLimit = {\n bucketSize: 100,\n refillRate: 10 // tokens per second\n}\n```\n\nWhen rate limit is exceeded, return 429 Too Many Requests with retry-after header.", "writing_type": "documentation" } ``` -------------------------------- ### Defining Input Schema with Zod in TypeScript Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/code-review.md Demonstrates how to use the Zod library to define a robust schema for input validation, supporting a union type for either a file path or a code snippet, ensuring type safety and structure. ```typescript import { z } from 'zod'; const CodeReviewSchema = z.union([ z.object({ file_path: z.string().min(1), language: z.string().min(1) }), z.object({ code_snippet: z.string().min(1), language: z.string().min(1) }) ]); ``` -------------------------------- ### Example Request Payload for Design Critique Tool (JSON) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/design-critique.md This JSON object represents the input payload sent to a design critique tool. It contains the 'design_document' field describing the UI design and the 'design_type' field specifying the type of design (web UI). ```json { "design_document": "A dashboard interface for a cloud monitoring system with the following components:\n\n- Top navigation bar with company logo, user profile, and notifications\n- Left sidebar with collapsible menu items for different monitoring categories (CPU, Memory, Network, Storage)\n- Main content area showing:\n - Overview cards with key metrics\n - Real-time graphs showing system performance\n - Alert history table\n - Resource usage breakdown\n- Footer with system status and last update timestamp\n\nThe design uses a dark theme with accent colors for critical alerts and status indicators. Graphs update every 30 seconds and alerts appear as toast notifications.", "design_type": "web UI" } ``` -------------------------------- ### Brainstormed Enhancements Response (Markdown) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/brainstorm-enhancements.md Presents a structured list of potential enhancements for the AI code review tool, categorized into Quick Wins, Strategic Enhancements, and Transformative Ideas, detailing descriptions, impact, complexity, resources, and challenges for each. ```markdown ### **1. Quick Wins (Immediate, Low-Effort Improvements)** --- #### **A. Contextual Inline Comment Explanations** - **Description**: Add brief explanations and code examples to AI-generated inline comments to help developers understand *why* a change is suggested (e.g., "This SQL query is vulnerable to injection; here's a parameterized example"). - **Impact**: Reduces ambiguity, accelerates fixes, and improves trust in AI feedback. - **Complexity**: Low (leverage existing LLMs like GPT-4 for concise explanations). - **Resources**: 1–2 developers, 2–3 weeks. - **Challenges**: Ensuring explanations are accurate and non-redundant. #### **B. Customizable Rulesets** - **Description**: Allow teams to toggle specific code quality rules (e.g., enforce strict TypeScript typings but ignore line-length warnings). - **Impact**: Tailors feedback to team priorities, reducing noise. - **Complexity**: Low (add UI toggles tied to existing rule configurations). - **Resources**: 1 frontend developer, 1 backend developer, 3 weeks. - **Challenges**: Managing conflicting rule combinations. #### **C. Severity-Based Issue Prioritization** - **Description**: Flag issues as Critical/High/Medium/Low (e.g., security vulnerabilities = Critical, formatting = Low) and sort them in the summary report. - **Impact**: Helps developers triage fixes efficiently. - **Complexity**: Low (predefined severity tiers for common issues). - **Resources**: 1 developer, 1–2 weeks. - **Challenges**: Subjective severity assignments may require user customization. #### **D. Dark Mode for Summary Reports** - **Description**: Add a dark theme option to the PDF/HTML summary reports. - **Impact**: Improves readability and aligns with developer preferences. - **Complexity**: Low (CSS/theme adjustments). - **Resources**: 1 frontend developer, 1 week. - **Challenges**: Minimal. --- ### **2. Strategic Enhancements (Medium-Term, Moderate Complexity)** --- #### **A. Multi-Platform CI/CD Integration** - **Description**: Expand beyond GitHub to natively support GitLab, Bitbucket, and Azure DevOps pipelines. - **Impact**: Captures broader market share and enterprise clients. - **Complexity**: Medium (API integrations, testing across platforms). - **Resources**: 2–3 developers, 2–3 months. - **Challenges**: Varying API limitations across platforms. #### **B. Real-Time Collaboration Mode** - **Description**: Enable multiple users to interact with AI feedback simultaneously (e.g., threaded discussions, vote on fixes). - **Impact**: Streamlines team collaboration and decision-making. - **Complexity**: Medium (real-time sync, conflict resolution). - **Resources**: 2 backend developers, 1 frontend developer, 3–4 months. - **Challenges**: Scaling real-time features for large PRs. #### **C. Predictive Impact Analysis** - **Description**: Use AI to predict how code changes might affect system performance or security in production (e.g., "This loop could cause latency spikes at scale"). - **Impact**: Proactively prevents regressions. - **Complexity**: High (requires training ML models on historical performance data). - **Resources**: 1 ML engineer, 2 backend developers, 4–6 months. - **Challenges**: Data collection and model accuracy. #### **D. Automated Remediation for Simple Fixes** - **Description**: Offer one-click fixes for low-complexity issues (e.g., updating deprecated dependencies, fixing syntax errors). - **Impact**: Reduces manual toil for trivial tasks. - **Complexity**: Medium (code generation + safety checks). - **Resources**: 2 developers, 3 months. - **Challenges**: Ensuring automated fixes don't introduce new bugs. #### **E. Developer Learning Hub** - **Description**: Curate a knowledge base of common issues flagged by the tool, with links to tutorials and best practices. - **Impact**: Turns code reviews into teaching moments, improving team skills. - **Complexity**: Medium (content curation + UI integration). - **Resources**: 1 technical writer, 1 developer, 2 months. - **Challenges**: Keeping content updated. --- ### **3. Transformative Ideas (Long-Term, Innovative Solutions)** --- ``` -------------------------------- ### Creating Custom Error Class for Code Review Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/code-review.md Defines a custom `CodeReviewError` class extending the built-in `Error`, adding a `isUserSafe` property to indicate whether the error message is safe to expose to the user, improving error handling consistency and security. ```typescript class CodeReviewError extends Error { public readonly isUserSafe: boolean; constructor(message: string, isUserSafe: boolean) { super(message); this.isUserSafe = isUserSafe; } } ``` -------------------------------- ### Request Concept for AI Code Review Tool (JSON) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/brainstorm-enhancements.md Defines the initial concept for an AI-powered code review tool that integrates with GitHub to analyze pull requests for quality, security, and performance, providing inline comments and a summary report. ```json { "concept": "A code review tool that integrates with GitHub and uses AI to automatically analyze pull requests, focusing on code quality, security vulnerabilities, and performance issues. The tool currently provides inline comments on the PR and a summary report." } ``` -------------------------------- ### Handling Code Review Tool Request in TypeScript Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/examples/code-review.md This TypeScript function `handler` processes incoming requests for a code review tool. It performs input validation, checks for rate limits, reads code content either from a specified file path or directly from a provided snippet, sanitizes the input, constructs a prompt using a predefined template, calls the Deepseek API for the review, and returns a structured response indicating success or failure. ```typescript import type { ToolDefinition, CodeReviewArgs, ToolResponse } from '../../types/index.js'; import { makeDeepseekAPICall, checkRateLimit } from '../../api/deepseek/deepseek.js'; import { readFileContent } from '../../utils/file.js'; import { createPrompt, PromptTemplate, sanitizeInput } from '../../utils/prompt.js'; const SYSTEM_PROMPT = `You are an expert code reviewer...`; const PROMPT_TEMPLATE: PromptTemplate = { template: `Review the following {language} code...`, systemPrompt: SYSTEM_PROMPT }; export const definition: ToolDefinition = { name: 'code_review', description: 'Provides a code review...', inputSchema: { type: 'object', properties: { file_path: { type: 'string', description: 'The full path...' }, language: { type: 'string', description: 'The programming language...' }, code_snippet: { type: 'string', description: 'Optional small code...' } }, oneOf: [ { required: ['file_path', 'language'] }, { required: ['code_snippet', 'language'] } ] } }; export async function handler(args: unknown): Promise { if (!checkRateLimit()) { return { content: [{ type: 'text', text: 'Rate limit exceeded' }], isError: true }; } if (!args || typeof args !== 'object') { return { content: [{ type: 'text', text: 'Invalid arguments' }], isError: true }; } if (!('language' in args) || typeof args.language !== 'string') { return { content: [{ type: 'text', text: 'Language required' }], isError: true }; } try { let codeToReview: string; const typedArgs = args as CodeReviewArgs; if (typedArgs.file_path) { try { codeToReview = await readFileContent(typedArgs.file_path); } catch (error) { return { content: [{ type: 'text', text: `Error reading file: ${error}` }], isError: true }; } } else if (typedArgs.code_snippet) { codeToReview = typedArgs.code_snippet; } else { return { content: [{ type: 'text', text: 'File path or snippet required' }], isError: true }; } const sanitizedCode = sanitizeInput(codeToReview); const sanitizedLanguage = sanitizeInput(typedArgs.language); const prompt = createPrompt(PROMPT_TEMPLATE, { language: sanitizedLanguage, code: sanitizedCode }); const response = await makeDeepseekAPICall(prompt, SYSTEM_PROMPT); if (response.isError) { return { content: [{ type: 'text', text: `Error: ${response.errorMessage}` }], isError: true }; } return { content: [{ type: 'text', text: response.text }] }; } catch (error) { console.error('Code review error:', error); return { content: [{ type: 'text', text: `Error: ${error}` }], isError: true }; } } ``` -------------------------------- ### Configuring MCP Client for mentor-mcp-server (JSON) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/README.md Shows the JSON configuration required within an MCP client's settings to register and launch the mentor-mcp-server. It specifies the command to run the server and includes environment variables for Deepseek API key and model settings. ```json { "mcpServers": { "mentor": { "command": "node", "args": ["build/index.js"], "env": { "DEEPSEEK_API_KEY": "your_api_key", "DEEPSEEK_MODEL": "deepseek-reasoner", "DEEPSEEK_MAX_TOKENS": "8192", "DEEPSEEK_MAX_RETRIES": "3", "DEEPSEEK_TIMEOUT": "30000" } } } } ``` -------------------------------- ### Using the Code Review MCP Tool (XML) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/README.md Illustrates the XML format used by MCP clients to invoke the `code_review` tool on the mentor-mcp-server. It specifies the server name, tool name, and arguments including the file path and language for the review. ```xml mentor-mcp-server code_review { "file_path": "src/app.ts", "language": "typescript" } ``` -------------------------------- ### Using the Design Critique MCP Tool (XML) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/README.md Shows the XML format for invoking the `design_critique` tool on the mentor-mcp-server through an MCP client. It includes the server name, tool name, and arguments specifying the design document path and type. ```xml mentor-mcp-server design_critique { "design_document": "path/to/design.fig", "design_type": "web UI" } ``` -------------------------------- ### Using the Brainstorm Enhancements MCP Tool (XML) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/README.md Illustrates the XML format for invoking the `brainstorm_enhancements` tool on the mentor-mcp-server via an MCP client. It includes the server name, tool name, and arguments specifying the concept for brainstorming. ```xml mentor-mcp-server brainstorm_enhancements { "concept": "User authentication system" } ``` -------------------------------- ### Using the Writing Feedback MCP Tool (XML) Source: https://github.com/cyanheads/mentor-mcp-server/blob/main/README.md Provides the XML structure for an MCP client to request writing feedback from the mentor-mcp-server. It specifies the server name, tool name, and arguments containing the text content and its type. ```xml mentor-mcp-server writing_feedback { "text": "Documentation content...", "writing_type": "documentation" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.