AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat: MCP client OAuth2 (#15699)
Daniel Poon191c4b7538ec
diff --git a/brain/knowledge/connections-auth/app-connections.md b/brain/knowledge/connections-auth/app-connections.mdindex f05a164716d..4a0f49cd7a0 100644--- a/brain/knowledge/connections-auth/app-connections.md+++ b/brain/knowledge/connections-auth/app-connections.md@@ -31,6 +31,9 @@ Encrypted credential records (OAuth2 tokens, API keys, basic/custom auth, OIDC p- **A pasted service-account JSON is attacker-controlled config, and `token_uri` inside it is an SSRF vector.** A Google service-account key file carries its own `token_uri`/`auth_uri`, and `google-auth-library` (`GoogleAuth`, `JWT`) *honours* them — so `{ ...JSON.parse(raw) }` handed to `googleAuthOptions.credentials` lets whoever pasted the file redirect the OAuth token exchange to any host, link-local metadata included, behind a valid-looking `type: service_account`. Forward only the fields you use (`client_email`, `private_key`, `project_id` if you check it); never spread the parsed object. This bit the Vertex AI provider in review, and **`packages/pieces/community/google-vertexai/.../common.ts` still does `{ ...raw, private_key }`** — worse there than in a provider, because a piece connection needs only connection-write, not platform admin. The same `new GoogleAuth`/`new JWT` shape recurs across the google-* pieces, so grep before assuming one is narrow. Note `.claude/rules/safe-http.md` does **not** catch this: the request is made inside the auth library, never through `safeHttp.axios`, so the rule's "admin config reaching outbound HTTP" clause has to be applied by hand.- **Never hand a Google `OAuth2Client` the whole OAuth2 connection value. Pass `setCredentials({ access_token })` only.** The client is built with no client ID or secret (`setCredentials` ignores any `client_id` in the value), but the value carries a `refresh_token` and no `expiry_date`. In `google-auth-library` 10.x that keeps the retry-on-401/403 path open: the library tries its own refresh, sends only `{refresh_token, grant_type}`, and Google's `400 invalid_request` "Could not determine client ID from request." replaces the real 401/403. This hits every OAuth2 flavour, and the library refresh gains nothing, because the server refreshes 15 minutes before expiry (`oauth2Util.isExpired`). Every Google piece's `createGoogleClient` follows this, and each has `test/oauth2-client.test.ts` asserting it; a new Google piece should copy that test. #11529 fixed only Slides, and #15648 put the bug back, which is why each piece now has the test. Upstream report: #16268.- **The two live OAuth2 redirect pages disagree on percent-decoding, so `getCode` decodes conditionally. Do not collapse it back to an unconditional decode, in either direction.** `redirect.tsx` decodes once via `URLSearchParams`, while **`https://secrets.activepieces.com/redirect` - the page every `CLOUD_OAUTH2` connect uses, and which does not live in this repo - posts the code raw, zero decodes** (verified 2026-09-08: `?code=k1%2Fk2` posts `'k1%2Fk2'`). `getCode` decodes only when `oauth2Type === AppConnectionType.CLOUD_OAUTH2` - the same condition `oauth2Utils.resolveRedirectUrl` uses to pick the secrets page - falling back to the raw value if `decodeURIComponent` throws. **The two live in separate files and nothing ties them together, so a third redirect page must be added to both**: pick its URL in `resolveRedirectUrl` and state its decode contract in `getCode`, or the pair drifts and you are back at this bug. The Mustache page in `app.ts` is a third sender on paper only: `setupApp` mounts under the `/api` prefix, so it serves at **`/api/redirect`**, nothing in the repo points at it, and a bare `/redirect` always falls through to the SPA. Deleting the decode outright was tried in #14879 and reverted 21 hours later in #14926, because it broke every managed OAuth app, self-hosted as much as Cloud: `CLOUD_OAUTH2` means "managed app", not "on Cloud", and `platform.cloudAuthEnabled` defaults to true everywhere. It also fired much more readily than the bug it fixed, since a raw posted code breaks on any `/`, `+` or `=` while the double decode needs a literal `%`. Grepping this repo for the senders is not enough; the cloud one is invisible here - and neither are tests, by themselves: #14879 shipped three of them, CI does run web tests (`ci.yml`, `--filter=web`), and they passed, because all three modelled `redirect.tsx`'s contract only. `oauth2-authorization-code-decode.test.ts` now covers both contracts, and fails in both directions. See decision *The browser normalises OAuth2 authorization codes, because the cloud redirect contract is frozen*.+- **An OAuth2 connection with no `authorization_method` sends its client credentials in the form body (`client_secret_post`) on both claim and refresh.** `credentialsOauth2Service` defaults to `OAuth2AuthorizationMethod.BODY`, and the value is set either from the piece's `auth.authorizationMethod` or by discovery. Any flow that registers its own client must carry back the `token_endpoint_auth_method` the server registered. Otherwise strict servers (Keycloak, Hydra, Spring AS) reject the token call with `invalid_client`. Dynamic Client Registration ([000039](../decisions/000039-a-discoverable-oauth2-connection-registers-its-own-client.md)) does this: `oauth2Discovery` maps `client_secret_basic` → `HEADER` and `client_secret_post` → `BODY`, then returns the result as `discovered.authorization_method`. Server code imports `OAuth2AuthorizationMethod` from `@activepieces/pieces-framework`. The copy in `@activepieces/shared` is not exported from its index, so importing it from there gives `undefined` at runtime.++- **Adding an optional field to an `AppConnectionValue` shape (e.g. `BaseOAuth2ConnectionValue`) needs no migration and is safe in both rolling-deploy directions, but confirm each of these rather than assuming it** (checked in full when RFC 8707's `resource` was added, [000039](../decisions/000039-a-discoverable-oauth2-connection-registers-its-own-client.md)): (1) `value` is one `EncryptedObject` column (`AppConnectionSchema.value: EncryptedObject`) — an encrypted JSON blob, not per-field DB columns, so a new key is purely additive at the application layer. (2) The upsert/response zod schemas here don't use `.strict()`, so an old server silently drops a field a newer client sends, and a new server sees `undefined` for a field an old client never sends — neither direction throws. (3) `removeRefreshTokenAndClientSecret` redacts via spread-and-overwrite (`{ ...connection.value, refresh_token: '(REDACTED)' }`), not an explicit field allowlist, so a new field survives redaction automatically — check this specifically if you ever rewrite it as an allowlist. (4) `removeSensitiveData` strips the **entire** `value` object as one unit before an API response, so a new field gets the same blanket treatment as everything else in `value` — no per-field decision needed. (5) `BaseOAuth2ConnectionValue` is defined **twice**, independently, in `packages/core/piece-types` (piece-facing `context.auth`) and `packages/core/shared` (what the server actually persists) — they've already diverged (`authorization_method` exists only on the `shared` one), and the two packages can't share the type (`core-piece-types` may only import `core-utils`). Check which one a given call site actually resolves (`grep -rn 'export type BaseOAuth2ConnectionValue' packages/core/`) before editing — the wrong one type-checks in isolation and only fails once the real call site's package rebuilds against it.### Key filesEntry point: `appConnectionService`, exported from the app-connection service and reached through `appConnectionModule`, registered in `packages/server/api/src/app/app.ts`.diff --git a/brain/knowledge/decisions/000039-a-discoverable-oauth2-connection-registers-its-own-client.md b/brain/knowledge/decisions/000039-a-discoverable-oauth2-connection-registers-its-own-client.mdnew file mode 100644index 00000000000..f40fe04011f--- /dev/null+++ b/brain/knowledge/decisions/000039-a-discoverable-oauth2-connection-registers-its-own-client.md@@ -0,0 +1,79 @@+---+icon: 🔐+status: accepted+---++# A discoverable OAuth2 connection registers its own client++## Decision++`PieceAuth.OAuth2` takes an optional `discovery` descriptor naming which of its props hold the+server URL and which receive the discovered endpoints. When it is set, the **existing**+`POST /v1/app-connections/oauth2/authorization-url` endpoint — not a new route — reads the server's+RFC 9728 → RFC 8414 `.well-known` metadata, registers a client via RFC 7591 Dynamic Client+Registration, merges the results into `props`, and returns them to the connect dialog as a+`discovered` payload. The dialog writes them into the form and then follows the unchanged+popup → upsert path. v1 registers a **confidential** client and rejects servers that issue public+(secret-less) ones.++## Context++MCP servers authenticate over OAuth2 but typically have no developer console: the endpoints are+published as metadata and credentials are self-registered. Asking a user for Authorize URL, Token+URL, Scopes, Client ID and Client Secret asked for five values they mostly cannot obtain. The first+attempt shipped those as a piece action whose output the user pasted into the connection form, which+worked but read as a workaround.++## Why++Claim derives the token URL from the submitted `props` via the existing `'{tokenUrl}'` template, and+refresh reads `token_url`/`client_id`/`client_secret` off the **stored** connection value without+ever consulting piece metadata again. So discovery only has to run once, and routing its results+through `props` means the token exchange and refresh code — the delicate part — is untouched.++A dedicated `/oauth2/discover` route was rejected: `buildAuthorizationUrl` already needs a resolved+`authUrl` and a client id, so discovering anywhere else means asserting placeholders against props+that are still empty. Folding it in also saved a request DTO, an API client method and an error path.+A new `AppConnectionType` was rejected outright — every claim/refresh/redaction switch would grow a+case for something that is an ordinary OAuth2 connection once established.++Public clients were deferred rather than supported: the claim path does `body.client_secret =+request.clientSecret!` then `String(value)`, so a secret-less client literally posts+`client_secret=undefined`. Real support means four coordinated touchpoints (the zod `min(1)`, the+claim body, the claim Basic header, and refresh's `resolveString({ throwOnFailure: true })`) in+exactly the code this design set out not to touch.++## Consequences++Fully backward compatible, confirmed by checking every gate rather than assuming: `discovery` is+`undefined` for every piece except `mcp-client` (grepped `packages/pieces/community/*` for it), so+`discoverOAuth2Client` returns `undefined` on its first line and `buildAuthorizationUrl` falls+through to the original code unchanged; every web-side branch (`isClientSecretValid`, `isPropsValid`,+hiding Client ID/Secret, `hiddenPropNames`) is gated on the same flag and collapses to its original+condition too. The one shared-code change, `assertPlaceholdersResolved` skipping `required: false`+props, doesn't even apply to `http-oauth2`'s identical `'{authUrl}'` template — its `scopes` prop is+`required: true`. Already-claimed connections on any piece are entirely unaffected: refresh reads+`token_url`/`client_id`/`client_secret`/`props` off the *stored* value, and that code path was never+touched.++`http-oauth2` has the identical manual-entry problem and can adopt the same descriptor. Reconnecting+registers a fresh client and orphans the previous one on the authorization server.++RFC 8707 `resource` was initially sent on the authorize request only; a later pass threaded it+through the token and refresh requests too (`OAuth2RequestBody`, both `credentials-oauth2-service.ts`+paths, persisted on the connection value). This wasn't a net-new class of gap — `pieceAuth.extra`+(a static per-piece query-param map) already had the identical limitation: spread into+`buildAuthorizationUrl`'s query params, never referenced in `credentials-oauth2-service.ts`. No+piece before this one ever needed a value on both legs, because no existing piece's authorization+server issues tokens for more than one resource server — the gap was real in shape but dormant until+an AS-multiplexing case (MCP servers sharing one Auth0/Okta tenant) actually exercised it. The fix+threads `resource` through `commonOAuth2ValueProps`, shared by all three OAuth2 connection types+(`OAUTH2`, `CLOUD_OAUTH2`, `PLATFORM_OAUTH2`) for consistency with how `props`/`code_challenge`/+`scope` are already uniform there — but only the plain `OAUTH2` branch ever populates it in practice,+since `CLOUD_OAUTH2`/`PLATFORM_OAUTH2` use a platform-admin-configured predefined app, and no piece+today has both a predefined app and `discovery` set. The other two call sites are consistent, not+currently exercised — narrowing `resource` to just `UpsertOAuth2Request` was considered and rejected+in favor of matching the existing uniform-field pattern.++Self-hosters pointing at an internal MCP server hit+`safeHttp`'s SSRF filter and must set `AP_SSRF_ALLOW_LIST`.diff --git a/bun.lock b/bun.lockindex 9801f96d016..44e3cc2f705 100644--- a/bun.lock+++ b/bun.lock@@ -1,6 +1,5 @@{"lockfileVersion": 1,- "configVersion": 0,"workspaces": {"": {"name": "activepieces",@@ -5699,7 +5698,7 @@},"packages/pieces/community/mcp-client": {"name": "@activepieces/piece-mcp-client",- "version": "0.0.6",+ "version": "0.0.7","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -10877,7 +10876,7 @@},"packages/pieces/framework": {"name": "@activepieces/pieces-framework",- "version": "0.40.0",+ "version": "0.41.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/core/shared/src/lib/automation/app-connection/app-connection.ts b/packages/core/shared/src/lib/automation/app-connection/app-connection.tsindex 5a1fef7f602..cbc21cc7a21 100755--- a/packages/core/shared/src/lib/automation/app-connection/app-connection.ts+++ b/packages/core/shared/src/lib/automation/app-connection/app-connection.ts@@ -52,6 +52,7 @@ export type BaseOAuth2ConnectionValue = {data: Record<string, any>props?: Record<string, unknown>grant_type?: OAuth2GrantType+ resource?: string}export type CustomAuthConnectionValue<T extends Record<string, unknown> = Record<string, unknown>> = {diff --git a/packages/core/shared/src/lib/automation/app-connection/dto/upsert-app-connection-request.ts b/packages/core/shared/src/lib/automation/app-connection/dto/upsert-app-connection-request.tsindex 7dc9ae1474e..89fb4f41268 100644--- a/packages/core/shared/src/lib/automation/app-connection/dto/upsert-app-connection-request.ts+++ b/packages/core/shared/src/lib/automation/app-connection/dto/upsert-app-connection-request.ts@@ -59,7 +59,8 @@ const commonOAuth2ValueProps = {code: z.string().min(1),code_challenge: z.string().optional(),scope: z.string(),- authorization_method: z.nativeEnum(OAuth2AuthorizationMethod).optional(),+ authorization_method: z.enum(OAuth2AuthorizationMethod).optional(),+ resource: z.string().optional(),}export const UpsertPlatformOAuth2Request = z.object({...commonAuthProps,@@ -99,9 +100,9 @@ export const UpsertOAuth2Request = z.object({value: z.object({...commonOAuth2ValueProps,client_secret: z.string().min(1),- grant_type: z.nativeEnum(OAuth2GrantType).optional(),+ grant_type: z.enum(OAuth2GrantType).optional(),props: z.record(z.string(), z.any()).optional(),- authorization_method: z.nativeEnum(OAuth2AuthorizationMethod).optional(),+ authorization_method: z.enum(OAuth2AuthorizationMethod).optional(),redirect_url: z.string().min(1),type: z.literal(AppConnectionType.OAUTH2),}),@@ -189,6 +190,13 @@ export type GetOAuth2AuthorizationUrlRequestBody = z.infer<typeof GetOAuth2Authoexport const GetOAuth2AuthorizationUrlResponse = z.object({authorizationUrl: z.string(),codeVerifier: z.string().optional(),+ discovered: z.object({+ props: z.record(z.string(), z.unknown()),+ client_id: z.string(),+ client_secret: z.string(),+ resource: z.string(),+ authorization_method: z.enum(OAuth2AuthorizationMethod),+ }).optional(),})export type GetOAuth2AuthorizationUrlResponse = z.infer<typeof GetOAuth2AuthorizationUrlResponse>diff --git a/packages/pieces/community/mcp-client/package.json b/packages/pieces/community/mcp-client/package.jsonindex 2619f0b33d7..9b150208162 100644--- a/packages/pieces/community/mcp-client/package.json+++ b/packages/pieces/community/mcp-client/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-mcp-client",- "version": "0.0.6",+ "version": "0.0.7","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",diff --git a/packages/pieces/community/mcp-client/src/i18n/translation.json b/packages/pieces/community/mcp-client/src/i18n/translation.jsonindex 97f2247a989..d5e85251cda 100644--- a/packages/pieces/community/mcp-client/src/i18n/translation.json+++ b/packages/pieces/community/mcp-client/src/i18n/translation.json@@ -1,5 +1,6 @@{"Call tools on an external MCP server deterministically, without an LLM.": "Call tools on an external MCP server deterministically, without an LLM.",+ "API Key / Headers": "API Key / Headers","Server URL": "Server URL","Transport": "Transport","Authentication": "Authentication",@@ -7,6 +8,10 @@"API Key": "API Key","API Key Header Name": "API Key Header Name","Custom Headers": "Custom Headers",+ "OAuth2": "OAuth2",+ "Authorize URL": "Authorize URL",+ "Token URL": "Token URL",+ "Scopes (whitespace separated)": "Scopes (whitespace separated)","The MCP server endpoint, e.g. https://example.com/mcp": "The MCP server endpoint, e.g. https://example.com/mcp","Used when Authentication is \"Bearer Token\".": "Used when Authentication is \"Bearer Token\".","Used when Authentication is \"API Key\".": "Used when Authentication is \"API Key\".",@@ -21,5 +26,9 @@"Invoke a specific tool on an external MCP server and return its result.": "Invoke a specific tool on an external MCP server and return its result.","Tool": "Tool","Tool Inputs": "Tool Inputs",- "The tool to call. The list is loaded from the MCP server.": "The tool to call. The list is loaded from the MCP server."-}\ No newline at end of file+ "The tool to call. The list is loaded from the MCP server.": "The tool to call. The list is loaded from the MCP server.",+ "Connect to an external MCP server that authenticates via OAuth2.\n\nEnter the server URL and click Connect — the OAuth2 endpoints are read from the server's own metadata and a client is registered automatically.\n\nIf the server doesn't publish that metadata, or doesn't support Dynamic Client Registration, the fields to fill in by hand appear instead.": "Connect to an external MCP server that authenticates via OAuth2.\n\nEnter the server URL and click Connect — the OAuth2 endpoints are read from the server's own metadata and a client is registered automatically.\n\nIf the server doesn't publish that metadata, or doesn't support Dynamic Client Registration, the fields to fill in by hand appear instead.",+ "The authorization server's `authorization_endpoint`.": "The authorization server's `authorization_endpoint`.",+ "The authorization server's `token_endpoint`.": "The authorization server's `token_endpoint`.",+ "The authorization server's `scopes_supported`, if it requires specific scopes.": "The authorization server's `scopes_supported`, if it requires specific scopes."+}diff --git a/packages/pieces/community/mcp-client/src/index.ts b/packages/pieces/community/mcp-client/src/index.tsindex 9d6ef88560b..892b0856714 100644--- a/packages/pieces/community/mcp-client/src/index.ts+++ b/packages/pieces/community/mcp-client/src/index.ts@@ -1,12 +1,12 @@import { createPiece, PieceCategory } from '@activepieces/pieces-framework';import { callTool } from './lib/actions/call-tool';-import { mcpClientAuth } from './lib/auth';+import { mcpAuth } from './lib/auth';export const mcpClient = createPiece({displayName: 'MCP Client',description: 'Call tools on an external MCP server deterministically, without an LLM.',- auth: mcpClientAuth,- minimumSupportedRelease: '0.86.3',+ auth: mcpAuth,+ minimumSupportedRelease: '0.92.4',logoUrl: 'https://cdn.activepieces.com/pieces/new-core/mcp.svg',authors: ['sanket-a11y'],categories: [PieceCategory.ARTIFICIAL_INTELLIGENCE, PieceCategory.UNIVERSAL_AI],diff --git a/packages/pieces/community/mcp-client/src/lib/actions/call-tool.ts b/packages/pieces/community/mcp-client/src/lib/actions/call-tool.tsindex 6e0119c3e5e..d7b50863aab 100644--- a/packages/pieces/community/mcp-client/src/lib/actions/call-tool.ts+++ b/packages/pieces/community/mcp-client/src/lib/actions/call-tool.ts@@ -4,11 +4,11 @@ import {InputPropertyMap,Property,} from '@activepieces/pieces-framework';-import { mcpClientAuth } from '../auth';+import { mcpAuth } from '../auth';import { mcpClient, McpToolInfo } from '../common/client';export const callTool = createAction({- auth: mcpClientAuth,+ auth: mcpAuth,name: 'call-tool',classification: 'WRITE',displayName: 'Call Tool',@@ -16,8 +16,8 @@ export const callTool = createAction({audience: 'both',aiMetadata: { description: 'Invokes one named tool on the connected external MCP server with arguments matching that tool\'s own input schema; the tool list and its input fields are discovered live from the server, so what is callable varies by which MCP server the connection points at. Use it to call a third-party MCP tool deterministically as a flow step instead of delegating the choice to an LLM. Requires the exact tool name the server exposes, and it fails when the server flags the result as an error. Not idempotent: the effect depends on the remote tool invoked, which may create or mutate data on every call.', idempotent: false },props: {- tool: Property.Dropdown<string, true, typeof mcpClientAuth>({- auth: mcpClientAuth,+ tool: Property.Dropdown<string, true, typeof mcpAuth>({+ auth: mcpAuth,displayName: 'Tool',description: 'The tool to call. The list is loaded from the MCP server.',required: true,@@ -27,7 +27,7 @@ export const callTool = createAction({return { disabled: true, placeholder: 'Connect an MCP server first', options: [] };}try {- const tools = await mcpClient.listTools(auth.props);+ const tools = await mcpClient.listTools(auth);return { options: tools.map((tool) => ({ label: tool.name, value: tool.name })) };} catch (error) {return {@@ -39,7 +39,7 @@ export const callTool = createAction({},}),args: Property.DynamicProperties({- auth: mcpClientAuth,+ auth: mcpAuth,displayName: 'Tool Inputs',required: false,refreshers: ['tool'],@@ -48,7 +48,7 @@ export const callTool = createAction({return {};}try {- const tools = await mcpClient.listTools(auth.props);+ const tools = await mcpClient.listTools(auth);const selected = tools.find((candidate) => candidate.name === tool);return schemaToProps(selected?.inputSchema);} catch {@@ -59,7 +59,7 @@ export const callTool = createAction({},async run(context) {const { tool, args } = context.propsValue;- const client = await mcpClient.connect(context.auth.props);+ const client = await mcpClient.connect(context.auth);try {const result = await client.callTool({ name: tool, arguments: args ?? {} });if (isErrorResult(result)) {diff --git a/packages/pieces/community/mcp-client/src/lib/auth.ts b/packages/pieces/community/mcp-client/src/lib/auth.tsindex 3a31f943195..133e30af26e 100644--- a/packages/pieces/community/mcp-client/src/lib/auth.ts+++ b/packages/pieces/community/mcp-client/src/lib/auth.ts@@ -1,10 +1,13 @@-import { McpAuthType, McpProtocol, PieceAuth, Property } from '@activepieces/pieces-framework';+import {+ McpAuthType,+ McpProtocol,+ OAuth2GrantType,+ PieceAuth,+ Property,+} from '@activepieces/pieces-framework';-export const mcpClientAuth = PieceAuth.CustomAuth({- description:- 'Connect to an external MCP server. Fill only the fields relevant to the chosen authentication method.',- required: true,- props: {+function serverConnectionProps() {+ return {serverUrl: Property.ShortText({displayName: 'Server URL',description: 'The MCP server endpoint, e.g. https://example.com/mcp',@@ -22,6 +25,16 @@ export const mcpClientAuth = PieceAuth.CustomAuth({],},}),+ };+}++export const mcpClientAuth = PieceAuth.CustomAuth({+ displayName: 'API Key / Headers',+ description:+ 'Connect to an external MCP server. Fill only the fields relevant to the chosen authentication method.',+ required: true,+ props: {+ ...serverConnectionProps(),authType: Property.StaticDropdown({displayName: 'Authentication',required: true,@@ -47,7 +60,8 @@ export const mcpClientAuth = PieceAuth.CustomAuth({}),apiKeyHeader: Property.ShortText({displayName: 'API Key Header Name',- description: 'Header carrying the API key, e.g. "x-api-key". Used when Authentication is "API Key".',+ description:+ 'Header carrying the API key, e.g. "x-api-key". Used when Authentication is "API Key".',required: false,}),headers: Property.LongText({@@ -58,3 +72,46 @@ export const mcpClientAuth = PieceAuth.CustomAuth({}),},});++export const mcpOAuth2Auth = PieceAuth.OAuth2({+ displayName: 'OAuth2',+ description: `Connect to an external MCP server that authenticates via OAuth2.++Enter the server URL and click Connect — the OAuth2 endpoints are read from the server's own metadata and a client is registered automatically.++If the server doesn't publish that metadata, or doesn't support Dynamic Client Registration, the fields to fill in by hand appear instead.`,+ authUrl: '{authUrl}',+ tokenUrl: '{tokenUrl}',+ required: true,+ scope: '{scopes}'.split(' '),+ grantType: OAuth2GrantType.AUTHORIZATION_CODE,+ pkce: true,+ pkceMethod: 'S256',+ discovery: {+ serverUrlProp: 'serverUrl',+ authUrlProp: 'authUrl',+ tokenUrlProp: 'tokenUrl',+ scopesProp: 'scopes',+ },+ props: {+ ...serverConnectionProps(),+ authUrl: Property.ShortText({+ displayName: 'Authorize URL',+ required: true,+ description: "The authorization server's `authorization_endpoint`.",+ }),+ tokenUrl: Property.ShortText({+ displayName: 'Token URL',+ required: true,+ description: "The authorization server's `token_endpoint`.",+ }),+ scopes: Property.ShortText({+ displayName: 'Scopes (whitespace separated)',+ required: false,+ description:+ "The authorization server's `scopes_supported`, if it requires specific scopes.",+ }),+ },+});++export const mcpAuth = [mcpClientAuth, mcpOAuth2Auth];diff --git a/packages/pieces/community/mcp-client/src/lib/common/client.ts b/packages/pieces/community/mcp-client/src/lib/common/client.tsindex c941504636d..c3345d668b7 100644--- a/packages/pieces/community/mcp-client/src/lib/common/client.ts+++ b/packages/pieces/community/mcp-client/src/lib/common/client.ts@@ -1,23 +1,25 @@import {+ AppConnectionType,+ AppConnectionValueForAuthProperty,buildAuthHeaders,McpAuthConfig,McpAuthType,McpProtocol,- PiecePropValueSchema,} from '@activepieces/pieces-framework';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';-import { mcpClientAuth } from '../auth';+import { mcpAuth } from '../auth';async function connect(auth: McpClientAuthValue): Promise<Client> {const headers = buildAuthHeaders(toAuthConfig(auth));- const url = new URL(auth.serverUrl);+ const { serverUrl, protocol } = resolveServerConfig(auth);+ const url = new URL(serverUrl);// ponytail: Streamable HTTP transport also serves plain-JSON ("HTTP") servers,// so both HTTP variants share it; only legacy SSE needs its own transport.const transport =- auth.protocol === McpProtocol.SSE+ protocol === McpProtocol.SSE? new SSEClientTransport(url, { requestInit: { headers } }): new StreamableHTTPClientTransport(url, { requestInit: { headers } });@@ -37,22 +39,42 @@ async function listTools(auth: McpClientAuthValue): Promise<McpToolInfo[]> {}function toAuthConfig(auth: McpClientAuthValue): McpAuthConfig {- switch (auth.authType) {+ if (auth.type === AppConnectionType.OAUTH2) {+ return { type: McpAuthType.ACCESS_TOKEN, accessToken: auth.access_token };+ }+ switch (auth.props.authType) {case McpAuthType.ACCESS_TOKEN:- return { type: McpAuthType.ACCESS_TOKEN, accessToken: auth.accessToken ?? '' };+ return { type: McpAuthType.ACCESS_TOKEN, accessToken: auth.props.accessToken ?? '' };case McpAuthType.API_KEY:return {type: McpAuthType.API_KEY,- apiKey: auth.apiKey ?? '',- apiKeyHeader: auth.apiKeyHeader ?? '',+ apiKey: auth.props.apiKey ?? '',+ apiKeyHeader: auth.props.apiKeyHeader ?? '',};case McpAuthType.HEADERS:- return { type: McpAuthType.HEADERS, headers: parseHeaders(auth.headers) };+ return { type: McpAuthType.HEADERS, headers: parseHeaders(auth.props.headers) };default:return { type: McpAuthType.NONE };}}+function resolveServerConfig(auth: McpClientAuthValue): { serverUrl: string; protocol: McpProtocol } {+ if (auth.type !== AppConnectionType.OAUTH2) {+ return { serverUrl: auth.props.serverUrl, protocol: auth.props.protocol };+ }+ // The OAuth2 connection value's own `props` is framework-typed as an untyped bag+ // (`BaseOAuth2ConnectionValue.props?: Record<string, unknown>`), so narrow by hand.+ const serverUrl = auth.props?.['serverUrl'];+ const protocol = auth.props?.['protocol'];+ if (typeof serverUrl !== 'string') {+ throw new Error('OAuth2 connection is missing the MCP Server URL.');+ }+ return {+ serverUrl,+ protocol: protocol === McpProtocol.SSE || protocol === McpProtocol.SIMPLE_HTTP ? protocol : McpProtocol.STREAMABLE_HTTP,+ };+}+function parseHeaders(raw: string | undefined): Record<string, string> {if (!raw || raw.trim().length === 0) {return {};@@ -73,5 +95,5 @@ function parseHeaders(raw: string | undefined): Record<string, string> {export const mcpClient = { connect, listTools };-export type McpClientAuthValue = PiecePropValueSchema<typeof mcpClientAuth>;+export type McpClientAuthValue = AppConnectionValueForAuthProperty<typeof mcpAuth>;export type McpToolInfo = Awaited<ReturnType<Client['listTools']>>['tools'][number];diff --git a/packages/pieces/framework/package.json b/packages/pieces/framework/package.jsonindex 386e8feec59..7c363976881 100644--- a/packages/pieces/framework/package.json+++ b/packages/pieces/framework/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/pieces-framework",- "version": "0.40.0",+ "version": "0.41.0","type": "commonjs","main": "./dist/src/index.js","types": "./dist/src/index.d.ts",diff --git a/packages/pieces/framework/src/lib/property/authentication/oauth2-prop.ts b/packages/pieces/framework/src/lib/property/authentication/oauth2-prop.tsindex 3c5246e5c86..186292b39aa 100644--- a/packages/pieces/framework/src/lib/property/authentication/oauth2-prop.ts+++ b/packages/pieces/framework/src/lib/property/authentication/oauth2-prop.ts@@ -35,6 +35,20 @@ export type OAuth2Props = {type OAuthPropsValue<T extends OAuth2Props> = StaticPropsValue<T>;+export const OAuth2Discovery = z.object({+ serverUrlProp: z.string(),+ authUrlProp: z.string(),+ tokenUrlProp: z.string(),+ scopesProp: z.optional(z.string()),+})++export type OAuth2Discovery = {+ serverUrlProp: string+ authUrlProp: string+ tokenUrlProp: string+ scopesProp?: string+}+const OAuth2ExtraProps = z.object({props: z.optional(z.record(z.string(), OAuthProp)),authUrl: z.string(),@@ -46,6 +60,7 @@ const OAuth2ExtraProps = z.object({authorizationMethod: z.optional(z.enum(OAuth2AuthorizationMethod)),grantType: z.optional(z.union([z.enum(OAuth2GrantType), z.literal(BOTH_CLIENT_CREDENTIALS_AND_AUTHORIZATION_CODE)])),extra: z.optional(z.record(z.string(), z.string())),+ discovery: z.optional(OAuth2Discovery),})type OAuth2ExtraProps = {@@ -59,6 +74,7 @@ type OAuth2ExtraProps = {authorizationMethod?: OAuth2AuthorizationMethodgrantType?: OAuth2GrantType | typeof BOTH_CLIENT_CREDENTIALS_AND_AUTHORIZATION_CODEextra?: Record<string, string>,+ discovery?: OAuth2Discovery}export const OAuth2PropertyValue = z.object({diff --git a/packages/pieces/framework/src/lib/property/index.ts b/packages/pieces/framework/src/lib/property/index.tsindex 397d60c1b80..391f1dd502a 100644--- a/packages/pieces/framework/src/lib/property/index.ts+++ b/packages/pieces/framework/src/lib/property/index.ts@@ -29,6 +29,7 @@ export { NumberProperty } from './input/number-property';export { ObjectProperty } from './input/object-property';export { OAuth2Props } from './authentication/oauth2-prop';export { OAuth2AuthorizationMethod } from './authentication/oauth2-prop';+export { OAuth2Discovery } from './authentication/oauth2-prop';export { BasicAuthPropertyValue } from './authentication/basic-auth-prop';export { StaticMultiSelectDropdownProperty } from './input/dropdown/static-dropdown';export { StaticDropdownProperty } from './input/dropdown/static-dropdown';diff --git a/packages/server/api/src/app/app-connection/app-connection-service/app-connection-service.ts b/packages/server/api/src/app/app-connection/app-connection-service/app-connection-service.tsindex 22c0338ab39..485e694b694 100644--- a/packages/server/api/src/app/app-connection/app-connection-service/app-connection-service.ts+++ b/packages/server/api/src/app/app-connection/app-connection-service/app-connection-service.ts@@ -712,6 +712,7 @@ const validateConnectionValue = async (authorizationMethod: value.authorization_method,codeVerifier: value.code_challenge,redirectUrl: value.redirect_url,+ resource: value.resource,},})}@@ -734,6 +735,7 @@ const validateConnectionValue = async (clientId: value.client_id,authorizationMethod: value.authorization_method,codeVerifier: value.code_challenge,+ resource: value.resource,},})}@@ -760,6 +762,7 @@ const validateConnectionValue = async (authorizationMethod: value.authorization_method,codeVerifier: value.code_challenge,scope: value.scope,+ resource: value.resource,},})await engineValidateAuth({diff --git a/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-discovery.ts b/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-discovery.tsnew file mode 100644index 00000000000..32f54831f35--- /dev/null+++ b/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-discovery.ts@@ -0,0 +1,189 @@+import { ActivepiecesError, ErrorCode, isNil, tryCatch, tryCatchSync } from '@activepieces/core-utils'+import { OAuth2AuthorizationMethod } from '@activepieces/pieces-framework'+import { safeHttp } from '@activepieces/server-utils'++const REQUEST_TIMEOUT_MS = 10_000++async function discoverAndRegister({ serverUrl, redirectUrl }: DiscoverAndRegisterParams): Promise<DiscoveredOAuth2Client> {+ const authorizationServer = await resolveAuthorizationServer(serverUrl)+ const metadata = await fetchAuthorizationServerMetadata(authorizationServer)++ if (isNil(metadata.registration_endpoint)) {+ throw invalidConnection(`${authorizationServer} does not support Dynamic Client Registration (no registration_endpoint in its metadata). Provide a Client ID and Client Secret from the server's own documentation instead.`)+ }++ const requestedAuthMethod = pickTokenEndpointAuthMethod(metadata.token_endpoint_auth_methods_supported)+ const client = await registerClient({+ registrationEndpoint: metadata.registration_endpoint,+ redirectUrl,+ scope: (metadata.scopes_supported ?? []).join(' '),+ tokenEndpointAuthMethod: requestedAuthMethod,+ })++ if (isNil(client.client_secret) || client.client_secret.length === 0) {+ throw invalidConnection(`${authorizationServer} issues public OAuth2 clients (no client secret), which is not supported yet. Provide a Client ID and Client Secret manually instead.`)+ }++ const registeredAuthMethod = client.token_endpoint_auth_method ?? requestedAuthMethod+ const authorizationMethod = TOKEN_ENDPOINT_AUTH_METHODS[registeredAuthMethod]+ if (isNil(authorizationMethod)) {+ throw invalidConnection(`${authorizationServer} registered the client with token_endpoint_auth_method "${registeredAuthMethod}", which is not supported. Provide a Client ID and Client Secret manually instead.`)+ }++ const resource = canonicalResourceUri(serverUrl)+ return {+ authUrl: withResourceIndicator({ authorizationEndpoint: metadata.authorization_endpoint, resource }),+ tokenUrl: metadata.token_endpoint,+ scopes: (metadata.scopes_supported ?? []).join(' '),+ clientId: client.client_id,+ clientSecret: client.client_secret,+ resource,+ authorizationMethod,+ }+}++function pickTokenEndpointAuthMethod(supported: string[] | undefined): TokenEndpointAuthMethod {+ const methods = supported ?? ['client_secret_basic']+ if (methods.includes('client_secret_basic')) {+ return 'client_secret_basic'+ }+ if (methods.includes('client_secret_post')) {+ return 'client_secret_post'+ }+ return 'client_secret_basic'+}++// An MCP server that skips RFC 9728 is its own authorization server.+async function resolveAuthorizationServer(serverUrl: string): Promise<string> {+ const url = parseUrl(serverUrl)+ const resourcePath = url.pathname === '/' ? '' : url.pathname+ const metadata = await fetchFirst<ProtectedResourceMetadata>([+ `${url.origin}/.well-known/oauth-protected-resource${resourcePath}`,+ `${url.origin}/.well-known/oauth-protected-resource`,+ ])+ return metadata?.authorization_servers?.[0] ?? url.origin+}++async function fetchAuthorizationServerMetadata(authorizationServer: string): Promise<AuthorizationServerMetadata> {+ const issuer = parseUrl(authorizationServer)+ const path = issuer.pathname === '/' ? '' : issuer.pathname.replace(/\/$/, '')+ const candidates = [+ // RFC 8414: the well-known suffix goes between the host and the issuer's path.+ `${issuer.origin}/.well-known/oauth-authorization-server${path}`,+ // OpenID Connect Discovery 1.0: the opposite order — suffix appended after the path.+ `${issuer.origin}${path}/.well-known/openid-configuration`,+ ]+ const metadata = await fetchFirst<AuthorizationServerMetadata>(candidates)+ if (isNil(metadata) || isNil(metadata.authorization_endpoint) || isNil(metadata.token_endpoint)) {+ throw invalidConnection(`Could not discover OAuth2 endpoints for ${authorizationServer}. Tried ${candidates.join(' and ')}. If this server is on a private network, add its host to AP_SSRF_ALLOW_LIST.`)+ }+ return metadata+}++async function fetchFirst<T>(candidates: string[]): Promise<T | null> {+ for (const url of candidates) {+ const { data: response, error } = await tryCatch(() => safeHttp.axios.get<T>(url, { timeout: REQUEST_TIMEOUT_MS }))+ if (isNil(error) && !isNil(response)) {+ return response.data+ }+ }+ return null+}++async function registerClient({ registrationEndpoint, redirectUrl, scope, tokenEndpointAuthMethod }: RegisterClientParams): Promise<ClientRegistrationResponse> {+ const { data: response, error } = await tryCatch(() => safeHttp.axios.post<ClientRegistrationResponse>(registrationEndpoint, {+ client_name: 'Activepieces',+ redirect_uris: [redirectUrl],+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ token_endpoint_auth_method: tokenEndpointAuthMethod,+ ...(scope.length > 0 ? { scope } : {}),+ }, {+ headers: { 'content-type': 'application/json' },+ timeout: REQUEST_TIMEOUT_MS,+ }))+ if (!isNil(error) || isNil(response)) {+ throw invalidConnection(`Dynamic Client Registration failed at ${registrationEndpoint}: ${error instanceof Error ? error.message : String(error)}`)+ }+ return response.data+}++function withResourceIndicator({ authorizationEndpoint, resource }: WithResourceIndicatorParams): string {+ const url = new URL(authorizationEndpoint)+ url.searchParams.set('resource', resource)+ return url.toString()+}++function canonicalResourceUri(serverUrl: string): string {+ const url = parseUrl(serverUrl)+ return `${url.origin}${url.pathname}`.replace(/\/$/, '')+}++function parseUrl(url: string): URL {+ const { data: parsed, error } = tryCatchSync(() => new URL(url))+ if (!isNil(error) || isNil(parsed)) {+ throw invalidConnection(`"${url}" is not a valid URL.`)+ }+ return parsed+}++function invalidConnection(error: string): ActivepiecesError {+ return new ActivepiecesError({+ code: ErrorCode.INVALID_APP_CONNECTION,+ params: { error },+ })+}++const TOKEN_ENDPOINT_AUTH_METHODS: Partial<Record<string, OAuth2AuthorizationMethod>> = {+ client_secret_basic: OAuth2AuthorizationMethod.HEADER,+ client_secret_post: OAuth2AuthorizationMethod.BODY,+}++export const oauth2Discovery = { discoverAndRegister }++type TokenEndpointAuthMethod = 'client_secret_basic' | 'client_secret_post'++type DiscoverAndRegisterParams = {+ serverUrl: string+ redirectUrl: string+}++type RegisterClientParams = {+ registrationEndpoint: string+ redirectUrl: string+ scope: string+ tokenEndpointAuthMethod: TokenEndpointAuthMethod+}++type WithResourceIndicatorParams = {+ authorizationEndpoint: string+ resource: string+}++export type DiscoveredOAuth2Client = {+ authUrl: string+ tokenUrl: string+ scopes: string+ clientId: string+ clientSecret: string+ resource: string+ authorizationMethod: OAuth2AuthorizationMethod+}++type ProtectedResourceMetadata = {+ authorization_servers?: string[]+}++type AuthorizationServerMetadata = {+ authorization_endpoint: string+ token_endpoint: string+ registration_endpoint?: string+ scopes_supported?: string[]+ token_endpoint_auth_methods_supported?: string[]+}++type ClientRegistrationResponse = {+ client_id: string+ client_secret?: string+ token_endpoint_auth_method?: string+}diff --git a/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-service.ts b/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-service.tsindex bdce0815d13..6ef9bd4a2e3 100644--- a/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-service.ts+++ b/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-service.ts@@ -30,6 +30,7 @@ export type OAuth2RequestBody = {authorizationMethod?: OAuth2AuthorizationMethodcodeVerifier?: stringscope?: string+ resource?: string}export type ClaimOAuth2Request = {diff --git a/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-util.ts b/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-util.tsindex d9ceb18ffae..d239bdf1650 100644--- a/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-util.ts+++ b/packages/server/api/src/app/app-connection/app-connection-service/oauth2/oauth2-util.ts@@ -1,12 +1,13 @@import { createHash, randomBytes } from 'crypto'import { ActivepiecesError, assertNotNullOrUndefined, deleteProps, ErrorCode, isNil, PlatformId, unique } from '@activepieces/core-utils'-import { OAuth2Props, PropertyType } from '@activepieces/pieces-framework'+import { OAuth2Property, OAuth2Props, PropertyType } from '@activepieces/pieces-framework'import { AppConnection, AppConnectionType, BaseOAuth2ConnectionValue, GetOAuth2AuthorizationUrlResponse, OAuth2GrantType, resolveValueFromProps } from '@activepieces/shared'import { isAxiosError } from 'axios'import { FastifyBaseLogger } from 'fastify'import { nanoid } from 'nanoid'import { secretManagersService } from '../../../ee/secret-managers/secret-managers.service'import { pieceMetadataService } from '../../../pieces/metadata/piece-metadata-service'+import { oauth2Discovery } from './oauth2-discovery'export const oauth2Util = (log: FastifyBaseLogger) => ({formatOAuth2Response: (response: Omit<BaseOAuth2ConnectionValue, 'claimed_at'>): BaseOAuth2ConnectionValue => {@@ -77,13 +78,15 @@ export const oauth2Util = (log: FastifyBaseLogger) => ({const pieceAuth = Array.isArray(pieceMetadata.auth) ? pieceMetadata.auth.find(auth => auth.type === PropertyType.OAUTH2) : pieceMetadata.authassertNotNullOrUndefined(pieceAuth, 'auth')switch (pieceAuth.type) {- case PropertyType.OAUTH2:+ case PropertyType.OAUTH2: {+ const templateProps = backfillOptionalProps(props, pieceAuth.props)assertPlaceholdersResolved({templates: [pieceAuth.tokenUrl, ...pieceAuth.scope],- props,+ props: templateProps,authProps: pieceAuth.props,})- return resolveValueFromProps(props, pieceAuth.tokenUrl)+ return resolveValueFromProps(templateProps, pieceAuth.tokenUrl)+ }default:throw new ActivepiecesError({code: ErrorCode.INVALID_APP_CONNECTION,@@ -119,20 +122,25 @@ export const oauth2Util = (log: FastifyBaseLogger) => ({})}- const resolvedClientId = await secretManagersService(log).resolveString({- key: clientId,- platformId,- throwOnFailure: true,- projectIds: projectId ? [projectId] : undefined,- })+ const discovered = await discoverOAuth2Client({ pieceAuth, props, redirectUrl })+ const resolvedProps = isNil(discovered) ? props : { ...props, ...discovered.props }+ const resolvedClientId = isNil(discovered)+ ? await secretManagersService(log).resolveString({+ key: clientId,+ platformId,+ throwOnFailure: true,+ projectIds: projectId ? [projectId] : undefined,+ })+ : discovered.client_idconst selectedScopes = resolveSelectedScopes(scopes, pieceAuth.scope)+ const templateProps = backfillOptionalProps(resolvedProps, pieceAuth.props)assertPlaceholdersResolved({templates: [pieceAuth.authUrl, ...selectedScopes],- props,+ props: templateProps,authProps: pieceAuth.props,})- const authUrl = resolveValueFromProps(props, pieceAuth.authUrl)- const scope = resolveValueFromProps(props, selectedScopes.join(' '))+ const authUrl = resolveValueFromProps(templateProps, pieceAuth.authUrl)+ const scope = resolveValueFromProps(templateProps, selectedScopes.join(' '))const queryParams: Record<string, string> = {response_type: 'code',@@ -177,6 +185,7 @@ export const oauth2Util = (log: FastifyBaseLogger) => ({return {authorizationUrl: url.toString(),codeVerifier,+ ...(isNil(discovered) ? {} : { discovered }),}},removeRefreshTokenAndClientSecret: (connection: AppConnection): AppConnection => {@@ -223,6 +232,51 @@ const resolveSelectedScopes = (requested: string[] | undefined, allowed: string[return requested}+const discoverOAuth2Client = async ({ pieceAuth, props, redirectUrl }: DiscoverOAuth2ClientParams): Promise<DiscoveredOAuth2Props | undefined> => {+ const discovery = pieceAuth.discovery+ if (isNil(discovery)) {+ return undefined+ }+ const alreadyFilledIn = String(props?.[discovery.authUrlProp] ?? '').trim() !== ''+ if (alreadyFilledIn) {+ return undefined+ }+ const serverUrl = props?.[discovery.serverUrlProp]+ if (typeof serverUrl !== 'string' || serverUrl.trim() === '') {+ const label = pieceAuth.props?.[discovery.serverUrlProp]?.displayName ?? discovery.serverUrlProp+ throw new ActivepiecesError({+ code: ErrorCode.INVALID_APP_CONNECTION,+ params: { error: `missing required connection settings: ${label}` },+ })+ }+ const client = await oauth2Discovery.discoverAndRegister({ serverUrl, redirectUrl })+ return {+ props: {+ [discovery.authUrlProp]: client.authUrl,+ [discovery.tokenUrlProp]: client.tokenUrl,+ ...(isNil(discovery.scopesProp) ? {} : { [discovery.scopesProp]: client.scopes }),+ },+ client_id: client.clientId,+ client_secret: client.clientSecret,+ resource: client.resource,+ authorization_method: client.authorizationMethod,+ }+}++// `resolveValueFromProps` only substitutes a `{key}` placeholder when `key` is present in+// `props`; an optional prop the caller never supplied is absent, not empty, and would+// otherwise leak through as the literal `{key}` text (e.g. a bare `scope={scopes}`).+const backfillOptionalProps = (props: Record<string, unknown> | undefined, authProps: OAuth2Props | undefined): Record<string, unknown> => {+ const declaredProps = authProps ?? {}+ const backfilled = { ...(props ?? {}) }+ Object.entries(declaredProps).forEach(([key, prop]) => {+ if (prop.required === false && isNil(backfilled[key])) {+ backfilled[key] = ''+ }+ })+ return backfilled+}+const assertPlaceholdersResolved = ({ templates, props, authProps }: AssertPlaceholdersResolvedParams): void => {const declaredProps = authProps ?? {}const missing = unique(@@ -230,6 +284,7 @@ const assertPlaceholdersResolved = ({ templates, props, authProps }: AssertPlace.flatMap(template => [...template.matchAll(/\{([A-Za-z0-9_]+)\}/g)]).map(match => match[1]).filter(key => !isNil(declaredProps[key]))+ .filter(key => declaredProps[key].required !== false).filter(key => {const value = props?.[key]return isNil(value) || String(value).trim() === ''@@ -251,6 +306,14 @@ type AssertPlaceholdersResolvedParams = {authProps: OAuth2Props | undefined}+type DiscoverOAuth2ClientParams = {+ pieceAuth: OAuth2Property<OAuth2Props>+ props: Record<string, unknown> | undefined+ redirectUrl: string+}++type DiscoveredOAuth2Props = NonNullable<GetOAuth2AuthorizationUrlResponse['discovered']>+type BuildAuthorizationUrlParams = {platformId: PlatformIdpieceName: stringdiff --git a/packages/server/api/src/app/app-connection/app-connection-service/oauth2/services/credentials-oauth2-service.ts b/packages/server/api/src/app/app-connection/app-connection-service/oauth2/services/credentials-oauth2-service.tsindex 388073cdf77..b97e4a49190 100644--- a/packages/server/api/src/app/app-connection/app-connection-service/oauth2/services/credentials-oauth2-service.ts+++ b/packages/server/api/src/app/app-connection/app-connection-service/oauth2/services/credentials-oauth2-service.ts@@ -42,7 +42,10 @@ export const credentialsOauth2Service = (log: FastifyBaseLogger): OAuth2Service<if (request.codeVerifier) {body.code_verifier = request.codeVerifier}-+ if (request.resource) {+ body.resource = request.resource+ }+const headers: Record<string, string> = {'content-type': 'application/x-www-form-urlencoded',accept: 'application/json',@@ -78,6 +81,7 @@ export const credentialsOauth2Service = (log: FastifyBaseLogger): OAuth2Service<grant_type: grantType,props: request.props,authorization_method: authorizationMethod,+ resource: request.resource,}}catch (e: unknown) {@@ -143,6 +147,9 @@ export const credentialsOauth2Service = (log: FastifyBaseLogger): OAuth2Service<default:throw new Error(`Unknown grant type: ${grantType}`)}+ if (appConnection.resource) {+ body.resource = appConnection.resource+ }const headers: Record<string, string> = {'content-type': 'application/x-www-form-urlencoded',@@ -176,6 +183,7 @@ export const credentialsOauth2Service = (log: FastifyBaseLogger): OAuth2Service<return {...mergedObject,props: appConnection.props,+ resource: appConnection.resource,}},})diff --git a/packages/server/api/test/unit/app/app-connection/credentials-oauth2-service.test.ts b/packages/server/api/test/unit/app/app-connection/credentials-oauth2-service.test.tsnew file mode 100644index 00000000000..5a1af0f49ce--- /dev/null+++ b/packages/server/api/test/unit/app/app-connection/credentials-oauth2-service.test.ts@@ -0,0 +1,154 @@+import { AppConnectionType, OAuth2GrantType } from '@activepieces/shared'+import { beforeEach, describe, expect, it, vi } from 'vitest'++const mockPost = vi.fn()+vi.mock('@activepieces/server-utils', () => ({+ safeHttp: {+ retryingAxios: {+ post: (...args: unknown[]) => mockPost(...args),+ },+ },+}))++const mockResolveString = vi.fn()+vi.mock('../../../../src/app/ee/secret-managers/secret-managers.service', () => ({+ secretManagersService: () => ({ resolveString: mockResolveString }),+}))++// oauth2-util.ts imports pieceMetadataService, whose module chain touches DB config at+// import time; credentialsOauth2Service never calls it, but the import graph still does.+vi.mock('../../../../src/app/pieces/metadata/piece-metadata-service', () => ({+ pieceMetadataService: () => ({ getOrThrow: vi.fn() }),+}))++import { credentialsOauth2Service } from '../../../../src/app/app-connection/app-connection-service/oauth2/services/credentials-oauth2-service'++const log = {} as never+const service = credentialsOauth2Service(log)+const RESOURCE = 'https://mcp.example.com/mcp'++function tokenResponseBody(): { data: Record<string, unknown> } {+ return { data: { access_token: 'token', refresh_token: 'refresh', expires_in: 3600 } }+}++describe('credentialsOauth2Service.claim', () => {+ beforeEach(() => {+ mockPost.mockReset()+ mockPost.mockResolvedValue(tokenResponseBody())+ })++ it('sends the RFC 8707 resource indicator on the authorization_code token request when discovery set one', async () => {+ await service.claim({+ projectId: undefined,+ platformId: 'platform',+ pieceName: 'mcp-client',+ request: {+ code: 'auth-code',+ clientId: 'client-id',+ clientSecret: 'client-secret',+ tokenUrl: 'https://as.example.com/token',+ redirectUrl: 'https://redirect',+ resource: RESOURCE,+ },+ })++ const [, body] = mockPost.mock.calls[0]+ expect((body as URLSearchParams).get('resource')).toBe(RESOURCE)+ })++ it('omits resource from the token request when discovery did not set one (unrelated, non-discoverable pieces)', async () => {+ await service.claim({+ projectId: undefined,+ platformId: 'platform',+ pieceName: 'zoom',+ request: {+ code: 'auth-code',+ clientId: 'client-id',+ clientSecret: 'client-secret',+ tokenUrl: 'https://as.example.com/token',+ redirectUrl: 'https://redirect',+ },+ })++ const [, body] = mockPost.mock.calls[0]+ expect((body as URLSearchParams).has('resource')).toBe(false)+ })++ it('persists the resource on the claimed connection value so refresh can read it back', async () => {+ const result = await service.claim({+ projectId: undefined,+ platformId: 'platform',+ pieceName: 'mcp-client',+ request: {+ code: 'auth-code',+ clientId: 'client-id',+ clientSecret: 'client-secret',+ tokenUrl: 'https://as.example.com/token',+ redirectUrl: 'https://redirect',+ resource: RESOURCE,+ },+ })++ expect(result.resource).toBe(RESOURCE)+ })+})++describe('credentialsOauth2Service.refresh', () => {+ beforeEach(() => {+ mockPost.mockReset()+ mockPost.mockResolvedValue(tokenResponseBody())+ mockResolveString.mockReset()+ mockResolveString.mockImplementation(({ key }: { key: string }) => Promise.resolve(key))+ })++ function expiredConnection(resource: string | undefined): never {+ return {+ type: AppConnectionType.OAUTH2,+ access_token: 'stale-token',+ refresh_token: 'refresh-token',+ claimed_at: 0,+ expires_in: 3600,+ client_id: 'client-id',+ client_secret: 'client-secret',+ token_url: 'https://as.example.com/token',+ grant_type: OAuth2GrantType.AUTHORIZATION_CODE,+ data: {},+ resource,+ } as never+ }++ it('re-sends the persisted resource indicator on refresh', async () => {+ await service.refresh({+ pieceName: 'mcp-client',+ platformId: 'platform',+ projectId: undefined,+ connectionValue: expiredConnection(RESOURCE),+ })++ const [, body] = mockPost.mock.calls[0]+ expect((body as URLSearchParams).get('resource')).toBe(RESOURCE)+ })++ it('omits resource from the refresh request when the connection never had one', async () => {+ await service.refresh({+ pieceName: 'mcp-client',+ platformId: 'platform',+ projectId: undefined,+ connectionValue: expiredConnection(undefined),+ })++ const [, body] = mockPost.mock.calls[0]+ expect((body as URLSearchParams).has('resource')).toBe(false)+ })++ it('keeps the resource on the connection value after a successful refresh', async () => {+ const result = await service.refresh({+ pieceName: 'mcp-client',+ platformId: 'platform',+ projectId: undefined,+ connectionValue: expiredConnection(RESOURCE),+ })++ expect(result.resource).toBe(RESOURCE)+ })+})diff --git a/packages/server/api/test/unit/app/app-connection/oauth2-discovery.test.ts b/packages/server/api/test/unit/app/app-connection/oauth2-discovery.test.tsnew file mode 100644index 00000000000..c54860fe635--- /dev/null+++ b/packages/server/api/test/unit/app/app-connection/oauth2-discovery.test.ts@@ -0,0 +1,186 @@+import { OAuth2AuthorizationMethod } from '@activepieces/pieces-framework'+import { beforeEach, describe, expect, it, vi } from 'vitest'++const mockGet = vi.fn()+const mockPost = vi.fn()++vi.mock('@activepieces/server-utils', () => ({+ safeHttp: {+ axios: {+ get: (...args: unknown[]) => mockGet(...args),+ post: (...args: unknown[]) => mockPost(...args),+ },+ },+}))++import { oauth2Discovery } from '../../../../src/app/app-connection/app-connection-service/oauth2/oauth2-discovery'++const SERVER_URL = 'https://mcp.example.com/mcp'+const REDIRECT_URL = 'https://cloud.activepieces.com/redirect'++const AUTHORIZATION_SERVER_METADATA = {+ authorization_endpoint: 'https://as.example.com/authorize',+ token_endpoint: 'https://as.example.com/token',+ registration_endpoint: 'https://as.example.com/register',+ scopes_supported: ['openid', 'profile'],+}++function serve(documents: Record<string, unknown>): void {+ mockGet.mockImplementation(async (url: string) => {+ if (url in documents) {+ return { data: documents[url] }+ }+ throw new Error(`not found: ${url}`)+ })+}++function registers(client: Record<string, unknown>): void {+ mockPost.mockResolvedValue({ data: client })+}++describe('oauth2Discovery.discoverAndRegister', () => {+ beforeEach(() => {+ mockGet.mockReset()+ mockPost.mockReset()+ registers({ client_id: 'cid', client_secret: 'secret' })+ })++ it('walks protected-resource metadata to the authorization server and registers a client', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/'] },+ 'https://as.example.com/.well-known/oauth-authorization-server': AUTHORIZATION_SERVER_METADATA,+ })++ const result = await oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL })++ expect(result.tokenUrl).toBe('https://as.example.com/token')+ expect(result.scopes).toBe('openid profile')+ expect(result.clientId).toBe('cid')+ expect(result.clientSecret).toBe('secret')+ expect(result.authorizationMethod).toBe(OAuth2AuthorizationMethod.HEADER)++ const [registrationEndpoint, body] = mockPost.mock.calls[0]+ expect(registrationEndpoint).toBe('https://as.example.com/register')+ expect(body).toMatchObject({+ redirect_uris: [REDIRECT_URL],+ token_endpoint_auth_method: 'client_secret_basic',+ })+ })++ it('sends the MCP server as the resource indicator on the authorize url', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/'] },+ 'https://as.example.com/.well-known/oauth-authorization-server': AUTHORIZATION_SERVER_METADATA,+ })++ const result = await oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL })++ expect(new URL(result.authUrl).searchParams.get('resource')).toBe(SERVER_URL)+ })++ it('registers with client_secret_post and sends credentials in the body when that is the only supported method', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/'] },+ 'https://as.example.com/.well-known/oauth-authorization-server': { ...AUTHORIZATION_SERVER_METADATA, token_endpoint_auth_methods_supported: ['client_secret_post'] },+ })++ const result = await oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL })++ expect(mockPost.mock.calls[0][1]).toMatchObject({ token_endpoint_auth_method: 'client_secret_post' })+ expect(result.authorizationMethod).toBe(OAuth2AuthorizationMethod.BODY)+ })++ it('honours the auth method the server actually registered over the one requested', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/'] },+ 'https://as.example.com/.well-known/oauth-authorization-server': AUTHORIZATION_SERVER_METADATA,+ })+ registers({ client_id: 'cid', client_secret: 'secret', token_endpoint_auth_method: 'client_secret_post' })++ const result = await oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL })++ expect(result.authorizationMethod).toBe(OAuth2AuthorizationMethod.BODY)+ })++ it('rejects a client registered with an auth method the token exchange cannot perform', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/'] },+ 'https://as.example.com/.well-known/oauth-authorization-server': AUTHORIZATION_SERVER_METADATA,+ })+ registers({ client_id: 'cid', client_secret: 'secret', token_endpoint_auth_method: 'private_key_jwt' })++ await expect(oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL }))+ .rejects.toMatchObject({ error: { params: { error: expect.stringContaining('private_key_jwt') } } })+ })++ it('falls back to openid-configuration when the rfc 8414 document is absent', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/'] },+ 'https://as.example.com/.well-known/openid-configuration': AUTHORIZATION_SERVER_METADATA,+ })++ const result = await oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL })++ expect(result.tokenUrl).toBe('https://as.example.com/token')+ })++ it('inserts the rfc 8414 well-known suffix before the issuer path, not after (Okta/Keycloak-shaped issuers)', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/realms/demo'] },+ 'https://as.example.com/.well-known/oauth-authorization-server/realms/demo': AUTHORIZATION_SERVER_METADATA,+ })++ const result = await oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL })++ expect(result.tokenUrl).toBe('https://as.example.com/token')+ })++ it('appends the openid-configuration well-known suffix after the issuer path', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/realms/demo'] },+ 'https://as.example.com/realms/demo/.well-known/openid-configuration': AUTHORIZATION_SERVER_METADATA,+ })++ const result = await oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL })++ expect(result.tokenUrl).toBe('https://as.example.com/token')+ })++ it('treats the server as its own authorization server when it publishes no protected-resource document', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-authorization-server': AUTHORIZATION_SERVER_METADATA,+ })++ const result = await oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL })++ expect(result.tokenUrl).toBe('https://as.example.com/token')+ })++ it('rejects a server that does not support dynamic client registration', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/'] },+ 'https://as.example.com/.well-known/oauth-authorization-server': { ...AUTHORIZATION_SERVER_METADATA, registration_endpoint: undefined },+ })++ await expect(oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL }))+ .rejects.toMatchObject({ error: { params: { error: expect.stringContaining('Dynamic Client Registration') } } })+ })++ it('rejects a public client, which the token exchange cannot authenticate', async () => {+ serve({+ 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp': { authorization_servers: ['https://as.example.com/'] },+ 'https://as.example.com/.well-known/oauth-authorization-server': AUTHORIZATION_SERVER_METADATA,+ })+ registers({ client_id: 'cid' })++ await expect(oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL }))+ .rejects.toMatchObject({ error: { params: { error: expect.stringContaining('public OAuth2 clients') } } })+ })++ it('reports discovery failure when no metadata can be reached', async () => {+ serve({})++ await expect(oauth2Discovery.discoverAndRegister({ serverUrl: SERVER_URL, redirectUrl: REDIRECT_URL }))+ .rejects.toMatchObject({ error: { params: { error: expect.stringContaining('AP_SSRF_ALLOW_LIST') } } })+ })+})diff --git a/packages/server/api/test/unit/app/app-connection/oauth2-util.test.ts b/packages/server/api/test/unit/app/app-connection/oauth2-util.test.tsindex 32651131df4..4886c38ac91 100644--- a/packages/server/api/test/unit/app/app-connection/oauth2-util.test.ts+++ b/packages/server/api/test/unit/app/app-connection/oauth2-util.test.ts@@ -1,5 +1,17 @@+import { PropertyType } from '@activepieces/pieces-framework'import { OAuth2GrantType } from '@activepieces/shared'import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'++const mockGetOrThrow = vi.fn()+vi.mock('../../../../src/app/pieces/metadata/piece-metadata-service', () => ({+ pieceMetadataService: () => ({ getOrThrow: mockGetOrThrow }),+}))++const mockResolveString = vi.fn()+vi.mock('../../../../src/app/ee/secret-managers/secret-managers.service', () => ({+ secretManagersService: () => ({ resolveString: mockResolveString }),+}))+import { oauth2Util } from '../../../../src/app/app-connection/app-connection-service/oauth2/oauth2-util'const util = oauth2Util({} as never)@@ -92,3 +104,31 @@ describe('oauth2Util.formatOAuth2Response', () => {expect(util.formatOAuth2Response({ access_token: 'token', expires_in: '1e999' } as never).expires_in).toBeUndefined()})})++describe('oauth2Util.buildAuthorizationUrl', () => {+ it('omits scope from the authorize url rather than sending the literal placeholder when an optional scope prop is not provided', async () => {+ mockGetOrThrow.mockResolvedValue({+ auth: {+ type: PropertyType.OAUTH2,+ authUrl: 'https://as.example.com/authorize',+ tokenUrl: 'https://as.example.com/token',+ scope: ['{scopes}'],+ props: {+ scopes: { required: false, displayName: 'Scopes' },+ },+ },+ })+ mockResolveString.mockResolvedValue('client-id')++ const result = await util.buildAuthorizationUrl({+ platformId: 'platform',+ pieceName: 'piece',+ clientId: 'client-id',+ redirectUrl: 'https://redirect',+ props: {},+ } as never)++ const url = new URL(result.authorizationUrl)+ expect(url.searchParams.has('scope')).toBe(false)+ })+})diff --git a/packages/web/src/app/builder/piece-properties/generic-properties-form.tsx b/packages/web/src/app/builder/piece-properties/generic-properties-form.tsxindex faea872f7d0..138d0ebcd82 100644--- a/packages/web/src/app/builder/piece-properties/generic-properties-form.tsx+++ b/packages/web/src/app/builder/piece-properties/generic-properties-form.tsx@@ -24,7 +24,7 @@ import { PropertyGroupTabs } from './property-group-tabs';export const GenericPropertiesForm = React.memo(({markdownVariables,- props,+ props: allProps,propertySettings,prefixValue,disabled,@@ -32,7 +32,9 @@ export const GenericPropertiesForm = React.memo(onValueChange,dynamicPropsInfo,propertyGroups,+ hiddenPropNames,}: GenericPropertiesFormProps) => {+ const props = omitProps(allProps, hiddenPropNames);const form = useFormContext();const groupByPropName = buildGroupByPropName(propertyGroups);const renderedGroups = new Set<string>();@@ -155,6 +157,18 @@ export const GenericPropertiesForm = React.memo(GenericPropertiesForm.displayName = 'GenericFormComponent';+function omitProps<T extends GenericPropertiesFormProps['props']>(+ props: T,+ hiddenPropNames: string[] | undefined,+): T {+ if (!hiddenPropNames || hiddenPropNames.length === 0) {+ return props;+ }+ return Object.fromEntries(+ Object.entries(props).filter(([name]) => !hiddenPropNames.includes(name)),+ ) as T;+}+function buildGroupByPropName(propertyGroups: PropertyGroup[] | undefined,): Map<string, PropertyGroup> {@@ -180,4 +194,6 @@ type GenericPropertiesFormProps = {dynamicPropsInfo: SelectGenericFormComponentForPropertyParams['dynamicPropsInfo'];/**groups multiple props into a single widget (e.g. tabbed recipients) */propertyGroups?: PropertyGroup[];+ /**props the caller fills in itself, so the user never sees them */+ hiddenPropNames?: string[];};diff --git a/packages/web/src/app/connections/oauth2-connection-settings.tsx b/packages/web/src/app/connections/oauth2-connection-settings.tsxindex 3eb57b563dd..5036e0f61d1 100644--- a/packages/web/src/app/connections/oauth2-connection-settings.tsx+++ b/packages/web/src/app/connections/oauth2-connection-settings.tsx@@ -63,13 +63,26 @@ function OAuth2ConnectionSettings({| UpsertPlatformOAuth2Request;}>();+ const [discoveryFailed, setDiscoveryFailed] = useState(false);+ // Endpoints and credentials are fetched from the server's own metadata on Connect,+ // so the fields that would carry them stay hidden until that fails.+ const useDiscovery = !isNil(authProperty.discovery) && !discoveryFailed;+const isClientIdValid = isNil(form.formState.errors.request?.value?.client_id,);const isClientSecretValid =oauth2App.oauth2Type !== AppConnectionType.OAUTH2 ||+ useDiscovery ||form.getValues('request.value.client_secret');- const isPropsValid = isNil(form.formState.errors.request?.value?.props);+ // Discovery fills these on Connect, so their emptiness must not gate the button+ // that triggers it — but every other prop (the server URL) still gates it.+ const propErrors = form.formState.errors.request?.value?.props;+ const discoveredNames = discoveredPropNames(authProperty.discovery);+ const isPropsValid =+ isNil(propErrors) ||+ (useDiscovery &&+ Object.keys(propErrors).every((name) => discoveredNames.includes(name)));const selectedScopeString = form.watch('request.value.scope') ?? '';const showScopeSelector = authProperty.scope.length > 1;const hasSelectedScopes =@@ -106,7 +119,7 @@ function OAuth2ConnectionSettings({</div>)}- {oauth2App.oauth2Type === AppConnectionType.OAUTH2 && (+ {oauth2App.oauth2Type === AppConnectionType.OAUTH2 && !useDiscovery && (<><FormFieldname="request.value.client_id"@@ -151,6 +164,7 @@ function OAuth2ConnectionSettings({useMentionTextInput={false}propertySettings={null}dynamicPropsInfo={null}+ hiddenPropNames={useDiscovery ? discoveredNames : []}/>)}@@ -298,6 +312,7 @@ function OAuth2ConnectionSettings({scopes:scopesList.length > 0 ? scopesList : undefined,setLoading,+ onDiscoveryFailed: () => setDiscoveryFailed(true),});} else {field.onChange('');@@ -330,6 +345,19 @@ function parseScopeString(value: string | undefined): string[] {return value.split(' ').filter((scope) => scope.length > 0);}+function discoveredPropNames(+ discovery: OAuth2Property<OAuth2Props>['discovery'],+): string[] {+ if (isNil(discovery)) {+ return [];+ }+ return [+ discovery.authUrlProp,+ discovery.tokenUrlProp,+ ...(isNil(discovery.scopesProp) ? [] : [discovery.scopesProp]),+ ];+}+async function openPopup({redirectUrl,oauth2Type,@@ -340,6 +368,7 @@ async function openPopup({form,scopes,setLoading,+ onDiscoveryFailed,}: OpenPopupParams) {let authorizationUrl, codeVerifier;try {@@ -356,10 +385,38 @@ async function openPopup({});authorizationUrl = result.authorizationUrl;codeVerifier = result.codeVerifier;+ if (!isNil(result.discovered)) {+ form.setValue('request.value.client_id', result.discovered.client_id, {+ shouldValidate: true,+ });+ form.setValue(+ 'request.value.client_secret',+ result.discovered.client_secret,+ { shouldValidate: true },+ );+ form.setValue(+ 'request.value.props',+ { ...props, ...result.discovered.props },+ { shouldValidate: true },+ );+ form.setValue('request.value.resource', result.discovered.resource, {+ shouldValidate: true,+ });+ form.setValue(+ 'request.value.authorization_method',+ result.discovered.authorization_method,+ { shouldValidate: true },+ );+ }} catch (error: unknown) {const apError = api.isError(error)? (error.response?.data as ApErrorParams | undefined): undefined;+ // Only a rejection by the server itself means discovery can't work here; a+ // transient failure should leave the Connect button able to try again.+ if (apError?.code === ErrorCode.INVALID_APP_CONNECTION) {+ onDiscoveryFailed();+ }form.setError('request.value.code', {type: 'manual',message:@@ -410,4 +467,5 @@ type OpenPopupParams = {| UpsertPlatformOAuth2Request;}>;setLoading: Dispatch<SetStateAction<boolean>>;+ onDiscoveryFailed: () => void;};