Skip to content

Commit ad417b2

Browse files
committed
refactor(mcp): give OAuth identity one home and make authorization resumable
McpOAuthIdentity owns the store-key grammar (operator keys byte-identical, zero migration); provider, coordinator, fetch, transport, CLI, and doctor receive identity instead of re-deriving (serverName, serverUrl) keys. The authorize -> capture -> exchange dance moves from the CLI into the coordinator as a resumable session (start persists the pending verifier/ URL in the store row; complete exchanges the code under the same lease), leaving the CLI loopback as a capture adapter. Production net -7 lines.
1 parent dfb4712 commit ad417b2

22 files changed

Lines changed: 654 additions & 672 deletions

‎src/agents/mcp-auth-profile.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,10 @@ describe("mcp auth profile bearer projection", () => {
6868
);
6969
expect(authMocks.resolveMcpOAuthAccessToken).toHaveBeenCalledWith(
7070
expect.objectContaining({
71-
serverName: "docs",
72-
serverUrl: "https://mcp.example.com/mcp",
71+
identity: expect.objectContaining({
72+
serverName: "docs",
73+
serverUrl: "https://mcp.example.com/mcp",
74+
}),
7375
config: { scope: "docs.read" },
7476
fetchFn: expect.any(Function),
7577
}),

‎src/agents/mcp-auth-profile.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
withoutMcpAuthorizationHeader,
1414
withSameOriginMcpHttpHeaders,
1515
} from "./mcp-http-fetch.js";
16+
import { operatorMcpOAuthIdentity } from "./mcp-oauth-identity.js";
1617
import { resolveMcpOAuthAccessToken, type McpOAuthConfig } from "./mcp-oauth.js";
1718
import { resolveMcpTransportConfig } from "./mcp-transport-config.js";
1819

@@ -131,8 +132,7 @@ async function resolveMcpBearerToken(params: {
131132
resourceUrl: resolved.url,
132133
});
133134
return await resolveMcpOAuthAccessToken({
134-
serverName: params.serverName,
135-
serverUrl: resolved.url,
135+
identity: operatorMcpOAuthIdentity(params.serverName, resolved.url),
136136
config: resolved.oauth as McpOAuthConfig | undefined,
137137
fetchFn,
138138
});

‎src/agents/mcp-http-fetch.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
withSameOriginMcpHttpHeaders,
1414
} from "./mcp-http-fetch.js";
1515
import { withMcpOAuthBearer } from "./mcp-oauth-fetch.js";
16+
import { operatorMcpOAuthIdentity } from "./mcp-oauth-identity.js";
1617

