Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(mcp): keep OAuth credentials on cloud saves and skip consent when tokens still work (#17677)

Hiep Le446fae2c0048
diff --git a/__tests__/api/settings-service.test.ts b/__tests__/api/settings-service.test.ts
index 4231ca7cfc..fff99df9c1 100644
--- a/__tests__/api/settings-service.test.ts
+++ b/__tests__/api/settings-service.test.ts
@@ -609,7 +609,7 @@ describe("SettingsService", () => {
});
});
- it("converts OAuth token state to headers when saving mcp_config to cloud", async () => {
+ it("keeps the OAuth credential and its token state when saving mcp_config to cloud", async () => {
setRegisteredBackends([cloudBackend]);
setActiveSelection({ backendId: cloudBackend.id });
@@ -643,8 +643,17 @@ describe("SettingsService", () => {
notion: {
transport: "http",
url: "https://mcp.example.com/mcp",
- headers: {
- Authorization: "Bearer oauth-access-token",
+ auth: {
+ strategy: "oauth2",
+ authentication: {
+ type: "oauth",
+ client_auth_method: "client_secret_post",
+ },
+ state: {
+ tokens: {
+ access_token: "oauth-access-token",
+ },
+ },
},
},
},
@@ -652,6 +661,50 @@ describe("SettingsService", () => {
});
});
+ it("tombstones a legacy bearer header when a cloud MCP keeps its OAuth credential", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+ // Stored by the flattening earlier Canvas versions applied on cloud saves.
+ mockFetchCloudSettings.mockResolvedValue({
+ agent_settings: {
+ mcp_config: {
+ gitlab: {
+ url: "https://gitlab.example/api/v4/mcp",
+ headers: { Authorization: "**********" },
+ },
+ },
+ },
+ });
+ const auth = {
+ strategy: "oauth2" as const,
+ authentication: {
+ type: "oauth" as const,
+ client_auth_method: "none" as const,
+ },
+ state: {
+ tokens: {
+ access_token: "fresh-access-token",
+ refresh_token: "fresh-refresh-token",
+ },
+ },
+ };
+
+ await SettingsService.patchMcpServer("gitlab", { auth });
+
+ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);
+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({
+ agent_settings_diff: {
+ mcp_config: {
+ gitlab: {
+ url: "https://gitlab.example/api/v4/mcp",
+ headers: {},
+ auth,
+ },
+ },
+ },
+ });
+ });
+
it("clears cloud MCP credential headers when auth is explicitly cleared", async () => {
setRegisteredBackends([cloudBackend]);
setActiveSelection({ backendId: cloudBackend.id });
diff --git a/src/api/mcp-service/mcp-service.api.test.ts b/src/api/mcp-service/mcp-service.api.test.ts
index 6d2af2b8e2..0eddfc4888 100644
--- a/src/api/mcp-service/mcp-service.api.test.ts
+++ b/src/api/mcp-service/mcp-service.api.test.ts
@@ -736,19 +736,17 @@ describe("McpService.testServer", () => {
expect(close).toHaveBeenCalledOnce();
});
- it("rejects an OAuth start response without an authorization URL", async () => {
+ it("polls the status route when OAuth starts without an authorization URL", async () => {
const popup = popupWindow();
vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);
startOAuth.mockResolvedValueOnce({ ok: true, job_id: "job-1" });
const result = await McpService.authorizeOAuth(oauthServer());
- expect(result).toEqual({
- ok: false,
- error: "Could not start OAuth authorization",
- error_kind: "unknown",
- });
+ expect(result).toEqual({ ok: true, tools: ["search_mail"] });
+ expect(getOAuthStatus).toHaveBeenCalledWith("job-1");
expect(popup.close).toHaveBeenCalledOnce();
+ expect(popup.location.href).toBe("about:blank");
});
it("returns an immediately completed OAuth result with optional state", async () => {
diff --git a/src/api/mcp-service/mcp-service.api.ts b/src/api/mcp-service/mcp-service.api.ts
index 32bffcfa9a..697cc7dafa 100644
--- a/src/api/mcp-service/mcp-service.api.ts
+++ b/src/api/mcp-service/mcp-service.api.ts
@@ -313,12 +313,12 @@ class McpService {
finalizeMcpTestResponse(result, validation, [server]);
// Opened synchronously inside the click handler so popup blockers allow
// it; every failure path below closes it again.
- const popup = window.open("about:blank", "_blank");
+ let popup: Window | null = window.open("about:blank", "_blank");
let transport: McpOAuthTransport | null = null;
try {
transport = McpService.createOAuthTransport();
const start = await transport.start(server);
- if (!start.ok || !start.job_id || !start.authorization_url) {
+ if (!start.ok || !start.job_id) {
popup?.close();
return finalize({
ok: false,
@@ -326,6 +326,13 @@ class McpService {
error_kind: start.error_kind || "unknown",
});
}
+ // No authorization URL: the probe completed on the stored tokens (still
+ // valid, or refreshed), so no consent is needed and the outcome is read
+ // from the status route.
+ if (!start.authorization_url) {
+ popup?.close();
+ popup = null;
+ }
let status = await transport.status(start.job_id);
for (let attempt = 0; attempt < 20; attempt += 1) {
@@ -338,7 +345,7 @@ class McpService {
status = await transport.status(start.job_id);
}
- if (popup) {
+ if (popup && start.authorization_url) {
popup.location.href = start.authorization_url;
}
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index 5634146dba..8932d66169 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -292,6 +292,13 @@ export const headersFromMcpAuth = (
/**
* Convert SDK `auth` credentials to the cloud's header-only storage shape.
*
+ * An `oauth2` credential is the exception and is sent as-is: the app server
+ * stores its token state under `auth.state` (restoring redacted parts by
+ * key) and the sandbox refreshes the access token from it. Flattening it to
+ * a bearer header drops the refresh token, so the server stops working once
+ * the access token expires. A header the old flattening stored is tombstoned
+ * like any other header the credential no longer produces.
+ *
* Only the entries in `value` are converted. The cloud `POST /api/v1/settings`
* applies an `mcp_config` map WITHOUT a `null` entry as a full-catalog
* replacement and only a map WITH a `null` entry (delete / rename) as a
@@ -359,7 +366,10 @@ const cloudCompatibleMcpConfig = async (
}
if (!isRecord(server.auth)) return [name, server];
- const authHeaders = headersFromMcpAuth(server.auth);
+ const keepsAuth = server.auth.strategy === "oauth2";
+ const authHeaders: Record<string, string> | null = keepsAuth
+ ? {}
+ : headersFromMcpAuth(server.auth);
if (authHeaders === null) return [name, server];
const nextServer = { ...server };
@@ -376,7 +386,7 @@ const cloudCompatibleMcpConfig = async (
}
}
- delete nextServer.auth;
+ if (!keepsAuth) delete nextServer.auth;
if (Object.keys(mergedHeaders).length > 0) {
nextServer.headers = mergedHeaders;
} else {