@adonis-agora/agent
Version:
Governed, durable-backed AI agent (chat + tool-calling + governance) for AdonisJS — part of the Agora ecosystem.
134 lines • 5.11 kB
JavaScript
export const DEFAULT_MCP_SESSION_LIMITS = {
max: 1000,
maxPerPrincipal: 16,
idleTimeoutMs: 30 * 60_000,
};
/** Validates and fills {@link McpSessionLimits}; throws naming the bad field. */
export function resolveMcpSessionLimits(limits) {
const resolved = { ...DEFAULT_MCP_SESSION_LIMITS, ...(limits ?? {}) };
for (const key of ['max', 'maxPerPrincipal', 'idleTimeoutMs']) {
const value = resolved[key];
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
throw new Error(`[-agora/agent] config/mcp.ts: \`sessions.${key}\` must be a positive number`);
}
}
if (resolved.maxPerPrincipal > resolved.max) {
throw new Error('[@adonis-agora/agent] config/mcp.ts: `sessions.maxPerPrincipal` cannot exceed `sessions.max`');
}
return resolved;
}
/**
* Who a session belongs to: the token's client and the actor it resolved. A session id is a bearer
* capability on its own, so every later request on it must come from the same principal.
*/
export function mcpPrincipalOf(auth) {
return JSON.stringify([auth.clientId ?? '', auth.extra.actor.id]);
}
/**
* The live sessions of one MCP endpoint: bound to the principal that opened them, capped per
* principal and overall, and closed after `idleTimeoutMs` without use. In memory, per process.
*/
export class McpSessionPool {
limits;
#entries = new Map();
#now;
#sweeper;
constructor(limits, options = {}) {
this.limits = resolveMcpSessionLimits(limits);
this.#now = options.now ?? Date.now;
}
get size() {
return this.#entries.size;
}
/** Sessions held by `principal`. */
countOf(principal) {
let count = 0;
for (const entry of this.#entries.values())
if (entry.principal === principal)
count += 1;
return count;
}
/**
* The session's transport, for its own principal only (and marked used). `other-principal` when
* the id is live but was opened by someone else.
*/
get(sessionId, principal) {
const entry = this.#entries.get(sessionId);
if (entry === undefined)
return 'unknown';
if (this.#expired(entry)) {
this.#evict(sessionId, entry);
return 'unknown';
}
if (entry.principal !== principal)
return 'other-principal';
entry.lastSeen = this.#now();
return entry.transport;
}
/**
* Make room for a new session of `principal` and register it under `sessionId`: idle sessions go
* first, then the principal's least recently used one when it is at its cap. `full` when every
* slot of the endpoint is held by live sessions.
*/
open(sessionId, principal, transport) {
this.sweep();
while (this.countOf(principal) >= this.limits.maxPerPrincipal) {
const oldest = this.#oldestOf(principal);
if (oldest === undefined)
break;
this.#evict(oldest[0], oldest[1]);
}
if (this.#entries.size >= this.limits.max)
return 'full';
this.#entries.set(sessionId, { transport, principal, lastSeen: this.#now() });
return true;
}
/** Forget `sessionId` (when it still holds `transport`): the transport closed. */
delete(sessionId, transport) {
const entry = this.#entries.get(sessionId);
if (entry !== undefined && (transport === undefined || entry.transport === transport)) {
this.#entries.delete(sessionId);
}
}
/** Close every session idle past `idleTimeoutMs`. */
sweep() {
for (const [id, entry] of this.#entries)
if (this.#expired(entry))
this.#evict(id, entry);
}
/** Sweep on a timer (unref'd: it never keeps the process alive). */
startSweeping() {
if (this.#sweeper !== undefined)
return;
const every = Math.max(1_000, Math.min(this.limits.idleTimeoutMs, 60_000));
this.#sweeper = setInterval(() => this.sweep(), every);
this.#sweeper.unref?.();
}
/** Stop the timer and close every session. */
async closeAll() {
if (this.#sweeper !== undefined)
clearInterval(this.#sweeper);
this.#sweeper = undefined;
const entries = [...this.#entries.values()];
this.#entries.clear();
await Promise.all(entries.map((entry) => entry.transport.close().catch(() => undefined)));
}
#expired(entry) {
return this.#now() - entry.lastSeen >= this.limits.idleTimeoutMs;
}
#oldestOf(principal) {
let oldest;
for (const pair of this.#entries) {
if (pair[1].principal !== principal)
continue;
if (oldest === undefined || pair[1].lastSeen < oldest[1].lastSeen)
oldest = pair;
}
return oldest;
}
#evict(id, entry) {
this.#entries.delete(id);
void entry.transport.close().catch(() => undefined);
}
}
//# sourceMappingURL=session-pool.js.map