Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions apps/docs/content/docs/agents/mcp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<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.
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:
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<NEXT_PUBLIC_APP_URL>/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 `<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) |
| `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 |

Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/api/mcp/oauth/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReturnType<typeof mcpAuthGuarded>>
try {
// An egress refusal of a URL the server named is the server's configuration, not a
Expand Down
45 changes: 45 additions & 0 deletions apps/sim/app/api/mcp/oauth/client-metadata/route.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
22 changes: 22 additions & 0 deletions apps/sim/app/api/mcp/oauth/client-metadata/route.ts
Original file line number Diff line number Diff line change
@@ -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}` },
})
)
2 changes: 1 addition & 1 deletion apps/sim/app/api/mcp/oauth/start/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions apps/sim/lib/api/contracts/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof mcpOauthClientMetadataDocumentSchema>

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',
Expand Down
9 changes: 9 additions & 0 deletions apps/sim/lib/core/config/env-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions apps/sim/lib/core/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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')
Expand Down
2 changes: 2 additions & 0 deletions apps/sim/lib/credential-groups/mcp-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 2 additions & 0 deletions apps/sim/lib/credentials/managed-mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export interface ManagedMcpRuntimeCredential {
credentialId: string
mcpServerId: string
mcpServerName: string
mcpServerUrl: string
workspaceId: string
tokenVersion: string
tokens: OAuthTokens
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions apps/sim/lib/mcp/application/managed-auth-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
5 changes: 4 additions & 1 deletion apps/sim/lib/mcp/connection-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -181,6 +183,7 @@ export class McpConnectionManager {
credentialId: config.id,
initialProvider: new SimMcpOauthProvider({
row,
serverUrl,
preregistered: await loadPreregisteredClient(config.id),
}),
loadProvider: async () => {
Expand All @@ -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 })
},
}
}
Expand Down
Loading
Loading