The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix: request supported offline access for generic MCP OAuth (#14950)
Dotta839cac1343c9
diff --git a/doc/connections/GENERIC-REMOTE-MCP.md b/doc/connections/GENERIC-REMOTE-MCP.mdindex 543c910c63..9cc4d5cd12 100644--- a/doc/connections/GENERIC-REMOTE-MCP.md+++ b/doc/connections/GENERIC-REMOTE-MCP.md@@ -199,6 +199,59 @@ The discovered auth kind, issuer, and resource are persisted on the connection,so refresh, reconnect, revoke and diagnostics all use the generic path instead offalling back to `authKind: none` semantics.+### Staying connected after access-token expiry++For generic MCP connections, Paperclip adds `offline_access` to the selected+tool scopes when the **authorization server** advertises it in+`scopes_supported` and does not explicitly exclude the refresh-token grant.+This works even when the MCP server's challenge or protected-resource metadata+lists only tool scopes. Paperclip requests `prompt=consent`, stores the actual+requested scopes for callback completion and reconnect, and refreshes access+tokens using its existing encrypted-vault and rotating-token lease paths.+Curated Apps continue to use their reviewed scope and authorization-parameter+allowlists.++The provider still decides whether to issue a refresh token. Existing grants+without one require another sign-in; reconnect also discovers refresh support+for older generic connections that already cached their OAuth endpoints.+Transport failures and provider-revoked refresh tokens are separate errors.++#### Local OAuth expiry simulation++Run the standalone MCP/OAuth test server with no external credentials:++```sh+node scripts/mcp-fixtures/servers/oauth-refresh-fixture.mjs+```++It binds only to `127.0.0.1` and prints an MCP URL. Add that URL through+**Apps → Connect an app → Connect your own MCP server** on a local/private+Paperclip instance with a loopback HTTP callback URL, approve the test consent+page, and use **read_status**.+Access tokens last two minutes; later calls should refresh without another+sign-in. Stop the fixture with Ctrl-C; all provider state is in memory.++The fixture separates the MCP resource's `mcp:read` scope from the identity+provider's `offline_access` scope. It issues refresh tokens only with offline+consent and a registered refresh grant, enforces PKCE/client/resource binding,+rejects expired access tokens, and rotates refresh tokens after every use.+Diagnostics record only protocol events and scope names, never token values.++Run the fixture controls and Paperclip integration regressions:++```sh+node --test scripts/mcp-fixtures/servers/oauth-refresh-fixture.test.mjs+pnpm exec vitest run server/src/__tests__/generic-mcp-connection.test.ts+```++The integration tests use actual loopback HTTP and a disposable PostgreSQL+database. They cover shared and personal sign-in, a successful gateway tool+call, two expiry/refresh rotations without another sign-in, scope overrides,+unsupported refresh, and reconnecting a legacy cached connection. Provider time+and cached expiry timestamps are advanced explicitly, so no real-time wait is+needed. The standalone controls prove that omitting offline scope or consent+creates an access-only grant that loses MCP access after expiry.+## Curated definitions remain optionalA curated definition matching a pasted endpoint is offered as a brandeddiff --git a/scripts/mcp-fixtures/servers/oauth-refresh-fixture.mjs b/scripts/mcp-fixtures/servers/oauth-refresh-fixture.mjsnew file mode 100644index 0000000000..e951db9f36--- /dev/null+++ b/scripts/mcp-fixtures/servers/oauth-refresh-fixture.mjs@@ -0,0 +1,179 @@+#!/usr/bin/env node+import { createHash, randomUUID } from "node:crypto";+import { once } from "node:events";+import { createServer } from "node:http";+import { pathToFileURL } from "node:url";++/** A loopback-only MCP + OAuth provider; no vendor account or fetch mock needed. */+export async function startOAuthRefreshFixture({+ port = 0,+ supportsOfflineAccess = true,+ grantTypes = ["authorization_code", "refresh_token"],+ challengeScope = true,+ resourceScopes = ["mcp:read"],+ accessTokenLifetimeSeconds = 3600,+} = {}) {+ const clients = new Map();+ const codes = new Map();+ const accessTokens = new Map();+ const refreshTokens = new Map();+ // Diagnostics deliberately contain no credentials, codes, or PKCE verifiers.+ const events = [];+ let clockOffset = 0;+ let origin;+ const now = () => Date.now() + clockOffset;+ const issuer = () => `${origin}/identity/acme`;+ const resource = () => `${origin}/mcp`;+ const supportedScopes = () => ["mcp:read", "admin:all", ...(supportsOfflineAccess ? ["offline_access"] : [])];+ const json = (res, status, body) => {+ res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });+ res.end(JSON.stringify(body));+ };+ const fail = (res, error) => json(res, 400, { error });++ function issueTokens(grant) {+ const accessToken = `fixture-access-${randomUUID()}`;+ accessTokens.set(accessToken, { ...grant, expiresAt: now() + accessTokenLifetimeSeconds * 1000 });+ const refreshToken = grant.offline ? `fixture-refresh-${randomUUID()}` : null;+ if (refreshToken) refreshTokens.set(refreshToken, grant);+ return {+ access_token: accessToken,+ ...(refreshToken ? { refresh_token: refreshToken } : {}),+ expires_in: accessTokenLifetimeSeconds,+ token_type: "Bearer",+ scope: grant.scopes.join(" "),+ };+ }++ const server = createServer(async (req, res) => {+ try {+ const url = new URL(req.url, origin);+ const chunks = [];+ for await (const chunk of req) chunks.push(chunk);+ const rawBody = Buffer.concat(chunks).toString("utf8");+ const form = new URLSearchParams(rawBody);+ const path = url.pathname;++ if (path === "/.well-known/oauth-protected-resource/mcp") {+ json(res, 200, { resource: resource(), authorization_servers: [issuer()], scopes_supported: resourceScopes });+ } else if (path === "/.well-known/oauth-authorization-server/identity/acme") {+ json(res, 200, {+ issuer: issuer(),+ authorization_endpoint: `${issuer()}/authorize`,+ token_endpoint: `${issuer()}/token`,+ registration_endpoint: `${issuer()}/register`,+ scopes_supported: supportedScopes(),+ grant_types_supported: grantTypes,+ response_types_supported: ["code"],+ code_challenge_methods_supported: ["S256"],+ token_endpoint_auth_methods_supported: ["none"],+ });+ } else if (path === "/identity/acme/register" && req.method === "POST") {+ const metadata = JSON.parse(rawBody);+ if (!Array.isArray(metadata.redirect_uris) || metadata.redirect_uris.some((uri) => {+ const parsed = new URL(uri);+ return parsed.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(parsed.hostname);+ })) return fail(res, "invalid_redirect_uri");+ const requestedGrantTypes = metadata.grant_types ?? ["authorization_code"];+ if (!Array.isArray(requestedGrantTypes) || requestedGrantTypes.some((type) => !grantTypes.includes(type))) return fail(res, "invalid_client_metadata");+ metadata.grant_types = requestedGrantTypes;+ const clientId = `fixture-client-${randomUUID()}`;+ clients.set(clientId, metadata);+ events.push({ kind: "registration", grantTypes: metadata.grant_types });+ json(res, 201, { ...metadata, client_id: clientId });+ } else if (path === "/identity/acme/authorize") {+ const params = req.method === "POST" ? form : url.searchParams;+ const clientId = params.get("client_id");+ const client = clients.get(clientId);+ const redirectUri = params.get("redirect_uri");+ const scopes = (params.get("scope") ?? "").split(/\s+/).filter(Boolean);+ if (!client || !client.redirect_uris.includes(redirectUri)) return fail(res, "invalid_client");+ if (params.get("response_type") !== "code" || params.get("code_challenge_method") !== "S256") return fail(res, "invalid_request");+ if (params.get("resource") !== resource()) return fail(res, "invalid_target");+ if (scopes.some((scope) => !supportedScopes().includes(scope))) return fail(res, "invalid_scope");+ if (req.method === "GET") {+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });+ const escape = (value) => String(value).replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[char]));+ res.end(`<!doctype html><html><title>Test MCP consent</title><h1>Connect the test MCP server</h1><p>Requested scopes: ${escape(scopes.join(" "))}</p><form method="post">${[...params].map(([key, value]) => `<input type="hidden" name="${escape(key)}" value="${escape(value)}">`).join("")}<button name="decision" value="allow">Allow</button><button name="decision" value="deny">Deny</button></form></html>`);+ return;+ }+ const callback = new URL(redirectUri);+ callback.searchParams.set("state", params.get("state") ?? "");+ callback.searchParams.set("iss", issuer());+ if (params.get("decision") !== "allow") callback.searchParams.set("error", "access_denied");+ else {+ const offline = grantTypes.includes("refresh_token") && scopes.includes("offline_access") && params.get("prompt")?.split(/\s+/).includes("consent") && client.grant_types.includes("refresh_token");+ const code = `fixture-code-${randomUUID()}`;+ codes.set(code, {+ clientId, redirectUri, resource: resource(), codeChallenge: params.get("code_challenge"),+ scopes: offline ? scopes : scopes.filter((scope) => scope !== "offline_access"), offline,+ });+ events.push({ kind: "authorization", scopes, prompt: params.get("prompt"), offline: Boolean(offline) });+ callback.searchParams.set("code", code);+ }+ res.writeHead(302, { Location: callback.toString() });+ res.end();+ } else if (path === "/identity/acme/token" && req.method === "POST") {+ const grantType = form.get("grant_type");+ if (!grantTypes.includes(grantType)) return fail(res, "unsupported_grant_type");+ let grant;+ if (grantType === "authorization_code") {+ const code = form.get("code");+ grant = codes.get(code);+ const challenge = createHash("sha256").update(form.get("code_verifier") ?? "").digest("base64url");+ if (!grant || grant.clientId !== form.get("client_id") || grant.redirectUri !== form.get("redirect_uri") || grant.resource !== form.get("resource") || grant.codeChallenge !== challenge) return fail(res, "invalid_grant");+ codes.delete(code);+ } else if (grantType === "refresh_token") {+ const refreshToken = form.get("refresh_token");+ grant = refreshTokens.get(refreshToken);+ if (!grant || grant.clientId !== form.get("client_id") || grant.resource !== form.get("resource")) return fail(res, "invalid_grant");+ refreshTokens.delete(refreshToken); // Rotation: reuse must fail.+ } else return fail(res, "unsupported_grant_type");+ events.push({ kind: "token", grantType, resource: grant.resource, offline: Boolean(grant.offline) });+ json(res, 200, issueTokens(grant));+ } else if (path === "/mcp") {+ const token = accessTokens.get(req.headers.authorization?.replace(/^Bearer /, ""));+ if (!token || token.expiresAt <= now()) {+ events.push({ kind: "mcp_unauthorized" });+ res.writeHead(401, { "WWW-Authenticate": `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"${challengeScope ? ', scope="mcp:read"' : ""}` });+ res.end();+ return;+ }+ if (!token.scopes.includes("mcp:read")) { json(res, 403, { error: "insufficient_scope" }); return; }+ if (req.method !== "POST") { res.writeHead(405); res.end(); return; }+ const rpc = JSON.parse(rawBody);+ events.push({ kind: "mcp", method: rpc.method });+ if (rpc.method === "notifications/initialized") { res.writeHead(202); res.end(); return; }+ let result;+ if (rpc.method === "initialize") result = { protocolVersion: rpc.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: "offline-access-fixture", version: "1.0.0" } };+ else if (rpc.method === "tools/list") result = { tools: [{ name: "read_status", description: "Read the test server status", inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: true } }] };+ else if (rpc.method === "tools/call" && rpc.params.name === "read_status") result = { content: [{ type: "text", text: "Authenticated MCP call succeeded" }] };+ else { json(res, 200, { jsonrpc: "2.0", id: rpc.id, error: { code: -32601, message: "Method not found" } }); return; }+ json(res, 200, { jsonrpc: "2.0", id: rpc.id, result });+ } else { json(res, 404, { error: "not_found" }); }+ } catch {+ json(res, 400, { error: "invalid_request" });+ }+ });+ server.listen(port, "127.0.0.1");+ await once(server, "listening");+ origin = `http://127.0.0.1:${server.address().port}`;+ return {+ origin, mcpUrl: resource(), issuer: issuer(), events,+ /** Advance only provider time; callers can separately expire their cached token. */+ advanceTime(ms) { clockOffset += ms; },+ async close() {+ const closed = new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));+ server.closeAllConnections();+ await closed;+ },+ };+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ const fixture = await startOAuthRefreshFixture({ port: Number(process.env.PORT ?? 0), accessTokenLifetimeSeconds: 120 });+ console.log(JSON.stringify({ event: "ready", mcpUrl: fixture.mcpUrl, accessTokenLifetimeSeconds: 120 }));+ const stop = async () => { await fixture.close(); process.exit(0); };+ process.once("SIGINT", stop);+ process.once("SIGTERM", stop);+}diff --git a/scripts/mcp-fixtures/servers/oauth-refresh-fixture.test.mjs b/scripts/mcp-fixtures/servers/oauth-refresh-fixture.test.mjsnew file mode 100644index 0000000000..bc10e45cdf--- /dev/null+++ b/scripts/mcp-fixtures/servers/oauth-refresh-fixture.test.mjs@@ -0,0 +1,92 @@+import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import test from "node:test";+import { startOAuthRefreshFixture } from "./oauth-refresh-fixture.mjs";++async function connect(fixture, { offline = true, consent = true, grantTypes = ["authorization_code", "refresh_token"] } = {}) {+ const redirectUri = "http://127.0.0.1:3100/api/tools/oauth/callback";+ const registration = await fetch(`${fixture.issuer}/register`, {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ redirect_uris: [redirectUri], grant_types: grantTypes }),+ });+ assert.equal(registration.status, 201);+ const client = await registration.json();+ const verifier = "fixture-proof-key-for-tests";+ const authorization = new URLSearchParams({+ client_id: client.client_id, redirect_uri: redirectUri, response_type: "code", state: "fixture-state",+ resource: fixture.mcpUrl, code_challenge_method: "S256",+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),+ scope: offline ? "mcp:read offline_access" : "mcp:read", decision: "allow",+ ...(consent ? { prompt: "consent" } : {}),+ });+ const response = await fetch(`${fixture.issuer}/authorize`, { method: "POST", body: authorization, redirect: "manual" });+ assert.equal(response.status, 302);+ const callback = new URL(response.headers.get("location"));+ const exchangeBody = new URLSearchParams({+ grant_type: "authorization_code", client_id: client.client_id, redirect_uri: redirectUri,+ resource: fixture.mcpUrl, code_verifier: verifier, code: callback.searchParams.get("code"),+ });+ const exchange = await fetch(`${fixture.issuer}/token`, { method: "POST", body: exchangeBody });+ assert.equal(exchange.status, 200);+ return { tokens: await exchange.json(), clientId: client.client_id };+}++async function call(fixture, accessToken) {+ return fetch(fixture.mcpUrl, {+ method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}` },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "read_status", arguments: {} } }),+ });+}++for (const options of [{ offline: false }, { consent: false }]) {+ test(`access-only grant disconnects after expiry: ${JSON.stringify(options)}`, async () => {+ const fixture = await startOAuthRefreshFixture();+ try {+ const { tokens } = await connect(fixture, options);+ assert.equal(tokens.refresh_token, undefined);+ assert.equal((await call(fixture, tokens.access_token)).status, 200);+ fixture.advanceTime(3_601_000);+ assert.equal((await call(fixture, tokens.access_token)).status, 401);+ } finally { await fixture.close(); }+ });+}++test("authorization-code-only provider rejects refresh registration and token requests", async () => {+ const fixture = await startOAuthRefreshFixture({ grantTypes: ["authorization_code"] });+ try {+ const registration = await fetch(`${fixture.issuer}/register`, {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ redirect_uris: ["http://127.0.0.1:3100/api/tools/oauth/callback"], grant_types: ["authorization_code", "refresh_token"] }),+ });+ assert.equal(registration.status, 400);+ assert.deepEqual(await registration.json(), { error: "invalid_client_metadata" });+ const { tokens, clientId } = await connect(fixture, { grantTypes: ["authorization_code"] });+ assert.equal(tokens.refresh_token, undefined);+ assert.equal((await call(fixture, tokens.access_token)).status, 200);+ const body = new URLSearchParams({ grant_type: "refresh_token", client_id: clientId, resource: fixture.mcpUrl, refresh_token: "unissued-token" });+ const refresh = await fetch(`${fixture.issuer}/token`, { method: "POST", body });+ assert.equal(refresh.status, 400);+ assert.deepEqual(await refresh.json(), { error: "unsupported_grant_type" });+ fixture.advanceTime(3_601_000);+ assert.equal((await call(fixture, tokens.access_token)).status, 401);+ } finally { await fixture.close(); }+});++test("offline consent permits refresh, requires the same resource, and rejects refresh-token reuse", async () => {+ const fixture = await startOAuthRefreshFixture();+ try {+ const { tokens, clientId } = await connect(fixture);+ assert.ok(tokens.refresh_token);+ fixture.advanceTime(3_601_000);+ assert.equal((await call(fixture, tokens.access_token)).status, 401);+ const body = new URLSearchParams({ grant_type: "refresh_token", client_id: clientId, resource: `${fixture.origin}/other`, refresh_token: tokens.refresh_token });+ assert.equal((await fetch(`${fixture.issuer}/token`, { method: "POST", body })).status, 400);+ body.set("resource", fixture.mcpUrl);+ const refresh = await fetch(`${fixture.issuer}/token`, { method: "POST", body });+ assert.equal(refresh.status, 200);+ const rotated = await refresh.json();+ assert.notEqual(rotated.refresh_token, tokens.refresh_token);+ assert.equal((await call(fixture, rotated.access_token)).status, 200);+ assert.equal((await fetch(`${fixture.issuer}/token`, { method: "POST", body })).status, 400);+ } finally { await fixture.close(); }+});diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.tsindex a25aefede6..2374ad0c46 100644--- a/server/src/__tests__/generic-mcp-connection.test.ts+++ b/server/src/__tests__/generic-mcp-connection.test.ts@@ -50,6 +50,7 @@ import { toolAccessRoutes } from "../routes/tool-access.js";import { errorHandler } from "../middleware/index.js";import { createHttpLogger } from "../middleware/logger.js";import { HTTP_LOG_REDACT_PATHS } from "../middleware/http-log-redaction.js";+import { startOAuthRefreshFixture } from "../../../scripts/mcp-fixtures/servers/oauth-refresh-fixture.mjs";const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;@@ -853,6 +854,198 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {.toEqual(["oauth.access_token", "oauth.refresh_token"]);});+ async function approveFixtureAuthorization(authorizationUrl: string) {+ const url = new URL(authorizationUrl);+ const consent = await fetch(url);+ expect(consent.status).toBe(200);+ expect(await consent.text()).toContain("Connect the test MCP server");+ const body = new URLSearchParams(url.search);+ body.set("decision", "allow");+ const response = await fetch(url, { method: "POST", body, redirect: "manual" });+ expect(response.status).toBe(302);+ return new URL(response.headers.get("location")!);+ }++ async function expireFixtureCredentials(connectionId: string) {+ const expiredAt = new Date(Date.now() - 1000).toISOString();+ const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, connectionId));+ const config = { ...connection!.config, oauth: { ...connection!.config.oauth as object, expiresAt: expiredAt } };+ await db.update(toolConnections).set({ config, transportConfig: config }).where(eq(toolConnections.id, connectionId));+ const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connectionId));+ for (const grant of grants) {+ await db.update(connectionGrants).set({+ providerTenant: { ...grant.providerTenant, oauth: { ...grant.providerTenant?.oauth as object, accessTokenExpiresAt: expiredAt } },+ }).where(eq(connectionGrants.id, grant.id));+ }+ }++ it.each(["organization", "user"] as const)("keeps a real %s MCP connection usable across offline-access token expiry and rotation", async (grantKind) => {+ const fixture = await startOAuthRefreshFixture();+ try {+ const company = await createCompany(db);+ const app = createRouteApp(db, { deploymentMode: "local_trusted", deploymentExposure: "private" });+ const redirectUri = "http://127.0.0.1:3100/api/tools/oauth/callback";+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "http://127.0.0.1:3100");+ const actor = { actorType: "user" as const, actorId: "board-user" };+ const connected = await request(app).post(`/api/companies/${company.id}/tools/apps/connect`)+ .send({ link: fixture.mcpUrl, name: "Offline access MCP", grantKind }).expect(201);+ const connectionId = connected.body.connectionId;+ const start = await request(app).post(`/api/tools/oauth/${connectionId}/start`)+ .send(grantKind === "user" ? { asCurrentUser: true } : {}).expect(200);+ const callback = await approveFixtureAuthorization(start.body.authorizationUrl);+ await toolAccessService(db).completeOAuthCallback({+ state: callback.searchParams.get("state")!, code: callback.searchParams.get("code")!,+ iss: callback.searchParams.get("iss")!, redirectUri, actor,+ });+ const service = toolAccessService(db);+ const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Offline access reader", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning();+ const catalog = await service.refreshCatalog(connectionId, actor);+ await service.finishGalleryAppConnection(company.id, connectionId, {+ enabledCatalogEntryIds: catalog.catalog.map((entry) => entry.id), askFirstCatalogEntryIds: [], access: { agentIds: [agent!.id] },+ }, actor);+ const call = () => createToolGatewayService(db).executeTestCall({+ companyId: company.id, connectionId, agentId: agent!.id, userId: "board-user", toolName: "read_status", parameters: {},+ });+ const successfulCall = { decision: "allowed", result: { data: { content: [{ type: "text", text: "Authenticated MCP call succeeded" }] } } };+ await expect(call()).resolves.toMatchObject(successfulCall);+ // The provider actually rejects its old access token. Expire Paperclip's+ // cached timestamp too, without waiting an hour or mocking global time.+ for (let rotation = 0; rotation < 2; rotation += 1) {+ fixture.advanceTime(3_601_000);+ await expireFixtureCredentials(connectionId);+ await expect(service.refreshCatalog(connectionId, actor)).resolves.toMatchObject({ catalog: [expect.objectContaining({ toolName: "read_status" })] });+ await expect(call()).resolves.toMatchObject(successfulCall);+ }+ expect(fixture.events.filter((event) => event.kind === "registration")).toHaveLength(1);+ expect(fixture.events.filter((event) => event.kind === "authorization")).toEqual([+ { kind: "authorization", scopes: ["mcp:read", "offline_access"], prompt: "consent", offline: true },+ ]);+ expect(fixture.events.filter((event) => event.kind === "token").map((event) => event.grantType))+ .toEqual(["authorization_code", "refresh_token", "refresh_token"]);+ const state = await service.getConnection(connectionId, company.id);+ expect(JSON.stringify(state)).not.toMatch(/fixture-(access|refresh)-/);+ } finally { await fixture.close(); }+ });++ it.each([+ { challengeScope: false, resourceScopes: ["mcp:read"], requestedScopes: undefined },+ { challengeScope: false, resourceScopes: [], requestedScopes: ["mcp:read"] },+ ])("adds only offline access to generic discovery scopes ($resourceScopes)", async (options) => {+ const fixture = await startOAuthRefreshFixture(options);+ try {+ const company = await createCompany(db);+ const service = toolAccessService(db);+ const connected = await service.connectGalleryApp(company.id, { link: fixture.mcpUrl });+ // Explicit scope overrides must still get refresh capability, and must+ // remain the saved scope set used by reconnect and callback persistence.+ const actor = { actorType: "user" as const, actorId: "board-user" };+ const input = { redirectUri: "http://127.0.0.1:3100/api/tools/oauth/callback", actor, scopes: options.requestedScopes };+ const start = await service.startOAuth(company.id, connected.connectionId, input);+ expect(new URL(start.authorizationUrl).searchParams.get("scope")).toBe("mcp:read offline_access");+ const saved = await service.getConnection(connected.connectionId, company.id);+ expect(saved.config.oauth).toMatchObject({ scopes: ["mcp:read", "offline_access"] });+ const callback = await approveFixtureAuthorization(start.authorizationUrl);+ const completed = await service.completeOAuthCallback({+ state: callback.searchParams.get("state")!, code: callback.searchParams.get("code")!,+ iss: callback.searchParams.get("iss")!, redirectUri: input.redirectUri, actor,+ });+ expect(completed.connection.config.oauth).toMatchObject({ scopes: ["mcp:read", "offline_access"] });+ const reconnect = await service.startOAuth(company.id, connected.connectionId, { redirectUri: input.redirectUri, actor });+ expect(new URL(reconnect.authorizationUrl).searchParams.get("scope")).toBe("mcp:read offline_access");+ } finally { await fixture.close(); }+ });++ it.each([+ { supportsOfflineAccess: false },+ { grantTypes: ["authorization_code"] },+ ])("does not request offline access when the authorization server does not support refresh ($supportsOfflineAccess, $grantTypes)", async (options) => {+ const fixture = await startOAuthRefreshFixture(options);+ try {+ const company = await createCompany(db);+ const service = toolAccessService(db);+ const connected = await service.connectGalleryApp(company.id, { link: fixture.mcpUrl });+ const start = await service.startOAuth(company.id, connected.connectionId, {+ redirectUri: "http://127.0.0.1:3100/api/tools/oauth/callback", actor: { actorType: "user", actorId: "board-user" },+ });+ const url = new URL(start.authorizationUrl);+ expect(url.searchParams.get("scope")).toBe("mcp:read");+ expect(url.searchParams.has("prompt")).toBe(false);+ const callback = await approveFixtureAuthorization(start.authorizationUrl);+ expect(callback.searchParams.has("code")).toBe(true);+ expect(fixture.events.find((event) => event.kind === "authorization").offline).toBe(false);+ const completed = await service.completeOAuthCallback({+ state: callback.searchParams.get("state")!, code: callback.searchParams.get("code")!,+ iss: callback.searchParams.get("iss")!, redirectUri: "http://127.0.0.1:3100/api/tools/oauth/callback",+ actor: { actorType: "user", actorId: "board-user" },+ });+ expect(completed.connection.status).toBe("active");+ expect(completed.connection.credentialSecretRefs.some((ref) => ref.configPath === "oauth.access_token")).toBe(true);+ expect(completed.connection.credentialSecretRefs.some((ref) => ref.configPath === "oauth.refresh_token")).toBe(false);+ } finally { await fixture.close(); }+ });++ it.each([+ { name: "different authorization endpoint", authorizationUrl: `${ISSUER}/other-authorize`, tokenUrl: `${ISSUER}/token`, issuer: ISSUER, offline: false },+ { name: "different token endpoint", authorizationUrl: `${ISSUER}/authorize`, tokenUrl: `${ISSUER}/other-token`, issuer: ISSUER, offline: false },+ { name: "different issuer", authorizationUrl: `${ISSUER}/authorize`, tokenUrl: `${ISSUER}/token`, issuer: `${MCP_ORIGIN}/tenant/other`, offline: false },+ { name: "matching endpoints and issuer", authorizationUrl: `${ISSUER}/authorize`, tokenUrl: `${ISSUER}/token`, issuer: ISSUER, offline: true },+ ])("binds offline support to the selected OAuth server: $name", async (candidate) => {+ const fixture = installMcpOAuthFixture({ auth: "oauth" });+ const originalFetch = fixture.fetchMock.getMockImplementation()!;+ fixture.fetchMock.mockImplementation(async (url, init) => {+ const href = String(url);+ if (href === `${MCP_ORIGIN}/.well-known/oauth-protected-resource/mcp`) {+ return jsonResponse({+ resource: MCP_URL, issuer: ISSUER, authorization_servers: [candidate.issuer],+ authorization_endpoint: `${ISSUER}/authorize`, token_endpoint: `${ISSUER}/token`,+ registration_endpoint: `${ISSUER}/register`, scopes_supported: ["mcp:read"],+ code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["none"],+ });+ }+ const issuerPath = new URL(candidate.issuer).pathname;+ if (href === `${MCP_ORIGIN}/.well-known/oauth-authorization-server${issuerPath}`) {+ return jsonResponse({+ issuer: candidate.issuer, authorization_endpoint: candidate.authorizationUrl,+ token_endpoint: candidate.tokenUrl, scopes_supported: ["mcp:read", "offline_access"],+ grant_types_supported: ["authorization_code", "refresh_token"],+ });+ }+ return originalFetch(url, init);+ });+ const company = await createCompany(db);+ const service = toolAccessService(db);+ const connected = await service.connectGalleryApp(company.id, { link: MCP_URL });+ const start = await service.startOAuth(company.id, connected.connectionId, {+ redirectUri: REDIRECT_URI, actor: { actorType: "user", actorId: "board-user" },+ });+ const url = new URL(start.authorizationUrl);+ expect(url.origin + url.pathname).toBe(`${ISSUER}/authorize`);+ expect(url.searchParams.get("scope")).toBe(candidate.offline ? "mcp:read offline_access" : "mcp:read");+ expect(url.searchParams.get("prompt")).toBe(candidate.offline ? "consent" : null);+ });++ it("discovers offline refresh support when reconnecting a legacy connection with cached endpoints", async () => {+ const fixture = await startOAuthRefreshFixture();+ try {+ const company = await createCompany(db);+ const service = toolAccessService(db);+ const connected = await service.connectGalleryApp(company.id, { link: fixture.mcpUrl });+ const input = { redirectUri: "http://127.0.0.1:3100/api/tools/oauth/callback", actor: { actorType: "user" as const, actorId: "board-user" } };+ await service.startOAuth(company.id, connected.connectionId, input);+ const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId));+ const oauth = { ...connection!.config.oauth as Record<string, unknown>, scopes: ["mcp:read"] };+ delete oauth.offlineAccessSupported;+ delete oauth.grantTypesSupported;+ const config = { ...connection!.config, oauth };+ await db.update(toolConnections).set({ config, transportConfig: config }).where(eq(toolConnections.id, connected.connectionId));+ const reconnect = await service.startOAuth(company.id, connected.connectionId, input);+ const url = new URL(reconnect.authorizationUrl);+ expect(url.searchParams.get("scope")).toBe("mcp:read offline_access");+ expect(url.searchParams.get("prompt")).toBe("consent");+ expect(fixture.events.filter((event) => event.kind === "registration")).toHaveLength(1);+ } finally { await fixture.close(); }+ });+it("discovers OAuth for a personal URL connection before its user grant exists", async () => {const fixture = installMcpOAuthFixture({ auth: "oauth" });const company = await createCompany(db);diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.tsindex 08d6472532..6f9ad22446 100644--- a/server/src/services/tool-access.ts+++ b/server/src/services/tool-access.ts@@ -495,6 +495,8 @@ export function oauthClientIdMetadataDocument(input: {type OAuthProviderEndpoints = {provider: string;scopes: string[];+ /** Refresh permission belongs to authorization-server metadata, not MCP tool scopes. */+ offlineAccessSupported?: boolean;authorizationUrl: string;tokenUrl: string;registrationUrl?: string | null;@@ -8752,6 +8754,9 @@ export function toolAccessService(firstPartyOrigin,);let scopes = normalizeOauthScopes(metadata.scopes_supported);+ let offlineAccessSupported = Boolean(+ authorizationUrl && scopes.includes("offline_access"),+ );let codeChallengeMethodsSupported = normalizeOauthScopes(metadata.code_challenge_methods_supported,);@@ -8804,6 +8809,15 @@ export function toolAccessService(!sameOAuthIssuer(advertisedIssuer, candidate.issuer))continue;+ // A document can carry its own endpoints and also list other servers.+ // Adopt capabilities only from metadata bound to the selected endpoints+ // and issuer; otherwise offline access could break an unrelated sign-in.+ if (+ (authorizationUrl && candidateAuthorizationUrl !== authorizationUrl) ||+ (tokenUrl && candidateTokenUrl !== tokenUrl) ||+ (issuer && !sameOAuthIssuer(issuer, advertisedIssuer ?? candidate.issuer))+ )+ continue;authorizationUrl = authorizationUrl ?? candidateAuthorizationUrl;tokenUrl = tokenUrl ?? candidateTokenUrl;registrationUrl =@@ -8815,6 +8829,8 @@ export function toolAccessService(firstPartyOrigin,);issuer = issuer ?? advertisedIssuer ?? candidate.issuer;+ offlineAccessSupported = offlineAccessSupported ||+ normalizeOauthScopes(authMetadata.scopes_supported).includes("offline_access");if (scopes.length === 0)scopes = normalizeOauthScopes(authMetadata.scopes_supported);if (codeChallengeMethodsSupported.length === 0) {@@ -8842,6 +8858,7 @@ export function toolAccessService(return {provider: oauthProviderForConnection(connection, metadataUrl),scopes,+ offlineAccessSupported,authorizationUrl,tokenUrl,registrationUrl,@@ -8908,9 +8925,31 @@ export function toolAccessService(? oauth.resource.trim(): canonicalResourceIndicator(remoteEndpoint(connection.config));if (configuredAuthorizationUrl && configuredTokenUrl) {+ // Pre-existing generic connections cached endpoints before refresh-scope+ // support was recorded. Recover that capability from their bound metadata+ // without adopting a different issuer or changing their requested tool scopes.+ let refreshMetadata: OAuthProviderEndpoints | null = null;+ if (+ !connection.config.sourceTemplateKey &&+ typeof oauth.offlineAccessSupported !== "boolean" &&+ typeof oauth.metadataUrl === "string"+ ) {+ const discovered = await endpointsFromMetadataUrl(+ connection, oauth.metadataUrl, rejections, firstPartyOrigin,+ );+ if (+ discovered?.authorizationUrl === configuredAuthorizationUrl &&+ discovered.tokenUrl === configuredTokenUrl &&+ (typeof oauth.issuer !== "string" ||+ (discovered.issuer && sameOAuthIssuer(discovered.issuer, oauth.issuer)))+ ) refreshMetadata = discovered;+ }return {provider,scopes,+ offlineAccessSupported: typeof oauth.offlineAccessSupported === "boolean"+ ? oauth.offlineAccessSupported+ : refreshMetadata?.offlineAccessSupported,authorizationUrl: configuredAuthorizationUrl,tokenUrl: configuredTokenUrl,registrationUrl: safeOAuthEndpointUrl(@@ -8925,6 +8964,9 @@ export function toolAccessService(tokenEndpointAuthMethodsSupported: normalizeOauthScopes(oauth.tokenEndpointAuthMethodsSupported,),+ grantTypesSupported: Array.isArray(oauth.grantTypesSupported)+ ? normalizeOauthScopes(oauth.grantTypesSupported)+ : refreshMetadata?.grantTypesSupported,grantType,metadataUrl:typeof oauth.metadataUrl === "string"@@ -9541,6 +9583,8 @@ export function toolAccessService(registrationUrl: input.endpoints.registrationUrl,metadataUrl: input.endpoints.metadataUrl ?? null,scopes: input.endpoints.scopes,+ offlineAccessSupported: input.endpoints.offlineAccessSupported,+ grantTypesSupported: input.endpoints.grantTypesSupported ?? [],codeChallengeMethodsSupported:input.endpoints.codeChallengeMethodsSupported ?? [],tokenEndpointAuthMethodsSupported:@@ -9607,6 +9651,8 @@ export function toolAccessService(registrationUrl: input.endpoints.registrationUrl ?? null,metadataUrl: input.endpoints.metadataUrl ?? null,scopes: input.endpoints.scopes,+ offlineAccessSupported: input.endpoints.offlineAccessSupported,+ grantTypesSupported: input.endpoints.grantTypesSupported ?? [],codeChallengeMethodsSupported:input.endpoints.codeChallengeMethodsSupported ?? [],tokenEndpointAuthMethodsSupported:@@ -14242,6 +14288,17 @@ export function toolAccessService(`OAuth client id is not configured for ${endpoints.provider}`,);+ const authorizationScopes = normalizeOauthScopes(+ galleryMethod ? (requestedScopes ?? []) : (input.scopes ?? endpoints.scopes),+ );+ if (+ !galleryMethod &&+ endpoints.offlineAccessSupported &&+ (!endpoints.grantTypesSupported?.length ||+ endpoints.grantTypesSupported.includes("refresh_token")) &&+ !authorizationScopes.includes("offline_access")+ ) authorizationScopes.push("offline_access");+await db.delete(toolOauthStates).where(lt(toolOauthStates.expiresAt, new Date()));@@ -14262,7 +14319,7 @@ export function toolAccessService(createdByActorId: binding.actorId,createdBySessionId: binding.sessionId,subjectUserId: authorizationSubjectUserId,- requestedScopes: requestedScopes ?? undefined,+ requestedScopes: authorizationScopes,returnTo: input.returnTo,issueId: intentLink?.issueId ?? input.issueId,interactionId: intentLink?.id,@@ -14298,9 +14355,6 @@ export function toolAccessService(// method either sends its reviewed hint or omits scope entirely. Generic// MCP URLs retain discovery-first behavior because Paperclip has no manifest// against which it could safely judge the caller's requested scope.- const authorizationScopes = galleryMethod- ? (requestedScopes ?? [])- : (input.scopes ?? endpoints.scopes);if (authorizationScopes.length > 0)authorizationUrl.searchParams.set("scope", authorizationScopes.join(" "));const reviewedAuthorizationParams =@@ -14315,6 +14369,10 @@ export function toolAccessService("prompt",reviewedAuthorizationParams.prompt,);+ else if (!galleryMethod && authorizationScopes.includes("offline_access"))+ // OIDC offline access requires consent unless the provider has another+ // established basis for granting it. A generic server has no reviewed override.+ authorizationUrl.searchParams.set("prompt", "consent");if (authorizationSubjectUserId &&@@ -14442,7 +14500,9 @@ export function toolAccessService(// Curated apps persist only the reviewed scopes attached to this OAuth// state. Discovery metadata can advertise a provider's entire scope// universe and must never silently become Paperclip's requested set.- scopes: galleryMethod ? (requestedScopes ?? []) : endpoints.scopes,+ scopes: authorizationScopes,+ offlineAccessSupported: endpoints.offlineAccessSupported,+ grantTypesSupported: endpoints.grantTypesSupported ?? [],codeChallengeMethodsSupported:endpoints.codeChallengeMethodsSupported ?? [],tokenEndpointAuthMethodsSupported:@@ -15509,6 +15569,11 @@ export function toolAccessService(input.redirectUri,);assertOAuthCallbackIssuer(connection, endpoints, input.iss);+ // Generic states created before requested scopes were persisted may still+ // complete after an upgrade. Keep their original cached/discovered scope set.+ const authorizedScopes = normalizeOauthScopes(+ stateRow.requestedScopes ?? (galleryEntry ? [] : endpoints.scopes),+ );const client = await oauthClientForConnection(connection,endpoints.provider,@@ -15631,7 +15696,7 @@ export function toolAccessService(strategy: "direct_oauth",accessTokenExpiresAt: expiresAt ?? undefined,scopes: normalizeOauthScopes(- token.scope ?? stateRow.requestedScopes,+ token.scope ?? authorizedScopes,),tokenType: token.tokenType,refreshedAt: connectedAt.toISOString(),@@ -15669,9 +15734,7 @@ export function toolAccessService(authorizationUrl: endpoints.authorizationUrl,tokenUrl: endpoints.tokenUrl,metadataUrl: endpoints.metadataUrl ?? null,- scopes: galleryEntry- ? normalizeOauthScopes(stateRow.requestedScopes)- : endpoints.scopes,+ scopes: authorizedScopes,clientIdEnv: client.clientIdEnv,clientSecretEnv: client.clientSecret? client.clientSecretEnv@@ -15933,9 +15996,7 @@ export function toolAccessService(authorizationUrl: endpoints.authorizationUrl,tokenUrl: endpoints.tokenUrl,metadataUrl: endpoints.metadataUrl ?? null,- scopes: galleryEntry- ? normalizeOauthScopes(stateRow.requestedScopes)- : endpoints.scopes,+ scopes: authorizedScopes,clientIdEnv: client.clientIdEnv,clientSecretEnv: client.clientSecret ? client.clientSecretEnv : null,credentialScope: credentialScope(connection, input.actor),