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
7 changes: 6 additions & 1 deletion src/config/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,9 @@ export function shouldSkipDangerousPatternCheck(): boolean {
* - POOL_MAX_CONCURRENT: Maximum concurrent requests (default: 100)
* - POOL_QUEUE_SIZE: Queue size when at capacity (default: 200)
* - POOL_QUEUE_TIMEOUT_MS: Queue timeout in ms (default: 30000)
* - POOL_CONNECT_TIMEOUT_MS: Per-server connect timeout in ms (default: 20000)
* - POOL_STARTUP_CONCURRENCY: Max servers connecting at once at startup (default: 6)
* - POOL_STARTUP_RETRIES: Serial connect retries for servers that missed the first window (default: 1)
*
* @returns Validated pool configuration with defaults
* @throws {z.ZodError} If environment variables are invalid (non-numeric, out of bounds)
Expand All @@ -334,6 +337,8 @@ export function getPoolConfig(): PoolConfig {
queueSize: parseEnvInt(process.env.POOL_QUEUE_SIZE, 'POOL_QUEUE_SIZE'),
queueTimeoutMs: parseEnvInt(process.env.POOL_QUEUE_TIMEOUT_MS, 'POOL_QUEUE_TIMEOUT_MS'),
connectTimeoutMs: parseEnvInt(process.env.POOL_CONNECT_TIMEOUT_MS, 'POOL_CONNECT_TIMEOUT_MS'),
startupConcurrency: parseEnvInt(process.env.POOL_STARTUP_CONCURRENCY, 'POOL_STARTUP_CONCURRENCY'),
startupRetries: parseEnvInt(process.env.POOL_STARTUP_RETRIES, 'POOL_STARTUP_RETRIES'),
});
} catch (error) {
// WHY: Wrap Zod errors with user-friendly messages
Expand All @@ -343,7 +348,7 @@ export function getPoolConfig(): PoolConfig {
const field = firstError?.path.join('.') || 'unknown';
throw new Error(
`Invalid pool configuration: ${field} - ${firstError?.message}. ` +
`Check environment variables: POOL_MAX_CONCURRENT (1-1000), POOL_QUEUE_SIZE (1-1000), POOL_QUEUE_TIMEOUT_MS (1000-300000), POOL_CONNECT_TIMEOUT_MS (1000-120000).`
`Check environment variables: POOL_MAX_CONCURRENT (1-1000), POOL_QUEUE_SIZE (1-1000), POOL_QUEUE_TIMEOUT_MS (1000-300000), POOL_CONNECT_TIMEOUT_MS (1000-120000), POOL_STARTUP_CONCURRENCY (1-64), POOL_STARTUP_RETRIES (0-5).`
);
}
// Re-throw non-Zod errors (e.g., parseEnvInt errors)
Expand Down
17 changes: 15 additions & 2 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ export type RateLimitConfig = z.infer<typeof RateLimitConfigSchema>;
* - queueTimeoutMs: 1s-5min ensures reasonable wait times
* - connectTimeoutMs: 1s-2min caps how long a single downstream MCP server may
* take to connect, so one slow/unreachable server cannot stall pool startup
* - startupConcurrency: 1-64 caps how many downstream servers spawn+handshake at
* once. Connecting all servers simultaneously (unbounded Promise.all) makes many
* cold-starting `uvx`/`npx` children contend for CPU/IO β€” a "thundering herd"
* that pushes the slowest server (e.g. basic-memory) over connectTimeoutMs. A
* bounded window keeps startup fast while removing that contention.
* - startupRetries: 0-5 extra connect attempts for servers that missed the first
* window. Retries run serially AFTER the initial batch settles β€” with the herd
* gone, a slow server gets the machine to itself and connects on the retry
* instead of being dropped for the whole process lifetime.
*/
export const PoolConfigSchema = z.object({
/** Maximum concurrent requests (default: 100) */
Expand All @@ -38,8 +47,12 @@ export const PoolConfigSchema = z.object({
queueSize: z.number().int().min(1).max(1000).default(200),
/** Queue timeout in milliseconds (default: 30000ms = 30s) */
queueTimeoutMs: z.number().int().min(1000).max(300000).default(30000),
/** Per-server connect timeout in milliseconds (default: 15000ms = 15s) */
connectTimeoutMs: z.number().int().min(1000).max(120000).default(15000),
/** Per-server connect timeout in milliseconds (default: 20000ms = 20s) */
connectTimeoutMs: z.number().int().min(1000).max(120000).default(20000),
/** Max downstream servers connecting concurrently at startup (default: 6) */
startupConcurrency: z.number().int().min(1).max(64).default(6),
/** Serial connect retries for servers that missed the first window (default: 1) */
startupRetries: z.number().int().min(0).max(5).default(1),
});

export type PoolConfig = z.infer<typeof PoolConfigSchema>;
Expand Down
149 changes: 132 additions & 17 deletions src/mcp/client-pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,57 @@ import type { SchemaCache } from '../validation/schema-cache.js';
import { ConnectionQueue } from './connection-queue.js';
import type { MetricsExporter } from '../observability/metrics-exporter.js';

/** Result of a single downstream-server connect attempt (used by initialize()). */
interface ConnectOutcome {
serverName: string;
ok: boolean;
/** Wall-clock duration of the (last) attempt, ms. */
ms: number;
/** Failure message, present only when ok === false. */
error?: string;
/** True when the server connected on a retry rather than the first window. */
viaRetry?: boolean;
}

/**
* Run `worker` over `items` with at most `limit` in flight at once, preserving
* input order in the returned array. A bounded alternative to
* `Promise.all(items.map(worker))` for when unbounded fan-out would overload a
* shared resource β€” here, many cold-starting downstream MCP children spawning
* simultaneously and starving each other's connect handshake.
*
* Uses a fixed set of `limit` runners pulling from a shared cursor (sliding
* window), so a fast item never waits behind a slow one in the same batch. The
* cursor read+increment is synchronous (single-threaded event loop), so no lock
* is needed. `worker` is expected not to throw β€” callers wrap per-item errors
* into a result object; a throw rejects the whole run, matching Promise.all.
*/
export async function mapWithConcurrency<T, R>(
items: readonly T[],
limit: number,
worker: (item: T, index: number) => Promise<R>
): Promise<R[]> {
const results = new Array<R>(items.length);
let next = 0;
// Defensive: a non-finite or <1 limit must never yield 0 workers, which would
// leave `results` holes (undefined) and silently drop items. Fall back to
// serial (1) so every item is still processed.
const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.floor(limit) : 1;
const workerCount = Math.min(safeLimit, items.length);
const runners: Promise<void>[] = [];
for (let w = 0; w < workerCount; w++) {
runners.push(
(async () => {
for (let current = next++; current < items.length; current = next++) {
results[current] = await worker(items[current]!, current);
}
})()
);
}
await Promise.all(runners);
return results;
}

/**
* MCP Client Pool Configuration (US4: FR-4)
*
Expand All @@ -47,8 +98,12 @@ export interface MCPClientPoolConfig {
queueSize?: number;
/** Queue timeout in milliseconds (default: 30000ms = 30s) */
queueTimeoutMs?: number;
/** Per-server connect timeout in milliseconds (default: 15000ms = 15s) */
/** Per-server connect timeout in milliseconds (default: 20000ms = 20s) */
connectTimeoutMs?: number;
/** Max downstream servers connecting concurrently at startup (default: 6) */
startupConcurrency?: number;
/** Serial connect retries for servers that missed the first window (default: 1) */
startupRetries?: number;
}

/**
Expand All @@ -73,6 +128,15 @@ export class MCPClientPool implements IToolSchemaProvider {
// trigger a supervisor restart loop). See connectStdio/connectHttp.
private connectTimeoutMs: number;

// Startup fan-out control. connectToServer() for all configured servers used to
// run under one unbounded Promise.all β€” every cold-starting `uvx`/`npx` child
// spawning at once contends for CPU/IO (a "thundering herd") and pushes the
// slowest server over connectTimeoutMs. startupConcurrency bounds how many
// connect at once; startupRetries re-attempts the ones that missed the first
// window, serially, after the herd has cleared. See initialize().
private startupConcurrency: number;
private startupRetries: number;

// STDIO transports that have spawned a child process but whose connect() has
// not yet resolved. Tracked here so a child can still be reaped if the whole
// pool is torn down (or the process exits) before connect() completes β€”
Expand Down Expand Up @@ -116,6 +180,10 @@ export class MCPClientPool implements IToolSchemaProvider {
// Per-server connect timeout (Priority: explicit config > env-validated default)
this.connectTimeoutMs = config?.connectTimeoutMs ?? poolConfig.connectTimeoutMs;

// Startup fan-out control (Priority: explicit config > env-validated default)
this.startupConcurrency = config?.startupConcurrency ?? poolConfig.startupConcurrency;
this.startupRetries = config?.startupRetries ?? poolConfig.startupRetries;

// T053: Initialize connection queue
this.connectionQueue = new ConnectionQueue({
maxSize: config?.queueSize ?? poolConfig.queueSize,
Expand Down Expand Up @@ -344,24 +412,71 @@ export class MCPClientPool implements IToolSchemaProvider {
// server can never block the others β€” failures degrade gracefully and the
// pool comes up with whatever connected. A failed server is NEVER added to
// `clients`/`toolCache`, so its tools are not discoverable or callable.
//
// Fan-out is bounded (startupConcurrency) instead of one unbounded
// Promise.all: connecting every server at once makes cold-starting
// `uvx`/`npx` children contend for CPU/IO and pushes the slowest (e.g.
// basic-memory) past connectTimeoutMs. Servers that still miss the window
// are retried serially (startupRetries) once the herd has cleared.
const serverNames = filteredServers.map(([name]) => name);
const outcomes = await Promise.all(
filteredServers.map(async ([serverName, serverConfig]) => {
const startedAt = Date.now();
try {
await this.connectToServer(serverName, serverConfig);
return { serverName, ok: true as const, ms: Date.now() - startedAt };
} catch (error) {
return {
serverName,
ok: false as const,
ms: Date.now() - startedAt,
error: error instanceof Error ? error.message : String(error),
};
}
})
const configByName = new Map<string, MCPServerConfig>(filteredServers);

const connectOne = async (
serverName: string,
serverConfig: MCPServerConfig
): Promise<ConnectOutcome> => {
const startedAt = Date.now();
try {
await this.connectToServer(serverName, serverConfig);
return { serverName, ok: true, ms: Date.now() - startedAt };
} catch (error) {
return {
serverName,
ok: false,
ms: Date.now() - startedAt,
error: error instanceof Error ? error.message : String(error),
};
}
};

// First window: bounded-concurrency connect across all servers.
const outcomeByName = new Map<string, ConnectOutcome>();
const firstRound = await mapWithConcurrency(
filteredServers,
this.startupConcurrency,
([serverName, serverConfig]) => connectOne(serverName, serverConfig)
);
for (const outcome of firstRound) {
outcomeByName.set(outcome.serverName, outcome);
}

// Serial retry for servers that missed the first window. With the herd
// gone, a slow server usually connects immediately on the retry instead of
// being dropped for the whole process lifetime (there is no lazy reconnect).
for (let attempt = 1; attempt <= this.startupRetries; attempt++) {
const stillFailed = [...outcomeByName.values()].filter(o => !o.ok);
if (stillFailed.length === 0) {
break;
}
console.error(
`πŸ” Retry ${attempt}/${this.startupRetries} for ${stillFailed.length} server(s) that missed the startup window: ${stillFailed.map(o => o.serverName).join(', ')}`
);
for (const failed of stillFailed) {
const serverConfig = configByName.get(failed.serverName);
if (!serverConfig) {
continue;
}
const retried = await connectOne(failed.serverName, serverConfig);
if (retried.ok) {
retried.viaRetry = true;
}
outcomeByName.set(failed.serverName, retried);
}
}

// Report in original config order (Map preserves insertion order, but be
// explicit so a future config-merge change can't reorder the report).
const outcomes = serverNames.map(name => outcomeByName.get(name)!);
const failures = outcomes.filter(o => !o.ok);
const successes = outcomes.length - failures.length;

Expand All @@ -374,7 +489,7 @@ export class MCPClientPool implements IToolSchemaProvider {
console.error(`πŸ“‹ MCP server startup report (${successes}/${serverNames.length} connected):`);
for (const o of outcomes) {
if (o.ok) {
console.error(` βœ“ ${o.serverName} (${o.ms}ms)`);
console.error(` βœ“ ${o.serverName} (${o.ms}ms)${o.viaRetry ? ' [via retry]' : ''}`);
} else {
console.error(` βœ— ${o.serverName} (${o.ms}ms): ${o.error}`);
}
Expand Down
3 changes: 3 additions & 0 deletions tests/exclude-servers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ describe('excludeServers', () => {
maxConcurrent: 100,
queueSize: 200,
queueTimeoutMs: 30000,
connectTimeoutMs: 20000,
startupConcurrency: 6,
startupRetries: 1,
});

pool = new MCPClientPool();
Expand Down
110 changes: 110 additions & 0 deletions tests/map-with-concurrency.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* Unit tests for mapWithConcurrency β€” the bounded startup fan-out helper.
*
* This replaces the unbounded `Promise.all(servers.map(connect))` in the MCP
* client pool: connecting every downstream server at once made cold-starting
* children contend and pushed the slowest past its connect timeout. The helper
* must (a) process every item, (b) preserve input order in the result, and
* (c) never run more than `limit` workers at once.
*/

import { describe, it, expect } from 'vitest';
import { mapWithConcurrency } from '../src/mcp/client-pool.js';

/** Resolve after `ms` via a microtask chain (no real timers β†’ fast, deterministic). */
function tick(rounds: number): Promise<void> {
let p = Promise.resolve();
for (let i = 0; i < rounds; i++) {
p = p.then(() => undefined);
}
return p;
}

describe('mapWithConcurrency', () => {
it('preserves input order in the result regardless of completion order', async () => {
const items = [0, 1, 2, 3, 4, 5];

// Later items resolve sooner (more items complete first) β€” result must
// still be in input order, not completion order.
const result = await mapWithConcurrency(items, 3, async (n) => {
await tick(items.length - n);
return n * 10;
});

expect(result).toEqual([0, 10, 20, 30, 40, 50]);
});

it('processes every item exactly once', async () => {
const items = Array.from({ length: 25 }, (_, i) => i);
const seen: number[] = [];

const result = await mapWithConcurrency(items, 4, async (n) => {
seen.push(n);
return n;
});

expect(result).toEqual(items);
expect([...seen].sort((a, b) => a - b)).toEqual(items);
expect(seen.length).toBe(items.length);
});

it('never exceeds the concurrency limit', async () => {
const items = Array.from({ length: 20 }, (_, i) => i);
let inFlight = 0;
let maxInFlight = 0;

await mapWithConcurrency(items, 5, async () => {
inFlight++;
maxInFlight = Math.max(maxInFlight, inFlight);
await tick(3);
inFlight--;
});

expect(maxInFlight).toBeLessThanOrEqual(5);
// Sanity: with 20 items and limit 5, the window should actually fill.
expect(maxInFlight).toBe(5);
});

it('passes the correct index to the worker', async () => {
const items = ['a', 'b', 'c'];

const result = await mapWithConcurrency(items, 2, async (item, index) => `${index}:${item}`);

expect(result).toEqual(['0:a', '1:b', '2:c']);
});

it('returns an empty array for empty input (no workers spawned)', async () => {
let called = false;
const result = await mapWithConcurrency([], 4, async () => {
called = true;
return 1;
});

expect(result).toEqual([]);
expect(called).toBe(false);
});

it('handles limit larger than item count', async () => {
const items = [1, 2, 3];
const result = await mapWithConcurrency(items, 100, async (n) => n * 2);

expect(result).toEqual([2, 4, 6]);
});

it('treats limit < 1 as a single serial worker', async () => {
const items = [1, 2, 3, 4];
let inFlight = 0;
let maxInFlight = 0;

const result = await mapWithConcurrency(items, 0, async (n) => {
inFlight++;
maxInFlight = Math.max(maxInFlight, inFlight);
await tick(2);
inFlight--;
return n;
});

expect(result).toEqual(items);
expect(maxInFlight).toBe(1);
});
});
Loading
Loading