@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
434 lines • 17.6 kB
JavaScript
import { dirname } from "node:path";
import { resolveServerAuth } from "./auth/context.js";
import { diagnoseCapturedMcpConnectFailure, diagnoseMcpConnectFailure } from "./diagnose.js";
import { ConnectError } from "./errors.js";
import { legacyMcpFormEligible } from "./elicitation.js";
import { isModernMcpClient, legacyMcpFormsAdvertised } from "./modern/request.js";
import { subscribeMcpServerLogging } from "./logging.js";
import { isMcpNeedsAuthError } from "./needs-auth.js";
import { subscribeMcpListChanged } from "./notifications.js";
import { subscribeMcpResourceUpdated } from "./resources.js";
import { connectMcpTransport, createMcpTransport, shutdownMcpTransport, } from "./transport.js";
import { wrapAsync } from "./wrap.js";
export class ServerConnection {
#logger;
#env;
#config;
#authProvider;
#elicitationUiProvider;
#elicitationEnabled;
#resolveConfig;
#projectPolicy;
#policyAbort;
#requestLifetime = new AbortController();
get requestLifetimeSignal() {
return this.#requestLifetime.signal;
}
#startedGrantNames = [];
#state;
#generation = 0;
#connection;
#pendingConnection;
#pendingConnect;
#renegotiatingForms;
#stopFormReadiness;
#lastError;
#stateListeners = new Set();
#toolsListeners = new Set();
#shutdownConnections = new Map();
constructor(options) {
this.serverName = options.serverName;
this.#config = options.config;
this.#logger = options.logger;
this.#env = options.env;
this.#authProvider = options.authProvider;
this.#elicitationUiProvider = options.elicitationUiProvider;
this.#elicitationEnabled = options.elicitationEnabled;
this.#resolveConfig = options.resolveConfig;
this.#projectPolicy = options.projectPolicy;
this.#startedGrantNames = options.projectPolicy?.initial.grantedNames ?? [];
this.#state = options.config.enabled ? "idle" : "disabled";
}
get state() {
return this.#state;
}
get declarationIdentity() {
return this.#projectPolicy?.identity;
}
get projectPolicy() {
return this.#projectPolicy;
}
get startedGrantNames() {
return this.#startedGrantNames;
}
get lastError() {
return this.#lastError;
}
get generation() {
return this.#generation;
}
refreshCapturedDiagnostics() {
const current = this.#lastError;
if (current === undefined)
return;
const capturedError = diagnoseCapturedMcpConnectFailure({
config: this.#config,
cause: current,
env: this.#env,
logger: this.#logger,
serverName: this.serverName,
});
if (capturedError !== null && capturedError.message !== current.message) {
this.#lastError = capturedError;
}
}
get client() {
if (this.#connection === undefined) {
throw new ConnectError(`MCP server ${this.serverName} is not connected`, {
phase: "client",
serverName: this.serverName,
});
}
return this.#connection.client;
}
getRootPid() {
return this.#connection?.getRootPid() ?? null;
}
connect() {
return this.#renegotiatingForms ?? this.#connect();
}
#legacyFormsChanged(client) {
return (this.#elicitationUiProvider?.enforced?.() === true &&
!isModernMcpClient(client) &&
legacyMcpFormsAdvertised(client) !==
legacyMcpFormEligible(this.#elicitationUiProvider, this.#elicitationEnabled !== false));
}
#refreshLegacyForms() {
if (this.#state !== "connected" || this.#renegotiatingForms || !this.#legacyFormsChanged(this.client))
return;
// Publish the single flight before renewing: connect callers join it while the old transport closes.
this.#renegotiatingForms = Promise.resolve()
.then(() => this.renew())
.finally(() => {
this.#renegotiatingForms = undefined;
});
void this.#renegotiatingForms.catch((error) => {
this.markDegraded(error instanceof Error ? error : new Error(String(error)));
});
}
#connect() {
if (this.#state === "disabled") {
return Promise.reject(this.#connectError(`MCP server ${this.serverName} is disabled`, "connect"));
}
if (this.#elicitationUiProvider?.enforced?.())
this.#stopFormReadiness ??= this.#elicitationUiProvider.subscribe?.(() => this.#refreshLegacyForms());
if (this.#state === "connected")
return Promise.resolve(this.client);
if (this.#pendingConnect)
return this.#pendingConnect;
const generation = this.#generation;
let attempt;
if (this.#projectPolicy !== undefined)
attempt = this.#openProjectConnection(generation);
else {
try {
attempt = this.#openConnection(this.#createTransportConnection(), generation);
}
catch (error) {
return Promise.reject(error);
}
}
this.#pendingConnect = attempt.finally(() => {
if (this.#pendingConnect !== undefined && generation === this.#generation)
this.#pendingConnect = undefined;
});
// Emit "connecting" only after the single-flight promise is published, so a listener that calls
// connect() joins this attempt instead of starting a second one.
if (generation === this.#generation)
this.#setState("connecting");
return this.#pendingConnect;
}
async #openProjectConnection(generation) {
const policy = this.#projectPolicy;
if (policy === undefined)
throw this.#connectError("Missing project MCP policy", "create");
const abort = new AbortController();
this.#policyAbort = abort;
try {
const resolved = await policy.resolve(abort.signal);
if (abort.signal.aborted || generation !== this.#generation) {
throw this.#connectError("Project MCP materialization was invalidated; retry", "connect", true);
}
this.#startedGrantNames = resolved.grantedNames;
return await this.#openConnection(this.#createTransportConnection(resolved), generation);
}
catch (error) {
if (abort.signal.aborted || generation !== this.#generation) {
throw this.#connectError("Project MCP materialization was invalidated; retry", "connect", true);
}
throw error;
}
}
// Own the connection before discovery so a concurrent dispose can abort the probe.
async #openConnection(connection, generation) {
this.#pendingConnection = connection;
try {
return await this.#connectTransport(connection, generation);
}
finally {
if (this.#pendingConnection === connection)
this.#pendingConnection = undefined;
}
}
async renew() {
if (this.#state === "disabled") {
throw this.#connectError(`MCP server ${this.serverName} is disabled`, "renew");
}
this.#policyAbort?.abort();
this.#requestLifetime.abort();
this.#requestLifetime = new AbortController();
this.#generation++;
this.#pendingConnect = undefined;
this.#setState("idle");
await this.#disposeOwnedConnections();
return this.#connect();
}
bumpGeneration() {
this.#requestLifetime.abort();
this.#requestLifetime = new AbortController();
this.#policyAbort?.abort();
this.#generation++;
this.#pendingConnect = undefined;
this.#lastError = undefined;
if (this.#state !== "disabled")
this.#setState("idle");
return this.#disposeOwnedConnections();
}
disable() {
this.#stopFormReadiness?.();
this.#stopFormReadiness = undefined;
this.#requestLifetime.abort();
this.#policyAbort?.abort();
this.#generation++;
this.#pendingConnect = undefined;
this.#lastError = undefined;
this.#setState("disabled");
return this.#disposeOwnedConnections();
}
async dispose() {
this.#stopFormReadiness?.();
this.#stopFormReadiness = undefined;
this.#requestLifetime.abort();
this.#policyAbort?.abort();
this.#generation++;
this.#pendingConnect = undefined;
this.#setState("disabled");
await this.#disposeOwnedConnections();
}
markDegraded(error) {
this.#markFailure("degraded", error);
}
markSuspended(error) {
this.#markFailure("suspended", error);
}
markNeedsAuth(error) {
this.#markFailure("needs_auth", error);
}
markNeedsClientRegistration(error) {
this.#markFailure("needs_client_registration", error);
}
markToolsChanged(cause = "notification") {
this.#emit(this.#toolsListeners, {
type: "tools_changed",
serverName: this.serverName,
generation: this.#generation,
cause,
});
}
onStateChange(listener) {
this.#stateListeners.add(listener);
return () => this.#stateListeners.delete(listener);
}
onToolsChanged(listener) {
this.#toolsListeners.add(listener);
return () => this.#toolsListeners.delete(listener);
}
#createTransportConnection(resolved) {
const projectAbort = this.#policyAbort;
const authProvider = resolved === undefined
? this.#authProvider
: resolveServerAuth({
agentDir: this.#projectPolicy === undefined ? undefined : dirname(this.#projectPolicy.storePath),
config: resolved.config,
env: resolved.env,
logger: this.#logger,
serverName: this.serverName,
}).provider;
return createMcpTransport({
authProvider,
config: resolved?.config ?? this.#config,
env: resolved?.env ?? this.#env,
projectPolicy: resolved !== undefined,
resolveProjectPolicy: resolved === undefined
? undefined
: async () => {
const policy = this.#projectPolicy;
const abort = projectAbort;
if (policy === undefined || abort === undefined) {
throw this.#connectError("Project MCP policy is no longer available", "create", true);
}
const current = await policy.resolve(abort.signal, false);
abort.signal.throwIfAborted();
this.#startedGrantNames = current.grantedNames;
return current;
},
elicitationUiProvider: this.#elicitationUiProvider,
elicitationEnabled: this.#elicitationEnabled,
logger: this.#logger,
resolveConfig: this.#resolveConfig,
serverName: this.serverName,
});
}
#trackTransport(connection, generation) {
connection.transport.onclose = wrapAsync("connection.transport.onclose", () => {
if (this.#shutdownConnections.has(connection))
return;
if (connection === this.#pendingConnection && this.#state === "connecting") {
const closeError = this.#connectError(`MCP server ${this.serverName} transport closed`, "close", true);
const capturedError = diagnoseCapturedMcpConnectFailure({
config: this.#config,
cause: closeError,
env: this.#env,
logger: this.#logger,
serverName: this.serverName,
});
if (capturedError !== null)
this.markDegraded(capturedError);
return;
}
if (connection !== this.#connection && connection !== this.#pendingConnection)
return;
if (generation === this.#generation && this.#state !== "disabled") {
this.markDegraded(this.#connectError(`MCP server ${this.serverName} transport closed`, "close", true));
}
}, this.#sink);
}
async #connectTransport(connection, generation) {
try {
await connection.materialize();
this.#trackTransport(connection, generation);
await connectMcpTransport(connection);
}
catch (error) {
if (this.#pendingConnection === connection)
this.#pendingConnection = undefined;
await this.#shutdown(connection);
if (generation !== this.#generation || this.#state === "disabled") {
throw this.#connectError(`MCP server ${this.serverName} connect was superseded`, "connect", true);
}
if (error instanceof ConnectError && error.phase === "modern-stdio") {
this.markDegraded(error);
throw error;
}
if (isMcpNeedsAuthError(error)) {
const authError = error instanceof Error ? error : new Error(String(error));
this.markNeedsAuth(authError);
throw authError;
}
const connectError = await diagnoseMcpConnectFailure({
config: this.#config,
cause: error instanceof Error ? error : new Error(String(error)),
env: this.#env,
logger: this.#logger,
serverName: this.serverName,
});
this.markDegraded(connectError);
throw connectError;
}
if (generation !== this.#generation || this.#state === "disabled") {
await this.#shutdown(connection);
throw this.#connectError(`MCP server ${this.serverName} connect was superseded`, "connect", true);
}
if (this.#pendingConnection === connection)
this.#pendingConnection = undefined;
this.#connection = connection;
this.#lastError = undefined;
// Subscribe to list_changed on the fresh client (even if the server never
// declared the capability) so dynamic catalog updates reach the service.
subscribeMcpListChanged(connection.client, () => this.markToolsChanged());
// Resource updates ride the same refresh path: the service re-collects the
// catalog (tools AND resources) on tools-changed.
subscribeMcpResourceUpdated(connection.client, () => this.markToolsChanged());
// Server logging notifications (todo 42): RFC-5424 → the per-server
// logger, filtered by config.logLevel, burst-capped.
subscribeMcpServerLogging(connection.client, { logLevel: this.#config.logLevel, logger: this.#logger });
// Readiness can change while initialize is in flight; never publish that stale negotiation as connected.
if (this.#legacyFormsChanged(connection.client))
return this.renew();
this.#setState("connected");
this.markToolsChanged("connect");
return connection.client;
}
async #disposeOwnedConnections() {
const connections = new Set();
const connection = this.#connection;
this.#connection = undefined;
if (connection !== undefined)
connections.add(connection);
const pendingConnection = this.#pendingConnection;
this.#pendingConnection = undefined;
if (pendingConnection !== undefined)
connections.add(pendingConnection);
await Promise.all([...connections].map((item) => this.#shutdown(item)));
}
async #shutdown(connection) {
const pending = this.#shutdownConnections.get(connection);
if (pending !== undefined) {
await pending;
return;
}
const shutdown = (async () => {
await shutdownMcpTransport(connection);
})();
this.#shutdownConnections.set(connection, shutdown);
try {
await shutdown;
}
finally {
this.#shutdownConnections.delete(connection);
}
}
#setState(state, error) {
if (this.#state === state)
return;
const previousState = this.#state;
this.#state = state;
this.#emit(this.#stateListeners, {
type: "state_changed",
serverName: this.serverName,
previousState,
state,
generation: this.#generation,
error,
});
}
#emit(listeners, event) {
for (const listener of listeners) {
void wrapAsync("connection.event", listener, this.#sink)(event);
}
}
#markFailure(state, error) {
// disabled is terminal (dispose/disable): a late failure from an attempt it superseded must not revive it (senpi#4013).
if (this.#state === "disabled")
return;
this.#lastError = error;
this.#setState(state, error);
}
#connectError(message, phase, retriable, cause) {
return new ConnectError(message, { cause, phase, retriable, serverName: this.serverName });
}
get #sink() {
return { logger: this.#logger };
}
}
//# sourceMappingURL=connection.js.map