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
Binary file added docs/images/agent-presence-after.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/agent-presence-before.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 5 additions & 4 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ locally — so Electroscope also watches the server-to-client event stream: when
not come back within ten seconds, the agent is dropped. A reconnect inside that window keeps the
session, and so does any other request.

An agent that uses neither — no `DELETE`, no event stream — cannot be detected leaving. It keeps
its session until it has been idle for 30 minutes, and the window stops counting it as watching
after 90 seconds of silence: it is listed as idle, with when it was last heard from, rather than
as a second pair of eyes on the board.
Each session request renews the agent's place in the window. After 90 seconds of silence, the
window shows the agent as idle. After three minutes, it removes the agent from the list and the
`/health` client count, even if an event stream is still open. A client that wants to remain
visible while waiting can send an MCP `ping` once a minute. A later request restores the entry
using the same session ID until the server cleans up the session after 30 minutes of inactivity.

## Coordinates

Expand Down
39 changes: 28 additions & 11 deletions src/main/mcp/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ export interface McpHttpOptions {
/** Called once per agent session; the ClientInfo is live and gains its id once the session starts. */
createServer: (client: ClientInfo) => McpServer;
onClientsChanged?: (clients: ClientInfo[]) => void;
/** How long the roster lists a client after its last request. */
presenceLeaseMs?: number;
/** Sessions idle for longer than this are dropped. */
sessionTtlMs?: number;
/** How long a session may keep its place after its event stream drops, to allow a reconnect. */
Expand All @@ -28,6 +30,7 @@ interface Session {
transport: StreamableHTTPServerTransport;
server: McpServer;
info: ClientInfo;
presence?: NodeJS.Timeout;
/** Set while the agent's event stream is gone and we are waiting to see if it comes back. */
gone?: NodeJS.Timeout;
}
Expand Down Expand Up @@ -102,14 +105,17 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise<McpHttp> {
const own = osHostname().toLowerCase();
const names = new Set([own, `${own}.local`, ...(opts.names ?? []).map((n) => n.toLowerCase())]);
const ttl = opts.sessionTtlMs ?? 30 * 60_000;
const lease = opts.presenceLeaseMs ?? 3 * 60_000;
const grace = opts.streamGraceMs ?? 10_000;
const sessions = new Map<string, Session>();

const emit = () => opts.onClientsChanged?.([...sessions.values()].map((s) => s.info));
const clients = () => [...sessions.values()].filter((s) => s.presence).map((s) => s.info);
const emit = () => opts.onClientsChanged?.(clients());

const drop = (id: string) => {
const s = sessions.get(id);
if (!s) return;
clearTimeout(s.presence);
clearTimeout(s.gone);
sessions.delete(id);
void s.server.close().catch(() => undefined);
Expand All @@ -121,6 +127,16 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise<McpHttp> {
session.info.lastSeen = new Date().toISOString();
clearTimeout(session.gone);
session.gone = undefined;
if (session.presence) {
session.presence.refresh();
return;
}
session.presence = setTimeout(() => {
session.presence = undefined;
emit();
}, lease);
session.presence.unref();
emit();
};

/**
Expand Down Expand Up @@ -156,7 +172,7 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise<McpHttp> {
const url = new URL(req.url ?? '/', 'http://electroscope');

if (url.pathname === '/health') {
return sendJson(res, 200, { name: 'electroscope', version: opts.version, ok: true, clients: sessions.size });
return sendJson(res, 200, { name: 'electroscope', version: opts.version, ok: true, clients: clients().length });
}
if (url.pathname !== '/mcp') {
return sendJson(res, 404, { error: 'Not found. The MCP endpoint is /mcp' });
Expand All @@ -172,7 +188,7 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise<McpHttp> {
} catch (e) {
return rpcError(res, 400, -32700, (e as Error).message);
}
let session = sid ? sessions.get(sid) : undefined;
const session = sid ? sessions.get(sid) : undefined;
if (!session) {
if (sid || !isInitializeRequest(body)) {
return rpcError(res, sid ? 404 : 400, -32000, sid ? 'Unknown session' : 'No session: send initialize first');
Expand All @@ -191,18 +207,17 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise<McpHttp> {
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (id) => {
info.id = id;
sessions.set(id, { transport, server, info });
emit();
const initialized = { transport, server, info };
sessions.set(id, initialized);
seen(initialized);
},
});
transport.onclose = () => {
if (info.id) drop(info.id);
};
await server.connect(transport);
session = { transport, server, info };
try {
seen(session);
await session.transport.handleRequest(req, res, body);
await transport.handleRequest(req, res, body);
} catch (e) {
// The session id is only assigned once initialize succeeds; without it `drop` cannot
// find this server later, so close it here rather than leak it for the app's lifetime.
Expand All @@ -220,8 +235,10 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise<McpHttp> {
if (req.method === 'GET' || req.method === 'DELETE') {
const session = sid ? sessions.get(sid) : undefined;
if (!session) return rpcError(res, sid ? 404 : 400, -32000, 'Unknown or missing session');
seen(session);
if (req.method === 'GET') watchEventStream(session, res);
if (req.method === 'GET') {
seen(session);
watchEventStream(session, res);
}
await session.transport.handleRequest(req, res);
if (req.method === 'DELETE' && sid) drop(sid);
return;
Expand Down Expand Up @@ -249,7 +266,7 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise<McpHttp> {
return {
port,
url: `http://127.0.0.1:${port}/mcp`,
clients: () => [...sessions.values()].map((s) => s.info),
clients,
close: async () => {
clearInterval(sweeper);
for (const id of [...sessions.keys()]) drop(id);
Expand Down
42 changes: 39 additions & 3 deletions test/mcp-sessions.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, expect, it } from 'vitest';
import { afterEach, expect, it } from 'vitest';
import { request, type ClientRequest, type IncomingMessage } from 'node:http';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
Expand All @@ -10,17 +10,18 @@ const GRACE = 150;
let http: McpHttp;
let announced: string[][] = [];

beforeEach(async () => {
async function start(presenceLeaseMs?: number) {
announced = [];
http = await startMcpHttp({
port: 0,
host: '127.0.0.1',
version: 'test',
streamGraceMs: GRACE,
presenceLeaseMs,
createServer: () => new McpServer({ name: 'electroscope', version: 'test' }),
onClientsChanged: (list) => announced.push(list.map((c) => c.name)),
});
});
}

afterEach(async () => {
await http.close();
Expand Down Expand Up @@ -90,6 +91,7 @@ async function openStream(sid: string): Promise<{ req: ClientRequest; res: Incom
}

it('forgets an agent that walks away without saying so', async () => {
await start();
// The SDK's client closes its transport locally and never sends a DELETE, which is exactly
// the case that used to leave a ghost in the window for half an hour.
const client = new Client({ name: 'quiet-leaver', version: '1.0.0' });
Expand All @@ -107,6 +109,7 @@ it('forgets an agent that walks away without saying so', async () => {
});

it('keeps an agent that loses its stream and comes straight back', async () => {
await start();
const sid = await initialize();
const first = await openStream(sid);
expect(names()).toEqual(['raw-agent']);
Expand All @@ -121,13 +124,15 @@ it('keeps an agent that loses its stream and comes straight back', async () => {
});

it('keeps an agent that never opens a stream at all', async () => {
await start();
// A POST-only client is legitimate; nothing about it says it has gone.
await initialize();
await sleep(GRACE * 3);
expect(names()).toEqual(['raw-agent']);
});

it('does not evict an agent when a second stream is refused', async () => {
await start();
const sid = await initialize();
const real = await openStream(sid);
const refused = await openStream(sid);
Expand All @@ -139,6 +144,7 @@ it('does not evict an agent when a second stream is refused', async () => {
});

it('still removes an agent that says goodbye properly', async () => {
await start();
const sid = await initialize();
await openStream(sid);
const status = await new Promise<number>((resolve, reject) => {
Expand All @@ -155,3 +161,33 @@ it('still removes an agent that says goodbye properly', async () => {
expect(status).toBeLessThan(300);
expect(names()).toEqual([]);
});

it.each(['POST only', 'open stream'])('expires and renews presence with %s', async (mode) => {
const lease = 1200;
await start(lease);
const sid = await initialize();
if (mode === 'open stream') await openStream(sid);
const health = async () => (await fetch(new URL('/health', http.url))).json();
const ping = () => fetch(http.url, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
'mcp-session-id': sid,
},
body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' }),
});

await sleep(lease * 0.6);
expect((await ping()).status).toBe(200);
await sleep(lease * 0.6);
expect(names()).toEqual(['raw-agent']);
await until(() => names().length === 0);
expect(names()).toEqual([]);
expect(announced.at(-1)).toEqual([]);
expect(await health()).toMatchObject({ clients: 0 });

expect((await ping()).status).toBe(200);
expect(announced.at(-1)).toEqual(['raw-agent']);
expect(await health()).toMatchObject({ clients: 1 });
});
Loading