Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(mcp): preserve OAuth issuer paths and resource scopes

zszz34c59cd5378ff
diff --git a/apps/desktop/electron/main/mcp-oauth-discovery.ts b/apps/desktop/electron/main/mcp-oauth-discovery.ts
new file mode 100644
index 000000000..446fdb45d
--- /dev/null
+++ b/apps/desktop/electron/main/mcp-oauth-discovery.ts
@@ -0,0 +1,56 @@
+/** MCP authorization discovery rules, independent of network and login state. */
+export function authorizationMetadataUrls(issuer: URL): string[] {
+ const path = issuer.pathname.replace(/\/+$/, "");
+ const paths = path
+ ? [
+ `/.well-known/oauth-authorization-server${path}`,
+ `/.well-known/openid-configuration${path}`,
+ `${path}/.well-known/openid-configuration`,
+ ]
+ : ["/.well-known/oauth-authorization-server", "/.well-known/openid-configuration"];
+ return paths.map((candidate) => {
+ const url = new URL(issuer.origin);
+ url.pathname = candidate;
+ return url.toString();
+ });
+}
+
+/** Read one Bearer challenge without borrowing parameters from another scheme. */
+export function parseBearerChallenge(header: string): {
+ resourceMetadataUrl?: string;
+ scope?: string;
+} {
+ const params = new Map<string, string>();
+ let bearer = false;
+ // Commas inside quoted strings delimit neither parameters nor challenges.
+ for (const part of header.match(/(?:[^",]|"(?:\\.|[^"\\])*")+/g) ?? []) {
+ let value = part.trim();
+ const scheme = value.match(/^([!#$%&'*+.^_`|~0-9A-Za-z-]+)(?:[ \t]+(?![ \t]*=)|$)/);
+ if (scheme) {
+ if (bearer) break;
+ bearer = scheme[1].toLowerCase() === "bearer";
+ value = value.slice(scheme[0].length);
+ }
+ if (!bearer) continue;
+ const param = value.match(/^([\w-]+)\s*=\s*(?:"((?:\\.|[^"\\])*)"|([^\s,]+))\s*$/);
+ if (param) {
+ const key = param[1].toLowerCase();
+ if (!params.has(key)) params.set(key, param[2]?.replace(/\\(.)/g, "$1") ?? param[3]);
+ }
+ }
+ return { resourceMetadataUrl: params.get("resource_metadata"), scope: params.get("scope") };
+}
+
+// RFC 6749 scope-token excludes whitespace, double quotes and backslashes.
+function isScopeToken(value: unknown): value is string {
+ return typeof value === "string" && /^[\x21\x23-\x5B\x5D-\x7E]+$/.test(value);
+}
+
+export function selectOAuthScope(challengeScope: string | undefined, resourceScopes: unknown): string | undefined {
+ if (challengeScope) {
+ const tokens = challengeScope.split(" ").filter(Boolean);
+ if (tokens.length > 0 && tokens.every(isScopeToken)) return tokens.join(" ");
+ }
+ if (!Array.isArray(resourceScopes)) return undefined;
+ return resourceScopes.filter(isScopeToken).join(" ") || undefined;
+}
diff --git a/apps/desktop/electron/main/mcp-oauth.ts b/apps/desktop/electron/main/mcp-oauth.ts
index 75ecf830c..4b702213c 100644
--- a/apps/desktop/electron/main/mcp-oauth.ts
+++ b/apps/desktop/electron/main/mcp-oauth.ts
@@ -8,6 +8,7 @@ import {
type McpServerStatus,
} from "@pi-desktop/shared";
import { allowInsecureUserEndpointsEnabled } from "./endpoint-policy.ts";
+import { authorizationMetadataUrls, parseBearerChallenge, selectOAuthScope } from "./mcp-oauth-discovery.ts";
export type StoredMcpOAuthToken = {
clientId: string;
clientSecret?: string;
@@ -27,7 +28,7 @@ export type McpOAuthMetadata = {
authorizationEndpoint: string;
tokenEndpoint: string;
registrationEndpoint?: string;
- scopesSupported?: string[];
+ scope?: string;
};
export type McpOAuthDeps = {
@@ -202,6 +203,7 @@ export class McpOAuthManager {
async discoverMetadata(serverUrl: string): Promise<McpOAuthMetadata> {
const urlObj = new URL(serverUrl);
let resourceMetadataUrl: string | undefined;
+ let challengeScope: string | undefined;
// Step 1: Probe endpoint to check for 401 with WWW-Authenticate
try {
@@ -226,12 +228,9 @@ export class McpOAuthManager {
if (probeRes.status === 401) {
const wwwAuth = probeRes.headers.get("www-authenticate");
if (wwwAuth) {
- const match =
- wwwAuth.match(/resource_metadata="([^"]+)"/i) ??
- wwwAuth.match(/resource_metadata=([^,\s]+)/i);
- if (match?.[1]) {
- resourceMetadataUrl = match[1];
- }
+ const challenge = parseBearerChallenge(wwwAuth);
+ resourceMetadataUrl = challenge.resourceMetadataUrl;
+ challengeScope = challenge.scope;
}
}
} catch {
@@ -278,10 +277,7 @@ export class McpOAuthManager {
// Step 3: Fetch Authorization Server Metadata (RFC 8414)
let asMeta: Record<string, unknown> | null = null;
- const asMetaCandidates = [
- new URL("/.well-known/oauth-authorization-server", authServerObj.origin).toString(),
- new URL("/.well-known/openid-configuration", authServerObj.origin).toString(),
- ];
+ const asMetaCandidates = authorizationMetadataUrls(authServerObj);
for (const asUrl of asMetaCandidates) {
try {
@@ -312,11 +308,7 @@ export class McpOAuthManager {
if (registrationEndpoint) {
assertTlsProtectedUrl(registrationEndpoint, "registration_endpoint", serverUrl);
}
- const scopesSupported = Array.isArray(asMeta?.scopes_supported)
- ? (asMeta.scopes_supported as string[])
- : Array.isArray(prm?.scopes_supported)
- ? (prm.scopes_supported as string[])
- : undefined;
+ const scope = selectOAuthScope(challengeScope, prm?.scopes_supported);
return {
resource: typeof prm?.resource === "string" ? prm.resource : serverUrl,
@@ -324,7 +316,7 @@ export class McpOAuthManager {
authorizationEndpoint,
tokenEndpoint,
registrationEndpoint,
- scopesSupported,
+ scope,
};
}
@@ -697,12 +689,10 @@ export class McpOAuthManager {
authUrl.searchParams.set("code_challenge_method", "S256");
authUrl.searchParams.set("resource", metadata.resource);
- // MVP: no per-server scope picker. Prefer a literal "default" if
- // advertised (Notion-class), otherwise the first supported scope.
- if (metadata.scopesSupported?.includes("default")) {
- authUrl.searchParams.set("scope", "default");
- } else if (metadata.scopesSupported?.[0]) {
- authUrl.searchParams.set("scope", metadata.scopesSupported[0]);
+ if (metadata.scope) {
+ authUrl.searchParams.set("scope", metadata.scope);
+ } else {
+ authUrl.searchParams.delete("scope");
}
this.deps.log?.("info", "opening browser for mcp oauth", {
diff --git a/apps/desktop/test/mcp-oauth-discovery.test.mjs b/apps/desktop/test/mcp-oauth-discovery.test.mjs
new file mode 100644
index 000000000..891304ab1
--- /dev/null
+++ b/apps/desktop/test/mcp-oauth-discovery.test.mjs
@@ -0,0 +1,173 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { createServer } from "node:http";
+import test from "node:test";
+import { McpOAuthManager } from "../electron/main/mcp-oauth.ts";
+import { authorizationMetadataUrls } from "../electron/main/mcp-oauth-discovery.ts";
+
+test("issuer paths cannot change the discovery origin", () => {
+ const issuer = new URL("https://auth.example:8443//other.example/tenant");
+ const urls = authorizationMetadataUrls(issuer).map(value => new URL(value));
+ assert.ok(urls.every(url => url.origin === issuer.origin));
+ assert.equal(urls[2].pathname, "//other.example/tenant/.well-known/openid-configuration");
+});
+
+// Real HTTP discovery, registration, authorization redirect and token exchange;
+// only the browser launcher and encrypted host storage are external test seams.
+async function authorize(t, options = {}) {
+ const requests = [];
+ const secrets = new Map();
+ const opened = Promise.withResolvers();
+ const completed = Promise.withResolvers();
+ let authorization;
+ let tokenRequest;
+ let registration;
+ let origin;
+ const issuerPath = options.issuerPath ?? "/api/auth";
+ const suffix = issuerPath.replace(/\/+$/, "");
+ const candidates = suffix ? [
+ `/.well-known/oauth-authorization-server${suffix}`,
+ `/.well-known/openid-configuration${suffix}`,
+ `${suffix}/.well-known/openid-configuration`,
+ ] : ["/.well-known/oauth-authorization-server", "/.well-known/openid-configuration"];
+ const metadataPath = candidates[options.availableCandidate ?? 0];
+ const server = createServer(async (req, res) => {
+ try {
+ const url = new URL(req.url, origin);
+ requests.push(url.pathname);
+ const json = (data, status = 200) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(data));
+ };
+ const body = async () => {
+ let text = "";
+ for await (const chunk of req) text += chunk;
+ return text;
+ };
+ if (url.pathname === "/mcp") {
+ const challenge = options.challenge ?? `Bearer resource_metadata="${origin}/metadata"`;
+ res.setHeader("WWW-Authenticate", challenge.replaceAll("{origin}", origin));
+ json({ error: "unauthorized" }, options.probeStatus ?? 401);
+ } else if (url.pathname === "/metadata" || url.pathname === "/.well-known/oauth-protected-resource/mcp") {
+ json({
+ resource: `${origin}/mcp`,
+ authorization_servers: [`${origin}${issuerPath}`],
+ ...("resourceScopes" in options ? { scopes_supported: options.resourceScopes } : {}),
+ });
+ } else if (url.pathname === metadataPath) {
+ json({
+ issuer: `${origin}${issuerPath}`,
+ authorization_endpoint: `${origin}/authorize?scope=provider-default`,
+ token_endpoint: `${origin}/token`,
+ registration_endpoint: `${origin}/register`,
+ scopes_supported: ["openid", "default", "offline_access"],
+ });
+ } else if (url.pathname === "/register") {
+ registration = JSON.parse(await body());
+ json({ client_id: "fixture-client", redirect_uris: registration.redirect_uris }, 201);
+ } else if (url.pathname === "/authorize") {
+ authorization = url.searchParams;
+ const callback = new URL(authorization.get("redirect_uri"));
+ callback.searchParams.set("state", authorization.get("state"));
+ callback.searchParams.set("code", "fixture-code");
+ res.writeHead(302, { location: callback.toString() });
+ res.end();
+ } else if (url.pathname === "/token") {
+ tokenRequest = new URLSearchParams(await body());
+ json({ access_token: "fixture-token", token_type: "Bearer" });
+ } else {
+ res.writeHead(404);
+ res.end();
+ }
+ } catch (error) {
+ res.writeHead(500);
+ res.end();
+ opened.reject(error);
+ }
+ });
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
+ origin = `http://127.0.0.1:${server.address().port}`;
+ const manager = new McpOAuthManager({
+ call: async (method, params) => {
+ if (method === "secrets.getForRuntime") return { value: secrets.get(params.secretRef) ?? null };
+ if (method === "secrets.set") {
+ secrets.set(params.secretRef, params.value);
+ return { ok: true };
+ }
+ throw new Error(`Unexpected host method: ${method}`);
+ },
+ openExternal: async url => { opened.resolve(url); },
+ emit: event => {
+ if (event.kind === "error") opened.reject(new Error(event.message));
+ if (event.kind === "done" || event.kind === "error") completed.resolve(event);
+ },
+ });
+ t.after(async () => {
+ manager.disposeAll();
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
+ });
+
+ await manager.start("fixture", `${origin}/mcp`);
+ const authUrl = new URL(await opened.promise);
+ assert.equal(authUrl.searchParams.get("scope"), options.expectedScope ?? null);
+ const callbackResponse = await fetch(authUrl);
+ assert.equal(callbackResponse.status, 200);
+ assert.match(await callbackResponse.text(), /Authorization successful/);
+ assert.equal((await completed.promise).kind, "done");
+ assert.equal(await manager.getValidAccessToken("fixture"), "fixture-token");
+ assert.equal(authorization.get("resource"), `${origin}/mcp`);
+ assert.equal(tokenRequest.get("resource"), `${origin}/mcp`);
+ assert.equal(tokenRequest.get("code"), "fixture-code");
+ assert.equal(tokenRequest.get("client_id"), "fixture-client");
+ assert.equal(tokenRequest.get("redirect_uri"), authorization.get("redirect_uri"));
+ assert.ok(registration.redirect_uris.includes(authorization.get("redirect_uri")));
+ assert.equal(authorization.get("code_challenge_method"), "S256");
+ assert.equal(authorization.get("code_challenge"),
+ createHash("sha256").update(tokenRequest.get("code_verifier")).digest("base64url"));
+ assert.deepEqual(requests.filter(path => candidates.includes(path)),
+ candidates.slice(0, (options.availableCandidate ?? 0) + 1));
+}
+
+for (const issuerPath of ["/api/auth", "/realms/team-a/", "/tenant%2Fone", ""]) {
+ for (let availableCandidate = 0; availableCandidate < (issuerPath ? 3 : 2); availableCandidate++) {
+ test(`OAuth login preserves issuer ${issuerPath || "/"} through discovery fallback ${availableCandidate + 1}`, { timeout: 5000 }, async t => {
+ await authorize(t, { issuerPath, availableCandidate });
+ });
+ }
+}
+
+for (const [name, options] of [
+ ["challenge overrides resource scopes", {
+ challenge: 'Bearer resource_metadata="{origin}/metadata", scope="files:read files:search"',
+ resourceScopes: ["files:admin"], expectedScope: "files:read files:search",
+ }],
+ ["challenge scope works without a metadata URL", {
+ challenge: 'Bearer scope="files:read"', expectedScope: "files:read",
+ }],
+ ["resource metadata supplies all scopes", {
+ resourceScopes: ["files:read", "files:search"], expectedScope: "files:read files:search",
+ }],
+ ["missing resource scopes do not inherit authorization server scopes", {}],
+ ["empty resource scopes omit scope", { resourceScopes: [] }],
+ ["non-string resource scopes are not sent", { resourceScopes: [null, 42, {}] }],
+ ["Basic challenge scopes are ignored", {
+ challenge: 'Basic realm="private, scope=admin", scope="admin", Bearer scope="files:read"',
+ expectedScope: "files:read",
+ }],
+ ["later Basic challenge cannot supply Bearer scope", {
+ challenge: 'Bearer realm="mcp", Basic realm="private", scope="admin"',
+ resourceScopes: ["files:read"], expectedScope: "files:read",
+ }],
+ ["unquoted and case-insensitive Bearer parameters work", {
+ challenge: 'bEaReR SCOPE = files:read', expectedScope: "files:read",
+ }],
+ ["scope is only taken from an unauthorized response", {
+ challenge: 'Bearer scope="admin"', probeStatus: 200,
+ resourceScopes: ["files:read"], expectedScope: "files:read",
+ }],
+]) {
+ test(`OAuth scope: ${name}`, { timeout: 5000 }, async t => {
+ await authorize(t, { issuerPath: "", ...options });
+ });
+}
diff --git a/docs/adr/0283-remote-mcp-oauth.md b/docs/adr/0283-remote-mcp-oauth.md
index 08c228063..3a83fa0d5 100644
--- a/docs/adr/0283-remote-mcp-oauth.md
+++ b/docs/adr/0283-remote-mcp-oauth.md
@@ -49,4 +49,9 @@ Previous MCP implementations in PI-Desktop supported only static HTTP headers. U
- Loopback `/callback` validates `state` before looking at `error` or `code`. A mismatched `state` is a stray request and does not abort the login. A matching callback is consumed once (replay returns 409).
- `invalid_grant` on refresh deletes the stored secret; transient 5xx keeps the existing access token.
- `mcp/oauth/start` passes the listed `McpServerRecord` through to `onAuthorized` so a project-level server that is not in the current workspace runtime can still handshake after login.
-- Scope selection remains an MVP heuristic (`default` if advertised, else `scopes_supported[0]`). There is no per-server scope picker, device-code flow, or DPoP.
+- Scope selection initially used an MVP heuristic (`default` if advertised, else `scopes_supported[0]`); the amendment below supersedes it. There is no per-server scope picker, device-code flow, or DPoP.
+
+## Amendment (2026-09-29) — issuer discovery and resource scopes (#1221)
+
+- Preserve issuer paths when discovering authorization metadata: try OAuth path insertion, OIDC path insertion, then OIDC path appending. Root issuers retain the two root discovery URLs. Keep the existing TLS checks and manual redirect policy.
+- Request scopes from the initial 401 Bearer challenge first, otherwise all valid `scopes_supported` entries from protected-resource metadata. Omit `scope` when neither supplies one; authorization-server scope catalogs do not describe the resource's requirements and must not supply defaults or extra scopes.
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 5701a6a70..e44da0ae8 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1634,6 +1634,12 @@ Desktop-only MCP market channels (not host RPC) live on Electron IPC:
Browser-based OAuth 2.1 authentication for HTTP MCP servers is handled in the Electron main process via non-blocking IPC invocations and an event stream:
+Discovery preserves authorization-server issuer paths, trying OAuth path insertion,
+OIDC path insertion, then OIDC path appending (root issuers use the two root URLs).
+The authorization request uses the initial 401 Bearer challenge's `scope`, otherwise
+all valid protected-resource `scopes_supported` entries, otherwise omits `scope`.
+Authorization-server scope catalogs do not add or select requested permissions.
+
- `pi-desktop/mcp/oauth/start({ id, level?, projectPath? }) -> { ok: true, loginId }`
Initiates OAuth metadata discovery and PKCE authorization code flow. Returns immediately; user browser navigation and callback exchange proceed asynchronously in the background.
- `pi-desktop/mcp/oauth/cancel({ loginId?, id? }) -> { ok: boolean }`
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 10a4a4943..0d4f53a89 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -7313,7 +7313,8 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
- **Specs linked**: `03-runtime/01-ipc-protocol.md`, ADR 0283, ADR 0142
- **Acceptance**: E (tools & permissions), Security
- **Milestone**: M5
-- **Status**: Unit-covered (`apps/desktop/test/mcp-oauth.test.mjs`, `apps/desktop/test/user-mcp.test.mjs`); full UI journey Draft
+- **Discovery regression (#1221):** Local HTTP authorization flow covers root and path issuers, ordered OAuth/OIDC fallbacks, challenge-scope precedence, all protected-resource scopes, and omitted scope when absent. It checks the real callback, PKCE token exchange and storage handoff using synthetic tokens; no external account is contacted.
+- **Status**: Unit-covered (`apps/desktop/test/mcp-oauth.test.mjs`, `apps/desktop/test/user-mcp.test.mjs`); local HTTP flow covered by `apps/desktop/test/mcp-oauth-discovery.test.mjs`; full UI journey Draft
#### E2E-SKILL-import-multiple-folders