Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Per-user OAuth sign-in for admin-configured MCP servers (#1812)

Joshua Francede870065040c
diff --git a/src/api/routes/admin/mcp-servers.ts b/src/api/routes/admin/mcp-servers.ts
index a0e76a5aa..e14246d11 100644
--- a/src/api/routes/admin/mcp-servers.ts
+++ b/src/api/routes/admin/mcp-servers.ts
@@ -5,11 +5,13 @@
// model-provider credential, not like a personal connector.
import { isValidMcpServerId, type McpServer, type McpServerAuthMode } from "../../../mcp/mcp-server-store.ts";
+import { PROVIDERS } from "../../../connectors/oauth.ts";
+import { discoverOAuth, httpsUrl, parseScopes, type DiscoveredOAuth } from "../../../mcp/oauth-discovery.ts";
import { sendJson } from "../../http.ts";
import type { ApiCtx } from "../route.ts";
import { audit, authorizeAdmin, orgScope } from "../shared.ts";
-const AUTH_MODES: McpServerAuthMode[] = ["none", "bearer", "client-credentials"];
+const AUTH_MODES: McpServerAuthMode[] = ["none", "bearer", "client-credentials", "oauth-user"];
async function actor(ctx: ApiCtx) {
const scope = orgScope(ctx.deps);
@@ -79,11 +81,34 @@ export async function putMcpServer(ctx: ApiCtx): Promise<void> {
return sendJson(ctx.res, 400, { error: "bad_request", message: `auth must be one of ${AUTH_MODES.join(", ")}` });
}
const existing = await ctx.deps.mcpServers.get(id);
- const credentialScope = b.credentialScope ?? existing?.credentialScope ?? "shared";
+ const oauthUser = auth === "oauth-user";
+ if (oauthUser && PROVIDERS[id]) {
+ return sendJson(ctx.res, 400, { error: "bad_request", message: `id ${id} is reserved by a built-in connector` });
+ }
+ const credentialScope = oauthUser ? "per-user" : (b.credentialScope ?? existing?.credentialScope ?? "shared");
if (credentialScope !== "shared" && credentialScope !== "per-user") {
return sendJson(ctx.res, 400, { error: "bad_request", message: "credentialScope must be shared or per-user" });
}
- const credentialHost = b.credentialHost ?? existing?.credentialHost;
+ const credentialHost = b.credentialHost ?? existing?.credentialHost ?? (oauthUser ? parsed.hostname : undefined);
+ if (
+ oauthUser &&
+ typeof credentialHost === "string" &&
+ Object.values(PROVIDERS).some((p) =>
+ p.hosts.some((h) => credentialHost === h || credentialHost.endsWith(`.${h}`) || h.endsWith(`.${credentialHost}`)),
+ )
+ ) {
+ return sendJson(ctx.res, 400, {
+ error: "bad_request",
+ message: "credentialHost is already used by another connector",
+ });
+ }
+ for (const field of ["oauthAuthorizeUrl", "oauthTokenUrl"] as const) {
+ if (oauthUser && b[field] !== undefined && !httpsUrl(b[field])) {
+ return sendJson(ctx.res, 400, { error: "bad_request", message: `${field} must be an HTTPS URL` });
+ }
+ }
+ let oauthAuthorizeUrl = httpsUrl(b.oauthAuthorizeUrl) ?? (oauthUser ? existing?.oauthAuthorizeUrl : undefined);
+ let oauthTokenUrl = httpsUrl(b.oauthTokenUrl) ?? (oauthUser ? existing?.oauthTokenUrl : undefined);
const credentialAccountType = b.credentialAccountType ?? existing?.credentialAccountType ?? "default";
if (!["default", "personal", "company"].includes(credentialAccountType)) {
return sendJson(ctx.res, 400, {
@@ -111,6 +136,12 @@ export async function putMcpServer(ctx: ApiCtx): Promise<void> {
message: "per-user credentials require HTTPS (except loopback)",
});
}
+ let discovered: DiscoveredOAuth | undefined;
+ if (oauthUser && (!oauthAuthorizeUrl || !oauthTokenUrl)) {
+ discovered = await discoverOAuth(parsed);
+ oauthAuthorizeUrl ??= discovered.authorize;
+ oauthTokenUrl ??= discovered.token;
+ }
const server: McpServer = {
id,
name: typeof b.name === "string" && b.name.trim() ? b.name.trim().slice(0, 80) : id,
@@ -121,6 +152,14 @@ export async function putMcpServer(ctx: ApiCtx): Promise<void> {
...(auth === "bearer"
? { bearerToken: typeof b.bearerToken === "string" && b.bearerToken ? b.bearerToken : existing?.bearerToken }
: {}),
+ ...(oauthUser
+ ? {
+ clientId: typeof b.clientId === "string" && b.clientId ? b.clientId.trim() : existing?.clientId,
+ oauthAuthorizeUrl,
+ oauthTokenUrl,
+ oauthScopes: parseScopes(b.oauthScopes) ?? existing?.oauthScopes ?? discovered?.scopes ?? [],
+ }
+ : {}),
...(auth === "client-credentials"
? {
clientId: typeof b.clientId === "string" && b.clientId ? b.clientId : existing?.clientId,
@@ -141,8 +180,16 @@ export async function putMcpServer(ctx: ApiCtx): Promise<void> {
message: "client-credentials auth requires clientId and clientSecret",
});
}
+ if (oauthUser && (!server.clientId || !server.oauthAuthorizeUrl || !server.oauthTokenUrl)) {
+ return sendJson(ctx.res, 400, {
+ error: "bad_request",
+ message:
+ "oauth-user auth requires clientId plus HTTPS oauthAuthorizeUrl and oauthTokenUrl, or OAuth metadata to discover them" +
+ (discovered?.errors.length ? ` (discovery: ${discovered.errors.join("; ")})` : ""),
+ });
+ }
let toolNames: string[] | undefined;
- if (b.validate !== false && ctx.deps.mcpToolService) {
+ if (b.validate !== false && !oauthUser && ctx.deps.mcpToolService) {
try {
toolNames = await ctx.deps.mcpToolService.probe(server);
} catch (e) {
diff --git a/src/api/routes/connectors.ts b/src/api/routes/connectors.ts
index acbaf128e..35fd2d096 100644
--- a/src/api/routes/connectors.ts
+++ b/src/api/routes/connectors.ts
@@ -5,6 +5,8 @@ import {
exchangeCode,
openOAuthState,
PROVIDERS,
+ oauthProvider,
+ withPublicOAuthClients,
sealOAuthState,
createSecretClientResolver,
generateCodeVerifier,
@@ -46,7 +48,8 @@ async function resumeOAuthFlow(deps: ServerDeps, secret: string | undefined, par
export function resolverFor(deps: ServerDeps): OAuthClientResolver {
return (
- deps.resolveClient ?? createSecretClientResolver(deps.oauthEnv ? createEnvSecretSource(deps.oauthEnv) : undefined)
+ deps.resolveClient ??
+ withPublicOAuthClients(createSecretClientResolver(deps.oauthEnv ? createEnvSecretSource(deps.oauthEnv) : undefined))
);
}
@@ -192,7 +195,7 @@ async function oauthCallback(ctx: BaseCtx): Promise<void> {
}
async function principalHasProvider(deps: ServerDeps, provider: string, principalId: string): Promise<boolean> {
- const p = PROVIDERS[provider];
+ const p = oauthProvider(provider);
if (!p || !deps.connectorTokens) return false;
for (const host of p.hosts) {
for (const at of CONNECTOR_STATUS_ACCOUNT_TYPES) {
@@ -217,7 +220,7 @@ async function consentRedeem(ctx: ApiCtx): Promise<void> {
}
const rec = peeked.rec;
if (rec.orgId !== undefined && rec.orgId !== configOrgId()) return sendJson(res, 200, { status: "invalid" });
- if (!PROVIDERS[rec.provider]) return sendJson(res, 200, { status: "invalid" });
+ if (!oauthProvider(rec.provider)) return sendJson(res, 200, { status: "invalid" });
if (!samePerson(clicker, rec.principalId)) {
const clickerConnected = await principalHasProvider(deps, rec.provider, clicker);
audit(deps, {
@@ -242,7 +245,7 @@ async function consentRedeem(ctx: ApiCtx): Promise<void> {
});
}
const returnTo = safeReturnTo(url.searchParams.get("returnTo")) ?? rec.returnTo;
- const codeVerifier = PROVIDERS[rec.provider]?.pkce ? generateCodeVerifier() : undefined;
+ const codeVerifier = oauthProvider(rec.provider)?.pkce ? generateCodeVerifier() : undefined;
const state = await beginOAuthFlow(deps, secret, {
provider: rec.provider,
principalId: rec.principalId,
@@ -286,7 +289,7 @@ async function consentMint(ctx: ApiCtx): Promise<void> {
intendedPrincipalId?: unknown;
};
const provider = typeof b.provider === "string" ? b.provider : "";
- if (!PROVIDERS[provider])
+ if (!oauthProvider(provider))
return sendJson(res, 404, { error: "not_found", message: `unknown OAuth provider: ${provider}` });
const accountType = parseAccountType(typeof b.accountType === "string" ? b.accountType : null);
const base = deps.publicUrl ? deps.publicUrl.replace(/\/$/, "") : "";
@@ -357,7 +360,7 @@ async function oauthStart(ctx: ApiCtx): Promise<void> {
const oauthRoute = parseOAuthRoute(pathname)!;
if (!deps.connectorTokens)
return sendJson(res, 501, { error: "not_configured", message: "connector token store not wired" });
- const provider = PROVIDERS[oauthRoute.provider];
+ const provider = oauthProvider(oauthRoute.provider);
if (!provider)
return sendJson(res, 404, { error: "not_found", message: `unknown OAuth provider: ${oauthRoute.provider}` });
const principalId = url.searchParams.get("principalId") ?? "";
@@ -445,7 +448,7 @@ export async function oauthRevoke(ctx: ApiCtx): Promise<void> {
return sendJson(res, 400, { error: "bad_request", message: "principalId and provider or host required" });
}
if (providerName) {
- const provider = PROVIDERS[providerName];
+ const provider = oauthProvider(providerName);
if (!provider)
return sendJson(res, 404, { error: "not_found", message: `unknown OAuth provider: ${providerName}` });
for (const h of provider.hosts)
diff --git a/src/connectors/oauth.ts b/src/connectors/oauth.ts
index 9a7f4198d..b48599238 100644
--- a/src/connectors/oauth.ts
+++ b/src/connectors/oauth.ts
@@ -90,6 +90,9 @@ function toToken(
};
}
+const resourceBody = (p: OAuthProviderConfig): Record<string, string> =>
+ p.authParams?.resource ? { resource: p.authParams.resource } : {};
+
function makeTokenAdapters(opts: {
acceptJson?: boolean;
rejectErrorBody?: boolean;
@@ -109,7 +112,7 @@ function makeTokenAdapters(opts: {
...(basic ? { authorization: `Basic ${Buffer.from(`${client.id}:${client.secret}`).toString("base64")}` } : {}),
});
const clientBody = (client: ResolvedClient): Record<string, string> =>
- basic ? { client_id: client.id } : { client_id: client.id, client_secret: client.secret };
+ basic || !client.secret ? { client_id: client.id } : { client_id: client.id, client_secret: client.secret };
const checkErrorBody = (raw: Record<string, unknown>): void => {
if (opts.rejectErrorBody && raw.error)
throw new Error(`${prefix}oauth error: ${String(raw.error_description ?? raw.error)}`);
@@ -125,6 +128,7 @@ function makeTokenAdapters(opts: {
redirect_uri: redirectUri,
...clientBody(client),
...(codeVerifier ? { code_verifier: codeVerifier } : {}),
+ ...resourceBody(provider),
}).toString(),
});
if (!res.ok) throw new Error(`${prefix}token exchange failed (${res.status})`);
@@ -140,6 +144,7 @@ function makeTokenAdapters(opts: {
grant_type: "refresh_token",
refresh_token: token.refreshToken ?? "",
...clientBody(client),
+ ...resourceBody(provider),
}).toString(),
});
if (!res.ok) throw new Error(`${prefix}token refresh failed (${res.status})`);
@@ -442,6 +447,53 @@ export const PROVIDERS: Record<string, OAuthProviderConfig> = {
},
};
+export interface PublicOAuthClient {
+ name: string;
+ host: string;
+ authUrl: string;
+ tokenUrl: string;
+ scopes: string[];
+ clientId: string;
+ resource?: string;
+}
+
+const publicClients = new Map<string, PublicOAuthClient>();
+const publicProviders = new Map<string, OAuthProviderConfig>();
+
+export function setPublicOAuthClients(clients: PublicOAuthClient[]): void {
+ publicClients.clear();
+ publicProviders.clear();
+ for (const c of clients) {
+ if (PROVIDERS[c.name]) continue;
+ publicClients.set(c.name, c);
+ publicProviders.set(c.name, {
+ hosts: [c.host],
+ authUrl: c.authUrl,
+ tokenUrl: c.tokenUrl,
+ scopes: c.scopes,
+ clientIdEnv: "",
+ clientSecretEnv: "",
+ redirectPath: `${c.name}/callback`,
+ consentMode: "standard",
+ egressRule: [],
+ pkce: true,
+ ...(c.resource ? { authParams: { resource: c.resource } } : {}),
+ setupGuide: { console: "Admin → MCP servers", url: "", steps: [] },
+ });
+ }
+}
+
+export function oauthProvider(name: string): OAuthProviderConfig | undefined {
+ return PROVIDERS[name] ?? publicProviders.get(name);
+}
+
+export function withPublicOAuthClients(resolve: OAuthClientResolver): OAuthClientResolver {
+ return async (provider, ctx) => {
+ const c = publicClients.get(provider);
+ return c ? { id: c.clientId, secret: "", clientRef: `public:${provider}` } : resolve(provider, ctx);
+ };
+}
+
export interface ResolvedClient {
id: string;
secret: string;
@@ -545,7 +597,7 @@ export function authorizeUrl(
codeChallenge?: string;
},
): string {
- const p = PROVIDERS[provider];
+ const p = oauthProvider(provider);
if (!p) throw new Error(`unknown OAuth provider: ${provider}`);
const accountType = opts.accountType ?? "default";
const scopes = scopesFor(p, opts.client);
@@ -577,7 +629,7 @@ export async function exchangeCode(
codeVerifier?: string;
},
): Promise<{ hosts: string[]; token: OAuthToken }> {
- const p = PROVIDERS[provider];
+ const p = oauthProvider(provider);
if (!p) throw new Error(`unknown OAuth provider: ${provider}`);
const adapter = p.exchange ?? defaultExchange;
return adapter({
@@ -593,7 +645,7 @@ export async function exchangeCode(
}
function providerForHost(host: string): { name: string; config: OAuthProviderConfig } | null {
- for (const [name, config] of Object.entries(PROVIDERS)) {
+ for (const [name, config] of [...Object.entries(PROVIDERS), ...publicProviders]) {
if (config.hosts.some((h) => host === h || host.endsWith(`.${h}`))) return { name, config };
}
return null;
diff --git a/src/mcp/mcp-server-store.ts b/src/mcp/mcp-server-store.ts
index ac2dd4de6..c3b6e56aa 100644
--- a/src/mcp/mcp-server-store.ts
+++ b/src/mcp/mcp-server-store.ts
@@ -7,7 +7,7 @@
import type { DurableMap } from "../persistence/durable-map.ts";
-export type McpServerAuthMode = "none" | "bearer" | "client-credentials";
+export type McpServerAuthMode = "none" | "bearer" | "client-credentials" | "oauth-user";
export interface McpServer {
id: string;
@@ -20,6 +20,10 @@ export interface McpServer {
bearerToken?: string;
clientId?: string;
clientSecret?: string;
+ oauthAuthorizeUrl?: string;
+ oauthTokenUrl?: string;
+ oauthScopes?: string[];
+ tools?: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>;
readOnly: boolean;
enabled: boolean;
updatedAt: number;
diff --git a/src/mcp/mcp-tool-service.ts b/src/mcp/mcp-tool-service.ts
index 4fac7e904..f88ee1a06 100644
--- a/src/mcp/mcp-tool-service.ts
+++ b/src/mcp/mcp-tool-service.ts
@@ -9,6 +9,7 @@
import type { ConnectorTokenStore } from "../credentials/keychain.ts";
import type { AuditLog } from "../audit/audit-log.ts";
import { errMessage, reportFailureAs } from "../util/errors.ts";
+import { setPublicOAuthClients, type PublicOAuthClient } from "../connectors/oauth.ts";
import { createMcpClient, mcpResultText, type McpAuth, type McpClient, type McpFetch } from "./mcp-client.ts";
import type { McpServer, McpServerStore } from "./mcp-server-store.ts";
@@ -16,6 +17,24 @@ const REFRESH_INTERVAL_MS = 5 * 60_000;
const MAX_TOOLS_PER_SERVER = 64;
const MAX_RESULT_CHARS = 60_000;
+export function mcpPublicOAuthClients(servers: McpServer[]): PublicOAuthClient[] {
+ return servers.flatMap((s) =>
+ s.enabled && s.auth === "oauth-user" && s.clientId && s.oauthAuthorizeUrl && s.oauthTokenUrl && s.credentialHost
+ ? [
+ {
+ name: s.id,
+ host: s.credentialHost,
+ authUrl: s.oauthAuthorizeUrl,
+ tokenUrl: s.oauthTokenUrl,
+ scopes: s.oauthScopes ?? [],
+ clientId: s.clientId,
+ resource: s.url,
+ },
+ ]
+ : [],
+ );
+}
+
export interface McpToolDescriptor {
/** Namespaced tool name exposed to the model, e.g. "salesforce_query". */
name: string;
@@ -24,6 +43,7 @@ export interface McpToolDescriptor {
description: string;
inputSchema: Record<string, unknown>;
readOnly: boolean;
+ signIn?: true;
}
export interface McpToolService {
@@ -38,6 +58,8 @@ export interface McpToolService {
close(): void;
}
+class SignInRequired extends Error {}
+
function authOf(server: McpServer): McpAuth {
if (server.auth === "bearer") return { mode: "bearer", token: server.bearerToken ?? "" };
if (server.auth === "client-credentials")
@@ -52,10 +74,18 @@ export function createMcpToolService(opts: {
fetchImpl?: McpFetch;
now?: () => number;
refreshIntervalMs?: number;
+ signInUrl?: (serverId: string) => string;
}): McpToolService {
const now = opts.now ?? (() => Date.now());
const clients = new Map<string, { client: McpClient; server: McpServer }>();
let snapshot: McpToolDescriptor[] = [];
+
+ function signInMessage(server: McpServer): string {
+ const url = opts.signInUrl?.(server.id);
+ return url
+ ? `Sign in to ${server.name} first: [Connect ${server.name}](${url}). Then try again.`
+ : `Sign in to ${server.name} from the Connectors page first, then try again.`;
+ }
let closed = false;
function record(action: string, resource: string, status: string, principalId?: string): void {
@@ -93,7 +123,10 @@ export function createMcpToolService(opts: {
principalId,
server.credentialAccountType,
);
- if (!token) throw new Error(`Connect your account for MCP server ${server.id} before using this tool`);
+ if (!token) {
+ if (server.auth === "oauth-user") throw new SignInRequired(signInMessage(server));
+ throw new Error(`Connect your account for MCP server ${server.id} before using this tool`);
+ }
return createMcpClient({
url: server.url,
auth: { mode: "bearer", token },
@@ -103,11 +136,28 @@ export function createMcpToolService(opts: {
}
async function refresh(): Promise<void> {
- const servers = (await opts.servers.list()).filter((s) => s.enabled);
+ const all = await opts.servers.list();
+ setPublicOAuthClients(mcpPublicOAuthClients(all));
+ const servers = all.filter((s) => s.enabled);
const next: McpToolDescriptor[] = [];
for (const server of servers) {
try {
- const tools = (await clientFor(server).listTools()).slice(0, MAX_TOOLS_PER_SERVER);
+ let tools: Array<{ name: string; description: string; inputSchema: Record<string, unknown> }>;
+ if (server.auth === "oauth-user") {
+ tools = server.tools ?? [];
+ if (!tools.length) {
+ next.push({
+ name: `${server.id}_sign_in`.replace(/[^a-zA-Z0-9_-]/g, "_"),
+ serverId: server.id,
+ remoteName: "sign_in",
+ signIn: true,
+ description: `Connect your own ${server.name} account and load its tools. Call this before anything else on ${server.name}.`,
+ inputSchema: { type: "object", properties: {} },
+ readOnly: true,
+ });
+ continue;
+ }
+ } else tools = (await clientFor(server).listTools()).slice(0, MAX_TOOLS_PER_SERVER);
for (const tool of tools) {
next.push({
name: `${server.id}_${tool.name}`.replace(/[^a-zA-Z0-9_-]/g, "_"),
@@ -144,11 +194,24 @@ export function createMcpToolService(opts: {
const server = await opts.servers.get(def.serverId);
if (!server || !server.enabled) throw new Error(`MCP server ${def.serverId} is not available`);
try {
- const result = await (await callerClient(server, principalId)).callTool(def.remoteName, args);
+ const client = await callerClient(server, principalId);
+ if (def.signIn) {
+ const tools = (await client.listTools()).slice(0, MAX_TOOLS_PER_SERVER);
+ const current = await opts.servers.get(server.id);
+ if (current) await opts.servers.put({ ...current, tools });
+ await refresh();
+ record("call", `${def.serverId}/sign_in`, `ok tools=${tools.length}`, principalId);
+ return `Signed in to ${server.name}. Tools now available: ${tools.map((t) => `${server.id}_${t.name}`).join(", ")}`;
+ }
+ const result = await client.callTool(def.remoteName, args);
record("call", `${def.serverId}/${def.remoteName}`, "ok", principalId);
const text = mcpResultText(result) || JSON.stringify(result.structuredContent ?? "") || "";
return text.length > MAX_RESULT_CHARS ? `${text.slice(0, MAX_RESULT_CHARS)}\n[truncated]` : text;
} catch (e) {
+ if (e instanceof SignInRequired) {
+ record("call", `${def.serverId}/${def.remoteName}`, "sign-in required", principalId);
+ return e.message;
+ }
record("call", `${def.serverId}/${def.remoteName}`, `error: ${errMessage(e)}`, principalId);
throw e;
}
diff --git a/src/mcp/oauth-discovery.ts b/src/mcp/oauth-discovery.ts
new file mode 100644
index 000000000..51cb79064
--- /dev/null
+++ b/src/mcp/oauth-discovery.ts
@@ -0,0 +1,79 @@
+import { errMessage } from "../util/errors.ts";
+
+export function httpsUrl(v: unknown): string | undefined {
+ if (typeof v !== "string") return undefined;
+ try {
+ const u = new URL(v.trim());
+ return u.protocol === "https:" || ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname)
+ ? u.toString()
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function parseScopes(v: unknown): string[] | undefined {
+ const raw: unknown[] | undefined = typeof v === "string" ? v.split(/\s+/) : undefined;
+ return (raw ?? (Array.isArray(v) ? (v as unknown[]) : undefined))
+ ?.filter((x): x is string => typeof x === "string" && !!x.trim())
+ .map((x) => x.trim());
+}
+
+export interface DiscoveredOAuth {
+ authorize?: string;
+ token?: string;
+ scopes?: string[];
+ errors: string[];
+}
+
+async function fetchMeta(url: string, errors: string[]): Promise<Record<string, unknown> | undefined> {
+ let r: Response;
+ try {
+ r = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(5_000) });
+ } catch (e) {
+ errors.push(`${url}: ${errMessage(e)}`);
+ return undefined;
+ }
+ if (!r.ok) {
+ errors.push(`${url}: HTTP ${r.status}`);
+ return undefined;
+ }
+ const meta: unknown = await r.json().catch(() => undefined);
+ if (meta && typeof meta === "object") return meta as Record<string, unknown>;
+ errors.push(`${url}: response is not a JSON object`);
+ return undefined;
+}
+
+function wellKnown(base: URL, suffix: string): string[] {
+ const path = base.pathname.replace(/\/+$/, "");
+ return [...new Set([`${base.origin}/.well-known/${suffix}${path}`, `${base.origin}/.well-known/${suffix}`])];
+}
+
+export async function discoverOAuth(resource: URL): Promise<DiscoveredOAuth> {
+ const errors: string[] = [];
+ for (const url of wellKnown(resource, "oauth-protected-resource")) {
+ const meta = await fetchMeta(url, errors);
+ const issuer = Array.isArray(meta?.authorization_servers) ? httpsUrl(meta.authorization_servers[0]) : undefined;
+ if (!issuer) {
+ if (meta) errors.push(`${url}: no HTTPS authorization_servers entry`);
+ continue;
+ }
+ const scopes = parseScopes(meta?.scopes_supported);
+ const base = new URL(issuer);
+ const path = base.pathname.replace(/\/+$/, "");
+ for (const candidate of [
+ `${base.origin}/.well-known/oauth-authorization-server${path}`,
+ `${base.origin}/.well-known/openid-configuration${path}`,
+ ...(path ? [`${base.origin}${path}/.well-known/openid-configuration`] : []),
+ ]) {
+ const server = await fetchMeta(candidate, errors);
+ if (!server) continue;
+ const authorize = httpsUrl(server.authorization_endpoint);
+ const token = httpsUrl(server.token_endpoint);
+ if (!authorize || !token) errors.push(`${candidate}: missing or non-HTTPS authorization/token endpoint`);
+ return { authorize, token, scopes, errors };
+ }
+ return { scopes, errors };
+ }
+ return { errors };
+}
diff --git a/src/wiring.ts b/src/wiring.ts
index f729511fb..fb7a4062a 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -279,7 +279,7 @@ import {
type FeatureFlagRecord,
type FeatureFlagStore,
} from "./feature-flags.ts";
-import { makeRefresh, type OAuthClientResolver, type OAuthState } from "./connectors/oauth.ts";
+import { makeRefresh, withPublicOAuthClients, type OAuthClientResolver, type OAuthState } from "./connectors/oauth.ts";
import {
createConnectorClientResolver,
deriveConnectorKey,
@@ -1209,11 +1209,13 @@ export function buildApp(
createAwsSecretsManagerSource({ prefix: config.secretsPrefix }),
)
: createEnvSecretSource();
- const resolveClient: OAuthClientResolver = createConnectorClientResolver({
- reader: configStore,
- orgScopeId: (o) => scopeId("org", o),
- secrets: secretSource,
- });
+ const resolveClient: OAuthClientResolver = withPublicOAuthClients(
+ createConnectorClientResolver({
+ reader: configStore,
+ orgScopeId: (o) => scopeId("org", o),
+ secrets: secretSource,
+ }),
+ );
const keychainKeyMaterial = config.connectorSecretKey;
const legacyCredentialKey =
keychainKeyMaterial && config.signingSecret && config.signingSecret !== keychainKeyMaterial
@@ -1277,6 +1279,12 @@ export function buildApp(
servers: mcpServers,
audit: auditLog,
...(keychain ? { userTokens: keychain } : {}),
+ ...(config.publicWebUrl
+ ? {
+ signInUrl: (id: string) =>
+ `${config.publicWebUrl!.replace(/\/$/, "")}/connect/${encodeURIComponent(id)}/self-connect`,
+ }
+ : {}),
});
const mcpTools = () => mcpToolService.toolDefs();
const browserSessionStore: BrowserSessionStore | undefined = keychainKeyMaterial
diff --git a/test/mcp-admin.test.ts b/test/mcp-admin.test.ts
index 36c976ebb..a47a785d3 100644
--- a/test/mcp-admin.test.ts
+++ b/test/mcp-admin.test.ts
@@ -144,3 +144,80 @@ test("production wiring never uses operator fallback tokens for per-user MCP cal
assert.equal(await built.mcpToolService.call("crm_identity", {}, "internal:alice"), "Bearer alice-only");
assert.equal(calls, 1);
});
+
+test("MCP admin accepts per-user OAuth servers, discovers endpoints from metadata, and never shadows built-in connectors", async (t) => {
+ const dir = await mkdtemp(join(tmpdir(), "mcp-admin-oauth-"));
+ const built = buildApp(testConfig({ dataDir: dir }));
+ const store = createMcpServerStore(createMemoryMap<McpServer>());
+ const server = createInsecureTestServer(built.app, {
+ admin: built.admin,
+ auditLog: built.auditLog,
+ mcpServers: store,
+ });
+ const issuer = createServer((req, res) => {
+ const base = `http://127.0.0.1:${(issuer.address() as AddressInfo).port}`;
+ const metadata: Record<string, object> = {
+ "/.well-known/oauth-authorization-server/id": {
+ authorization_endpoint: `${base}/id/authorize`,
+ token_endpoint: `${base}/id/token`,
+ },
+ "/.well-known/oauth-protected-resource/mcp": {
+ resource: `${base}/mcp`,
+ authorization_servers: [`${base}/id`],
+ scopes_supported: ["mcp:write"],
+ },
+ };
+ const meta = metadata[req.url ?? ""];
+ if (!meta) return void res.writeHead(404).end();
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(meta));
+ });
+ server.listen(0, "127.0.0.1");
+ issuer.listen(0, "127.0.0.1");
+ await Promise.all([once(server, "listening"), once(issuer, "listening")]);
+ t.after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await new Promise<void>((resolve) => issuer.close(() => resolve()));
+ await rm(dir, { recursive: true, force: true });
+ });
+ const issuerUrl = `http://127.0.0.1:${(issuer.address() as AddressInfo).port}`;
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1/admin/mcp-servers`;
+ const put = (id: string, body: object) =>
+ fetch(`${base}/${id}`, {
+ method: "PUT",
+ headers: ADMIN,
+ body: JSON.stringify({ url: `${issuerUrl}/mcp`, auth: "oauth-user", ...body }),
+ });
+
+ const undiscoverable = await put("orders", { clientId: "c", url: `${issuerUrl}/elsewhere` });
+ assert.equal(undiscoverable.status, 400);
+ assert.match(((await undiscoverable.json()) as { message: string }).message, /discovery: .*HTTP 404/);
+ assert.equal((await put("github", { clientId: "c" })).status, 400, "built-in connector ids are reserved");
+ assert.equal((await put("orders", { clientId: "c", credentialHost: "github.com" })).status, 400);
+ assert.equal((await put("orders", { clientId: "c", oauthTokenUrl: "http://id.example.com/token" })).status, 400);
+
+ assert.equal((await put("orders", { clientId: " c " })).status, 200);
+ const record = (await store.get("orders"))!;
+ assert.equal(record.credentialScope, "per-user");
+ assert.equal(record.credentialHost, "127.0.0.1");
+ assert.equal(record.clientId, "c");
+ assert.equal(record.oauthAuthorizeUrl, `${issuerUrl}/id/authorize`);
+ assert.equal(record.oauthTokenUrl, `${issuerUrl}/id/token`);
+ assert.deepEqual(record.oauthScopes, ["mcp:write"]);
+ assert.equal(record.clientSecret, undefined);
+
+ assert.equal(
+ (
+ await put("manual", {
+ clientId: "c",
+ url: "https://tools.example.com/mcp",
+ oauthAuthorizeUrl: "https://id.example.com/authorize",
+ oauthTokenUrl: "https://id.example.com/token",
+ oauthScopes: "a b",
+ })
+ ).status,
+ 200,
+ "explicit endpoints skip discovery",
+ );
+ assert.deepEqual((await store.get("manual"))!.oauthScopes, ["a", "b"]);
+});
diff --git a/test/mcp-oauth-user.test.ts b/test/mcp-oauth-user.test.ts
new file mode 100644
index 000000000..ad69267f3
--- /dev/null
+++ b/test/mcp-oauth-user.test.ts
@@ -0,0 +1,136 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createMcpServerStore, type McpServer } from "../src/mcp/mcp-server-store.ts";
+import { createMcpToolService, mcpPublicOAuthClients } from "../src/mcp/mcp-tool-service.ts";
+import {
+ authorizeUrl,
+ exchangeCode,
+ makeRefresh,
+ oauthProvider,
+ setPublicOAuthClients,
+ withPublicOAuthClients,
+} from "../src/connectors/oauth.ts";
+import { createMemoryMap } from "../src/persistence/durable-map.ts";
+
+const HOST = "mcp.example.com";
+
+function oauthServer(partial?: Partial<McpServer>): McpServer {
+ return {
+ id: "orders",
+ name: "Orders",
+ url: `https://${HOST}/mcp`,
+ auth: "oauth-user",
+ credentialScope: "per-user",
+ credentialHost: HOST,
+ clientId: "public-client",
+ oauthAuthorizeUrl: "https://id.example.com/authorize",
+ oauthTokenUrl: "https://id.example.com/token",
+ oauthScopes: ["mcp:write"],
+ readOnly: false,
+ enabled: true,
+ updatedAt: 0,
+ updatedBy: "internal:admin",
+ ...partial,
+ };
+}
+
+test("oauth-user servers register a PKCE public client that exchanges and refreshes without a secret", async (t) => {
+ t.after(() => setPublicOAuthClients([]));
+ setPublicOAuthClients(mcpPublicOAuthClients([oauthServer(), oauthServer({ id: "off", enabled: false })]));
+ assert.ok(oauthProvider("orders")?.pkce);
+ assert.equal(oauthProvider("off"), undefined);
+ const resolve = withPublicOAuthClients(async () => {
+ throw new Error("secret resolver must not be used");
+ });
+ const client = await resolve("orders", {});
+ assert.equal(client.secret, "");
+ const consent = new URL(
+ authorizeUrl("orders", { redirectUri: "https://qm/cb", state: "s", client, codeChallenge: "cc" }),
+ );
+ assert.equal(consent.origin + consent.pathname, "https://id.example.com/authorize");
+ assert.equal(consent.searchParams.get("client_id"), "public-client");
+ assert.equal(consent.searchParams.get("scope"), "mcp:write");
+ assert.equal(consent.searchParams.get("code_challenge_method"), "S256");
+ assert.equal(consent.searchParams.get("resource"), `https://${HOST}/mcp`);
+
+ const bodies: URLSearchParams[] = [];
+ const fetchImpl = async (_url: string, init: { body: string }) => {
+ bodies.push(new URLSearchParams(init.body));
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ access_token: `a${bodies.length}`, refresh_token: "r", expires_in: 60 }),
+ };
+ };
+ const { hosts, token } = await exchangeCode("orders", "code", "https://qm/cb", {
+ client,
+ fetchImpl,
+ codeVerifier: "v",
+ });
+ assert.deepEqual(hosts, [HOST]);
+ assert.equal(token.accessToken, "a1");
+ const fresh = await makeRefresh({ resolveClient: resolve, fetchImpl })(HOST, token);
+ assert.equal(fresh.accessToken, "a2");
+ for (const b of bodies) {
+ assert.equal(b.get("client_id"), "public-client");
+ assert.equal(b.has("client_secret"), false);
+ }
+ assert.equal(bodies[0]!.get("code_verifier"), "v");
+ for (const b of bodies) assert.equal(b.get("resource"), `https://${HOST}/mcp`);
+
+ setPublicOAuthClients([]);
+ assert.equal(oauthProvider("orders"), undefined);
+ setPublicOAuthClients(mcpPublicOAuthClients([oauthServer({ id: "github", credentialHost: "x.example" })]));
+ assert.notEqual(oauthProvider("github")?.pkce, true, "built-in providers are never shadowed");
+});
+
+test("oauth-user tools offer a sign-in link until the caller connects, then use only their token", async (t) => {
+ const store = createMcpServerStore(createMemoryMap<McpServer>());
+ const tokens = new Map<string, string>();
+ const auth: string[] = [];
+ const service = createMcpToolService({
+ servers: store,
+ userTokens: { connectorAccessToken: async (_host, principalId) => tokens.get(principalId) ?? null },
+ signInUrl: (id) => `https://qm.example/connect/${id}/self-connect`,
+ fetchImpl: async (_url, init) => {
+ auth.push(init.headers.authorization ?? "");
+ const rpc = JSON.parse(init.body) as { id: number; method: string; params: { arguments?: { q?: string } } };
+ const result =
+ rpc.method === "tools/list"
+ ? { tools: [{ name: "search", description: "Search", inputSchema: { type: "object" } }] }
+ : { content: [{ type: "text", text: `found ${rpc.params.arguments?.q}` }] };
+ return { ok: true, status: 200, text: async () => JSON.stringify({ jsonrpc: "2.0", id: rpc.id, result }) };
+ },
+ });
+ t.after(() => {
+ service.close();
+ setPublicOAuthClients([]);
+ });
+ await store.put(oauthServer());
+ await service.refresh();
+ assert.ok(oauthProvider("orders")?.pkce, "refresh registers the server's OAuth client");
+ assert.deepEqual(
+ service.toolDefs().map((d) => d.name),
+ ["orders_sign_in"],
+ );
+ assert.equal(auth.length, 0, "no unauthenticated discovery");
+ assert.match(
+ await service.call("orders_sign_in", {}, "internal:alice"),
+ /\[Connect Orders\]\(https:\/\/qm\.example\/connect\/orders\/self-connect\)/,
+ );
+
+ tokens.set("internal:alice", "alice-token");
+ assert.match(await service.call("orders_sign_in", {}, "internal:alice"), /orders_search/);
+ assert.deepEqual(
+ service.toolDefs().map((d) => d.name),
+ ["orders_search"],
+ );
+ assert.deepEqual(
+ (await store.get("orders"))!.tools?.map((tool) => tool.name),
+ ["search"],
+ "learned tools are stored with the server so every instance and restart sees them",
+ );
+ assert.equal(await service.call("orders_search", { q: "tacos" }, "internal:alice"), "found tacos");
+ assert.match(await service.call("orders_search", { q: "x" }, "internal:bob"), /Connect Orders/);
+ assert.deepEqual(auth, ["Bearer alice-token", "Bearer alice-token"]);
+});