Skip to content

Commit 98e4ff7

Browse files
mzxchandrawaleedlatif1claude
authored
feat(mcp): register with OAuth client ID metadata documents (#10690)
* feat(mcp): register with OAuth client ID metadata documents Sim now serves an OAuth Client ID Metadata Document at /api/mcp/oauth/client-metadata and offers its URL as the client_id to MCP authorization servers that advertise client_id_metadata_document_supported, ahead of dynamic client registration, as the MCP authorization spec recommends. A pre-registered client ID and stored registrations still win. On by default for Sim Cloud, opt-in for self-hosted via MCP_OAUTH_CLIENT_METADATA_DOCUMENT_ENABLED. Canva is excluded: it rejects redirect URIs it has not allowlisted. * chore(helm): bump chart version for the MCP OAuth metadata document setting * refactor(mcp): derive OAuth client metadata paths from contracts and trim tests - Build the redirect and metadata URLs from the route contracts' paths - Shared HubSpot/Zoom client fingerprints use getMcpOauthRedirectUrl - Prove the HTTPS guard through the SDK flow on both providers - Drop duplicate tests and trim repeated comments Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Waleed Latif <walif6@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 50a3659 commit 98e4ff7

24 files changed

Lines changed: 490 additions & 15 deletions

File tree

‎apps/docs/content/docs/agents/mcp.mdx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ The registration uses `streamable-http` and defaults to a 30,000 ms connection t
2626

2727
**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.
2828

29+
### OAuth client registration
30+
31+
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:
32+
33+
1. The **Client ID** and **Client Secret** entered in **Advanced settings**.
34+
2. Sim's client ID metadata document, when the server supports these documents. It is a public page describing Sim, served at `<your Sim URL>/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.
35+
3. Automatic registration, when the server offers it.
36+
37+
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`.
38+
2939
### Secrets in URLs and headers
3040

3141
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
138148

139149
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).
140150

151+
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.
152+
141153
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.
142154

143155
## Related docs

‎apps/docs/content/docs/platform/self-hosting/environment-variables.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ Production Compose derives `DATABASE_URL` and `BETTER_AUTH_URL` on its service d
3939
| `AUTH_TRUSTED_PROXIES` | Comma-separated reverse-proxy IPs/CIDRs so the client IP cannot be forged through `X-Forwarded-For` |
4040
| `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. |
4141
| `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 `<NEXT_PUBLIC_APP_URL>/api/mcp` |
42+
| `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 `<NEXT_PUBLIC_APP_URL>/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) |
4243
| `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) |
4344
| `DATABASE_REPLICA_URL` | Read-replica connection string for log listing, audit logs, and dashboard aggregations. Falls back to the primary when unset |
4445

