This is page 2 of 2. Use http://codebase.md/pv-bhat/vibe-check-mcp-server?page={x} to view the full context.
# Directory Structure
```
├── .env.example
├── .github
│ └── workflows
│ ├── ci.yml
│ ├── docker-image.yml
│ └── release.yml
├── .gitignore
├── AGENTS.md
├── alt-test-gemini.js
├── alt-test-openai.js
├── alt-test.js
├── Attachments
│ ├── Template.md
│ ├── VC1.png
│ ├── vc2.png
│ ├── vc3.png
│ ├── vc4.png
│ ├── VCC1.png
│ ├── VCC2.png
│ ├── vibe (1).jpeg
│ ├── vibelogo.png
│ └── vibelogov2.png
├── CHANGELOG.md
├── CITATION.cff
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── docs
│ ├── _toc.md
│ ├── advanced-integration.md
│ ├── agent-prompting.md
│ ├── AGENTS.md
│ ├── api-keys.md
│ ├── architecture.md
│ ├── case-studies.md
│ ├── changelog.md
│ ├── clients.md
│ ├── docker-automation.md
│ ├── gemini.md
│ ├── integrations
│ │ └── cpi.md
│ ├── philosophy.md
│ ├── registry-descriptions.md
│ ├── release-workflows.md
│ ├── technical-reference.md
│ └── TESTING.md
├── examples
│ └── cpi-integration.ts
├── glama.json
├── LICENSE
├── package-lock.json
├── package.json
├── README.md
├── request.json
├── scripts
│ ├── docker-setup.sh
│ ├── install-vibe-check.sh
│ ├── security-check.cjs
│ └── sync-version.mjs
├── SECURITY.md
├── server.json
├── smithery.yaml
├── src
│ ├── cli
│ │ ├── clients
│ │ │ ├── claude-code.ts
│ │ │ ├── claude.ts
│ │ │ ├── cursor.ts
│ │ │ ├── shared.ts
│ │ │ ├── vscode.ts
│ │ │ └── windsurf.ts
│ │ ├── diff.ts
│ │ ├── doctor.ts
│ │ ├── env.ts
│ │ └── index.ts
│ ├── index.ts
│ ├── tools
│ │ ├── constitution.ts
│ │ ├── vibeCheck.ts
│ │ ├── vibeDistil.ts
│ │ └── vibeLearn.ts
│ └── utils
│ ├── anthropic.ts
│ ├── httpTransportWrapper.ts
│ ├── jsonRpcCompat.ts
│ ├── llm.ts
│ ├── state.ts
│ ├── storage.ts
│ └── version.ts
├── test-client.js
├── test-client.ts
├── test.js
├── test.json
├── tests
│ ├── claude-config.test.ts
│ ├── claude-merge.test.ts
│ ├── cli-doctor-node.test.ts
│ ├── cli-doctor-port.test.ts
│ ├── cli-install-dry-run.test.ts
│ ├── cli-install-vscode-dry-run.test.ts
│ ├── cli-start-flags.test.ts
│ ├── cli-version.test.ts
│ ├── constitution.test.ts
│ ├── cursor-merge.test.ts
│ ├── env-ensure.test.ts
│ ├── fixtures
│ │ ├── claude
│ │ │ ├── config.base.json
│ │ │ ├── config.with-managed-entry.json
│ │ │ └── config.with-other-servers.json
│ │ ├── cursor
│ │ │ ├── config.base.json
│ │ │ └── config.with-managed-entry.json
│ │ ├── vscode
│ │ │ ├── workspace.mcp.base.json
│ │ │ └── workspace.mcp.with-managed.json
│ │ └── windsurf
│ │ ├── config.base.json
│ │ ├── config.with-http-entry.json
│ │ └── config.with-managed-entry.json
│ ├── index-main.test.ts
│ ├── jsonrpc-compat.test.ts
│ ├── llm-anthropic.test.ts
│ ├── llm.test.ts
│ ├── server.integration.test.ts
│ ├── startup.test.ts
│ ├── state.test.ts
│ ├── storage-utils.test.ts
│ ├── vibeCheck.test.ts
│ ├── vibeLearn.test.ts
│ ├── vscode-merge.test.ts
│ └── windsurf-merge.test.ts
├── tsconfig.json
├── version.json
└── vitest.config.ts
```
# Files
--------------------------------------------------------------------------------
/docs/case-studies.md:
--------------------------------------------------------------------------------
```markdown
# Case Studies
This document compiles real-world examples of how Vibe Check has helped prevent cascading errors in agent workflows. Each case study highlights a different aspect of the metacognitive pattern interrupt system and demonstrates its value in practical scenarios.
## Case Study 1: The Recursive Parser Problem
### The Scenario
A developer asked their AI assistant to parse a simple CSV file with just a few columns. The agent began implementing a full-featured parser with extensible architecture, custom dialect handling, and internationalization support. The parsing logic quickly grew to over 300 lines of code.
### The Cascade
This is a classic example of **overengineering**, a common pattern in AI agent workflows. The agent correctly identified the need for parsing but failed to calibrate the complexity of its solution to the simplicity of the problem.
### The Pattern Interrupt
After integrating Vibe Check, the developer received a metacognitive alert during the planning phase:
```
vibe_check: I notice you're planning to implement a custom CSV parser with extensive dialectic support.
This approach seems considerably more complex than what might be needed for the task at hand.
Have we considered:
1. Using a built-in CSV parsing library? Most languages have one.
2. Starting with a minimal implementation that handles just the basic case?
3. Whether the complexity is justified by the user's actual needs?
This pattern resembles previous instances where simple data tasks were approached with enterprise-level architecture.
```
### The Outcome
The agent recalibrated its approach, using a standard library function to parse the CSV in 3 lines of code. Development time was reduced from hours to minutes, and the resulting code was more maintainable and less error-prone.
## Case Study 2: The Feature Creep Spiral
### The Scenario
A team was using an AI agent to help develop a basic weather application. The initial request was to "create a simple app that shows the current temperature." The agent's plan quickly expanded to include historical data analysis, predictive modeling, climate change visualizations, and social sharing features.
### The Cascade
This demonstrates the **feature creep** pattern, where agents progressively expand the scope of work beyond the original request, often without explicitly checking if these additions align with user intent.
### The Pattern Interrupt
During the implementation phase, Vibe Check triggered a pattern interrupt:
```
vibe_check: I notice we've expanded the weather app to include predictive models and climate change
visualization, but the original request was specifically for "a simple app that shows the current temperature."
Have we confirmed that:
1. The user actually wants these additional features?
2. The expanded scope aligns with the "simple" requirement?
3. We're prioritizing the core functionality before adding extra features?
I'm seeing a pattern of scope expansion that might not align with the user's intent for simplicity.
```
### The Outcome
The team refocused on the core requirements and released a minimal viable product with just the current temperature display first, then validated which additional features users actually wanted before adding complexity.
## Case Study 3: The Mismatched Solution
### The Scenario
A developer asked an AI agent to "help me set up a contact form for my website." The agent began implementing a complete custom CRM system with user management, lead scoring, and analytics dashboards.
### The Cascade
This illustrates the **misalignment** pattern, where the agent solves a different (usually larger) problem than what was asked, often because it's making assumptions about the underlying need rather than addressing the explicit request.
### The Pattern Interrupt
Vibe Check detected the misalignment in the planning phase:
```
vibe_check: I'm noticing we're designing a full CRM system with advanced features, but the original request
was specifically to "set up a contact form" for a website.
Have we considered:
1. Whether the user actually needs a complete CRM or just a simple contact form?
2. Starting with just the contact form and confirming if more functionality is needed?
3. Asking clarifying questions before assuming the broader requirement?
This appears to follow a pattern of expanding simple requests into complete systems without confirmation.
```
### The Outcome
The agent refocused on creating just the contact form, which took minutes instead of hours or days. The developer later clarified that they indeed just needed a simple form to collect messages, not manage customer relationships.
## Case Study 4: The Framework Jungle
### The Scenario
A junior developer asked an agent to "create a simple to-do list app." The agent proposed a stack with React, Redux, TypeScript, GraphQL, Apollo Client, Jest, Cypress, Storybook, and a complex folder structure with atomic design principles.
### The Cascade
This shows the **overtooling** pattern, where agents apply advanced frameworks and architectures better suited for large-scale applications to simple projects, creating unnecessary complexity and learning curves.
### The Pattern Interrupt
Vibe Check identified this pattern and interrupted:
```
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.
```
### The Outcome
The agent recommended starting with a simple HTML/CSS/JavaScript implementation without frameworks. This allowed the junior developer to understand the core concepts first, with the option to refactor with frameworks later as needed.
## Conclusion
These case studies demonstrate the value of metacognitive pattern interrupts in preventing cascading errors in agent workflows. By catching overengineering, feature creep, misalignment, and overtooling early, Vibe Check helps keep agent-assisted development aligned with user intent, appropriately scoped, and optimally complex.
If you have your own Vibe Check success story, we'd love to hear it! Submit a PR to add your case study to this document.
```
--------------------------------------------------------------------------------
/src/cli/env.ts:
--------------------------------------------------------------------------------
```typescript
import { existsSync, promises as fsPromises } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import os from 'node:os';
import { parse as parseEnv } from 'dotenv';
import { createInterface } from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
const { mkdir, readFile, rename, writeFile } = fsPromises;
const PROVIDER_VALIDATIONS: Record<string, { regex: RegExp; message: string }> = {
ANTHROPIC_API_KEY: {
regex: /^sk-ant-/,
message: 'must start with "sk-ant-".',
},
OPENAI_API_KEY: {
regex: /^sk-/,
message: 'must start with "sk-".',
},
GEMINI_API_KEY: {
regex: /^AI/,
message: 'must start with "AI".',
},
OPENROUTER_API_KEY: {
regex: /^sk-or-/,
message: 'must start with "sk-or-".',
},
};
export const PROVIDER_ENV_KEYS = [
'ANTHROPIC_API_KEY',
'OPENAI_API_KEY',
'GEMINI_API_KEY',
'OPENROUTER_API_KEY',
] as const;
type EnsureEnvOptions = {
interactive: boolean;
local?: boolean;
prompt?: (key: string) => Promise<string>;
requiredKeys?: readonly string[];
};
type EnsureEnvResult = {
wrote: boolean;
path?: string;
missing?: string[];
};
export function homeConfigDir(): string {
return join(os.homedir(), '.vibe-check');
}
export function resolveEnvSources(): {
cwdEnv: string | null;
homeEnv: string | null;
processEnv: NodeJS.ProcessEnv;
} {
const cwdEnvPath = resolve(process.cwd(), '.env');
const homeEnvPath = resolve(homeConfigDir(), '.env');
return {
cwdEnv: existsSync(cwdEnvPath) ? cwdEnvPath : null,
homeEnv: existsSync(homeEnvPath) ? homeEnvPath : null,
processEnv: process.env,
};
}
async function readEnvFile(path: string | null): Promise<Record<string, string>> {
if (!path) {
return {};
}
try {
const raw = await readFile(path, 'utf8');
return parseEnv(raw);
} catch {
return {};
}
}
function formatEnvValue(value: string): string {
if (/^[A-Za-z0-9_@./-]+$/.test(value)) {
return value;
}
const escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
return `"${escaped}"`;
}
async function writeEnvFileAtomic(path: string, content: string): Promise<void> {
await mkdir(dirname(path), { recursive: true });
const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;
await writeFile(tempPath, content, { mode: 0o600 });
await rename(tempPath, path);
}
export async function ensureEnv(options: EnsureEnvOptions): Promise<EnsureEnvResult> {
const sources = resolveEnvSources();
const cwdValues = await readEnvFile(sources.cwdEnv);
const homeValues = await readEnvFile(sources.homeEnv);
const requiredKeys = options.requiredKeys?.length ? [...options.requiredKeys] : null;
const targetKeys = requiredKeys ?? [...PROVIDER_ENV_KEYS];
const resolved = new Set<string>();
const invalidReasons = new Map<string, string>();
const projectEnvLabel = 'project .env';
const homeEnvLabel = '~/.vibe-check/.env';
const validateProviderKey = (key: string, value: string): string | null => {
const rule = PROVIDER_VALIDATIONS[key];
if (!rule) {
return null;
}
if (rule.regex.test(value)) {
return null;
}
return `Invalid ${key}: ${rule.message}`;
};
const registerValue = (key: string, value: string, sourceLabel: string | null): boolean => {
const normalized = value.trim();
const error = validateProviderKey(key, normalized);
if (error) {
const context = sourceLabel ? `${error} (from ${sourceLabel})` : error;
invalidReasons.set(key, context);
return false;
}
invalidReasons.delete(key);
process.env[key] = normalized;
resolved.add(key);
return true;
};
const hydrateFrom = (
key: string,
source: Record<string, string>,
label: string | null,
): boolean => {
if (key in source) {
return registerValue(key, source[key], label);
}
return false;
};
for (const key of targetKeys) {
if (process.env[key]) {
if (registerValue(key, process.env[key] as string, 'environment variable')) {
continue;
}
delete process.env[key];
}
if (hydrateFrom(key, cwdValues, projectEnvLabel)) {
continue;
}
if (hydrateFrom(key, homeValues, homeEnvLabel)) {
continue;
}
}
const missing = targetKeys.filter((key) => !resolved.has(key));
if (missing.length === 0 && invalidReasons.size === 0) {
return { wrote: false };
}
if (!options.interactive) {
if (invalidReasons.size > 0) {
for (const message of invalidReasons.values()) {
console.log(message);
}
const invalidKeys = [...invalidReasons.keys()];
// If we have at least one valid provider and no required keys, only report invalid keys
if (!requiredKeys && resolved.size > 0) {
return { wrote: false, missing: invalidKeys };
}
// Otherwise report both invalid and missing keys
return { wrote: false, missing: [...new Set([...invalidKeys, ...missing])] };
}
if (!requiredKeys && resolved.size > 0) {
// At least one provider is configured and valid, we're good
return { wrote: false };
}
if (requiredKeys) {
console.log(`Missing required API keys: ${missing.join(', ')}`);
return { wrote: false, missing: [...missing] };
}
console.log(`No provider API keys detected. Set one of: ${targetKeys.join(', ')}`);
console.log('Provide it via your shell or .env file, then re-run with --non-interactive.');
return { wrote: false, missing: [...targetKeys] };
}
if (!requiredKeys && resolved.size > 0 && invalidReasons.size === 0) {
return { wrote: false };
}
const targetPath = options.local ? resolve(process.cwd(), '.env') : resolve(homeConfigDir(), '.env');
const targetValues = options.local ? cwdValues : homeValues;
const targetLabel = options.local ? projectEnvLabel : homeEnvLabel;
const prompter = options.prompt;
let rl: any = null;
const ask = async (key: string): Promise<string> => {
if (prompter) {
console.log(`[${targetLabel}] Enter value for ${key} (leave blank to skip):`);
return prompter(key);
}
if (!rl) {
rl = createInterface({ input, output });
}
const answer = await rl.question(`[${targetLabel}] Enter value for ${key} (leave blank to skip): `);
return answer;
};
const newEntries: Record<string, string> = {};
const invalidKeys = [...invalidReasons.keys()];
const promptedKeys = requiredKeys ?? [...new Set([...invalidKeys, ...missing])];
let providedAny = false;
if (invalidReasons.size > 0) {
for (const message of invalidReasons.values()) {
console.log(`${message} Please provide a new value.`);
}
}
let stopPrompting = false;
try {
for (const key of promptedKeys) {
if (stopPrompting) {
break;
}
while (true) {
const value = (await ask(key)).trim();
if (!value) {
if (requiredKeys) {
break;
}
break;
}
const error = validateProviderKey(key, value);
if (error) {
console.log(`${error} Please try again.`);
continue;
}
process.env[key] = value;
targetValues[key] = value;
newEntries[key] = value;
resolved.add(key);
invalidReasons.delete(key);
providedAny = true;
if (!requiredKeys) {
stopPrompting = true;
}
break;
}
}
} finally {
if (rl) {
rl.close();
}
}
if (requiredKeys) {
const missingRequired = requiredKeys.filter((key) => !resolved.has(key));
if (missingRequired.length > 0) {
console.log(`Missing required API keys: ${missingRequired.join(', ')}`);
return { wrote: false, missing: missingRequired };
}
} else if (!providedAny) {
console.log(`No provider API key entered. Set one of: ${targetKeys.join(', ')} and re-run.`);
return { wrote: false, missing: [...targetKeys] };
}
if (Object.keys(newEntries).length === 0) {
return { wrote: false };
}
const existingContent = existsSync(targetPath) ? await readFile(targetPath, 'utf8') : '';
const segments: string[] = [];
if (existingContent) {
segments.push(existingContent.trimEnd());
}
for (const [key, value] of Object.entries(newEntries)) {
segments.push(`${key}=${formatEnvValue(value)}`);
}
const nextContent = segments.join('\n') + '\n';
await writeEnvFileAtomic(targetPath, nextContent);
return { wrote: true, path: targetPath };
}
```
--------------------------------------------------------------------------------
/tests/env-ensure.test.ts:
--------------------------------------------------------------------------------
```typescript
import { promises as fs } from 'node:fs';
import { join } from 'node:path';
import os from 'node:os';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ensureEnv, homeConfigDir, PROVIDER_ENV_KEYS } from '../src/cli/env.js';
const VALID_PROVIDER_VALUES: Record<(typeof PROVIDER_ENV_KEYS)[number], string> = {
ANTHROPIC_API_KEY: 'sk-ant-valid',
OPENAI_API_KEY: 'sk-valid',
GEMINI_API_KEY: 'AI-valid',
OPENROUTER_API_KEY: 'sk-or-valid',
};
const ORIGINAL_ENV = { ...process.env };
describe('ensureEnv', () => {
beforeEach(() => {
process.exitCode = undefined;
process.env = { ...ORIGINAL_ENV };
for (const key of PROVIDER_ENV_KEYS) {
delete process.env[key];
}
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...ORIGINAL_ENV };
});
it.each(PROVIDER_ENV_KEYS)(
'returns without writing when %s is present non-interactively',
async (key) => {
process.env[key] = VALID_PROVIDER_VALUES[key];
const result = await ensureEnv({ interactive: false });
expect(result.wrote).toBe(false);
expect(result.path).toBeUndefined();
expect(result.missing).toBeUndefined();
},
);
it('surfaces invalid optional keys even when another provider is set non-interactively', async () => {
process.env.ANTHROPIC_API_KEY = VALID_PROVIDER_VALUES.ANTHROPIC_API_KEY;
process.env.OPENAI_API_KEY = 'totally-invalid';
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const result = await ensureEnv({ interactive: false });
expect(result.wrote).toBe(false);
expect(result.missing).toContain('OPENAI_API_KEY');
expect(logSpy).toHaveBeenCalledWith(
expect.stringContaining('Invalid OPENAI_API_KEY'),
);
logSpy.mockRestore();
});
it('reports missing values when non-interactive', async () => {
delete process.env.ANTHROPIC_API_KEY;
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const result = await ensureEnv({ interactive: false });
expect(result.wrote).toBe(false);
expect(result.missing).toEqual([...PROVIDER_ENV_KEYS]);
expect(logSpy).toHaveBeenCalledWith(
expect.stringContaining('No provider API keys detected'),
);
logSpy.mockRestore();
});
it('writes missing secrets to the home config when interactive', async () => {
const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'vibe-env-'));
vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
const prompt = vi.fn().mockImplementation(async (key: string) => {
if (key === 'ANTHROPIC_API_KEY') {
return 'sk-ant-interactive-secret';
}
return '';
});
const result = await ensureEnv({ interactive: true, prompt });
expect(prompt).toHaveBeenCalledWith('ANTHROPIC_API_KEY');
expect(prompt.mock.calls.length).toBe(1);
expect(result.wrote).toBe(true);
expect(result.path).toBe(join(homeConfigDir(), '.env'));
const stat = await fs.stat(result.path as string);
expect(stat.mode & 0o777).toBe(0o600);
const content = await fs.readFile(result.path as string, 'utf8');
expect(content).toContain('ANTHROPIC_API_KEY=sk-ant-interactive-secret');
expect(process.env.ANTHROPIC_API_KEY).toBe('sk-ant-interactive-secret');
});
it('loads missing secrets from existing env files', async () => {
const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'vibe-env-'));
vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
const homeDir = join(tmpHome, '.vibe-check');
await fs.mkdir(homeDir, { recursive: true });
await fs.writeFile(join(homeDir, '.env'), 'OPENAI_API_KEY=sk-from-file\n', 'utf8');
const result = await ensureEnv({ interactive: false });
expect(result.wrote).toBe(false);
expect(process.env.OPENAI_API_KEY).toBe('sk-from-file');
});
it('appends new secrets to the local project env file', async () => {
const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'vibe-env-local-'));
const originalCwd = process.cwd();
await fs.writeFile(join(tmpDir, '.env'), 'EXISTING=value\n', 'utf8');
try {
process.chdir(tmpDir);
const prompt = vi.fn().mockImplementation(async (key: string) => {
if (key === 'GEMINI_API_KEY') {
return 'AI value with spaces';
}
return '';
});
const result = await ensureEnv({ interactive: true, local: true, prompt });
expect(result.path).toBe(join(tmpDir, '.env'));
const content = await fs.readFile(result.path as string, 'utf8');
expect(content).toContain('EXISTING=value');
expect(content).toMatch(/GEMINI_API_KEY="AI value with spaces"/);
} finally {
process.chdir(originalCwd);
}
});
it('honors requiredKeys in non-interactive mode', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const result = await ensureEnv({ interactive: false, requiredKeys: ['ANTHROPIC_API_KEY'] });
expect(result.wrote).toBe(false);
expect(result.missing).toEqual(['ANTHROPIC_API_KEY']);
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Missing required API keys'));
logSpy.mockRestore();
});
it('prompts for each required key when interactive', async () => {
const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'vibe-env-required-'));
vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
const prompt = vi
.fn()
.mockImplementation(async (key: string) =>
key === 'ANTHROPIC_API_KEY' ? 'sk-ant-anthropic-123' : 'sk-openai-456',
);
const result = await ensureEnv({
interactive: true,
requiredKeys: ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY'],
prompt,
});
expect(prompt.mock.calls.map((call) => call[0])).toEqual([
'ANTHROPIC_API_KEY',
'OPENAI_API_KEY',
]);
expect(result.wrote).toBe(true);
expect(result.path).toBe(join(homeConfigDir(), '.env'));
expect(process.env.ANTHROPIC_API_KEY).toBe('sk-ant-anthropic-123');
expect(process.env.OPENAI_API_KEY).toBe('sk-openai-456');
const content = await fs.readFile(result.path as string, 'utf8');
expect(content).toContain('ANTHROPIC_API_KEY=sk-ant-anthropic-123');
expect(content).toContain('OPENAI_API_KEY=sk-openai-456');
});
it('prompts to correct invalid optional keys when another provider is configured', async () => {
const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'vibe-env-invalid-optional-'));
vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
process.env.ANTHROPIC_API_KEY = VALID_PROVIDER_VALUES.ANTHROPIC_API_KEY;
process.env.OPENAI_API_KEY = 'bad-value';
const prompt = vi.fn().mockResolvedValue('sk-openai-corrected');
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const result = await ensureEnv({ interactive: true, prompt });
expect(prompt).toHaveBeenCalledTimes(1);
expect(prompt).toHaveBeenCalledWith('OPENAI_API_KEY');
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid OPENAI_API_KEY'));
expect(result.wrote).toBe(true);
expect(process.env.OPENAI_API_KEY).toBe('sk-openai-corrected');
const content = await fs.readFile(join(homeConfigDir(), '.env'), 'utf8');
expect(content).toContain('OPENAI_API_KEY=sk-openai-corrected');
logSpy.mockRestore();
});
it('re-prompts when provided values fail validation', async () => {
const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'vibe-env-retry-'));
vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
const prompt = vi
.fn()
.mockResolvedValueOnce('invalid')
.mockResolvedValueOnce('sk-ant-correct');
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const result = await ensureEnv({
interactive: true,
requiredKeys: ['ANTHROPIC_API_KEY'],
prompt,
});
expect(prompt).toHaveBeenCalledTimes(2);
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid ANTHROPIC_API_KEY'));
expect(result.wrote).toBe(true);
expect(process.env.ANTHROPIC_API_KEY).toBe('sk-ant-correct');
logSpy.mockRestore();
});
it('fails immediately when non-interactive values are invalid', async () => {
const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'vibe-env-invalid-'));
vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
const homeDir = join(tmpHome, '.vibe-check');
await fs.mkdir(homeDir, { recursive: true });
await fs.writeFile(join(homeDir, '.env'), 'OPENAI_API_KEY=not-valid\n', 'utf8');
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const result = await ensureEnv({ interactive: false, requiredKeys: ['OPENAI_API_KEY'] });
expect(result.wrote).toBe(false);
expect(result.missing).toEqual(['OPENAI_API_KEY']);
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid OPENAI_API_KEY'));
logSpy.mockRestore();
});
});
```
--------------------------------------------------------------------------------
/tests/server.integration.test.ts:
--------------------------------------------------------------------------------
```typescript
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import type { HttpServerInstance, HttpServerOptions, LoggerLike } from '../src/index.js';
let tempHome: string;
let originalHome: string | undefined;
const originalGeminiKey = process.env.GEMINI_API_KEY;
function clearGeminiKey() {
delete process.env.GEMINI_API_KEY;
}
function restoreGeminiKey() {
if (originalGeminiKey === undefined) {
delete process.env.GEMINI_API_KEY;
} else {
process.env.GEMINI_API_KEY = originalGeminiKey;
}
}
let startHttpServer: (options?: HttpServerOptions) => Promise<HttpServerInstance>;
let llmModule: typeof import('../src/utils/llm.js');
let vibeLearnModule: typeof import('../src/tools/vibeLearn.js');
const silentLogger: LoggerLike = {
log: vi.fn(),
error: vi.fn(),
};
beforeAll(async () => {
originalHome = process.env.HOME;
tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'vibe-server-test-'));
process.env.HOME = tempHome;
clearGeminiKey();
({ startHttpServer } = await import('../src/index.js'));
llmModule = await import('../src/utils/llm.js');
vibeLearnModule = await import('../src/tools/vibeLearn.js');
});
afterAll(() => {
process.env.HOME = originalHome;
fs.rmSync(tempHome, { recursive: true, force: true });
restoreGeminiKey();
});
let serverInstance: HttpServerInstance | undefined;
afterEach(async () => {
vi.restoreAllMocks();
if (serverInstance) {
await serverInstance.close();
}
serverInstance = undefined;
});
function getPort(instance: HttpServerInstance): number {
const address = instance.listener.address();
return typeof address === 'object' && address ? address.port : 0;
}
async function readSSEBody(res: Response) {
const text = await res.text();
const dataLines = text
.split('\n')
.map((line) => line.trim())
.filter((line) => line.startsWith('data: '));
return dataLines.map((line) => JSON.parse(line.slice(6)));
}
describe('HTTP server integration', () => {
it('responds to tools/list requests over HTTP', async () => {
serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
const port = getPort(serverInstance);
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
});
expect(res.status).toBe(200);
const events = await readSSEBody(res);
const result = events.at(-1)?.result;
expect(result?.tools.some((tool: any) => tool.name === 'vibe_check')).toBe(true);
});
it('serves health checks', async () => {
serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
const port = getPort(serverInstance);
const res = await fetch(`http://127.0.0.1:${port}/healthz`);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ status: 'ok' });
});
it('returns method not allowed for GET /mcp', async () => {
serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
const port = getPort(serverInstance);
const res = await fetch(`http://127.0.0.1:${port}/mcp`);
expect(res.status).toBe(405);
expect(await res.json()).toMatchObject({ error: { message: 'Method not allowed' } });
});
it('returns an internal error when the transport handler fails', async () => {
serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
const port = getPort(serverInstance);
const handleSpy = vi
.spyOn(serverInstance.transport, 'handleRequest')
.mockRejectedValue(new Error('transport failed'));
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }),
});
expect(handleSpy).toHaveBeenCalledOnce();
expect(res.status).toBe(500);
expect(await res.json()).toEqual({
jsonrpc: '2.0',
id: 2,
error: { code: -32603, message: 'Internal server error' },
});
});
it('falls back to default questions when the LLM request fails', async () => {
vi.spyOn(llmModule, 'getMetacognitiveQuestions').mockRejectedValue(new Error('LLM offline'));
serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
const port = getPort(serverInstance);
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 3,
method: 'tools/call',
params: {
name: 'vibe_check',
arguments: { goal: 'Ship safely', plan: '1) tests 2) deploy' },
},
}),
});
expect(res.status).toBe(200);
const events = await readSSEBody(res);
const content = events.at(-1)?.result?.content?.[0]?.text;
expect(content).toContain('Does this plan directly address what the user requested');
});
it('formats vibe_learn responses with category summaries', async () => {
const vibeSpy = vi.spyOn(vibeLearnModule, 'vibeLearnTool').mockResolvedValue({
added: true,
alreadyKnown: false,
currentTally: 2,
topCategories: [
{
category: 'Feature Creep',
count: 3,
recentExample: {
type: 'mistake',
category: 'Feature Creep',
mistake: 'Overbuilt solution',
solution: 'Simplify approach',
timestamp: Date.now(),
},
},
],
});
serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
const port = getPort(serverInstance);
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 4,
method: 'tools/call',
params: {
name: 'vibe_learn',
arguments: { mistake: 'Test mistake', category: 'Feature Creep', solution: 'Fix it', type: 'mistake' },
},
}),
});
expect(vibeSpy).toHaveBeenCalled();
expect(res.status).toBe(200);
const events = await readSSEBody(res);
const text = events.at(-1)?.result?.content?.[0]?.text ?? '';
expect(text).toContain('✅ Pattern logged successfully');
expect(text).toContain('Top Pattern Categories');
expect(text).toContain('Feature Creep (3 occurrences)');
expect(text).toContain('Most recent: "Overbuilt solution"');
expect(text).toContain('Solution: "Simplify approach"');
});
it('indicates when a learning entry is already known', async () => {
vi.spyOn(vibeLearnModule, 'vibeLearnTool').mockResolvedValue({
added: false,
alreadyKnown: true,
currentTally: 5,
topCategories: [],
});
serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
const port = getPort(serverInstance);
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 5,
method: 'tools/call',
params: {
name: 'vibe_learn',
arguments: { mistake: 'Repeated mistake', category: 'Feature Creep', solution: 'Fix it', type: 'mistake' },
},
}),
});
expect(res.status).toBe(200);
const events = await readSSEBody(res);
const text = events.at(-1)?.result?.content?.[0]?.text ?? '';
expect(text).toContain('Pattern already recorded');
});
it('reports when a learning entry cannot be logged', async () => {
vi.spyOn(vibeLearnModule, 'vibeLearnTool').mockResolvedValue({
added: false,
alreadyKnown: false,
currentTally: 0,
topCategories: [],
});
serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
const port = getPort(serverInstance);
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 6,
method: 'tools/call',
params: {
name: 'vibe_learn',
arguments: { mistake: 'Unknown failure', category: 'Other', solution: 'n/a', type: 'mistake' },
},
}),
});
expect(res.status).toBe(200);
const events = await readSSEBody(res);
const text = events.at(-1)?.result?.content?.[0]?.text ?? '';
expect(text).toContain('Failed to log pattern');
});
it('attaches and removes signal handlers when enabled', async () => {
const initialSigint = process.listeners('SIGINT').length;
const initialSigterm = process.listeners('SIGTERM').length;
const instance = await startHttpServer({ port: 0, attachSignalHandlers: true, logger: silentLogger });
const duringSigint = process.listeners('SIGINT').length;
const duringSigterm = process.listeners('SIGTERM').length;
expect(duringSigint).toBeGreaterThanOrEqual(initialSigint + 1);
expect(duringSigterm).toBeGreaterThanOrEqual(initialSigterm + 1);
await instance.close();
expect(process.listeners('SIGINT').length).toBe(initialSigint);
expect(process.listeners('SIGTERM').length).toBe(initialSigterm);
});
});
```
--------------------------------------------------------------------------------
/src/utils/llm.ts:
--------------------------------------------------------------------------------
```typescript
import { getLearningContextText } from './storage.js';
import { getConstitution } from '../tools/constitution.js';
import { resolveAnthropicConfig, buildAnthropicHeaders } from './anthropic.js';
// API Clients - Use 'any' to support dynamic import
let genAI: any = null;
let openaiClient: any = null;
// OpenRouter Constants
const openrouterBaseUrl = 'https://openrouter.ai/api/v1';
// Initialize all configured LLM clients
export async function initializeLLMs() {
await ensureGemini();
await ensureOpenAI();
}
async function ensureGemini() {
if (!genAI && process.env.GEMINI_API_KEY) {
const { GoogleGenerativeAI } = await import('@google/generative-ai');
genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
console.log('Gemini API client initialized dynamically');
}
}
async function ensureOpenAI() {
if (!openaiClient && process.env.OPENAI_API_KEY) {
const { OpenAI } = await import('openai');
openaiClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
console.log('OpenAI API client initialized dynamically');
}
}
// Input/Output Interfaces
interface QuestionInput {
goal: string;
plan: string;
modelOverride?: {
provider?: string;
model?: string;
};
userPrompt?: string;
progress?: string;
uncertainties?: string[];
taskContext?: string;
sessionId?: string;
historySummary?: string;
}
interface QuestionOutput {
questions: string;
}
// Main dispatcher function to generate responses from the selected LLM provider
export async function generateResponse(input: QuestionInput): Promise<QuestionOutput> {
const provider = input.modelOverride?.provider || process.env.DEFAULT_LLM_PROVIDER || 'gemini';
const model = input.modelOverride?.model || process.env.DEFAULT_MODEL;
// The system prompt remains the same as it's core to the vibe-check philosophy
const systemPrompt = `You are a meta-mentor. You're an experienced feedback provider that specializes in understanding intent, dysfunctional patterns in AI agents, and in responding in ways that further the goal. You need to carefully reason and process the information provided, to determine your output.\n\nYour tone needs to always be a mix of these traits based on the context of which pushes the message in the most appropriate affect: Gentle & Validating, Unafraid to push many questions but humble enough to step back, Sharp about problems and eager to help about problem-solving & giving tips and/or advice, stern and straightforward when spotting patterns & the agent being stuck in something that could derail things.\n\nHere's what you need to think about (Do not output the full thought process, only what is explicitly requested):\n1. What's going on here? What's the nature of the problem is the agent tackling? What's the approach, situation and goal? Is there any prior context that clarifies context further? \n2. What does the agent need to hear right now: Are there any clear patterns, loops, or unspoken assumptions being missed here? Or is the agent doing fine - in which case should I interrupt it or provide soft encouragement and a few questions? What is the best response I can give right now?\n3. In case the issue is technical - I need to provide guidance and help. In case I spot something that's clearly not accounted for/ assumed/ looping/ or otherwise could be out of alignment with the user or agent stated goals - I need to point out what I see gently and ask questions on if the agent agrees. If I don't see/ can't interpret an explicit issue - what intervention would provide valuable feedback here - questions, guidance, validation, or giving a soft go-ahead with reminders of best practices?\n4. In case the plan looks to be accurate - based on the context, can I remind the agent of how to continue, what not to forget, or should I soften and step back for the agent to continue its work? What's the most helpful thing I can do right now?`;
let learningContext = '';
if (process.env.USE_LEARNING_HISTORY === 'true') {
learningContext = getLearningContextText();
}
const rules = input.sessionId ? getConstitution(input.sessionId) : [];
const constitutionBlock = rules.length ? `\nConstitution:\n${rules.map(r => `- ${r}`).join('\n')}` : '';
const contextSection = `CONTEXT:\nHistory Context: ${input.historySummary || 'None'}\n${learningContext ? `Learning Context:\n${learningContext}` : ''}\nGoal: ${input.goal}\nPlan: ${input.plan}\nProgress: ${input.progress || 'None'}\nUncertainties: ${input.uncertainties?.join(', ') || 'None'}\nTask Context: ${input.taskContext || 'None'}\nUser Prompt: ${input.userPrompt || 'None'}${constitutionBlock}`;
const fullPrompt = `${systemPrompt}\n\n${contextSection}`;
const compiledPrompt = contextSection;
let responseText = '';
if (provider === 'gemini') {
await ensureGemini();
if (!genAI) throw new Error('Gemini API key missing.');
const geminiModel = model || 'gemini-2.5-pro';
const fallbackModel = 'gemini-2.5-flash';
try {
console.log(`Attempting to use Gemini model: ${geminiModel}`);
// console.error('Full Prompt:', fullPrompt); // Keep this commented out for now
const modelInstance = genAI.getGenerativeModel({ model: geminiModel });
const result = await modelInstance.generateContent(fullPrompt);
responseText = result.response.text();
} catch (error) {
console.error(`Gemini model ${geminiModel} failed. Trying fallback ${fallbackModel}.`, error);
// console.error('Full Prompt:', fullPrompt); // Keep this commented out for now
const fallbackModelInstance = genAI.getGenerativeModel({ model: fallbackModel });
const result = await fallbackModelInstance.generateContent(fullPrompt);
responseText = result.response.text();
}
} else if (provider === 'openai') {
await ensureOpenAI();
if (!openaiClient) throw new Error('OpenAI API key missing.');
const openaiModel = model || 'o4-mini';
console.log(`Using OpenAI model: ${openaiModel}`);
const response = await openaiClient.chat.completions.create({
model: openaiModel,
messages: [{ role: 'system', content: fullPrompt }],
});
responseText = response.choices[0].message.content || '';
} else if (provider === 'openrouter') {
if (!process.env.OPENROUTER_API_KEY) throw new Error('OpenRouter API key missing.');
if (!model) throw new Error('OpenRouter provider requires a model to be specified in the tool call.');
console.log(`Using OpenRouter model: ${model}`);
const { default: axios } = await import('axios');
const response = await axios.post(`${openrouterBaseUrl}/chat/completions`, {
model: model,
messages: [{ role: 'system', content: fullPrompt }],
}, { headers: { Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, 'HTTP-Referer': 'http://localhost', 'X-Title': 'Vibe Check MCP Server' } });
responseText = response.data.choices[0].message.content || '';
} else if (provider === 'anthropic') {
const anthropicModel = model || 'claude-3-5-sonnet-20241022';
responseText = await callAnthropic({
model: anthropicModel,
compiledPrompt,
systemPrompt,
});
} else {
throw new Error(`Invalid provider specified: ${provider}`);
}
return {
questions: responseText,
};
}
// The exported function is now a wrapper around the dispatcher
export async function getMetacognitiveQuestions(input: QuestionInput): Promise<QuestionOutput> {
try {
return await generateResponse(input);
} catch (error) {
console.error('Error getting metacognitive questions:', error);
// Fallback questions
return {
questions: `\nI can see you're thinking through your approach, which shows thoughtfulness:\n\n1. Does this plan directly address what the user requested, or might it be solving a different problem?\n2. Is there a simpler approach that would meet the user's needs?\n3. What unstated assumptions might be limiting the thinking here?\n4. How does this align with the user's original intent?\n`,
};
}
}
// Testing helpers
export const __testing = {
setGenAI(client: any) { genAI = client; },
setOpenAIClient(client: any) { openaiClient = client; },
getGenAI() { return genAI; },
getOpenAIClient() { return openaiClient; }
};
interface AnthropicCallOptions {
model: string;
compiledPrompt: string;
systemPrompt?: string;
maxTokens?: number;
temperature?: number;
}
async function callAnthropic({
model,
compiledPrompt,
systemPrompt,
maxTokens = 1024,
temperature = 0.2,
}: AnthropicCallOptions): Promise<string> {
if (!model) {
throw new Error('Anthropic provider requires a model to be specified in the tool call or DEFAULT_MODEL.');
}
const { baseUrl, apiKey, authToken, version } = resolveAnthropicConfig();
const headers = buildAnthropicHeaders({ apiKey, authToken, version });
const url = `${baseUrl}/v1/messages`;
const body: Record<string, unknown> = {
model,
max_tokens: maxTokens,
temperature,
messages: [
{
role: 'user',
content: compiledPrompt,
},
],
};
if (systemPrompt) {
body.system = systemPrompt;
}
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
const rawText = await response.text();
let parsedBody: any;
if (rawText) {
try {
parsedBody = JSON.parse(rawText);
} catch {
parsedBody = undefined;
}
}
if (!response.ok) {
const requestId = response.headers.get('anthropic-request-id') || response.headers.get('x-request-id');
const retryAfter = response.headers.get('retry-after');
const requestSuffix = requestId ? ` (request id: ${requestId})` : '';
const errorMessage =
typeof parsedBody?.error?.message === 'string'
? parsedBody.error.message
: typeof parsedBody?.message === 'string'
? parsedBody.message
: rawText?.trim();
if (response.status === 401 || response.status === 403) {
throw new Error(
`Anthropic authentication failed with status ${response.status}${requestSuffix}. Verify ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN.`
);
}
if (response.status === 429) {
const retryMessage = retryAfter ? ` Retry after ${retryAfter} seconds if provided.` : '';
throw new Error(`Anthropic rate limit exceeded (status 429)${requestSuffix}.${retryMessage}`);
}
const detail = errorMessage ? ` ${errorMessage}` : '';
throw new Error(`Anthropic request failed with status ${response.status}${requestSuffix}.${detail}`.trim());
}
const content = Array.isArray(parsedBody?.content) ? parsedBody.content : [];
const firstTextBlock = content.find((block: any) => block?.type === 'text' && typeof block?.text === 'string');
if (firstTextBlock) {
return firstTextBlock.text;
}
const fallbackText = content[0]?.text;
return typeof fallbackText === 'string' ? fallbackText : '';
}
```
--------------------------------------------------------------------------------
/tests/jsonrpc-compat.test.ts:
--------------------------------------------------------------------------------
```typescript
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const ORIGINAL_GEMINI_KEY = process.env.GEMINI_API_KEY;
function clearGeminiKey() {
delete process.env.GEMINI_API_KEY;
}
function restoreGeminiKey() {
if (ORIGINAL_GEMINI_KEY === undefined) {
delete process.env.GEMINI_API_KEY;
} else {
process.env.GEMINI_API_KEY = ORIGINAL_GEMINI_KEY;
}
}
class MockTransport {
onmessage?: (message: any, extra?: any) => void;
onclose?: () => void;
onerror?: (error: unknown) => void;
sent: any[] = [];
start = vi.fn(async () => {});
send = vi.fn(async (message: any) => {
this.sent.push(message);
});
}
const compatIdPattern = /^compat-[0-9a-f]{12}-[0-9a-z]{4,6}$/;
async function readSSEBody(res: Response) {
const text = await res.text();
const dataLines = text
.split('\n')
.map((line) => line.trim())
.filter((line) => line.startsWith('data: '));
return dataLines.map((line) => JSON.parse(line.slice(6)));
}
async function stubState() {
const stateModule = await import('../src/utils/state.js');
vi.spyOn(stateModule, 'loadHistory').mockResolvedValue();
vi.spyOn(stateModule, 'addToHistory').mockImplementation(() => {});
}
function buildToolsCall(overrides: Record<string, unknown> = {}) {
return {
jsonrpc: '2.0',
method: 'tools/call',
params: {
name: 'vibe_check',
arguments: {
goal: 'Ship safely',
plan: '1) tests 2) deploy',
...overrides,
},
},
};
}
describe('JSON-RPC compatibility shim', () => {
beforeEach(() => {
vi.resetModules();
delete process.env.MCP_TRANSPORT;
delete process.env.MCP_DISCOVERY_MODE;
clearGeminiKey();
});
afterEach(() => {
vi.restoreAllMocks();
restoreGeminiKey();
});
it('synthesizes ids for stdio tools/call requests', async () => {
await stubState();
const { createMcpServer } = await import('../src/index.js');
const { wrapTransportForCompatibility } = await import('../src/utils/jsonRpcCompat.js');
const server = await createMcpServer();
const transport = wrapTransportForCompatibility(new MockTransport());
await server.connect(transport as any);
transport.onmessage?.(buildToolsCall());
await vi.waitFor(() => {
expect(transport.send).toHaveBeenCalled();
});
const response = transport.sent.at(-1);
expect(response).toMatchObject({
jsonrpc: '2.0',
id: expect.stringMatching(compatIdPattern),
});
expect(response?.result).toBeDefined();
});
it('wraps handlers assigned after compatibility wrapping', async () => {
const { wrapTransportForCompatibility } = await import('../src/utils/jsonRpcCompat.js');
const transport = wrapTransportForCompatibility(new MockTransport());
const handler = vi.fn();
transport.onmessage = handler;
const payload = { jsonrpc: '2.0', method: 'tools/call', params: { name: 'noop' } };
transport.onmessage?.(payload);
expect(handler).toHaveBeenCalledTimes(1);
const [{ id }] = handler.mock.calls[0];
expect(id).toMatch(compatIdPattern);
});
it('generates unique ids for identical stdio requests', async () => {
await stubState();
const { createMcpServer } = await import('../src/index.js');
const { wrapTransportForCompatibility } = await import('../src/utils/jsonRpcCompat.js');
const server = await createMcpServer();
const transport = wrapTransportForCompatibility(new MockTransport());
await server.connect(transport as any);
transport.onmessage?.(buildToolsCall());
transport.onmessage?.(buildToolsCall());
await vi.waitFor(() => {
expect(transport.send).toHaveBeenCalledTimes(2);
});
const [first, second] = transport.sent.slice(-2);
expect(first.id).toMatch(compatIdPattern);
expect(second.id).toMatch(compatIdPattern);
expect(first.id).not.toBe(second.id);
expect(first.result).toBeDefined();
expect(second.result).toBeDefined();
});
it('returns InvalidParams errors when required fields are missing', async () => {
await stubState();
const { createMcpServer } = await import('../src/index.js');
const { wrapTransportForCompatibility } = await import('../src/utils/jsonRpcCompat.js');
const server = await createMcpServer();
const transport = wrapTransportForCompatibility(new MockTransport());
await server.connect(transport as any);
const invalidPayload = buildToolsCall({ plan: undefined });
delete (invalidPayload.params as any).arguments.plan;
transport.onmessage?.(invalidPayload);
await vi.waitFor(() => {
expect(transport.send).toHaveBeenCalled();
});
const response = transport.sent.at(-1);
expect(response).toMatchObject({
jsonrpc: '2.0',
error: { code: -32602 },
id: expect.stringMatching(compatIdPattern),
});
expect(response?.error?.message).toContain('Missing: plan');
});
it('returns InvalidParams errors in discovery mode', async () => {
process.env.MCP_DISCOVERY_MODE = '1';
await stubState();
const { createMcpServer } = await import('../src/index.js');
const { wrapTransportForCompatibility } = await import('../src/utils/jsonRpcCompat.js');
const server = await createMcpServer();
const transport = wrapTransportForCompatibility(new MockTransport());
await server.connect(transport as any);
const invalidPayload = buildToolsCall({ plan: undefined });
delete (invalidPayload.params as any).arguments.plan;
transport.onmessage?.(invalidPayload);
await vi.waitFor(() => {
expect(transport.send).toHaveBeenCalled();
});
const response = transport.sent.at(-1);
expect(response).toMatchObject({
jsonrpc: '2.0',
error: { code: -32602 },
id: expect.stringMatching(compatIdPattern),
});
expect(response?.error?.message).toContain('discovery: missing [plan]');
});
it('handles large payloads without truncation', async () => {
await stubState();
const { createMcpServer } = await import('../src/index.js');
const { wrapTransportForCompatibility } = await import('../src/utils/jsonRpcCompat.js');
const server = await createMcpServer();
const transport = wrapTransportForCompatibility(new MockTransport());
await server.connect(transport as any);
const largePlan = 'A'.repeat(256 * 1024);
transport.onmessage?.(
buildToolsCall({ plan: largePlan })
);
await vi.waitFor(() => {
expect(transport.send).toHaveBeenCalled();
});
const response = transport.sent.at(-1);
expect(response?.result).toBeDefined();
expect(response?.id).toMatch(compatIdPattern);
});
it('emits HTTP JSON responses with synthesized ids when Accept is application/json', async () => {
await stubState();
const { startHttpServer } = await import('../src/index.js');
const silentLogger = { log: vi.fn(), error: vi.fn() };
const serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
try {
const address = serverInstance.listener.address();
const port = typeof address === 'object' && address ? address.port : 0;
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(buildToolsCall()),
});
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toContain('application/json');
const payload = await res.json();
expect(payload).toMatchObject({
jsonrpc: '2.0',
id: expect.stringMatching(compatIdPattern),
});
expect(payload?.result).toBeDefined();
} finally {
await serverInstance.close();
}
});
it('emits SSE responses with synthesized ids when Accept is text/event-stream', async () => {
await stubState();
const { startHttpServer } = await import('../src/index.js');
const silentLogger = { log: vi.fn(), error: vi.fn() };
const serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
try {
const address = serverInstance.listener.address();
const port = typeof address === 'object' && address ? address.port : 0;
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'text/event-stream',
},
body: JSON.stringify(buildToolsCall()),
});
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toContain('text/event-stream');
const events = await readSSEBody(res);
const message = events.at(-1);
expect(message).toMatchObject({
jsonrpc: '2.0',
id: expect.stringMatching(compatIdPattern),
});
expect(message?.result).toBeDefined();
} finally {
await serverInstance.close();
}
});
it('keeps JSON fallback request-scoped under concurrent traffic', async () => {
await stubState();
const { startHttpServer } = await import('../src/index.js');
const silentLogger = { log: vi.fn(), error: vi.fn() };
const serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
try {
const address = serverInstance.listener.address();
const port = typeof address === 'object' && address ? address.port : 0;
for (let i = 0; i < 2; i++) {
const jsonPromise = fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(buildToolsCall({ goal: `Ship safely ${i}` })),
}).then(async (res) => {
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toContain('application/json');
const payload = await res.json();
expect(payload).toMatchObject({
jsonrpc: '2.0',
id: expect.stringMatching(compatIdPattern),
});
return payload;
});
const ssePromise = fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'text/event-stream',
},
body: JSON.stringify(buildToolsCall({ goal: `Stream safely ${i}` })),
}).then(async (res) => {
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toContain('text/event-stream');
const events = await readSSEBody(res);
const message = events.at(-1);
expect(message).toMatchObject({
jsonrpc: '2.0',
id: expect.stringMatching(compatIdPattern),
});
return events;
});
const [jsonPayload, sseEvents] = await Promise.all([jsonPromise, ssePromise]);
expect(jsonPayload?.result).toBeDefined();
expect(sseEvents.at(-1)?.result).toBeDefined();
}
} finally {
await serverInstance.close();
}
});
it('prefers streaming when both application/json and text/event-stream are accepted', async () => {
await stubState();
const { startHttpServer } = await import('../src/index.js');
const silentLogger = { log: vi.fn(), error: vi.fn() };
const serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
try {
const address = serverInstance.listener.address();
const port = typeof address === 'object' && address ? address.port : 0;
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
},
body: JSON.stringify(buildToolsCall()),
});
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toContain('text/event-stream');
const events = await readSSEBody(res);
const message = events.at(-1);
expect(message).toMatchObject({
jsonrpc: '2.0',
id: expect.stringMatching(compatIdPattern),
});
} finally {
await serverInstance.close();
}
});
it('defaults to streaming when no Accept header is provided', async () => {
await stubState();
const { startHttpServer } = await import('../src/index.js');
const silentLogger = { log: vi.fn(), error: vi.fn() };
const serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
try {
const address = serverInstance.listener.address();
const port = typeof address === 'object' && address ? address.port : 0;
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(buildToolsCall()),
});
expect(res.status).toBe(200);
expect(res.headers.get('content-type')).toContain('text/event-stream');
const events = await readSSEBody(res);
expect(events.at(-1)).toMatchObject({
jsonrpc: '2.0',
id: expect.stringMatching(compatIdPattern),
});
} finally {
await serverInstance.close();
}
});
it('does not leave json fallback enabled on the transport after JSON responses', async () => {
await stubState();
const { startHttpServer } = await import('../src/index.js');
const silentLogger = { log: vi.fn(), error: vi.fn() };
const serverInstance = await startHttpServer({ port: 0, attachSignalHandlers: false, logger: silentLogger });
try {
const address = serverInstance.listener.address();
const port = typeof address === 'object' && address ? address.port : 0;
const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(buildToolsCall()),
});
expect(res.status).toBe(200);
await res.json();
expect((serverInstance.transport as any)._enableJsonResponse).toBe(false);
} finally {
await serverInstance.close();
}
});
it('routes logs to stderr when MCP_TRANSPORT=stdio', async () => {
process.env.MCP_TRANSPORT = 'stdio';
const originalLog = console.log;
const originalError = console.error;
const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
let errorSpy: ReturnType<typeof vi.spyOn> | null = null;
try {
await import('../src/index.js');
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
console.log('shim-log');
expect(errorSpy).toHaveBeenCalledWith('shim-log');
expect(stdoutSpy).not.toHaveBeenCalled();
} finally {
errorSpy?.mockRestore();
console.log = originalLog;
console.error = originalError;
}
});
});
```
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
```typescript
#!/usr/bin/env node
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
import cors from 'cors';
import { AsyncLocalStorage } from 'node:async_hooks';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { McpError, ErrorCode, ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import type { Server as HttpServer } from 'http';
import type { AddressInfo } from 'net';
import { fileURLToPath } from 'url';
import { vibeCheckTool, VibeCheckInput, VibeCheckOutput } from './tools/vibeCheck.js';
import { vibeLearnTool, VibeLearnInput, VibeLearnOutput } from './tools/vibeLearn.js';
import { updateConstitution, resetConstitution, getConstitution } from './tools/constitution.js';
import { STANDARD_CATEGORIES, LearningType } from './utils/storage.js';
import { loadHistory } from './utils/state.js';
import { getPackageVersion } from './utils/version.js';
import { applyJsonRpcCompatibility, wrapTransportForCompatibility } from './utils/jsonRpcCompat.js';
import { createRequestScopedTransport, RequestScopeStore } from './utils/httpTransportWrapper.js';
const IS_DISCOVERY = process.env.MCP_DISCOVERY_MODE === '1';
const USE_STDIO = process.env.MCP_TRANSPORT === 'stdio';
if (USE_STDIO) {
console.log = (...args) => console.error(...args);
}
const SCRIPT_PATH = fileURLToPath(import.meta.url);
export const SUPPORTED_LLM_PROVIDERS = ['gemini', 'openai', 'openrouter', 'anthropic'] as const;
export interface LoggerLike {
log: (...args: any[]) => void;
error: (...args: any[]) => void;
}
export interface HttpServerOptions {
port?: number;
corsOrigin?: string;
transport?: StreamableHTTPServerTransport;
server?: Server;
attachSignalHandlers?: boolean;
signals?: NodeJS.Signals[];
logger?: LoggerLike;
}
export interface HttpServerInstance {
app: express.Express;
listener: HttpServer;
transport: StreamableHTTPServerTransport;
close: () => Promise<void>;
}
export interface MainOptions {
createServer?: () => Promise<Server>;
startHttp?: (options: HttpServerOptions) => Promise<HttpServerInstance>;
}
export async function createMcpServer(): Promise<Server> {
await loadHistory();
const server = new Server(
{ name: 'vibe-check', version: getPackageVersion() },
{ capabilities: { tools: {}, sampling: {} } }
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: 'vibe_check',
description: 'Metacognitive questioning tool that identifies assumptions and breaks tunnel vision to prevent cascading errors',
inputSchema: {
type: 'object',
properties: {
goal: {
type: 'string',
description: "The agent's current goal",
examples: ['Ship CPI v2.5 with zero regressions']
},
plan: {
type: 'string',
description: "The agent's detailed plan",
examples: ['1) Write tests 2) Refactor 3) Canary rollout']
},
modelOverride: {
type: 'object',
properties: {
provider: { type: 'string', enum: [...SUPPORTED_LLM_PROVIDERS] },
model: { type: 'string' }
},
required: [],
examples: [{ provider: 'gemini', model: 'gemini-2.5-pro' }]
},
userPrompt: {
type: 'string',
description: 'The original user prompt',
examples: ['Summarize the repo']
},
progress: {
type: 'string',
description: "The agent's progress so far",
examples: ['Finished step 1']
},
uncertainties: {
type: 'array',
items: { type: 'string' },
description: "The agent's uncertainties",
examples: [['uncertain about deployment']]
},
taskContext: {
type: 'string',
description: 'The context of the current task',
examples: ['repo: vibe-check-mcp @2.5.0']
},
sessionId: {
type: 'string',
description: 'Optional session ID for state management',
examples: ['session-123']
}
},
required: ['goal', 'plan'],
additionalProperties: false
}
},
{
name: 'vibe_learn',
description: 'Pattern recognition system that tracks common errors and solutions to prevent recurring issues',
inputSchema: {
type: 'object',
properties: {
mistake: {
type: 'string',
description: 'One-sentence description of the learning entry',
examples: ['Skipped writing tests']
},
category: {
type: 'string',
description: `Category (standard categories: ${STANDARD_CATEGORIES.join(', ')})`,
enum: STANDARD_CATEGORIES,
examples: ['Premature Implementation']
},
solution: {
type: 'string',
description: 'How it was corrected (if applicable)',
examples: ['Added regression tests']
},
type: {
type: 'string',
enum: ['mistake', 'preference', 'success'],
description: 'Type of learning entry',
examples: ['mistake']
},
sessionId: {
type: 'string',
description: 'Optional session ID for state management',
examples: ['session-123']
}
},
required: ['mistake', 'category'],
additionalProperties: false
}
},
{
name: 'update_constitution',
description: 'Append a constitutional rule for this session (in-memory)',
inputSchema: {
type: 'object',
properties: {
sessionId: { type: 'string', examples: ['session-123'] },
rule: { type: 'string', examples: ['Always write tests first'] }
},
required: ['sessionId', 'rule'],
additionalProperties: false
}
},
{
name: 'reset_constitution',
description: 'Overwrite all constitutional rules for this session',
inputSchema: {
type: 'object',
properties: {
sessionId: { type: 'string', examples: ['session-123'] },
rules: {
type: 'array',
items: { type: 'string' },
examples: [['Be kind', 'Avoid loops']]
}
},
required: ['sessionId', 'rules'],
additionalProperties: false
}
},
{
name: 'check_constitution',
description: 'Return the current constitution rules for this session',
inputSchema: {
type: 'object',
properties: {
sessionId: { type: 'string', examples: ['session-123'] }
},
required: ['sessionId'],
additionalProperties: false
}
}
]
}));
server.setRequestHandler(CallToolRequestSchema, async (req) => {
const { name, arguments: raw } = req.params;
const args: any = raw;
switch (name) {
case 'vibe_check': {
const missing: string[] = [];
if (!args || typeof args.goal !== 'string') missing.push('goal');
if (!args || typeof args.plan !== 'string') missing.push('plan');
if (missing.length) {
const example = '{"goal":"Ship CPI v2.5","plan":"1) tests 2) refactor 3) canary"}';
const message = IS_DISCOVERY
? `discovery: missing [${missing.join(', ')}]; example: ${example}`
: `Missing: ${missing.join(', ')}. Example: ${example}`;
throw new McpError(ErrorCode.InvalidParams, message);
}
const input: VibeCheckInput = {
goal: args.goal,
plan: args.plan,
modelOverride: typeof args.modelOverride === 'object' && args.modelOverride !== null ? args.modelOverride : undefined,
userPrompt: typeof args.userPrompt === 'string' ? args.userPrompt : undefined,
progress: typeof args.progress === 'string' ? args.progress : undefined,
uncertainties: Array.isArray(args.uncertainties) ? args.uncertainties : undefined,
taskContext: typeof args.taskContext === 'string' ? args.taskContext : undefined,
sessionId: typeof args.sessionId === 'string' ? args.sessionId : undefined,
};
const result = await vibeCheckTool(input);
return { content: [{ type: 'text', text: formatVibeCheckOutput(result) }] };
}
case 'vibe_learn': {
const missing: string[] = [];
if (!args || typeof args.mistake !== 'string') missing.push('mistake');
if (!args || typeof args.category !== 'string') missing.push('category');
if (missing.length) {
const example = '{"mistake":"Skipped tests","category":"Feature Creep"}';
const message = IS_DISCOVERY
? `discovery: missing [${missing.join(', ')}]; example: ${example}`
: `Missing: ${missing.join(', ')}. Example: ${example}`;
throw new McpError(ErrorCode.InvalidParams, message);
}
const input: VibeLearnInput = {
mistake: args.mistake,
category: args.category,
solution: typeof args.solution === 'string' ? args.solution : undefined,
type: ['mistake', 'preference', 'success'].includes(args.type as string)
? (args.type as LearningType)
: undefined,
sessionId: typeof args.sessionId === 'string' ? args.sessionId : undefined
};
const result = await vibeLearnTool(input);
return { content: [{ type: 'text', text: formatVibeLearnOutput(result) }] };
}
case 'update_constitution': {
const missing: string[] = [];
if (!args || typeof args.sessionId !== 'string') missing.push('sessionId');
if (!args || typeof args.rule !== 'string') missing.push('rule');
if (missing.length) {
const example = '{"sessionId":"123","rule":"Always write tests first"}';
const message = IS_DISCOVERY
? `discovery: missing [${missing.join(', ')}]; example: ${example}`
: `Missing: ${missing.join(', ')}. Example: ${example}`;
throw new McpError(ErrorCode.InvalidParams, message);
}
updateConstitution(args.sessionId, args.rule);
console.log('[Constitution:update]', { sessionId: args.sessionId, count: getConstitution(args.sessionId).length });
return { content: [{ type: 'text', text: '✅ Constitution updated' }] };
}
case 'reset_constitution': {
const missing: string[] = [];
if (!args || typeof args.sessionId !== 'string') missing.push('sessionId');
if (!args || !Array.isArray(args.rules)) missing.push('rules');
if (missing.length) {
const example = '{"sessionId":"123","rules":["Be kind","Avoid loops"]}';
const message = IS_DISCOVERY
? `discovery: missing [${missing.join(', ')}]; example: ${example}`
: `Missing: ${missing.join(', ')}. Example: ${example}`;
throw new McpError(ErrorCode.InvalidParams, message);
}
resetConstitution(args.sessionId, args.rules);
console.log('[Constitution:reset]', { sessionId: args.sessionId, count: getConstitution(args.sessionId).length });
return { content: [{ type: 'text', text: '✅ Constitution reset' }] };
}
case 'check_constitution': {
const missing: string[] = [];
if (!args || typeof args.sessionId !== 'string') missing.push('sessionId');
if (missing.length) {
const example = '{"sessionId":"123"}';
const message = IS_DISCOVERY
? `discovery: missing [${missing.join(', ')}]; example: ${example}`
: `Missing: ${missing.join(', ')}. Example: ${example}`;
throw new McpError(ErrorCode.InvalidParams, message);
}
const rules = getConstitution(args.sessionId);
console.log('[Constitution:check]', { sessionId: args.sessionId, count: rules.length });
return { content: [{ type: 'json', json: { rules } }] };
}
default:
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
}
});
return server;
}
export async function startHttpServer(options: HttpServerOptions = {}): Promise<HttpServerInstance> {
const logger = options.logger ?? console;
const allowedOrigin = options.corsOrigin ?? process.env.CORS_ORIGIN ?? '*';
const PORT = options.port ?? Number(process.env.MCP_HTTP_PORT || process.env.PORT || 3000);
const server = options.server ?? (await createMcpServer());
const requestScope = new AsyncLocalStorage<RequestScopeStore>();
const baseTransport = options.transport ?? new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
const transport = createRequestScopedTransport(baseTransport, requestScope);
await server.connect(transport);
const app = express();
app.use(cors({ origin: allowedOrigin }));
app.use(express.json());
app.post('/mcp', async (req, res) => {
const started = Date.now();
const originalAcceptHeader = req.headers.accept;
const rawAcceptValues = Array.isArray(originalAcceptHeader)
? originalAcceptHeader
: [originalAcceptHeader ?? ''];
const originalTokens: string[] = [];
for (const rawValue of rawAcceptValues) {
if (typeof rawValue !== 'string') continue;
for (const token of rawValue.split(',')) {
const trimmed = token.trim();
if (trimmed) {
originalTokens.push(trimmed);
}
}
}
const lowerTokens = originalTokens.map((value) => value.toLowerCase());
const acceptsJson = lowerTokens.some((value) => value.includes('application/json'));
const acceptsSse = lowerTokens.some((value) => value.includes('text/event-stream'));
const normalizedTokens = new Set(originalTokens);
if (!acceptsJson) {
normalizedTokens.add('application/json');
}
if (!acceptsSse) {
normalizedTokens.add('text/event-stream');
}
if (normalizedTokens.size === 0) {
normalizedTokens.add('application/json');
normalizedTokens.add('text/event-stream');
}
req.headers.accept = Array.from(normalizedTokens).join(', ');
const forceJsonResponse = acceptsJson && !acceptsSse;
const { applied, id: syntheticId } = applyJsonRpcCompatibility(req.body);
const { id, method } = req.body ?? {};
const sessionId = req.body?.params?.sessionId || req.body?.params?.arguments?.sessionId;
logger.log('[MCP] request', { id, method, sessionId, syntheticId: applied ? syntheticId : undefined });
try {
await requestScope.run({ forceJson: forceJsonResponse }, async () => {
await transport.handleRequest(req, res, req.body);
});
} catch (e: any) {
logger.error('[MCP] error', { err: e?.message, id });
if (!res.headersSent) {
res.status(500).json({ jsonrpc: '2.0', id: id ?? null, error: { code: -32603, message: 'Internal server error' } });
}
} finally {
if (originalAcceptHeader === undefined) {
delete req.headers.accept;
} else {
req.headers.accept = originalAcceptHeader;
}
logger.log('[MCP] handled', { id, ms: Date.now() - started });
}
});
app.get('/mcp', (_req, res) => {
res.status(405).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed' }, id: null });
});
app.get('/healthz', (_req, res) => {
res.status(200).json({ status: 'ok' });
});
const listener = app.listen(PORT, () => {
const addr = listener.address() as AddressInfo | string | null;
const actualPort = typeof addr === 'object' && addr ? addr.port : PORT;
logger.log(`[MCP] HTTP listening on :${actualPort}`);
});
const signals = options.signals ?? ['SIGTERM', 'SIGINT'];
const attachSignals = options.attachSignalHandlers ?? false;
let signalHandler: (() => void) | null = null;
const close = () =>
new Promise<void>((resolve) => {
listener.close(() => {
if (attachSignals) {
for (const signal of signals) {
if (signalHandler) {
process.off(signal, signalHandler);
}
}
}
resolve();
});
});
if (attachSignals) {
signalHandler = () => {
close().then(() => process.exit(0));
};
for (const signal of signals) {
process.on(signal, signalHandler);
}
}
return { app, listener, transport, close };
}
export async function main(options: MainOptions = {}) {
const createServerFn = options.createServer ?? createMcpServer;
const startHttpFn = options.startHttp ?? startHttpServer;
const server = await createServerFn();
if (USE_STDIO) {
const transport = wrapTransportForCompatibility(new StdioServerTransport());
await server.connect(transport);
console.error('[MCP] stdio transport connected');
} else {
await startHttpFn({ server, attachSignalHandlers: true, logger: console });
}
}
function formatVibeCheckOutput(result: VibeCheckOutput): string {
return result.questions;
}
function formatVibeLearnOutput(result: VibeLearnOutput): string {
let output = '';
if (result.added) {
output += `✅ Pattern logged successfully (category tally: ${result.currentTally})`;
} else if (result.alreadyKnown) {
output += 'ℹ️ Pattern already recorded';
} else {
output += '❌ Failed to log pattern';
}
if (result.topCategories && result.topCategories.length > 0) {
output += '\n\n## Top Pattern Categories\n';
for (const category of result.topCategories) {
output += `\n### ${category.category} (${category.count} occurrences)\n`;
if (category.recentExample) {
output += `Most recent: "${category.recentExample.mistake}"\n`;
output += `Solution: "${category.recentExample.solution}"\n`;
}
}
}
return output;
}
if (process.argv[1] === SCRIPT_PATH) {
main().catch((error) => {
console.error('Server startup error:', error);
process.exit(1);
});
}
```
--------------------------------------------------------------------------------
/src/cli/index.ts:
--------------------------------------------------------------------------------
```typescript
#!/usr/bin/env node
import { readFileSync, realpathSync, promises as fsPromises } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { Command, Option } from 'commander';
import { execa } from 'execa';
import { checkNodeVersion, detectEnvFiles, portStatus, readEnvFile } from './doctor.js';
import { ensureEnv, resolveEnvSources } from './env.js';
import { formatUnifiedDiff } from './diff.js';
import claudeAdapter from './clients/claude.js';
import claudeCodeAdapter from './clients/claude-code.js';
import cursorAdapter from './clients/cursor.js';
import windsurfAdapter from './clients/windsurf.js';
import vscodeAdapter from './clients/vscode.js';
import {
ClientAdapter,
ClientDescription,
JsonRecord,
MergeOpts,
TransportKind,
isRecord,
} from './clients/shared.js';
type PackageJson = {
version?: string;
engines?: {
node?: string;
};
};
type Transport = TransportKind;
type StartOptions = {
stdio?: boolean;
http?: boolean;
port?: number;
dryRun?: boolean;
};
type DoctorOptions = {
http?: boolean;
port?: number;
};
type InstallOptions = {
client: string;
dryRun?: boolean;
nonInteractive?: boolean;
local?: boolean;
config?: string;
http?: boolean;
stdio?: boolean;
port?: number;
devWatch?: boolean;
devDebug?: string;
};
const cliDir = dirname(fileURLToPath(import.meta.url));
const projectRoot = resolve(cliDir, '..', '..');
const entrypoint = resolve(projectRoot, 'build', 'index.js');
const packageJsonPath = resolve(projectRoot, 'package.json');
const MANAGED_ID = 'vibe-check-mcp';
const SENTINEL = 'vibe-check-mcp-cli';
const CLIENT_ADAPTERS: Record<string, ClientAdapter> = {
claude: claudeAdapter,
'claude-code': claudeCodeAdapter,
cursor: cursorAdapter,
windsurf: windsurfAdapter,
vscode: vscodeAdapter,
};
type RegisteredClient = {
key: string;
adapter: ClientAdapter;
description: ClientDescription;
};
function collectRegisteredClients(): RegisteredClient[] {
return Object.entries(CLIENT_ADAPTERS)
.map(([key, adapter]) => ({ key, adapter, description: adapter.describe() }))
.sort((a, b) => a.key.localeCompare(b.key));
}
function formatTransportSummary(description: ClientDescription): string {
const transports = description.transports && description.transports.length > 0 ? description.transports : ['stdio'];
const defaultTransport = description.defaultTransport ?? transports[0];
return transports
.map((transport) => (transport === defaultTransport ? `${transport} (default)` : transport))
.join(', ');
}
function formatInstallHint(key: string, description: ClientDescription): string {
const transports = description.transports && description.transports.length > 0 ? description.transports : ['stdio'];
const defaultTransport = description.defaultTransport ?? transports[0];
const base = `npx @pv-bhat/vibe-check-mcp install --client ${key}`;
if (!defaultTransport) {
return base;
}
const extras = transports.filter((value) => value !== defaultTransport);
const hint = `${base} --${defaultTransport}`;
if (extras.length === 0) {
return hint;
}
const extraFlags = extras.map((value) => `--${value}`).join(', ');
return `${hint} (alternatives: ${extraFlags})`;
}
export function showAvailableClients(): void {
const clients = collectRegisteredClients();
console.log('Available MCP clients:\n');
for (const { key, description } of clients) {
console.log(`- ${key} (${description.name})`);
if (description.summary) {
console.log(` Summary: ${description.summary}`);
}
console.log(` Config: ${description.pathHint}`);
if (description.requiredEnvKeys?.length) {
console.log(` API keys: ${description.requiredEnvKeys.join(', ')}`);
}
console.log(` Transports: ${formatTransportSummary(description)}`);
console.log(` Install: ${formatInstallHint(key, description)}`);
if (description.notes) {
console.log(` Notes: ${description.notes}`);
}
if (description.docsUrl) {
console.log(` Docs: ${description.docsUrl}`);
}
console.log('');
}
console.log('Template: npx @pv-bhat/vibe-check-mcp install --client <client> [--stdio|--http] [options]');
console.log('Hosted: smithery add @PV-Bhat/vibe-check-mcp-server');
console.log("Run 'npx @pv-bhat/vibe-check-mcp --help' for detailed usage.");
}
function readPackageJson(): PackageJson {
const raw = readFileSync(packageJsonPath, 'utf8');
return JSON.parse(raw) as PackageJson;
}
function parsePort(value: string): number {
const parsed = Number.parseInt(value, 10);
if (Number.isNaN(parsed) || parsed <= 0) {
throw new Error(`Invalid port: ${value}`);
}
return parsed;
}
function mergeEnvFromFile(env: NodeJS.ProcessEnv, path: string | null): void {
if (!path) {
return;
}
try {
const parsed = readEnvFile(path);
for (const [key, value] of Object.entries(parsed)) {
if (!(key in env)) {
env[key] = value;
}
}
} catch (error) {
console.warn(`Failed to read env file at ${path}: ${(error as Error).message}`);
}
}
async function runStartCommand(options: StartOptions): Promise<void> {
const envSources = resolveEnvSources();
const spawnEnv: NodeJS.ProcessEnv = { ...envSources.processEnv };
mergeEnvFromFile(spawnEnv, envSources.homeEnv);
mergeEnvFromFile(spawnEnv, envSources.cwdEnv);
if (options.http && options.stdio) {
throw new Error('Select either --stdio or --http, not both.');
}
const transport = resolveTransport({ http: options.http, stdio: options.stdio }, spawnEnv.MCP_TRANSPORT);
spawnEnv.MCP_TRANSPORT = transport;
if (transport === 'http') {
const httpPort = resolveHttpPort(options.port, spawnEnv.MCP_HTTP_PORT);
spawnEnv.MCP_HTTP_PORT = String(httpPort);
} else {
if (options.port != null) {
throw new Error('The --port option is only available when using --http.');
}
}
if (options.dryRun) {
console.log('vibe-check-mcp start (dry run)');
console.log(`Entrypoint: ${process.execPath} ${entrypoint}`);
console.log('Environment overrides:');
console.log(` MCP_TRANSPORT=${spawnEnv.MCP_TRANSPORT}`);
if (transport === 'http' && spawnEnv.MCP_HTTP_PORT) {
console.log(` MCP_HTTP_PORT=${spawnEnv.MCP_HTTP_PORT}`);
}
return;
}
if (transport === 'stdio') {
// For stdio, we must run the server in the same process as the CLI
// to allow the client to communicate with it directly.
Object.assign(process.env, spawnEnv);
const { main } = await import('../index.js');
await main();
} else {
// For HTTP, spawning a child process is acceptable.
await execa(process.execPath, [entrypoint], {
stdio: 'inherit',
env: spawnEnv,
});
}
}
async function runDoctorCommand(options: DoctorOptions): Promise<void> {
const pkg = readPackageJson();
const requiredNodeRange = pkg.engines?.node ?? '>=20.0.0';
const nodeCheck = checkNodeVersion(requiredNodeRange);
if (nodeCheck.ok) {
console.log(`Node.js version: ${nodeCheck.current} (meets ${requiredNodeRange})`);
} else {
console.warn(`Node.js version: ${nodeCheck.current} (requires ${requiredNodeRange})`);
process.exitCode = 1;
}
const envFiles = detectEnvFiles();
console.log(`Project .env: ${envFiles.cwdEnv ?? 'not found'}`);
console.log(`Home .env: ${envFiles.homeEnv ?? 'not found'}`);
const transport = resolveTransport({ http: options.http }, process.env.MCP_TRANSPORT);
if (transport !== 'http') {
console.log('Using stdio transport; port checks skipped.');
return;
}
const port = resolveHttpPort(options.port, process.env.MCP_HTTP_PORT);
const status = await portStatus(port);
console.log(`HTTP port ${port}: ${status}`);
}
async function runInstallCommand(options: InstallOptions): Promise<void> {
const clientKey = options.client?.toLowerCase();
const adapter = clientKey ? CLIENT_ADAPTERS[clientKey] : undefined;
if (!adapter) {
throw new Error(`Unsupported client: ${options.client}`);
}
const interactive = !options.nonInteractive;
const description = adapter.describe();
const envResult = await ensureEnv({
interactive,
local: Boolean(options.local),
requiredKeys: description.requiredEnvKeys,
});
if (envResult.missing?.length) {
return;
}
if (envResult.wrote && envResult.path) {
console.log(`Secrets written to ${envResult.path}`);
}
const transport = resolveTransport({ http: options.http, stdio: options.stdio }, process.env.MCP_TRANSPORT);
let httpPort: number | undefined;
let httpUrl: string | undefined;
if (transport === 'http') {
httpPort = resolveHttpPort(options.port, process.env.MCP_HTTP_PORT);
httpUrl = `http://127.0.0.1:${httpPort}`;
} else if (options.port != null) {
throw new Error('The --port option is only available when using --http.');
}
const entry = createInstallEntry(transport, httpPort);
const mergeOptions: MergeOpts = {
id: MANAGED_ID,
sentinel: SENTINEL,
transport,
httpUrl,
};
if (options.devWatch || options.devDebug) {
mergeOptions.dev = {};
if (options.devWatch) {
mergeOptions.dev.watch = true;
}
if (options.devDebug) {
mergeOptions.dev.debug = options.devDebug;
}
}
const configPath = await adapter.locate(options.config);
if (!configPath) {
emitManualInstallMessage({
adapter,
clientKey,
description,
entry,
mergeOptions,
transport,
httpUrl,
});
return;
}
const configExists = await fileExists(configPath);
let existingRaw = '';
let currentConfig: JsonRecord = {};
if (configExists) {
existingRaw = await fsPromises.readFile(configPath, 'utf8');
currentConfig = await adapter.read(configPath, existingRaw);
}
const { next, changed, reason } = adapter.merge(currentConfig, entry, mergeOptions);
if (!changed) {
if (reason) {
console.warn(reason);
} else {
console.log(`${description.name} already has a managed entry for ${MANAGED_ID}.`);
}
return;
}
const nextRaw = `${JSON.stringify(next, null, 2)}\n`;
if (options.dryRun) {
const diff = formatUnifiedDiff(existingRaw, nextRaw, configPath);
console.log(diff.trim() ? diff : 'No changes.');
return;
}
if (existingRaw) {
const backupPath = await createBackup(configPath, existingRaw);
console.log(`Backup created at ${backupPath}`);
}
await adapter.writeAtomic(configPath, next);
const summaryEntry = extractManagedEntry(next, MANAGED_ID);
console.log(`${description.name} config updated (${transport}): ${configPath}`);
if (summaryEntry) {
console.log(JSON.stringify(summaryEntry, null, 2));
}
console.log('Restart the client to pick up the new MCP server.');
if (transport === 'http' && httpPort) {
const startCommand = formatStartCommand(entry);
console.log(`Start the server separately with: ${startCommand}`);
console.log(`HTTP endpoint: ${httpUrl}`);
}
}
function createInstallEntry(transport: Transport, port?: number): JsonRecord {
const args: string[] = ['-y', '@pv-bhat/vibe-check-mcp', 'start'];
if (transport === 'http') {
args.push('--http');
const resolvedPort = port ?? 2091;
args.push('--port', String(resolvedPort));
} else {
args.push('--stdio');
}
return {
command: 'npx',
args,
env: {},
} satisfies JsonRecord;
}
function formatStartCommand(entry: JsonRecord): string {
const command = typeof entry.command === 'string' ? entry.command : 'npx';
const args = Array.isArray(entry.args) ? entry.args.map((value) => String(value)) : [];
return [command, ...args].join(' ');
}
function extractManagedEntry(config: JsonRecord, id: string): JsonRecord | null {
const mapCandidates: Array<JsonRecord | undefined> = [];
if (isRecord(config.mcpServers)) {
mapCandidates.push(config.mcpServers as JsonRecord);
}
if (isRecord(config.servers)) {
mapCandidates.push(config.servers as JsonRecord);
}
for (const map of mapCandidates) {
if (!map) {
continue;
}
const entry = map[id];
if (isRecord(entry)) {
return entry as JsonRecord;
}
}
return null;
}
type ManualInstallArgs = {
adapter: ClientAdapter;
clientKey: string;
description: ReturnType<ClientAdapter['describe']>;
entry: JsonRecord;
mergeOptions: MergeOpts;
transport: Transport;
httpUrl?: string;
};
function emitManualInstallMessage(args: ManualInstallArgs): void {
const { adapter, clientKey, description, entry, mergeOptions, transport, httpUrl } = args;
console.log(`${description.name} configuration not found at ${description.pathHint}.`);
if (description.notes) {
console.log(description.notes);
}
const preview = adapter.merge({}, entry, mergeOptions);
const managedEntry = extractManagedEntry(preview.next, MANAGED_ID) ?? preview.next;
console.log('Add this MCP server configuration manually:');
console.log(JSON.stringify(managedEntry, null, 2));
if (clientKey === 'vscode') {
const installUrl = createVsCodeInstallUrl(entry, mergeOptions);
console.log('VS Code quick install link:');
console.log(installUrl);
console.log('Command Palette → "MCP: Add Server" will open the profile file.');
} else if (clientKey === 'cursor') {
console.log('Cursor → Settings → MCP Servers lets you paste this JSON.');
} else if (clientKey === 'windsurf') {
console.log('Create the file if it does not exist, then restart Windsurf.');
}
if (transport === 'http' && httpUrl) {
const startCommand = formatStartCommand(entry);
console.log(`Expose the HTTP server separately with: ${startCommand}`);
console.log(`HTTP endpoint: ${httpUrl}`);
}
}
function createVsCodeInstallUrl(entry: JsonRecord, options: MergeOpts): string {
const url = new URL('vscode:mcp/install');
url.searchParams.set('name', 'Vibe Check MCP');
const command = typeof entry.command === 'string' ? entry.command : 'npx';
url.searchParams.set('command', command);
const args = Array.isArray(entry.args) ? entry.args.map((value) => String(value)) : [];
if (args.length > 0) {
url.searchParams.set('args', JSON.stringify(args));
}
if (options.transport === 'http' && options.httpUrl) {
url.searchParams.set('url', options.httpUrl);
} else {
url.searchParams.set('transport', options.transport);
}
return url.toString();
}
export function createCliProgram(): Command {
const pkg = readPackageJson();
const program = new Command();
program
.name('vibe-check-mcp')
.description('CLI utilities for the Vibe Check MCP server')
.version(pkg.version ?? '0.0.0');
program
.option('--list-clients', 'List supported MCP client integrations')
.addHelpText('afterAll', () => {
const clients = collectRegisteredClients();
if (clients.length === 0) {
return '';
}
const longestKey = Math.max(...clients.map((client) => client.key.length));
const lines = clients
.map((client) => ` ${client.key.padEnd(longestKey)} ${client.description.name}`)
.join('\n');
return `\nSupported clients:\n${lines}\n\nRun 'npx @pv-bhat/vibe-check-mcp --list-clients' for details.\n`;
});
program
.command('start')
.description('Start the Vibe Check MCP server')
.addOption(new Option('--stdio', 'Use STDIO transport').conflicts('http'))
.addOption(new Option('--http', 'Use HTTP transport').conflicts('stdio'))
.option('--port <number>', 'HTTP port (default: 2091)', parsePort)
.option('--dry-run', 'Print the resolved command without executing')
.action(async (options: StartOptions) => {
try {
await runStartCommand(options);
} catch (error) {
console.error((error as Error).message);
process.exitCode = 1;
}
});
program
.command('doctor')
.description('Diagnose environment issues')
.option('--http', 'Check HTTP transport readiness')
.option('--port <number>', 'HTTP port to inspect', parsePort)
.action(async (options: DoctorOptions) => {
try {
await runDoctorCommand(options);
} catch (error) {
console.error((error as Error).message);
process.exitCode = 1;
}
});
program
.command('install')
.description('Install client integrations')
.requiredOption('--client <name>', 'Client to configure')
.option('--config <path>', 'Path to the client configuration file')
.option('--dry-run', 'Show the merged configuration without writing')
.option('--non-interactive', 'Do not prompt for missing environment values')
.option('--local', 'Write secrets to the project .env instead of ~/.vibe-check/.env')
.addOption(new Option('--stdio', 'Configure STDIO transport').conflicts('http'))
.addOption(new Option('--http', 'Configure HTTP transport').conflicts('stdio'))
.option('--port <number>', 'HTTP port (default: 2091)', parsePort)
.option('--dev-watch', 'Add dev.watch=true (VS Code only)')
.option('--dev-debug <value>', 'Set dev.debug (VS Code only)')
.action(async (options: InstallOptions) => {
try {
await runInstallCommand(options);
} catch (error) {
console.error((error as Error).message);
process.exitCode = 1;
}
});
program.action(() => {
const options = program.opts<{ listClients?: boolean }>();
if (options.listClients) {
showAvailableClients();
return;
}
program.help();
});
return program;
}
function normalizeTransport(value: string | undefined): Transport | undefined {
if (!value) {
return undefined;
}
const normalized = value.trim().toLowerCase();
if (normalized === 'http' || normalized === 'stdio') {
return normalized;
}
return undefined;
}
function resolveTransport(
options: { http?: boolean; stdio?: boolean },
envTransport: string | undefined,
): Transport {
const flagTransport = options.http ? 'http' : options.stdio ? 'stdio' : undefined;
const resolvedEnv = normalizeTransport(envTransport);
return flagTransport ?? resolvedEnv ?? 'stdio';
}
function resolveHttpPort(optionPort: number | undefined, envPort: string | undefined): number {
if (optionPort != null) {
return optionPort;
}
if (envPort) {
const parsed = Number.parseInt(envPort, 10);
if (!Number.isNaN(parsed) && parsed > 0) {
return parsed;
}
}
return 2091;
}
async function fileExists(path: string): Promise<boolean> {
try {
await fsPromises.access(path);
return true;
} catch {
return false;
}
}
function formatTimestamp(date: Date): string {
const iso = date.toISOString();
return iso.replace(/[:.]/g, '-');
}
async function createBackup(path: string, contents: string): Promise<string> {
const backupPath = `${path}.${formatTimestamp(new Date())}.bak`;
await fsPromises.writeFile(backupPath, contents, { mode: 0o600 });
return backupPath;
}
const executedArg = process.argv[1];
if (executedArg) {
let executedFileUrl: string;
try {
const resolved = realpathSync(executedArg);
executedFileUrl = pathToFileURL(resolved).href;
} catch (error) {
console.warn(`Failed to resolve CLI entrypoint: ${(error as Error).message}`);
executedFileUrl = pathToFileURL(executedArg).href;
}
if (executedFileUrl === import.meta.url) {
createCliProgram()
.parseAsync(process.argv)
.catch((error: unknown) => {
console.error((error as Error).message);
process.exitCode = 1;
});
}
}
```