fix(mcp): retry Claude user config locks

This commit is contained in:
walker1211 authored and GitHub committed 2026-06-10 13:03:25 -04:00
1 parent f59536a81f
commit cf90f48240
6 files changed
+313 -176

No files matched your search

+4 -33
View File
@@ -4,10 +4,13 @@
import * as fs from 'fs';
import * as path from 'path';
import * as lockfile from 'proper-lockfile';
import { InstanceManager } from '../../management/instance-manager';
import { getClaudeUserConfigPath } from '../claude-config-path';
import { getCcsDir } from '../config-manager';
import {
isClaudeUserConfigLockUnavailableError as isLockUnavailableError,
withClaudeUserConfigLock,
} from '../claude-user-config-lock';
const BROWSER_MCP_SERVER = 'ccs-browser-server.cjs';
const BROWSER_MCP_SERVER_NAME = 'ccs-browser';
@@ -133,38 +136,6 @@ function writeClaudeUserConfig(configPath: string, config: ClaudeUserConfig): bo
}
}
function withClaudeUserConfigLock<T>(configPath: string, callback: () => T): T {
const configDir = path.dirname(configPath);
const lockTarget = path.join(configDir, `${path.basename(configPath)}.ccs-lock`);
let release: (() => void) | undefined;
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
}
if (!fs.existsSync(lockTarget)) {
fs.writeFileSync(lockTarget, '', { encoding: 'utf8', mode: 0o600 });
}
try {
release = lockfile.lockSync(lockTarget, { stale: 10000 }) as () => void;
return callback();
} finally {
if (release) {
try {
release();
} catch {
// Best-effort release.
}
}
}
}
function isLockUnavailableError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ELOCKED' || code === 'ENOTACQUIRED';
}
function removeManagedServerConfig(configPath: string): boolean {
if (!fs.existsSync(configPath)) {
return false;
+102
View File
@@ -0,0 +1,102 @@
import * as fs from 'fs';
import * as path from 'path';
import * as lockfile from 'proper-lockfile';
const DEFAULT_LOCK_STALE_MS = 10000;
const DEFAULT_LOCK_RETRY_DELAY_MS = 200;
const DEFAULT_LOCK_RETRY_TIMEOUT_MS = 10000;
interface LockOptions {
staleMs?: number;
retryDelayMs?: number;
retryTimeoutMs?: number;
}
export function withClaudeUserConfigLock<T>(
configPath: string,
callback: () => T,
options: LockOptions = {}
): T {
const configDir = path.dirname(configPath);
const lockTarget = path.join(configDir, `${path.basename(configPath)}.ccs-lock`);
const staleMs = options.staleMs ?? DEFAULT_LOCK_STALE_MS;
const retryDelayMs = options.retryDelayMs ?? DEFAULT_LOCK_RETRY_DELAY_MS;
const retryTimeoutMs = options.retryTimeoutMs ?? DEFAULT_LOCK_RETRY_TIMEOUT_MS;
let release: (() => void) | undefined;
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
}
if (!fs.existsSync(lockTarget)) {
fs.writeFileSync(lockTarget, '', { encoding: 'utf8', mode: 0o600 });
}
try {
release = acquireClaudeUserConfigLock(
lockTarget,
configPath,
staleMs,
retryDelayMs,
retryTimeoutMs
);
return callback();
} finally {
if (release) {
try {
release();
} catch {}
}
}
}
export function isClaudeUserConfigLockUnavailableError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ELOCKED' || code === 'ENOTACQUIRED';
}
function acquireClaudeUserConfigLock(
lockTarget: string,
configPath: string,
staleMs: number,
retryDelayMs: number,
retryTimeoutMs: number
): () => void {
const startedAt = Date.now();
let lastError: unknown;
for (;;) {
try {
return lockfile.lockSync(lockTarget, { stale: staleMs }) as () => void;
} catch (error) {
if (!isClaudeUserConfigLockUnavailableError(error)) {
throw error;
}
lastError = error;
if (Date.now() - startedAt >= retryTimeoutMs) {
throw buildLockTimeoutError(configPath, retryTimeoutMs, lastError);
}
sleepSync(retryDelayMs);
}
}
}
function sleepSync(ms: number): void {
if (ms <= 0) {
return;
}
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
function buildLockTimeoutError(
configPath: string,
timeoutMs: number,
cause: unknown
): NodeJS.ErrnoException {
const causeCode = (cause as NodeJS.ErrnoException | undefined)?.code;
const error = new Error(
`Failed to acquire Claude user config lock for ${configPath} after ${timeoutMs}ms; another CCS process may be starting CLIProxy`
) as NodeJS.ErrnoException;
error.code = causeCode === 'ENOTACQUIRED' ? 'ENOTACQUIRED' : 'ELOCKED';
return error;
}
+4 -33
View File
@@ -4,7 +4,6 @@
import * as fs from 'fs';
import * as path from 'path';
import * as lockfile from 'proper-lockfile';
import { getCcsDir } from '../config-manager';
import { getClaudeUserConfigPath } from '../claude-config-path';
@@ -12,6 +11,10 @@ import { info, warn } from '../ui';
import { InstanceManager } from '../../management/instance-manager';
import { installImageAnalysisPrompts } from './hook-installer';
import { getImageAnalysisConfig } from '../../config/config-loader-facade';
import {
isClaudeUserConfigLockUnavailableError as isLockUnavailableError,
withClaudeUserConfigLock,
} from '../claude-user-config-lock';
const IMAGE_ANALYSIS_MCP_SERVER = 'ccs-image-analysis-server.cjs';
const IMAGE_ANALYSIS_MCP_RUNTIME = 'image-analysis-runtime.cjs';
@@ -121,38 +124,6 @@ function writeClaudeUserConfig(configPath: string, config: ClaudeUserConfig): bo
}
}
function withClaudeUserConfigLock<T>(configPath: string, callback: () => T): T {
const configDir = path.dirname(configPath);
const lockTarget = path.join(configDir, `${path.basename(configPath)}.ccs-lock`);
let release: (() => void) | undefined;
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
}
if (!fs.existsSync(lockTarget)) {
fs.writeFileSync(lockTarget, '', { encoding: 'utf8', mode: 0o600 });
}
try {
release = lockfile.lockSync(lockTarget, { stale: 10000 }) as () => void;
return callback();
} finally {
if (release) {
try {
release();
} catch {
// Best-effort release.
}
}
}
}
function isLockUnavailableError(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
return code === 'ELOCKED' || code === 'ENOTACQUIRED';
}
export function hasImageAnalysisMcpServerInstalled(): boolean {
return (
fs.existsSync(getImageAnalysisMcpServerPath()) &&
+134 -95
View File
@@ -12,6 +12,10 @@ import { InstanceManager } from '../../management/instance-manager';
import { installWebSearchHook } from './hook-installer';
import { appendWebSearchTrace } from './trace';
import { getWebSearchConfig } from '../../config/config-loader-facade';
import {
isClaudeUserConfigLockUnavailableError as isLockUnavailableError,
withClaudeUserConfigLock,
} from '../claude-user-config-lock';
const WEBSEARCH_MCP_SERVER = 'ccs-websearch-server.cjs';
const WEBSEARCH_MCP_SERVER_NAME = 'ccs-websearch';
@@ -118,47 +122,63 @@ function removeManagedServerConfig(configPath: string): boolean {
return false;
}
const config = readClaudeUserConfig(configPath);
if (config === null) {
if (process.env.CCS_DEBUG) {
console.error(warn(`Malformed Claude config prevents MCP cleanup: ${configPath}`));
}
return false;
}
const existingServers =
config.mcpServers && typeof config.mcpServers === 'object' && !Array.isArray(config.mcpServers)
? { ...(config.mcpServers as Record<string, unknown>) }
: {};
if (!(WEBSEARCH_MCP_SERVER_NAME in existingServers)) {
return false;
}
delete existingServers[WEBSEARCH_MCP_SERVER_NAME];
const nextConfig: ClaudeUserConfig = { ...config };
if (Object.keys(existingServers).length === 0) {
delete nextConfig.mcpServers;
} else {
nextConfig.mcpServers = existingServers;
}
try {
writeClaudeUserConfig(configPath, nextConfig);
if (process.env.CCS_DEBUG) {
console.error(info(`Removed WebSearch MCP config from ${configPath}`));
}
return true;
return withClaudeUserConfigLock(configPath, () => {
const config = readClaudeUserConfig(configPath);
if (config === null) {
if (process.env.CCS_DEBUG) {
console.error(warn(`Malformed Claude config prevents MCP cleanup: ${configPath}`));
}
return false;
}
const existingServers =
config.mcpServers &&
typeof config.mcpServers === 'object' &&
!Array.isArray(config.mcpServers)
? { ...(config.mcpServers as Record<string, unknown>) }
: {};
if (!(WEBSEARCH_MCP_SERVER_NAME in existingServers)) {
return false;
}
delete existingServers[WEBSEARCH_MCP_SERVER_NAME];
const nextConfig: ClaudeUserConfig = { ...config };
if (Object.keys(existingServers).length === 0) {
delete nextConfig.mcpServers;
} else {
nextConfig.mcpServers = existingServers;
}
try {
writeClaudeUserConfig(configPath, nextConfig);
if (process.env.CCS_DEBUG) {
console.error(info(`Removed WebSearch MCP config from ${configPath}`));
}
return true;
} catch (error) {
if (process.env.CCS_DEBUG) {
console.error(
warn(
`Failed to remove WebSearch MCP config from ${configPath}: ${(error as Error).message}`
)
);
}
return false;
}
});
} catch (error) {
if (process.env.CCS_DEBUG) {
console.error(
warn(
`Failed to remove WebSearch MCP config from ${configPath}: ${(error as Error).message}`
)
);
if (isLockUnavailableError(error)) {
appendWebSearchTrace('websearch_mcp_config_remove_skipped', {
reason: 'user_config_locked',
configPath,
error: (error as Error).message,
});
return false;
}
return false;
throw error;
}
}
@@ -243,67 +263,86 @@ export function ensureWebSearchMcpConfig(): boolean {
}
const claudeUserConfigPath = getClaudeUserConfigPath();
const claudeUserConfigDir = path.dirname(claudeUserConfigPath);
const config = readClaudeUserConfig(claudeUserConfigPath);
if (config === null) {
appendWebSearchTrace('websearch_mcp_config_failed', { reason: 'malformed_user_config' });
if (process.env.CCS_DEBUG) {
console.error(warn('Malformed ~/.claude.json prevents WebSearch MCP provisioning'));
}
return false;
}
if (!fs.existsSync(claudeUserConfigDir)) {
fs.mkdirSync(claudeUserConfigDir, { recursive: true, mode: 0o700 });
}
const existingServers =
config.mcpServers && typeof config.mcpServers === 'object' && !Array.isArray(config.mcpServers)
? (config.mcpServers as Record<string, unknown>)
: {};
const desiredServerConfig: ManagedWebSearchMcpConfig = {
type: 'stdio',
command: 'node',
args: [getWebSearchMcpServerPath()],
env: {},
};
const currentConfig = existingServers[WEBSEARCH_MCP_SERVER_NAME];
if (
typeof currentConfig === 'object' &&
currentConfig !== null &&
JSON.stringify(currentConfig) === JSON.stringify(desiredServerConfig)
) {
appendWebSearchTrace('websearch_mcp_config_ready', { configPath: claudeUserConfigPath });
return true;
}
const nextConfig: ClaudeUserConfig = {
...config,
mcpServers: {
...existingServers,
[WEBSEARCH_MCP_SERVER_NAME]: desiredServerConfig,
},
};
try {
writeClaudeUserConfig(claudeUserConfigPath, nextConfig);
appendWebSearchTrace('websearch_mcp_config_ready', { configPath: claudeUserConfigPath });
if (process.env.CCS_DEBUG) {
console.error(info(`Ensured WebSearch MCP config in ${claudeUserConfigPath}`));
}
return true;
} catch (error) {
appendWebSearchTrace('websearch_mcp_config_failed', {
reason: 'write_failed',
configPath: claudeUserConfigPath,
error: (error as Error).message,
return withClaudeUserConfigLock(claudeUserConfigPath, () => {
const config = readClaudeUserConfig(claudeUserConfigPath);
if (config === null) {
appendWebSearchTrace('websearch_mcp_config_failed', { reason: 'malformed_user_config' });
if (process.env.CCS_DEBUG) {
console.error(warn('Malformed ~/.claude.json prevents WebSearch MCP provisioning'));
}
return false;
}
const existingServers =
config.mcpServers &&
typeof config.mcpServers === 'object' &&
!Array.isArray(config.mcpServers)
? (config.mcpServers as Record<string, unknown>)
: {};
const desiredServerConfig: ManagedWebSearchMcpConfig = {
type: 'stdio',
command: 'node',
args: [getWebSearchMcpServerPath()],
env: {},
};
const currentConfig = existingServers[WEBSEARCH_MCP_SERVER_NAME];
if (
typeof currentConfig === 'object' &&
currentConfig !== null &&
JSON.stringify(currentConfig) === JSON.stringify(desiredServerConfig)
) {
appendWebSearchTrace('websearch_mcp_config_ready', { configPath: claudeUserConfigPath });
return true;
}
const nextConfig: ClaudeUserConfig = {
...config,
mcpServers: {
...existingServers,
[WEBSEARCH_MCP_SERVER_NAME]: desiredServerConfig,
},
};
try {
writeClaudeUserConfig(claudeUserConfigPath, nextConfig);
appendWebSearchTrace('websearch_mcp_config_ready', { configPath: claudeUserConfigPath });
if (process.env.CCS_DEBUG) {
console.error(info(`Ensured WebSearch MCP config in ${claudeUserConfigPath}`));
}
return true;
} catch (error) {
appendWebSearchTrace('websearch_mcp_config_failed', {
reason: 'write_failed',
configPath: claudeUserConfigPath,
error: (error as Error).message,
});
if (process.env.CCS_DEBUG) {
console.error(warn(`Failed to update ~/.claude.json: ${(error as Error).message}`));
}
return false;
}
});
if (process.env.CCS_DEBUG) {
console.error(warn(`Failed to update ~/.claude.json: ${(error as Error).message}`));
} catch (error) {
if (isLockUnavailableError(error)) {
appendWebSearchTrace('websearch_mcp_config_failed', {
reason: 'user_config_locked',
configPath: claudeUserConfigPath,
error: (error as Error).message,
});
if (process.env.CCS_DEBUG) {
console.error(
warn(
`WebSearch MCP config skipped because ${claudeUserConfigPath} is locked by another process`
)
);
}
return false;
}
return false;
throw error;
}
}