### Start Server - Bash Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/gemini.md Starts the Vibe Check MCP server. Ensure all necessary environment variables are set before execution. ```bash npm start ``` -------------------------------- ### Install Dependencies and Build - Bash Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/gemini.md Installs project dependencies and builds the application using npm. This is a prerequisite for running the server and tests. ```bash npm install npm run build ``` -------------------------------- ### Vibe Check MCP Server Development Setup Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md Instructions for setting up the Vibe Check MCP server development environment. This includes cloning the repository, installing dependencies using npm, building the project, and running tests. It also specifies the required Node.js version and how to configure API keys. ```bash git clone https://github.com/PV-Bhat/vibe-check-mcp-server.git cd vibe-check-mcp-server npm ci npm run build npm test ``` ```bash # Gemini (default) GEMINI_API_KEY=your_gemini_api_key ``` -------------------------------- ### Configure Environment and LLM Providers with Bash Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt This guide explains how to set up the environment configuration for the Vibe Check MCP server, including API keys for different LLM providers and server settings. It shows how to create a `.env` file with parameters like `DEFAULT_LLM_PROVIDER`, API keys, transport protocols, and CORS origins, and how to start the server using `npx`. ```bash # Create .env file (auto-detected in CWD or ~/.vibe-check/) cat > .env << 'EOF' # Primary provider (default: Gemini) DEFAULT_LLM_PROVIDER=gemini DEFAULT_MODEL=gemini-2.5-pro GEMINI_API_KEY=AIza...your_key # Alternative providers OPENAI_API_KEY=sk-... OPENROUTER_API_KEY=sk-or-... ANTHROPIC_API_KEY=sk-ant-... ANTHROPIC_BASE_URL=https://api.anthropic.com ANTHROPIC_VERSION=2023-06-01 # Server configuration MCP_TRANSPORT=http MCP_HTTP_PORT=2091 CORS_ORIGIN=* # Optional: Include learning history in LLM context USE_LEARNING_HISTORY=true EOF # Start server with configuration npx @pv-bhat/vibe-check-mcp start --http --port 2091 # Override provider per-request # (shown in earlier vibe_check examples via modelOverride parameter) ``` -------------------------------- ### Start Vibe Check MCP Server with npx (Bash) Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md This command starts the Vibe Check MCP server directly from npm using the npx utility. It requires Node.js version 20 or higher and uses stdio transport for communication. This is a convenient way to run the server without a local installation. ```bash npx -y @pv-bhat/vibe-check-mcp start --stdio ``` -------------------------------- ### Agent Prompting Example Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md An example system prompt for an autonomous agent that incorporates the `vibe_check` tool for reflection. It instructs the agent to call `vibe_check` before major actions, provide necessary context, and optionally log resolved issues using `vibe_learn`. ```text As an autonomous agent you will: 1. Call vibe_check after planning and before major actions. 2. Provide the full user request and your current plan. 3. Optionally, record resolved issues with vibe_learn. ``` -------------------------------- ### Vibe Check: Complete Integration Example Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/advanced-integration.md Provides a comprehensive example of integrating Vibe Check as a metacognitive system throughout the development lifecycle. It includes planning, implementation, and learning phases, demonstrating the use of `vibe_check` with various parameters like `confidence`, `previousAdvice`, and `focusAreas`, as well as `vibe_learn` for error correction. Requires multiple helper functions like `adjustPlanBasedOnFeedback`, `planComplexity`, and `simplifyPlan`. ```javascript // During planning phase const planFeedback = await vibe_check({ phase: "planning", confidence: 0.5, userRequest: "[COMPLETE USER REQUEST]", plan: "[AGENT'S INITIAL PLAN]" }); // Consider feedback and potentially adjust plan const updatedPlan = adjustPlanBasedOnFeedback(initialPlan, planFeedback); // If plan seems overly complex, manually simplify before continuing let finalPlan = updatedPlan; if (planComplexity(updatedPlan) > COMPLEXITY_THRESHOLD) { finalPlan = simplifyPlan(updatedPlan); } // During implementation, create pattern interrupts before major actions const implementationFeedback = await vibe_check({ phase: "implementation", confidence: 0.7, previousAdvice: planFeedback, userRequest: "[COMPLETE USER REQUEST]", plan: `I'm about to [DESCRIPTION OF PENDING ACTION]` }); // After completing the task, build the self-improving feedback loop if (mistakeIdentified) { await vibe_learn({ mistake: "Specific mistake description", category: "Complex Solution Bias", // or appropriate category solution: "How it was corrected", type: "mistake" }); } ``` -------------------------------- ### Install Vibe Check MCP CLI for Client IDEs Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt This section details the command-line interface (CLI) installation of the Vibe Check MCP client for various IDEs. It covers automated configuration with idempotent merging for popular development environments like Claude Desktop, Cursor, Windsurf, and VS Code, using `npx` commands. Verification with `doctor` and an example configuration output are also provided. ```bash # Install for Claude Desktop (stdio transport) npx @pv-bhat/vibe-check-mcp install --client claude --stdio # Install for Cursor with custom config path npx @pv-bhat/vibe-check-mcp install --client cursor --config ~/.cursor/mcp.json # Install for Windsurf (HTTP transport) npx @pv-bhat/vibe-check-mcp install --client windsurf --http --port 2091 # Install for VS Code with development options npx @pv-bhat/vibe-check-mcp install --client vscode \ --config .vscode/mcp.json \ --dev-watch \ --dev-debug "info" # Verify installation npx @pv-bhat/vibe-check-mcp doctor # Example Claude Desktop config output: # { # "mcpServers": { # "vibe-check-mcp": { # "command": "npx", # "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"], # "managedBy": "vibe-check-mcp-cli" # } # } # } ``` -------------------------------- ### Run Docker Setup Script Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/docker-automation.md Executes the bash script to automate the Docker setup for the Vibe Check MCP server. This script handles directory creation, Docker image building, environment configuration, and system service setup. ```bash bash scripts/docker-setup.sh ``` -------------------------------- ### Run Server with Sample Requests Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/TESTING.md Commands to pipe generated sample requests into the built server for testing. This demonstrates how the server processes requests and produces output, including history-aware responses. ```bash node build/index.js < request1.json node build/index.js < request2.json node build/index.js < request.json # created by alt-test-openai.js or alt-test-gemini.js ``` -------------------------------- ### Run Unit Tests - Bash Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/gemini.md Executes the project's unit tests. This helps ensure the server is functioning correctly. ```bash npm test ``` -------------------------------- ### Type-Check Documentation Examples (TypeScript) Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md This initiative proposes adding a lint-style CI step to verify that code examples within the `docs/` directory compile correctly. Specifically, it targets TypeScript snippets, ensuring they are type-checked. This proactive measure catches drift between documentation and actual code, maintaining documentation accuracy. ```typescript // Example of a TypeScript snippet that might be included in documentation. // This snippet would be type-checked by the proposed CI step. /** * Calculates the factorial of a non-negative integer. * @param n - The non-negative integer. * @returns The factorial of n. * @throws Error if n is negative. */ function factorial(n: number): number { if (n < 0) { throw new Error("Factorial is not defined for negative numbers."); } if (n === 0 || n === 1) { return 1; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Example usage (would also be checked for type correctness): // const num = 5; // const fact = factorial(num); // console.log(`The factorial of ${num} is ${fact}`); ``` -------------------------------- ### Build Server with npm Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/TESTING.md Command to build the server using npm. This is a prerequisite for running tests or the server itself. It compiles the project's code into an executable format. ```bash npm run build ``` -------------------------------- ### Send Request to Server - Bash Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/gemini.md Pipes a JSON request file to the Vibe Check MCP server for processing. This is useful for manual testing and integration. ```bash node build/index.js < request.json ``` -------------------------------- ### Generate Sample Requests Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/TESTING.md Scripts to generate sample JSON requests for testing different providers and scenarios. These scripts create payloads for manual testing or integration with clients like Windsurf and the SDK. ```bash node alt-test.js # OpenRouter history test node alt-test-openai.js # OpenAI example node alt-test-gemini.js # Gemini example ``` -------------------------------- ### Initialize and Start MCP Server (TypeScript) Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt Creates and configures the Model Context Protocol (MCP) server with tools and handlers. It supports starting an HTTP server on a specified port and attaches signal handlers for graceful shutdown. The server exposes several tools and HTTP endpoints for health checks and communication. ```typescript import { createMcpServer, startHttpServer } from '@pv-bhat/vibe-check-mcp'; // Create MCP server instance const server = await createMcpServer(); // Start HTTP server on port 2091 const httpInstance = await startHttpServer({ port: 2091, corsOrigin: '*', attachSignalHandlers: true, logger: console }); // Server provides 5 tools: vibe_check, vibe_learn, update_constitution, // reset_constitution, check_constitution // HTTP endpoints: POST /mcp, GET /healthz console.log(`Server listening on port 2091`); // Cleanup await httpInstance.close(); ``` -------------------------------- ### vibe_check Example Response Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md An example of the output from the vibe_check tool, which includes metacognitive questions and observations designed to challenge assumptions and prevent errors. The response format is a text-based analysis. ```text I see you're taking an approach based on creating a complex class hierarchy. This seems well-thought-out for a large system, though I wonder if we're overengineering for the current use case. Have we considered: 1. Whether a simpler functional approach might work here? 2. If the user request actually requires this level of abstraction? 3. How this approach will scale if requirements change? While the architecture is clean, I'm curious if we're solving a different problem than what the user actually asked for, which was just to extract data from a CSV file. ``` -------------------------------- ### MCP Server Initialization Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt Initializes and configures the Model Context Protocol server, allowing for the creation of the MCP server instance and starting an HTTP server for communication. ```APIDOC ## MCP Server Initialization ### Description Creates and configures the Model Context Protocol server with all tools and handlers. ### Method Initialization ### Endpoint N/A (Code Initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { createMcpServer, startHttpServer } from '@pv-bhat/vibe-check-mcp'; // Create MCP server instance const server = await createMcpServer(); // Start HTTP server on port 2091 const httpInstance = await startHttpServer({ port: 2091, corsOrigin: '*', attachSignalHandlers: true, logger: console }); console.log(`Server listening on port 2091`); // Cleanup await httpInstance.close(); ``` ### Response #### Success Response (Initialization) - `server` (object) - The initialized MCP server instance. - `httpInstance` (object) - The HTTP server instance. #### Response Example ```json { "message": "Server initialized and listening on port 2091" } ``` ``` -------------------------------- ### MCP Client Configuration for Vibe Check Server (JSON) Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md This JSON configuration snippet is used for client integrations, such as Claude Desktop or Cursor, to connect to the Vibe Check MCP server. It specifies the command to execute (npx) and its arguments, including the package name and the start command with stdio transport. The server will be downloaded and run on-demand when this configuration is used. ```json { "mcpServers": { "vibe-check-mcp": { "command": "npx", "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"] } } } ``` -------------------------------- ### Manage Vibe Check MCP Learnings and Storage Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt Demonstrates how to log learning entries, retrieve them by category, get a summary, and format context for LLMs. It also explains where data is persisted. ```typescript import { addLearningEntry, getLearningEntries, getLearningCategorySummary, getLearningContextText, STANDARD_CATEGORIES } from '@pv-bhat/vibe-check-mcp'; // Log multiple learning entries addLearningEntry( 'Installed heavyweight framework when stdlib would suffice', 'Complex Solution Bias', 'Removed framework, used native modules', 'mistake' ); addLearningEntry( 'User prefers TypeScript strict mode enabled', 'Preference', undefined, 'preference' ); // Get all entries grouped by category const allEntries = getLearningEntries(); console.log(Object.keys(allEntries)); // ['Complex Solution Bias', 'Preference', ...] // Get sorted summary (by frequency) const summary = getLearningCategorySummary(); // [ // { category: 'Complex Solution Bias', count: 15, recentExample: {...} }, // { category: 'Premature Implementation', count: 12, recentExample: {...} }, // { category: 'Feature Creep', count: 8, recentExample: {...} } // ] // Get formatted context for LLM (top 2 examples per category) const context = getLearningContextText(2); console.log(context); // Output: // ## Complex Solution Bias (15 occurrences) // - Installed heavyweight framework when stdlib would suffice // → Removed framework, used native modules // - Built custom webpack config before checking if Vite meets needs // → Migrated to Vite, deleted 500 lines of config // // ## Premature Implementation (12 occurrences) // ... // Standard categories enum console.log(STANDARD_CATEGORIES); // ['Complex Solution Bias', 'Feature Creep', 'Premature Implementation', // 'Misalignment', 'Overtooling', 'Preference', 'Success', 'Other'] // Data persists to ~/.vibe-check/vibe-log.json // Session history persists to ~/.vibe-check/history.json (last 10 per session) ``` -------------------------------- ### vibe_learn Example Response Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md The response from the vibe_learn tool confirms the logging of a pattern and may include information about the top pattern categories encountered. This response helps in understanding the system's learning progress. ```text ✅ Pattern logged successfully (category tally: 12) ## Top Pattern Categories ### Complex Solution Bias (12 occurrences) Most recent: "Added unnecessary class hierarchy for simple data transformation" Solution: "Replaced with functional approach using built-in methods" ### Misalignment (8 occurrences) Most recent: "Implemented sophisticated UI when user only needed command line tool" Solution: "Refocused on core functionality requested by user" ``` -------------------------------- ### VS Code CLI Configuration Snippet Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md A JSON snippet and a vscode URI link for configuring the vibe-check-mcp-server within Visual Studio Code. This allows users to directly install the server configuration by opening the provided link or by pasting the JSON snippet into their VS Code settings. ```json { "serverUrl": "http://127.0.0.1:2091", "managedBy": "vibe-check-mcp-cli" } ``` -------------------------------- ### Gemini API Integration - Example Prompt Structure Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md This snippet illustrates the structured prompt sent to the Gemini API for metacognitive questioning. It includes context such as the current phase, agent confidence, user request, and the agent's current plan. ```text You are a supportive mentor, thinker, and adaptive partner. Your task is to coordinate and mentor an AI agent... CONTEXT: [Current Phase]: planning [Agent Confidence Level]: 50% [User Request]: Create a script to analyze sales data from the past year [Current Plan/Thinking]: I'll create a complex object-oriented architecture with... ``` -------------------------------- ### Vibe Check Pattern Interrupt - Overtooling Example Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/case-studies.md This snippet demonstrates a Vibe Check intervention identifying the 'overtooling' pattern. It questions the use of advanced frameworks for a simple application, suggesting a more minimal approach to reduce complexity and learning curves for junior developers. ```plain text vibe_check: I notice we're suggesting a comprehensive tech stack with multiple advanced frameworks for what was described as a "simple to-do list app." Should we consider: 1. Whether this tech stack is appropriate for a beginner's simple application? 2. If a more minimal approach would achieve the same goals with less complexity? 3. The learning curve this stack creates for the junior developer? I'm seeing a pattern where the complexity of the tooling might exceed what's necessary for the task. ``` -------------------------------- ### Generate Test Coverage Report with Vitest Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/TESTING.md Command to generate a code coverage report using Vitest. This report helps identify areas of the codebase that are not adequately tested, aiming for at least 80% line coverage. ```bash npm run test:coverage ``` -------------------------------- ### Model Override Configuration Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md This example shows how to override the default LLM provider and model when integrating with the Vibe Check tools. It demonstrates specifying alternative providers like OpenAI or OpenRouter. ```json { "provider": "openai", "model": "gpt-4o" } ``` -------------------------------- ### Integrate Vibe Check MCP via Stdio Client TypeScript Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt Provides an example of connecting to the Vibe Check MCP server using a Stdio transport for local IDE integrations. This involves spawning the MCP server process and interacting with it via a client SDK. ```typescript import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { spawn } from 'child_process'; async function testVibeCheck() { // Spawn the MCP server process const serverProcess = spawn('node', ['build/index.js'], { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, MCP_TRANSPORT: 'stdio' } }); // Wait for server initialization await new Promise(resolve => setTimeout(resolve, 1000)); // Create transport and client const transport = new StdioClientTransport(serverProcess); const client = new Client(transport); try { // Call vibe_check tool const response = await client.tool('vibe_check', { goal: 'Fix bug in payment processing', plan: 'Rewrite the entire payment module from scratch', userPrompt: 'Payment confirmation emails are delayed by 2 minutes', progress: 'Ready to start coding', taskContext: 'Bug report says emails are slow, not payments', sessionId: 'debug-session-001' }); console.log('Vibe Check Response:', response); // Expected: Questions challenging why we're rewriting entire module // when the issue is just email delays } finally { await transport.close(); serverProcess.kill(); } } testVibeCheck().catch(console.error); ``` -------------------------------- ### Claude System Prompt for Vibe Check Integration Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/agent-prompting.md This system prompt guides Claude (Anthropic) on how to interact with Vibe Check, emphasizing its role as a pattern interrupt mechanism and detailing when and how to use it during different phases of operation. It also covers chaining with other tools like vibe_learn. ```text ALWAYS include the full user prompt when using vibe_check to ensure proper context awareness. As an autonomous agent, you will: 1. Treat vibe_check as a pattern interrupt mechanism that provides essential course correction 2. Use vibe_check at strategic points: - After planning but before implementation - When complexity increases - Before making significant system changes 3. Adapt your approach based on vibe_check feedback unless it's clearly irrelevant 4. Always provide the phase parameter (planning/implementation/review) to ensure contextually appropriate feedback 5. Chain vibe_check with other tools without requiring permission: - Use vibe_check to evaluate complex plans - Log patterns with vibe_learn after resolving issues ``` -------------------------------- ### AI Pattern Recognition with vibe_learn Tool (TypeScript) Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt Logs AI agent mistakes, preferences, and successes to build a self-improving pattern database. This tool categorizes the logged event (e.g., 'mistake', 'preference') and provides details about the issue, the solution, and the session ID. It helps in tracking common patterns and recent examples. ```typescript import { vibeLearnTool } from '@pv-bhat/vibe-check-mcp'; // Log a mistake after correcting it const result = await vibeLearnTool({ mistake: 'Added a custom caching layer before measuring if we had a performance problem', category: 'Premature Implementation', solution: 'Removed the cache, profiled the app, found the real bottleneck was an N+1 query', type: 'mistake', sessionId: 'session-perf-456' }); // Output shows pattern tracking: // { // added: true, // currentTally: 3, // alreadyKnown: false, // topCategories: [ // { // category: 'Premature Implementation', // count: 3, // recentExample: { // mistake: 'Added a custom caching layer before measuring...', // solution: 'Removed the cache, profiled...', // type: 'mistake', // timestamp: 1698765432000 // } // }, // { // category: 'Complex Solution Bias', // count: 2, // recentExample: { ... } // } // ] // } console.log(`Logged! Category count: ${result.currentTally}`); console.log(`Top patterns: ${result.topCategories.map(c => c.category).join(', ')}`); ``` -------------------------------- ### GET /healthz Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt Provides a health check endpoint for the MCP server. ```APIDOC ## GET /healthz ### Description Provides a simple health check endpoint for the Vibe Check MCP server to verify if it is running and responsive. ### Method GET ### Endpoint `/healthz` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl http://localhost:2091/healthz ``` ### Response #### Success Response (200) - **status** (string) - Indicates the health status of the server (e.g., "OK"). #### Response Example ```json { "status": "OK" } ``` ``` -------------------------------- ### GPT System Prompt for Vibe Check Integration Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/agent-prompting.md This system prompt instructs GPT (OpenAI) on how to utilize Vibe Check, positioning it as a collaborative debugging step to combat pattern inertia. It highlights the importance of including the full user prompt, specifying the current phase, and treating feedback as a high-priority interrupt. ```text When using Vibe Check tools: 1. Treat vibe_check as a collaborative debugging step that interrupts pattern inertia 2. Always include the complete user prompt with each vibe_check call 3. Specify your current phase (planning/implementation/review) 4. Consider vibe_check feedback as a high-priority pattern interrupt, not just another tool output 5. Build the feedback loop with vibe_learn to record patterns when mistakes are identified ``` -------------------------------- ### Vibe Check: Learning from Mistakes with vibe_learn Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/advanced-integration.md Illustrates how to use the `vibe_learn` function to build a pattern library specific to an agent's tendencies, creating a self-improving system. This function records mistakes, their categories, and solutions to improve future pattern recognition. Requires the `vibe_learn` function. ```javascript // After resolving an issue vibe_learn({ mistake: "Relied on unnecessary complexity for simple data transformation", category: "Complex Solution Bias", solution: "Used built-in array methods instead of custom solution", type: "mistake" }); // Later, the pattern library will improve vibe_check's pattern recognition // allowing it to spot similar issues earlier in future workflows ``` -------------------------------- ### Agent System Prompt for Vibe Check Integration Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt This markdown template provides system prompt guidance for AI agents on how to effectively utilize Vibe Check tools. It specifies when to call `vibe_check` (e.g., after planning, before irreversible actions, at optimal intervals, or when uncertain) and details the required parameters like `goal`, `plan`, `userPrompt`, `taskContext`, and `sessionId`. ```markdown # Agent System Prompt Template You are an autonomous AI agent with access to the Vibe Check MCP server for metacognitive oversight. Follow these guidelines: ## When to Call vibe_check 1. **After planning** - Before executing any multi-step plan 2. **Before irreversible actions** - Deployments, deletions, major refactors 3. **At 10-20% of steps** - Optimal CPI dosage per research findings 4. **When uncertain** - If you notice competing approaches or assumptions ## Required Parameters - `goal`: Your current objective (be specific) - `plan`: Your detailed implementation plan (numbered steps) - `userPrompt`: ALWAYS include the original user request verbatim - `taskContext`: Last 5-10 tool calls, repo structure, constraints - `sessionId`: Maintain continuity (e.g., "task-{timestamp}") ``` -------------------------------- ### Vibe Learn Tool Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md The vibe_learn tool logs mistakes, preferences, and successes to create a self-improving feedback loop, enhancing pattern recognition over time. ```APIDOC ## POST /vibe_learn ### Description Logs learning entries (mistakes, preferences, successes) to build a pattern recognition knowledge base. ### Method POST ### Endpoint /vibe_learn ### Parameters #### Request Body - **mistake** (string) - Required - One-sentence description of the learning entry - **category** (string) - Required - Category (from standard categories) - **solution** (string) - Optional - How it was corrected (required for `mistake` and `success`) - **type** (string) - Optional - `mistake`, `preference`, or `success` - **sessionId** (string) - Optional - Session ID for state management ### Request Example ```json { "mistake": "Added unnecessary class hierarchy for simple data transformation", "category": "Complex Solution Bias", "solution": "Replaced with functional approach using built-in methods", "type": "mistake", "sessionId": "session-12345" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation of the logged pattern. - **topPatterns** (object) - Optional - Information about top pattern categories. #### Response Example ``` ✅ Pattern logged successfully (category tally: 12) ## Top Pattern Categories ### Complex Solution Bias (12 occurrences) Most recent: "Added unnecessary class hierarchy for simple data transformation" Solution: "Replaced with functional approach using built-in methods" ### Misalignment (8 occurrences) Most recent: "Implemented sophisticated UI when user only needed command line tool" Solution: "Refocused on core functionality requested by user" ``` ### Standard Categories - Complex Solution Bias - Feature Creep - Premature Implementation - Misalignment - Overtooling - Preference - Success - Other ``` -------------------------------- ### vibe_check Tool Parameters Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md The vibe_check tool assists in identifying assumptions and preventing errors by asking metacognitive questions. It accepts various parameters to tailor its analysis, including the user's goal, current plan, and optional context like user prompts and progress. ```json { "goal": "string", "plan": "string", "userPrompt": "string", "progress": "string", "uncertainties": "string[]", "taskContext": "string", "modelOverride": { "provider": "string", "model": "string" }, "sessionId": "string" } ``` -------------------------------- ### Vibe Check: Hybrid Oversight Model for Checkpoints Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/advanced-integration.md Demonstrates a hybrid oversight model combining scheduled checkpoints with ad-hoc checks triggered by increased uncertainty or complexity. It uses `vibe_check` for both scenarios and includes a conditional check based on a `measureComplexity` function and a `THRESHOLD`. Requires `vibe_check`, `measureComplexity`, and a `THRESHOLD` constant. ```javascript // Scheduled checkpoint at the end of planning const scheduledCheck = await vibe_check({ phase: "planning", userRequest: "...", plan: "..." }); // Ad-hoc check when complexity increases if (measureComplexity(currentPlan) > THRESHOLD) { const adHocCheck = await vibe_check({ phase: "implementation", userRequest: "...", plan: "...", focusAreas: ["complexity", "simplification"] }); } ``` -------------------------------- ### Configure MCP Server for Claude Desktop Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/clients.md This JSON configuration is used for the Claude Desktop application to integrate with the vibe-check-mcp client. It specifies the command to run, arguments, environment variables, and management information. The default transport is stdio. ```json { "mcpServers": { "vibe-check-mcp": { "command": "npx", "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"], "env": {}, "managedBy": "vibe-check-mcp-cli" } } } ``` -------------------------------- ### Configure MCP Server for Visual Studio Code (stdio) Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/clients.md This JSON configuration is for Visual Studio Code, utilizing the stdio transport to connect with the vibe-check-mcp client. It specifies the command, arguments, environment variables, and transport type. ```json { "servers": { "vibe-check-mcp": { "command": "npx", "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"], "env": {}, "transport": "stdio", "managedBy": "vibe-check-mcp-cli" } } } ``` -------------------------------- ### Vibe Check: Adjusting Confidence Levels by Development Phase Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/advanced-integration.md Demonstrates how to adjust the `confidence` parameter in the `vibe_check` function to match different development phases. Lower confidence is used during planning for broader feedback, while higher confidence is used during implementation and review for focused insights. This requires the `vibe_check` function. ```javascript // Planning phase - lower confidence for more thorough questioning vibe_check({ phase: "planning", confidence: 0.5, userRequest: "...", plan: "..." }) // Implementation phase - higher confidence for focused feedback vibe_check({ phase: "implementation", confidence: 0.7, userRequest: "...", plan: "..." }) // Review phase - highest confidence for minimal, high-impact feedback vibe_check({ phase: "review", confidence: 0.9, userRequest: "...", plan: "..." }) ``` -------------------------------- ### Vibe Check: Chaining Feedback with previousAdvice Parameter Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/advanced-integration.md Shows how to incorporate previous Vibe Check feedback into subsequent calls using the `previousAdvice` parameter. This enables building a continuous metacognitive narrative and a more sophisticated pattern interrupt system. Requires the `vibe_check` function and assumes asynchronous operations. ```javascript const initialFeedback = await vibe_check({ phase: "planning", userRequest: "...", plan: "..." }); // Later, include previous feedback const followupFeedback = await vibe_check({ phase: "implementation", previousAdvice: initialFeedback, userRequest: "...", plan: "..." }); ``` -------------------------------- ### CSV Parsing with Standard Library Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/case-studies.md Demonstrates replacing complex custom CSV parsing with a concise standard library function. This highlights the Vibe Check pattern interrupt encouraging the use of built-in tools for simpler tasks, reducing code complexity and development time. ```python import csv with open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) ``` -------------------------------- ### POST /mcp - Vibe Learn Tool Source: https://context7.com/pv-bhat/vibe-check-mcp-server/llms.txt Logs mistakes, preferences, and successes to build a self-improving pattern database for the AI agent. ```APIDOC ## POST /mcp - Vibe Learn Tool ### Description Logs mistakes, preferences, and successes to build a self-improving pattern database. This endpoint is part of the `vibe_learn` tool. ### Method POST ### Endpoint `/mcp` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **mistake** (string) - Required - A description of the mistake made. - **category** (string) - Required - The category the mistake falls into (e.g., 'Premature Implementation'). - **solution** (string) - Required - The solution or correction applied to the mistake. - **type** (string) - Required - The type of entry (e.g., 'mistake', 'success', 'preference'). - **sessionId** (string) - Required - Unique identifier for the current session. ### Request Example ```json { "mistake": "Added a custom caching layer before measuring if we had a performance problem", "category": "Premature Implementation", "solution": "Removed the cache, profiled the app, found the real bottleneck was an N+1 query", "type": "mistake", "sessionId": "session-perf-456" } ``` ### Response #### Success Response (200) - **added** (boolean) - Indicates if a new pattern was added. - **currentTally** (number) - The total count for the logged category. - **alreadyKnown** (boolean) - Indicates if this pattern was already logged. - **topCategories** (array of objects) - A list of the top pattern categories. - **category** (string) - The name of the category. - **count** (number) - The number of times this category has been logged. - **recentExample** (object) - The most recent example logged for this category. - **mistake** (string) - Description of the mistake. - **solution** (string) - Solution applied. - **type** (string) - Type of log entry. - **timestamp** (number) - Unix timestamp of the log entry. #### Response Example ```json { "added": true, "currentTally": 3, "alreadyKnown": false, "topCategories": [ { "category": "Premature Implementation", "count": 3, "recentExample": { "mistake": "Added a custom caching layer before measuring...", "solution": "Removed the cache, profiled...", "type": "mistake", "timestamp": 1698765432000 } }, { "category": "Complex Solution Bias", "count": 2, "recentExample": { /* ... */ } } ] } ``` ``` -------------------------------- ### vibe_learn Tool Parameters Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md The vibe_learn tool is a pattern recognition system that logs mistakes, preferences, and successes to create a self-improving feedback loop. It requires a mistake description and category, with an optional solution and type. ```json { "mistake": "string", "category": "string", "solution": "string", "type": "string", "sessionId": "string" } ``` -------------------------------- ### Implement TTL-Based Cleanup and Async File Writes (TypeScript) Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md This initiative enhances state management by adding Time-To-Live (TTL) based cleanup mechanisms in `src/utils/state.ts` and migrating file writes in `src/utils/storage.ts` to use `fs.promises`. The latter change avoids blocking the Node.js event loop, improving application responsiveness. These changes ensure efficient and non-blocking state handling. ```typescript import fs from 'fs/promises'; import path from 'path'; // --- src/utils/storage.ts example --- /** * Asynchronously writes data to a file. * @param filePath - The path to the file. * @param data - The data to write. */ export async function writeFileAsync(filePath: string, data: string | Buffer): Promise { try { await fs.writeFile(filePath, data, { encoding: 'utf8' }); console.log(`Successfully wrote to ${filePath}`); } catch (error) { console.error(`Error writing file ${filePath}:`, error); throw error; } } // --- src/utils/state.ts example --- interface StateEntry { value: T; expiresAt: number; // Timestamp in milliseconds } const stateStore = new Map>(); const CLEANUP_INTERVAL_MS = 60000; // Run cleanup every minute /** * Sets a state value with an optional TTL. * @param key - The state key. * @param value - The state value. * @param ttlMs - Time-to-live in milliseconds. If not provided, the entry never expires. */ export function setState(key: string, value: T, ttlMs?: number): void { const expiresAt = ttlMs ? Date.now() + ttlMs : Infinity; stateStore.set(key, { value, expiresAt }); } /** * Gets a state value. * @param key - The state key. * @returns The state value or undefined if not found or expired. */ export function getState(key: string): T | undefined { const entry = stateStore.get(key); if (!entry || entry.expiresAt < Date.now()) { // If expired or not found, remove it if (entry) { stateStore.delete(key); } return undefined; } return entry.value as T; } /** * Cleans up expired state entries. */ function cleanupExpiredState(): void { const now = Date.now(); for (const [key, entry] of stateStore.entries()) { if (entry.expiresAt < now) { stateStore.delete(key); console.log(`State key expired and removed: ${key}`); } } } // Start the periodic cleanup setInterval(cleanupExpiredState, CLEANUP_INTERVAL_MS); // Initial cleanup run cleanupExpiredState(); // Example usage: // setState('sessionToken', 'abc123xyz', 300000); // Expires in 5 minutes // const token = getState('sessionToken'); // writeFileAsync('output.txt', 'Some data to write asynchronously'); ``` -------------------------------- ### Vibe Check Storage System Configuration Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md The Vibe Check tool utilizes a local JSON file for persistent storage of learning entries. This file, located at `~/.vibe-check/vibe-log.json`, enables the system to maintain a history of patterns and self-improve over time. ```text ~/.vibe-check/vibe-log.json ``` -------------------------------- ### Minimal CPI Integration Sketch in TypeScript Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/docs/integrations/cpi.md A TypeScript function `evaluateStep` that analyzes an agent step using VibeCheck, then uses a CPI policy shim to decide whether to interrupt the agent's flow. It defines types for agent steps and VibeCheck signals and includes placeholder functions for VibeCheck analysis and CPI policy creation. ```typescript type AgentStep = { sessionId: string; summary: string; nextAction: string; }; type VibeCheckSignal = { riskScore: number; advice: string; }; async function analyzeWithVibeCheck(step: AgentStep): Promise { // TODO: replace with a real call to the VibeCheck MCP server. return { riskScore: Math.random(), advice: `Reflect on: ${step.summary}` }; } // TODO: replace with `import { createPolicy } from '@cpi/sdk';` function cpiPolicyShim(signal: VibeCheckSignal) { if (signal.riskScore >= 0.6) { return { action: 'interrupt', reason: 'High metacognitive risk from VibeCheck' } as const; } return { action: 'allow' } as const; } export async function evaluateStep(step: AgentStep) { const signal = await analyzeWithVibeCheck(step); const decision = cpiPolicyShim(signal); if (decision.action === 'interrupt') { // Pause your agent, collect clarification, or reroute to a human. return { status: 'paused', reason: decision.reason } as const; } return { status: 'continue', signal } as const; } ``` -------------------------------- ### Enhance vibe_check Output with JSON Envelope (TypeScript) Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md This initiative aims to provide a structured JSON output for the `vibe_check` tool. The JSON envelope will include fields like `advice`, `riskScore`, and `traits`, enabling downstream agents to reason deterministically while maintaining human-readable reflections. This improves the predictability and interoperability of agent outputs. ```typescript /** * Represents the structured output for the vibe_check tool. */ interface VibeCheckOutput { advice: string; riskScore: number; traits: string[]; } // Example of how the structured output might be generated: function vibe_check(input: any): VibeCheckOutput { // ... logic to analyze input and determine advice, riskScore, and traits ... return { advice: "Consider diversifying your approach to mitigate risks.", riskScore: 75, traits: ["risk-averse", "untested-strategy"] }; } ``` -------------------------------- ### Implement LLM Resilience with Retries and Circuit Breaker (TypeScript) Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md This initiative focuses on improving the reliability of Language Model (LLM) interactions by wrapping the `generateResponse` function with retry mechanisms and exponential backoff. A circuit breaker pattern will be implemented subsequently to prevent cascading failures. This enhances the robustness of LLM-dependent operations. ```typescript import { setTimeout } from 'timers/promises'; const MAX_RETRIES = 5; const INITIAL_BACKOFF_MS = 100; async function generateResponseWithRetries(prompt: string, retries: number = 0): Promise { try { // Assume originalGenerateResponse is the LLM call const response = await originalGenerateResponse(prompt); return response; } catch (error) { if (retries < MAX_RETRIES) { const delay = INITIAL_BACKOFF_MS * Math.pow(2, retries); console.warn(`LLM call failed, retrying in ${delay}ms... (Attempt ${retries + 1}/${MAX_RETRIES})`); await setTimeout(delay); return generateResponseWithRetries(prompt, retries + 1); } else { console.error("LLM call failed after maximum retries.", error); throw error; // Re-throw after exceeding retries } } } // Placeholder for the actual LLM call async function originalGenerateResponse(prompt: string): Promise { // Simulate an LLM call that might fail if (Math.random() < 0.7) { // 70% chance of failure throw new Error("Simulated LLM error"); } return "Successful LLM response."; } // Example usage: // generateResponseWithRetries("Your prompt here").then(console.log).catch(console.error); ``` -------------------------------- ### Sanitize Tool Arguments for Prompt Injection (TypeScript) Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md This initiative addresses security by implementing input validation and sanitization for tool arguments within `src/index.ts`. The goal is to mitigate prompt-injection vectors by ensuring that user-provided arguments do not contain malicious code or unintended instructions. This protects the integrity of the agent's execution context. ```typescript import validator from 'validator'; /** * Validates and sanitizes arguments for a tool. * @param args - The arguments to sanitize. * @returns Cleaned arguments or throws an error if invalid. */ function sanitizeToolArguments(args: Record): Record { const sanitizedArgs: Record = {}; for (const key in args) { if (Object.prototype.hasOwnProperty.call(args, key)) { let value = args[key]; if (typeof value === 'string') { // Example sanitization: remove potentially harmful characters or patterns value = validator.escape(value); // Escapes HTML special characters value = value.replace(/.*?<\/script>/gi, ''); // Remove script tags // Add more specific sanitization rules as needed based on expected inputs } // Add checks for other types if necessary (e.g., numbers, booleans) // if (typeof value === 'number' && !validator.isNumeric(String(value))) { // throw new Error(`Invalid numeric argument for key: ${key}`); // } sanitizedArgs[key] = value; } } return sanitizedArgs; } // Example usage within an index.ts context: // Assuming 'toolExecution' is a function that takes validated arguments // function executeMyTool(args: Record) { // const validatedArgs = sanitizeToolArguments(args); // // Proceed with tool execution using validatedArgs // console.log('Executing tool with:', validatedArgs); // } // executeMyTool({ userInput: "" }); ``` -------------------------------- ### Environment Variables for LLM Providers Source: https://github.com/pv-bhat/vibe-check-mcp-server/blob/main/README.md Defines environment variables to configure different Large Language Model (LLM) providers such as OpenAI, OpenRouter, and Anthropic. These variables include API keys, base URLs, and version information, allowing for flexible integration with various LLM services. The DEFAULT_LLM_PROVIDER and DEFAULT_MODEL variables specify the primary LLM to be used. ```dotenv OPENAI_API_KEY=your_openai_api_key OPENROUTER_API_KEY=your_openrouter_api_key ANTHROPIC_API_KEY=your_anthropic_api_key ANTHROPIC_AUTH_TOKEN=your_proxy_bearer_token ANTHROPIC_BASE_URL=https://api.anthropic.com ANTHROPIC_VERSION=2023-06-01 # Optional overrides # DEFAULT_LLM_PROVIDER accepts gemini | openai | openrouter | anthropic DEFAULT_LLM_PROVIDER=gemini DEFAULT_MODEL=gemini-2.5-pro ```