diff --git a/apps/docs/content/docs/agents/mcp.mdx b/apps/docs/content/docs/agents/mcp.mdx index 17a7cffcb88..ed651c2a456 100644 --- a/apps/docs/content/docs/agents/mcp.mdx +++ b/apps/docs/content/docs/agents/mcp.mdx @@ -26,6 +26,16 @@ The registration uses `streamable-http` and defaults to a 30,000 ms connection t **Edit JSON** accepts a remote configuration with a named `mcpServers` entry containing `url` and optional `headers`, or a configuration containing `url` directly. If several entries are present, it reads the first. It does not import a desktop client's executable command configuration. +### OAuth client registration + +Before anyone can sign in to an OAuth-protected server, Sim needs a client ID at that server. Sim uses the first option that applies: + +1. The **Client ID** and **Client Secret** entered in **Advanced settings**. +2. Sim's client ID metadata document, when the server supports these documents. It is a public page describing Sim, served at `/api/mcp/oauth/client-metadata`. Its URL is the client ID, so the server needs no registration step. Sim skips it for Canva, which accepts these documents only from clients it has approved. +3. Automatic registration, when the server offers it. + +If none applies, **Authorize** reports that the server cannot register Sim automatically; enter a client ID in **Advanced settings**. Sim Cloud uses its metadata document by default. A self-hosted deployment uses it once an operator sets `MCP_OAUTH_CLIENT_METADATA_DOCUMENT_ENABLED` to `true`. + ### Secrets in URLs and headers URLs and headers support `{{VAR_NAME}}` substitution from available saved secrets. Type `{{` in either field to open the secret picker: @@ -138,6 +148,8 @@ Set `ALLOWED_MCP_DOMAINS` to a comma-separated list of exact approved hostnames Domain approval and network reachability are separate checks. Private-address servers also need `EGRESS_ALLOWED_HOSTS` or `EGRESS_ALLOWED_IP_RANGES`; see [the SSRF boundary](/platform/self-hosting/security#the-ssrf-boundary). +Set `MCP_OAUTH_CLIENT_METADATA_DOCUMENT_ENABLED` to `true` to use [Sim's client ID metadata document](#oauth-client-registration). OAuth servers fetch that document from your Sim URL, so turn it on only when that URL is reachable from the internet over HTTPS. While it is off, Sim registers through automatic registration or the client ID you enter. + The domain allowlist applies to the configured server URL. For OAuth, an endpoint on that server's origin retains its reachability. An endpoint named by metadata on a different origin is treated as fetched content and must be publicly routable under the egress policy. ## Related docs diff --git a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx index 1d9ddcab03a..3483be41e3e 100644 --- a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx +++ b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx @@ -39,6 +39,7 @@ Production Compose derives `DATABASE_URL` and `BETTER_AUTH_URL` on its service d | `AUTH_TRUSTED_PROXIES` | Comma-separated reverse-proxy IPs/CIDRs so the client IP cannot be forged through `X-Forwarded-For` | | `INTERNAL_API_BASE_URL` | Internal URL for server-side self-calls, e.g. `http://sim-app.simstudio.svc.cluster.local:3000`. Defaults to the public base URL. The Trigger.dev worker ignores it and uses the public app URL. | | `SIM_MCP_URL` | Public URL of the [Sim MCP server](/mcp/overview) when you serve it on its own host, e.g. `https://mcp.example.com/mcp`. Point that host at the app; Sim serves only the MCP endpoint and its OAuth metadata there, and stops serving `/api/mcp` on the app host so clients use one URL. Optional — defaults to `/api/mcp` | +| `MCP_OAUTH_CLIENT_METADATA_DOCUMENT_ENABLED` | Set to `true` so Sim identifies itself to MCP OAuth servers that support it with a client ID metadata document, instead of registering a new client at each server. The server reads `/api/mcp/oauth/client-metadata`, so turn it on only when that HTTPS URL is reachable from the internet. Off by default on self-hosted deployments, and has no effect while the app URL is not HTTPS. See [MCP client registration](/agents/mcp#oauth-client-registration) | | `ENCRYPT_ACCOUNT_TOKENS` | Set to `false` to stop sealing connected-account OAuth tokens on write and during `migrate`. Sealing is on by default with a 64-hex `ENCRYPTION_KEY`; see [Account token sealing](/platform/self-hosting/security#account-token-sealing) | | `DATABASE_REPLICA_URL` | Read-replica connection string for log listing, audit logs, and dashboard aggregations. Falls back to the primary when unset | diff --git a/apps/sim/app/api/mcp/oauth/callback/route.ts b/apps/sim/app/api/mcp/oauth/callback/route.ts index 9a521e49585..7cf3ee76bed 100644 --- a/apps/sim/app/api/mcp/oauth/callback/route.ts +++ b/apps/sim/app/api/mcp/oauth/callback/route.ts @@ -283,7 +283,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => { const preregistered = await timedStep('loadPreregisteredClient', 15_000, () => loadPreregisteredClient(server.id) ) - const provider = new SimMcpOauthProvider({ row, preregistered }) + const provider = new SimMcpOauthProvider({ row, serverUrl, preregistered }) let result: Awaited> try { // An egress refusal of a URL the server named is the server's configuration, not a diff --git a/apps/sim/app/api/mcp/oauth/client-metadata/route.test.ts b/apps/sim/app/api/mcp/oauth/client-metadata/route.test.ts new file mode 100644 index 00000000000..03aec371a30 --- /dev/null +++ b/apps/sim/app/api/mcp/oauth/client-metadata/route.test.ts @@ -0,0 +1,45 @@ +/** + * @vitest-environment node + */ +import { resetEnvFlagsMock, resetEnvMock, setEnv, setEnvFlags } from '@sim/testing' +import { NextRequest } from 'next/server' +import { afterEach, describe, expect, it } from 'vitest' +import { mcpOauthClientMetadataDocumentSchema } from '@/lib/api/contracts/mcp' +import { GET } from '@/app/api/mcp/oauth/client-metadata/route' + +describe('GET /api/mcp/oauth/client-metadata', () => { + afterEach(() => { + resetEnvMock() + resetEnvFlagsMock() + }) + + it('serves the configured document whatever host the request names', async () => { + setEnv({ NEXT_PUBLIC_APP_URL: 'https://sim.example.com' }) + + const response = await GET( + new NextRequest('https://attacker.example/api/mcp/oauth/client-metadata', { + headers: { host: 'attacker.example', 'x-forwarded-host': 'attacker.example' }, + }), + undefined + ) + + expect(response.status).toBe(200) + expect(response.headers.get('content-type')).toContain('application/json') + expect(response.headers.get('cache-control')).toBe('public, max-age=3600') + const document = mcpOauthClientMetadataDocumentSchema.parse(await response.json()) + expect(document.client_id).toBe('https://sim.example.com/api/mcp/oauth/client-metadata') + expect(document.redirect_uris).toEqual(['https://sim.example.com/api/mcp/oauth/callback']) + }) + + it('keeps serving while the deployment does not present it, for grants already issued', async () => { + setEnv({ NEXT_PUBLIC_APP_URL: 'https://sim.example.com' }) + setEnvFlags({ isMcpOauthClientMetadataDocumentEnabled: false }) + + const response = await GET( + new NextRequest('https://sim.example.com/api/mcp/oauth/client-metadata'), + undefined + ) + + expect(response.status).toBe(200) + }) +}) diff --git a/apps/sim/app/api/mcp/oauth/client-metadata/route.ts b/apps/sim/app/api/mcp/oauth/client-metadata/route.ts new file mode 100644 index 00000000000..f12dd119c90 --- /dev/null +++ b/apps/sim/app/api/mcp/oauth/client-metadata/route.ts @@ -0,0 +1,22 @@ +import { NextResponse } from 'next/server' +import { getMcpOauthClientMetadataDocumentContract } from '@/lib/api/contracts/mcp' +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { buildMcpOauthClientMetadataDocument } from '@/lib/mcp/oauth/client-metadata' + +export const dynamic = 'force-dynamic' + +/** The document changes only with the deployment's configuration. */ +const CLIENT_METADATA_CACHE_SECONDS = 3600 + +const documentSchema = getMcpOauthClientMetadataDocumentContract.response.schema + +/** + * Sim's public OAuth Client ID Metadata Document, fetched by MCP authorization servers Sim presents + * this URL to as its `client_id`. Served even while the setting is off: authorization servers fetch + * it again on refresh, so grants already issued would otherwise be stranded. + */ +export const GET = withRouteHandler(() => + NextResponse.json(documentSchema.parse(buildMcpOauthClientMetadataDocument()), { + headers: { 'Cache-Control': `public, max-age=${CLIENT_METADATA_CACHE_SECONDS}` }, + }) +) diff --git a/apps/sim/app/api/mcp/oauth/start/route.ts b/apps/sim/app/api/mcp/oauth/start/route.ts index 4d0fd73bc37..ce6f8d3b209 100644 --- a/apps/sim/app/api/mcp/oauth/start/route.ts +++ b/apps/sim/app/api/mcp/oauth/start/route.ts @@ -169,7 +169,7 @@ export const GET = withRouteHandler( const preregistered = await timedStep('loadPreregisteredClient', DB_STEP_MS, () => loadPreregisteredClient(server.id) ) - const provider = new SimMcpOauthProvider({ row, preregistered }) + const provider = new SimMcpOauthProvider({ row, serverUrl, preregistered }) // OAuth discovery + DCR through the guarded fetch, bounded so a transient stall fails // fast with a labeled log instead of hanging the popup. `McpOauthRedirectRequired` is diff --git a/apps/sim/lib/api/contracts/mcp.ts b/apps/sim/lib/api/contracts/mcp.ts index 485850216f8..088aebe00d3 100644 --- a/apps/sim/lib/api/contracts/mcp.ts +++ b/apps/sim/lib/api/contracts/mcp.ts @@ -493,6 +493,37 @@ export const mcpOauthCallbackContract = defineRouteContract({ response: { mode: 'text' }, }) +/** + * Sim's OAuth Client ID Metadata Document. Sim is a public PKCE client, so it carries no secret or + * key material, and `strict` keeps one from being added unnoticed. Both auth-method fields are sent: + * MCP's profile and older servers read the singular, the current draft prefers the plural. + */ +export const mcpOauthClientMetadataDocumentSchema = z + .object({ + client_id: z.string().url(), + client_name: z.string().min(1), + client_uri: z.string().url(), + logo_uri: z.string().url(), + tos_uri: z.string().url().optional(), + policy_uri: z.string().url().optional(), + redirect_uris: z.array(z.string().url()).min(1), + grant_types: z.array(z.enum(['authorization_code', 'refresh_token'])).min(1), + response_types: z.array(z.literal('code')).min(1), + token_endpoint_auth_method: z.literal('none'), + token_endpoint_auth_methods_supported: z.array(z.literal('none')).min(1), + }) + .strict() +export type McpOauthClientMetadataDocument = z.output + +export const getMcpOauthClientMetadataDocumentContract = defineRouteContract({ + method: 'GET', + path: '/api/mcp/oauth/client-metadata', + response: { + mode: 'json', + schema: mcpOauthClientMetadataDocumentSchema, + }, +}) + export const getAllowedMcpDomainsContract = defineRouteContract({ method: 'GET', path: '/api/settings/allowed-mcp-domains', diff --git a/apps/sim/lib/core/config/env-flags.ts b/apps/sim/lib/core/config/env-flags.ts index cf428dc0b6b..ccf6b455652 100644 --- a/apps/sim/lib/core/config/env-flags.ts +++ b/apps/sim/lib/core/config/env-flags.ts @@ -120,6 +120,15 @@ export const isCopilotToolPermissionsEnabled = isTruthy(env.COPILOT_TOOL_PERMISS /** Deployment-only opt-in; authenticated resource permissions still apply. */ export const isMothershipBenchmarkEnabled = isTruthy(env.MOTHERSHIP_BENCHMARK_ENABLED) +/** + * Present Sim's Client ID Metadata Document URL as its `client_id` to MCP authorization servers + * that support it, instead of registering dynamically. A server that cannot fetch the document + * fails sign-in outright, with no fallback to registration, so this defaults on only for Sim Cloud; + * self-hosted operators opt in once the app URL is publicly reachable. + */ +export const isMcpOauthClientMetadataDocumentEnabled = + envBoolean(env.MCP_OAUTH_CLIENT_METADATA_DOCUMENT_ENABLED) ?? isHosted + /** * A server-only switch: `serverValue` on the server; in the browser, which never * sees server variables, the server's answer from the deployment-shape projection diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 3aa87360102..af98abb8b9e 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -301,6 +301,7 @@ export const env = createEnv({ BLACKLISTED_PROVIDERS: z.string().optional(), // Comma-separated provider IDs to hide (e.g., "openai,anthropic") BLACKLISTED_MODELS: z.string().optional(), // Comma-separated model names/prefixes to hide (e.g., "gpt-4,claude-*") ALLOWED_MCP_DOMAINS: z.string().optional(), // Comma-separated domains for MCP servers (e.g., "internal.company.com,mcp.example.org"). Empty = all allowed. + MCP_OAUTH_CLIENT_METADATA_DOCUMENT_ENABLED: z.string().optional(), // Present a Client ID Metadata Document to MCP OAuth servers instead of dynamic registration. Default: true on Sim Cloud, false self-hosted; needs a publicly reachable HTTPS NEXT_PUBLIC_APP_URL. Coerced via envBoolean ALLOWED_INTEGRATIONS: z.string().optional(), // Comma-separated block types to allow (e.g., "slack,github,agent"). Empty = all allowed. PREVIEW_BLOCKS: z.string().optional(), // Comma-separated preview block types to reveal off-AppConfig (e.g., "gmail_v2,notion_v3"). Empty = all preview blocks hidden. diff --git a/apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts b/apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts index 051b2a85893..15044b94970 100644 --- a/apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts +++ b/apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts @@ -339,6 +339,7 @@ describe.each(SHARED_CLIENTS)('$name shared member connector', (connector) => { const loadProvider = async () => new SimMcpOauthProvider({ row: await getOrCreateOauthRow({ mcpServerId: mcpServer.id, organizationId: org }), + serverUrl: connector.url, preregistered: await loadPreregisteredClient(mcpServer.id), }) const provider = await loadProvider() @@ -406,6 +407,7 @@ describe.each(SHARED_CLIENTS)('$name shared member connector', (connector) => { const substitute = 'https://oauth.substitute.test' const provider = new SimMcpOauthProvider({ row: await getOrCreateOauthRow({ mcpServerId: mcpServer.id, organizationId: org }), + serverUrl: connector.url, preregistered: await loadPreregisteredClient(mcpServer.id), }) if (phase === 'code exchange') await provider.saveCodeVerifier('fixture-verifier') diff --git a/apps/sim/lib/credential-groups/mcp-oauth.ts b/apps/sim/lib/credential-groups/mcp-oauth.ts index 701ebf26b97..48b55b549d4 100644 --- a/apps/sim/lib/credential-groups/mcp-oauth.ts +++ b/apps/sim/lib/credential-groups/mcp-oauth.ts @@ -54,6 +54,7 @@ export async function startCredentialGroupMcpOAuth( const preregistered = await loadPreregisteredClient(context.server.id) const provider = new ManagedMcpOauthProvider({ clientRow, + serverUrl: context.server.url, preregistered, async onSaveTokens() { throw new Error('Managed MCP OAuth start cannot persist grant tokens') @@ -160,6 +161,7 @@ export async function completeCredentialGroupMcpOAuth( let grantedTokens: OAuthTokens | undefined const provider = new ManagedMcpOauthProvider({ clientRow, + serverUrl: context.server.url, preregistered, codeVerifier, async onSaveTokens(tokens) { diff --git a/apps/sim/lib/credentials/managed-mcp.ts b/apps/sim/lib/credentials/managed-mcp.ts index 55cbc87f633..9ee170a3fc6 100644 --- a/apps/sim/lib/credentials/managed-mcp.ts +++ b/apps/sim/lib/credentials/managed-mcp.ts @@ -66,6 +66,7 @@ export interface ManagedMcpRuntimeCredential { credentialId: string mcpServerId: string mcpServerName: string + mcpServerUrl: string workspaceId: string tokenVersion: string tokens: OAuthTokens @@ -307,6 +308,7 @@ export async function loadScopedManagedMcpRuntimeCredential( scope, mcpServerId: row.mcpServerId, mcpServerName: row.mcpServerName, + mcpServerUrl: row.serverUrl, tokenVersion: row.encryptedTokens, grantedAt: row.grantedAt, tokens: envelope.tokens, diff --git a/apps/sim/lib/mcp/application/managed-auth-provider.ts b/apps/sim/lib/mcp/application/managed-auth-provider.ts index 03d2d684270..58e87a13c4d 100644 --- a/apps/sim/lib/mcp/application/managed-auth-provider.ts +++ b/apps/sim/lib/mcp/application/managed-auth-provider.ts @@ -46,6 +46,7 @@ export async function createManagedMcpAuthProvider( let tokenVersion: string | null = current.tokenVersion return new ManagedMcpOauthProvider({ clientRow, + serverUrl: current.mcpServerUrl, preregistered, tokens: current.tokens, async onSaveTokens(tokens) { diff --git a/apps/sim/lib/mcp/connection-manager.ts b/apps/sim/lib/mcp/connection-manager.ts index 8f420aae107..0feae695d97 100644 --- a/apps/sim/lib/mcp/connection-manager.ts +++ b/apps/sim/lib/mcp/connection-manager.ts @@ -165,6 +165,8 @@ export class McpConnectionManager { let oauthCredentials: McpClientOptions['oauthCredentials'] if (config.authType === 'oauth') { + const serverUrl = config.url + if (!serverUrl) throw new Error('OAuth MCP server requires a URL') const row = await getOrCreateOauthRow({ mcpServerId: config.id, userId, @@ -181,6 +183,7 @@ export class McpConnectionManager { credentialId: config.id, initialProvider: new SimMcpOauthProvider({ row, + serverUrl, preregistered: await loadPreregisteredClient(config.id), }), loadProvider: async () => { @@ -193,7 +196,7 @@ export class McpConnectionManager { throw new McpOauthAuthorizationRequiredError(config.id, config.name) } const preregistered = await loadPreregisteredClient(config.id) - return new SimMcpOauthProvider({ row: current, preregistered }) + return new SimMcpOauthProvider({ row: current, serverUrl, preregistered }) }, } } diff --git a/apps/sim/lib/mcp/oauth/client-metadata.test.ts b/apps/sim/lib/mcp/oauth/client-metadata.test.ts new file mode 100644 index 00000000000..e605bd3e416 --- /dev/null +++ b/apps/sim/lib/mcp/oauth/client-metadata.test.ts @@ -0,0 +1,223 @@ +/** + * @vitest-environment node + */ +import { auth, type OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js' +import { + encryptionMock, + resetDbChainMock, + resetEnvFlagsMock, + resetEnvMock, + setEnv, + setEnvFlags, +} from '@sim/testing' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/security/encryption', () => encryptionMock) + +import { + buildMcpOauthClientMetadataDocument, + getMcpOauthClientMetadataUrl, +} from '@/lib/mcp/oauth/client-metadata' +import { ManagedMcpOauthProvider } from '@/lib/mcp/oauth/managed-provider' +import { + McpOauthRedirectRequired, + type PreregisteredClient, + SimMcpOauthProvider, +} from '@/lib/mcp/oauth/provider' +import type { McpOauthRow } from '@/lib/mcp/oauth/storage' + +const APP_URL = 'https://sim.example.com' +const METADATA_URL = `${APP_URL}/api/mcp/oauth/client-metadata` +const CALLBACK_URL = `${APP_URL}/api/mcp/oauth/callback` +const SERVER_URL = 'https://mcp.example.com/mcp' +const ISSUER = 'https://auth.example.com' + +afterEach(() => { + resetEnvMock() + resetEnvFlagsMock() +}) + +describe('Sim MCP OAuth client metadata document', () => { + it('normalizes the client_id, which the authorization server compares character for character', () => { + setEnv({ NEXT_PUBLIC_APP_URL: 'https://Sim.Example.com:443/' }) + setEnvFlags({ isMcpOauthClientMetadataDocumentEnabled: true }) + + expect(buildMcpOauthClientMetadataDocument().client_id).toBe(METADATA_URL) + expect(getMcpOauthClientMetadataUrl(SERVER_URL)).toBe(METADATA_URL) + }) + + it('registers dynamically with servers that reject metadata documents', () => { + setEnv({ NEXT_PUBLIC_APP_URL: APP_URL }) + setEnvFlags({ isMcpOauthClientMetadataDocumentEnabled: true }) + + expect(getMcpOauthClientMetadataUrl('https://mcp.canva.com/mcp')).toBeUndefined() + }) + + it('links Sim Cloud terms and privacy, which a self-hosted deployment leaves out', () => { + setEnv({ NEXT_PUBLIC_APP_URL: APP_URL }) + + setEnvFlags({ isHosted: true }) + expect(buildMcpOauthClientMetadataDocument()).toMatchObject({ + tos_uri: `${APP_URL}/terms`, + policy_uri: `${APP_URL}/privacy`, + }) + + setEnvFlags({ isHosted: false }) + const selfHosted = buildMcpOauthClientMetadataDocument() + expect(selfHosted).not.toHaveProperty('tos_uri') + expect(selfHosted).not.toHaveProperty('policy_uri') + }) +}) + +/** The response the authorization server returns to dynamic registration. */ +const REGISTERED_CLIENT = { + client_id: 'registered-client-1', + redirect_uris: [CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'none', +} + +/** An authorization server that offers dynamic registration and, optionally, metadata documents. */ +function authorizationServer({ acceptsMetadataDocuments }: { acceptsMetadataDocuments: boolean }) { + return vi.fn(async (input: string | URL, _init?: RequestInit) => { + const url = String(input) + const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' }, + }) + if (url.startsWith('https://mcp.example.com/.well-known/oauth-protected-resource')) + return json(200, { resource: SERVER_URL, authorization_servers: [ISSUER] }) + if (url.startsWith(`${ISSUER}/.well-known/`)) + return json(200, { + issuer: ISSUER, + authorization_endpoint: `${ISSUER}/authorize`, + token_endpoint: `${ISSUER}/token`, + registration_endpoint: `${ISSUER}/register`, + response_types_supported: ['code'], + code_challenge_methods_supported: ['S256'], + ...(acceptsMetadataDocuments ? { client_id_metadata_document_supported: true } : {}), + }) + if (url === `${ISSUER}/register`) return json(201, REGISTERED_CLIENT) + return json(404, {}) + }) +} + +function newRow(): McpOauthRow { + return { + id: 'oauth-row-1', + mcpServerId: 'server-1', + userId: 'user-1', + workspaceId: 'workspace-1', + organizationId: null, + clientInformation: null, + tokens: null, + codeVerifier: null, + state: null, + stateCreatedAt: null, + updatedAt: new Date(), + } +} + +const PREREGISTERED: PreregisteredClient = { clientId: 'preregistered-client-1' } + +const providers: Array<{ + name: string + create: (preregistered?: PreregisteredClient) => OAuthClientProvider +}> = [ + { + name: 'SimMcpOauthProvider', + create: (preregistered) => + new SimMcpOauthProvider({ row: newRow(), serverUrl: SERVER_URL, preregistered }), + }, + { + name: 'ManagedMcpOauthProvider', + create: (preregistered) => + new ManagedMcpOauthProvider({ + clientRow: newRow(), + serverUrl: SERVER_URL, + preregistered, + onSaveTokens: vi.fn(async () => {}), + }), + }, +] + +/** Runs the SDK's authorization step and returns the URL it sends the user to. */ +async function authorizationUrl( + provider: OAuthClientProvider, + fetchFn: ReturnType +): Promise { + const error = await auth(provider, { serverUrl: SERVER_URL, fetchFn }).then( + () => undefined, + (caught: unknown) => caught + ) + expect(error).toBeInstanceOf(McpOauthRedirectRequired) + return new URL((error as McpOauthRedirectRequired).authorizationUrl) +} + +function registrationCalls(fetchFn: ReturnType) { + return fetchFn.mock.calls.filter(([input]) => String(input) === `${ISSUER}/register`) +} + +describe.each(providers)('$name client registration', ({ create }) => { + beforeEach(() => { + resetDbChainMock() + setEnv({ NEXT_PUBLIC_APP_URL: APP_URL }) + setEnvFlags({ isMcpOauthClientMetadataDocumentEnabled: true }) + }) + + it('presents the metadata document URL as its client_id without registering', async () => { + const provider = create() + const fetchFn = authorizationServer({ acceptsMetadataDocuments: true }) + + const url = await authorizationUrl(provider, fetchFn) + + expect(url.searchParams.get('client_id')).toBe(METADATA_URL) + expect(url.searchParams.get('redirect_uri')).toBe(CALLBACK_URL) + expect(registrationCalls(fetchFn)).toHaveLength(0) + expect((await provider.clientInformation())?.client_id).toBe(METADATA_URL) + }) + + it('registers dynamically with a server that does not accept metadata documents', async () => { + const provider = create() + const fetchFn = authorizationServer({ acceptsMetadataDocuments: false }) + + const url = await authorizationUrl(provider, fetchFn) + + expect(url.searchParams.get('client_id')).toBe(REGISTERED_CLIENT.client_id) + expect(registrationCalls(fetchFn)).toHaveLength(1) + }) + + it('registers dynamically while the deployment does not present the document', async () => { + setEnvFlags({ isMcpOauthClientMetadataDocumentEnabled: false }) + const provider = create() + const fetchFn = authorizationServer({ acceptsMetadataDocuments: true }) + + const url = await authorizationUrl(provider, fetchFn) + + expect(url.searchParams.get('client_id')).toBe(REGISTERED_CLIENT.client_id) + expect(registrationCalls(fetchFn)).toHaveLength(1) + }) + + it('registers dynamically when the deployment is not served over HTTPS', async () => { + setEnv({ NEXT_PUBLIC_APP_URL: 'http://localhost:3000' }) + const provider = create() + const fetchFn = authorizationServer({ acceptsMetadataDocuments: true }) + + const url = await authorizationUrl(provider, fetchFn) + + expect(url.searchParams.get('client_id')).toBe(REGISTERED_CLIENT.client_id) + expect(registrationCalls(fetchFn)).toHaveLength(1) + }) + + it('keeps a pre-registered client ahead of the metadata document', async () => { + const provider = create(PREREGISTERED) + const fetchFn = authorizationServer({ acceptsMetadataDocuments: true }) + + const url = await authorizationUrl(provider, fetchFn) + + expect(url.searchParams.get('client_id')).toBe(PREREGISTERED.clientId) + expect(registrationCalls(fetchFn)).toHaveLength(0) + }) +}) diff --git a/apps/sim/lib/mcp/oauth/client-metadata.ts b/apps/sim/lib/mcp/oauth/client-metadata.ts new file mode 100644 index 00000000000..0151da65af7 --- /dev/null +++ b/apps/sim/lib/mcp/oauth/client-metadata.ts @@ -0,0 +1,70 @@ +import { + getMcpOauthClientMetadataDocumentContract, + type McpOauthClientMetadataDocument, + mcpOauthCallbackContract, +} from '@/lib/api/contracts/mcp' +import { isHosted, isMcpOauthClientMetadataDocumentEnabled } from '@/lib/core/config/env-flags' +import { getBaseUrl } from '@/lib/core/utils/urls' + +/** Square app icon, which consent screens show beside the client name. */ +const MCP_OAUTH_CLIENT_LOGO_PATH = '/favicon/web-app-manifest-512x512.png' + +/** + * MCP servers that advertise Client ID Metadata Documents but reject Sim's: Canva fetches the + * document, then refuses its redirect URI unless Canva has allowlisted it. They register + * dynamically instead. + */ +const CLIENT_METADATA_DOCUMENT_EXCLUDED_HOSTS: ReadonlySet = new Set(['mcp.canva.com']) + +/** + * The redirect URI Sim sends in every MCP authorization request. Clients registered dynamically + * recorded this exact string, and the metadata document lists it, so it must not change shape. + */ +export function getMcpOauthRedirectUrl(): string { + return `${getBaseUrl()}${mcpOauthCallbackContract.path}` +} + +/** + * The metadata document's URL, normalized because the authorization server compares it to the + * document's `client_id` character for character. It is Sim's `client_id` at every server that + * accepted it, so changing the route's path makes Sim a different client and strands its grants. + */ +function getMcpOauthClientMetadataDocumentUrl(): string { + return new URL(`${getBaseUrl()}${getMcpOauthClientMetadataDocumentContract.path}`).href +} + +/** + * The `client_id` Sim offers to authorization servers that accept Client ID Metadata Documents, or + * undefined to register dynamically instead. A non-HTTPS URL is never offered: the MCP SDK rejects + * one before checking server support, which would fail every OAuth connection, not just these. + */ +export function getMcpOauthClientMetadataUrl(serverUrl: string): string | undefined { + if (!isMcpOauthClientMetadataDocumentEnabled) return undefined + const host = URL.canParse(serverUrl) ? new URL(serverUrl).hostname : '' + if (CLIENT_METADATA_DOCUMENT_EXCLUDED_HOSTS.has(host)) return undefined + const url = getMcpOauthClientMetadataDocumentUrl() + return url.startsWith('https://') ? url : undefined +} + +/** + * Sim's Client ID Metadata Document. Every value comes from this deployment's configuration, never + * from the fetching request, as the draft requires: a caller-shaped document would let anyone mint + * a client identity under Sim's URL. Terms and privacy links are Sim Cloud's, so self-hosted + * deployments omit them. + */ +export function buildMcpOauthClientMetadataDocument(): McpOauthClientMetadataDocument { + return { + client_id: getMcpOauthClientMetadataDocumentUrl(), + client_name: 'Sim', + client_uri: getBaseUrl(), + logo_uri: `${getBaseUrl()}${MCP_OAUTH_CLIENT_LOGO_PATH}`, + ...(isHosted + ? { tos_uri: `${getBaseUrl()}/terms`, policy_uri: `${getBaseUrl()}/privacy` } + : {}), + redirect_uris: [getMcpOauthRedirectUrl()], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'none', + token_endpoint_auth_methods_supported: ['none'], + } +} diff --git a/apps/sim/lib/mcp/oauth/managed-provider.ts b/apps/sim/lib/mcp/oauth/managed-provider.ts index b604d8c0e5d..3f1d1522ae6 100644 --- a/apps/sim/lib/mcp/oauth/managed-provider.ts +++ b/apps/sim/lib/mcp/oauth/managed-provider.ts @@ -5,7 +5,10 @@ import type { OAuthTokens, } from '@modelcontextprotocol/sdk/shared/auth.js' import { generateId } from '@sim/utils/id' -import { getBaseUrl } from '@/lib/core/utils/urls' +import { + getMcpOauthClientMetadataUrl, + getMcpOauthRedirectUrl, +} from '@/lib/mcp/oauth/client-metadata' import { McpOauthRedirectRequired, type PreregisteredClient, @@ -15,6 +18,8 @@ import { clearClient, type McpOauthRow, saveClientInformation } from '@/lib/mcp/ interface ManagedMcpOauthProviderInit { clientRow: McpOauthRow + /** The MCP server being authorized; decides whether Sim offers its metadata document. */ + serverUrl: string preregistered?: PreregisteredClient tokens?: OAuthTokens codeVerifier?: string @@ -24,6 +29,7 @@ interface ManagedMcpOauthProviderInit { /** Shares server client registration while keeping grant tokens scoped to one enrollment. */ export class ManagedMcpOauthProvider implements OAuthClientProvider { private readonly clientRow: McpOauthRow + private readonly serverUrl: string private readonly preregistered?: PreregisteredClient private readonly onSaveTokens: (tokens: OAuthTokens | null) => Promise private currentTokens?: OAuthTokens @@ -32,12 +38,14 @@ export class ManagedMcpOauthProvider implements OAuthClientProvider { constructor({ clientRow, + serverUrl, preregistered, tokens, codeVerifier, onSaveTokens, }: ManagedMcpOauthProviderInit) { this.clientRow = clientRow + this.serverUrl = serverUrl this.preregistered = preregistered this.currentTokens = tokens this.currentCodeVerifier = codeVerifier @@ -50,7 +58,15 @@ export class ManagedMcpOauthProvider implements OAuthClientProvider { } get redirectUrl(): string { - return `${getBaseUrl().replace(/\/$/, '')}/api/mcp/oauth/callback` + return getMcpOauthRedirectUrl() + } + + /** + * Offered as the `client_id` when the authorization server accepts Client ID Metadata + * Documents; the SDK then stores that URL as the shared client registration. + */ + get clientMetadataUrl(): string | undefined { + return getMcpOauthClientMetadataUrl(this.serverUrl) } get clientMetadata(): OAuthClientMetadata { diff --git a/apps/sim/lib/mcp/oauth/provider.test.ts b/apps/sim/lib/mcp/oauth/provider.test.ts index a24c3d06268..23daf34e3ee 100644 --- a/apps/sim/lib/mcp/oauth/provider.test.ts +++ b/apps/sim/lib/mcp/oauth/provider.test.ts @@ -61,7 +61,11 @@ describe('SimMcpOauthProvider preserving the shared grant', () => { }) it('writes nothing to the OAuth row when a refresh is rejected', async () => { - const provider = new SimMcpOauthProvider({ row: grantRow(), preserveGrant: true }) + const provider = new SimMcpOauthProvider({ + row: grantRow(), + serverUrl: 'https://mcp.example.com/mcp', + preserveGrant: true, + }) await expect( auth(provider, { @@ -76,7 +80,11 @@ describe('SimMcpOauthProvider preserving the shared grant', () => { }) it('persists a successful refresh, which keeps the grant valid for everyone', async () => { - const provider = new SimMcpOauthProvider({ row: grantRow(), preserveGrant: true }) + const provider = new SimMcpOauthProvider({ + row: grantRow(), + serverUrl: 'https://mcp.example.com/mcp', + preserveGrant: true, + }) await expect( auth(provider, { diff --git a/apps/sim/lib/mcp/oauth/provider.ts b/apps/sim/lib/mcp/oauth/provider.ts index ece15d37b29..8965ce36cf4 100644 --- a/apps/sim/lib/mcp/oauth/provider.ts +++ b/apps/sim/lib/mcp/oauth/provider.ts @@ -12,8 +12,11 @@ import { generateId } from '@sim/utils/id' import { eq } from 'drizzle-orm' import { resourceScopeFromOwner } from '@/lib/core/resource-scope' import { decryptSecret } from '@/lib/core/security/encryption' -import { getBaseUrl } from '@/lib/core/utils/urls' import { MANAGED_MCP_CONNECTORS } from '@/lib/credential-groups/managed-mcp-connectors' +import { + getMcpOauthClientMetadataUrl, + getMcpOauthRedirectUrl, +} from '@/lib/mcp/oauth/client-metadata' import { getSharedHubSpotMcpClient, getSharedZoomMcpClient } from '@/lib/mcp/oauth/shared-clients' import { clearClient, @@ -65,6 +68,8 @@ export function withPinnedIssuer( interface SimMcpOauthProviderInit { row: McpOauthRow + /** The MCP server being authorized; decides whether Sim offers its metadata document. */ + serverUrl: string scope?: string /** * Optional user-supplied client credentials. When provided, the SDK skips @@ -89,12 +94,20 @@ class McpOauthGrantPreservedError extends Error { export class SimMcpOauthProvider implements OAuthClientProvider { private row: McpOauthRow + private readonly serverUrl: string private readonly scope?: string private readonly preregistered?: PreregisteredClient private readonly preserveGrant: boolean - constructor({ row, scope, preregistered, preserveGrant = false }: SimMcpOauthProviderInit) { + constructor({ + row, + serverUrl, + scope, + preregistered, + preserveGrant = false, + }: SimMcpOauthProviderInit) { this.row = row + this.serverUrl = serverUrl this.scope = preregistered?.scope ?? scope this.preregistered = preregistered this.preserveGrant = preserveGrant @@ -110,7 +123,16 @@ export class SimMcpOauthProvider implements OAuthClientProvider { } get redirectUrl(): string { - return `${getBaseUrl().replace(/\/$/, '')}/api/mcp/oauth/callback` + return getMcpOauthRedirectUrl() + } + + /** + * Offered as the `client_id` when the authorization server accepts Client ID Metadata + * Documents. The SDK prefers it to dynamic registration and never reaches it while a + * pre-registered client or a stored registration is present. + */ + get clientMetadataUrl(): string | undefined { + return getMcpOauthClientMetadataUrl(this.serverUrl) } get clientMetadata(): OAuthClientMetadata { diff --git a/apps/sim/lib/mcp/oauth/shared-clients.ts b/apps/sim/lib/mcp/oauth/shared-clients.ts index f20030ea5b0..cbba6b0eef2 100644 --- a/apps/sim/lib/mcp/oauth/shared-clients.ts +++ b/apps/sim/lib/mcp/oauth/shared-clients.ts @@ -3,8 +3,8 @@ import { inspectConfiguredOAuthClient, requireConfiguredOAuthClient, } from '@/lib/core/config/env-capabilities.server' -import { getBaseUrl } from '@/lib/core/utils/urls' import { MANAGED_MCP_CONNECTORS } from '@/lib/credential-groups/managed-mcp-connectors' +import { getMcpOauthRedirectUrl } from '@/lib/mcp/oauth/client-metadata' /** Deployment-owned registration; access tokens remain personal managed grants. */ export function getSharedHubSpotMcpClient() { @@ -20,7 +20,7 @@ export function getSharedHubSpotMcpClient() { JSON.stringify([ 'shared-hubspot-mcp', MANAGED_MCP_CONNECTORS.hubspot.url, - `${getBaseUrl().replace(/\/$/, '')}/api/mcp/oauth/callback`, + getMcpOauthRedirectUrl(), clientId, clientSecret, ]) @@ -46,7 +46,7 @@ export function getSharedZoomMcpClient() { JSON.stringify([ 'shared-zoom-mcp', MANAGED_MCP_CONNECTORS.zoom.url, - `${getBaseUrl().replace(/\/$/, '')}/api/mcp/oauth/callback`, + getMcpOauthRedirectUrl(), clientId, clientSecret, scope, diff --git a/apps/sim/lib/mcp/service.ts b/apps/sim/lib/mcp/service.ts index f5828309afe..5be18df2572 100644 --- a/apps/sim/lib/mcp/service.ts +++ b/apps/sim/lib/mcp/service.ts @@ -453,6 +453,8 @@ class McpService { throw new Error('OAuth MCP server requires both userId and workspaceId') } const workspaceId = config.workspaceId + const serverUrl = config.url + if (!serverUrl) throw new Error('OAuth MCP server requires a URL') const loadProvider = async () => { const row = await getOrCreateOauthRow({ @@ -464,7 +466,7 @@ class McpService { throw new McpOauthAuthorizationRequiredError(config.id, config.name) } const preregistered = await loadPreregisteredClient(config.id) - return new SimMcpOauthProvider({ row, preregistered, preserveGrant }) + return new SimMcpOauthProvider({ row, serverUrl, preregistered, preserveGrant }) } const client = new McpClient({ config, diff --git a/helm/sim/Chart.yaml b/helm/sim/Chart.yaml index 738ec12ba09..9d542241daa 100644 --- a/helm/sim/Chart.yaml +++ b/helm/sim/Chart.yaml @@ -2,7 +2,7 @@ apiVersion: v2 name: sim description: A Helm chart for Sim - the open-source AI workspace where teams build, deploy, and manage AI agents type: application -version: 1.16.0 +version: 1.16.1 appVersion: "v0.8.26" kubeVersion: ">=1.25.0-0" home: https://sim.ai diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 22e132a0788..7ea708f9306 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -228,6 +228,7 @@ app: BLACKLISTED_PROVIDERS: "" # Comma-separated provider IDs to hide from UI (e.g., "openai,anthropic,google") BLACKLISTED_MODELS: "" # Comma-separated model names/prefixes to hide (e.g., "gpt-4,claude-*") ALLOWED_MCP_DOMAINS: "" # Comma-separated domains for MCP servers (e.g., "internal.company.com,mcp.example.org"). Empty = all allowed. + MCP_OAUTH_CLIENT_METADATA_DOCUMENT_ENABLED: "" # Set to "true" to identify Sim to MCP OAuth servers with a client ID metadata document instead of dynamic registration. Needs an HTTPS app URL reachable from the internet # Integration/Block Restrictions (leave empty if not restricting) ALLOWED_INTEGRATIONS: "" # Comma-separated block types to allow (e.g., "slack,github,agent"). Empty = all allowed. diff --git a/packages/testing/src/mocks/env-flags.mock.ts b/packages/testing/src/mocks/env-flags.mock.ts index eeac43e6a60..8dbfddd8ad5 100644 --- a/packages/testing/src/mocks/env-flags.mock.ts +++ b/packages/testing/src/mocks/env-flags.mock.ts @@ -19,6 +19,7 @@ interface EnvFlagsMockState { isStatusNoticePreviewEnabled: boolean isCopilotToolPermissionsEnabled: boolean isMothershipBenchmarkEnabled: boolean + isMcpOauthClientMetadataDocumentEnabled: boolean isBillingEnabled: boolean isEmailVerificationEnabled: boolean isAuthDisabled: boolean @@ -69,6 +70,7 @@ const defaultEnvFlagsState: EnvFlagsMockState = { isStatusNoticePreviewEnabled: false, isCopilotToolPermissionsEnabled: false, isMothershipBenchmarkEnabled: false, + isMcpOauthClientMetadataDocumentEnabled: false, isBillingEnabled: false, isEmailVerificationEnabled: false, isAuthDisabled: false,