From 3ca319abbb5fb54a2749ff90dbdc09da23bd9c18 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 09:18:39 -0800 Subject: [PATCH 1/5] fix(mcp): close bounded discovery audit gaps --- CHANGELOG.md | 5 +++-- src/amp/provider-origin.json | 4 ++-- src/amp/provider.ts | 4 ++-- src/mcp/catalog.ts | 13 ++++++++++--- src/mcp/relay-participants.ts | 5 ++++- src/messaging/relaycast.ts | 8 ++++---- test/amp.test.ts | 14 ++++++++++++++ test/mcp.test.ts | 31 ++++++++++++++++++++++++------- test/messaging.test.ts | 11 +++++++++++ 9 files changed, 74 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d990ca62..1b4f1919 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,11 +5,12 @@ assigned at release. ## Unreleased -- 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_amp_threads` now returns `{ threads, truncated }` instead of a bare thread array. Clients that parse the old array must read the `threads` field; `truncated` truthfully reports whether Amp returned more than the first 100 threads by requesting one lookahead row. - 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. - Added: every MCP `list_session_summaries` row now includes `transcript_status: "not_verified"`, because directory publication does not prove that the transcript index is readable yet. -- Changed: on a managed Desktop connection, MCP `describe_capabilities` now reports `relay_messaging` as `restricted` when the chat's synced Desktop identity cannot be verified, with the safe refusal reason or retry guidance when the check itself is temporarily unavailable. +- Changed: on a managed Desktop connection whose synced identity cannot be verified, MCP `describe_capabilities` keeps `relay_messaging` available for `list_relay_agents` and `get_relay_agent_card` while listing every actor-dependent tool in `restricted_tools`, with the safe refusal reason or retry guidance. +- Fixed: `check_relay_inbox` bounds sender-address enrichment to one second and still returns pending messages with a null address when the lookup fails or stalls. - Added: Cursor cloud agents can join Agent Relay as their own runs (migration 0081; docs/cursor-cloud-agents.md). A Cursor cloud agent connects with the person's OAuth grant from cursor.com/agents. It proves which run it is with a Cursor-signed OIDC token, minted in its VM for this server's audience and the grant's nonce, and verified against api.cursor.com's keys, once. It then joins with `join_relay` `cursor_identity_token` as `cursor-cloud-` and acts with `as`. The Cursor account must first be linked to the person: they confirm a one-time link in the browser, or the operator trusts their Cursor team (`SELFHOST_CURSOR_CLOUD_TRUSTED_TEAMS`) and the token carries their own email. `SELFHOST_CURSOR_CLOUD_RUN_IDENTITY=required` refuses the connection's shared agent. Revoking the connection releases its runs. - Changed: OAuth connections with a `cursor.com/agents` callback are now the `cursor-cloud` connector kind (cards, relaygate `clients`), not `grok-bot`; x.ai callbacks stay `grok-bot`. Grok Bot routines work for both kinds. **On gate-only installs**, a Cursor-hosted Grok Bot that relaygate admitted as `grok-bot` re-enrols as `cursor-cloud` on next use. Add `"cursor-cloud"` to the relaygate rule that allows `"grok-bot"`. - Changed: the MCP endpoint's `[selfhost-mcp] native chat context refused` log diff --git a/src/amp/provider-origin.json b/src/amp/provider-origin.json index 48ba7c32..c092facb 100644 --- a/src/amp/provider-origin.json +++ b/src/amp/provider-origin.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/AgentWorkforce/relayhistory", - "commit": "b904e7ac570a22c3568879f5c4136d48f745984e", + "commit": "7c9ef71c69527b78e151abb3a0830da34e93ca80", "path": "sdk-ts/src/amp-source.ts", - "sha256": "aaf7feedda1bdcdeb6ef91bf6138e3662f10c3b6148c6267a484907580c4c1e9" + "sha256": "e04b19806ce728976feb4a8f06fc84ac54a101255b29c2f45ebfad4c5d9d5853" } diff --git a/src/amp/provider.ts b/src/amp/provider.ts index eae64259..4b755cf6 100644 --- a/src/amp/provider.ts +++ b/src/amp/provider.ts @@ -1,5 +1,5 @@ // Generated from AgentWorkforce/relayhistory sdk-ts/src/amp-source.ts. Do not edit here. -// sha256: aaf7feedda1bdcdeb6ef91bf6138e3662f10c3b6148c6267a484907580c4c1e9 +// sha256: e04b19806ce728976feb4a8f06fc84ac54a101255b29c2f45ebfad4c5d9d5853 /** Amp evidence projection. Cloud owns credentials, scheduling and delivery; * this module owns interpreting provider JSON. Unknown fields stay in raw. */ export type AmpMessage = Record; @@ -193,7 +193,7 @@ let op;try{op=JSON.parse(process.env.RELAY_AMP_OPERATION)}catch{} if(op&&typeof op.threadId==='string'){op.threadId=op.threadId.trim();const prefix='https://ampcode.com/threads/';if(op.threadId.startsWith(prefix))op.threadId=op.threadId.slice(prefix.length);if(op.threadId.endsWith('/'))op.threadId=op.threadId.slice(0,-1)} if(!op||!['discover','export','inject'].includes(op.kind)||(op.kind!=='discover'&&(typeof op.threadId!=='string'||!/^T-[A-Za-z0-9-]{6,100}$/.test(op.threadId)))||(op.kind==='inject'&&(typeof op.text!=='string'||!op.text||op.text.includes(String.fromCharCode(0))))){process.stdout.write(JSON.stringify({ok:false,outcome:'rejected',code:'amp_invalid_operation'}));process.exit(0)} const args=['--log-file','/dev/null']; -if(op.kind==='discover')args.push('threads','search','author:me','--json','--limit','100'); +if(op.kind==='discover')args.push('threads','search','author:me','--json','--limit','101'); else if(op.kind==='export')args.push('threads','export',op.threadId); else if(op.kind==='inject')args.push('threads','continue',op.threadId,'-ox'); const r=spawnSync(process.env.RELAY_AMP_CLI_PATH||'/tmp/relay-amp/node_modules/.bin/amp',args,{encoding:'utf8',input:op.kind==='inject'?op.text:undefined,timeout:45000,maxBuffer:16777216,env:{...process.env,RELAY_AMP_OPERATION:''}}); diff --git a/src/mcp/catalog.ts b/src/mcp/catalog.ts index 91c966b8..046404e6 100644 --- a/src/mcp/catalog.ts +++ b/src/mcp/catalog.ts @@ -44,6 +44,8 @@ export function ensureToolTitles(server: McpServer): void { export const RELAY_TOOLS = ["list_relay_agents", "get_relay_agent_card", "set_relay_agent_card", "send_relay_message", "get_relay_message_status", "read_relay_conversation", "join_relay", "leave_relay", "relay_status", "check_relay_inbox", "list_relay_channels", "subscribe_relay_channel", "unsubscribe_relay_channel", "post_relay_channel", "read_relay_channel"] as const; +/** Directory reads do not act as the managed chat, so they survive a missing synced Desktop identity. */ +const RELAY_DIRECTORY_TOOLS = ["list_relay_agents", "get_relay_agent_card"] as const; const RELAY_SPAWN_TOOLS = ["list_relay_spawn_targets", "spawn_relay_agent", "get_relay_spawn_status", "release_relay_agent"] as const; const AMP_TOOLS = ["list_amp_threads", "bind_amp_thread", "unbind_amp_thread"] as const; const WEBHOOK_INBOX_TOOLS = ["link_webhook_inbox", "unlink_webhook_inbox"] as const; @@ -160,6 +162,8 @@ export type CapabilityGroup = { title: string; status: "available" | "restricted" | "unavailable"; tools: string[]; + /** Listed tools whose calls are refused while the rest of the group remains usable. */ + restricted_tools?: Array<{ name: string; reason: string }>; reason?: string; how_to_enable?: string; call_requirements?: string; @@ -256,9 +260,12 @@ export function describeCapabilities(input: { ? "Use your own Agent Relay sign-in (a person connection) for these tools." : "An operator adds events_shim to SELFHOST_FEATURES (chart selectedFeatures)." }; if (item && id === "relay_messaging" && input.nativeAuthorityAvailable === false) { - return { ...base, status: "restricted", tools: [...item.tools], - reason: input.nativeAuthorityReason ?? "Agent Relay could not verify this chat's synced Desktop identity.", - how_to_enable: input.nativeAuthorityHowToEnable ?? "Reconnect this chat from Agent Relay Desktop and wait for its identity to sync, then retry." }; + const reason = input.nativeAuthorityReason ?? "Agent Relay could not verify this chat's synced Desktop identity."; + return { ...base, status: "available", tools: [...item.tools], + restricted_tools: item.tools.filter(name => !(RELAY_DIRECTORY_TOOLS as readonly string[]).includes(name)) + .map(name => ({ name, reason })), + how_to_enable: input.nativeAuthorityHowToEnable ?? "Reconnect this chat from Agent Relay Desktop and wait for its identity to sync, then retry.", + call_requirements: "Agent directory reads remain available. Acting as this managed chat requires its synced Desktop identity." }; } if (item) return { ...base, status: "available", tools: [...item.tools], ...(id === "customer_support" ? { call_requirements: "Available to all signed-in customers. Current credentials and workspace membership are checked before sending and before returning an answer." } : {}) }; diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 5bf71088..56310436 100644 --- a/src/mcp/relay-participants.ts +++ b/src/mcp/relay-participants.ts @@ -104,6 +104,7 @@ const DESKTOP_LINK_FIELDS = "desktop_address cannot be combined with name or des const DESKTOP_LINK_NEEDS_SESSION = "Initialize MCP to receive Mcp-Session-Id before linking a desktop identity."; const DESKTOP_LINK_OAUTH = "This connection acts only as the agent approved for it and cannot link a desktop identity. Use a native MCP session (one that keeps Mcp-Session-Id) to call join_relay with desktop_address."; const DESKTOP_INBOX_GUIDANCE = "Replies are injected into your session by Agent Relay Desktop; check_relay_inbox is not used for this linked identity."; +const INBOX_SENDER_LOOKUP_TIMEOUT_MS = 1_000; const CHANNEL_REPLY_GUIDANCE = "Reply to a post in this channel with post_relay_channel channel= thread_id=. Use send_relay_message only when the reply is private."; const RESERVED_CHANNEL_PREFIX = "agent-events-"; const CHANNEL_NAME = /^[a-z0-9][a-z0-9_-]{0,79}$/; @@ -1547,7 +1548,9 @@ function createRelayService(context: McpContext) { ]); // Sender addresses come from one bounded lookup of the senders' names. const senders = [...new Set(messages.flatMap(message => message.sender ? [message.sender] : []))]; - const agents = senders.length ? (await dir.via.findAgentsByNames(dir.credential, senders)).filter(isListedRelayAgent) : []; + const agents = senders.length ? (await dir.via.findAgentsByNames(dir.credential, senders, { + signal: AbortSignal.timeout(INBOX_SENDER_LOOKUP_TIMEOUT_MS), + }).catch(() => [])).filter(isListedRelayAgent) : []; const addresses = new Map(agents.map(agent => [agent.name, agent.address])); const channelNames = new Map(); if (messages.some(isChannelDelivery)) { diff --git a/src/messaging/relaycast.ts b/src/messaging/relaycast.ts index f94f0548..367689eb 100644 --- a/src/messaging/relaycast.ts +++ b/src/messaging/relaycast.ts @@ -266,14 +266,14 @@ export function createRelaycastClient(input: { } /** Bounded name lookup behind findAgentsByNames and findAgentByName. */ - async function agentsByNames(workspaceKey: string, names: string[]): Promise { + async function agentsByNames(workspaceKey: string, names: string[], options: { signal?: AbortSignal } = {}): Promise { const wanted = [...new Set(names.map(name => name.trim()).filter(Boolean))]; const found: RosterAgent[] = []; for (let start = 0; start < wanted.length; start += AGENT_NAME_LOOKUP_MAX) { const chunk = wanted.slice(start, start + AGENT_NAME_LOOKUP_MAX); const query = new URLSearchParams(); for (const name of chunk) query.append("names", name); - const data = await labeled("find_agents", () => call("GET", `/v1/agents?${query}`, workspaceKey)); + const data = await labeled("find_agents", () => call("GET", `/v1/agents?${query}`, workspaceKey, undefined, undefined, false, options.signal)); if (!Array.isArray(data)) throw new RelaycastCallError(200, "", true); const requested = new Set(chunk); for (const item of data) { @@ -498,8 +498,8 @@ export function createRelaycastClient(input: { * filtering keeps the result bounded and correct there too. Errors are not * retried with a full-roster read. */ - async findAgentsByNames(workspaceKey: string, names: string[]): Promise { - return agentsByNames(workspaceKey, names); + async findAgentsByNames(workspaceKey: string, names: string[], options: { signal?: AbortSignal } = {}): Promise { + return agentsByNames(workspaceKey, names, options); }, /** diff --git a/test/amp.test.ts b/test/amp.test.ts index 053f7c52..e6ba2ac9 100644 --- a/test/amp.test.ts +++ b/test/amp.test.ts @@ -1,8 +1,10 @@ import assert from "node:assert/strict"; import test from "node:test"; +import { runInNewContext } from "node:vm"; import { registerAmpTools } from "../src/amp/mcp-tools.js"; import { claimNext, RELAY_EVENT_MAX_BYTES } from "../src/amp/delivery.js"; import { decrypt, ownedThreadPage } from "../src/amp/service.js"; +import { AMP_CLI_BRIDGE } from "../src/amp/provider.js"; import { startAmpWorker } from "../src/amp/worker.js"; import { planToolGroups } from "../src/mcp/catalog.js"; import type { McpContext } from "../src/mcp/context.js"; @@ -15,6 +17,18 @@ import { BOOTSTRAP } from "./flows-helpers.js"; const NOT_FOUND = { error: "Not found" }; +test("Amp discovery requests one lookahead row for the bounded 100-thread page", () => { + let args: string[] = []; + runInNewContext(AMP_CLI_BRIDGE, { + require: () => ({ spawnSync: (_command: string, value: string[]) => { + args = value; return { status: 0, stdout: "[]" }; + } }), + process: { env: { RELAY_AMP_OPERATION: JSON.stringify({ kind: "discover" }) }, + stdout: { write: () => undefined }, exit: () => undefined }, + }); + assert.deepEqual(Array.from(args), ["--log-file", "/dev/null", "threads", "search", "author:me", "--json", "--limit", "101"]); +}); + test("amp gating: off answers 404 before auth on every route and starts no worker (req 8)", async (t) => { for (const variant of [{ amp: null }, { amp: ampConfig({ enabled: false }) }]) { const h = await startAmp(t, variant); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 70c5b243..35123f0b 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -531,8 +531,11 @@ test("describe_capabilities does not advertise managed relay tools without a syn workspaceId: "workspace", role: "owner", providers: [], nativeAuthorityAvailable: false, nativeAuthorityReason: "This chat has no synced Desktop identity." }); const messaging = report.groups.find(group => group.id === "relay_messaging"); - assert.equal(messaging?.status, "restricted"); - assert.equal(messaging?.reason, "This chat has no synced Desktop identity."); + assert.equal(messaging?.status, "available"); + assert.deepEqual(messaging?.restricted_tools?.map(tool => tool.name).slice(0, 3), + ["set_relay_agent_card", "send_relay_message", "get_relay_message_status"]); + assert.equal(messaging?.restricted_tools?.every(tool => tool.reason === "This chat has no synced Desktop identity."), true); + assert.equal(messaging?.restricted_tools?.some(tool => tool.name === "list_relay_agents" || tool.name === "get_relay_agent_card"), false); }); test("the capability handler preserves safe refusals, distinguishes outages, and skips unavailable or unmanaged relay messaging", async (t) => { @@ -545,23 +548,25 @@ test("the capability handler preserves safe refusals, distinguishes outages, and registerCapabilityDiscovery({ registerTool: (_name: string, _definition: unknown, run: typeof handler) => { handler = run; } } as never, { ...baseContext, authMode, desktopCall: { required, nativeSession: required ? { kind: "codex", id: "native" } : undefined } } as unknown as McpContext, { nativeStatus }); - return (await handler!()).structuredContent as { groups: Array<{ id: string; status: string; reason?: string; how_to_enable?: string }> }; + return (await handler!()).structuredContent as { groups: Array<{ id: string; status: string; reason?: string; how_to_enable?: string; + restricted_tools?: Array<{ name: string; reason: string }> }> }; } let checks = 0; const refusal = "This chat is synced to two Desktop identities. Remove the duplicate identity, then retry."; const refused = await call(true, async () => { checks += 1; throw new RelayToolError(refusal); }); assert.equal(checks, 1); const refusedMessaging = refused.groups.find(group => group.id === "relay_messaging"); - assert.equal(refusedMessaging?.status, "restricted"); - assert.equal(refusedMessaging?.reason, refusal); + assert.equal(refusedMessaging?.status, "available"); + assert.equal(refusedMessaging?.restricted_tools?.find(tool => tool.name === "send_relay_message")?.reason, refusal); assert.doesNotMatch(refusedMessaging?.how_to_enable ?? "", /reconnect/i); const warnings: unknown[][] = []; t.mock.method(console, "warn", (...args: unknown[]) => warnings.push(args)); const unavailable = await call(true, async () => { checks += 1; throw new Error("private outage details"); }); const unavailableMessaging = unavailable.groups.find(group => group.id === "relay_messaging"); - assert.match(unavailableMessaging?.reason ?? "", /could not check.*right now/i); - assert.doesNotMatch(unavailableMessaging?.reason ?? "", /private outage details|reconnect/i); + const unavailableReason = unavailableMessaging?.restricted_tools?.find(tool => tool.name === "send_relay_message")?.reason ?? ""; + assert.match(unavailableReason, /could not check.*right now/i); + assert.doesNotMatch(unavailableReason, /private outage details|reconnect/i); assert.deepEqual(warnings, [["[selfhost-mcp] native identity capability check failed", { error: "Error" }]]); const available = await call(true, async () => { checks += 1; }); @@ -1617,6 +1622,18 @@ test("check_relay_inbox resolves sender addresses with one bounded lookup", asyn assert.deepEqual([...lookups.names[0]!].sort(), ["peer-a", "peer-b"]); }); +test("check_relay_inbox delivers messages with null sender addresses when bounded enrichment fails", async (t) => { + const env = await setup(t); + env.relay.world.addAgent("peer-a"); + const client = await relayClient(t, env); + structured(await client.callTool({ name: "join_relay", arguments: { name: "owner-inbox" } })); + env.relay.world.sendAs("peer-a", "owner-inbox", "from a"); + env.relay.namesLookup = "fail"; + const inbox = structured(await client.callTool({ name: "check_relay_inbox", arguments: {} })); + assert.deepEqual(inbox.messages.map((message: any) => ({ sender: message.sender, sender_address: message.sender_address })), + [{ sender: "peer-a", sender_address: null }]); +}); + type AuditRow = Record; async function auditRows(env: Awaited>): Promise { diff --git a/test/messaging.test.ts b/test/messaging.test.ts index da148ab9..04624095 100644 --- a/test/messaging.test.ts +++ b/test/messaging.test.ts @@ -1193,6 +1193,17 @@ test("relaycast client looks agents up by name with the bounded names query", as await assert.rejects(client.findAgentByName(key, "alpha"), (error: unknown) => error instanceof RelaycastCallError && error.status === 503 && error.operation === "find_agents"); assert.equal(calls.length, 1, "no fallback roster read"); + + const hanging = createRelaycastClient({ + internalOrigin: "http://relaycast.test/", + fetchImpl: (async (_input: string | URL | Request, init?: RequestInit) => new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true }); + })) as typeof fetch, + }); + const controller = new AbortController(); + setTimeout(() => controller.abort(), 10); + await assert.rejects(hanging.findAgentsByNames(key, ["alpha"], { signal: controller.signal }), + (error: unknown) => error instanceof RelaycastCallError && error.status === 0 && error.operation === "find_agents"); }); // ---- GET /resolve: the workspace-wide Relaycast key (Cloud parity) ---------- From e5120d82c4b20ddbac775ca4be9be9bfbc749f45 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 09:24:31 -0800 Subject: [PATCH 2/5] chore(amp): refresh RelayHistory provenance --- src/amp/provider-origin.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/amp/provider-origin.json b/src/amp/provider-origin.json index c092facb..d7170c26 100644 --- a/src/amp/provider-origin.json +++ b/src/amp/provider-origin.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/AgentWorkforce/relayhistory", - "commit": "7c9ef71c69527b78e151abb3a0830da34e93ca80", + "commit": "2ed814241fd6a51f9dfeb2e71a5e39db91cd50d7", "path": "sdk-ts/src/amp-source.ts", "sha256": "e04b19806ce728976feb4a8f06fc84ac54a101255b29c2f45ebfad4c5d9d5853" } From da055ad8b9ad07b763d859d06906be3c03f8203c Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 09:43:56 -0800 Subject: [PATCH 3/5] fix(mcp): make inbox degradation observable --- src/mcp/capabilities.ts | 2 +- src/mcp/relay-participants.ts | 12 +++++++--- test/mcp.test.ts | 44 ++++++++++++++++++++++++++++++++--- 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/src/mcp/capabilities.ts b/src/mcp/capabilities.ts index 33b2b954..2f5f99a8 100644 --- a/src/mcp/capabilities.ts +++ b/src/mcp/capabilities.ts @@ -17,7 +17,7 @@ export function registerCapabilityDiscovery(server: McpServer, context: McpConte options: { nativeStatus?: () => Promise } = {}): void { server.registerTool(CAPABILITY_DISCOVERY_TOOL, { title: "Describe this connection's capabilities", - description: "Use when an expected Agent Relay capability is missing or an operation is refused. Returns this MCP connection's endpoint, authentication mode, granted scopes, current workspace role and tool groups; unavailable or restricted groups include the exact reason and enablement requirements. Read-only.", + description: "Use when an expected Agent Relay capability is missing or an operation is refused. Returns this MCP connection's endpoint, authentication mode, granted scopes, current workspace role and tool groups. A group can remain available for directory reads while actor-dependent calls appear in restricted_tools as { name, reason }; unavailable or fully restricted groups include the exact reason and enablement requirements. Read-only.", inputSchema: {}, annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, }, async () => { diff --git a/src/mcp/relay-participants.ts b/src/mcp/relay-participants.ts index 56310436..9adb68f1 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 inboxSenderEnrichmentFailed = (error: unknown) => { + console.warn("[selfhost-mcp] inbox sender enrichment failed", { + operation: "check_relay_inbox", 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."; @@ -1539,8 +1544,9 @@ function createRelayService(context: McpContext) { const hosted = await participant(as); if (!hosted) throw new RelayToolError("No hosted participant is bound to this MCP session. Send a message with send_relay_message to auto-join, or call join_relay first."); await touchPresence(hosted); - // Every fallible read finishes before any acknowledgement, so a failed - // enrichment leaves the deliveries pending for a retry. + // Required inbox and conversation reads finish before acknowledgement. + // Sender-address enrichment is optional and bounded: failure is logged + // and returned as a null address without failing the delivery read. const via = clientFor(hosted); const dir = directory(hosted); const [messages, conversations] = await Promise.all([ @@ -1550,7 +1556,7 @@ function createRelayService(context: McpContext) { const senders = [...new Set(messages.flatMap(message => message.sender ? [message.sender] : []))]; const agents = senders.length ? (await dir.via.findAgentsByNames(dir.credential, senders, { signal: AbortSignal.timeout(INBOX_SENDER_LOOKUP_TIMEOUT_MS), - }).catch(() => [])).filter(isListedRelayAgent) : []; + }).catch(error => { inboxSenderEnrichmentFailed(error); return []; })).filter(isListedRelayAgent) : []; const addresses = new Map(agents.map(agent => [agent.name, agent.address])); const channelNames = new Map(); if (messages.some(isChannelDelivery)) { diff --git a/test/mcp.test.ts b/test/mcp.test.ts index 35123f0b..e254f59f 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -150,8 +150,8 @@ type RelaycastCall = { path: string; authorization: string | null }; /** Relaycast served through the injected messaging fetch: roster and presence, and the relay world. */ function fakeRelaycast(state: { agents: unknown[]; presence: unknown[] | "fail"; calls: RelaycastCall[]; world: RelaycastWorld; - /** The bounded `names` lookup: "fail" answers 503; "roster" plays an older engine that ignores `names`. */ - namesLookup?: "fail" | "roster"; + /** The bounded `names` lookup: "fail" answers 503; "hang" waits for abort; "roster" ignores `names`. */ + namesLookup?: "fail" | "hang" | "roster"; }): typeof fetch { return (async (input: string | URL | Request, init?: RequestInit) => { const url = new URL(String(input instanceof Request ? input.url : input)); @@ -164,6 +164,13 @@ function fakeRelaycast(state: { if (url.pathname === "/v1/agents" && (init?.method ?? "GET") === "GET") { const names = url.searchParams.getAll("names"); if (state.namesLookup === "fail" && names.length) return json(503, { ok: false, error: { code: "unavailable" } }); + if (state.namesLookup === "hang" && names.length) { + return await new Promise((_resolve, reject) => { + const aborted = () => reject(init?.signal?.reason ?? new DOMException("Aborted", "AbortError")); + if (init?.signal?.aborted) aborted(); + else init?.signal?.addEventListener("abort", aborted, { once: true }); + }); + } if (names.length === 0 || state.namesLookup === "roster") return json(200, { ok: true, data: state.agents }); // The engine's bounded lookup: only the requested names. return json(200, { ok: true, data: state.agents.filter(row => names.includes((row as { name?: string }).name ?? "")) }); @@ -186,7 +193,7 @@ async function setup(t: TestContext, telemetry?: TelemetryModule) { const history = await startHistory(t); const agents: unknown[] = []; const relay = { agents, presence: [] as unknown[] | "fail", calls: [] as RelaycastCall[], world: createRelaycastWorld(agents), - namesLookup: undefined as "fail" | "roster" | undefined }; + namesLookup: undefined as "fail" | "hang" | "roster" | undefined }; const database = new PGliteDatabase(); await migrate(database); const config: SelfhostConfig = { @@ -341,6 +348,8 @@ test("initialize advertises the self-host server and its tools on both paths", a "subscribe_relay_channel", "unsubscribe_relay_channel", ]); + assert.match(tools.find(tool => tool.name === "describe_capabilities")?.description ?? "", + /restricted_tools as \{ name, reason \}/); for (const tool of tools) { assert.equal(typeof tool.title, "string", tool.name); assert.equal(tool._meta, undefined, tool.name); @@ -1629,9 +1638,38 @@ test("check_relay_inbox delivers messages with null sender addresses when bounde structured(await client.callTool({ name: "join_relay", arguments: { name: "owner-inbox" } })); env.relay.world.sendAs("peer-a", "owner-inbox", "from a"); env.relay.namesLookup = "fail"; + const warnings: unknown[][] = []; + t.mock.method(console, "warn", (...args: unknown[]) => warnings.push(args)); const inbox = structured(await client.callTool({ name: "check_relay_inbox", arguments: {} })); assert.deepEqual(inbox.messages.map((message: any) => ({ sender: message.sender, sender_address: message.sender_address })), [{ sender: "peer-a", sender_address: null }]); + assert.deepEqual(warnings, [["[selfhost-mcp] inbox sender enrichment failed", + { operation: "check_relay_inbox", error: "RelaycastCallError" }]]); +}); + +test("check_relay_inbox times out sender enrichment and acknowledges the delivery once on the following call", async (t) => { + const env = await setup(t); + env.relay.world.addAgent("peer-a"); + const client = await relayClient(t, env); + structured(await client.callTool({ name: "join_relay", arguments: { name: "owner-inbox" } })); + env.relay.world.sendAs("peer-a", "owner-inbox", "from a"); + env.relay.namesLookup = "hang"; + const warnings: unknown[][] = []; + t.mock.method(console, "warn", (...args: unknown[]) => warnings.push(args)); + const started = Date.now(); + const inbox = structured(await client.callTool({ name: "check_relay_inbox", arguments: {} })); + assert(Date.now() - started < 2_500, "sender enrichment stays within its one-second budget"); + assert.equal(inbox.messages[0].sender_address, null); + const deliveryId = inbox.messages[0].delivery_id as string; + assert.deepEqual(env.relay.world.pending("owner-inbox").map(row => row.id), [deliveryId]); + assert.equal(warnings[0]?.[0], "[selfhost-mcp] inbox sender enrichment failed"); + assert.equal((warnings[0]?.[1] as Record)?.operation, "check_relay_inbox"); + + env.relay.namesLookup = undefined; + const acknowledged = structured(await client.callTool({ name: "check_relay_inbox", arguments: { acknowledge: [deliveryId] } })); + assert.deepEqual(acknowledged.acknowledged, [deliveryId]); + assert.deepEqual(env.relay.world.pending("owner-inbox"), []); + assert.equal(env.relay.world.bodies.filter(call => call.path === `/v1/deliveries/${deliveryId}/ack`).length, 1); }); type AuditRow = Record; From 3ac800d034a8c0bc139cf21520ba2d3c8494a6e5 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 09:48:01 -0800 Subject: [PATCH 4/5] chore(ci): retrigger exact-head checks From d761b0784809be80043391b724f6bb5c93ddcca0 Mon Sep 17 00:00:00 2001 From: khaliqgant Date: Thu, 19 Nov 2026 11:14:21 -0800 Subject: [PATCH 5/5] chore(amp): pin landed RelayHistory source --- src/amp/provider-origin.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/amp/provider-origin.json b/src/amp/provider-origin.json index d7170c26..d18b121c 100644 --- a/src/amp/provider-origin.json +++ b/src/amp/provider-origin.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/AgentWorkforce/relayhistory", - "commit": "2ed814241fd6a51f9dfeb2e71a5e39db91cd50d7", + "commit": "703d9f115a31551e70a9f7207be1ede9fe2f0c74", "path": "sdk-ts/src/amp-source.ts", "sha256": "e04b19806ce728976feb4a8f06fc84ac54a101255b29c2f45ebfad4c5d9d5853" }