Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions src/cli/commands/project-detection-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* Short-lived memo for project detection on the HTTP request path.
*
* Stateless (2026-07-28) MCP requests carry no session, so serve-http resolves
* the project root on every request, up to three times. When that root is not
* inside a Git repository, detection falls through to a synchronous
* `git rev-parse` subprocess, which blocks the event loop. On hosts where
* process creation is slow (endpoint security scanners on Windows routinely
* add one to several seconds), the stateless probe of clients such as Claude
* Code then exceeds its budget and the client falls back to legacy sessions.
*
* Results, including "not a project", are cached per path for a bounded time
* so the subprocess runs at most once per path per TTL.
*/

import type { ProjectInfo } from '../../types.js';

export const DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS = 5 * 60 * 1000;
export const MAX_PROJECT_DETECTION_CACHE_ENTRIES = 256;

export interface ProjectDetectionCacheOptions {
ttlMs?: number;
maxEntries?: number;
now?: () => number;
}

export type CachedProjectDetector = ((root: string) => ProjectInfo | null) & {
/** Drop every cached result. */
clear(): void;
/** Number of cached paths (diagnostics/tests). */
size(): number;
};

export function createCachedProjectDetector(
detect: (root: string) => ProjectInfo | null,
options: ProjectDetectionCacheOptions = {},
): CachedProjectDetector {
const ttlMs = options.ttlMs ?? DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS;
const maxEntries = options.maxEntries ?? MAX_PROJECT_DETECTION_CACHE_ENTRIES;
const now = options.now ?? Date.now;
const cache = new Map<string, { project: ProjectInfo | null; expiresAt: number }>();

const cached = ((root: string) => {
const at = now();
const hit = cache.get(root);
if (hit && hit.expiresAt > at) return hit.project;
const project = detect(root);
cache.delete(root);
cache.set(root, { project, expiresAt: at + ttlMs });
while (cache.size > maxEntries) {
const oldest = cache.keys().next().value as string | undefined;
if (oldest === undefined) break;
cache.delete(oldest);
}
return project;
}) as CachedProjectDetector;

cached.clear = () => cache.clear();
cached.size = () => cache.size;
return cached;
}
10 changes: 7 additions & 3 deletions src/cli/commands/serve-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { CURRENT_MCP_PROTOCOL_VERSION, MCP_SERVER_NAME, getMcpDiagnostics } from
import { createMcpStartupDiscoverResult, getMcpServerInfo } from '../../server/mcp-discovery.js';
import { parseTcpPortOrReport } from '../port.js';
import { mcpFileUriToPath } from '../mcp-root-path.js';
import { createCachedProjectDetector } from './project-detection-cache.js';

/**
* HTTP MCP is a shared control plane. A normal thinking break should not
Expand Down Expand Up @@ -363,10 +364,13 @@ export default defineCommand({
const statelessBindingStore = new McpBindingStore();
await statelessBindingStore.init(controlPlaneBaseDir);
const modernRuntimePool = new ModernMcpRuntimePool(MAX_STORE_CACHE_ENTRIES);
// Stateless requests resolve their project on every call. Memoize it so a
// non-Git root does not spawn `git rev-parse` (synchronously) per request.
const detectRequestProject = createCachedProjectDetector(detectorMod.detectProject);

async function resolveModernDataDir(root: string, persisted?: { dataDir?: string }): Promise<string> {
if (persisted?.dataDir) return persisted.dataDir;
const detected = detectorMod.detectProject(root);
const detected = detectRequestProject(root);
return detected
? persistMod.getProjectDataDir(detected.id)
: controlPlaneBaseDir;
Expand All @@ -383,7 +387,7 @@ export default defineCommand({
const root = persisted?.projectRoot ?? requestedRoot ?? projectRoot;
const dataDir = await resolveModernDataDir(root, persisted);
const binding = persisted ?? (() => {
const detected = detectorMod.detectProject(root);
const detected = detectRequestProject(root);
if (!detected) return undefined;
const existing = statelessBindingStore.findByProjectRoot(detected.rootPath);
return existing ? statelessBindingStore.touch(existing.handleId) ?? existing : undefined;
Expand Down Expand Up @@ -706,7 +710,7 @@ export default defineCommand({
const requestedRoot = typeof req.headers['mcp-project-root'] === 'string'
? req.headers['mcp-project-root']
: projectRoot;
const detected = detectorMod.detectProject(requestedRoot);
const detected = detectRequestProject(requestedRoot);
if (detected) {
const bindingDataDir = await persistMod.getProjectDataDir(detected.id);
const binding = statelessBindingStore.findByProjectRoot(detected.rootPath)
Expand Down
52 changes: 52 additions & 0 deletions tests/cli/project-detection-cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { describe, expect, it, vi } from 'vitest';

import {
DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS,
createCachedProjectDetector,
} from '../../src/cli/commands/project-detection-cache.js';

const project = { id: 'local/demo', name: 'demo', rootPath: '/repo/demo' };

describe('createCachedProjectDetector', () => {
it('runs detection once per path within the TTL, including negative results', () => {
const detect = vi.fn((root: string) => (root === '/repo/demo' ? project : null));
let clock = 0;
const cached = createCachedProjectDetector(detect, { now: () => clock });

expect(cached('/repo/demo')).toEqual(project);
expect(cached('/not-a-repo')).toBeNull();
clock += DEFAULT_PROJECT_DETECTION_CACHE_TTL_MS - 1;
expect(cached('/repo/demo')).toEqual(project);
expect(cached('/not-a-repo')).toBeNull();
expect(detect).toHaveBeenCalledTimes(2);
});

it('detects again once the TTL has elapsed', () => {
const detect = vi.fn((): typeof project | null => null);
let clock = 0;
const cached = createCachedProjectDetector(detect, { ttlMs: 1_000, now: () => clock });

expect(cached('/repo/new')).toBeNull();
detect.mockReturnValue(project);
clock += 1_000;
expect(cached('/repo/new')).toEqual(project);
expect(detect).toHaveBeenCalledTimes(2);
});

it('keeps at most maxEntries paths, evicting the oldest', () => {
const detect = vi.fn(() => null);
const cached = createCachedProjectDetector(detect, { maxEntries: 2 });

cached('/a');
cached('/b');
cached('/c');
expect(cached.size()).toBe(2);
cached('/b');
cached('/c');
expect(detect).toHaveBeenCalledTimes(3);
cached('/a');
expect(detect).toHaveBeenCalledTimes(4);
cached.clear();
expect(cached.size()).toBe(0);
});
});