diff --git a/docs/images/agent-presence-after.png b/docs/images/agent-presence-after.png new file mode 100644 index 0000000..c27e412 Binary files /dev/null and b/docs/images/agent-presence-after.png differ diff --git a/docs/images/agent-presence-before.png b/docs/images/agent-presence-before.png new file mode 100644 index 0000000..ae866a7 Binary files /dev/null and b/docs/images/agent-presence-before.png differ diff --git a/docs/mcp.md b/docs/mcp.md index 02995ff..ab6c47b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 diff --git a/src/main/mcp/http.ts b/src/main/mcp/http.ts index 56c205b..ac6321d 100644 --- a/src/main/mcp/http.ts +++ b/src/main/mcp/http.ts @@ -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. */ @@ -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; } @@ -102,14 +105,17 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise { 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(); - 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); @@ -121,6 +127,16 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise { 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(); }; /** @@ -156,7 +172,7 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise { 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' }); @@ -172,7 +188,7 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise { } 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'); @@ -191,18 +207,17 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise { 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. @@ -220,8 +235,10 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise { 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; @@ -249,7 +266,7 @@ export async function startMcpHttp(opts: McpHttpOptions): Promise { 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); diff --git a/test/mcp-sessions.test.ts b/test/mcp-sessions.test.ts index 2f943d6..dec4546 100644 --- a/test/mcp-sessions.test.ts +++ b/test/mcp-sessions.test.ts @@ -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'; @@ -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(); @@ -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' }); @@ -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']); @@ -121,6 +124,7 @@ 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); @@ -128,6 +132,7 @@ it('keeps an agent that never opens a stream at all', async () => { }); 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); @@ -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((resolve, reject) => { @@ -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 }); +});