From a08b92f6937a6d6d939324c51ddd276db75f7b41 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 06:47:30 -0800 Subject: [PATCH 1/9] fix(mcp): return filtered summaries and synced sessions --- CHANGELOG.md | 1 + docs/session-summaries.md | 10 +++++---- src/mcp/relay-participants.ts | 34 ++++++++++++++++++++++++++++-- src/mcp/session-summaries.ts | 8 ++++++- test/mcp-session-summaries.test.ts | 9 +++++++- test/mcp.test.ts | 31 +++++++++++++++++++++++++++ 6 files changed, 85 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3560bc1..977ebc2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ assigned at release. ## Unreleased +- Fixed: MCP repository-filtered session summaries apply a repo-only filter in the session directory before pagination, while still verifying the returned repository URL. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. No migration. - Fixed: the analytics collector accepts the sessions read API route `/v1/sessions/users`. The reader has reported it since that route shipped, and the collector refused any batch that contained it. It also accepts the patterns `/v1/coordination/advisories` and `/v1/coordination/advisories/:advisoryId/ack`, so the reader can start naming them without a refused batch. No setting or migration; analytics stays off unless configured. - Added: `SELFHOST_DEFAULT_SHARING_MODE` (`all` | `new` | `selected`) sets a deployment sharing mode served to callers whose organization has not saved one, and `SELFHOST_SHARING_MODE_OVERRIDE_ROLES` (`owner` and/or `admin`) leaves callers with those roles unlocked: their v1 policy omits `sharing_mode` and `sharing_mode_since`, and the v2 document serves the effective mode as `sections.capture.defaults.sharing_mode`. The organization-saved mode always wins. Applied per caller on `access/me`, the enrollment key exchange, introspection `capture_policy` (staff read grants as a member) and the upload-credentials revision check. Nothing is stored, no revision moves, and the organization policy routes and fleet view still show only what is stored. Both unset (the default), every response is unchanged. See docs/capture-policy.md. - Added: `relayfacts_list` and `relayfacts_get` on the Agent Relay MCP. They read the sessions pipeline read API's `GET /v1/relayfacts` (topics with counts) and `GET /v1/relayfacts/{topic}` (one page of a topic as markdown, `page` passed back as its cursor) through the same reader as the shared-session tools: `workspace` is always the credential's workspace, and a response without the workspace attestation returns nothing. They store and write nothing. Until the read API serves relayfacts (`READ_API_RELAYFACTS_ENABLED` off), every 501 is a successful `status: "disabled"` result ("relayfacts disabled") with the upstream reason. OAuth connections need `relay:history`; staff read grants do not get them. The per-user session reader now passes relayfacts cursors through unchanged and reports a 501's upstream reason. diff --git a/docs/session-summaries.md b/docs/session-summaries.md index a2546da3..87304c4a 100644 --- a/docs/session-summaries.md +++ b/docs/session-summaries.md @@ -12,12 +12,14 @@ that an agent is currently running; use the existing presence tools for that. reads one `GET /v1/sessions?includeShortSummary=recorded` page. `limit` defaults to 20 and cannot exceed 50. `since` is an ISO timestamp mapped to `lastTsAfter`; `project` maps to the -directory's `projectContains` substring filter. `person` resolves an exact +directory's `projectContains` substring filter. A repo-only filter also uses +`projectContains`, whose directory semantics include the recorded repository, +so matching happens before pagination; the returned rows are still checked +against the repository URL to exclude project-id or catalog-key matches. `person` resolves an exact workspace member ID, email or unambiguous name and sends that recorded user ID as `user`. Unknown and ambiguous members are refused rather than -broadening the request. `repo` filters the recorded repository URL within -the page, case-insensitively; an empty filtered page may have `next_cursor`. -Keep filters unchanged when following that cursor. +broadening the request. `repo` matches the recorded repository URL +case-insensitively. Keep filters unchanged when following `next_cursor`. Each result has `session_id`, `source`, `owner` (an array, since sessions may have several recorded owners), `project`, `repo`, `branch`, `last_active`, diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 47179994..049f358f 100644 --- a/src/mcp/relay-participants.ts +++ b/src/mcp/relay-participants.ts @@ -670,9 +670,39 @@ function createRelayService(context: McpContext) { return (await dir.via.listAgents(dir.credential, status, { includeStale })).filter(isListedRelayAgent); } + const syncedSessionKinds = new Set(["codex", "grok", "pi", "opencode", "claude", "copilot", "cursor"]); + const syncedSessionId = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/; + async function syncedDesktopSessions(agents: readonly RosterAgent[]) { + const ids = [...new Set(agents.map(agent => agent.id))]; + if (!ids.length) return new Map(); + const rows = await executor.query<{ agent_remote_id: string; native_session_kind: string; native_session_id: string }>( + `SELECT agent_remote_id, native_session_kind, native_session_id + FROM desktop_relay_identities + WHERE workspace_id = $1 AND agent_remote_id = ANY($2::text[]) + AND native_session_kind IS NOT NULL AND native_session_id IS NOT NULL`, + [workspaceId, ids], + ); + const sessions = new Map(); + for (const row of rows.rows) { + const kind = row.native_session_kind.trim(); + if (syncedSessionKinds.has(kind) && syncedSessionId.test(row.native_session_id)) { + sessions.set(row.agent_remote_id, { sessionId: row.native_session_id, sessionKind: kind }); + } + } + return sessions; + } + async function roster(status: "live" | "all" | "offline", people: readonly McpMember[], includeStale = false, dir: Directory = directory()) { - return (await listedAgents(status === "live" ? "active" : "all", includeStale, dir)) - .map(agent => ({ ...rosterAgent(agent, people, userId, workspaceId), ...cardSummary(agent.metadata) })) + const agents = await listedAgents(status === "live" ? "active" : "all", includeStale, dir); + const synced = await syncedDesktopSessions(agents); + return agents + .map(agent => { + const listed = rosterAgent(agent, people, userId, workspaceId); + const session = listed.session_attribution ? null : synced.get(agent.id); + return { ...listed, + ...(session ? { session_id: session.sessionId, session_kind: session.sessionKind, session_attribution: "synced" as const } : {}), + ...cardSummary(agent.metadata) }; + }) .filter(agent => status === "all" || (status === "live" ? agent.online : !agent.online)); } diff --git a/src/mcp/session-summaries.ts b/src/mcp/session-summaries.ts index a628c882..e07f42ba 100644 --- a/src/mcp/session-summaries.ts +++ b/src/mcp/session-summaries.ts @@ -44,7 +44,7 @@ export function registerSessionSummaries(server: McpServer, context: McpContext) inputSchema: { since: timestamp.optional().describe("Select sessions last active after this ISO timestamp."), project: z.string().trim().min(1).max(200).optional().describe("Project substring filter applied by the session directory."), - repo: z.string().trim().min(1).max(512).optional().describe("Case-insensitive substring of the recorded repository URL, filtered within each directory page. Empty pages may have next_cursor; continue pagination."), + repo: z.string().trim().min(1).max(200).optional().describe("Case-insensitive substring of the recorded repository URL. The session directory applies the filter before pagination."), person: id.optional().describe("Exact workspace member ID, name or email; ambiguous names are refused."), limit: z.number().int().min(1).max(50).default(20), cursor: cursor.optional().describe("Opaque next_cursor from the preceding call; keep the same filters."), @@ -60,7 +60,13 @@ export function registerSessionSummaries(server: McpServer, context: McpContext) const names = new Map(members.map(member => [member.userId, member.name ?? member.email])); const params = new URLSearchParams({ limit: String(input.limit), includeShortSummary: "recorded" }); if (input.since) params.set("lastTsAfter", input.since); + // projectContains also searches the recorded repository URL. Push a + // repo-only filter into the directory so the limit counts matching + // sessions, then retain the exact URL check below because the directory + // filter also searches project ids and catalog keys. If both filters are + // present, preserve the existing directory-level project constraint. if (input.project) params.set("projectContains", input.project); + else if (input.repo) params.set("projectContains", input.repo); if (input.cursor) params.set("cursor", input.cursor); if (input.person) { const value = input.person.toLowerCase(); diff --git a/test/mcp-session-summaries.test.ts b/test/mcp-session-summaries.test.ts index b4692694..f7320fa4 100644 --- a/test/mcp-session-summaries.test.ts +++ b/test/mcp-session-summaries.test.ts @@ -74,13 +74,20 @@ test("list never substitutes a task title for an absent recorded summary", async assert.equal(legacy.paths.length, 1, "missing summary fields never trigger a fallback or detail scan"); }); -test("repo filtering preserves pagination, including an empty filtered page", async t => { +test("repo filtering is applied by the directory before pagination and verified against the URL", async t => { const f = await fixture(t); const value = data(await call(f.client, "list_session_summaries", { repo: "unmatched" })); assert.deepEqual(value.sessions, []); assert.equal(value.next_cursor, "b96l1:opaque-page"); assert.equal(f.paths.length, 1); + assert.equal(new URL(f.paths[0]!, "https://reader.test").searchParams.get("projectContains"), "unmatched"); assert.equal(data(await call(f.client, "list_session_summaries", { repo: "ORG/REPO" })).sessions.length, 1); }); +test("combined project and repo filters preserve the directory project constraint", async t => { + const f = await fixture(t); + assert.equal(data(await call(f.client, "list_session_summaries", { project: "fake", repo: "org/repo" })).sessions.length, 1); + assert.equal(new URL(f.paths[0]!, "https://reader.test").searchParams.get("projectContains"), "fake"); +}); + test("recorded list summaries use the reader bound of 1000 Unicode code points", async t => { for (const count of [1000, 1001]) { const f = await fixture(t, { body: { sessions: [{ ...row(), shortSummary: "😀".repeat(count) }], nextCursor: null } }); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 2f8b1b75..03f9bae6 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -732,6 +732,37 @@ test("get_relay_agent_card returns a minimal card for an agent without one, and assert.equal(env.relay.world.bodies.some(call => call.method === "PATCH"), false); }); +test("list_relay_agents links synced Desktop sessions and keeps validated declarations authoritative", async (t) => { + const env = await setup(t); + const synced = env.relay.world.addAgent("synced-session", { source: "relay-desktop", owner_hash: sha256(env.ownerId) }); + const declared = env.relay.world.addAgent("declared-session", { + source: "relay-desktop", owner_hash: sha256(env.ownerId), injectable: "true", + session_id: "declared-session-id", session_kind: "claude", + }); + const insert = (values: { id: string; sourceId: string; agentName: string; agentRemoteId: string; sessionKind: string; sessionId: string }) => + env.database.query( + `INSERT INTO desktop_relay_identities + (id, workspace_id, organization_id, user_id, relaycast_workspace_id, source_id, + agent_name, agent_remote_id, address, token_ciphertext, native_session_kind, native_session_id) + VALUES ($1, $2, $3, $4, 'rc-first', $5, $6, $7, $6 || '@fixture', 'encrypted', $8, $9)`, + [values.id, env.workspaceId, env.orgId, env.ownerId, values.sourceId, values.agentName, + values.agentRemoteId, values.sessionKind, values.sessionId], + ); + await insert({ id: "00000000-0000-4000-8000-000000000101", sourceId: "00000000-0000-4000-8000-000000000102", + agentName: synced.name, agentRemoteId: synced.id, sessionKind: "opencode", sessionId: "ses_ABCD1234" }); + await insert({ id: "00000000-0000-4000-8000-000000000103", sourceId: "00000000-0000-4000-8000-000000000104", + agentName: declared.name, agentRemoteId: declared.id, sessionKind: "codex", sessionId: "00000000-0000-4000-8000-000000000105" }); + + const client = await relayClient(t, env); + const agents = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })).agents; + const syncedRow = agents.find((agent: any) => agent.name === synced.name); + assert.deepEqual([syncedRow.session_id, syncedRow.session_kind, syncedRow.session_attribution], + ["ses_ABCD1234", "opencode", "synced"]); + const declaredRow = agents.find((agent: any) => agent.name === declared.name); + assert.deepEqual([declaredRow.session_id, declaredRow.session_kind, declaredRow.session_attribution], + ["declared-session-id", "claude", "declared"]); +}); + test("set_relay_agent_card writes only the joined participant's card and preserves its other metadata", async (t) => { const env = await setup(t); const client = await relayClient(t, env); From 9369233d334086f76cbd3a478a91d28960969d08 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 06:54:37 -0800 Subject: [PATCH 2/9] fix(mcp): match gated synced session ids --- src/mcp/relay-participants.ts | 19 ++++++++++++++----- test/gate-only-desktop-identities.test.ts | 8 ++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 049f358f..49f17160 100644 --- a/src/mcp/relay-participants.ts +++ b/src/mcp/relay-participants.ts @@ -672,11 +672,19 @@ function createRelayService(context: McpContext) { const syncedSessionKinds = new Set(["codex", "grok", "pi", "opencode", "claude", "copilot", "cursor"]); const syncedSessionId = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/; + const syncedIdentityId = (agent: RosterAgent) => { + if (!gate) return agent.id; + const metadata = agent.metadata.relaygate; + if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return agent.id; + const id = (metadata as Record).agent_id; + return typeof id === "string" && syncedSessionId.test(id) ? id : agent.id; + }; async function syncedDesktopSessions(agents: readonly RosterAgent[]) { - const ids = [...new Set(agents.map(agent => agent.id))]; + const candidates = new Map(agents.map(agent => [`${syncedIdentityId(agent)}\0${agent.name}`, agent])); + const ids = [...new Set(agents.map(syncedIdentityId))]; if (!ids.length) return new Map(); - const rows = await executor.query<{ agent_remote_id: string; native_session_kind: string; native_session_id: string }>( - `SELECT agent_remote_id, native_session_kind, native_session_id + const rows = await executor.query<{ agent_name: string; agent_remote_id: string; native_session_kind: string; native_session_id: string }>( + `SELECT agent_name, agent_remote_id, native_session_kind, native_session_id FROM desktop_relay_identities WHERE workspace_id = $1 AND agent_remote_id = ANY($2::text[]) AND native_session_kind IS NOT NULL AND native_session_id IS NOT NULL`, @@ -684,9 +692,10 @@ function createRelayService(context: McpContext) { ); const sessions = new Map(); for (const row of rows.rows) { + const agent = candidates.get(`${row.agent_remote_id}\0${row.agent_name}`); const kind = row.native_session_kind.trim(); - if (syncedSessionKinds.has(kind) && syncedSessionId.test(row.native_session_id)) { - sessions.set(row.agent_remote_id, { sessionId: row.native_session_id, sessionKind: kind }); + if (agent && syncedSessionKinds.has(kind) && syncedSessionId.test(row.native_session_id)) { + sessions.set(agent.id, { sessionId: row.native_session_id, sessionKind: kind }); } } return sessions; diff --git a/test/gate-only-desktop-identities.test.ts b/test/gate-only-desktop-identities.test.ts index 98c4a482..16c5ffc4 100644 --- a/test/gate-only-desktop-identities.test.ts +++ b/test/gate-only-desktop-identities.test.ts @@ -187,6 +187,14 @@ test("a signed Cursor call on a gate-only install sends, reads and reports statu tuid: randomUUID(), kind: "cursor", extra: { args } }) } }, }); + assert.notEqual(env.world.agents.get(chat.name)?.id, chat.agent_id, "the two agent-id namespaces differ"); + const listed = await rpc(env.origin, secret, await call("list_relay_agents", { status: "all" })); + assert.equal(listed.status, 200, JSON.stringify(listed.body)); + assert.notEqual(listed.body.result.isError, true, JSON.stringify(listed.body.result)); + const listedChat = listed.body.result.structuredContent.agents.find((agent: any) => agent.name === chat.name); + assert.deepEqual([listedChat.session_id, listedChat.session_kind, listedChat.session_attribution], + [chat.native_session.id, chat.native_session.kind, "synced"]); + const sent = await rpc(env.origin, secret, await call("send_relay_message", { to: "peer", text: "hello through the gate" })); assert.equal(sent.status, 200, JSON.stringify(sent.body)); assert.notEqual(sent.body.result.isError, true, JSON.stringify(sent.body.result)); From 3952b4a9c0232a830aa822299758a57dde6388db Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 07:16:20 -0800 Subject: [PATCH 3/9] fix(mcp): document and test repo pushdown --- CHANGELOG.md | 2 +- docs/session-summaries.md | 16 +++++++++++----- src/mcp/relay-participants.ts | 8 +++----- src/mcp/session-summaries.ts | 4 ++-- test/mcp-session-summaries.test.ts | 19 +++++++++++++++++-- 5 files changed, 34 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fb1e887..2ab4a748 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ assigned at release. ## Unreleased -- Fixed: MCP repository-filtered session summaries apply a repo-only filter in the session directory before pagination, while still verifying the returned repository URL. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. No migration. +- Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. The push-down requires the sessions read API P3b directory-list version (`feat(read-api): serve the session list and activity from the Supabase directory`, commit `92b907e3`, migration `20261105034000`) or later, whose `projectContains` is case-insensitive across project ID, catalog key and repository URL. Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. No migration. - Fixed: `list_session_timings` now sends `user_id` to RelayHistory and, when a filtered page comes back empty, reads up to five pages before answering, so a member's sessions are no longer hidden behind an empty page with a cursor. `sessions_scanned` counts every page read. - Fixed: the analytics collector accepts the sessions read API route `/v1/sessions/users`. The reader has reported it since that route shipped, and the collector refused any batch that contained it. It also accepts the patterns `/v1/coordination/advisories` and `/v1/coordination/advisories/:advisoryId/ack`, so the reader can start naming them without a refused batch. No setting or migration; analytics stays off unless configured. - Added: `SELFHOST_DEFAULT_SHARING_MODE` (`all` | `new` | `selected`) sets a deployment sharing mode served to callers whose organization has not saved one, and `SELFHOST_SHARING_MODE_OVERRIDE_ROLES` (`owner` and/or `admin`) leaves callers with those roles unlocked: their v1 policy omits `sharing_mode` and `sharing_mode_since`, and the v2 document serves the effective mode as `sections.capture.defaults.sharing_mode`. The organization-saved mode always wins. Applied per caller on `access/me`, the enrollment key exchange, introspection `capture_policy` (staff read grants as a member) and the upload-credentials revision check. Nothing is stored, no revision moves, and the organization policy routes and fleet view still show only what is stored. Both unset (the default), every response is unchanged. See docs/capture-policy.md. diff --git a/docs/session-summaries.md b/docs/session-summaries.md index 87304c4a..ff340b38 100644 --- a/docs/session-summaries.md +++ b/docs/session-summaries.md @@ -13,13 +13,19 @@ reads one `GET /v1/sessions?includeShortSummary=recorded` page. `limit` defaults to 20 and cannot exceed 50. `since` is an ISO timestamp mapped to `lastTsAfter`; `project` maps to the directory's `projectContains` substring filter. A repo-only filter also uses -`projectContains`, whose directory semantics include the recorded repository, -so matching happens before pagination; the returned rows are still checked -against the repository URL to exclude project-id or catalog-key matches. `person` resolves an exact +the first 200 characters as `projectContains`, whose directory semantics are a +case-insensitive literal substring of the project ID, catalog project key or +recorded repository URL, so matching happens before pagination; the returned +rows are still checked against the full repository URL to exclude project-id +or catalog-key matches. This requires the sessions read API P3b directory-list +version (`feat(read-api): serve the session list and activity from the Supabase +directory`, commit `92b907e3`, migration `20261105034000`) or later. `person` resolves an exact workspace member ID, email or unambiguous name and sends that recorded user ID as `user`. Unknown and ambiguous members are refused rather than -broadening the request. `repo` matches the recorded repository URL -case-insensitively. Keep filters unchanged when following `next_cursor`. +broadening the request. `repo` accepts up to 512 characters and matches the +recorded repository URL case-insensitively. Exact URL verification can make a +page short or empty while it still has `next_cursor`; keep paging with the same +filters. Each result has `session_id`, `source`, `owner` (an array, since sessions may have several recorded owners), `project`, `repo`, `branch`, `last_active`, diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 49f17160..06d5132b 100644 --- a/src/mcp/relay-participants.ts +++ b/src/mcp/relay-participants.ts @@ -6,7 +6,7 @@ import { RelaycastCallError, type RosterAgent } from "../messaging/relaycast.js" import { bindDesktopSession, DesktopIdentityUnavailable, DESKTOP_IDENTITY_MESSAGES, findDesktopIdentityByAddress, findDesktopIdentityByName, findDesktopIdentityBySession, linkedDesktopIdentity, unbindDesktopSession, verifyDesktopIdentity, - type DesktopIdentityRow, type LinkedDesktopIdentity, + relaygateAgentId, type DesktopIdentityRow, type LinkedDesktopIdentity, } from "../messaging/desktop-identities.js"; import type { McpContext, McpMember } from "./context.js"; import { isListedRelayAgent, rosterAgent } from "./team-activity.js"; @@ -674,10 +674,8 @@ function createRelayService(context: McpContext) { const syncedSessionId = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/; const syncedIdentityId = (agent: RosterAgent) => { if (!gate) return agent.id; - const metadata = agent.metadata.relaygate; - if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return agent.id; - const id = (metadata as Record).agent_id; - return typeof id === "string" && syncedSessionId.test(id) ? id : agent.id; + const id = relaygateAgentId(agent.metadata); + return id && syncedSessionId.test(id) ? id : agent.id; }; async function syncedDesktopSessions(agents: readonly RosterAgent[]) { const candidates = new Map(agents.map(agent => [`${syncedIdentityId(agent)}\0${agent.name}`, agent])); diff --git a/src/mcp/session-summaries.ts b/src/mcp/session-summaries.ts index e07f42ba..4b2731a1 100644 --- a/src/mcp/session-summaries.ts +++ b/src/mcp/session-summaries.ts @@ -44,7 +44,7 @@ export function registerSessionSummaries(server: McpServer, context: McpContext) inputSchema: { since: timestamp.optional().describe("Select sessions last active after this ISO timestamp."), project: z.string().trim().min(1).max(200).optional().describe("Project substring filter applied by the session directory."), - repo: z.string().trim().min(1).max(200).optional().describe("Case-insensitive substring of the recorded repository URL. The session directory applies the filter before pagination."), + repo: z.string().trim().min(1).max(512).optional().describe("Case-insensitive substring of the recorded repository URL. A repo-only prefix is applied before pagination, then the exact URL is checked. A page can be short or empty and still have next_cursor; keep paging with the same filters."), person: id.optional().describe("Exact workspace member ID, name or email; ambiguous names are refused."), limit: z.number().int().min(1).max(50).default(20), cursor: cursor.optional().describe("Opaque next_cursor from the preceding call; keep the same filters."), @@ -66,7 +66,7 @@ export function registerSessionSummaries(server: McpServer, context: McpContext) // filter also searches project ids and catalog keys. If both filters are // present, preserve the existing directory-level project constraint. if (input.project) params.set("projectContains", input.project); - else if (input.repo) params.set("projectContains", input.repo); + else if (input.repo) params.set("projectContains", input.repo.slice(0, 200)); if (input.cursor) params.set("cursor", input.cursor); if (input.person) { const value = input.person.toLowerCase(); diff --git a/test/mcp-session-summaries.test.ts b/test/mcp-session-summaries.test.ts index f7320fa4..9d049a49 100644 --- a/test/mcp-session-summaries.test.ts +++ b/test/mcp-session-summaries.test.ts @@ -18,7 +18,15 @@ async function fixture(t: TestContext, options: Setup = {}) { const paths: string[] = []; const context = { workspace: { id: "ws-a", organizationId: "org-a" }, origin: "https://relay.example.test", members: options.members ?? (async () => [{ userId: "user-a", name: "Example User", email: "fake@example.test" }]), - readHistory: async (path: string) => { paths.push(path); if (options.readError) throw options.readError; return options.body ?? page(); }, + readHistory: async (path: string) => { + paths.push(path); + if (options.readError) throw options.readError; + if (options.body !== undefined) return options.body; + const result = page(); + const needle = new URL(path, "https://reader.test").searchParams.get("projectContains")?.toLowerCase(); + return needle ? { ...result, sessions: result.sessions.filter(item => + [item.projectId, item.catalog?.repoUrl].some(value => value?.toLowerCase().includes(needle))) } : result; + }, } as unknown as McpContext; const server = new McpServer({ name: "summaries-test", version: "1" }); registerSharedSessionReads(server, context); @@ -82,6 +90,13 @@ test("repo filtering is applied by the directory before pagination and verified assert.equal(data(await call(f.client, "list_session_summaries", { repo: "ORG/REPO" })).sessions.length, 1); }); +test("repo filtering preserves the 512-character input and bounds the directory prefix to 200", async t => { + const f = await fixture(t); + const repo = "x".repeat(512); + assert.deepEqual(data(await call(f.client, "list_session_summaries", { repo })).sessions, []); + assert.equal(new URL(f.paths[0]!, "https://reader.test").searchParams.get("projectContains"), repo.slice(0, 200)); +}); + test("combined project and repo filters preserve the directory project constraint", async t => { const f = await fixture(t); assert.equal(data(await call(f.client, "list_session_summaries", { project: "fake", repo: "org/repo" })).sessions.length, 1); @@ -108,7 +123,7 @@ test("ambiguous or unknown person filters refuse without broadening to all works test("schema bounds reject limit over 50 and invalid timestamps before any reader call", async t => { const f = await fixture(t); - for (const args of [{ limit: 51 }, { limit: 0 }, { since: "yesterday" }]) { + for (const args of [{ limit: 51 }, { limit: 0 }, { since: "yesterday" }, { repo: "x".repeat(513) }]) { assert.equal((await call(f.client, "list_session_summaries", args)).isError, true); } assert.deepEqual(f.paths, []); From 37ce05ed7fce7972a95c75b58ce70fb331937a2a Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 07:43:31 -0800 Subject: [PATCH 4/9] fix(mcp): retain session timing failure causes --- CHANGELOG.md | 2 +- src/mcp/session-timings.ts | 14 +++++++++---- test/session-timings-user-filter.test.ts | 25 ++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 832281e2..eb268235 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ assigned at release. - Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. The push-down requires the sessions read API P3b directory-list version (`feat(read-api): serve the session list and activity from the Supabase directory`, commit `92b907e3`, migration `20261105034000`) or later, whose `projectContains` is case-insensitive across project ID, catalog key and repository URL. Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. No migration. - Fixed: `list_team_activity` no longer holds the request open when Relaycast or History stall. The roster read is bounded at 10 seconds, the optional presence read at 2 seconds (after which the roster is returned with `presence_source: "unavailable"`), and all activity reads at 20 seconds in total; an agent whose read did not finish in time is returned with `activity_status: "unavailable"`. -- Fixed: `list_session_timings` now sends `user_id` to RelayHistory and, when a filtered page comes back empty, reads up to five pages before answering, so a member's sessions are no longer hidden behind an empty page with a cursor. `sessions_scanned` counts every page read. +- Fixed: `list_session_timings` now sends `user_id` to RelayHistory and, when a filtered page comes back empty, reads up to five pages before answering, so a member's sessions are no longer hidden behind an empty page with a cursor. `sessions_scanned` counts every page read. Each row now retains a safe `timing_unavailable_reason` (`read_failed`, `invalid_response`, or `identity_mismatch`) instead of collapsing every timing failure to an unexplained unavailable value. - Fixed: MCP `list_session_timings` now reads each selected session's timing from the same per-user sessions reader as transcript search, the session directory and exact-session transcript reads. A Reader-only desktop session diff --git a/src/mcp/session-timings.ts b/src/mcp/session-timings.ts index a56d5d9a..fbf07535 100644 --- a/src/mcp/session-timings.ts +++ b/src/mcp/session-timings.ts @@ -57,6 +57,7 @@ type SessionsPage = z.infer; * filters each page and skips ahead so an empty page never hides later matches. */ const MAX_USER_FILTER_PAGES = 5; +const timingUnavailableReason = z.enum(["read_failed", "invalid_response", "identity_mismatch"]); type Member = { userId: string; name: string | null }; type Context = { @@ -82,6 +83,7 @@ export function registerSessionTimings( attribution: z.enum(["single_member", "shared", "unattributed"]), members: z.array(z.object({ user_id: z.string(), name: z.string().nullable() })), timing_status: z.enum(["ok", "unavailable"]), + timing_unavailable_reason: timingUnavailableReason.nullable(), timing: timingOutput.nullable(), recorded_span_ms: z.number().nonnegative().nullable(), citation_url: z.string().url(), @@ -134,11 +136,14 @@ export function registerSessionTimings( rows.push(...await Promise.all(selected.slice(i, i + 5).map(async session => { const ids = [...new Set(session.userIds ?? [])]; let timing: z.infer | null = null; + let unavailableReason: z.infer | null = null; try { - const parsed = sessionTimingResponse.parse(await ctx.read(`/v1/sessions/${encodeURIComponent(session.sessionId)}/timing?${new URLSearchParams({ source: session.source })}`)); - if (parsed.sessionId !== session.sessionId || parsed.source !== session.source) throw new Error("Timing identity mismatch"); - timing = parsed; - } catch { /* Preserve the session and explicitly report missing timing. */ } + const parsed = sessionTimingResponse.safeParse(await ctx.read(`/v1/sessions/${encodeURIComponent(session.sessionId)}/timing?${new URLSearchParams({ source: session.source })}`)); + if (!parsed.success) unavailableReason = "invalid_response"; + else if (parsed.data.sessionId !== session.sessionId || parsed.data.source !== session.source) { + unavailableReason = "identity_mismatch"; + } else timing = parsed.data; + } catch { unavailableReason = "read_failed"; } const span = timing?.startedAt && timing.lastActionAt ? Date.parse(timing.lastActionAt) - Date.parse(timing.startedAt) : null; const { correlationId: _correlationId, ...timingData } = timing ?? { correlationId: "" }; @@ -148,6 +153,7 @@ export function registerSessionTimings( attribution: ids.length === 1 ? "single_member" as const : ids.length > 1 ? "shared" as const : "unattributed" as const, members: ids.map(id => ({ user_id: id, name: names.get(id) ?? null })), timing_status: timing ? "ok" as const : "unavailable" as const, + timing_unavailable_reason: unavailableReason, timing: timing ? timingOutput.parse(timingData) : null, recorded_span_ms: span !== null && span >= 0 ? span : null, citation_url: ctx.citation(session.sessionId, session.source), diff --git a/test/session-timings-user-filter.test.ts b/test/session-timings-user-filter.test.ts index ac777e8e..3b6757df 100644 --- a/test/session-timings-user-filter.test.ts +++ b/test/session-timings-user-filter.test.ts @@ -108,3 +108,28 @@ test("reads one page and sends no user filter when no member is given", async () assert.equal(h.calls.filter(isList).length, 1); } finally { await h.close(); } }); + +test("keeps a safe cause when a session timing is unavailable", async () => { + const cases = [ + { reason: "read_failed", response: () => { throw new Error("private upstream detail"); } }, + { reason: "invalid_response", response: () => ({}) }, + { reason: "identity_mismatch", response: () => timing("other") }, + ]; + for (const item of cases) { + const h = await harness((path) => isList(path) ? page([session("s1", ["u1"])], null) : item.response()); + try { + const r = await h.call({ since }); + const data = r.structuredContent as { sessions: Array<{ + timing_status: string; timing_unavailable_reason: string | null; timing: unknown; + }> }; + assert.deepEqual(data.sessions[0], { + session_id: "s1", source: "claude", task_title: null, project_id: null, + attribution: "single_member", members: [{ user_id: "u1", name: "One" }], + timing_status: "unavailable", timing_unavailable_reason: item.reason, + timing: null, recorded_span_ms: null, + citation_url: "https://control.example.com/s/claude/s1", + }); + assert.ok(!JSON.stringify(data).includes("private upstream detail")); + } finally { await h.close(); } + } +}); From c659902dab84cafd5233ec5cd901726caf1ac6a1 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 09:16:17 -0800 Subject: [PATCH 5/9] fix(mcp): make session enrichment failure-safe --- CHANGELOG.md | 2 +- docs/session-summaries.md | 7 +++--- src/mcp/relay-participants.ts | 22 ++++++++++++++--- test/mcp.test.ts | 45 +++++++++++++++++++++++++++++++---- 4 files changed, 65 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c69911e..22b86b00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ assigned at release. ## Unreleased -- Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. The push-down requires the sessions read API P3b directory-list version (`feat(read-api): serve the session list and activity from the Supabase directory`, commit `92b907e3`, migration `20261105034000`) or later, whose `projectContains` is case-insensitive across project ID, catalog key and repository URL. Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. No migration. +- Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. No migration. - Changed: MCP `list_amp_threads` now returns `{ threads, truncated }` instead of a bare thread array. Clients that parse the old array must read the `threads` field; `truncated` reports whether Amp returned more than the first 100 threads. - Changed: MCP `list_relay_agents` now returns the first at most 100 matching agents in relay order and adds `total_matching` and `truncated`; it previously returned the whole matching roster. - Changed: MCP `get_session_summary` now returns `summary: { status: "unsupported" }` as a normal result when the selected backend records that status; it previously returned a tool error. diff --git a/docs/session-summaries.md b/docs/session-summaries.md index ff340b38..5e64d00c 100644 --- a/docs/session-summaries.md +++ b/docs/session-summaries.md @@ -17,9 +17,10 @@ the first 200 characters as `projectContains`, whose directory semantics are a case-insensitive literal substring of the project ID, catalog project key or recorded repository URL, so matching happens before pagination; the returned rows are still checked against the full repository URL to exclude project-id -or catalog-key matches. This requires the sessions read API P3b directory-list -version (`feat(read-api): serve the session list and activity from the Supabase -directory`, commit `92b907e3`, migration `20261105034000`) or later. `person` resolves an exact +or catalog-key matches. This requires a sessions read API whose session directory +list applies `projectContains` as a case-insensitive substring of project ID, +catalog project key or recorded repository URL (directory migration +`20261105034000` or later). `person` resolves an exact workspace member ID, email or unambiguous name and sends that recorded user ID as `user`. Unknown and ambiguous members are refused rather than broadening the request. `repo` accepts up to 512 characters and matches the diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 0149a5a4..0689f9a2 100644 --- a/src/mcp/relay-participants.ts +++ b/src/mcp/relay-participants.ts @@ -75,6 +75,11 @@ const ownerEnrichmentFailed = (operation: "list_relay_agents" | "get_relay_agent operation, error: error instanceof Error ? error.name : "unknown", }); }; +const sessionEnrichmentFailed = (error: unknown) => { + console.warn("[selfhost-mcp] session enrichment failed", { + operation: "list_relay_agents", error: error instanceof Error ? error.name : "unknown", + }); +}; /** Contract section 4, verbatim (shared with Cloud's hosted MCP). */ export const RELAY_AGENT_CARD_GUIDANCE = "Before delegating to a peer, read its card with get_relay_agent_card to see what it does and what to send it. Keep your own card current with set_relay_agent_card: a description of your purpose and one skill per kind of work you take on, with example requests."; @@ -742,14 +747,22 @@ function createRelayService(context: McpContext) { `SELECT agent_name, agent_remote_id, native_session_kind, native_session_id FROM desktop_relay_identities WHERE workspace_id = $1 AND agent_remote_id = ANY($2::text[]) + AND relaycast_workspace_id = $3 AND native_session_kind IS NOT NULL AND native_session_id IS NOT NULL`, - [workspaceId, ids], + [workspaceId, ids, relayWorkspaceId], ); const sessions = new Map(); + const matched = new Set(); for (const row of rows.rows) { const agent = candidates.get(`${row.agent_remote_id}\0${row.agent_name}`); + if (!agent) continue; + if (matched.has(agent.id)) { + sessions.delete(agent.id); + continue; + } + matched.add(agent.id); const kind = row.native_session_kind.trim(); - if (agent && syncedSessionKinds.has(kind) && syncedSessionId.test(row.native_session_id)) { + if (syncedSessionKinds.has(kind) && syncedSessionId.test(row.native_session_id)) { sessions.set(agent.id, { sessionId: row.native_session_id, sessionKind: kind }); } } @@ -761,7 +774,10 @@ function createRelayService(context: McpContext) { const [owners, synced] = await Promise.all([ loadRelayAgentOwners(database, workspaceId, relayWorkspaceId, listed, people, Boolean(gate)) .catch(error => { ownerEnrichmentFailed("list_relay_agents", error); return undefined; }), - syncedDesktopSessions(listed), + syncedDesktopSessions(listed).catch(error => { + sessionEnrichmentFailed(error); + return new Map(); + }), ]); return listed .map(agent => { diff --git a/test/mcp.test.ts b/test/mcp.test.ts index f0f11770..22cea1f3 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -879,15 +879,19 @@ test("list_relay_agents links synced Desktop sessions and keeps validated declar source: "relay-desktop", owner_hash: sha256(env.ownerId), injectable: "true", session_id: "declared-session-id", session_kind: "claude", }); - const insert = (values: { id: string; sourceId: string; agentName: string; agentRemoteId: string; sessionKind: string; sessionId: string }) => + const insert = (values: { id: string; sourceId: string; agentName: string; agentRemoteId: string; sessionKind: string; sessionId: string; + relaycastWorkspaceId?: string }) => env.database.query( `INSERT INTO desktop_relay_identities (id, workspace_id, organization_id, user_id, relaycast_workspace_id, source_id, agent_name, agent_remote_id, address, token_ciphertext, native_session_kind, native_session_id) - VALUES ($1, $2, $3, $4, 'rc-first', $5, $6, $7, $6 || '@fixture', 'encrypted', $8, $9)`, - [values.id, env.workspaceId, env.orgId, env.ownerId, values.sourceId, values.agentName, - values.agentRemoteId, values.sessionKind, values.sessionId], + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $7 || '@fixture', 'encrypted', $9, $10)`, + [values.id, env.workspaceId, env.orgId, env.ownerId, values.relaycastWorkspaceId ?? "rc-first", values.sourceId, + values.agentName, values.agentRemoteId, values.sessionKind, values.sessionId], ); + await insert({ id: "00000000-0000-4000-8000-000000000106", sourceId: "00000000-0000-4000-8000-000000000107", + agentName: synced.name, agentRemoteId: synced.id, sessionKind: "claude", sessionId: "foreign-session-id", + relaycastWorkspaceId: "rc-other" }); await insert({ id: "00000000-0000-4000-8000-000000000101", sourceId: "00000000-0000-4000-8000-000000000102", agentName: synced.name, agentRemoteId: synced.id, sessionKind: "opencode", sessionId: "ses_ABCD1234" }); await insert({ id: "00000000-0000-4000-8000-000000000103", sourceId: "00000000-0000-4000-8000-000000000104", @@ -903,6 +907,39 @@ test("list_relay_agents links synced Desktop sessions and keeps validated declar ["declared-session-id", "claude", "declared"]); }); +test("list_relay_agents session enrichment fails open and refuses ambiguous Desktop rows", async (t) => { + const env = await setup(t); + const peer = env.relay.world.addAgent("session-fallback", { source: "relay-desktop" }); + const client = await relayClient(t, env); + const originalQuery = env.database.query.bind(env.database); + let mode: "reject" | "duplicate" = "reject"; + env.database.query = (async >(sql: string, params: unknown[] = []) => { + if (sql.includes("FROM desktop_relay_identities") && sql.includes("native_session_kind IS NOT NULL")) { + if (mode === "reject") throw new TypeError("private session query detail"); + return { rows: [ + { agent_name: peer.name, agent_remote_id: peer.id, native_session_kind: "codex", native_session_id: "session-one" }, + { agent_name: peer.name, agent_remote_id: peer.id, native_session_kind: "claude", native_session_id: "session-two" }, + ] as unknown as T[] }; + } + return originalQuery(sql, params); + }) as typeof env.database.query; + t.after(() => { env.database.query = originalQuery; }); + const warnings: unknown[][] = []; + t.mock.method(console, "warn", (...args: unknown[]) => warnings.push(args)); + + const unavailable = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })); + const unavailableRow = unavailable.agents.find((agent: any) => agent.name === peer.name); + assert.deepEqual([unavailableRow.session_id, unavailableRow.session_attribution], [null, null]); + assert.deepEqual(warnings, [["[selfhost-mcp] session enrichment failed", + { operation: "list_relay_agents", error: "TypeError" }]]); + assert.doesNotMatch(JSON.stringify(warnings), /private session query detail/); + + mode = "duplicate"; + const ambiguous = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })); + const ambiguousRow = ambiguous.agents.find((agent: any) => agent.name === peer.name); + assert.deepEqual([ambiguousRow.session_id, ambiguousRow.session_attribution], [null, null]); +}); + test("agent card owner enrichment fails open when its journal or membership read fails", async (t) => { const env = await setup(t); env.relay.world.addAgent("peer-bot", { From d2a8a1d7d196e76b4f8b2096d2a21b25988f3462 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 09:42:20 -0800 Subject: [PATCH 6/9] fix(mcp): explain unavailable relay sessions --- CHANGELOG.md | 2 +- src/mcp/relay-messaging.ts | 2 +- src/mcp/relay-participants.ts | 20 +++++++++++++++----- test/mcp.test.ts | 14 ++++++++------ 4 files changed, 25 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22b86b00..c50f7430 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ assigned at release. ## Unreleased -- Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. No migration. +- Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. The optional session join is failure-open: the roster still returns null session fields with `session_unavailable_reason` set to `enrichment_failed` or `ambiguous_sync`. No migration. - Changed: MCP `list_amp_threads` now returns `{ threads, truncated }` instead of a bare thread array. Clients that parse the old array must read the `threads` field; `truncated` reports whether Amp returned more than the first 100 threads. - Changed: MCP `list_relay_agents` now returns the first at most 100 matching agents in relay order and adds `total_matching` and `truncated`; it previously returned the whole matching roster. - Changed: MCP `get_session_summary` now returns `summary: { status: "unsupported" }` as a normal result when the selected backend records that status; it previously returned a tool error. diff --git a/src/mcp/relay-messaging.ts b/src/mcp/relay-messaging.ts index 270e51d9..f8064798 100644 --- a/src/mcp/relay-messaging.ts +++ b/src/mcp/relay-messaging.ts @@ -55,7 +55,7 @@ export function registerRelayMessaging(server: McpServer, context: McpContext): }; server.registerTool("list_relay_agents", { - description: "List the first matching agents in relay order across every teammate in your current workspace's relay, with exact machine addresses, presence, descriptions and owners. The page defaults to 100 agents and cannot exceed 100; total_matching and truncated disclose omitted matches, so narrow the filters when truncated. Ownership metadata describes the roster; it does not grant permission to act as an agent.", + description: "List the first matching agents in relay order across every teammate in your current workspace's relay, with exact machine addresses, presence, descriptions and owners. The page defaults to 100 agents and cannot exceed 100; total_matching and truncated disclose omitted matches, so narrow the filters when truncated. A null session with session_unavailable_reason means optional Desktop session enrichment failed or was ambiguous; the roster remains available. Ownership metadata describes the roster; it does not grant permission to act as an agent.", inputSchema: { person: z.string().trim().min(1).max(200).optional().describe("me, a teammate's user ID, or display name"), status: z.enum(["live", "offline", "all"]).default("live"), query: z.string().trim().max(200).optional(), limit: z.number().int().min(1).max(100).default(100).describe("Maximum matching agents returned from the start of relay order. Use person/query/status filters to narrow a truncated result."), diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 0689f9a2..1d3ab196 100644 --- a/src/mcp/relay-participants.ts +++ b/src/mcp/relay-participants.ts @@ -738,11 +738,15 @@ function createRelayService(context: McpContext) { const syncedSessionKinds = new Set(["codex", "grok", "pi", "opencode", "claude", "copilot", "cursor"]); const syncedSessionId = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/; + type SyncedDesktopSessions = { + sessions: Map; + ambiguous: Set; + }; async function syncedDesktopSessions(agents: readonly RosterAgent[]) { const targets = agents.map(agent => relayAgentOwnerTarget(agent, Boolean(gate))); const candidates = new Map(targets.map((target, index) => [`${target.lookupId}\0${target.name}`, agents[index]!])); const ids = [...new Set(targets.map(target => target.lookupId))]; - if (!ids.length) return new Map(); + if (!ids.length) return { sessions: new Map(), ambiguous: new Set() } satisfies SyncedDesktopSessions; const rows = await executor.query<{ agent_name: string; agent_remote_id: string; native_session_kind: string; native_session_id: string }>( `SELECT agent_name, agent_remote_id, native_session_kind, native_session_id FROM desktop_relay_identities @@ -753,11 +757,13 @@ function createRelayService(context: McpContext) { ); const sessions = new Map(); const matched = new Set(); + const ambiguous = new Set(); for (const row of rows.rows) { const agent = candidates.get(`${row.agent_remote_id}\0${row.agent_name}`); if (!agent) continue; if (matched.has(agent.id)) { sessions.delete(agent.id); + ambiguous.add(agent.id); continue; } matched.add(agent.id); @@ -766,7 +772,7 @@ function createRelayService(context: McpContext) { sessions.set(agent.id, { sessionId: row.native_session_id, sessionKind: kind }); } } - return sessions; + return { sessions, ambiguous }; } async function roster(status: "live" | "all" | "offline", people: readonly McpMember[], includeStale = false, dir: Directory = directory()) { @@ -774,17 +780,21 @@ function createRelayService(context: McpContext) { const [owners, synced] = await Promise.all([ loadRelayAgentOwners(database, workspaceId, relayWorkspaceId, listed, people, Boolean(gate)) .catch(error => { ownerEnrichmentFailed("list_relay_agents", error); return undefined; }), - syncedDesktopSessions(listed).catch(error => { + syncedDesktopSessions(listed).then(result => ({ ...result, failed: false as const })).catch(error => { sessionEnrichmentFailed(error); - return new Map(); + return { sessions: new Map(), + ambiguous: new Set(), failed: true as const }; }), ]); return listed .map(agent => { const row = rosterAgent(agent, people, userId, workspaceId, owners?.get(agent.id)); - const session = row.session_attribution ? null : synced.get(agent.id); + const session = row.session_attribution ? null : synced.sessions.get(agent.id); return { ...row, ...(session ? { session_id: session.sessionId, session_kind: session.sessionKind, session_attribution: "synced" as const } : {}), + session_unavailable_reason: row.session_attribution || session ? null + : synced.failed ? "enrichment_failed" as const + : synced.ambiguous.has(agent.id) ? "ambiguous_sync" as const : null, ...cardSummary(agent.metadata, agent) }; }) .filter(agent => status === "all" || (status === "live" ? agent.online : !agent.online)); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 22cea1f3..63224c4b 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -900,11 +900,11 @@ test("list_relay_agents links synced Desktop sessions and keeps validated declar const client = await relayClient(t, env); const agents = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })).agents; const syncedRow = agents.find((agent: any) => agent.name === synced.name); - assert.deepEqual([syncedRow.session_id, syncedRow.session_kind, syncedRow.session_attribution], - ["ses_ABCD1234", "opencode", "synced"]); + assert.deepEqual([syncedRow.session_id, syncedRow.session_kind, syncedRow.session_attribution, + syncedRow.session_unavailable_reason], ["ses_ABCD1234", "opencode", "synced", null]); const declaredRow = agents.find((agent: any) => agent.name === declared.name); - assert.deepEqual([declaredRow.session_id, declaredRow.session_kind, declaredRow.session_attribution], - ["declared-session-id", "claude", "declared"]); + assert.deepEqual([declaredRow.session_id, declaredRow.session_kind, declaredRow.session_attribution, + declaredRow.session_unavailable_reason], ["declared-session-id", "claude", "declared", null]); }); test("list_relay_agents session enrichment fails open and refuses ambiguous Desktop rows", async (t) => { @@ -929,7 +929,8 @@ test("list_relay_agents session enrichment fails open and refuses ambiguous Desk const unavailable = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })); const unavailableRow = unavailable.agents.find((agent: any) => agent.name === peer.name); - assert.deepEqual([unavailableRow.session_id, unavailableRow.session_attribution], [null, null]); + assert.deepEqual([unavailableRow.session_id, unavailableRow.session_attribution, + unavailableRow.session_unavailable_reason], [null, null, "enrichment_failed"]); assert.deepEqual(warnings, [["[selfhost-mcp] session enrichment failed", { operation: "list_relay_agents", error: "TypeError" }]]); assert.doesNotMatch(JSON.stringify(warnings), /private session query detail/); @@ -937,7 +938,8 @@ test("list_relay_agents session enrichment fails open and refuses ambiguous Desk mode = "duplicate"; const ambiguous = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })); const ambiguousRow = ambiguous.agents.find((agent: any) => agent.name === peer.name); - assert.deepEqual([ambiguousRow.session_id, ambiguousRow.session_attribution], [null, null]); + assert.deepEqual([ambiguousRow.session_id, ambiguousRow.session_attribution, + ambiguousRow.session_unavailable_reason], [null, null, "ambiguous_sync"]); }); test("agent card owner enrichment fails open when its journal or membership read fails", async (t) => { From 3246ff4aae45e1f6e5891740c7d9c8189f1856a8 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 10:02:51 -0800 Subject: [PATCH 7/9] fix(mcp): clear unavailable session metadata --- src/mcp/relay-participants.ts | 8 +++++--- test/mcp.test.ts | 10 +++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 1d3ab196..7a7d5587 100644 --- a/src/mcp/relay-participants.ts +++ b/src/mcp/relay-participants.ts @@ -790,11 +790,13 @@ function createRelayService(context: McpContext) { .map(agent => { const row = rosterAgent(agent, people, userId, workspaceId, owners?.get(agent.id)); const session = row.session_attribution ? null : synced.sessions.get(agent.id); + const unavailableReason = row.session_attribution || session ? null + : synced.failed ? "enrichment_failed" as const + : synced.ambiguous.has(agent.id) ? "ambiguous_sync" as const : null; return { ...row, ...(session ? { session_id: session.sessionId, session_kind: session.sessionKind, session_attribution: "synced" as const } : {}), - session_unavailable_reason: row.session_attribution || session ? null - : synced.failed ? "enrichment_failed" as const - : synced.ambiguous.has(agent.id) ? "ambiguous_sync" as const : null, + ...(unavailableReason ? { session_id: null, session_kind: null, session_attribution: null } : {}), + session_unavailable_reason: unavailableReason, ...cardSummary(agent.metadata, agent) }; }) .filter(agent => status === "all" || (status === "live" ? agent.online : !agent.online)); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 63224c4b..c7c7f2a5 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -909,7 +909,7 @@ test("list_relay_agents links synced Desktop sessions and keeps validated declar test("list_relay_agents session enrichment fails open and refuses ambiguous Desktop rows", async (t) => { const env = await setup(t); - const peer = env.relay.world.addAgent("session-fallback", { source: "relay-desktop" }); + const peer = env.relay.world.addAgent("session-fallback", { source: "relay-desktop", session_kind: "claude" }); const client = await relayClient(t, env); const originalQuery = env.database.query.bind(env.database); let mode: "reject" | "duplicate" = "reject"; @@ -929,8 +929,8 @@ test("list_relay_agents session enrichment fails open and refuses ambiguous Desk const unavailable = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })); const unavailableRow = unavailable.agents.find((agent: any) => agent.name === peer.name); - assert.deepEqual([unavailableRow.session_id, unavailableRow.session_attribution, - unavailableRow.session_unavailable_reason], [null, null, "enrichment_failed"]); + assert.deepEqual([unavailableRow.session_id, unavailableRow.session_kind, unavailableRow.session_attribution, + unavailableRow.session_unavailable_reason], [null, null, null, "enrichment_failed"]); assert.deepEqual(warnings, [["[selfhost-mcp] session enrichment failed", { operation: "list_relay_agents", error: "TypeError" }]]); assert.doesNotMatch(JSON.stringify(warnings), /private session query detail/); @@ -938,8 +938,8 @@ test("list_relay_agents session enrichment fails open and refuses ambiguous Desk mode = "duplicate"; const ambiguous = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })); const ambiguousRow = ambiguous.agents.find((agent: any) => agent.name === peer.name); - assert.deepEqual([ambiguousRow.session_id, ambiguousRow.session_attribution, - ambiguousRow.session_unavailable_reason], [null, null, "ambiguous_sync"]); + assert.deepEqual([ambiguousRow.session_id, ambiguousRow.session_kind, ambiguousRow.session_attribution, + ambiguousRow.session_unavailable_reason], [null, null, null, "ambiguous_sync"]); }); test("agent card owner enrichment fails open when its journal or membership read fails", async (t) => { From 49eb62dd24f3d5bbdf25b3e1ddd58bc97d8b103b Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 10:18:55 -0800 Subject: [PATCH 8/9] fix(mcp): preserve roster session kind --- CHANGELOG.md | 2 +- src/mcp/relay-participants.ts | 1 - test/mcp.test.ts | 4 ++-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c50f7430..7aa84d47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ assigned at release. ## Unreleased -- Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. The optional session join is failure-open: the roster still returns null session fields with `session_unavailable_reason` set to `enrichment_failed` or `ambiguous_sync`. No migration. +- Fixed: MCP repository-filtered session summaries apply the first 200 characters of a repo-only filter in the session directory before pagination, while still accepting a 512-character repo value and verifying the full returned repository URL. This requires a sessions read API whose session directory list applies `projectContains` as a case-insensitive substring of project ID, catalog project key or recorded repository URL (directory migration `20261105034000` or later). Exact verification can still produce a short or empty page with a cursor. Relay agent listings now link an exact roster agent ID to its already-synced Desktop native session when the agent has no validated Relaycast session declaration. The optional session join is failure-open: the roster still returns a null session ID and attribution with `session_unavailable_reason` set to `enrichment_failed` or `ambiguous_sync`; an independently recorded metadata session kind is preserved. No migration. - Changed: MCP `list_amp_threads` now returns `{ threads, truncated }` instead of a bare thread array. Clients that parse the old array must read the `threads` field; `truncated` reports whether Amp returned more than the first 100 threads. - Changed: MCP `list_relay_agents` now returns the first at most 100 matching agents in relay order and adds `total_matching` and `truncated`; it previously returned the whole matching roster. - Changed: MCP `get_session_summary` now returns `summary: { status: "unsupported" }` as a normal result when the selected backend records that status; it previously returned a tool error. diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 7a7d5587..72a5f955 100644 --- a/src/mcp/relay-participants.ts +++ b/src/mcp/relay-participants.ts @@ -795,7 +795,6 @@ function createRelayService(context: McpContext) { : synced.ambiguous.has(agent.id) ? "ambiguous_sync" as const : null; return { ...row, ...(session ? { session_id: session.sessionId, session_kind: session.sessionKind, session_attribution: "synced" as const } : {}), - ...(unavailableReason ? { session_id: null, session_kind: null, session_attribution: null } : {}), session_unavailable_reason: unavailableReason, ...cardSummary(agent.metadata, agent) }; }) diff --git a/test/mcp.test.ts b/test/mcp.test.ts index c7c7f2a5..8c807586 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -930,7 +930,7 @@ test("list_relay_agents session enrichment fails open and refuses ambiguous Desk const unavailable = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })); const unavailableRow = unavailable.agents.find((agent: any) => agent.name === peer.name); assert.deepEqual([unavailableRow.session_id, unavailableRow.session_kind, unavailableRow.session_attribution, - unavailableRow.session_unavailable_reason], [null, null, null, "enrichment_failed"]); + unavailableRow.session_unavailable_reason], [null, "claude", null, "enrichment_failed"]); assert.deepEqual(warnings, [["[selfhost-mcp] session enrichment failed", { operation: "list_relay_agents", error: "TypeError" }]]); assert.doesNotMatch(JSON.stringify(warnings), /private session query detail/); @@ -939,7 +939,7 @@ test("list_relay_agents session enrichment fails open and refuses ambiguous Desk const ambiguous = structured(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })); const ambiguousRow = ambiguous.agents.find((agent: any) => agent.name === peer.name); assert.deepEqual([ambiguousRow.session_id, ambiguousRow.session_kind, ambiguousRow.session_attribution, - ambiguousRow.session_unavailable_reason], [null, null, null, "ambiguous_sync"]); + ambiguousRow.session_unavailable_reason], [null, "claude", null, "ambiguous_sync"]); }); test("agent card owner enrichment fails open when its journal or membership read fails", async (t) => { From 9ae0315f9fa38160502f673555a0a84c0239b17d Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 10:40:53 -0800 Subject: [PATCH 9/9] test(mcp): preserve declared session on lookup failure --- test/mcp.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 8c807586..d23cf8de 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -910,6 +910,9 @@ test("list_relay_agents links synced Desktop sessions and keeps validated declar test("list_relay_agents session enrichment fails open and refuses ambiguous Desktop rows", async (t) => { const env = await setup(t); const peer = env.relay.world.addAgent("session-fallback", { source: "relay-desktop", session_kind: "claude" }); + const declared = env.relay.world.addAgent("session-declared-fallback", { + source: "relay-desktop", session_id: "declared-session-id", session_kind: "claude", injectable: "true", + }); const client = await relayClient(t, env); const originalQuery = env.database.query.bind(env.database); let mode: "reject" | "duplicate" = "reject"; @@ -931,6 +934,9 @@ test("list_relay_agents session enrichment fails open and refuses ambiguous Desk const unavailableRow = unavailable.agents.find((agent: any) => agent.name === peer.name); assert.deepEqual([unavailableRow.session_id, unavailableRow.session_kind, unavailableRow.session_attribution, unavailableRow.session_unavailable_reason], [null, "claude", null, "enrichment_failed"]); + const declaredRow = unavailable.agents.find((agent: any) => agent.name === declared.name); + assert.deepEqual([declaredRow.session_id, declaredRow.session_kind, declaredRow.session_attribution, + declaredRow.session_unavailable_reason], ["declared-session-id", "claude", "declared", null]); assert.deepEqual(warnings, [["[selfhost-mcp] session enrichment failed", { operation: "list_relay_agents", error: "TypeError" }]]); assert.doesNotMatch(JSON.stringify(warnings), /private session query detail/);