‎apps/sim/app/api/mcp/oauth/callback/route.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
283283
const preregistered = await timedStep('loadPreregisteredClient', 15_000, () =>
284284
loadPreregisteredClient(server.id)
285285
)
286-
const provider = new SimMcpOauthProvider({ row, preregistered })
286+
const provider = new SimMcpOauthProvider({ row, serverUrl, preregistered })
287287
let result: Awaited<ReturnType<typeof mcpAuthGuarded>>
288288
try {
289289
// An egress refusal of a URL the server named is the server's configuration, not a
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @vitest-environment node
3+
*/
4+
import { resetEnvFlagsMock, resetEnvMock, setEnv, setEnvFlags } from '@sim/testing'
5+
import { NextRequest } from 'next/server'
6+
import { afterEach, describe, expect, it } from 'vitest'
7+
import { mcpOauthClientMetadataDocumentSchema } from '@/lib/api/contracts/mcp'
8+
import { GET } from '@/app/api/mcp/oauth/client-metadata/route'
9+
10+
describe('GET /api/mcp/oauth/client-metadata', () => {
11+
afterEach(() => {
12+
resetEnvMock()
13+
resetEnvFlagsMock()
14+
})
15+
16+
it('serves the configured document whatever host the request names', async () => {
17+
setEnv({ NEXT_PUBLIC_APP_URL: 'https://sim.example.com' })
18+
19+
const response = await GET(
20+
new NextRequest('https://attacker.example/api/mcp/oauth/client-metadata', {
21+
headers: { host: 'attacker.example', 'x-forwarded-host': 'attacker.example' },
22+
}),
23+
undefined
24+
)
25+
26+
expect(response.status).toBe(200)
27+
expect(response.headers.get('content-type')).toContain('application/json')
28+
expect(response.headers.get('cache-control')).toBe('public, max-age=3600')
29+
const document = mcpOauthClientMetadataDocumentSchema.parse(await response.json())
30+
expect(document.client_id).toBe('https://sim.example.com/api/mcp/oauth/client-metadata')
31+
expect(document.redirect_uris).toEqual(['https://sim.example.com/api/mcp/oauth/callback'])
32+
})
33+
34+
it('keeps serving while the deployment does not present it, for grants already issued', async () => {
35+
setEnv({ NEXT_PUBLIC_APP_URL: 'https://sim.example.com' })
36+
setEnvFlags({ isMcpOauthClientMetadataDocumentEnabled: false })
37+
38+
const response = await GET(
39+
new NextRequest('https://sim.example.com/api/mcp/oauth/client-metadata'),
40+
undefined
41+
)
42+
43+
expect(response.status).toBe(200)
44+
})
45+
})
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { NextResponse } from 'next/server'
2+
import { getMcpOauthClientMetadataDocumentContract } from '@/lib/api/contracts/mcp'
3+
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
4+
import { buildMcpOauthClientMetadataDocument } from '@/lib/mcp/oauth/client-metadata'
5+
6+
export const dynamic = 'force-dynamic'
7+
8+
/** The document changes only with the deployment's configuration. */
9+
const CLIENT_METADATA_CACHE_SECONDS = 3600
10+
11+
const documentSchema = getMcpOauthClientMetadataDocumentContract.response.schema
12+
13+
/**
14+
* Sim's public OAuth Client ID Metadata Document, fetched by MCP authorization servers Sim presents
15+
* this URL to as its `client_id`. Served even while the setting is off: authorization servers fetch
16+
* it again on refresh, so grants already issued would otherwise be stranded.
17+
*/
18+
export const GET = withRouteHandler(() =>
19+
NextResponse.json(documentSchema.parse(buildMcpOauthClientMetadataDocument()), {
20+
headers: { 'Cache-Control': `public, max-age=${CLIENT_METADATA_CACHE_SECONDS}` },
21+
})
22+
)

‎apps/sim/app/api/mcp/oauth/start/route.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ export const GET = withRouteHandler(
169169
const preregistered = await timedStep('loadPreregisteredClient', DB_STEP_MS, () =>
170170
loadPreregisteredClient(server.id)
171171
)
172-
const provider = new SimMcpOauthProvider({ row, preregistered })
172+
const provider = new SimMcpOauthProvider({ row, serverUrl, preregistered })
173173

174174
// OAuth discovery + DCR through the guarded fetch, bounded so a transient stall fails
175175
// fast with a labeled log instead of hanging the popup. `McpOauthRedirectRequired` is

‎apps/sim/lib/api/contracts/mcp.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,37 @@ export const mcpOauthCallbackContract = defineRouteContract({
493493
response: { mode: 'text' },
494494
})
495495

496+
/**
497+
* Sim's OAuth Client ID Metadata Document. Sim is a public PKCE client, so it carries no secret or
498+
* key material, and `strict` keeps one from being added unnoticed. Both auth-method fields are sent:
499+
* MCP's profile and older servers read the singular, the current draft prefers the plural.
500+
*/
501+
export const mcpOauthClientMetadataDocumentSchema = z
502+
.object({
503+
client_id: z.string().url(),
504+
client_name: z.string().min(1),
505+
client_uri: z.string().url(),
506+
logo_uri: z.string().url(),
507+
tos_uri: z.string().url().optional(),
508+
policy_uri: z.string().url().optional(),
509+
redirect_uris: z.array(z.string().url()).min(1),
510+
grant_types: z.array(z.enum(['authorization_code', 'refresh_token'])).min(1),
511+
response_types: z.array(z.literal('code')).min(1),
512+
token_endpoint_auth_method: z.literal('none'),
513+
token_endpoint_auth_methods_supported: z.array(z.literal('none')).min(1),
514+
})
515+
.strict()
516+
export type McpOauthClientMetadataDocument = z.output<typeof mcpOauthClientMetadataDocumentSchema>
517+
518+
export const getMcpOauthClientMetadataDocumentContract = defineRouteContract({
519+
method: 'GET',
520+
path: '/api/mcp/oauth/client-metadata',
521+
response: {
522+
mode: 'json',
523+
schema: mcpOauthClientMetadataDocumentSchema,
524+
},
525+
})
526+
496527
export const getAllowedMcpDomainsContract = defineRouteContract({
497528
method: 'GET',
498529
path: '/api/settings/allowed-mcp-domains',

‎apps/sim/lib/core/config/env-flags.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,15 @@ export const isCopilotToolPermissionsEnabled = isTruthy(env.COPILOT_TOOL_PERMISS
120120
/** Deployment-only opt-in; authenticated resource permissions still apply. */
121121
export const isMothershipBenchmarkEnabled = isTruthy(env.MOTHERSHIP_BENCHMARK_ENABLED)
122122

123+
/**
124+
* Present Sim's Client ID Metadata Document URL as its `client_id` to MCP authorization servers
125+
* that support it, instead of registering dynamically. A server that cannot fetch the document
126+
* fails sign-in outright, with no fallback to registration, so this defaults on only for Sim Cloud;
127+
* self-hosted operators opt in once the app URL is publicly reachable.
128+
*/
129+
export const isMcpOauthClientMetadataDocumentEnabled =
130+
envBoolean(env.MCP_OAUTH_CLIENT_METADATA_DOCUMENT_ENABLED) ?? isHosted
131+
123132
/**
124133
* A server-only switch: `serverValue` on the server; in the browser, which never
125134
* sees server variables, the server's answer from the deployment-shape projection

‎apps/sim/lib/core/config/env.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,7 @@ export const env = createEnv({
301301
BLACKLISTED_PROVIDERS: z.string().optional(), // Comma-separated provider IDs to hide (e.g., "openai,anthropic")
302302
BLACKLISTED_MODELS: z.string().optional(), // Comma-separated model names/prefixes to hide (e.g., "gpt-4,claude-*")
303303
ALLOWED_MCP_DOMAINS: z.string().optional(), // Comma-separated domains for MCP servers (e.g., "internal.company.com,mcp.example.org"). Empty = all allowed.
304+
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
304305
ALLOWED_INTEGRATIONS: z.string().optional(), // Comma-separated block types to allow (e.g., "slack,github,agent"). Empty = all allowed.
305306
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.
306307

‎apps/sim/lib/credential-groups/__integration__/hubspot-mcp.integration.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,7 @@ describe.each(SHARED_CLIENTS)('$name shared member connector', (connector) => {
339339
const loadProvider = async () =>
340340
new SimMcpOauthProvider({
341341
row: await getOrCreateOauthRow({ mcpServerId: mcpServer.id, organizationId: org }),
342+
serverUrl: connector.url,
342343
preregistered: await loadPreregisteredClient(mcpServer.id),
343344
})
344345
const provider = await loadProvider()
@@ -406,6 +407,7 @@ describe.each(SHARED_CLIENTS)('$name shared member connector', (connector) => {
406407
const substitute = 'https://oauth.substitute.test'
407408
const provider = new SimMcpOauthProvider({
408409
row: await getOrCreateOauthRow({ mcpServerId: mcpServer.id, organizationId: org }),
410+
serverUrl: connector.url,
409411
preregistered: await loadPreregisteredClient(mcpServer.id),
410412
})
411413
if (phase === 'code exchange') await provider.saveCodeVerifier('fixture-verifier')

0 commit comments

Comments
 (0)