Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

A Team Cloud tells its admins how each connection is really doing (#5174)

Milind Soni523e70443eb4
diff --git a/docs/team-cloud.md b/docs/team-cloud.md
index 5d57f09c88..03834baa3a 100644
--- a/docs/team-cloud.md
+++ b/docs/team-cloud.md
@@ -171,6 +171,31 @@ this server shares with every bot. It exists only on a Team Cloud.
engines: [{ id, name, authenticated, account: { email, organization, method } | null }] } }` (`cloud-team-admin.ts`).
Names, states and the identities the providers report: never a key, a token, a header or environment value (`secrets`
are their names), nor any part of an MCP address but its host.
+- **How each connection is doing** (`server/host/connection-health-host.ts`, kept in `connection-health.json`). Each
+ `mcp` entry and each `apps.services` entry may also carry, every field absent when unknown (times ISO 8601):
+ `health` (`working` | `needs-sign-in` | `refused` | `unreachable`), `checkedAt` (when that was established),
+ `lastError` (a fixed class while it isn't working: `sign-in`, `expired`, `refresh-rejected`, `account-inactive`,
+ `refused`, `account-failed`, `cant-connect`, `timeout`, `not-found`, `bad-answer`; never what a server said),
+ `lastUsedAt` (the last real tool call on it), `addedBy` (`{ email, name }`, `name` null when they set none) with
+ `addedAt` (recorded from when this was built, so older connections have none), and `bots` (the names of the team bots
+ that use it; each member's own MausBot is left out). An `mcp` entry adds `expiresAt` for a sign-in that expires and
+ that nothing can refresh, and each app account adds `health`, its status word as one of the four (`ACTIVE` working,
+ `FAILED` refused, `EXPIRED`, `INACTIVE` and an unfinished connection needs-sign-in).
+ - **Real use decides it.** A tool call that works marks it working. One a server refuses with HTTP 401 on a sign-in
+ gets the sign-in refreshed at once: refused for good, or nothing can refresh it, and the sign-in ends (the app shows
+ it signed out, here and on a personal install or My Cloud, which take the same path); a key refused, or a 403, is
+ `refused`. A refresh refused as a turn starts is `needs-sign-in`. Not reaching a server (refused connection, timeout,
+ not found) is `unreachable` only once it happens twice in a row. An app call is read from its own error words only.
+ An app whose accounts all say they are not active shows that, whatever the last call did.
+ - **The background check.** A team server nothing used or checked for a day is tested once, as Test does it, at most
+ one about every hour (jittered, the first a quarter hour after start). It never runs while the machine has agreed
+ to sleep, starts no request to it, and a check the machine slept through is dropped. Apps aren't checked in the
+ background: the read itself asks the connected-apps service for each account's status.
+ - **Each person's own.** A connection each person connects has no `health` or `lastUsedAt` of its own; instead
+ `people.states` is `{ apps: { <slug>: { <address>: state } }, mcp: { <name>: { <address>: state } } }`, with
+ `state` `connected` | `needs-sign-in` | `not-connected`, for every member the Admin paired here and only for those
+ connections: whether they connected what an admin asked everyone to connect, never when or how they used it, nor
+ any other connection of theirs. A member who left is not listed.
- Changes are never signed calls of their own. The Admin pairs as the admin making the change (the usual signed pairing
with their `member` claim: an `owner` or `admin` gets the admin scope) and uses that session with the routes the app
uses: `PATCH /api/config` for a key, `/api/mcp/servers` to add, test, sign in to and remove a server,
diff --git a/server/cloud-team-admin.e2e.test.ts b/server/cloud-team-admin.e2e.test.ts
index 1fa6122075..bbb64bb7bd 100644
--- a/server/cloud-team-admin.e2e.test.ts
+++ b/server/cloud-team-admin.e2e.test.ts
@@ -39,6 +39,7 @@ if (process.argv[2] === "auth") {
console.log(JSON.stringify({ loggedIn: true, email: "[email protected]" }));
process.exit(0);
}
+process.env.FAKE_CLAUDE_TOOL_CALLS_FILE = ${JSON.stringify(join(home, "tool-calls.json"))};
await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-claude-cli.ts")).href)});
`, { mode: 0o755 });
writeFileSync(join(dataDir, "config.json"), JSON.stringify({
@@ -86,7 +87,7 @@ it("the Admin reads a Team Cloud's shared connections and AI by a signed request
summary = (await signed("GET", CLOUD_TEAM_ADMIN_PATH)).body;
return summary?.ai?.engines?.find((engine: { id: string }) => engine.id === "claude")?.authenticated;
}, { timeout: 20_000, interval: 200 }).toBe(true);
- expect(summary.mcp).toEqual([{ name: "linear", transport: "http", host: "mcp.linear.app", enabled: true, signedIn: null, secrets: ["Authorization"] }]);
+ expect(summary.mcp).toEqual([{ name: "linear", transport: "http", host: "mcp.linear.app", enabled: true, signedIn: null, secrets: ["Authorization"], bots: expect.any(Array) }]);
expect(summary.keys.find((key: { id: string }) => key.id === "treg")).toEqual({ id: "treg", configured: true });
expect(summary.ai.engines.find((engine: { id: string }) => engine.id === "claude")).toMatchObject({ name: "Claude", authenticated: true, account: { email: "[email protected]" } });
expect(JSON.stringify(summary)).not.toMatch(/never-shown|token=|Bearer/);
@@ -122,3 +123,31 @@ it("an Owner or Admin's paired session (as the Admin holds one) sets a team key
const settings = await admin("GET", "/api/config");
expect([settings.status, settings.body.language]).toEqual([200, "de"]);
}, 30_000);
+
+it("the signed read says who added a server, which bots use it and how it is doing, from the bots' own tool calls", async () => {
+ const session = async (role: string) => {
+ const granted = await signed("POST", "/api/cloud/pairing", JSON.stringify({ label: "Team admin (MausBot Cloud)", ttlSeconds: 300, team: TEAM, member: { email: `${role}@acme.test`, role } }));
+ const token = (await call("POST", "/api/auth/pair", { body: JSON.stringify({ code: granted.body.code }), headers: { "content-type": "application/json" } })).body.token as string;
+ return (method: string, path: string, body?: unknown) => call(method, path, { ...(body === undefined ? {} : { body: JSON.stringify(body) }), headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) } });
+ };
+ const admin = await session("admin");
+ expect((await admin("POST", "/api/mcp/servers", { name: "tracker", type: "http", url: "https://tracker.example/mcp?token=query-never-shown", headers: { "X-Api-Key": "key-never-shown" } })).status).toBe(201);
+ const created = await admin("POST", "/api/bots", { name: "Scout" });
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ const bot = created.body.bot as { id: string; mainThreadId: string };
+ expect((await admin("PATCH", "/api/mcp/servers/tracker", { enabled: true })).status).toBe(200);
+ expect((await admin("PATCH", `/api/bots/${bot.id}`, { mcpServers: ["tracker"] })).status).toBe(200);
+ const tracker = async () => ((await signed("GET", CLOUD_TEAM_ADMIN_PATH)).body.mcp as Array<Record<string, unknown>>).find((server) => server.name === "tracker")!;
+ expect(await tracker()).toMatchObject({ addedBy: { email: "[email protected]", name: null }, addedAt: expect.any(String), bots: expect.arrayContaining(["Scout"]) });
+ expect(await tracker()).not.toHaveProperty("health");
+ const turn = async (calls: unknown[], until: (server: Record<string, unknown>) => boolean) => {
+ writeFileSync(join(home, "tool-calls.json"), JSON.stringify(calls));
+ expect((await admin("POST", `/api/bots/${bot.id}/messages`, { text: "Look at the tracker.", threadId: bot.mainThreadId })).status).toBe(202);
+ await expect.poll(async () => until(await tracker()), { timeout: 30_000, interval: 200 }).toBe(true);
+ };
+ await turn([{ name: "mcp__tracker__list_issues", ok: false, output: "HTTP 401 dialing https://tracker.example/mcp" }], (server) => server.health === "refused");
+ expect(await tracker()).toMatchObject({ health: "refused", lastError: "refused", checkedAt: expect.any(String), lastUsedAt: expect.any(String) });
+ await turn([{ name: "mcp__tracker__list_issues", ok: true, output: "[]" }], (server) => server.health === "working");
+ const summary = (await signed("GET", CLOUD_TEAM_ADMIN_PATH)).body;
+ expect(JSON.stringify(summary)).not.toMatch(/never-shown|token=/);
+}, 90_000);
diff --git a/server/cloud-team-admin.ts b/server/cloud-team-admin.ts
index 0dc844e356..3e720ea0cf 100644
--- a/server/cloud-team-admin.ts
+++ b/server/cloud-team-admin.ts
@@ -6,12 +6,38 @@ import type { ProviderSnapshot } from "./contracts.ts";
export const CLOUD_TEAM_ADMIN_PATH = "/api/cloud/team/admin";
+/** One of the four words a connection's health is (server/connection-health.ts). */
+export type ConnectionHealthWord = "working" | "needs-sign-in" | "refused" | "unreachable";
+
+/** How the team's connection is doing and where it came from. Every field is absent when unknown: a connection nothing
+ * used, checked or recorded since this was built has none. Times are ISO 8601. */
+export interface ConnectionStatus {
+ /** From real use (tool calls, token refreshes, Test) and a rare background check; for an app, its accounts' own status
+ * when that says it is not working. Absent for a connection each person connects (see `people.states`). */
+ health?: ConnectionHealthWord;
+ /** When `health` was last established. */
+ checkedAt?: string;
+ /** Why it is not working, as a fixed class (connection-health.ts FAILURE_CLASSES): never what a server said. */
+ lastError?: string;
+ /** The last real tool call on it, whatever its outcome. Absent for a connection each person connects. */
+ lastUsedAt?: string;
+ /** The admin who added it, by address and the name they go by on the team (null when they set none). */
+ addedBy?: { email: string; name: string | null };
+ addedAt?: string;
+ /** The team bots that use it (each member's own MausBot is left out). */
+ bots?: string[];
+}
+
+export type PersonConnectionState = "connected" | "needs-sign-in" | "not-connected";
+
/** The wire shape of `GET /api/cloud/team/admin` (signed by the Admin). */
export interface TeamAdminSummary {
v: 1;
- /** Connected apps (Composio). `available: false`: connected apps are off or unreadable here; `services` is then empty. */
- apps: { available: boolean; services: { slug: string; status: string; accounts: { id: string; alias: string | null; status: string }[] }[] };
- mcp: { name: string; transport: "http" | "sse" | "stdio"; host: string | null; enabled: boolean; signedIn: boolean | null; secrets: string[] }[];
+ /** Connected apps (Composio). `available: false`: connected apps are off or unreadable here; `services` is then empty.
+ * An account's `health` is its status word as one of the four (none for a word not known). */
+ apps: { available: boolean; services: ({ slug: string; status: string; accounts: { id: string; alias: string | null; status: string; health?: ConnectionHealthWord }[] } & ConnectionStatus)[] };
+ /** `expiresAt`: when the server's sign-in ends for good, for a sign-in that expires and that nothing can refresh. */
+ mcp: ({ name: string; transport: "http" | "sse" | "stdio"; host: string | null; enabled: boolean; signedIn: boolean | null; secrets: string[]; expiresAt?: string } & ConnectionStatus)[];
/** The team's own service keys, set or not: treg (X research) and voice (ElevenLabs). `included`: the Cloud's own voice
* serves the team while no key of its own is set. */
keys: { id: "treg" | "voice"; configured: boolean; included?: true }[];
@@ -21,8 +47,12 @@ export interface TeamAdminSummary {
};
/** The apps (slugs) and MCP servers each person connects for themselves; everything else is the team's. */
scopes?: { apps: string[]; mcp: string[] };
- /** Who has connected each of those: addresses only, never a key or token. */
- people?: { apps: Record<string, string[]>; mcp: Record<string, string[]> };
+ /** Who has connected each of those: addresses only, never a key or token. `states`: each member the Admin paired here,
+ * by address, for each of those only: whether they connected it, never what they did with it. */
+ people?: {
+ apps: Record<string, string[]>; mcp: Record<string, string[]>;
+ states?: { apps: Record<string, Record<string, PersonConnectionState>>; mcp: Record<string, Record<string, PersonConnectionState>> };
+ };
}
type ListedMcp = { name: string; enabled?: boolean; url?: string; type?: string; command?: string; headerKeys?: string[]; envKeys?: string[]; auth?: string };
diff --git a/server/cloud-team-connections.e2e.test.ts b/server/cloud-team-connections.e2e.test.ts
index 15ccce7e86..11d36c49d2 100644
--- a/server/cloud-team-connections.e2e.test.ts
+++ b/server/cloud-team-connections.e2e.test.ts
@@ -152,7 +152,8 @@ it("lets Ada connect her own Gmail and mail key, and nobody reads them back", as
// Admins see that she connected, never what with.
const read = await team.signed("GET", "/api/cloud/team/admin");
expect(read.body.scopes).toEqual({ apps: ["gmail"], mcp: ["mail"] });
- expect(read.body.people).toEqual({ apps: { gmail: [ADA.email] }, mcp: { mail: [ADA.email] } });
+ const states = Object.fromEntries([OWNER, ADMIN, ADA, CLEO].map((member) => [member.email, member === ADA ? "connected" : "not-connected"]));
+ expect(read.body.people).toEqual({ apps: { gmail: [ADA.email] }, mcp: { mail: [ADA.email] }, states: { apps: { gmail: states }, mcp: { mail: states } } });
const held = JSON.parse(readFileSync(join(team.home, ".openmausbot", "people-connections", "apps.json"), "utf8")).people[personKey({ id: "", email: ADA.email })].token as string;
for (const answer of [read.body, (await team.as(owner, "GET", "/api/mcp/servers")).body, (await team.as(admin, "GET", "/api/config")).body,
(await team.as(owner, "GET", "/api/connectors/connected")).body, (await team.as(admin, "GET", "/api/team/my-connections")).body]) {
diff --git a/server/connection-health-check.ts b/server/connection-health-check.ts
new file mode 100644
index 0000000000..80b86d2522
--- /dev/null
+++ b/server/connection-health-check.ts
@@ -0,0 +1,82 @@
+// The rare background check of connections nothing used lately, so "working" never rests on a week-old success. One
+// connection at a time, about once an hour (jittered), only one not used or checked for a day. It never runs while the
+// machine has agreed to sleep, and it starts no request to this machine, so it never wakes it: a timer only fires on a
+// machine that is already awake. A check the machine slept through is dropped, never taken for a server that is down.
+
+/** About this often a check may start; each wait is jittered by up to a quarter either way. */
+export const CHECK_EVERY_MS = 60 * 60_000;
+export const CHECK_JITTER = 0.25;
+/** A connection used or checked more recently than this is not checked. */
+export const STALE_MS = 24 * 60 * 60_000;
+/** The first check waits at least this long after start, so a boot or a wake is never spent on it. */
+export const FIRST_CHECK_MS = 15 * 60_000;
+
+export interface BackgroundCheckDeps<Ref, Outcome> {
+ /** The connections due a check (none used or checked within STALE_MS), the longest unchecked first. */
+ due(): Ref[];
+ check(ref: Ref, signal: AbortSignal): Promise<Outcome | null>;
+ record(ref: Ref, outcome: Outcome): void;
+ /** The machine agreed to sleep and has not woken since. */
+ asleep(): boolean;
+ /** When it last woke from sleep, if it ever did. */
+ wokeAt(): number | null;
+ now?(): number;
+ random?(): number;
+ setTimer?(run: () => void, ms: number): { cancel(): void };
+}
+
+export function jitteredWait(base: number, random: () => number): number {
+ return Math.round(base * (1 - CHECK_JITTER + 2 * CHECK_JITTER * random()));
+}
+
+export function createBackgroundCheck<Ref, Outcome>(deps: BackgroundCheckDeps<Ref, Outcome>) {
+ const now = deps.now ?? Date.now;
+ const random = deps.random ?? Math.random;
+ const setTimer = deps.setTimer ?? ((run, ms) => {
+ const timer = setTimeout(run, ms);
+ timer.unref?.();
+ return { cancel: () => clearTimeout(timer) };
+ });
+ let timer: { cancel(): void } | null = null;
+ let running: AbortController | null = null;
+ let stopped = true;
+
+ /** One check, if one is due and the machine is awake for it. Resolves with what was checked, or null. */
+ const tick = async (): Promise<Ref | null> => {
+ if (running || deps.asleep()) return null;
+ const ref = deps.due()[0];
+ if (ref === undefined) return null;
+ const startedAt = now();
+ running = new AbortController();
+ try {
+ const outcome = await deps.check(ref, running.signal).catch(() => null);
+ const woke = deps.wokeAt();
+ if (outcome === null || deps.asleep() || (woke !== null && woke >= startedAt) || running.signal.aborted) return null;
+ deps.record(ref, outcome);
+ return ref;
+ } finally {
+ running = null;
+ }
+ };
+ const schedule = (ms: number) => {
+ timer = setTimer(() => {
+ if (stopped) return;
+ void tick().finally(() => { if (!stopped) schedule(jitteredWait(CHECK_EVERY_MS, random)); });
+ }, ms);
+ };
+
+ return {
+ start(): void {
+ if (!stopped) return;
+ stopped = false;
+ schedule(FIRST_CHECK_MS + jitteredWait(CHECK_EVERY_MS, random));
+ },
+ stop(): void {
+ stopped = true;
+ timer?.cancel();
+ timer = null;
+ running?.abort();
+ },
+ tick,
+ };
+}
diff --git a/server/connection-health.test.ts b/server/connection-health.test.ts
new file mode 100644
index 0000000000..d3e2d8fe97
--- /dev/null
+++ b/server/connection-health.test.ts
@@ -0,0 +1,135 @@
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { CHECK_EVERY_MS, CHECK_JITTER, FIRST_CHECK_MS, createBackgroundCheck, jitteredWait } from "./connection-health-check.ts";
+import { accountHealth, createConnectionHealth, UNREACHABLE_AFTER } from "./connection-health.ts";
+import { appCallOutcome, probeOutcome } from "./connection-outcome.ts";
+
+const dirs: string[] = [];
+const temp = () => { const dir = mkdtempSync(join(tmpdir(), "omb-health-")); dirs.push(dir); return dir; };
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+describe("a connection's health", () => {
+ it("moves with each outcome: refused and signed out at once, unreachable only once it repeats, working on any success", () => {
+ let at = 1_000;
+ const file = join(temp(), "health.json");
+ const health = createConnectionHealth({ file, now: () => at });
+ const ref = { kind: "mcp" as const, id: "tracker" };
+ expect(health.observe(ref, { ok: true }, { use: true })).toBe("working");
+ at = 2_000;
+ expect(health.observe(ref, { ok: false, error: "cant-connect" }, { use: true })).toBe("working");
+ expect(health.get(ref)).toEqual({ health: "working", checkedAt: 1_000, lastUsedAt: 2_000 });
+ at = 3_000;
+ for (let miss = 1; miss < UNREACHABLE_AFTER; miss += 1) health.observe(ref, { ok: false, error: "timeout" });
+ expect(health.get(ref)).toMatchObject({ health: "unreachable", checkedAt: 3_000, lastError: "timeout" });
+ at = 4_000;
+ expect(health.observe(ref, { ok: true })).toBe("working");
+ expect(health.get(ref)).toEqual({ health: "working", checkedAt: 4_000, lastUsedAt: 2_000 });
+ expect(health.observe(ref, { ok: false, error: "sign-in" })).toBe("needs-sign-in");
+ expect(health.observe(ref, { ok: false, error: "refused" })).toBe("refused");
+ expect(health.get(ref).lastError).toBe("refused");
+ // One miss after a refusal leaves it refused; a reconnect clears what was known.
+ expect(health.observe(ref, { ok: false, error: "cant-connect" })).toBe("refused");
+ health.reset(ref);
+ expect(health.get(ref)).toEqual({ lastUsedAt: 2_000 });
+ health.flush();
+ expect(JSON.parse(readFileSync(file, "utf8")).connections["mcp:tracker"]).toMatchObject({ usedAt: 2_000 });
+ });
+
+ it("keeps each member's own apart from the team's, forgets a removed connection and a member who left", () => {
+ const file = join(temp(), "health.json");
+ const health = createConnectionHealth({ file, now: () => 5 });
+ health.observe({ kind: "app", id: "gmail" }, { ok: true });
+ health.observe({ kind: "app", id: "gmail", person: "p_ada" }, { ok: false, error: "sign-in" });
+ health.added("app", "gmail", "[email protected]");
+ expect(health.get({ kind: "app", id: "gmail" }).health).toBe("working");
+ expect(health.get({ kind: "app", id: "gmail", person: "p_ada" }).health).toBe("needs-sign-in");
+ expect(health.addedBy("app", "gmail")).toEqual({ email: "[email protected]", at: 5 });
+ health.forgetPerson("p_ada");
+ expect(health.get({ kind: "app", id: "gmail", person: "p_ada" })).toEqual({});
+ health.forget("app", "gmail");
+ expect([health.get({ kind: "app", id: "gmail" }), health.addedBy("app", "gmail"), health.known("app")]).toEqual([{}, undefined, []]);
+ });
+
+ it("reads a connected-apps account's status word as one of the four", () => {
+ expect(["ACTIVE", "EXPIRED", "INITIATED", "FAILED", "SOMETHING"].map((word) => accountHealth(word)?.health ?? null))
+ .toEqual(["working", "needs-sign-in", "needs-sign-in", "refused", null]);
+ });
+});
+
+describe("what a call shows", () => {
+ const answer = (text: string, isError = false) => new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { isError, content: [{ type: "text", text }] } }));
+ it("reads only a failed app call's own error, never what the tool returned", () => {
+ expect(appCallOutcome(200, answer(JSON.stringify({ successful: true, data: { body: "Unauthorized access to the vault, 401" } })), "application/json")).toEqual({ ok: true });
+ expect(appCallOutcome(200, answer(JSON.stringify({ successful: false, error: "Connected account is not active" })), "application/json")).toEqual({ ok: false, error: "sign-in" });
+ expect(appCallOutcome(200, answer(JSON.stringify({ data: { results: [{ response: { successful: false, error: "403 Forbidden: insufficient scope" } }] } })), "application/json")).toEqual({ ok: false, error: "refused" });
+ expect(appCallOutcome(200, answer(JSON.stringify({ successful: false, error: "Message not found" })), "application/json")).toEqual({ ok: true });
+ const sse = `event: message\ndata: ${new TextDecoder().decode(answer("Token has expired, reconnect", true))}\n\n`;
+ expect(appCallOutcome(200, new TextEncoder().encode(sse), "text/event-stream")).toEqual({ ok: false, error: "sign-in" });
+ expect(appCallOutcome(502, new Uint8Array(), "application/json")).toEqual({ ok: false, error: "cant-connect" });
+ expect(appCallOutcome(403, new Uint8Array(), "application/json")).toBeNull();
+ });
+ it("reads Test's answer", () => {
+ expect([
+ probeOutcome({ ok: true, tools: [] }), probeOutcome({ ok: false, error: "x", auth: "required" }), probeOutcome({ ok: false, error: "x", reason: "keys" }),
+ probeOutcome({ ok: false, error: "x", reason: "unreachable" }), probeOutcome({ ok: false, error: "x" }),
+ ]).toEqual([{ ok: true }, { ok: false, error: "sign-in" }, { ok: false, error: "refused" }, { ok: false, error: "cant-connect" }, { ok: false, error: "bad-answer" }]);
+ });
+});
+
+describe("the background check", () => {
+ const setup = (overrides: { due?: string[]; asleep?: () => boolean; wokeAt?: () => number | null; check?: () => Promise<string | null> } = {}) => {
+ let at = 0;
+ const checked: string[] = [], recorded: Array<[string, string]> = [], timers: number[] = [];
+ let pending: (() => void) | null = null;
+ const check = createBackgroundCheck<string, string>({
+ due: () => overrides.due ?? ["tracker", "notion"],
+ check: async (ref) => { checked.push(ref); return overrides.check ? overrides.check() : "ok"; },
+ record: (ref, outcome) => recorded.push([ref, outcome]),
+ asleep: overrides.asleep ?? (() => false),
+ wokeAt: overrides.wokeAt ?? (() => null),
+ now: () => at,
+ random: () => 1,
+ setTimer: (run, ms) => { timers.push(ms); pending = run; return { cancel: () => { pending = null; } }; },
+ });
+ return { check, checked, recorded, timers, advance: (ms: number) => { at += ms; }, fire: () => pending?.() };
+ };
+
+ it("waits at least a quarter hour after start, jittered, and checks one connection a time", async () => {
+ const run = setup();
+ run.check.start();
+ expect(run.timers[0]).toBe(FIRST_CHECK_MS + CHECK_EVERY_MS * (1 + CHECK_JITTER));
+ for (const random of [0, 0.5, 1]) {
+ const wait = jitteredWait(CHECK_EVERY_MS, () => random);
+ expect(wait).toBeGreaterThanOrEqual(CHECK_EVERY_MS * (1 - CHECK_JITTER));
+ expect(wait).toBeLessThanOrEqual(CHECK_EVERY_MS * (1 + CHECK_JITTER));
+ }
+ await run.check.tick();
+ expect([run.checked, run.recorded]).toEqual([["tracker"], [["tracker", "ok"]]]);
+ run.check.stop();
+ });
+
+ it("never checks while asleep, nor with nothing due, and drops a check the machine slept through", async () => {
+ const asleep = setup({ asleep: () => true });
+ expect(await asleep.check.tick()).toBeNull();
+ expect(asleep.checked).toEqual([]);
+ const nothing = setup({ due: [] });
+ expect(await nothing.check.tick()).toBeNull();
+ let woke: number | null = null;
+ const slept = setup({ wokeAt: () => woke, check: async () => { woke = 0; return "unreachable"; } });
+ expect(await slept.check.tick()).toBeNull();
+ expect([slept.checked, slept.recorded]).toEqual([["tracker"], []]);
+ });
+
+ it("starts no second check while one runs", async () => {
+ let release!: () => void;
+ const run = setup({ check: () => new Promise((resolve) => { release = () => resolve("ok"); }) });
+ const first = run.check.tick();
+ expect(await run.check.tick()).toBeNull();
+ release();
+ expect(await first).toBe("tracker");
+ expect(run.checked).toEqual(["tracker"]);
+ });
+});
diff --git a/server/connection-health.ts b/server/connection-health.ts
new file mode 100644
index 0000000000..efd830d183
--- /dev/null
+++ b/server/connection-health.ts
@@ -0,0 +1,171 @@
+// Whether each connection a Team Cloud's bots use works, as real use shows it: every tool call, token refresh and Test
+// moves it, and a rare background check (connection-health-check.ts) keeps one nothing used lately from resting on an old
+// success. Who added a connection and when are kept beside it, from the time this was built.
+// Security invariant: only fixed classes, times and the address of the admin who added a connection are kept or answered;
+// never a key, token, header value, address or anything a server or tool said.
+import { readFileSync } from "node:fs";
+import { z } from "zod";
+
+import { writeFileAtomic } from "./atomic.ts";
+
+export const CONNECTION_HEALTH_FILE = "connection-health.json";
+
+export const HEALTH_STATES = ["working", "needs-sign-in", "refused", "unreachable"] as const;
+export type ConnectionHealthState = typeof HEALTH_STATES[number];
+
+/** Why a connection is not working, as a fixed class. */
+export const FAILURE_CLASSES = [
+ "sign-in", "expired", "refresh-rejected", "account-inactive",
+ "refused", "account-failed",
+ "cant-connect", "timeout", "not-found", "bad-answer",
+] as const;
+export type ConnectionFailure = typeof FAILURE_CLASSES[number];
+
+const SIGNED_OUT: ReadonlySet<ConnectionFailure> = new Set(["sign-in", "expired", "refresh-rejected", "account-inactive"]);
+const REFUSED: ReadonlySet<ConnectionFailure> = new Set(["refused", "account-failed"]);
+/** A failure to reach a connection counts only once it repeats: one dropped call is not a server that is down. */
+export const UNREACHABLE_AFTER = 2;
+
+export type ConnectionKind = "app" | "mcp";
+/** A connection, the team's or, with `person`, one member's own (a person key). */
+export interface ConnectionRef { kind: ConnectionKind; id: string; person?: string }
+export type ConnectionOutcome = { ok: true } | { ok: false; error: ConnectionFailure };
+
+export const healthOf = (error: ConnectionFailure): ConnectionHealthState | null =>
+ SIGNED_OUT.has(error) ? "needs-sign-in" : REFUSED.has(error) ? "refused" : null;
+
+/** A connected-apps account's own status word, as one of the four. Unknown words have none. */
+export function accountHealth(status: string): { health: ConnectionHealthState; error?: ConnectionFailure } | null {
+ const word = status.trim().toUpperCase();
+ if (word === "ACTIVE") return { health: "working" };
+ if (word === "FAILED") return { health: "refused", error: "account-failed" };
+ if (["EXPIRED", "INACTIVE", "INITIATED", "INITIALIZING", "PENDING", "REVOKED", "DISABLED"].includes(word)) return { health: "needs-sign-in", error: "account-inactive" };
+ return null;
+}
+
+const failureSchema = z.enum(FAILURE_CLASSES);
+const keptSchema = z.object({
+ health: z.enum(HEALTH_STATES).optional(),
+ checkedAt: z.number().optional(),
+ lastError: failureSchema.optional(),
+ usedAt: z.number().optional(),
+ misses: z.number().int().nonnegative().optional(),
+ missError: failureSchema.optional(),
+});
+const fileSchema = z.object({
+ v: z.literal(1),
+ connections: z.record(z.string(), keptSchema).default({}),
+ people: z.record(z.string(), z.record(z.string(), keptSchema)).default({}),
+ added: z.record(z.string(), z.object({ email: z.string().max(320), at: z.number() })).default({}),
+});
+type Kept = z.infer<typeof keptSchema>;
+type HealthFile = z.infer<typeof fileSchema>;
+
+export interface ConnectionHealthView {
+ health?: ConnectionHealthState;
+ checkedAt?: number;
+ lastError?: ConnectionFailure;
+ lastUsedAt?: number;
+}
+
+const key = (kind: ConnectionKind, id: string) => `${kind}:${id}`;
+
+export function createConnectionHealth(options: { file: string; now?: () => number; saveDelayMs?: number }) {
+ const now = options.now ?? Date.now;
+ let data: HealthFile = { v: 1, connections: {}, people: {}, added: {} };
+ try { data = fileSchema.parse(JSON.parse(readFileSync(options.file, "utf8"))); } catch {}
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const flush = () => {
+ if (timer) { clearTimeout(timer); timer = null; }
+ try { writeFileAtomic(options.file, `${JSON.stringify(data)}\n`, { mode: 0o600 }); } catch (error) {
+ console.warn(`connection health: could not save: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ };
+ const save = () => {
+ if (timer) return;
+ timer = setTimeout(flush, options.saveDelayMs ?? 2_000);
+ timer.unref?.();
+ };
+ const slot = (ref: ConnectionRef, create: boolean): Kept | undefined => {
+ const k = key(ref.kind, ref.id);
+ if (!ref.person) return create ? (data.connections[k] ??= {}) : data.connections[k];
+ const own = create ? (data.people[ref.person] ??= {}) : data.people[ref.person];
+ return own ? (create ? (own[k] ??= {}) : own[k]) : undefined;
+ };
+
+ return {
+ /** What a call, refresh or check showed. `use`: a real call (it moves lastUsedAt); a check or a refresh doesn't. */
+ observe(ref: ConnectionRef, outcome: ConnectionOutcome, options: { use?: boolean } = {}): ConnectionHealthState | undefined {
+ const kept = slot(ref, true)!;
+ const at = now();
+ if (options.use) kept.usedAt = at;
+ if (outcome.ok) {
+ Object.assign(kept, { health: "working", checkedAt: at });
+ delete kept.lastError; delete kept.misses; delete kept.missError;
+ } else {
+ const decided = healthOf(outcome.error);
+ if (decided) {
+ Object.assign(kept, { health: decided, checkedAt: at, lastError: outcome.error });
+ delete kept.misses; delete kept.missError;
+ } else {
+ kept.misses = (kept.misses ?? 0) + 1;
+ kept.missError = outcome.error;
+ if (kept.misses >= UNREACHABLE_AFTER) Object.assign(kept, { health: "unreachable", checkedAt: at, lastError: outcome.error });
+ }
+ }
+ save();
+ return kept.health;
+ },
+ /** A real call whose outcome says nothing about the connection. */
+ used(ref: ConnectionRef): void {
+ slot(ref, true)!.usedAt = now();
+ save();
+ },
+ /** It was connected again: what was known about the old connection no longer holds. */
+ reset(ref: ConnectionRef): void {
+ const kept = slot(ref, false);
+ if (!kept) return;
+ for (const field of ["health", "checkedAt", "lastError", "misses", "missError"] as const) delete kept[field];
+ save();
+ },
+ get(ref: ConnectionRef): ConnectionHealthView {
+ const kept = slot(ref, false);
+ if (!kept) return {};
+ return {
+ ...(kept.health ? { health: kept.health, checkedAt: kept.checkedAt } : {}),
+ ...(kept.health && kept.health !== "working" && kept.lastError ? { lastError: kept.lastError } : {}),
+ ...(kept.usedAt ? { lastUsedAt: kept.usedAt } : {}),
+ };
+ },
+ /** An admin added the team's connection just now: who and when. Kept until it is removed. */
+ added(kind: ConnectionKind, id: string, email: string): void {
+ data.added[key(kind, id)] = { email: email.trim().toLowerCase(), at: now() };
+ save();
+ },
+ /** Who added it, when that was recorded. */
+ addedBy(kind: ConnectionKind, id: string): { email: string; at: number } | undefined {
+ return data.added[key(kind, id)];
+ },
+ /** It was removed: its health, every member's own, and who added it go. */
+ forget(kind: ConnectionKind, id: string): void {
+ const k = key(kind, id);
+ delete data.connections[k];
+ delete data.added[k];
+ for (const own of Object.values(data.people)) delete own[k];
+ save();
+ },
+ /** The connections ever seen of a kind, by id: to drop what is gone. */
+ known(kind: ConnectionKind): string[] {
+ const prefix = `${kind}:`;
+ return [...new Set([...Object.keys(data.connections), ...Object.keys(data.added)].filter((k) => k.startsWith(prefix)).map((k) => k.slice(prefix.length)))];
+ },
+ /** A member left: everything kept about them goes. */
+ forgetPerson(person: string): void {
+ delete data.people[person];
+ save();
+ },
+ flush,
+ };
+}
+
+export type ConnectionHealth = ReturnType<typeof createConnectionHealth>;
diff --git a/server/connection-outcome.ts b/server/connection-outcome.ts
new file mode 100644
index 0000000000..429bad6567
--- /dev/null
+++ b/server/connection-outcome.ts
@@ -0,0 +1,75 @@
+// What a call on a connection showed about it, as connection-health.ts reads outcomes. Only the class is kept: nothing a
+// server, an app or a tool said leaves these functions.
+import type { ConnectionFailure, ConnectionOutcome } from "./connection-health.ts";
+import type { McpFailureKind } from "./mcp-failure.ts";
+import type { McpProbeResult } from "./mcp-probe.ts";
+
+export const MCP_FAILURE_CLASS: Readonly<Record<McpFailureKind, ConnectionFailure>> = {
+ "sign-in": "sign-in", refused: "refused", "not-found": "not-found", timeout: "timeout", "cant-connect": "cant-connect",
+};
+
+/** A refused call names HTTP 403 (permission), not 401 (credentials): only a 401 means the sign-in itself was refused. */
+export const forbidsRatherThanSignsOut = (output: string) => /\b(?:HTTP )?403\b/.test(output.split("\n", 1)[0] ?? "");
+
+/** What Test or the background check found. */
+export function probeOutcome(result: McpProbeResult): ConnectionOutcome {
+ if (result.ok) return { ok: true };
+ if (result.auth === "required") return { ok: false, error: "sign-in" };
+ if (result.reason === "keys") return { ok: false, error: "refused" };
+ if (result.reason === "timeout") return { ok: false, error: "timeout" };
+ if (result.reason === "unreachable") return { ok: false, error: "cant-connect" };
+ return { ok: false, error: "bad-answer" };
+}
+
+/** How the connected-apps service and the apps behind it word an account that needs connecting again, or one refused. */
+const SIGNED_OUT = /\b401\b|unauthori[sz]ed|unauthenticated|invalid[_ ](?:grant|token|credentials)|(?:token|credentials?|connection|account)\s+(?:has\s+(?:been\s+)?|is\s+|was\s+)?(?:expired|revoked)|expired\s+(?:token|credentials?|connection|account)|(?:connected account|connection)\s+(?:is\s+)?(?:not active|inactive|not found)|re-?authori[sz]|reconnect|no (?:active )?connected account/i;
+const REFUSED = /\b403\b|forbidden|insufficient[_ ](?:scope|permission)s?|permission denied|access denied/i;
+const MAX_READ = 262_144;
+
+function frameOf(text: string, contentType: string): unknown {
+ if (!contentType.includes("text/event-stream")) {
+ try { return JSON.parse(text); } catch { return null; }
+ }
+ for (const line of text.split("\n").reverse()) {
+ if (!line.startsWith("data:")) continue;
+ try {
+ const frame = JSON.parse(line.slice(5)) as { id?: unknown };
+ if (frame && typeof frame === "object" && frame.id !== undefined) return frame;
+ } catch {}
+ }
+ return null;
+}
+
+/** Every `error` beside `successful: false` in a tool's answer (the connected-apps service's result shape), a few levels deep. */
+function failedErrors(value: unknown, depth = 0, out: string[] = []): string[] {
+ if (depth > 5 || !value || typeof value !== "object") return out;
+ if (Array.isArray(value)) { for (const item of value.slice(0, 50)) failedErrors(item, depth + 1, out); return out; }
+ const record = value as Record<string, unknown>;
+ if (record.successful === false || record.success === false) out.push(typeof record.error === "string" ? record.error : JSON.stringify(record.error ?? ""));
+ for (const child of Object.values(record)) if (child && typeof child === "object") failedErrors(child, depth + 1, out);
+ return out;
+}
+
+const classify = (text: string): ConnectionOutcome | null =>
+ SIGNED_OUT.test(text) ? { ok: false, error: "sign-in" } : REFUSED.test(text) ? { ok: false, error: "refused" } : null;
+
+/** What a connected-apps tool call's answer through the relay showed: the account works, needs connecting again or was
+ * refused, or the service could not be reached. Null: it says nothing about the account. A tool's own error (a message
+ * not found) is the account working. Only a failed call's own error words are read, never what the tool returned. */
+export function appCallOutcome(status: number, bytes: Uint8Array, contentType: string): ConnectionOutcome | null {
+ if (status === 0 || status >= 500) return { ok: false, error: "cant-connect" };
+ if (status < 200 || status >= 300) return null;
+ const frame = frameOf(Buffer.from(bytes.subarray(0, MAX_READ)).toString("utf8"), contentType) as { result?: { isError?: unknown; content?: unknown }; error?: unknown } | null;
+ if (!frame || typeof frame !== "object" || frame.error !== undefined || !frame.result) return null;
+ const texts = Array.isArray(frame.result.content)
+ ? frame.result.content.flatMap((item: { type?: unknown; text?: unknown }) => (item?.type === "text" && typeof item.text === "string" ? [item.text] : []))
+ : [];
+ const errors: string[] = [];
+ let parsed = false;
+ for (const text of texts) {
+ try { failedErrors(JSON.parse(text), 0, errors); parsed = true; } catch {}
+ }
+ if (!parsed && frame.result.isError === true) errors.push(...texts);
+ if (!errors.length) return { ok: true };
+ return classify(errors.join("\n").slice(0, 4_000)) ?? { ok: true };
+}
diff --git a/server/host/connection-health-host.test.ts b/server/host/connection-health-host.test.ts
new file mode 100644
index 0000000000..382a179f67
--- /dev/null
+++ b/server/host/connection-health-host.test.ts
@@ -0,0 +1,219 @@
+// The host as a Team Cloud runs it: a real sign-in store and a fake authorization server on loopback. No real service is
+// called and HOME is a temporary folder.
+import { createServer, type Server } from "node:http";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+
+import type { TeamAdminSummary } from "../cloud-team-admin.ts";
+import { McpOAuthManager } from "../mcp-oauth.ts";
+import { createConnectionHealthHost, type ConnectionHealthHostDeps } from "./connection-health-host.ts";
+
+let root = "", tokenUrl = "", answer: { status: number; body: Record<string, unknown> } = { status: 200, body: {} };
+let tokenServer: Server;
+const realHome = process.env.HOME;
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), "omb-health-host-"));
+ process.env.HOME = join(root, "home");
+ tokenServer = createServer((req, res) => {
+ req.resume();
+ req.on("end", () => res.writeHead(answer.status, { "content-type": "application/json" }).end(JSON.stringify(answer.body)));
+ });
+ await new Promise<void>((resolve) => tokenServer.listen(0, "127.0.0.1", resolve));
+ const address = tokenServer.address();
+ tokenUrl = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}/token`;
+});
+afterAll(async () => {
+ process.env.HOME = realHome;
+ await new Promise<void>((resolve) => tokenServer.close(() => resolve()));
+ rmSync(root, { recursive: true, force: true });
+});
+
+const TRACKER = "https://tracker.example/mcp?token=query-never-shown";
+const NOTES = "https://notes.example/mcp";
+const servers = {
+ tracker: { type: "http", url: TRACKER, headers: {} },
+ flaky: { type: "http", url: "https://flaky.example/mcp", headers: { "X-Api-Key": "key-never-shown" } },
+ notes: { type: "http", url: NOTES, headers: {} },
+};
+const ROSTER = [{ email: "[email protected]" }, { email: "[email protected]" }, { email: "[email protected]" }];
+const keyOf = (email: string) => `p_${email.split("@")[0]}`;
+const signIn = (manager: McpOAuthManager, name: string, url: string, tokens: { access: string; refresh?: string; expiresAt?: number }) =>
+ manager.adopt(name, url, { url, state: "signed-in", clientId: "client-1", tokenEndpoint: tokenUrl, tokens });
+
+let dir = "", host: ReturnType<typeof createConnectionHealthHost>, teamOAuth: McpOAuthManager, own: Record<string, McpOAuthManager>;
+let ownApps: Array<{ person: string; email: string; services: Record<string, { connected: boolean; pending: boolean; status: string; accounts: { id: string; status: string }[] }> | null }>;
+let turnPerson: string | null;
+const START = Date.parse("2026-11-10T10:00:00Z");
+let now = START;
+
+beforeEach(() => {
+ now = START;
+ dir = mkdtempSync(join(root, "data-"));
+ turnPerson = null;
+ ownApps = [];
+ const refreshed: Array<(person: string | null, name: string, outcome: Parameters<NonNullable<ConstructorParameters<typeof McpOAuthManager>[0]["onRefresh"]>>[1]) => void> = [];
+ teamOAuth = new McpOAuthManager({ file: join(dir, "mcp-oauth.json"), onRefresh: (name, outcome) => refreshed[0]?.(null, name, outcome) });
+ own = Object.fromEntries(ROSTER.map(({ email }) => [keyOf(email), new McpOAuthManager({ file: join(dir, `${keyOf(email)}.json`), onRefresh: (name, outcome) => refreshed[0]?.(keyOf(email), name, outcome) })]));
+ const deps: ConnectionHealthHostDeps<{ name: string; servers: string[]; hidden?: boolean; defaultBot?: { person?: string }; connectorScopes?: { apps: Record<string, unknown> } }> = {
+ dataDir: dir,
+ mcpServers: () => servers,
+ mcpOAuth: teamOAuth,
+ connections: {
+ personMcp: () => ["notes"], personApps: () => ["gmail"], turnPerson: () => turnPerson,
+ ownAppsServices: async () => ownApps,
+ people: { oauth: (person) => own[person]!, key: () => null, appsAccess: () => null },
+ },
+ bots: () => [
+ { name: "Scout", servers: ["tracker", "flaky"] },
+ { name: "Clerk", servers: ["tracker"], connectorScopes: { apps: { slack: "read" } } },
+ { name: "Old", servers: ["tracker"], hidden: true },
+ { name: "MausBot", servers: ["tracker"], defaultBot: { person: "[email protected]" } },
+ ],
+ botServers: (bot) => bot.servers,
+ roster: () => ROSTER,
+ personKey: keyOf,
+ personName: (email) => (email === "[email protected]" ? "Olive" : null),
+ asleep: () => false, wokeAt: () => null,
+ now: () => now,
+ };
+ host = createConnectionHealthHost(deps);
+ refreshed.push(host.refreshed);
+});
+
+const summary = (): TeamAdminSummary => ({
+ v: 1,
+ apps: { available: true, services: [{ slug: "slack", status: "ACTIVE", accounts: [{ id: "ca_1", alias: null, status: "ACTIVE" }] }, { slug: "github", status: "EXPIRED", accounts: [{ id: "ca_2", alias: null, status: "EXPIRED" }] }] },
+ mcp: Object.entries(servers).map(([name, server]) => ({ name, transport: "http" as const, host: new URL(server.url).host, enabled: true,
+ signedIn: teamOAuth.authState(name, server.url) === "none" ? null : teamOAuth.authState(name, server.url) === "signed-in", secrets: Object.keys(server.headers) })),
+ keys: [], ai: { keys: [], engines: [] },
+ scopes: { apps: ["gmail"], mcp: ["notes"] },
+ people: { apps: { gmail: [] }, mcp: { notes: [] } },
+});
+const read = async () => {
+ const out = await host.adminRead(summary());
+ return { out, mcp: Object.fromEntries(out.mcp.map((entry) => [entry.name, entry])), apps: Object.fromEntries(out.apps.services.map((entry) => [entry.slug, entry])) };
+};
+const step = (tool: string, ok: boolean, output?: string) => host.toolStep({ threadId: "t1", tool, ok, ...(output === undefined ? {} : { output }) });
+const REFUSED_401 = 'The MCP server "tracker" refused the sign-in or key it was sent (HTTP 401), so nothing ran.';
+
+describe("health from real calls", () => {
+ it("a 401 on a tool call renews the sign-in; when the server refuses the renewal, the sign-in ends and it needs a sign-in", async () => {
+ signIn(teamOAuth, "tracker", TRACKER, { access: "access-never-shown", refresh: "refresh-never-shown", expiresAt: now + 3_600_000 });
+ await step("mcp__tracker__list_issues", true, "[]");
+ expect((await read()).mcp.tracker).toMatchObject({ health: "working", lastUsedAt: "2026-11-10T10:00:00.000Z" });
+ answer = { status: 400, body: { error: "invalid_grant" } };
+ await step("mcp__tracker__list_issues", false, REFUSED_401);
+ expect(teamOAuth.authState("tracker", TRACKER)).toBe("needs-sign-in");
+ const { mcp, out } = await read();
+ expect(mcp.tracker).toMatchObject({ signedIn: false, health: "needs-sign-in", lastError: "sign-in" });
+ expect(JSON.stringify(out)).not.toMatch(/never-shown|token=|Bearer/);
+ });
+
+ it("a 401 the renewal fixes leaves it as it was, and the next call says how it is", async () => {
+ signIn(teamOAuth, "tracker", TRACKER, { access: "old-never-shown", refresh: "refresh-never-shown", expiresAt: now + 3_600_000 });
+ await step("mcp__tracker__list_issues", true, "[]");
+ answer = { status: 200, body: { access_token: "new-never-shown", expires_in: 3600 } };
+ await step("mcp__tracker__list_issues", false, REFUSED_401);
+ expect([teamOAuth.authState("tracker", TRACKER), await teamOAuth.accessToken("tracker", TRACKER)]).toEqual(["signed-in", "new-never-shown"]);
+ expect((await read()).mcp.tracker.health).toBe("working");
+ });
+
+ it("a refresh rejected as a turn starts marks it needs a sign-in", async () => {
+ signIn(teamOAuth, "tracker", TRACKER, { access: "a-never-shown", refresh: "r-never-shown", expiresAt: Date.now() - 1_000 });
+ answer = { status: 401, body: { error: "invalid_client" } };
+ expect(await teamOAuth.accessToken("tracker", TRACKER)).toBeNull();
+ expect((await read()).mcp.tracker).toMatchObject({ health: "needs-sign-in", lastError: "refresh-rejected" });
+ });
+
+ it("a key the server refuses is refused; a network failure counts once it repeats; a success after it is working", async () => {
+ await step("mcp__flaky__search", false, "HTTP 401 dialing https://flaky.example/mcp");
+ expect((await read()).mcp.flaky).toMatchObject({ health: "refused", lastError: "refused" });
+ await step("mcp__flaky__search", false, "ECONNREFUSED 127.0.0.1:443");
+ expect((await read()).mcp.flaky.health).toBe("refused");
+ now += 60_000;
+ await step("mcp__flaky__search", false, "Error: MCP error -32001: Request timed out");
+ expect((await read()).mcp.flaky).toMatchObject({ health: "unreachable", lastError: "timeout", checkedAt: "2026-11-10T10:01:00.000Z" });
+ now += 60_000;
+ await step("mcp__flaky__search", false, "thread not found");
+ expect((await read()).mcp.flaky).toEqual(expect.objectContaining({ health: "working", checkedAt: "2026-11-10T10:02:00.000Z", lastUsedAt: "2026-11-10T10:02:00.000Z" }));
+ expect((await read()).mcp.flaky.lastError).toBeUndefined();
+ });
+
+ it("an app call's failure and a provider's own status both show, normalised", async () => {
+ const reply = (text: string) => new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text }] } }));
+ host.appCall({ slugs: ["SLACK_SEND_MESSAGE"], status: 200, bytes: reply(JSON.stringify({ successful: false, error: "token_revoked: the token has been revoked" })), contentType: "application/json" });
+ const { apps } = await read();
+ expect(apps.slack).toMatchObject({ health: "needs-sign-in", lastError: "sign-in", lastUsedAt: "2026-11-10T10:00:00.000Z", accounts: [{ id: "ca_1", status: "ACTIVE", health: "working" }] });
+ expect(apps.github).toMatchObject({ health: "needs-sign-in", lastError: "account-inactive", accounts: [{ status: "EXPIRED", health: "needs-sign-in" }] });
+ host.appCall({ slugs: ["SLACK_SEND_MESSAGE"], status: 200, bytes: reply(JSON.stringify({ successful: true })), contentType: "application/json" });
+ expect((await read()).apps.slack.health).toBe("working");
+ });
+});
+
+describe("the admin read", () => {
+ it("says who added a connection and when, which team bots use it, and when a sign-in nothing can refresh ends", async () => {
+ host.added("mcp", "tracker", "[email protected]");
+ host.added("app", "slack", "[email protected]");
+ signIn(teamOAuth, "tracker", TRACKER, { access: "a-never-shown", expiresAt: now + 86_400_000 });
+ const { mcp, apps } = await read();
+ expect(mcp.tracker).toMatchObject({ addedBy: { email: "[email protected]", name: "Olive" }, addedAt: "2026-11-10T10:00:00.000Z", bots: ["Scout", "Clerk"], expiresAt: "2026-11-11T10:00:00.000Z" });
+ expect(mcp.flaky).toMatchObject({ bots: ["Scout"] });
+ expect(mcp.flaky.addedBy).toBeUndefined();
+ expect(apps.slack).toMatchObject({ addedBy: { email: "[email protected]", name: null }, bots: ["Scout", "Clerk"] });
+ expect(apps.github.bots).toEqual(["Scout"]);
+ teamOAuth.forget("tracker");
+ signIn(teamOAuth, "tracker", TRACKER, { access: "a-never-shown", expiresAt: now - 1 });
+ expect((await read()).mcp.tracker).toMatchObject({ health: "needs-sign-in", lastError: "expired" });
+ });
+
+ it("forgets what it kept about a connection once it is removed", async () => {
+ host.added("mcp", "tracker", "[email protected]");
+ host.removed("mcp", "tracker");
+ expect((await read()).mcp.tracker.addedBy).toBeUndefined();
+ });
+});
+
+describe("each person's own", () => {
+ it("states three members' own connections: connected, needs a sign-in, not connected", async () => {
+ signIn(own.p_ada!, "notes", NOTES, { access: "ada-never-shown" });
+ signIn(own.p_ben!, "notes", NOTES, { access: "ben-never-shown" });
+ own.p_ben!.markNeedsSignIn("notes", NOTES);
+ ownApps = [
+ { person: "p_ada", email: "[email protected]", services: { gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [{ id: "a", status: "ACTIVE" }] } } },
+ { person: "p_ben", email: "[email protected]", services: { gmail: { connected: false, pending: false, status: "EXPIRED", accounts: [{ id: "b", status: "EXPIRED" }] } } },
+ ];
+ const { out } = await read();
+ expect(out.people?.states).toEqual({
+ mcp: { notes: { "[email protected]": "connected", "[email protected]": "needs-sign-in", "[email protected]": "not-connected" } },
+ apps: { gmail: { "[email protected]": "connected", "[email protected]": "needs-sign-in", "[email protected]": "not-connected" } },
+ });
+ // Their own call refused: Ada needs to sign in again, and it says so.
+ turnPerson = "p_ada";
+ answer = { status: 400, body: { error: "invalid_grant" } };
+ await host.toolStep({ threadId: "ada-private", tool: "mcp__notes__search", ok: false, output: 'The MCP server "notes" needs a sign-in before its tools work (HTTP 401)' });
+ expect((await read()).out.people?.states?.mcp.notes?.["[email protected]"]).toBe("needs-sign-in");
+ });
+
+ it("says nothing about what a member did, a connection nobody asked them for, or someone not on the team", async () => {
+ signIn(own.p_ada!, "notes", NOTES, { access: "ada-never-shown" });
+ ownApps = [{ person: "p_ada", email: "[email protected]", services: {
+ gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [{ id: "a", status: "ACTIVE" }] },
+ dropbox: { connected: true, pending: false, status: "ACTIVE", accounts: [{ id: "d", status: "ACTIVE" }] },
+ } }, { person: "p_zed", email: "[email protected]", services: { gmail: { connected: true, pending: false, status: "ACTIVE", accounts: [] } } }];
+ turnPerson = "p_ada";
+ await host.toolStep({ threadId: "ada-private", tool: "mcp__notes__search", ok: true, output: "[]" });
+ host.appCall({ person: "p_ada", slugs: ["GMAIL_FETCH_EMAILS"], status: 200, bytes: new TextEncoder().encode(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: "{\"successful\":true}" }] } })), contentType: "application/json" });
+ // Not asked of everyone, so a turn that acts for nobody has no own server: nothing is kept.
+ turnPerson = null;
+ await host.toolStep({ threadId: "room", tool: "mcp__notes__search", ok: false, output: "ECONNREFUSED" });
+ const { out, mcp } = await read();
+ expect(Object.keys(out.people?.states?.apps ?? {})).toEqual(["gmail"]);
+ expect(Object.keys(out.people?.states?.apps.gmail ?? {})).toEqual(["[email protected]", "[email protected]", "[email protected]"]);
+ for (const field of ["health", "checkedAt", "lastError", "lastUsedAt", "expiresAt"]) expect(mcp.notes).not.toHaveProperty(field);
+ const text = JSON.stringify(out);
+ expect(text).not.toMatch(/dropbox|zed@|never-shown|ada-private/);
+ });
+});
diff --git a/server/host/connection-health-host.ts b/server/host/connection-health-host.ts
new file mode 100644
index 0000000000..ecb74680d2
--- /dev/null
+++ b/server/host/connection-health-host.ts
@@ -0,0 +1,290 @@
+// Feeds connection-health.ts from real use and answers what the Admin's signed read adds about each connection.
+// Everywhere: an MCP server that refuses a sign-in's token on a real call gets it refreshed at once, or the sign-in is
+// marked ended, so "signed in" stays true. On a Team Cloud also: each connection's health, who added it, the bots that
+// use it, and each member's own state for a connection each person connects.
+// Privacy (docs/team-cloud.md "private means private"): a member's own state says only whether they connected what an
+// admin asked everyone to connect: never when or how they used it, nor anything about a connection nobody asked for.
+import { join } from "node:path";
+
+import { type ConnectionHealthWord, type ConnectionStatus, type PersonConnectionState, type TeamAdminSummary } from "../cloud-team-admin.ts";
+import type { ConnectorServiceState } from "../composio.ts";
+import { STALE_MS, createBackgroundCheck } from "../connection-health-check.ts";
+import { CONNECTION_HEALTH_FILE, accountHealth, createConnectionHealth, type ConnectionHealthView, type ConnectionOutcome, type ConnectionRef } from "../connection-health.ts";
+import { MCP_FAILURE_CLASS, appCallOutcome, forbidsRatherThanSignsOut, probeOutcome } from "../connection-outcome.ts";
+import { serviceSlugFor } from "../connector-verdict.ts";
+import { mcpFailureKind, mcpServerOfTool } from "../mcp-failure.ts";
+import type { McpOAuthManager, McpRefreshOutcome } from "../mcp-oauth.ts";
+import type { McpProbeResult } from "../mcp-probe.ts";
+import { isRemoteMcpServer, parseStoredMcpServer } from "../mcp-registry.ts";
+import { personAppOf } from "../team-connections.ts";
+import type { McpConfigResult } from "./mcp-config.ts";
+import type { TeamConnectionsHost } from "./team-connections-host.ts";
+
+type Bot = {
+ name: string; hidden?: boolean; movedTo?: unknown; defaultBot?: { person?: string };
+ composio?: boolean; connectorTools?: Record<string, unknown>; connectorScopes?: { apps: Record<string, unknown> };
+};
+type OAuth = Pick<McpOAuthManager, "authState" | "tokenRefused" | "endsAt">;
+
+export interface ConnectionHealthHostDeps<B extends Bot = Bot> {
+ /** Where health is kept: a Team Cloud's data folder. Null elsewhere, where only the sign-in check runs. */
+ dataDir: string | null;
+ mcpServers(): Record<string, unknown>;
+ mcpOAuth: OAuth;
+ connections: Pick<TeamConnectionsHost, "personMcp" | "personApps" | "turnPerson" | "ownAppsServices"> & {
+ people: { oauth(person: string): OAuth; key(person: string, name: string, url: string): unknown; appsAccess(person: string): unknown };
+ };
+ bots(): readonly B[];
+ /** The MCP servers a bot's turns start, by name. */
+ botServers(bot: B): readonly string[];
+ /** The members the Admin paired here (team-people.json). */
+ roster(): ReadonlyArray<{ email: string }>;
+ personKey(email: string): string;
+ /** The name a member goes by on the team, if they set one. */
+ personName(email: string): string | null;
+ /** Test for the team's server, as the app's Test runs it. */
+ test?(name: string, signal: AbortSignal): Promise<McpConfigResult>;
+ asleep(): boolean;
+ wokeAt(): number | null;
+ now?(): number;
+}
+
+const iso = (ms: number | undefined) => (ms === undefined ? undefined : new Date(ms).toISOString());
+/** A connection whose app's account stays gone this long after it was added is taken for removed. */
+const ADD_PENDING_MS = 60 * 60_000;
+
+export function createConnectionHealthHost<B extends Bot>(deps: ConnectionHealthHostDeps<B>) {
+ const store = deps.dataDir === null ? null : createConnectionHealth({ file: join(deps.dataDir, CONNECTION_HEALTH_FILE), ...(deps.now ? { now: deps.now } : {}) });
+ const now = deps.now ?? Date.now;
+ const remote = (name: string) => {
+ const raw = deps.mcpServers()[name];
+ const parsed = raw === undefined ? null : parseStoredMcpServer(name, raw);
+ return parsed?.ok && isRemoteMcpServer(parsed.server) ? parsed.server : null;
+ };
+ const remoteUrl = (name: string): string | null => remote(name)?.url ?? null;
+ const oauthOf = (person: string | undefined) => (person ? deps.connections.people.oauth(person) : deps.mcpOAuth);
+
+ /** A server refused credentials: a sign-in's token is renewed or found ended; a key it was sent is refused. */
+ const refusedCredentials = async (ref: ConnectionRef, error: "sign-in" | "refused", firstLine: string): Promise<ConnectionOutcome | null> => {
+ const server = remote(ref.id);
+ if (!server) return { ok: false, error };
+ const oauth = oauthOf(ref.person);
+ if (oauth.authState(ref.id, server.url) !== "signed-in" || forbidsRatherThanSignsOut(firstLine)) {
+ const sentKey = ref.person ? deps.connections.people.key(ref.person, ref.id, server.url) !== null : Object.keys(server.headers).length > 0;
+ return { ok: false, error: sentKey ? "refused" : error };
+ }
+ const refusal = await oauth.tokenRefused(ref.id, server.url);
+ return refusal === "ended" ? { ok: false, error: "sign-in" } : refusal === "again" ? { ok: false, error: "refused" } : null;
+ };
+
+ const checkTeamServer = async (name: string, result: McpProbeResult): Promise<ConnectionOutcome | null> => {
+ const outcome = probeOutcome(result);
+ if (outcome.ok || outcome.error !== "refused") return outcome;
+ return refusedCredentials({ kind: "mcp", id: name }, "refused", result.ok ? "" : `HTTP ${result.status ?? ""}`);
+ };
+
+ const background = store && deps.test ? createBackgroundCheck<string, ConnectionOutcome>({
+ due: () => {
+ const personal = deps.connections.personMcp();
+ return Object.keys(deps.mcpServers()).flatMap((name) => {
+ const raw = deps.mcpServers()[name];
+ const parsed = parseStoredMcpServer(name, raw);
+ if (!parsed.ok || !isRemoteMcpServer(parsed.server) || !parsed.server.enabled || parsed.server.runsOn || personal.includes(name)) return [];
+ if (deps.mcpOAuth.authState(name, parsed.server.url) === "needs-sign-in") return [];
+ const view = store.get({ kind: "mcp", id: name });
+ const last = Math.max(view.lastUsedAt ?? 0, view.checkedAt ?? 0);
+ return now() - last >= STALE_MS ? [{ name, last }] : [];
+ }).sort((a, b) => a.last - b.last).map((entry) => entry.name);
+ },
+ check: async (name, signal) => {
+ const result = await deps.test!(name, signal);
+ return "body" in result ? checkTeamServer(name, result.body as McpProbeResult) : null;
+ },
+ record: (name, outcome) => { store.observe({ kind: "mcp", id: name }, outcome); },
+ asleep: deps.asleep,
+ wokeAt: deps.wokeAt,
+ now,
+ }) : null;
+
+ const teamBots = () => deps.bots().filter((bot) => !bot.hidden && !bot.movedTo && !bot.defaultBot?.person);
+ const usesApp = (bot: B, slug: string) => bot.composio !== false
+ && (!bot.connectorScopes || Object.hasOwn(bot.connectorScopes.apps, slug))
+ && (bot.connectorTools === undefined || Object.hasOwn(bot.connectorTools, slug));
+
+ const status = (view: ConnectionHealthView): ConnectionStatus => ({
+ ...(view.health ? { health: view.health, checkedAt: iso(view.checkedAt) } : {}),
+ ...(view.lastError ? { lastError: view.lastError } : {}),
+ ...(view.lastUsedAt ? { lastUsedAt: iso(view.lastUsedAt) } : {}),
+ });
+ const provenance = (kind: "app" | "mcp", id: string): Pick<ConnectionStatus, "addedBy" | "addedAt"> => {
+ const added = store?.addedBy(kind, id);
+ return added ? { addedBy: { email: added.email, name: deps.personName(added.email) }, addedAt: iso(added.at) } : {};
+ };
+ /** The team's MCP server's health, with what its stored sign-in says now. */
+ const mcpView = (name: string, signedIn: boolean | null, endsAt: number | null): ConnectionHealthView => {
+ const view = store?.get({ kind: "mcp", id: name }) ?? {};
+ if (endsAt !== null && endsAt <= now()) return { ...view, health: "needs-sign-in", checkedAt: endsAt, lastError: "expired" };
+ if (signedIn === false && view.health !== "needs-sign-in" && view.health !== "refused") return { ...view, health: "needs-sign-in", checkedAt: now(), lastError: "sign-in" };
+ return view;
+ };
+ /** The team's app's health: its accounts' own word when that says it is not working, else what real use showed. */
+ const appView = (slug: string, accounts: ReadonlyArray<{ status: string }>): ConnectionHealthView => {
+ const view = store?.get({ kind: "app", id: slug }) ?? {};
+ const words = accounts.map((account) => accountHealth(account.status)).filter((word) => word !== null);
+ if (words.some((word) => word.health === "working")) return view.health ? view : { ...view, health: "working", checkedAt: now() };
+ const first = words[0];
+ return first ? { ...view, health: first.health, checkedAt: now(), ...(first.error ? { lastError: first.error } : {}) } : view;
+ };
+ const ownState = (ref: ConnectionRef, connected: boolean, signedOut: boolean): PersonConnectionState => {
+ const health = store?.get(ref).health;
+ if (connected) return health === "needs-sign-in" || health === "refused" ? "needs-sign-in" : "connected";
+ return signedOut ? "needs-sign-in" : "not-connected";
+ };
+
+ /** Every member's own state for each connection each person connects, by address: only those, never another of theirs. */
+ const personStates = async (scopes: { apps: readonly string[]; mcp: readonly string[] }, members: ReadonlyArray<{ email: string }>) => {
+ const out: NonNullable<NonNullable<TeamAdminSummary["people"]>["states"]> = { apps: {}, mcp: {} };
+ for (const name of scopes.mcp) {
+ const url = remoteUrl(name);
+ out.mcp[name] = Object.fromEntries(members.map(({ email }) => {
+ const person = deps.personKey(email);
+ const signIn = url ? deps.connections.people.oauth(person).authState(name, url) : "none";
+ const key = url ? deps.connections.people.key(person, name, url) !== null : false;
+ return [email, ownState({ kind: "mcp", id: name, person }, signIn === "signed-in" || key, signIn === "needs-sign-in")];
+ }));
+ }
+ if (scopes.apps.length) {
+ const reads = new Map((await deps.connections.ownAppsServices()).map((read) => [read.person, read.services]));
+ for (const slug of scopes.apps) {
+ out.apps[slug] = Object.fromEntries(members.flatMap(({ email }) => {
+ const person = deps.personKey(email);
+ if (!reads.has(person)) return [[email, "not-connected" as const]];
+ const services: Record<string, ConnectorServiceState> | null = reads.get(person) ?? null;
+ if (!services) return [];
+ const service = services[slug];
+ return [[email, ownState({ kind: "app", id: slug, person }, Boolean(service?.connected), Boolean(service && !service.connected && service.accounts.length))]];
+ }));
+ }
+ }
+ return out;
+ };
+
+ return {
+ /** A finished tool step: when it was an MCP server's, what it showed about that server. */
+ async toolStep(step: { threadId: string; generation?: string; tool: string; ok?: boolean; output?: string }): Promise<void> {
+ if (step.ok === undefined) return;
+ const name = mcpServerOfTool(step.tool, Object.keys(deps.mcpServers()));
+ if (!name) return;
+ const personal = deps.connections.personMcp().includes(name);
+ const person = personal ? deps.connections.turnPerson(step.threadId, step.generation) : null;
+ if (personal && !person) return;
+ const ref: ConnectionRef = { kind: "mcp", id: name, ...(person ? { person } : {}) };
+ const kind = step.ok === false && step.output ? mcpFailureKind(step.output) : null;
+ if (step.ok === false && !step.output) return store?.used(ref);
+ if (!kind) return void store?.observe(ref, { ok: true }, { use: true });
+ const error = MCP_FAILURE_CLASS[kind];
+ const outcome = error === "sign-in" || error === "refused" ? await refusedCredentials(ref, error, step.output!) : { ok: false as const, error };
+ if (outcome) store?.observe(ref, outcome, { use: true });
+ else store?.used(ref);
+ },
+
+ /** A connected-apps call through the relay, the team's installation or (`person`) a member's own. */
+ appCall(call: { person?: string; slugs: readonly string[]; status: number; bytes: Uint8Array; contentType: string }): void {
+ if (!store) return;
+ const personApps = deps.connections.personApps();
+ const apps = [...new Set(call.slugs.map((slug) => (call.person ? personAppOf(slug, personApps) : null) ?? serviceSlugFor(slug)).filter((app): app is string => Boolean(app)))];
+ if (!apps.length) return;
+ const outcome = appCallOutcome(call.status, call.bytes, call.contentType);
+ for (const app of apps) {
+ const ref: ConnectionRef = { kind: "app", id: app, ...(call.person ? { person: call.person } : {}) };
+ if (!outcome || (!outcome.ok && apps.length > 1)) { store.used(ref); continue; }
+ store.observe(ref, outcome, { use: true });
+ }
+ },
+
+ /** How a refresh of the team's (`person` null) or a member's own sign-in ended. */
+ refreshed(person: string | null, name: string, outcome: McpRefreshOutcome): void {
+ if (outcome !== "rejected" && outcome !== "expired") return;
+ store?.observe({ kind: "mcp", id: name, ...(person ? { person } : {}) }, { ok: false, error: outcome === "rejected" ? "refresh-rejected" : "expired" });
+ },
+
+ /** Test on the team's server, pressed by an admin. */
+ async tested(name: string, result: McpProbeResult): Promise<void> {
+ if (!store || deps.connections.personMcp().includes(name)) return;
+ const outcome = await checkTeamServer(name, result);
+ if (outcome) store.observe({ kind: "mcp", id: name }, outcome);
+ },
+
+ /** An admin added the team's MCP server or started connecting an app (`email`: who, when known). */
+ added(kind: "app" | "mcp", id: string, email: string | null): void {
+ if (!store) return;
+ if (kind === "mcp") store.forget("mcp", id);
+ else store.reset({ kind, id });
+ if (email && (kind === "mcp" || !store.addedBy(kind, id))) store.added(kind, id, email);
+ },
+ removed(kind: "app" | "mcp", id: string): void { store?.forget(kind, id); },
+ /** The team's sign-in to a server succeeded, or a member connected their own again. */
+ connectedAgain(ref: ConnectionRef): void { store?.reset(ref); },
+ forgetPerson(person: string): void { store?.forgetPerson(person); },
+
+ /** The Admin's signed read, with each connection's health, origin, bots and use, and each member's own states. Drops
+ * what it kept about connections that are gone. */
+ async adminRead(summary: TeamAdminSummary): Promise<TeamAdminSummary> {
+ if (!store) return summary;
+ const configured = deps.mcpServers();
+ for (const id of store.known("mcp")) if (!Object.hasOwn(configured, id)) store.forget("mcp", id);
+ const scopes = summary.scopes ?? { apps: [], mcp: [] };
+ if (summary.apps.available) {
+ const listed = new Set(summary.apps.services.map((service) => service.slug));
+ for (const id of store.known("app")) {
+ const added = store.addedBy("app", id);
+ if (!listed.has(id) && !scopes.apps.includes(id) && (!added || now() - added.at >= ADD_PENDING_MS)) store.forget("app", id);
+ }
+ }
+ const bots = teamBots();
+ const servers = new Map(bots.map((bot) => [bot, deps.botServers(bot)]));
+ const members = deps.roster();
+ return {
+ ...summary,
+ apps: {
+ ...summary.apps,
+ services: summary.apps.services.map((service) => {
+ const shared = !scopes.apps.includes(service.slug);
+ return {
+ ...service,
+ accounts: service.accounts.map((account) => {
+ const word = accountHealth(account.status);
+ return word ? { ...account, health: word.health as ConnectionHealthWord } : account;
+ }),
+ ...(shared ? status(appView(service.slug, service.accounts)) : {}),
+ ...provenance("app", service.slug),
+ bots: bots.filter((bot) => usesApp(bot, service.slug)).map((bot) => bot.name),
+ };
+ }),
+ },
+ mcp: summary.mcp.map((server) => {
+ const shared = !scopes.mcp.includes(server.name);
+ const url = remoteUrl(server.name);
+ const endsAt = shared && url ? deps.mcpOAuth.endsAt(server.name, url) : null;
+ return {
+ ...server,
+ ...(endsAt !== null ? { expiresAt: iso(endsAt) } : {}),
+ ...(shared ? status(mcpView(server.name, server.signedIn, endsAt)) : {}),
+ ...provenance("mcp", server.name),
+ bots: bots.filter((bot) => servers.get(bot)!.includes(server.name)).map((bot) => bot.name),
+ };
+ }),
+ ...(summary.people ? {
+ people: { ...summary.people, states: await personStates(scopes, members) },
+ } : {}),
+ };
+ },
+
+ start(): void { background?.start(); },
+ stop(): void { background?.stop(); store?.flush(); },
+ /** Tests: one background check now. */
+ checkNow: () => background?.tick() ?? Promise.resolve(null),
+ };
+}
+
+export type ConnectionHealthHost = ReturnType<typeof createConnectionHealthHost>;
diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.ts
index 925aa03397..3b88555812 100644
--- a/server/host/team-connections-host.ts
+++ b/server/host/team-connections-host.ts
@@ -15,7 +15,7 @@ import type * as Composio from "../composio.ts";
import type { AppConfig } from "../config.ts";
import type { McpServerSpec } from "../contracts.ts";
import { serviceSlugFor } from "../connector-verdict.ts";
-import { type McpOAuthManager, type McpSignInPhase, withMcpSignIn, withoutPendingSignIn } from "../mcp-oauth.ts";
+import { type McpOAuthManager, type McpRefreshOutcome, type McpSignInPhase, withMcpSignIn, withoutPendingSignIn } from "../mcp-oauth.ts";
import { isRemoteMcpServer, parseStoredMcpServer } from "../mcp-registry.ts";
import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";
import { appLabel, ConnectionScopes, PeopleConnections, personAppOf, SCOPES_FILE, type BrokerAccess } from "../team-connections.ts";
@@ -48,6 +48,10 @@ export interface TeamConnectionsHostDeps {
/** Whether whoever started a member's sign-in (a session, or a chat's Sign in card) is still there to finish it. */
isOwnerLive(owner: string): boolean;
onSettled?(name: string, phase: McpSignInPhase, owner: string): void;
+ /** How each refresh of a member's own MCP sign-in ended. */
+ onRefresh?(person: string, name: string, outcome: McpRefreshOutcome): void;
+ /** A member signed in again, saved a key or started connecting an app of their own. */
+ onPersonChanged?(person: string, kind: "app" | "mcp", id: string): void;
/** The connected-apps service a member's own installation is made on; null: none here. */
brokerUrl(): string | null;
composio: Pick<typeof Composio, "configured" | "mcpIntegration" | "connectedServices" | "verifiedConnectedServiceSlugs" | "authorizeService" | "removeService">;
@@ -58,6 +62,8 @@ const list = (names: readonly string[]) => names.length <= 1 ? names.join("") :
/** How long a read of an installation's connected apps stands, how soon a failed first read is tried again, and how long a
* turn waits for an installation's first answer. */
const APPS_FRESH_MS = 60_000, APPS_RETRY_MS = 10_000, FIRST_APPS_WAIT_MS = 3_000;
+/** How long one read of every member's own apps serves the Admin's reads made together. */
+const OWN_APPS_READ_MS = 20_000;
export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
const team = deps.team;
@@ -74,6 +80,8 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
clients: (name, url) => { const server = teamServer(name); return server && isRemoteMcpServer(server) && server.url === url ? server.oauth : undefined; },
isOwnerLive: deps.isOwnerLive,
...(deps.onSettled ? { onSettled: deps.onSettled } : {}),
+ ...(deps.onRefresh ? { onRefresh: deps.onRefresh } : {}),
+ ...(deps.onPersonChanged ? { onChanged: deps.onPersonChanged } : {}),
});
const personApps = () => (team ? scopes.person("app") : []);
/** The apps connected for an installation, the team's or a member's own. A turn never waits on a refresh: what is known
@@ -99,6 +107,16 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
return tools.length ? { ...bridge, env: { ...bridge.env, [APP_TOOLS_ENV]: JSON.stringify(tools), [APP_TOOL_NAMES_ENV]: names } } : bridge;
};
const personMcp = () => (team ? scopes.person("mcp") : []);
+ let ownAppsRead: { at: number; read: Promise<Array<{ person: string; email: string; services: Record<string, Composio.ConnectorServiceState> | null }>> } | null = null;
+ /** Every member's own installation's apps (null where it could not be read), read once for reads close together. */
+ const ownAppsServices = () => {
+ if (!ownAppsRead || Date.now() - ownAppsRead.at >= OWN_APPS_READ_MS) {
+ ownAppsRead = { at: Date.now(), read: Promise.all(people.appsPeople().map(async ({ person, email, access }) => ({
+ person, email, services: await deps.composio.connectedServices(deps.cfg(), access).catch(() => null),
+ }))) };
+ }
+ return ownAppsRead.read;
+ };
const link = () => (team && deps.adminOrigin ? `${deps.adminOrigin}/cloud/team/${encodeURIComponent(team.id)}` : null);
const without = <T,>(servers: Record<string, T>, names: readonly string[]) =>
Object.fromEntries(Object.entries(servers).filter(([name]) => !names.includes(name)));
@@ -382,6 +400,7 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
return shared;
},
+ ownAppsServices,
/** A person who left the team (host/team-member-left.ts): every connection, key and sign-in of theirs goes. */
forgetPerson: (person: string) => people.forgetPerson(person),
/** For the Admin's signed read: what is `person`, and who has connected each (addresses, never a secret). */
@@ -390,10 +409,9 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {
const apps = personApps(), servers = personMcp();
const byApp: Record<string, string[]> = Object.fromEntries(apps.map((slug) => [slug, [] as string[]]));
if (apps.length) {
- await Promise.all(people.appsPeople().map(async ({ email, access }) => {
- const connected = await deps.composio.connectedServices(deps.cfg(), access).catch(() => null);
- for (const slug of apps) if (connected?.[slug]?.connected) byApp[slug]!.push(email);
- }));
+ for (const { email, services } of await ownAppsServices()) {
+ for (const slug of apps) if (services?.[slug]?.connected) byApp[slug]!.push(email);
+ }
}
const byServer: Record<string, string[]> = {};
for (const name of servers) {
diff --git a/server/index.ts b/server/index.ts
index 5aeadecdab..263279a855 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -622,7 +622,7 @@ import { createConfigRoutes } from "./routes/config.ts";
import { createInstanceRoutes } from "./routes/instances.ts";
import { createMcpConfig } from "./host/mcp-config.ts";
import { createMcpServerRoutes } from "./routes/mcp-servers.ts";
-import { teamAdminSummary } from "./cloud-team-admin.ts";
+import { teamAdminSummary } from "./cloud-team-admin.ts"; import { createConnectionHealthHost } from "./host/connection-health-host.ts";
import { createSetupImportRoutes } from "./routes/setup-import.ts";
import { createComputerRoutes } from "./routes/computers.ts";
import { createStatusRoutes } from "./routes/status.ts";
@@ -1371,7 +1371,7 @@ const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) =
const mcpOAuth = new McpOAuthManager({
file: join(DATA_DIR, "mcp-oauth.json"),
isOwnerLive: (owner) => owner === "loopback" || sessions.isLive(owner) || isCardOwnerLive(store, owner),
- onSettled: (name, phase, owner) => mcpSignInCards.settled(name, phase, owner),
+ onSettled: (name, phase, owner) => { if (phase === "succeeded") connectionHealth.connectedAgain({ kind: "mcp", id: name }); mcpSignInCards.settled(name, phase, owner); }, onRefresh: (name, outcome) => connectionHealth.refreshed(null, name, outcome),
// Read the registered app when needed; never copy its secret into the token store.
clients: (name, url) => {
const raw = cfg.mcpServers?.[name];
@@ -1382,8 +1382,8 @@ const mcpOAuth = new McpOAuthManager({
// Connector tool grants only filter tools/list; the relay's verdict decides each call.
const teamConnections = createTeamConnectionsHost({ team: CLOUD_TEAM, dataDir: DATA_DIR, cfg: () => cfg, adminOrigin: CLOUD_HOME?.adminOrigin ?? null, harnessUrl: `http://127.0.0.1:${PORT}`, audienceOf: teamHost.audienceOf,
requester: (threadId, generation) => actingPeople.requester(threadId, generation), personName: (person) => teamHost.personName(person), roster: () => (teamOwners.people?.list() ?? []).map((member) => ({ person: personKey({ id: "", email: member.email }), email: member.email, role: member.role })),
- mint: (capability) => mintInternalCapability({ ...capability, depth: 0, kind: "connectors", skillAuthoring: false, createdBots: 0, openedThreads: 0 }), mcpOAuth, isOwnerLive: (owner) => sessions.isLive(owner) || isCardOwnerLive(store, owner), onSettled: (name, phase, owner) => mcpSignInCards.settled(name, phase, owner),
- botMcp: (bot) => mcpServersHost.mounted(bot), brokerUrl: () => (CLOUD_TEAM ? cloudConnectedAppsBrokerUrl() || null : null), composio }); teamConnections.primeApps();
+ mint: (capability) => mintInternalCapability({ ...capability, depth: 0, kind: "connectors", skillAuthoring: false, createdBots: 0, openedThreads: 0 }), mcpOAuth, isOwnerLive: (owner) => sessions.isLive(owner) || isCardOwnerLive(store, owner), onSettled: (name, phase, owner) => mcpSignInCards.settled(name, phase, owner), onRefresh: (person, name, outcome) => connectionHealth.refreshed(person, name, outcome), onPersonChanged: (person, kind, id) => connectionHealth.connectedAgain({ kind, id, person }),
+ botMcp: (bot) => mcpServersHost.mounted(bot), brokerUrl: () => (CLOUD_TEAM ? cloudConnectedAppsBrokerUrl() || null : null), composio }); teamConnections.primeApps(); const connectionHealth = createConnectionHealthHost({ dataDir: CLOUD_TEAM ? DATA_DIR : null, mcpServers: () => cfg.mcpServers ?? {}, mcpOAuth, connections: teamConnections, bots: () => store.bots, botServers: (bot) => Object.keys(mcpServersHost.mounted(bot)), roster: () => teamOwners.people?.list() ?? [], personKey: (email) => personKey({ id: "", email }), personName: (email) => teamHost.people.profile(personKey({ id: "", email })).name || null, test: (name, signal) => mcpConfig.test(name, { signal, person: () => null }), asleep: () => cloudPowerNow()?.sleeping() ?? false, wokeAt: () => cloudPowerNow()?.sleptUntil() ?? null }); if (CLOUD_TEAM) connectionHealth.start();
// OpenCode reads provider keys (ANTHROPIC_API_KEY, OPENAI_API_KEY, …) from its environment. Wired before the first catalog probe below.
let openCodeOrganisationManaged = (): boolean => false;
const openCodeKeysAllowed = (): boolean => openCodeProviderKeysAllowed({
@@ -6462,7 +6462,7 @@ bus.subscribe((event: RuntimeEvent) => {
toolName = existing?.name ?? "tool";
store.patchMessage(event.threadId, messageId, {
tool: { ...existing, name: toolName, ok: event.ok, output: event.output === undefined ? undefined : scrubHeldSecrets(event.output), ...mcpToolProblem(toolName, event.ok, event.output, Object.keys(cfg.mcpServers ?? {}), threadLanguage(event.threadId)) },
- });
+ }); void connectionHealth.toolStep({ threadId: event.threadId, generation: activeInternalGenerationByThread.get(event.threadId), tool: toolName, ok: event.ok, output: event.output }).catch(() => {});
toolMessageByItem.delete(itemKey);
}
// Only computer tools change the screen, and each capture competes with the agent for the Boat's command endpoint.
@@ -11845,7 +11845,7 @@ function engineMcpServers(bot: BotRecord) { return teamConnections.engineMcp(bot
function teamAdminHost() {
if (!CLOUD_TEAM) return undefined;
return {
- summary: async () => ({ ...teamAdminSummary({
+ summary: async () => connectionHealth.adminRead({ ...teamAdminSummary({
apps: composio.configured(cfg) ? await composio.connectedServices(cfg).catch(() => null) : null,
mcp: mcpServerResponse().servers,
status: configStatus(),
@@ -12315,7 +12315,7 @@ const taskRoutes = createTaskRoutes({
revokeInternalCapabilitiesForThread,
stagedSkillCleanupsForThread,
rejectDeletedThreadSkillStages,
-}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { teamConnections.forgetPerson(person); personRooms.reads?.forgetPerson(person); } }) : null;
+}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { teamConnections.forgetPerson(person); connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); } }) : null;
ROUTES.push(createTeamRoutes({
store,
cfg,
@@ -12411,7 +12411,7 @@ ROUTES.push(createMcpServerRoutes({
cfg, bot: (id) => store.bot(id), sessions, mcpOAuth, teamConnections,
cloudHome: CLOUD_HOME,
fallbackPublicUrl: FALLBACK_PUBLIC_URL,
- mcpServerResponse, savedCustomDomain, appCatalog: chatAppsMcp, config: mcpConfig, lender: sessionLendingPrincipal, place: (server, auth) => lentMcp.place(server, { principal: sessionLendingPrincipal(auth), ...(auth.kind === "session" ? { session: auth.session.id } : {}), newest: true }) }));
+ mcpServerResponse, savedCustomDomain, appCatalog: chatAppsMcp, config: mcpConfig, lender: sessionLendingPrincipal, connectionHealth, place: (server, auth) => lentMcp.place(server, { principal: sessionLendingPrincipal(auth), ...(auth.kind === "session" ? { session: auth.session.id } : {}), newest: true }) }));
ROUTES.push(createSetupImportRoutes({ local: DESKTOP_MANAGED && !CLOUD_HOME && !HOSTED_WORKSPACE, cfg, mcpPolicyRefusal, persistMcpServers: persistAnnouncedMcpServers,
mcpConfigBusy: mcpConfig.busy }));
ROUTES.push(createComputerRoutes({
@@ -14587,7 +14587,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
"content-type": upstream.contentType,
"cache-control": "no-store",
};
- if (upstream.transportSessionId) headers["mcp-session-id"] = upstream.transportSessionId;
+ if (upstream.transportSessionId) headers["mcp-session-id"] = upstream.transportSessionId; if (connectorCalls.length) connectionHealth.appCall({ ...(internalCapability.connectorsFor ? { person: internalCapability.connectorsFor } : {}), slugs: connectorCalls.map((one) => one.slug), status: upstream.status, bytes: upstream.bytes, contentType: upstream.contentType });
res.writeHead(upstream.status, headers);
return res.end(Buffer.from(withScopeHint(proactive.fence.confines(internalCapability.threadId) ? recordsAnswer(upstream.bytes, upstream.contentType) : upstream.bytes, upstream.contentType, connectorCalls.map((call) => call.slug))));
}
@@ -15142,12 +15142,12 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
m = path.match(/^\/api\/connectors\/([\w-]+)\/authorize$/);
if (m && method === "POST") {
const body = await readBody(req); const refused = managedPolicy.appRefusal(m[1]); if (refused) return json(res, 403, { error: refused, code: "managed_policy" });
- const started = await composio.authorizeService(cfg, m[1], body.alias); void routineHolds?.connections("added"); return json(res, 200, started);
+ const started = await composio.authorizeService(cfg, m[1], body.alias); void routineHolds?.connections("added"); connectionHealth.added("app", m[1], auth.kind === "session" ? auth.session.email ?? null : null); return json(res, 200, started);
}
m = path.match(/^\/api\/connectors\/([\w-]+)\/accounts\/([A-Za-z0-9][A-Za-z0-9_-]{0,127})$/);
if (m && method === "DELETE") { const removed = await composio.removeAccount(cfg, m[1], m[2]); void routineHolds?.connections("removed"); return json(res, 200, removed); }
m = path.match(/^\/api\/connectors\/([\w-]+)$/);
- if (m && method === "DELETE") { const removed = await composio.removeService(cfg, m[1]); void routineHolds?.connections("removed"); return json(res, 200, removed); }
+ if (m && method === "DELETE") { const removed = await composio.removeService(cfg, m[1]); void routineHolds?.connections("removed"); connectionHealth.removed("app", m[1]); return json(res, 200, removed); }
// The browser auth URL goes only to this local UI and is never stored in the transcript.
m = path.match(/^\/api\/bots\/([\w-]+)\/connector-cards\/([\w-]+)\/(authorize|status|resume|dismiss)$/);
@@ -15168,7 +15168,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const alias = composio.normalizeAccountAlias(typeof body.alias === "string" ? body.alias : undefined) ?? connector.alias;
store.patchMessage(threadId, message.id, { connector: { ...connector, alias, status: "authorizing", error: undefined, dismissed: false } });
try {
- const started = await composio.authorizeService(cfg, connector.slug, alias); void routineHolds?.connections("added"); return json(res, 200, started);
+ const started = await composio.authorizeService(cfg, connector.slug, alias); void routineHolds?.connections("added"); connectionHealth.added("app", connector.slug, auth.kind === "session" ? auth.session.email ?? null : null); return json(res, 200, started);
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
store.patchMessage(threadId, message.id, {
diff --git a/server/mcp-oauth.ts b/server/mcp-oauth.ts
index 900c7bf314..7411aad0af 100644
--- a/server/mcp-oauth.ts
+++ b/server/mcp-oauth.ts
@@ -37,12 +37,21 @@ export class McpOAuthError extends Error {
export type McpAuthState = "signed-in" | "needs-sign-in" | "none";
+/** How a token refresh ended: a new token, refused for good (the sign-in ended), nothing could refresh an expired token, or
+ * no answer from the authorization server. */
+export type McpRefreshOutcome = "refreshed" | "rejected" | "expired" | "unreachable";
+/** A server refused a sign-in's token on a real call: a refresh got a new one, the sign-in has ended, the server refused
+ * a token renewed moments ago (the sign-in lacks something), or nothing could be learned. */
+export type McpTokenRefusal = "refreshed" | "ended" | "again" | "unknown";
+
/** The owner of a sign-in started from a chat's Sign in card: any device that can see the card may follow it. */
export const cardOwner = (threadId: string, messageId: string) => `card:${threadId}:${messageId}`;
const DEFAULT_LIFETIME_MS = 5 * 60_000;
const REFRESH_MARGIN_MS = 2 * 60_000;
const REQUEST_TIMEOUT_MS = 10_000;
+/** A token a server refused is renewed at most this often: one refused right after a renewal is not an expired one. */
+const REFUSED_RENEW_MS = 60_000;
export const MCP_OAUTH_CALLBACK_PATH = "/mcp-oauth/callback";
const CALLBACK_PATH = MCP_OAUTH_CALLBACK_PATH;
const DISCARDED = "discarded";
@@ -192,20 +201,24 @@ export class McpOAuthManager {
private readonly isOwnerLive: (owner: string) => boolean;
private readonly flows = new Map<string, Flow>();
private readonly starting = new Map<string, StartingFlow>();
- private readonly refreshing = new Map<string, Promise<string | null>>();
+ private readonly refreshing = new Map<string, Promise<{ token: string | null; outcome: McpRefreshOutcome | null }>>();
+ private readonly renewedAfterRefusal = new Map<string, number>();
private readonly clients: (name: string, url: string) => McpOAuthClientConfig | undefined;
private readonly onSettled: (name: string, phase: McpSignInPhase, owner: string) => void;
+ private readonly onRefresh: (name: string, outcome: McpRefreshOutcome) => void;
private disposed = false;
/** `clients` is read when needed: an app's secret is never copied into this store. `onSettled` hears each sign-in end
- * once, except when the server shuts down. */
+ * once, except when the server shuts down. `onRefresh` hears how each refresh ended. */
constructor(options: {
file: string; lifetimeMs?: number; clients?: (name: string, url: string) => McpOAuthClientConfig | undefined; isOwnerLive?: (owner: string) => boolean;
onSettled?(name: string, phase: McpSignInPhase, owner: string): void;
+ onRefresh?(name: string, outcome: McpRefreshOutcome): void;
}) {
this.store = new McpOAuthStore(options.file);
this.isOwnerLive = options.isOwnerLive ?? (() => true);
this.onSettled = options.onSettled ?? (() => {});
+ this.onRefresh = options.onRefresh ?? (() => {});
this.lifetimeMs = options.lifetimeMs ?? DEFAULT_LIFETIME_MS;
this.clients = options.clients ?? (() => undefined);
}
@@ -360,11 +373,26 @@ export class McpOAuthManager {
if (!record || record.state !== "signed-in" || !record.tokens) return Promise.resolve(null);
const { tokens } = record;
if (!tokens.expiresAt || tokens.expiresAt > Date.now() + REFRESH_MARGIN_MS) return Promise.resolve(tokens.access);
- const pending = this.refreshing.get(name);
- if (pending) return pending;
- const refreshed = this.refresh(name, record).finally(() => this.refreshing.delete(name));
- this.refreshing.set(name, refreshed);
- return refreshed;
+ return this.renew(name, record, false).then((renewed) => renewed.token);
+ }
+
+ /** When this sign-in ends for good: its token's expiry, when nothing can refresh it; null otherwise. */
+ endsAt(name: string, url: string): number | null {
+ const record = this.store.get(name, url);
+ if (!record || record.state !== "signed-in" || !record.tokens?.expiresAt) return null;
+ return this.renewable(name, record) ? null : record.tokens.expiresAt;
+ }
+
+ /** The server refused this sign-in's token on a real call (HTTP 401): it is refreshed now, or, when nothing can refresh
+ * it, the sign-in has ended. A token refused again right after a refresh is left as it is. */
+ async tokenRefused(name: string, url: string): Promise<McpTokenRefusal> {
+ const record = this.store.get(name, url);
+ if (!record || record.state !== "signed-in" || !record.tokens) return record?.state === "needs-sign-in" ? "ended" : "unknown";
+ const renewed = this.renewedAfterRefusal.get(name);
+ if (renewed !== undefined && Date.now() - renewed < REFUSED_RENEW_MS) return "again";
+ this.renewedAfterRefusal.set(name, Date.now());
+ const { outcome } = await this.renew(name, record, true);
+ return outcome === "refreshed" ? "refreshed" : outcome === "rejected" || outcome === "expired" ? "ended" : "unknown";
}
dispose(): void {
@@ -374,14 +402,33 @@ export class McpOAuthManager {
this.flows.clear();
}
- private async refresh(name: string, record: McpOAuthRecord): Promise<string | null> {
+ private renewable(name: string, record: McpOAuthRecord): boolean {
+ return Boolean(record.tokens?.refresh && record.tokenEndpoint && this.recordClient(name, record));
+ }
+
+ /** One refresh at a time per server. `forced`: a server refused the token, so it is renewed whatever its expiry says, and
+ * a token nothing can renew has ended. */
+ private renew(name: string, record: McpOAuthRecord, forced: boolean): Promise<{ token: string | null; outcome: McpRefreshOutcome | null }> {
+ const pending = this.refreshing.get(name);
+ if (pending) return pending;
+ const renewed = this.refresh(name, record, forced).then((result) => {
+ if (result.outcome) {
+ try { this.onRefresh(name, result.outcome); } catch (error) { console.error("mcp sign-in: onRefresh failed", error); }
+ }
+ return result;
+ }).finally(() => this.refreshing.delete(name));
+ this.refreshing.set(name, renewed);
+ return renewed;
+ }
+
+ private async refresh(name: string, record: McpOAuthRecord, forced: boolean): Promise<{ token: string | null; outcome: McpRefreshOutcome | null }> {
const tokens = record.tokens!;
- const stillValid = tokens.expiresAt !== undefined && tokens.expiresAt > Date.now();
+ const stillValid = !forced && tokens.expiresAt !== undefined && tokens.expiresAt > Date.now();
const client = this.recordClient(name, record);
if (!tokens.refresh || !record.tokenEndpoint || !client) {
- if (stillValid) return tokens.access;
+ if (stillValid) return { token: tokens.access, outcome: null };
this.markNeedsSignIn(name, record.url);
- return null;
+ return { token: null, outcome: "expired" };
}
let answer: Awaited<ReturnType<typeof postForm>>;
try {
@@ -391,20 +438,20 @@ export class McpOAuthManager {
resource: record.url,
}, client);
} catch {
- return stillValid ? tokens.access : null;
+ return { token: stillValid ? tokens.access : null, outcome: "unreachable" };
}
const next = answer.status >= 200 && answer.status < 300 ? tokensFrom(answer.body, tokens) : null;
if (!next) {
const dead = (answer.status === 400 || answer.status === 401)
&& (answer.body.error === "invalid_grant" || answer.body.error === "invalid_client");
- if (!dead) return stillValid ? tokens.access : null;
+ if (!dead) return { token: stillValid ? tokens.access : null, outcome: "unreachable" };
this.markNeedsSignIn(name, record.url);
- return null;
+ return { token: null, outcome: "rejected" };
}
// the entry may have been removed or re-pointed while this was in flight
- if (!this.store.get(name, record.url)) return null;
+ if (!this.store.get(name, record.url)) return { token: null, outcome: null };
this.store.put(name, { ...record, state: "signed-in", tokens: next });
- return next.access;
+ return { token: next.access, outcome: "refreshed" };
}
private async challenge(url: string): Promise<string | null> {
diff --git a/server/routes/mcp-servers.ts b/server/routes/mcp-servers.ts
index 63defb9466..55bad00ab2 100644
--- a/server/routes/mcp-servers.ts
+++ b/server/routes/mcp-servers.ts
@@ -3,6 +3,7 @@ import { hostedWorkspaceConfiguration } from "../enterprise.ts";
import { runsElsewhere, type McpConfig, type McpConfigDeps, type McpConfigResult } from "../host/mcp-config.ts";
import { McpOAuthError, McpSignInError, mcpCallbackOrigin } from "../mcp-oauth.ts";
import { isRemoteMcpServer, mcpServerBody, mcpServerNotFound, mcpServerServes, parseMcpServerMutation, parseMcpServersImport, parseStoredMcpServer, type StoredMcpServer } from "../mcp-registry.ts";
+import type { McpProbeResult } from "../mcp-probe.ts";
import { personKey } from "../person-key.ts";
import type { RequestAuth } from "../request-auth.ts";
import { toolBudgetOf } from "../tool-budgets.ts";
@@ -33,6 +34,12 @@ export interface McpServerRouteDeps extends Pick<McpConfigDeps, "cfg" | "session
lender?(auth: RequestAuth): string | null;
/** A server the person adds that needs their own computer, marked as running on the one of theirs lent now. */
place?(server: StoredMcpServer, auth: RequestAuth): Promise<{ ok: true; server: StoredMcpServer } | { ok: false; error: string }>;
+ /** Who added a server and what Test found, for the team's connections (server/host/connection-health-host.ts). */
+ connectionHealth?: {
+ added(kind: "mcp", name: string, email: string | null): void;
+ removed(kind: "mcp", name: string): void;
+ tested(name: string, result: McpProbeResult): Promise<void>;
+ };
}
export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
@@ -92,6 +99,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
},
lender: deps.lender?.(auth) ?? null,
});
+ if ("body" in result && result.status === 200) void deps.connectionHealth?.tested(name, result.body as McpProbeResult).catch(() => {});
return answer(res, json, result);
} finally {
res.off("close", disconnect);
@@ -163,7 +171,9 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
if (!parsed.ok) return json(res, 400, { error: parsed.error });
const placed = deps.place ? await deps.place(parsed.server, auth) : { ok: true as const, server: parsed.server };
if (!placed.ok) return json(res, 409, { error: placed.error });
- return answer(res, json, config.add(name, placed.server));
+ const added = config.add(name, placed.server);
+ if (added.status < 300) deps.connectionHealth?.added("mcp", name, auth.kind === "session" ? auth.session.email ?? null : null);
+ return answer(res, json, added);
}
// The {"mcpServers": {...}} block other agent tools write; imported servers stay disabled until enabled.
@@ -196,7 +206,11 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {
return json(res, 415, { error: "content-type must be application/json" });
}
const name = mcpServerRoute[1]!;
- if (method === "DELETE") return answer(res, json, config.remove(name));
+ if (method === "DELETE") {
+ const removed = config.remove(name);
+ if (removed.status < 300) deps.connectionHealth?.removed("mcp", name);
+ return answer(res, json, removed);
+ }
const body = await readBody(req);
const current = cfg.mcpServers ?? {};
if (!Object.hasOwn(current, name)) return json(res, 404, { error: mcpServerNotFound(name) });
diff --git a/server/routes/team-connections.ts b/server/routes/team-connections.ts
index 1c84690309..1749eef67d 100644
--- a/server/routes/team-connections.ts
+++ b/server/routes/team-connections.ts
@@ -114,7 +114,9 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Route
const access = await deps.host.people.ensureAppsAccess(person, email);
if (!access) return json(res, 503, { error: "Connected apps aren't available on this Cloud right now. Try again in a minute." });
try {
- return json(res, 200, await deps.composio.authorizeService(cfg, slug, null, access));
+ const started = await deps.composio.authorizeService(cfg, slug, null, access);
+ deps.host.people.appConnecting(person, slug);
+ return json(res, 200, started);
} catch (error) {
const status = (error as { status?: number }).status;
return json(res, typeof status === "number" && status >= 400 && status < 500 ? status : 502, { error: error instanceof Error ? error.message : "The app's sign-in couldn't start." });
diff --git a/server/team-connections.ts b/server/team-connections.ts
index 3f1f4e921e..b7d4a82bc9 100644
--- a/server/team-connections.ts
+++ b/server/team-connections.ts
@@ -12,7 +12,7 @@ import { z } from "zod";
import { ensureManagedComposioCredentials, managedComposioAccess } from "../electron/managed-composio.mjs";
import { writeFileAtomic } from "./atomic.ts";
-import { McpOAuthManager, type McpSignInPhase } from "./mcp-oauth.ts";
+import { McpOAuthManager, type McpRefreshOutcome, type McpSignInPhase } from "./mcp-oauth.ts";
import type { McpOAuthClientConfig } from "./mcp-registry.ts";
export type ConnectionScope = "team" | "person";
@@ -98,6 +98,10 @@ export interface PeopleConnectionsOptions {
isOwnerLive: (owner: string) => boolean;
/** Each member's sign-in ending, as McpOAuthManager's own option hears it. */
onSettled?: (name: string, phase: McpSignInPhase, owner: string) => void;
+ /** How each refresh of a member's own sign-in ended. */
+ onRefresh?: (person: string, name: string, outcome: McpRefreshOutcome) => void;
+ /** A member signed in again, saved a key or started connecting an app: what was known about their old one is stale. */
+ onChanged?: (person: string, kind: ConnectionKind, id: string) => void;
fetchImpl?: typeof fetch;
}
@@ -184,6 +188,11 @@ export class PeopleConnections {
file.people[person] = { email, servers: { ...own.servers, [name]: key } };
this.write("mcp-keys.json", file);
this.remember(person, email);
+ this.options.onChanged?.(person, "mcp", name);
+ }
+ /** The member started connecting their own app. */
+ appConnecting(person: string, slug: string): void {
+ this.options.onChanged?.(person, "app", slug);
}
deleteKey(person: string, name: string): void {
const file = this.keys();
@@ -204,7 +213,11 @@ export class PeopleConnections {
this.ensureDir();
manager = new McpOAuthManager({
file: join(this.dir, "mcp-oauth", `${person}.json`), clients: this.options.clients, isOwnerLive: this.options.isOwnerLive,
- ...(this.options.onSettled ? { onSettled: this.options.onSettled } : {}),
+ onSettled: (name: string, phase: McpSignInPhase, owner: string) => {
+ if (phase === "succeeded") this.options.onChanged?.(person, "mcp", name);
+ this.options.onSettled?.(name, phase, owner);
+ },
+ ...(this.options.onRefresh ? { onRefresh: (name: string, outcome: McpRefreshOutcome) => this.options.onRefresh?.(person, name, outcome) } : {}),
});
this.managers.set(person, manager);
}