1718
const testGlobal = globalThis as Record<string, unknown>;
1819
const TEST_UNDICI_RUNTIME_DEPS_KEY = "__OPENCLAW_TEST_UNDICI_RUNTIME_DEPS__";
@@ -321,8 +322,7 @@ describe("MCP HTTP fetch helpers", () => {
321322
const fetch = withMcpOAuthBearer({
322323
fetchFn: buildMcpHttpFetch({ resourceUrl }),
323324
authFetchFn: buildMcpHttpFetch({ resourceUrl }),
324-
serverName: "docs",
325-
resourceUrl,
325+
identity: operatorMcpOAuthIdentity("docs", resourceUrl),
326326
});
327327

328328
const response = await fetch(resourceUrl, {

‎src/agents/mcp-oauth-fetch.test.ts‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js";
22
import { beforeEach, describe, expect, it, vi } from "vitest";
33
import { withMcpOAuthBearer } from "./mcp-oauth-fetch.js";
4+
import { operatorMcpOAuthIdentity } from "./mcp-oauth-identity.js";
45

56
const oauthMocks = vi.hoisted(() => ({
67
recordAuthorizationRequired: vi.fn(),
78
resolve: vi.fn(),
89
}));
10+
const IDENTITY = operatorMcpOAuthIdentity("docs", "https://mcp.example.com/mcp");
911

1012
vi.mock("./mcp-oauth.js", () =>
1113
Object.fromEntries([
@@ -36,8 +38,7 @@ describe("MCP OAuth bearer fetch", () => {
3638
const wrapped = withMcpOAuthBearer({
3739
fetchFn,
3840
authFetchFn: fetchFn,
39-
serverName: "docs",
40-
resourceUrl: "https://mcp.example.com/mcp",
41+
identity: IDENTITY,
4142
});
4243

4344
await wrapped("https://mcp.example.com/mcp", { headers: { "x-tenant": "docs" } });
@@ -68,8 +69,7 @@ describe("MCP OAuth bearer fetch", () => {
6869
const wrapped = withMcpOAuthBearer({
6970
fetchFn,
7071
authFetchFn: fetchFn,
71-
serverName: "docs",
72-
resourceUrl: "https://mcp.example.com/mcp",
72+
identity: IDENTITY,
7373
config: { scope: "fallback" },
7474
});
7575
const controller = new AbortController();
@@ -108,8 +108,7 @@ describe("MCP OAuth bearer fetch", () => {
108108
const wrapped = withMcpOAuthBearer({
109109
fetchFn,
110110
authFetchFn: fetchFn,
111-
serverName: "docs",
112-
resourceUrl: "https://mcp.example.com/mcp",
111+
identity: IDENTITY,
113112
});
114113

115114
await expect(wrapped("https://mcp.example.com/mcp")).resolves.toMatchObject({ status: 200 });
@@ -138,8 +137,7 @@ describe("MCP OAuth bearer fetch", () => {
138137
const wrapped = withMcpOAuthBearer({
139138
fetchFn,
140139
authFetchFn: fetchFn,
141-
serverName: "docs",
142-
resourceUrl: "https://mcp.example.com/mcp",
140+
identity: IDENTITY,
143141
});
144142

145143
const response = await wrapped(
@@ -173,8 +171,7 @@ describe("MCP OAuth bearer fetch", () => {
173171
const wrapped = withMcpOAuthBearer({
174172
fetchFn,
175173
authFetchFn: fetchFn,
176-
serverName: "docs",
177-
resourceUrl: "https://mcp.example.com/mcp",
174+
identity: IDENTITY,
178175
});
179176

180177
await expect(wrapped("https://mcp.example.com/mcp")).rejects.toBe(loginRequired);
@@ -199,18 +196,16 @@ describe("MCP OAuth bearer fetch", () => {
199196
const wrapped = withMcpOAuthBearer({
200197
fetchFn,
201198
authFetchFn: fetchFn,
202-
serverName: "docs",
203-
resourceUrl: "https://mcp.example.com/mcp",
199+
identity: IDENTITY,
204200
});
205201

206202
await expect(wrapped("https://mcp.example.com/mcp")).resolves.toMatchObject({ status: 401 });
207203
expect(fetchFn).toHaveBeenCalledTimes(2);
208204
expect(oauthMocks.resolve).toHaveBeenCalledTimes(2);
209205
expect(oauthMocks.recordAuthorizationRequired).toHaveBeenCalledWith(
210206
expect.objectContaining({
207+
identity: IDENTITY,
211208
rejectedAccessToken: "test-auth-token",
212-
serverName: "docs",
213-
serverUrl: "https://mcp.example.com/mcp",
214209
}),
215210
);
216211
});

‎src/agents/mcp-oauth-fetch.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { extractWWWAuthenticateParams } from "@modelcontextprotocol/sdk/client/auth.js";
22
import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js";
3+
import type { McpOAuthIdentity } from "./mcp-oauth-identity.js";
34
import {
45
recordMcpOAuthAuthorizationRequired,
56
resolveMcpOAuthAccessToken,
@@ -47,11 +48,10 @@ async function dispatchRequest(fetchFn: FetchLike, request: Request): Promise<Re
4748
export function withMcpOAuthBearer(params: {
4849
fetchFn: FetchLike;
4950
authFetchFn: FetchLike;
50-
serverName: string;
51-
resourceUrl: string;
51+
identity: McpOAuthIdentity;
5252
config?: McpOAuthConfig;
5353
}): McpOAuthFetch {
54-
const resourceOrigin = new URL(params.resourceUrl).origin;
54+
const resourceOrigin = new URL(params.identity.serverUrl).origin;
5555
return async (input, init) => {
5656
const source = input instanceof Request ? input.clone() : input;
5757
const request = new Request(source, init);
@@ -60,8 +60,7 @@ export function withMcpOAuthBearer(params: {
6060
}
6161

6262
const accessToken = await resolveMcpOAuthAccessToken({
63-
serverName: params.serverName,
64-
serverUrl: params.resourceUrl,
63+
identity: params.identity,
6564
config: params.config,
6665
fetchFn: params.authFetchFn,
6766
// Resource feedback can reject an unknown-expiry token. Avoid rotating it
@@ -84,8 +83,7 @@ export function withMcpOAuthBearer(params: {
8483
// first request's dispatcher lease across discovery/refresh.
8584
await response.body?.cancel().catch(() => undefined);
8685
const nextAccessToken = await resolveMcpOAuthAccessToken({
87-
serverName: params.serverName,
88-
serverUrl: params.resourceUrl,
86+
identity: params.identity,
8987
config: params.config,
9088
fetchFn: params.authFetchFn,
9189
acceptUnknownExpiry: true,
@@ -104,8 +102,7 @@ export function withMcpOAuthBearer(params: {
104102
if (retryResponse.status === 401 || retryInsufficientScope) {
105103
const rejectedAccessToken = nextAccessToken;
106104
await recordMcpOAuthAuthorizationRequired({
107-
serverName: params.serverName,
108-
serverUrl: params.resourceUrl,
105+
identity: params.identity,
109106
rejectedAccessToken,
110107
resourceMetadataUrl: retryChallenge.resourceMetadataUrl ?? challenge.resourceMetadataUrl,
111108
scope: retryChallenge.scope ?? challenge.scope,

‎src/agents/mcp-oauth-identity.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { createHash } from "node:crypto";
2+
import { sanitizeServerName } from "./agent-bundle-mcp-names.js";
3+
4+
/** Identity of one principal's OAuth state for one MCP server. */
5+
export type McpOAuthIdentity = {
6+
storeKey: string;
7+
principal: "operator";
8+
serverName: string;
9+
serverUrl: string;
10+
};
11+
12+
export function operatorMcpOAuthIdentity(serverName: string, serverUrl: string): McpOAuthIdentity {
13+
const safeServerName = sanitizeServerName(serverName, new Set<string>());
14+
const hash = createHash("sha256").update(serverName).update("\0").update(serverUrl).digest("hex");
15+
return {
16+
storeKey: `${safeServerName}-${hash.slice(0, 16)}`,
17+
principal: "operator",
18+
serverName,
19+
serverUrl,
20+
};
21+
}
22+
23+
export function mcpOAuthStoreKeyFromLegacyFileName(fileName: string): string | null {
24+
return /^[A-Za-z][A-Za-z0-9_-]{0,29}-[0-9a-f]{16}\.json$/u.test(fileName)
25+
? fileName.slice(0, -".json".length)
26+
: null;
27+
}

‎src/agents/mcp-oauth-provider.ts‎

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,8 @@ import type { OAuthClientMetadata, OAuthTokens } from "@modelcontextprotocol/sdk
66
import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js";
77
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
88
import type { OpenClawStateLeaseContext } from "../state/openclaw-state-lease.js";
9-
import {
10-
readMcpOAuthStore,
11-
resolveMcpOAuthStoreKey,
12-
updateMcpOAuthStore,
13-
type McpOAuthStore,
14-
} from "./mcp-oauth-store.js";
9+
import type { McpOAuthIdentity } from "./mcp-oauth-identity.js";
10+
import { readMcpOAuthStore, updateMcpOAuthStore, type McpOAuthStore } from "./mcp-oauth-store.js";
1511

1612
export type McpOAuthConfig = {
1713
scope?: unknown;
@@ -82,25 +78,21 @@ function beginMcpOAuthAuthorization(store: McpOAuthStore): McpOAuthStore {
8278

8379
/** Creates the MCP SDK OAuth provider backed by canonical shared SQLite state. */
8480
export function createMcpOAuthClientProvider(params: {
85-
serverName: string;
86-
serverUrl: string;
81+
identity: McpOAuthIdentity;
8782
config?: McpOAuthConfig;
88-
onAuthorizationUrl?: (url: URL) => void | Promise<void>;
8983
allowAuthorizationRedirect?: boolean;
9084
suppressStoredTokens?: boolean;
9185
lease?: OpenClawStateLeaseContext;
9286
}): OAuthClientProvider {
9387
const config = params.config ?? {};
94-
const storeKey = resolveMcpOAuthStoreKey(params.serverName, params.serverUrl);
88+
const storeKey = params.identity.storeKey;
9589
const assertOwnedInTransaction = bindMcpOAuthLeaseAssertion(params.lease);
9690
const updateStore = (update: (store: McpOAuthStore) => McpOAuthStore) =>
9791
updateMcpOAuthStore(storeKey, update, assertOwnedInTransaction);
98-
const allowAuthorizationRedirect =
99-
params.allowAuthorizationRedirect ?? Boolean(params.onAuthorizationUrl);
10092
const assertAuthorizationRedirectAllowed = () => {
101-
if (!allowAuthorizationRedirect) {
93+
if (params.allowAuthorizationRedirect !== true) {
10294
throw new Error(
103-
`MCP server "${params.serverName}" requires OAuth authorization. Run openclaw mcp login ${params.serverName}.`,
95+
`MCP server "${params.identity.serverName}" requires OAuth authorization. Run openclaw mcp login ${params.identity.serverName}.`,
10496
);
10597
}
10698
};
@@ -162,8 +154,8 @@ export function createMcpOAuthClientProvider(params: {
162154
updateStore((store) => ({
163155
...beginMcpOAuthAuthorization(store),
164156
lastAuthorizationUrl: authorizationUrl.toString(),
157+
redirectUrl: resolveOAuthRedirectUrl(config, store),
165158
}));
166-
await params.onAuthorizationUrl?.(authorizationUrl);
167159
},
168160
saveCodeVerifier(codeVerifier) {
169161
assertAuthorizationRedirectAllowed();

‎src/agents/mcp-oauth-refresh-issuer.test.ts‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ import { withTempHome as withBaseTempHome } from "openclaw/plugin-sdk/test-env";
44
import { afterEach, beforeEach, describe, expect, it } from "vitest";
55
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
66
import { withMcpOAuthBearer } from "./mcp-oauth-fetch.js";
7+
import { operatorMcpOAuthIdentity } from "./mcp-oauth-identity.js";
78
import { createMcpOAuthClientProvider } from "./mcp-oauth-provider.js";
8-
import { readMcpOAuthStore, resolveMcpOAuthStoreKey } from "./mcp-oauth-store.js";
9+
import { readMcpOAuthStore } from "./mcp-oauth-store.js";
910

1011
const SERVER_NAME = "Remote Docs";
1112
const SERVER_URL = "https://mcp.example.com/mcp";
@@ -15,6 +16,7 @@ const ORIGINAL_ISSUER = "https://auth-old.example";
1516
const REPLACEMENT_ISSUER = "https://auth-new.example";
1617
const STORED_ACCESS = "stored-access";
1718
const STORED_REFRESH = "stored-refresh-secret";
19+
const IDENTITY = operatorMcpOAuthIdentity(SERVER_NAME, SERVER_URL);
1820

1921
async function withTempHome<T>(
2022
run: () => T | Promise<T>,
@@ -98,8 +100,7 @@ async function seedAuthorizedStore(
98100
expiresIn = 3600,
99101
) {
100102
const provider = createMcpOAuthClientProvider({
101-
serverName: SERVER_NAME,
102-
serverUrl: SERVER_URL,
103+
identity: IDENTITY,
103104
});
104105
const discoveryState = {
105106
authorizationServerUrl: ORIGINAL_ISSUER,
@@ -125,13 +126,12 @@ function buildOAuthFetch(fetchFn: FetchLike) {
125126
return withMcpOAuthBearer({
126127
fetchFn,
127128
authFetchFn: fetchFn,
128-
serverName: SERVER_NAME,
129-
resourceUrl: SERVER_URL,
129+
identity: IDENTITY,
130130
});
131131
}
132132

133133
function readStore() {
134-
return readMcpOAuthStore(resolveMcpOAuthStoreKey(SERVER_NAME, SERVER_URL));
134+
return readMcpOAuthStore(IDENTITY.storeKey);
135135
}
136136

137137
const TEMP_HOME_OPTIONS = {
@@ -212,8 +212,7 @@ describe("MCP OAuth refresh issuer binding", () => {
212212
async () => {
213213
await seedAuthorizedStore("discovery-then-tokens");
214214
const provider = createMcpOAuthClientProvider({
215-
serverName: SERVER_NAME,
216-
serverUrl: SERVER_URL,
215+
identity: IDENTITY,
217216
});
218217
await provider.saveDiscoveryState?.({
219218
authorizationServerUrl: issuer,
@@ -315,8 +314,7 @@ describe("MCP OAuth refresh issuer binding", () => {
315314
await withTempHome(
316315
async () => {
317316
const provider = createMcpOAuthClientProvider({
318-
serverName: SERVER_NAME,
319-
serverUrl: SERVER_URL,
317+
identity: IDENTITY,
320318
});
321319
await provider.saveClientInformation?.({ client_id: "stored-client-id" });
322320
await provider.saveTokens({

0 commit comments

Comments
 (0)