Skip to content

Commit 2a3a840

Browse files
authored
fix(gateway): expose OAuth-backed tools to CLI agents (#119166)
Carry prepared OAuth and model context through authenticated CLI loopback grants. Revoke cached credential-bearing tools synchronously while preserving the global cache cap.
1 parent c3f148f commit 2a3a840

12 files changed

Lines changed: 432 additions & 11 deletions

‎src/agents/auth-profiles/store.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ function isEnvOnlyAuthProfileRuntime(): boolean {
109109
return authProfileRuntimeMode.getStore()?.kind === "env-only";
110110
}
111111

112-
function resolveRuntimeAuthProfileAgentDir(agentDir?: string): string | undefined {
112+
export function resolveRuntimeAuthProfileAgentDir(agentDir?: string): string | undefined {
113113
const mode = authProfileRuntimeMode.getStore();
114114
return mode?.kind === "agent-dir" ? mode.agentDir : agentDir;
115115
}

‎src/agents/cli-runner/prepare.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2733,8 +2733,15 @@ describe("prepareCliRunContext", () => {
27332733
const grantContext = mintMcpLoopbackClientGrant.mock.calls.at(-1)?.[0]?.context;
27342734
expect(projected).toBeDefined();
27352735
expect(grantContext).toBeDefined();
2736-
const { cfg: projectedConfig, ...projectedContext } = projected ?? {};
2736+
const {
2737+
cfg: projectedConfig,
2738+
authProfileStore,
2739+
authProfileStoreAgentDir,
2740+
...projectedContext
2741+
} = projected ?? {};
27372742
expect(projectedConfig).toEqual(expect.any(Object));
2743+
expect(authProfileStore).toMatchObject({ version: 1, profiles: {} });
2744+
expect(authProfileStoreAgentDir).toEqual(expect.any(String));
27382745
expect(projectedContext).toEqual(grantContext);
27392746
expect(projectedContext).toMatchObject({
27402747
sessionKey: "agent:worker:main",
@@ -2981,6 +2988,10 @@ describe("prepareCliRunContext", () => {
29812988
spawnedBy: "agent:main:telegram:group:parent",
29822989
},
29832990
runtimeOwnerToken: "loopback-owner-token",
2991+
toolAuth: {
2992+
agentDir: expect.any(String),
2993+
store: expect.objectContaining({ version: 1, profiles: {} }),
2994+
},
29842995
});
29852996
context.preparedBackend.mcpClientGrantCapture?.activate("capture-test");
29862997
context.preparedBackend.mcpClientGrantCapture?.deactivate("capture-test");
@@ -3626,10 +3637,14 @@ describe("prepareCliRunContext", () => {
36263637
const {
36273638
cfg: _projectedConfig,
36283639
toolsAllow: projectedPolicy,
3640+
authProfileStore,
3641+
authProfileStoreAgentDir,
36293642
...projectedTrustedContext
36303643
} = projected ?? {};
36313644
const { toolsAllow: grantedTools, ...grantTrustedContext } = grantContext ?? {};
36323645
expect(projectedPolicy).toEqual(["write"]);
3646+
expect(authProfileStore).toMatchObject({ version: 1, profiles: {} });
3647+
expect(authProfileStoreAgentDir).toEqual(expect.any(String));
36333648
expect(grantedTools).toEqual(["write", "apply_patch"]);
36343649
expect(projectedTrustedContext).toEqual(grantTrustedContext);
36353650
} finally {

‎src/agents/cli-runner/prepare.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,10 @@ import {
5858
import { buildOAuthRefreshFailureLoginCommand } from "../auth-profiles/oauth-refresh-failure.js";
5959
import { resolveApiKeyForProfile } from "../auth-profiles/oauth.js";
6060
import { resolveAuthProfileOrder } from "../auth-profiles/order.js";
61-
import { loadAuthProfileStoreForRuntime } from "../auth-profiles/store.js";
61+
import {
62+
loadAuthProfileStoreForRuntime,
63+
resolveRuntimeAuthProfileAgentDir,
64+
} from "../auth-profiles/store.js";
6265
import type { AuthProfileCredential, AuthProfileStore } from "../auth-profiles/types.js";
6366
import {
6467
buildBootstrapBudgetState,
@@ -936,6 +939,15 @@ export async function prepareCliRunContext(
936939
modelId,
937940
})
938941
: undefined;
942+
const mcpToolAuthAgentDir = mcpContextBase
943+
? resolveRuntimeAuthProfileAgentDir(agentDir)
944+
: undefined;
945+
const mcpToolAuth = mcpContextBase
946+
? {
947+
...(mcpToolAuthAgentDir ? { agentDir: mcpToolAuthAgentDir } : {}),
948+
store: authStore ?? loadScopedAuthStore(),
949+
}
950+
: undefined;
939951
const requestedLoopbackToolsAllow =
940952
runtimeToolsAllowPolicy ?? params.cliToolAvailability?.openClaw;
941953
const mcpProjectionContext =
@@ -948,7 +960,12 @@ export async function prepareCliRunContext(
948960
: prepareDeps.resolveMcpLoopbackScopedTools;
949961
const projectedToolsBeforePromptBuild =
950962
(bundleMcpEnabled || shouldMaterializeRuntimePolicy) && mcpProjectionContext
951-
? resolveProjectedTools({ cfg: runtimeConfig, ...mcpProjectionContext }).tools
963+
? resolveProjectedTools({
964+
cfg: runtimeConfig,
965+
...mcpProjectionContext,
966+
...(mcpToolAuth ? { authProfileStore: mcpToolAuth.store } : {}),
967+
...(mcpToolAuth?.agentDir ? { authProfileStoreAgentDir: mcpToolAuth.agentDir } : {}),
968+
}).tools
952969
: [];
953970
const hookFilteredProjectedTools = applyEmbeddedAttemptToolsAllow(
954971
projectedToolsBeforePromptBuild,
@@ -1047,6 +1064,7 @@ export async function prepareCliRunContext(
10471064
? prepareDeps.mintMcpLoopbackClientGrant({
10481065
context: mcpGrantContext,
10491066
runtimeOwnerToken: mcpLoopbackRuntime.ownerToken,
1067+
...(mcpToolAuth ? { toolAuth: mcpToolAuth } : {}),
10501068
})
10511069
: undefined;
10521070
const mcpClientGrantCapture =

‎src/gateway/mcp-grant-store.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
deactivateMcpLoopbackClientGrantCapture,
55
mintAttachGrant,
66
mintMcpLoopbackClientGrant,
7+
registerMcpLoopbackClientGrantRevocationListener,
78
resolveAttachGrant,
89
resolveMcpLoopbackClientGrant,
910
revokeAttachGrant,
@@ -205,6 +206,40 @@ describe("mcp-grant-store", () => {
205206
expect(revokeMcpLoopbackClientGrant(successor.token)).toBe(false);
206207
});
207208

209+
it("notifies revocation listeners for single and runtime-wide cleanup", () => {
210+
const events: Array<{ token: string; runtimeOwnerToken: string }> = [];
211+
const unregister = registerMcpLoopbackClientGrantRevocationListener((event) => {
212+
events.push(event);
213+
});
214+
try {
215+
const first = mintMcpLoopbackClientGrant({
216+
context: { sessionKey: "agent:main:first", senderIsOwner: false },
217+
runtimeOwnerToken: "runtime-one",
218+
});
219+
const second = mintMcpLoopbackClientGrant({
220+
context: { sessionKey: "agent:main:second", senderIsOwner: false },
221+
runtimeOwnerToken: "runtime-one",
222+
});
223+
224+
expect(revokeMcpLoopbackClientGrant(first.token)).toBe(true);
225+
expect(revokeMcpLoopbackClientGrant(first.token)).toBe(false);
226+
expect(revokeMcpLoopbackClientGrantsForRuntime("runtime-one")).toBe(1);
227+
expect(events).toEqual([
228+
{ token: first.token, runtimeOwnerToken: "runtime-one" },
229+
{ token: second.token, runtimeOwnerToken: "runtime-one" },
230+
]);
231+
} finally {
232+
unregister();
233+
}
234+
235+
const afterUnregister = mintMcpLoopbackClientGrant({
236+
context: { sessionKey: "agent:main:later", senderIsOwner: false },
237+
runtimeOwnerToken: "runtime-one",
238+
});
239+
expect(revokeMcpLoopbackClientGrant(afterUnregister.token)).toBe(true);
240+
expect(events).toHaveLength(2);
241+
});
242+
208243
it("requires a session key for loopback client grants", () => {
209244
expect(() =>
210245
mintMcpLoopbackClientGrant({

‎src/gateway/mcp-grant-store.ts‎

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import crypto from "node:crypto";
2+
import type { AuthProfileStore } from "../agents/auth-profiles/types.js";
23
import type { ExecElevatedDefaults } from "../agents/bash-tools.exec-types.js";
34
import type { ExecPolicyOverrides, ExecSessionDefaults } from "../agents/exec-defaults.js";
45
import type { ScheduledToolPolicyContext } from "../agents/scheduled-tool-policy.js";
@@ -79,11 +80,24 @@ interface McpLoopbackClientGrant {
7980
readonly context: McpLoopbackRequestContext;
8081
}
8182

83+
type McpLoopbackToolAuth = {
84+
agentDir?: string;
85+
store: AuthProfileStore;
86+
};
87+
8288
type StoredMcpLoopbackClientGrant = McpLoopbackClientGrant & {
8389
runtimeOwnerToken: string;
8490
activeCaptureKey?: string;
91+
toolAuth?: McpLoopbackToolAuth;
92+
};
93+
94+
type McpLoopbackClientGrantRevocation = {
95+
token: string;
96+
runtimeOwnerToken: string;
8597
};
8698

99+
const clientGrantRevocationListeners = new Set<(event: McpLoopbackClientGrantRevocation) => void>();
100+
87101
const DEFAULT_TTL_MS = 60 * 60 * 1000; // 1h
88102
const MAX_TTL_MS = 12 * 60 * 60 * 1000;
89103

@@ -171,6 +185,7 @@ function sweepExpiredAttachGrants(nowMs: number = Date.now()): number {
171185
export function mintMcpLoopbackClientGrant(params: {
172186
context: McpLoopbackRequestContext;
173187
runtimeOwnerToken: string;
188+
toolAuth?: McpLoopbackToolAuth;
174189
}): McpLoopbackClientGrant {
175190
const sessionKey = params.context.sessionKey.trim();
176191
if (!sessionKey) {
@@ -184,6 +199,7 @@ export function mintMcpLoopbackClientGrant(params: {
184199
token: crypto.randomBytes(32).toString("hex"),
185200
context: structuredClone({ ...params.context, sessionKey }),
186201
runtimeOwnerToken,
202+
...(params.toolAuth ? { toolAuth: structuredClone(params.toolAuth) } : {}),
187203
};
188204
clientGrantsByToken.set(grant.token, grant);
189205
return structuredClone({
@@ -233,7 +249,13 @@ export function resolveMcpLoopbackClientGrant(params: {
233249
token: string;
234250
runtimeOwnerToken: string;
235251
captureKey: string;
236-
}): { context: McpLoopbackRequestContext; captureKey: string } | undefined {
252+
}):
253+
| {
254+
context: McpLoopbackRequestContext;
255+
captureKey: string;
256+
toolAuth?: McpLoopbackToolAuth;
257+
}
258+
| undefined {
237259
const grant = clientGrantsByToken.get(params.token);
238260
if (
239261
!grant ||
@@ -243,19 +265,41 @@ export function resolveMcpLoopbackClientGrant(params: {
243265
) {
244266
return undefined;
245267
}
246-
return structuredClone({ context: grant.context, captureKey: grant.activeCaptureKey });
268+
// Cached tools and OAuth refreshes must share the prepared store for this
269+
// grant; cloning on each request would discard refreshed credentials.
270+
return {
271+
context: structuredClone(grant.context),
272+
captureKey: grant.activeCaptureKey,
273+
...(grant.toolAuth ? { toolAuth: grant.toolAuth } : {}),
274+
};
275+
}
276+
277+
/** Registers cleanup tied to the exact lifetime of loopback client grants. */
278+
export function registerMcpLoopbackClientGrantRevocationListener(
279+
listener: (event: McpLoopbackClientGrantRevocation) => void,
280+
): () => void {
281+
clientGrantRevocationListeners.add(listener);
282+
return () => clientGrantRevocationListeners.delete(listener);
247283
}
248284

249285
export function revokeMcpLoopbackClientGrant(token: string): boolean {
250-
return clientGrantsByToken.delete(token);
286+
const grant = clientGrantsByToken.get(token);
287+
if (!grant || !clientGrantsByToken.delete(token)) {
288+
return false;
289+
}
290+
// Revocation must also release server-owned projections whose closures retain
291+
// this grant's prepared credentials.
292+
for (const listener of clientGrantRevocationListeners) {
293+
listener({ token, runtimeOwnerToken: grant.runtimeOwnerToken });
294+
}
295+
return true;
251296
}
252297

253298
export function revokeMcpLoopbackClientGrantsForRuntime(runtimeOwnerToken: string): number {
254299
let removed = 0;
255300
for (const [token, grant] of clientGrantsByToken) {
256301
if (grant.runtimeOwnerToken === runtimeOwnerToken) {
257-
clientGrantsByToken.delete(token);
258-
removed += 1;
302+
removed += revokeMcpLoopbackClientGrant(token) ? 1 : 0;
259303
}
260304
}
261305
return removed;
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { Type } from "typebox";
2+
import { describe, expect, it, vi } from "vitest";
3+
import { jsonResult } from "../agents/tools/common.js";
4+
import type { OpenClawConfig } from "../config/types.openclaw.js";
5+
import { resolveMcpLoopbackScopedTools } from "./mcp-http.runtime.js";
6+
7+
const pluginTools = vi.hoisted(() => ({
8+
resolve: vi.fn(),
9+
}));
10+
11+
vi.mock("../plugins/tools.js", async (importOriginal) => ({
12+
...(await importOriginal<typeof import("../plugins/tools.js")>()),
13+
resolvePluginTools: (params: unknown) => pluginTools.resolve(params),
14+
}));
15+
16+
describe("MCP loopback OAuth tools", () => {
17+
it("exposes a plugin tool backed by a prepared OAuth profile", () => {
18+
pluginTools.resolve.mockImplementation(
19+
(params: {
20+
context?: { activeModel?: { provider?: string; modelId?: string } };
21+
hasAuthForProvider?: (providerId: string) => boolean;
22+
}) =>
23+
params.hasAuthForProvider?.("xai") &&
24+
params.context?.activeModel?.provider === "anthropic" &&
25+
params.context.activeModel.modelId === "claude-haiku-4-5"
26+
? [
27+
{
28+
name: "x_search",
29+
label: "X search",
30+
description: "X search",
31+
parameters: Type.Object({}),
32+
execute: async () => jsonResult({ ok: true }),
33+
},
34+
]
35+
: [],
36+
);
37+
38+
const result = resolveMcpLoopbackScopedTools({
39+
cfg: {
40+
auth: { order: { xai: ["xai:oauth"] } },
41+
plugins: { allow: ["xai"] },
42+
} as OpenClawConfig,
43+
sessionKey: "agent:main:main",
44+
agentId: "main",
45+
modelProvider: "anthropic",
46+
modelId: "claude-haiku-4-5",
47+
senderIsOwner: true,
48+
authProfileStore: {
49+
version: 1,
50+
profiles: {
51+
"xai:oauth": {
52+
type: "oauth",
53+
provider: "xai",
54+
access: "xai-access-token",
55+
refresh: "xai-refresh-token",
56+
expires: Date.now() + 60_000,
57+
},
58+
},
59+
},
60+
});
61+
62+
expect(result.tools.map((tool) => tool.name)).toContain("x_search");
63+
});
64+
});

‎src/gateway/mcp-http.runtime.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,42 @@ describe("McpLoopbackToolCache", () => {
201201
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(3);
202202
});
203203

204+
it("evicts only the revoked grant's cached tool closures", () => {
205+
const cache = new McpLoopbackToolCache();
206+
const cfg = {} as OpenClawConfig;
207+
208+
cache.resolve(scopeParams({ cfg, grantToken: "grant-a" }));
209+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b" }));
210+
cache.resolve(scopeParams({ cfg, grantToken: "grant-a" }));
211+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b" }));
212+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(2);
213+
214+
expect(cache.evictGrant("grant-a")).toBe(true);
215+
cache.resolve(scopeParams({ cfg, grantToken: "grant-a" }));
216+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b" }));
217+
218+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(3);
219+
});
220+
221+
it("preserves the global 256-entry cache cap across grants", () => {
222+
const cache = new McpLoopbackToolCache();
223+
const cfg = {} as OpenClawConfig;
224+
225+
for (let index = 0; index < 256; index += 1) {
226+
cache.resolve(
227+
scopeParams({ cfg, grantToken: "grant-a", currentMessageId: `message-${index}` }),
228+
);
229+
}
230+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b", currentMessageId: "message-b" }));
231+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(257);
232+
233+
cache.resolve(scopeParams({ cfg, grantToken: "grant-a", currentMessageId: "message-0" }));
234+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(258);
235+
236+
cache.resolve(scopeParams({ cfg, grantToken: "grant-b", currentMessageId: "message-b" }));
237+
expect(resolveGatewayScopedTools).toHaveBeenCalledTimes(258);
238+
});
239+
204240
it("never reuses ordinary private-mode tools for a source-reply-only grant", () => {
205241
const cache = new McpLoopbackToolCache();
206242
const cfg = {} as OpenClawConfig;

0 commit comments

Comments
 (0)