@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
146 lines • 5.43 kB
JavaScript
import { execFile } from "node:child_process";
import { redactResolvedReferenceValues } from "../../../config-reference-redaction.js";
import { ConnectError } from "./errors.js";
import { redactMcpLogText } from "./log.js";
import { loadMcpSdkStdioTransport } from "./sdk.lazy.js";
export const MCP_STDIO_DIAGNOSTIC_TIMEOUT_MS = 5000;
const MCP_STDIO_DIAGNOSTIC_MAX_BYTES = 2048;
export async function diagnoseMcpConnectFailure(options) {
const diagnostic = await maybeDiagnoseStdioFailure(options);
return connectErrorFromDiagnostic(options, diagnostic);
}
export function diagnoseCapturedMcpConnectFailure(options) {
if (options.config.type !== "stdio")
return null;
const diagnostic = extractCapturedStderr(options.logger);
if (diagnostic.length === 0)
return null;
return connectErrorFromDiagnostic(options, boundDiagnostic(diagnostic));
}
function connectErrorFromDiagnostic(options, diagnostic) {
const message = diagnostic === null || diagnostic.length === 0
? `MCP server ${options.serverName} failed during connect: ${options.cause.message}`
: `MCP server ${options.serverName} failed during connect: ${options.cause.message}\n${diagnostic}`;
return new ConnectError(redactResolvedReferenceValues(message), {
cause: options.cause,
phase: "connect",
retriable: true,
serverName: options.serverName,
});
}
export async function maybeDiagnoseStdioFailure(options) {
if (options.config.type !== "stdio")
return null;
const captured = extractCapturedStderr(options.logger);
if (captured.length > 0)
return boundDiagnostic(captured);
const command = options.config.command;
if (command === undefined || command.trim().length === 0)
return null;
const env = await buildDiagnosticEnv(options);
const result = await execFileForDiagnostics(command, options.config.args, { cwd: options.config.cwd, env });
if (isNodeErrorCode(result.error, "ENOENT"))
return commandNotFoundDiagnostic(command, env, options);
const lines = meaningfulLines(`${result.stderr}\n${result.stdout}`);
if (lines.length > 0)
return boundDiagnostic(lines);
if (isTimedOut(result.error))
return `diagnostic rerun timed out after ${MCP_STDIO_DIAGNOSTIC_TIMEOUT_MS}ms`;
return null;
}
function extractCapturedStderr(logger) {
const messages = [];
for (const line of logger.getRingBuffer()) {
const parsed = parseLogLine(line);
if (parsed?.channel === "stderr" && typeof parsed.message === "string") {
messages.push(parsed.message);
}
}
return meaningfulLines(messages.join("\n"));
}
function parseLogLine(line) {
try {
const parsed = JSON.parse(line);
if (typeof parsed === "object" && parsed !== null)
return parsed;
}
catch {
return null;
}
return null;
}
function meaningfulLines(text) {
return text
.split(/\r?\n/)
.map((line) => redactMcpLogText(line.trim()))
.filter((line) => line.length > 0);
}
function boundDiagnostic(lines) {
let output = "";
for (const line of lines) {
const next = output.length === 0 ? line : `${output}\n${line}`;
if (Buffer.byteLength(next, "utf8") > MCP_STDIO_DIAGNOSTIC_MAX_BYTES)
break;
output = next;
}
return output || lines[0]?.slice(0, MCP_STDIO_DIAGNOSTIC_MAX_BYTES) || "";
}
function execFileForDiagnostics(command, args, options) {
return new Promise((resolve) => {
execFile(command, args ?? [], {
cwd: options.cwd,
env: options.env,
killSignal: "SIGKILL",
maxBuffer: MCP_STDIO_DIAGNOSTIC_MAX_BYTES * 4,
timeout: MCP_STDIO_DIAGNOSTIC_TIMEOUT_MS,
// senpi#3965: an MCP server command can be a console-subsystem
// exe on Windows; never flash its own console window.
windowsHide: true,
}, (error, stdout, stderr) => {
resolve({
error,
stdout,
stderr,
});
});
});
}
async function buildDiagnosticEnv(options) {
const { getDefaultEnvironment } = await loadMcpSdkStdioTransport();
return {
...getDefaultEnvironment(),
...definedEnv(options.env),
...(options.config.env ?? {}),
};
}
function commandNotFoundDiagnostic(command, env, options) {
const cwd = options.config.cwd ?? process.cwd();
const path = env.PATH ?? "";
return [
`command not found: ${redactMcpLogText(command)}`,
`cwd: ${redactMcpLogText(cwd)}`,
`PATH: ${redactMcpLogText(path)}`,
"Install the command, add it to PATH, or configure an absolute command path in mcp.json.",
].join("\n");
}
function definedEnv(env) {
const result = {};
for (const [key, value] of Object.entries(env ?? {})) {
if (value !== undefined)
result[key] = value;
}
return result;
}
function isTimedOut(error) {
if (error === null)
return false;
const signal = getProperty(error, "signal");
return signal === "SIGKILL" || error.message.includes("timed out");
}
function isNodeErrorCode(error, code) {
return error !== null && getProperty(error, "code") === code;
}
function getProperty(value, key) {
return value[key];
}
//# sourceMappingURL=diagnose.js.map