Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ assigned at release.
- 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 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.
- Fixed: MCP `list_relay_agents` now bounds its upstream roster read at 10 seconds, `describe_capabilities` bounds managed native-identity verification at 2 seconds, and `relay_status` bounds optional exact-name address enrichment at 1 second while returning the status with a null address on lookup failure or timeout.
- 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-<hash>` 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
Expand Down
10 changes: 7 additions & 3 deletions src/mcp/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { CAPABILITY_DISCOVERY_TOOL, describeCapabilities } from "./catalog.js";
import type { McpContext } from "./context.js";
import { RelayToolError, relayService } from "./relay-participants.js";
import { withinRelayRead } from "./team-activity.js";

const NATIVE_CHECK_RETRY_REASON = "Agent Relay could not check this chat's synced Desktop identity right now. Retry describe_capabilities.";
const NATIVE_CHECK_RETRY_GUIDANCE = "Retry shortly. If the check keeps failing, ask the operator to verify Relay and database health.";
const NATIVE_CAPABILITY_CHECK_TIMEOUT_MS = 2_000;

/**
* describe_capabilities, ported from Cloud's
Expand All @@ -14,7 +16,7 @@ const NATIVE_CHECK_RETRY_GUIDANCE = "Retry shortly. If the check keeps failing,
* one it cannot use. Read-only; the role was read at admission.
*/
export function registerCapabilityDiscovery(server: McpServer, context: McpContext,
options: { nativeStatus?: () => Promise<unknown> } = {}): void {
options: { nativeStatus?: () => Promise<unknown>; nativeTimeoutMs?: number } = {}): 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. 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.",
Expand All @@ -29,8 +31,10 @@ export function registerCapabilityDiscovery(server: McpServer, context: McpConte
// identity would add a database and Relay round trip without changing the report.
if (managed && context.authMode !== "staff_read_grant") {
try {
if (options.nativeStatus) await options.nativeStatus();
else await relayService(context).status();
await withinRelayRead(
() => options.nativeStatus ? options.nativeStatus() : relayService(context).status(),
options.nativeTimeoutMs ?? NATIVE_CAPABILITY_CHECK_TIMEOUT_MS,
);
nativeAuthorityAvailable = true;
} catch (error) {
nativeAuthorityAvailable = false;
Expand Down
23 changes: 20 additions & 3 deletions src/mcp/relay-participants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
type DesktopIdentityRow, type LinkedDesktopIdentity,
} from "../messaging/desktop-identities.js";
import type { McpContext, McpMember } from "./context.js";
import { isListedRelayAgent, rosterAgent } from "./team-activity.js";
import { isListedRelayAgent, rosterAgent, ROSTER_TIMEOUT_MS, withinRelayRead } from "./team-activity.js";
import { buildAgentCard, cardMetadata, cardSummary, recipientCard, type SetCardInput } from "./relay-agent-cards.js";
import { loadRelayAgentOwners, relayAgentOwnerTarget } from "./relay-agent-owners.js";
import { McpOAuthAccessRefused, McpOAuthActorRefused } from "./oauth/admission.js";
Expand Down Expand Up @@ -80,6 +80,11 @@ const inboxSenderEnrichmentFailed = (error: unknown) => {
operation: "check_relay_inbox", error: error instanceof Error ? error.name : "unknown",
});
};
const relayStatusAddressEnrichmentFailed = (error: unknown) => {
console.warn("[selfhost-mcp] relay status address enrichment failed", {
operation: "relay_status", 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",
Expand Down Expand Up @@ -115,6 +120,7 @@ const DESKTOP_LINK_NEEDS_SESSION = "Initialize MCP to receive Mcp-Session-Id bef
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 RELAY_STATUS_LOOKUP_TIMEOUT_MS = 1_000;
const CHANNEL_REPLY_GUIDANCE = "Reply to a post in this channel with post_relay_channel channel=<name> thread_id=<message_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}$/;
Expand Down Expand Up @@ -739,7 +745,10 @@ function createRelayService(context: McpContext) {
}

async function listedAgents(status: "active" | "all", includeStale = false, dir: Directory = directory()) {
return (await dir.via.listAgents(dir.credential, status, { includeStale })).filter(isListedRelayAgent);
return (await withinRelayRead(
signal => dir.via.listAgents(dir.credential, status, { includeStale, signal }),
ROSTER_TIMEOUT_MS,
)).filter(isListedRelayAgent);
}

const syncedSessionKinds = new Set(["codex", "grok", "pi", "opencode", "claude", "copilot", "cursor"]);
Expand Down Expand Up @@ -1584,7 +1593,15 @@ function createRelayService(context: McpContext) {
...(cursor ? { cursor_identity: cursor } : {}),
guidance: "Send a message with send_relay_message to auto-join this MCP session, or call join_relay first." };
await touchPresence(hosted);
const [address, inbox] = await Promise.all([addressFor(hosted.name, false, directory(hosted)), clientFor(hosted).readHostedInbox(hosted.token)]);
const dir = directory(hosted);
const [agents, inbox] = await Promise.all([
withinRelayRead(
signal => dir.via.findAgentsByNames(dir.credential, [hosted.name], { signal }),
RELAY_STATUS_LOOKUP_TIMEOUT_MS,
).catch(error => { relayStatusAddressEnrichmentFailed(error); return []; }),
clientFor(hosted).readHostedInbox(hosted.token),
]);
const address = agents.find(agent => agent.name === hosted.name && isListedRelayAgent(agent))?.address ?? null;
return { joined: true, linked: "hosted" as const, name: hosted.name, address,
unread_count: inbox.length, unread_count_is_lower_bound: inbox.length === 100,
...(cursor && !await ownRun(as) ? { cursor_identity: cursor } : {}) };
Expand Down
10 changes: 5 additions & 5 deletions src/mcp/team-activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { assertEventScope, boundedContent, buildDirectEventsPath, resolveWorkspa
const MAX_CONTENT_LENGTH = 4_000;
const ROSTER_UNAVAILABLE = "Workspace relay roster is temporarily unavailable. Please try again.";
/** Bound on the Relaycast roster read; without the roster the tool fails. */
const ROSTER_TIMEOUT_MS = 10_000;
export const ROSTER_TIMEOUT_MS = 10_000;
/**
* Bound on the Relaycast presence read. Presence is optional, so a stalled
* presence service gives way early and the roster is returned without it.
Expand All @@ -35,7 +35,7 @@ export type TeamActivityLimits = { rosterTimeoutMs?: number; presenceTimeoutMs?:
* Run `read` with a signal aborted after `ms`, and stop waiting then even if
* the read ignores the signal. A late result or rejection is dropped.
*/
function within<T>(read: (signal: AbortSignal) => Promise<T>, ms: number): Promise<T> {
export function withinRelayRead<T>(read: (signal: AbortSignal) => Promise<T>, ms: number): Promise<T> {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
Expand Down Expand Up @@ -205,9 +205,9 @@ async function readTeam(
context: McpContext, status: "live" | "all", rosterTimeoutMs: number, presenceTimeoutMs: number,
): Promise<{ agents: TeamAgent[]; presenceAvailable: boolean }> {
const [rosterResult, presenceResult, people] = await Promise.all([
Promise.allSettled([within(signal => context.relaycast.listAgents(status === "live" ? "active" : "all", { signal }), rosterTimeoutMs)])
Promise.allSettled([withinRelayRead(signal => context.relaycast.listAgents(status === "live" ? "active" : "all", { signal }), rosterTimeoutMs)])
.then(([result]) => result!),
Promise.allSettled([within(signal => context.relaycast.listPresence({ signal }), presenceTimeoutMs)]).then(([result]) => result!),
Promise.allSettled([withinRelayRead(signal => context.relaycast.listPresence({ signal }), presenceTimeoutMs)]).then(([result]) => result!),
context.members(),
]);
if (rosterResult.status === "rejected") {
Expand Down Expand Up @@ -335,7 +335,7 @@ export async function readTeamActivity(
await Promise.all(candidates.slice(i, i + 5).map(async ({ key, sessionId, source }) => {
try {
// A read still pending at the deadline is unavailable; its late answer is dropped.
const parsed = SessionEventsPageSchema.safeParse(await within(() => context.readHistory(
const parsed = SessionEventsPageSchema.safeParse(await withinRelayRead(() => context.readHistory(
buildDirectEventsPath(sessionId, { source, limit: 1, order: "desc", maxContent: input.max_content })), remaining));
if (!parsed.success || parsed.data.sessionId !== sessionId) {
throw new SharedSessionsToolError("Unsupported session response.");
Expand Down
50 changes: 47 additions & 3 deletions test/mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,9 @@ function fakeRelaycast(state: {
agents: unknown[]; presence: unknown[] | "fail"; calls: RelaycastCall[]; world: RelaycastWorld;
/** The bounded `names` lookup: "fail" answers 503; "hang" waits for abort; "roster" ignores `names`. */
namesLookup?: "fail" | "hang" | "roster";
/** A deliberately non-cooperative full-roster read, used to prove the outer MCP deadline. */
rosterLookup?: "hang";
rosterSignal?: AbortSignal;
}): typeof fetch {
return (async (input: string | URL | Request, init?: RequestInit) => {
const url = new URL(String(input instanceof Request ? input.url : input));
Expand All @@ -163,6 +166,10 @@ function fakeRelaycast(state: {
});
if (url.pathname === "/v1/agents" && (init?.method ?? "GET") === "GET") {
const names = url.searchParams.getAll("names");
if (state.rosterLookup === "hang" && names.length === 0) {
state.rosterSignal = init?.signal ?? undefined;
return await new Promise<Response>(() => {});
}
if (state.namesLookup === "fail" && names.length) return json(503, { ok: false, error: { code: "unavailable" } });
if (state.namesLookup === "hang" && names.length) {
return await new Promise<Response>((_resolve, reject) => {
Expand Down Expand Up @@ -193,7 +200,8 @@ 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" | "hang" | "roster" | undefined };
namesLookup: undefined as "fail" | "hang" | "roster" | undefined,
rosterLookup: undefined as "hang" | undefined, rosterSignal: undefined as AbortSignal | undefined };
const database = new PGliteDatabase();
await migrate(database);
const config: SelfhostConfig = {
Expand Down Expand Up @@ -552,11 +560,11 @@ test("the capability handler preserves safe refusals, distinguishes outages, and
endpointUrl: "https://relay.example.test/mcp", authMode: "cli_login", role: "owner",
principal: { scopes: ["cli:auth"] }, workspace: { id: "workspace" }, providers: async () => [],
};
async function call(required: boolean, nativeStatus: () => Promise<unknown>, authMode = "cli_login") {
async function call(required: boolean, nativeStatus: () => Promise<unknown>, authMode = "cli_login", nativeTimeoutMs?: number) {
let handler: (() => Promise<{ structuredContent: Record<string, unknown> }>) | undefined;
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 });
{ nativeStatus, nativeTimeoutMs });
return (await handler!()).structuredContent as { groups: Array<{ id: string; status: string; reason?: string; how_to_enable?: string;
restricted_tools?: Array<{ name: string; reason: string }> }> };
}
Expand All @@ -578,6 +586,12 @@ test("the capability handler preserves safe refusals, distinguishes outages, and
assert.doesNotMatch(unavailableReason, /private outage details|reconnect/i);
assert.deepEqual(warnings, [["[selfhost-mcp] native identity capability check failed", { error: "Error" }]]);

const timedOut = await call(true, () => new Promise(() => {}), "cli_login", 5);
const timeoutReason = timedOut.groups.find(group => group.id === "relay_messaging")?.restricted_tools
?.find(tool => tool.name === "send_relay_message")?.reason ?? "";
assert.match(timeoutReason, /could not check.*right now/i);
assert.deepEqual(warnings.at(-1), ["[selfhost-mcp] native identity capability check failed", { error: "Error" }]);

const available = await call(true, async () => { checks += 1; });
assert.equal(checks, 3);
assert.equal(available.groups.find(group => group.id === "relay_messaging")?.status, "available");
Expand Down Expand Up @@ -762,6 +776,25 @@ test("join_relay by name registers a hosted participant with Cloud's metadata",

const status = structured(await client.callTool({ name: "relay_status", arguments: {} }));
assert.deepEqual({ joined: status.joined, name: status.name, unread: status.unread_count }, { joined: true, name: "owner-helper", unread: 0 });
(remote.metadata as Record<string, unknown>).renamed_to = "owner-successor";
assert.equal(structured(await client.callTool({ name: "relay_status", arguments: {} })).address, null);
});

test("relay_status returns with a null address when its bounded exact-name lookup stalls", async (t) => {
const env = await setup(t);
const client = await relayClient(t, env);
structured(await client.callTool({ name: "join_relay", arguments: { name: "owner-status" } }));
env.relay.namesLookup = "hang";
const warnings: unknown[][] = [];
t.mock.method(console, "warn", (...args: unknown[]) => warnings.push(args));
const started = Date.now();
const status = structured(await client.callTool({ name: "relay_status", arguments: {} }));
assert(Date.now() - started < 2_500, "status address enrichment stays within its one-second budget");
assert.equal(status.joined, true);
assert.equal(status.name, "owner-status");
assert.equal(status.address, null);
assert.deepEqual(warnings, [["[selfhost-mcp] relay status address enrichment failed",
{ operation: "relay_status", error: "Error" }]]);
});

test("join_relay is idempotent, defaults its name, and refuses a foreign owner's agent", async (t) => {
Expand Down Expand Up @@ -886,6 +919,17 @@ test("every listed Desktop and spawned agent has an inferred card and trusted ow
assert.equal(env.relay.world.bodies.some(call => call.method === "PATCH"), false);
});

test("list_relay_agents stops waiting after ten seconds when the roster ignores cancellation", async (t) => {
const env = await setup(t);
const client = await relayClient(t, env);
env.relay.rosterLookup = "hang";
const started = Date.now();
assert.match(toolError(await client.callTool({ name: "list_relay_agents", arguments: { status: "all" } })),
/relay operation failed/i);
assert(Date.now() - started < 12_500, "the MCP roster read stays within its ten-second budget");
assert.equal(env.relay.rosterSignal?.aborted, true);
});

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) });
Expand Down
Loading