Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Show per-user MCP tools only to people who connected that server (#2507)

Regan Bellae796e56d338
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index e9d4db3e2..e09294037 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -1019,6 +1019,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
}
const childFloor = delegatedSession?.spawnMeta?.readOnly === true;
const strictReadOnly = input.readOnly === true || input.privateSessionMessage === true || childFloor;
+ const mcpToolsReady = !external && deps.mcp ? deps.mcp.toolDefsFor(actor.id) : undefined;
const useMemory = !external && input.skipMemory !== true;
const environmentId = external ? scopeId : await resolveEnvironmentId(deps.environments, scopeId);
const rwLayer = resolution.layers.find((l) => l.mode === "rw");
@@ -3589,6 +3590,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
systemPrompt,
history: continuation?.history ?? history,
tools,
+ ...(mcpToolsReady ? { mcpTools: await mcpToolsReady } : {}),
...(tools.commandCredentialHandles ? { commandCredentialHandles: tools.commandCredentialHandles } : {}),
...(resumePlan?.kind === "retry" && !continuation ? { resumeToolCall: resumePlan.call } : {}),
emit,
diff --git a/src/core/orchestrator/external-tools.ts b/src/core/orchestrator/external-tools.ts
index 3cf344bc4..e68179198 100644
--- a/src/core/orchestrator/external-tools.ts
+++ b/src/core/orchestrator/external-tools.ts
@@ -10,7 +10,6 @@ export function externalTools(tools: ToolContext, authorizeSandbox?: (id: string
return new Proxy(tools, {
get(target, property, receiver) {
if (property === "sessionSyscalls" || property === "runtime") return undefined;
- if (property === "mcpToolDefs") return () => [];
if (property === "execute")
return async (command: string, opts?: Parameters<ToolContext["execute"]>[1]) => {
if (opts?.scratch || opts?.ownerAuth || opts?.reachTarget) return denied();
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index 76f2162b4..bfd921f9f 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -317,7 +317,7 @@ export interface AgentToolsOptions {
backgroundJobTtlMs?: number;
backgroundJobTtlMaxMs?: number;
sandboxCapabilityTtlMs?: number;
- mcpTools?: () => McpToolDescriptor[];
+ mcpTools?: McpToolDescriptor[];
controlTools?: boolean;
sandboxResources?: boolean;
readOnly?: boolean;
@@ -4136,7 +4136,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
},
});
- const mcpDefs = opts?.mcpTools?.() ?? [];
+ const mcpDefs = opts?.mcpTools ?? [];
const mcpTools = mcpDefs
.filter((d) => !opts?.readOnly || d.readOnly)
.map((d) =>
diff --git a/src/harness/harness-shared.ts b/src/harness/harness-shared.ts
index 704fee58a..dc287e495 100644
--- a/src/harness/harness-shared.ts
+++ b/src/harness/harness-shared.ts
@@ -1,6 +1,5 @@
import { TURN_STOPPED_KIND, type ReplayImageRef } from "./replay.ts";
import { randomBytes } from "node:crypto";
-import type { McpToolDescriptor } from "../mcp/mcp-tool-service.ts";
import {
parseSecurityScreenVerdict,
SECURITY_SCREEN_STEP,
@@ -18,7 +17,6 @@ export interface HarnessToolPlumbing {
scratchExec?: boolean;
ownerAuthExec?: boolean;
reachExec?: boolean;
- mcpTools?: () => McpToolDescriptor[];
controlTools?: boolean;
sandboxResources?: boolean;
execTimeoutMs?: number;
@@ -131,7 +129,7 @@ export function harnessToolOptions(opts: HarnessToolPlumbing, turn?: HarnessTurn
scratchExec: opts.scratchExec,
ownerAuthExec: opts.ownerAuthExec,
reachExec: opts.reachExec,
- ...(opts.mcpTools ? { mcpTools: opts.mcpTools } : {}),
+ ...(turn?.mcpTools?.length ? { mcpTools: turn.mcpTools } : {}),
controlTools: opts.controlTools,
sandboxResources: opts.sandboxResources,
execTimeoutMs: opts.execTimeoutMs,
diff --git a/src/harness/harness.ts b/src/harness/harness.ts
index 541551ed1..e7adf48db 100644
--- a/src/harness/harness.ts
+++ b/src/harness/harness.ts
@@ -18,6 +18,7 @@ export type { GapWork } from "../sessions/session-store.ts";
import type { OverheardEntryPayload } from "./replay.ts";
import type { GoalRecord } from "./goal.ts";
import type { GrindMeter } from "./grind.ts";
+import type { McpToolDescriptor } from "../mcp/mcp-tool-service.ts";
import type { ProviderKeys } from "./pi-harness.ts";
import type { ToolContext } from "../tools/primitives.ts";
import type { SecurityScreenVerdict, ToolResultScreen, ToolResultScreenInput } from "../security/security-posture.ts";
@@ -129,6 +130,7 @@ export interface HarnessTurnInput {
goalMeter?: GrindMeter;
saveGoal?(goal: GoalRecord): Promise<void>;
tools: ToolContext;
+ mcpTools?: McpToolDescriptor[];
commandCredentialHandles?: readonly string[];
toolApprovalGate?(tool: string): boolean;
emit(entry: NewEntry): Promise<SessionEntry>;
diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.ts
index 6b5257267..2d8aab101 100644
--- a/src/harness/pi-harness.ts
+++ b/src/harness/pi-harness.ts
@@ -93,7 +93,6 @@ import {
type GapWork,
} from "./harness.ts";
import { coreToolOptions, createAgentTools, pauseStampAfterToolCall, type ToolContextRef } from "./agent-tools.ts";
-import type { McpToolDescriptor } from "../mcp/mcp-tool-service.ts";
import { startSignalPoll, type RunSignalStore } from "../runs/run-signal-store.ts";
import {
planColdStartSeed,
@@ -152,7 +151,6 @@ export interface PiHarnessOptions {
scratchExec?: boolean;
ownerAuthExec?: boolean;
reachExec?: boolean;
- mcpTools?: () => McpToolDescriptor[];
controlTools?: boolean;
sandboxResources?: boolean;
turnWallClockMs?: number;
@@ -1549,7 +1547,6 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
const scratchExec = opts?.scratchExec ?? false;
const ownerAuthExec = opts?.ownerAuthExec ?? false;
const reachExec = opts?.reachExec ?? false;
- const mcpTools = opts?.mcpTools;
const controlTools = opts?.controlTools ?? false;
const defaultTurnWallClockMs = opts?.turnWallClockMs ?? CONFIG_DEFAULTS.turnWallClockSec * 1000;
const signals = opts?.signals;
@@ -1560,7 +1557,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {
scratchExec,
ownerAuthExec,
reachExec,
- ...(mcpTools ? { mcpTools } : {}),
+ ...(turn.mcpTools?.length ? { mcpTools: turn.mcpTools } : {}),
controlTools,
...(turn.commandCredentialHandles?.length ? { commandCredentialHandles: turn.commandCredentialHandles } : {}),
...(turn.surfaceTools ? { surfaceTools: true } : {}),
diff --git a/src/mcp/mcp-tool-service.ts b/src/mcp/mcp-tool-service.ts
index c80c7e082..1bb913db6 100644
--- a/src/mcp/mcp-tool-service.ts
+++ b/src/mcp/mcp-tool-service.ts
@@ -49,6 +49,7 @@ export interface McpToolDescriptor {
export interface McpToolService {
/** Current snapshot of injectable tools across enabled servers. */
toolDefs(): McpToolDescriptor[];
+ toolDefsFor(principalId?: string): Promise<McpToolDescriptor[]>;
/** Call a namespaced tool. Returns the tool's text output (clamped). */
call(name: string, args: Record<string, unknown>, principalId?: string): Promise<string>;
/** Force a registry re-read + tools/list refresh (admin save path, tests). */
@@ -70,7 +71,7 @@ function authOf(server: McpServer): McpAuth {
export function createMcpToolService(opts: {
servers: McpServerStore;
audit?: AuditLog;
- userTokens?: Pick<ConnectorTokenStore, "connectorAccessToken">;
+ userTokens?: Pick<ConnectorTokenStore, "connectorAccessToken" | "connectorTokenStatus">;
now?: () => number;
refreshIntervalMs?: number;
signInUrl?: (serverId: string) => string;
@@ -78,6 +79,7 @@ export function createMcpToolService(opts: {
const now = opts.now ?? (() => Date.now());
const clients = new Map<string, { client: McpClient; server: McpServer }>();
let snapshot: McpToolDescriptor[] = [];
+ let perUserServers = new Map<string, McpServer>();
function signInMessage(server: McpServer): string {
const url = opts.signInUrl?.(server.id);
@@ -129,23 +131,23 @@ export function createMcpToolService(opts: {
setPublicOAuthClients(mcpPublicOAuthClients(all));
const servers = all.filter((s) => s.enabled);
const next: McpToolDescriptor[] = [];
+ const nextPerUser = new Map<string, McpServer>();
for (const server of servers) {
try {
let tools: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>;
if (server.auth === "oauth-user") {
+ nextPerUser.set(server.id, server);
+ next.push({
+ name: `${server.id}_sign_in`.replace(/[^a-zA-Z0-9_-]/g, "_"),
+ serverId: server.id,
+ remoteName: "sign_in",
+ signIn: true,
+ description: `Connect your own ${server.name} account and load its tools. Call this before anything else on ${server.name}.`,
+ inputSchema: { type: "object", properties: {} },
+ readOnly: true,
+ });
tools = server.tools ?? [];
- if (!tools.length) {
- next.push({
- name: `${server.id}_sign_in`.replace(/[^a-zA-Z0-9_-]/g, "_"),
- serverId: server.id,
- remoteName: "sign_in",
- signIn: true,
- description: `Connect your own ${server.name} account and load its tools. Call this before anything else on ${server.name}.`,
- inputSchema: { type: "object", properties: {} },
- readOnly: true,
- });
- continue;
- }
+ if (!tools.length) continue;
} else tools = await clientFor(server).listTools();
for (const tool of tools) {
next.push({
@@ -165,6 +167,29 @@ export function createMcpToolService(opts: {
// De-duplicate on the namespaced name; first server wins deterministically.
const seen = new Set<string>();
snapshot = next.filter((t) => (seen.has(t.name) ? false : (seen.add(t.name), true)));
+ perUserServers = nextPerUser;
+ }
+
+ async function connected(server: McpServer, principalId: string | undefined): Promise<boolean> {
+ if (!principalId || !server.credentialHost || !opts.userTokens) return false;
+ const status = await opts.userTokens
+ .connectorTokenStatus(server.credentialHost, principalId, server.credentialAccountType)
+ .catch(reportFailureAs("mcp: connector status", null));
+ return Boolean(status?.connected && !status.needsReconnect);
+ }
+
+ async function toolDefsFor(principalId?: string): Promise<McpToolDescriptor[]> {
+ const current = snapshot;
+ const gated = perUserServers;
+ if (!gated.size) return current;
+ const withTools = new Set(current.filter((t) => gated.has(t.serverId) && !t.signIn).map((t) => t.serverId));
+ const ready = new Set<string>();
+ await Promise.all(
+ [...withTools].map(async (id) => {
+ if (await connected(gated.get(id)!, principalId)) ready.add(id);
+ }),
+ );
+ return current.filter((t) => !gated.has(t.serverId) || Boolean(t.signIn) !== ready.has(t.serverId));
}
const refreshInBackground = (): void => {
@@ -177,6 +202,7 @@ export function createMcpToolService(opts: {
return {
toolDefs: () => snapshot,
+ toolDefsFor,
async call(name, args, principalId) {
const def = snapshot.find((t) => t.name === name);
if (!def) throw new Error(`unknown MCP tool: ${name}`);
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index 9f2c57e26..b36dcb582 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -62,7 +62,7 @@ import { errMessage, withCleanup } from "../util/errors.ts";
import type { FileArtifactStore } from "../files/file-artifact-store.ts";
import type { ScopedConfigStore } from "../resolution/config-store.ts";
import { MEMORY_FILE, type MemoryEdit, type MemoryService } from "../memory/memory-service.ts";
-import type { McpToolService, McpToolDescriptor } from "../mcp/mcp-tool-service.ts";
+import type { McpToolService } from "../mcp/mcp-tool-service.ts";
import type { ReachResolution } from "../resolution/scope-reach.ts";
import type {
ControlService,
@@ -245,7 +245,6 @@ export interface ToolContext extends SurfaceToolDeps {
memoryDelete(ids: string[]): Promise<true | null>;
history(q: string, limit?: number): Promise<string[]>;
historyOpen(seq: number): Promise<string | null>;
- mcpToolDefs(): McpToolDescriptor[];
callMcpTool(name: string, args: Record<string, unknown>): Promise<string>;
awaitClientResult(
callId: string,
@@ -1231,10 +1230,6 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
return deps.sessionHistory.open(seq);
},
- mcpToolDefs(): McpToolDescriptor[] {
- return deps.mcp?.toolDefs() ?? [];
- },
-
async callMcpTool(name: string, args: Record<string, unknown>): Promise<string> {
if (!deps.mcp) throw new Error("no MCP connectors are configured");
return deps.mcp.call(name, args, deps.createdBy);
diff --git a/src/wiring.ts b/src/wiring.ts
index 28d6d2ce1..0ba9a4de9 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1338,7 +1338,6 @@ export function buildApp(
}
: {}),
});
- const mcpTools = () => mcpToolService.toolDefs();
const browserSessionStore: BrowserSessionStore | undefined = keychainKeyMaterial
? createBrowserSessionStore({ sessions: artifactMap<StoredBrowserSession>("browser_sessions"), key: credentialKey })
: undefined;
@@ -1487,7 +1486,6 @@ export function buildApp(
resolveProviderKeys: resolvePiProviderKeys,
...(directProviderAvailability.codexOAuth ? { companyModelId } : {}),
signals: runSignals,
- mcpTools,
}),
],
[
@@ -1503,7 +1501,6 @@ export function buildApp(
}
: {}),
signals: runSignals,
- mcpTools,
}),
],
["mock", createMockHarness()],
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index 0a511de24..ef53b2f5c 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -361,9 +361,6 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["execute
async setStandingOrder(orders) {
return { ok: true, orders: orders ?? "" };
},
- mcpToolDefs() {
- return [];
- },
async callMcpTool() {
return "";
},
@@ -3505,7 +3502,7 @@ test("resource catalog exposes one home per operation and leaves MCP tools intac
{ current: fakeToolContext() },
{
controlTools: true,
- mcpTools: () => [
+ mcpTools: [
{
name: "example_search",
serverId: "example",
diff --git a/test/external-slack-core.test.ts b/test/external-slack-core.test.ts
index 9bfda7c9d..c70bb44a1 100644
--- a/test/external-slack-core.test.ts
+++ b/test/external-slack-core.test.ts
@@ -152,7 +152,6 @@ test("external native tool ceiling cannot delegate, switch sandboxes, read confi
])
assert.throws(call, /private access/);
assert.equal(tools.sessionSyscalls, undefined);
- assert.deepEqual(tools.mcpToolDefs(), []);
assert.equal(runs, 1);
});
diff --git a/test/mcp-oauth-user.test.ts b/test/mcp-oauth-user.test.ts
index 0b67c66b1..120f06b86 100644
--- a/test/mcp-oauth-user.test.ts
+++ b/test/mcp-oauth-user.test.ts
@@ -95,7 +95,10 @@ test("oauth-user tools offer a sign-in link until the caller connects, then use
const auth = () => mcp.requests.filter((r) => r.rpc?.startsWith("tools/")).map((r) => r.authorization ?? "");
const service = createMcpToolService({
servers: store,
- userTokens: { connectorAccessToken: async (_host, principalId) => tokens.get(principalId) ?? null },
+ userTokens: {
+ connectorAccessToken: async (_host, principalId) => tokens.get(principalId) ?? null,
+ connectorTokenStatus: async (_host, principalId) => ({ connected: tokens.has(principalId) }),
+ },
signInUrl: (id) => `https://qm.example/connect/${id}/self-connect`,
});
t.after(() => {
@@ -106,7 +109,7 @@ test("oauth-user tools offer a sign-in link until the caller connects, then use
await service.refresh();
assert.ok(oauthProvider("orders")?.pkce, "refresh registers the server's OAuth client");
assert.deepEqual(
- service.toolDefs().map((d) => d.name),
+ (await service.toolDefsFor("internal:alice")).map((d) => d.name),
["orders_sign_in"],
);
assert.equal(mcp.requests.length, 0, "no unauthenticated discovery");
@@ -118,9 +121,14 @@ test("oauth-user tools offer a sign-in link until the caller connects, then use
tokens.set("internal:alice", "alice-token");
assert.match(await service.call("orders_sign_in", {}, "internal:alice"), /orders_search/);
assert.deepEqual(
- service.toolDefs().map((d) => d.name),
+ (await service.toolDefsFor("internal:alice")).map((d) => d.name),
["orders_search"],
);
+ assert.deepEqual(
+ (await service.toolDefsFor("internal:bob")).map((d) => d.name),
+ ["orders_sign_in"],
+ "a teammate who has not connected sees only the sign-in tool, not the tools another person loaded",
+ );
assert.deepEqual(
(await store.get("orders"))!.tools?.map((tool) => tool.name),
["search"],
@@ -130,3 +138,36 @@ test("oauth-user tools offer a sign-in link until the caller connects, then use
assert.match(await service.call("orders_search", { q: "x" }, "internal:bob"), /Connect Orders/);
assert.deepEqual(auth(), ["Bearer alice-token", "Bearer alice-token"]);
});
+
+test("stored oauth-user tools survive a restart but stay hidden from callers whose connection needs repair", async (t) => {
+ const store = createMcpServerStore(createMemoryMap<McpServer>());
+ await store.put(oauthServer({ tools: [{ name: "search", description: "Search", inputSchema: { type: "object" } }] }));
+ const statuses: Record<string, { connected: boolean; needsReconnect?: boolean }> = {
+ "internal:alice": { connected: true },
+ "internal:carol": { connected: true, needsReconnect: true },
+ };
+ const service = createMcpToolService({
+ servers: store,
+ userTokens: {
+ connectorAccessToken: async () => null,
+ connectorTokenStatus: async (_host, principalId) => statuses[principalId] ?? { connected: false },
+ },
+ });
+ t.after(() => {
+ service.close();
+ setPublicOAuthClients([]);
+ });
+ await service.refresh();
+ assert.deepEqual(
+ (await service.toolDefsFor("internal:alice")).map((d) => d.name),
+ ["orders_search"],
+ );
+ assert.deepEqual(
+ (await service.toolDefsFor("internal:carol")).map((d) => d.name),
+ ["orders_sign_in"],
+ );
+ assert.deepEqual(
+ (await service.toolDefsFor("internal:dave")).map((d) => d.name),
+ ["orders_sign_in"],
+ );
+});
diff --git a/test/subagent-parity.test.ts b/test/subagent-parity.test.ts
index 9c5ac5865..0d12fe450 100644
--- a/test/subagent-parity.test.ts
+++ b/test/subagent-parity.test.ts
@@ -36,6 +36,7 @@ import { scopeId, type Principal, type Session } from "../src/types.ts";
import type { Sandbox } from "../src/sandbox/sandbox.ts";
import type { Run } from "../src/runs/run-store.ts";
import { singleProcessDeps } from "./support/single-process.ts";
+import type { McpToolService } from "../src/mcp/mcp-tool-service.ts";
type Call = { tool: string; args: Record<string, unknown> };
type Turn = {
@@ -169,6 +170,21 @@ async function world(flags: FeatureName[], next: (turn: Turn, subagent: boolean)
deliveries: createDeliveryStore(),
featureFlags,
sessionSyscalls,
+ mcp: {
+ toolDefsFor: async (principalId?: string) =>
+ principalId === actor.id
+ ? [
+ {
+ name: "orders_search",
+ serverId: "orders",
+ remoteName: "search",
+ description: "Search orders",
+ inputSchema: { type: "object", properties: {} },
+ readOnly: true,
+ },
+ ]
+ : [],
+ } as unknown as McpToolService,
});
const execute = async (run: Run) => {
const result = await orchestrator.handleTurn({ ...run.request, runId: run.id });
@@ -223,6 +239,11 @@ for (const [surface, flags] of [
const omit = (options: AgentToolsOptions) =>
Object.fromEntries(Object.entries(options).filter(([key]) => !(key in SUBAGENT_EXCEPTIONS)));
assert.deepEqual(omit(child.options), omit(parent.options));
+ assert.deepEqual(
+ parent.options.mcpTools?.map((tool) => tool.name),
+ ["orders_search"],
+ "the turn's actor gets the MCP tools resolved for them",
+ );
assert.equal(parent.ref.current?.humanTurn, true);
assert.equal(child.ref.current?.humanTurn, undefined);
assert.equal(parent.requestedRuntime?.fastMode, true);