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): run MCP on its own hostname, and fix SSO losing the MCP login (#15376)
Othman Abu Ajamieh22c239377ac5
diff --git a/brain/knowledge/ai-intelligence/mcp-server.md b/brain/knowledge/ai-intelligence/mcp-server.mdindex b275858e7ff..d6bb3bbb3f9 100644--- a/brain/knowledge/ai-intelligence/mcp-server.md+++ b/brain/knowledge/ai-intelligence/mcp-server.md@@ -71,10 +71,15 @@ Exposes an Activepieces project as an MCP server so AI clients (Claude Desktop,- Flow attribution: `ap_create_flow`/`ap_build_flow`/`ap_duplicate_flow` stamp `ownerId` (OAuth user) and `createdBy: { type: 'MCP', id }`.- `MCP_SERVER_CONNECTED` is deduped to at most one/user/server/day (`telemetryDedupe.onceToday`) — a daily-active signal, not request volume. Per-call usage is `MCP_TOOL_CALLED`.- **The MCP URL must be reachable without a redirect.** A cross-origin `301/302/307/308` strips the `Authorization` header in every spec-conforming client, and "cross-origin" includes the scheme — so a plain `http`→`https` canonicalisation at the proxy is as fatal as apex→www. It fails *loudly-looking-fine*: discovery is request-derived (`networkUtils.getRequestBaseUrl` reads `x-forwarded-proto`/host), so OAuth sign-in completes against the canonical origin while the client keeps POSTing the URL it was given, yielding permanent `401`s or a re-auth loop rather than a clean error. Activepieces never redirects there itself — the only prefixes are `/mcp` and `/mcp/platform`, and Fastify runs `ignoreTrailingSlash: true` so `/mcp/` matches the same route with no `301` — so it is always operator proxy config, and undetectable server-side (the proxy answers the pre-redirect request; AP never sees it).-- OAuth discovery URLs are built via `domainHelper.getPublicUrlFromRequest` so subpath-hosted instances advertise the right prefix. `401`s carry an RFC 9728 `WWW-Authenticate: Bearer resource_metadata="…"` header. Host-root `.well-known/oauth-*` must still be forwarded to AP by the operator.+- **Only a request on the `AP_MCP_URL` host is answered from config.** `domainHelper.getPublicUrlFromRequest` returns `AP_MCP_URL` verbatim (scheme and path) when the request host matches it; every other host gets the request origin plus `AP_FRONTEND_URL`'s pathname, which is main's behaviour and keeps Cloud custom domains and the #13603 subpath fix working. Matching `AP_FRONTEND_URL` too was tried and reverted: it took the scheme from config instead of `x-forwarded-proto`, so an `http://` `AP_FRONTEND_URL` behind TLS advertised an `http` issuer. The match is by host only, so `system-validator` refuses an `AP_MCP_URL` that shares a hostname with `AP_FRONTEND_URL` without being equal to it — on a shared host the MCP entry would also answer `/.well-known/openid-configuration` and split its issuer from the workload token's `iss` (decision 000038). The match needs the public host in `X-Forwarded-Host` or an unchanged `Host`; `/authorize` logs a warning when neither setting matches. `401`s carry an RFC 9728 `WWW-Authenticate: Bearer resource_metadata="…"` header. Host-root `.well-known/oauth-*` must still be forwarded to AP by the operator.+- **An `AP_FRONTEND_URL` path prefix is not a deployable shape, so MCP at `example.com/mcp` only works with the UI at the origin root.** The SPA is anchored to the origin root three ways (see [[web-feature-anatomy]]) and the router has no `basename`, so opening `example.com/<prefix>/` makes the app *relocate itself* to the origin root and nothing under the prefix ever routes. Measured 2026-09-09 behind Kong with a real SimpleSAMLphp IdP: with a prefixed `AP_FRONTEND_URL`, `/authorize` sends consent to `<prefix>/mcp-authorize`, SAML sign-in completes, and the user lands on `/projects/…` with the MCP flow silently abandoned and **no code issued**. With the UI at the root, `example.com/mcp` needs **no** `AP_MCP_URL` at all: discovery advertises `resource: example.com/mcp` against root-anchored `.well-known`, and the full round trip (IdP credential form → `/acs` → `/authenticate` → consent → code → token → `tools/list`) completes. The operator only has to forward the root-mounted protocol paths with `strip_path: false`.+- **A dedicated MCP host splits the flow between two parties, and only one of them needs the public internet.** The MCP *client* talks only to `AP_MCP_URL`; the *browser* is sent to `AP_FRONTEND_URL` for consent and sign-in, and the authorization code returns to the client's own `redirect_uri`, never to the MCP host. So an internal-only main host is a supported shape — a VPN user authorizes, and the cloud client then works from anywhere — and the corollary is that nobody outside that boundary can authorize at all. It also means SSO needs no second ACS URL: the browser always signs in on the main host, same origin as the configured ACS, so the `sessionStorage` continuation in [[ee-authentication-sso-rbac]] survives. Bouncing consent to the MCP host instead would break both properties.+- **On a dedicated MCP host, match `/mcp` exactly — a prefix rule also matches `/mcp-authorize`.** Kong's `paths: [/mcp]` (and any prefix-matching proxy rule) routes `/mcp-authorize` to the app too, so the MCP host serves the consent SPA shell — which cannot work there, because the whole point of the separate host is that it exposes no `/api` and no `/assets`. The operator sees a blank or broken consent page instead of a clean 404 telling them their rule is too broad. Route `/mcp` and `/mcp/platform` as exact matches alongside `/.well-known/oauth-*`, `/.well-known/openid-configuration`, `/.well-known/jwks.json`, `/authorize`, `/token`, `/register`, `/revoke`, `/userinfo`.+- **MCP access tokens are not bound to a host.** They carry `audience: JwtAudience.MCP_OAUTH_ACCESS` and no issuer or host claim, and while the OAuth `resource` parameter is accepted and recorded it is never enforced as an audience; DCR redirect URIs are ephemeral loopback, so they are host-independent too. Serving MCP on two hostnames at once is therefore safe — a client works against whichever URL it discovered — but a token minted on one is equally valid on the other. A separate MCP hostname is a traffic and WAF boundary, never a token boundary; do not describe it to an operator as isolation.- **DCR must issue a client secret when `token_endpoint_auth_method` is omitted.** RFC 7591 §2 says an omitted value defaults to `client_secret_basic`, *not* `none`, and [Microsoft Copilot Studio](https://learn.microsoft.com/en-us/microsoft-365/copilot/extensibility/plugin-authentication-dynamic-client-registration) refuses DCR outright without one ("DCR without a client secret isn't supported yet"). Defaulting an omitted method to `none` looks like it fixes the "public client handed a secret" contradiction, but it resolves it the wrong way: it breaks Copilot and makes `client_secret_basic` support unreachable for every client that omits the field. Resolve it the other way — default to `client_secret_basic` and keep issuing the secret.- `x-ap-conversation-id` header (EE chat) rebinds the server to a conversation's project, but only when scoping matches the token — it can never widen the grant.- **The platform server's selected project is keyed per OAuth client, and it has to be.** `/mcp/platform` registers `ap_set_project_context`, and every non-platform-level tool re-reads that selection from Redis on *every* call, because the transport is stateless (`sessionIdGenerator: undefined` — a fresh `McpServer` per POST) and there is no session to hold it in. The key is `mcp-project-selection:client:{platformId}:{userId}:{clientId}`, with `clientId` read off the access token: it was `…:user:{platformId}:{userId}` until GIT-1831, and two clients on the same platform-wide grant (Claude Code and LibreChat, both pointed at `/mcp/platform`) stomped each other's project — surfacing as intermittent "Flow not found" for a flow that exists and reads fine over REST. Two consequences of using `clientId`: a client's selection resets when it re-runs DCR sign-in (see the DCR gotcha above — `clientId` is per registration), and two instances of the *same* registration still share one selection. Nothing available on a stateless request can separate those. `ProjectSelectionScope` also used to carry a `{ conversationId }` variant — PR #13356 (`fbfbcd7578`) removed its only caller in favour of the conversation's own Postgres `projectId`, and when that resolves the server is built project-scoped so the selection layer is never touched; internal chat never writes this key at all (`ap_set_project_context` is in `CHAT_HIDDEN_TOOL_NAMES`). Do not reintroduce a conversation scope for external clients: they never send `x-ap-conversation-id`.+- **A dedicated MCP host needs no SPA and no `/api`, because consent is served from the frontend base.** When a request matches `AP_MCP_URL`, `/authorize` redirects to `domainHelper.getBrowserLandingUrl({ path: '/mcp-authorize' })` — the frontend **origin**, never its configured base URL — rather than following the request host — so the user signs in once, on the main host, where their session token already lives (it is `localStorage`, and therefore per-origin: consent on the MCP host would demand a second login). That leaves the MCP host serving only `/mcp`, `/mcp/platform`, `/.well-known/oauth-*`, `/.well-known/openid-configuration`, `/.well-known/jwks.json`, `/authorize`, `/token`, `/register`, `/revoke` and `/userinfo` — all mounted at the domain root in `server.ts`, outside the `/api` prefix — which is what makes the tight WAF rule set that motivates a separate host actually possible. The redirect is conditional on matching `AP_MCP_URL` on purpose: making it unconditional would bounce Cloud custom-domain users off their own domain. Use the *origin*, not `getPublicUrl`: a browser landing route cannot carry `AP_FRONTEND_URL`'s path, because the router has no `basename` and the request falls through to the default page — so on a prefixed instance the consent page never renders and no code is issued. Both branches of that conditional had this fault. The three `getPublicUrl` deep links (`/projects/{id}/flows/{id}`, `/runs/{id}`, `/agents/{id}`) still do.- **The platform server's selected project is live mutable state, so resolve it once per call and thread it.** `mcpProjectSelection.get` is an uncached Redis read, its scope is per OAuth client rather than per session (see the gotcha above), and the transport is stateless (`sessionIdGenerator: undefined`, a fresh server per POST) — so two concurrent requests from the same client share one key, and `ap_set_project_context` can flip it mid-call. Anything downstream of a tool call that re-reads the key instead of reusing what `execute` resolved will disagree with it: `ap_run_action` runs a real engine flow run, so the window is seconds wide, and a deferred read after the response lands in whatever project was selected *by then*. This bites attribution hardest — a row or file written from a second read names a project the action never touched, silently and plausibly.- **`openid` alone releases the email, and that is deliberate.** `buildClaims` treats `openid` or `email` as granting the email claim, where OIDC strictly wants `email` for it. ChatGPT's enterprise domain restriction is the whole reason the layer exists and it must not fail on a client that requests only `openid`. Nothing else narrows scopes either — `/authorize` stores `scope.split(' ')` verbatim, so a client self-granting `openid email` gets only the consenting user's own address, which the MCP grant it just approved already dominates.- **No `id_token` comes back from a refresh, on purpose.** OIDC makes it optional there, and `refreshAccessToken` has no `nonce` to echo — returning one would hand the RP a nonce-less assertion for a flow that required a nonce. Clients that need fresh claims call `/userinfo`, which is also the only path that re-reads the email after it changes.diff --git a/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md b/brain/knowledge/connections-auth/ee-authentication-sso-rbac.mdindex 9a3b5207c95..c8b4bbb793c 100644--- a/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md+++ b/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md@@ -24,6 +24,9 @@ Enterprise auth layer extending CE with SAML 2.0 SSO, Google/GitHub federated OA- **`otpService.confirm` used to refresh its own resend lock.** `updated` is an `updateDate` column, so marking a row CONFIRMED touched it and the ten-minute guard then refused to issue that identity another code for ten minutes after a successful verify. Rows are deleted on confirm now.- **One constant is both the expiry and the resend suppression.** `TEN_MINUTES` gates `confirm`'s freshness check and `createAndSend`'s "an OTP already exists" early return, so before this work a resend was impossible until the current credential expired, and the request endpoint still answered 204. Resend now re-delivers the existing value without touching `updated`.- **`email-service.ts` is not exhaustive over `OtpType`.** `frontendPath` is a literal keyed by only two members but indexed by the whole union, so adding a member is a compile break; its sibling `otpToTemplate` is typed `Record<string, EmailTemplateData>`, which type-checks and hands `undefined` to the sender at runtime instead.+- **The SAML round-trip used to forget where the login was going, and the obvious fix moves a trust boundary.** Three losses, all in the redirect and none in the assertion handling: the web app called `/api/v1/authn/saml/login` with no `from` (`saml-login-form.tsx`, `third-party-logins.tsx`), `/authenticate` hardcoded `navigate('/flows')`, and `/acs` redirected to `networkUtils.getRequestBaseUrl(req)` — an origin with no path — so a subpath instance 404'd at `example.com/authenticate`. Password sign-in hid all three by never leaving the origin; they surfaced the moment a login *started* elsewhere, so MCP OAuth (`/mcp-authorize` → `/sign-in?from=…`) abandoned the authorize request. **The trap worth remembering:** it is tempting to carry the starting origin through the IdP in RelayState. Do not. `/acs` derives its redirect from the IdP's POST, whose `x-forwarded-host` only the operator's edge sets; capturing the origin at `/login` instead hands that decision to an endpoint an attacker can call directly, and `networkUtils.candidateHosts` deliberately *prefers* `x-forwarded-host` — so a spoofed header would mint a return target for `evil.com`, and a phished IdP link carrying it would deliver the victim's session token to `/authenticate?response=`. Signing or storing the captured origin does not close that; only resolving it against an allowlist would. **What shipped avoids the question entirely:** MCP consent is served from the frontend base (see [[mcp-server]]), so login leaves and returns to the same origin in the same tab. `from` rides `sessionStorage` (`lib/federated-login-redirect.ts`, saved by `useStartSamlLogin` at the three SAML entry points, consumed and cleared at `/authenticate`). It stores **only** `/mcp-authorize`, exactly or followed by `?` — every other destination, including legitimate in-app deep links, is refused and SSO lands on the default page as it always has. That narrowness is deliberate: the mechanism exists for the one flow that cannot survive losing its continuation, and scoping it by destination keeps deployments without MCP on their existing code path. Gating it on `AP_MCP_URL` instead would not work — `getMcpUrl` falls back to `AP_FRONTEND_URL`, so the `MCP_URL` flag is never null, and `/authenticate` consumes synchronously on mount while flags arrive async, and `/acs` builds its redirect from the request origin (`new URL('/authenticate', networkUtils.getRequestBaseUrl(req))`), which is the one place the SPA can route it. No RelayState, no Redis, no allowlist, and the origin never crosses the IdP.+- **Restoring the subpath on the SSO return *breaks* SAML sign-in on a prefixed instance, because the SPA cannot route a prefixed path — and the bare-origin version it replaced accidentally could.** Verified end to end against a real SimpleSAMLphp IdP behind Kong (`strip_path: true`) with `AP_FRONTEND_URL=http://host/activepieces`: the assertion validates and `/acs` redirects to `http://host/activepieces/authenticate?response=…` exactly as intended — and the SPA then bounces away with the session response unconsumed, because `createBrowserRouter` has no `basename` (see [[web-feature-anatomy]]). Measured both ways on one harness: `new URL('/authenticate', getRequestBaseUrl(req))` drops the path, lands at the origin root, and signs in; restoring the prefix kills the login. So the two kinds of URL AP emits have opposite requirements and **must not share a helper**: *protocol URLs the server advertises* (OAuth issuer and endpoints, ACS `Destination`, webhooks, invitation links) need the configured base, while *browser landing routes* (`/authenticate`, `/mcp-authorize`, `/sign-in`) must stay wherever the SPA can actually route, which today is the origin root. With the origin-root return and the UI at the root, the whole SSO-into-MCP chain completes in a browser — IdP credential form → `/acs` → `/authenticate` → `from` restored from `sessionStorage` → consent → code → token → `tools/list`; that chain is the point of the `from` round trip, and it is what a prefixed instance loses. Until the SPA gains `basename` + vite `base`, prefixing a browser landing route is always wrong.+- **AP accepts only *plaintext* SAML assertions, and an encrypting IdP fails with a misleading error.** `createSp` sets `isAssertionEncrypted: true`, but samlify reads that flag off the **remote** entity (`flow.js`: `decryptRequired = from.entitySetting.isAssertionEncrypted`), where `createIdp` sets `false` — so the SP-side flag is inert. It could not work anyway: samlify decrypts with `entitySetting.encPrivateKey`, which AP never sets (`privateKey` holds `samlProvider.idpCertificate`, used for signing). Point an IdP with `assertion.encryption` on at it and the failure surfaces as `ERR_UNMATCH_ISSUER` — not a decryption error — because the issuer comparison reads the *assertion's* issuer out of a decrypted document that does not exist. Configure IdPs to sign but not encrypt.- SSO settings page wrapped in `LockedFeatureGuard` keyed on `ssoEnabled`.- Managed auth gated separately by `embeddingEnabled` (signing keys). See the Managed Auth page.- The authn rate limiter (`core/security/rate-limit.ts`) is registered with `global: false` — it protects NOTHING by default. Every public endpoint that sends email or does auth work must opt in per-route via `config.rateLimit` (see `authentication.controller.ts` / `otp-controller.ts` for the `API_RATE_LIMIT_AUTHN_*` pattern).diff --git a/brain/knowledge/decisions/000043-mcp-consent-stays-on-the-main-host.md b/brain/knowledge/decisions/000043-mcp-consent-stays-on-the-main-host.mdnew file mode 100644index 00000000000..341f097036e--- /dev/null+++ b/brain/knowledge/decisions/000043-mcp-consent-stays-on-the-main-host.md@@ -0,0 +1,19 @@+---+status: accepted+---++# MCP consent stays on the main host++## Decision+When a request arrives on `AP_MCP_URL`, the `/authorize` route redirects the browser to `AP_FRONTEND_URL`'s origin for `/mcp-authorize`, not to the MCP hostname it arrived on. The MCP hostname serves protocol routes only — no SPA, no `/api` — and the authorization code returns to the client's own `redirect_uri`, never to either host.++## Context+Self-hosters put MCP on a second hostname so that the MCP endpoint can be public while Activepieces itself is not — typically the app is VPN-only or IP-restricted, and a cloud MCP client cannot reach it. The OAuth flow then spans two parties: the client, which only ever talks to `AP_MCP_URL`, and the user's browser, which has to sign in and approve somewhere. Whichever host the browser lands on must be able to complete a full sign-in, and on self-hosted the SAML ACS URL is a single value derived from `AP_FRONTEND_URL`.++## Why+Consent on the main host is what lets single sign-on keep working with the IdP configuration the customer already has. The browser signs in on the same origin as the configured ACS, so the assertion comes back where the `sessionStorage` continuation was written and the flow resumes at `/mcp-authorize`. The rejected alternative — landing consent on the request origin, so the user finishes where they started — requires a second ACS URL registered at the IdP, and customers frequently cannot add one. It would also force the MCP hostname to proxy the whole app, defeating the narrow WAF surface that motivates a separate hostname, and cost a second sign-in because the session token is per-origin `localStorage`.++The accepted cost is that authorization is only possible from wherever the main host is reachable. That is acceptable because it is a one-time, interactive step, and everything after approval is client-to-`AP_MCP_URL` and works from anywhere.++## Consequences+A restricted main host is a supported deployment: an internal user authorizes once, and the cloud client works from anywhere afterwards. Nobody outside that boundary can authorize at all, which is documented against `AP_MCP_URL` rather than detectable at runtime — the server cannot know what the browser can reach. Anything that later varies the ACS per request must also widen the `createSamlClient` cache key, which is keyed by `platformId` alone.diff --git a/brain/knowledge/engineering/index.md b/brain/knowledge/engineering/index.mdindex b1cc8341b10..c9dfda6c6c0 100644--- a/brain/knowledge/engineering/index.md+++ b/brain/knowledge/engineering/index.md@@ -39,3 +39,4 @@ The **Activepieces engineering brain**: how the system works, and *why* it was b- **CI PR Review Hygiene** — draft-first Greptile review, the per-area PR size gate, and the workflow conventions reviewers keep re-litigating- **E2E Tests & Monitors** — the one Playwright suite behind CI, the Checkly monitors that run it against production Cloud, and the BetterStack script the repo pushes on merge- **Architecture Spine** — the load-bearing structure of the codebase, and the gotchas that come with it: request-body `.max()` as data loss, TypeORM soft-delete across a canary window, and canary not proxying websockets+- **Reproduce a Self-Hoster's Proxy Topology** — standing up a reverse proxy, a second hostname, a path prefix and a real SAML IdP locally, so a redirect or discovery bug can be measured instead of argued aboutdiff --git a/brain/knowledge/engineering/reproduce-a-self-hoster-proxy-topology.md b/brain/knowledge/engineering/reproduce-a-self-hoster-proxy-topology.mdnew file mode 100644index 00000000000..e3177070cd0--- /dev/null+++ b/brain/knowledge/engineering/reproduce-a-self-hoster-proxy-topology.md@@ -0,0 +1,84 @@+---+icon: 🧪+---++# Reproduce a Self-Hoster's Proxy Topology++How to stand up a self-hoster's real deployment shape locally — a reverse proxy, a second hostname, a path+prefix, a real SAML IdP — so a redirect or discovery bug can be measured instead of argued about. Unit tests+cannot catch these: the interesting failures live in what the *proxy* forwards and what the *browser* does with+the URL AP hands it. Everything below runs on one machine with no `/etc/hosts` edit and no DNS.++## Steps++1. **Get real hostnames for free.** `*.127.0.0.1.nip.io` resolves to loopback publicly, so+ `ap.127.0.0.1.nip.io`, `mcp.127.0.0.1.nip.io` and `idp.127.0.0.1.nip.io` are distinct hosts and distinct+ browser *origins* (which matters — `localStorage`/`sessionStorage` are per-origin, and that is exactly what+ the MCP consent redirect is about). No sudo, and Chrome reaches them.+2. **Put Kong 3.9 in front, DB-less.** `KONG_DATABASE=off` + a declarative `kong.yml`, published on `:80`,+ upstream `http://host.docker.internal:<port>` with `extra_hosts: host.docker.internal:host-gateway`. Kong's+ defaults are the realistic case: it rewrites `Host` to the upstream and sets `X-Forwarded-Host` to the public+ host, which is the branch `networkUtils.candidateHosts` prefers. Use `strip_path: true` for a prefix route —+ AP registers its routes at the root and expects the proxy to strip.+3. **Run AP in production mode, not dev.** `AP_ENVIRONMENT=prod` is what makes the API serve the built SPA from+ `dist/packages/web`; in dev it serves no frontend and the whole browser half is untestable. Build once with+ `npx turbo run build --filter=web`, then run the API from source with+ `npx tsx --tsconfig packages/server/api/tsconfig.app.json packages/server/api/src/bootstrap.ts` — the+ `--tsconfig` is required or workspace imports resolve to unbuilt `dist` paths. EE also rejects+ `AP_EXECUTION_MODE=UNSANDBOXED`, so pass `SANDBOX_CODE_ONLY`.+4. **Isolate the state.** A separate Postgres database and a separate Redis port, never the dev ones — BullMQ+ keys and platform rows collide otherwise, and you will be changing `AP_FRONTEND_URL` repeatedly.+5. **Use `kristophjunge/test-saml-idp` as a real IdP.** Mount your own `saml20-sp-remote.php` (SP entity ID is+ the literal `Activepieces`, ACS is `<AP_FRONTEND_URL>/api/v1/authn/saml/acs`) and your own `authsources.php`+ — the stock image sends only `uid`/`email`, and `resolveSamlAttributes` also requires `firstName` and+ `lastName`. Give the IdP route `preserve_host: true` so SimpleSAMLphp derives its own URLs from the public+ host; paste its metadata XML into `idpMetadata` inline, because a URL there goes through `safeHttp` and the+ SSRF filter rejects loopback.+6. **Unblock the EE gates by hand** — they are orthogonal to what you are testing, and each one is a dead end+ otherwise: `platform_plan.ssoEnabled = true`, `platform_plan.usersLimit` above 1 (free plan is 1 seat, and+ the invite 402s), `platform.ssoDomainVerification` set to `{"status":"VERIFIED",…}` (SAML config is refused+ until the domain is verified, and you cannot create the TXT record), and the SSO user's invitation must be+ **accepted**, not pending — `assertUserIsInvitedToPlatformOrProject` calls `hasAnyAcceptedInvitations`.+ Re-apply these after every restart: the plan row is recomputed at boot and silently reverts to 1 seat with+ SSO off.+7. **Drive SAML headlessly when you need the XML.** `curl -L` the login route to get the IdP form, POST+ `username`/`password`/`AuthState` back, and scrape `SAMLResponse` from the auto-submit page — that gives you+ a decodable assertion and a replayable POST to `/acs`. Switch to a real browser for anything involving+ `sessionStorage` or SPA routing, which is most redirect bugs.+8. **Finish in a browser, or you have not tested it.** curl proves what the server *advertises*; only the+ browser proves the flow *completes*. Run the whole chain — protocol `401`, discovery, DCR, `/authorize`,+ the IdP credential form, consent, the code landing on a local callback server, the token exchange, and one+ real `tools/call` — and check the callback actually received a code. A configuration can pass every curl+ assertion and still issue no code, which is how the prefixed-frontend shape in [[mcp-server]] was caught.+9. **Measure both branches on the same harness.** Kill the app, `git checkout` the other commit, restart with+ identical env, re-run the same request. A before/after pair of `Location` headers settles a redirect+ question in one command, and is how the SSO landing regression in [[ee-authentication-sso-rbac]] was found.++## Gotchas++- **`sed -i` on a bind-mounted single file breaks the mount.** It writes a new inode, and the container then+ fails to restart with `error mounting … no such file or directory`. Either truncate in place (`cat > file`)+ or edit and `docker compose up -d --force-recreate <svc>` — never `restart`.+- **Force-recreating the IdP is also how you get its login form back.** SimpleSAMLphp keeps a session, so a+ second run silently auto-authenticates and you stop exercising the credential step.+- **A prefix route in the proxy is not an exact route.** `paths: [/mcp]` also matches `/mcp-authorize`; see+ [[mcp-server]].+- **The harness lives in a scratch directory, so treat it as disposable and commit code changes early.** A+ `/tmp` wipe or host restart takes the worktree, the Kong and IdP configs, and any generated SP keypair with+ it; only the Postgres volume survives.+- **Turn assertion encryption OFF at the test IdP.** `createSp` sets `isAssertionEncrypted: true`, but samlify reads+ `decryptRequired` from the *IdP* entity, and `createIdp` sets it to `false` — so AP expects a signed, unencrypted+ assertion. With SimpleSAMLphp encrypting, you get `ERR_UNMATCH_ISSUER` (samlify skips decryption, then looks for+ `Assertion/Issuer` in a document that only holds `EncryptedAssertion`), and turning on response signing to fix it+ only moves you to `FAILED_TO_VERIFY_SIGNATURE`. `'assertion.encryption' => false` with `saml20.sign.assertion`+ is the combination that parses.+- **`createSamlClient` caches by `platformId` alone**, ignoring the `acsUrl` it was passed. Anything that varies the+ ACS per request needs the cache key widened, or the first caller's ACS is served to every later one.+- **The SPA cannot be tested under a path prefix**, because it is anchored to the origin root three ways — see+ [[web-feature-anatomy]]. Opening a prefixed URL makes the app relocate itself to the root. If you are testing+ a browser landing route, the prefix is the variable, so run the configuration both ways.++## Key files++- `packages/server/api/src/app/helper` — `domainHelper` and `networkUtils`, what every advertised URL is built from+- `packages/server/api/src/app/ee/authentication/saml-authn` — `createSamlClient`, the SP settings the IdP must matchdiff --git a/brain/knowledge/engineering/web-feature-anatomy.md b/brain/knowledge/engineering/web-feature-anatomy.mdindex ee87d7b67a7..ed81c7b2979 100644--- a/brain/knowledge/engineering/web-feature-anatomy.md+++ b/brain/knowledge/engineering/web-feature-anatomy.md@@ -78,6 +78,7 @@ way back was to stash the handful of intended edits, `git checkout` the package,## Gotchas+- **The SPA is hardcoded to the host root, so `AP_FRONTEND_URL`'s path prefix does not reach the frontend at all.** `index.html` carries `<base href="/" />`, there is no vite `base`, and `API_BASE_URL` in `lib/api.ts` is `window.location.origin` — origin only, path dropped. An instance served at `example.com/activepieces` therefore loads its bundle, its assets and every `/api/v1/...` call from `example.com/...` at the root, and only works because the operator's proxy exposes those at root too. The server-side subpath support (`domainHelper.getPublicUrlFromRequest`, which prepends the configured base path to advertised URLs) covers what AP *tells* clients, not what the browser *fetches* — the two do not meet. So "we support subpath hosting" is only half true: it holds for what the server advertises and for anything the browser never has to fetch. A second host escapes the constraint only if it serves no SPA at all — which is exactly why MCP consent is redirected back to the frontend base rather than served on the MCP host (see [[mcp-server]]), leaving `AP_MCP_URL` free to carry a prefix.- **A disabled TanStack query keeps `isPending: true` forever, so a skeleton driven by it never resolves.** `enabled: false` means "has no data and is not fetching", and `isPending` only reports the first half — the spinner spins for the life of the page. Drive loading UI off `isLoading` (`isPending && isFetching`), which is false while disabled. This bites hardest on the plan-gated queries the repo requires an `enabled: platform.plan.<flag>` on: every one of them is permanently pending for a platform without the feature. Also decide what the surface shows in that state — a count rendered from `data ?? 0` reads as a real zero, when the honest answer is that the feature is not on the plan.- **The `showcase/*.mp4` upsell videos on the CDN are all from 2024 and show the retired Admin Console.** `cdn.activepieces.com/videos/showcase/` holds seven of them (projects, templates, pieces, appearance, api-keys, alerts, flow-issues), last touched March-June 2024, and every frame is the old sidebar, the old tables and the old purple buttons. `FeatureTeaser` renders whatever `videoUrl`/`lockVideoUrl` it is handed, and the Templates locked page still passes `templates.mp4`, so a customer on the paywall watches a product that no longer exists. Do not reach for these when building an upsell surface — either reshoot or leave the video out. Pull a frame with ffmpeg before trusting any CDN asset whose name sounds right.- **`Button` tightens its own horizontal padding when a direct child is an `<svg>`, and the animated icons defeat it.** Every size variant carries a `has-[>svg]:px-*` pair (`sm` is `px-2.5 has-[>svg]:px-2`, so 10px normally and 8px with an icon) to stop an icon button reading as over-padded. The components in `components/icons/` wrap their `motion.svg` in a `<div>` to own the hover handlers, so `has-[>svg]` never matches and any `AnimatedIconButton` silently keeps the wider padding. Two buttons meant to look alike will differ by 2px a side the moment one uses a bare lucide icon and the other an animated one, so check the computed padding before assuming a diff caused it. To match the animated width deliberately, pass `cn('has-[>svg]:px-2.5', className)` — `Button` runs `cn(buttonVariants({ ..., className }))`, so tailwind-merge drops the variant's own value rather than leaving a specificity fight with `:has()`.diff --git a/bun.lock b/bun.lockindex e86d7eb9bea..80b4b9d5e72 100644--- a/bun.lock+++ b/bun.lock@@ -165,7 +165,7 @@},"packages/core/shared": {"name": "@activepieces/shared",- "version": "0.184.0",+ "version": "0.185.0","dependencies": {"@activepieces/core-execution": "workspace:*","@activepieces/core-formula": "workspace:*",@@ -712,7 +712,7 @@},"packages/pieces/community/apitemplate-io": {"name": "@activepieces/piece-apitemplate-io",- "version": "0.2.0",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -1463,7 +1463,7 @@},"packages/pieces/community/cal-com": {"name": "@activepieces/piece-cal-com",- "version": "0.4.9",+ "version": "0.5.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -5825,7 +5825,7 @@},"packages/pieces/community/microsoft-outlook": {"name": "@activepieces/piece-microsoft-outlook",- "version": "0.6.0",+ "version": "0.6.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -5837,6 +5837,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/microsoft-outlook-calendar": {@@ -6343,7 +6344,7 @@},"packages/pieces/community/nocodb": {"name": "@activepieces/piece-nocodb",- "version": "0.4.7",+ "version": "0.5.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -6356,7 +6357,7 @@},"packages/pieces/community/notion": {"name": "@activepieces/piece-notion",- "version": "0.7.2",+ "version": "0.7.3","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -7639,7 +7640,7 @@},"packages/pieces/community/reoon-verifier": {"name": "@activepieces/piece-reoon-verifier",- "version": "0.1.7",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8667,7 +8668,7 @@},"packages/pieces/community/straico": {"name": "@activepieces/piece-straico",- "version": "0.3.0",+ "version": "0.3.1","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -8908,7 +8909,7 @@},"packages/pieces/community/tavily": {"name": "@activepieces/piece-tavily",- "version": "0.2.0",+ "version": "0.3.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/docs/install/reference/environment-variables.mdx b/docs/install/reference/environment-variables.mdxindex 210d1c105ab..13151ae6e73 100644--- a/docs/install/reference/environment-variables.mdx+++ b/docs/install/reference/environment-variables.mdx@@ -64,7 +64,8 @@ protect connections and tokens, and telemetry.| ❗ `AP_ENCRYPTION_KEY` | 32-character (16-byte) hexadecimal key used to encrypt connections. Generate one with `openssl rand -hex 16`. | `None` || ❗ `AP_JWT_SECRET` | 32-character hexadecimal key used to sign JWT tokens. Generate one with `openssl rand -hex 32`. | `None` || `AP_CONFIG_PATH` | Path where the PGLite database and local settings are stored. | `~/.activepieces` |-| `AP_INTERNAL_URL` | (Beta) Internal URL used for SSO authentication, e.g. `https://demo.activepieces.com/api`. | `None` |+| `AP_MCP_URL` | Public base URL for MCP traffic on its own hostname (e.g. `https://mcp.example.com`). Must not share a hostname with `AP_FRONTEND_URL`. When unset, MCP is served from `AP_FRONTEND_URL`. See [Serving MCP from its own hostname](#serving-mcp-from-its-own-hostname). | `None` |+| `AP_INTERNAL_URL` | (Beta) Internal URL used for the Google sign-in redirect and for links in emails and alerts, e.g. `https://demo.activepieces.com/api`. SAML SSO does not use it: the SAML ACS URL is always based on `AP_FRONTEND_URL`. | `None` || `AP_TELEMETRY_ENABLED` | Starting value for product analytics. Each platform's setting is created from it on first read; after that, change it at Platform Admin → Account → Configurations. | `true` |<Warning>@@ -77,6 +78,76 @@ from the internet, set `AP_FRONTEND_URL` explicitly. For local development youcan expose the frontend port (4200) with a tunneling service such as[ngrok](https://ngrok.com/).+### Serving MCP from its own hostname++Set `AP_MCP_URL` when you want MCP traffic separated from the main app — to+apply distinct WAF rules, to observe it independently, or because your MCP+clients live on the internet while Activepieces itself does not. Discovery, the+`WWW-Authenticate` challenge and the token endpoint then advertise that hostname+instead of `AP_FRONTEND_URL`.++`AP_MCP_URL` must use its own hostname. Activepieces refuses to start when it+shares a hostname with `AP_FRONTEND_URL` but is not the same URL, because+requests on that hostname could not be told apart.++For example:++```bash+AP_FRONTEND_URL=https://example.com/activepieces+AP_MCP_URL=https://mcp.example.com+```++MCP clients then connect to `https://mcp.example.com/mcp` for a project, or+`https://mcp.example.com/mcp/platform` for the whole platform. The MCP settings+pages show these URLs.++**Routes on the MCP hostname.** Forward these paths to Activepieces without+rewriting them. It does **not** need to serve the web app or `/api`.++- `/mcp` and `/mcp/platform` — match them exactly. A prefix rule for `/mcp` also+ matches `/mcp-authorize`, which this hostname cannot serve.+- `/authorize`, `/token`, `/register`, `/revoke`, `/userinfo`+- `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource/*`,+ `/.well-known/openid-configuration`, `/.well-known/jwks.json`++**Routes on the main hostname.** The consent screen opens at `/mcp-authorize`+at the **root** of the `AP_FRONTEND_URL` hostname, even when `AP_FRONTEND_URL`+has a path prefix. Route it the same way as the SAML sign-in return+(`/authenticate`), `/api` and the web app's assets, which the browser already+loads from the root.++**Keep the public hostname.** Activepieces recognises an MCP request by its+hostname, so your proxy must pass `mcp.example.com` through — in+`X-Forwarded-Host`, or in an unchanged `Host` header. If the proxy replaces it+with an upstream name, discovery falls back to the main app's URLs and the+connection fails. Activepieces logs a warning when `/authorize` receives a+request for a hostname that matches neither setting.++<Warning>+ The two hostnames are reached by two different parties, and both must work.+ The **MCP client** — often a cloud service — only ever talks to `AP_MCP_URL`,+ so that hostname is the one that has to be publicly reachable. The **user's+ browser** is sent to `AP_FRONTEND_URL` to sign in and approve the connection,+ so whoever authorizes a client must be able to reach the main host at that+ moment. If your main host is restricted — to a VPN, an IP allow-list, or an+ internal network — then only users inside that boundary can authorize an MCP+ client. Everything after approval is client-to-`AP_MCP_URL` and works from+ anywhere.++ Single sign-on keeps working unchanged: the browser signs in on the main+ host. Your identity provider must keep posting SAML assertions to the ACS URL+ shown in Activepieces (`AP_FRONTEND_URL` followed by `/api/v1/authn/saml/acs`),+ not to `AP_MCP_URL` or `AP_INTERNAL_URL`. You do not need a second ACS URL.+</Warning>++`AP_MCP_URL` may carry a path prefix, for example+`https://gateway.example.com/activepieces`. Your proxy must then strip that+prefix before forwarding, and clients connect to+`https://gateway.example.com/activepieces/mcp`.++Setting `AP_MCP_URL` also changes the `mcpServerUrl` returned to embedded+clients by the project MCP token endpoint.+---### Databasediff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex b07961c3173..3c6539e969e 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.184.0",+ "version": "0.185.0","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/core/flag/flag.ts b/packages/core/shared/src/lib/core/flag/flag.tsindex 73ae7b10f0c..fcab4e05f38 100755--- a/packages/core/shared/src/lib/core/flag/flag.ts+++ b/packages/core/shared/src/lib/core/flag/flag.ts@@ -30,6 +30,7 @@ export enum ApFlagId {EXECUTION_DATA_RETENTION_DAYS = 'EXECUTION_DATA_RETENTION_DAYS',ENVIRONMENT = 'ENVIRONMENT',PUBLIC_URL = 'PUBLIC_URL',+ MCP_URL = 'MCP_URL',PRIVACY_POLICY_URL = 'PRIVACY_POLICY_URL',PIECES_SYNC_MODE = 'PIECES_SYNC_MODE',PRIVATE_PIECES_ENABLED = 'PRIVATE_PIECES_ENABLED',diff --git a/packages/server/api/src/app/flags/flag.service.ts b/packages/server/api/src/app/flags/flag.service.tsindex 94e5e4ed8ce..b8643ad8946 100644--- a/packages/server/api/src/app/flags/flag.service.ts+++ b/packages/server/api/src/app/flags/flag.service.ts@@ -202,6 +202,12 @@ export const flagService = (log: FastifyBaseLogger) => ({created,updated,},+ {+ id: ApFlagId.MCP_URL,+ value: domainHelper.getMcpUrl({ path: '' }),+ created,+ updated,+ },{id: ApFlagId.FLOW_RUN_TIME_SECONDS,value: system.getNumberOrThrow(AppSystemProp.FLOW_TIMEOUT_SECONDS),diff --git a/packages/server/api/src/app/helper/domain-helper.ts b/packages/server/api/src/app/helper/domain-helper.tsindex 1055321f835..8719e13a362 100644--- a/packages/server/api/src/app/helper/domain-helper.ts+++ b/packages/server/api/src/app/helper/domain-helper.ts@@ -1,4 +1,4 @@-import { tryCatchSync } from '@activepieces/core-utils'+import { isNil, tryCatchSync } from '@activepieces/core-utils'import { FastifyRequest } from 'fastify'import { networkUtils } from './network-utils'import { system } from './system/system'@@ -8,16 +8,35 @@ export const domainHelper = {async getPublicUrl({ path }: PublicUrlParams): Promise<string> {return networkUtils.combineUrl(system.getOrThrow(AppSystemProp.FRONTEND_URL), path ?? '')},+ getBrowserLandingUrl({ path }: PublicUrlParams): string {+ const { origin } = new URL(system.getOrThrow(AppSystemProp.FRONTEND_URL))+ return networkUtils.cleanTrailingSlash(networkUtils.combineUrl(origin, path ?? ''))+ },getConfiguredPublicUrl(): string {- return cleanTrailingSlash(system.getOrThrow(AppSystemProp.FRONTEND_URL))+ return networkUtils.cleanTrailingSlash(system.getOrThrow(AppSystemProp.FRONTEND_URL))},getPublicUrlFromRequest({ req, path }: PublicUrlFromRequestParams): string {- const requestBase = networkUtils.getRequestBaseUrl(req)- const baseWithPrefix = networkUtils.combineUrl(requestBase, getConfiguredBasePath())- return cleanTrailingSlash(networkUtils.combineUrl(baseWithPrefix, path ?? ''))+ const matchedHost = matchConfiguredHost(req)+ const baseUrl = matchedHost?.kind === 'mcp'+ ? matchedHost.baseUrl+ : networkUtils.combineUrl(networkUtils.getRequestBaseUrl(req), getConfiguredBasePath())+ return networkUtils.cleanTrailingSlash(networkUtils.combineUrl(baseUrl, path ?? ''))+ },+ isMcpHostRequest({ req }: RequestParams): boolean {+ return matchConfiguredHost(req)?.kind === 'mcp'+ },+ isUnconfiguredHostRequest({ req }: RequestParams): boolean {+ return isNil(matchConfiguredHost(req))+ },+ hasMcpUrl(): boolean {+ return !isNil(system.get(AppSystemProp.MCP_URL))+ },+ getMcpUrl({ path }: PublicUrlParams): string {+ const mcpUrl = system.get(AppSystemProp.MCP_URL) ?? system.getOrThrow(AppSystemProp.FRONTEND_URL)+ return networkUtils.cleanTrailingSlash(networkUtils.combineUrl(mcpUrl, path ?? ''))},async getPublicApiUrl({ path }: PublicUrlParams): Promise<string> {- return domainHelper.getPublicUrl({ path: `/api/${cleanLeadingSlash(path ?? '')}` })+ return domainHelper.getPublicUrl({ path: `/api/${networkUtils.cleanLeadingSlash(path ?? '')}` })},async getInternalUrl({ path }: InternalUrlParams): Promise<string> {const internalUrl = system.get(AppSystemProp.INTERNAL_URL)@@ -27,7 +46,7 @@ export const domainHelper = {return this.getPublicUrl({ path })},async getInternalApiUrl({ path }: InternalUrlParams): Promise<string> {- return this.getInternalUrl({ path: `/api/${cleanLeadingSlash(path ?? '')}` })+ return this.getInternalUrl({ path: `/api/${networkUtils.cleanLeadingSlash(path ?? '')}` })},async getApiUrlForWorker({ path }: PublicUrlParams): Promise<string> {const hasWorkerModule = system.isWorker()@@ -39,23 +58,51 @@ export const domainHelper = {},}-function cleanLeadingSlash(path: string) {- return path.startsWith('/') ? path.slice(1) : path+function getConfiguredBasePath(): string {+ const { data: url } = tryCatchSync(() => new URL(system.getOrThrow(AppSystemProp.FRONTEND_URL)))+ return url && url.pathname !== '/' ? url.pathname : ''+}++function getConfiguredHosts(): ConfiguredHost[] {+ const { data: frontendUrl } = tryCatchSync(() => system.getOrThrow(AppSystemProp.FRONTEND_URL))+ const candidates: { kind: ConfiguredHostKind, baseUrl: string | null | undefined }[] = [+ { kind: 'mcp', baseUrl: system.get(AppSystemProp.MCP_URL) },+ { kind: 'frontend', baseUrl: frontendUrl },+ ]+ return candidates.flatMap(({ kind, baseUrl }) => {+ if (isNil(baseUrl)) {+ return []+ }+ const parsed = tryCatchSync(() => new URL(baseUrl))+ return parsed.error ? [] : [{+ kind,+ host: parsed.data.host.toLowerCase(),+ baseUrl: networkUtils.cleanTrailingSlash(baseUrl),+ }]+ })}-function cleanTrailingSlash(url: string) {- return url.endsWith('/') ? url.slice(0, -1) : url+function matchConfiguredHost(req: FastifyRequest): ConfiguredHost | null {+ const requestHost = networkUtils.getRequestHost(req).toLowerCase()+ return getConfiguredHosts().find((entry) => entry.host === requestHost) ?? null}-function getConfiguredBasePath(): string {- const { data: url } = tryCatchSync(() => new URL(system.getOrThrow(AppSystemProp.FRONTEND_URL)))- return url && url.pathname !== '/' ? url.pathname : ''+type ConfiguredHostKind = 'mcp' | 'frontend'++type ConfiguredHost = {+ kind: ConfiguredHostKind+ host: string+ baseUrl: string}type PublicUrlParams = {path?: string}+type RequestParams = {+ req: FastifyRequest+}+type PublicUrlFromRequestParams = {req: FastifyRequestpath?: stringdiff --git a/packages/server/api/src/app/helper/network-utils.ts b/packages/server/api/src/app/helper/network-utils.tsindex d9a927edb65..1d04861783b 100644--- a/packages/server/api/src/app/helper/network-utils.ts+++ b/packages/server/api/src/app/helper/network-utils.ts@@ -111,6 +111,8 @@ export const networkUtils = {getPublicIp,getRequestHost,getRequestBaseUrl,+ cleanLeadingSlash,+ cleanTrailingSlash,combineUrl(url: string, path: string) {const cleanedUrl = cleanTrailingSlash(url)const cleanedPath = cleanLeadingSlash(path)diff --git a/packages/server/api/src/app/helper/system-validator.ts b/packages/server/api/src/app/helper/system-validator.tsindex 2f148c38751..6ec9e31a8c7 100644--- a/packages/server/api/src/app/helper/system-validator.ts+++ b/packages/server/api/src/app/helper/system-validator.ts@@ -1,5 +1,5 @@import { inspect } from 'util'-import { isNil } from '@activepieces/core-utils'+import { isNil, tryCatchSync } from '@activepieces/core-utils'import { ApEdition, ApEnvironment, DefaultProjectRole, ExecutionMode, FileLocation, maxBarrierSignalsBounds, NetworkMode, PieceSyncMode } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { DatabaseType } from '../database/database-type'@@ -7,6 +7,7 @@ import { RedisType } from '../database/redis/types'import { s3Helper } from '../file/s3-helper'import { encryptUtils } from './encryption'import { jwtUtils } from './jwt-utils'+import { networkUtils } from './network-utils'import { system } from './system/system'import { AppSystemProp, ContainerType, SystemProp } from './system/system-props'@@ -65,6 +66,27 @@ function urlValidator(value: string) {}}+function assertMcpUrlHasDistinctHost(): void {+ const mcpUrl = system.get(AppSystemProp.MCP_URL)+ const frontendUrl = system.get(AppSystemProp.FRONTEND_URL)+ if (isNil(mcpUrl) || isNil(frontendUrl)) {+ return+ }+ const parsedMcpUrl = tryCatchSync(() => new URL(mcpUrl))+ const parsedFrontendUrl = tryCatchSync(() => new URL(frontendUrl))+ if (parsedMcpUrl.error || parsedFrontendUrl.error) {+ return+ }+ const sameHost = parsedMcpUrl.data.host.toLowerCase() === parsedFrontendUrl.data.host.toLowerCase()+ const sameBaseUrl = networkUtils.cleanTrailingSlash(mcpUrl) === networkUtils.cleanTrailingSlash(frontendUrl)+ if (sameHost && !sameBaseUrl) {+ throw new Error(JSON.stringify({+ message: 'AP_MCP_URL and AP_FRONTEND_URL share a hostname but are not the same URL, so the server cannot tell requests for one from the other. Give AP_MCP_URL its own hostname, or leave it unset.',+ docUrl: 'https://www.activepieces.com/docs/install/configuration/environment-variables',+ }))+ }+}+const systemPropValidators: {[key in SystemProp]: (value: string) => true | string} = {@@ -108,6 +130,7 @@ const systemPropValidators: {[AppSystemProp.AXIOM_TOKEN]: stringValidator,[AppSystemProp.AXIOM_DATASET]: stringValidator,[AppSystemProp.FRONTEND_URL]: urlValidator,+ [AppSystemProp.MCP_URL]: urlValidator,[AppSystemProp.CONTAINER_TYPE]: enumValidator(Object.values(ContainerType)),[AppSystemProp.PORT]: numberValidator,[AppSystemProp.CONSOLE_API_SECRET_KEY]: stringValidator,@@ -333,4 +356,5 @@ export const validateEnvPropsOnStartup = async (log: FastifyBaseLogger): Promise}}+ assertMcpUrlHasDistinctHost()}diff --git a/packages/server/api/src/app/helper/system/system-props.ts b/packages/server/api/src/app/helper/system/system-props.tsindex c1c2086e283..38a8ec6eb90 100644--- a/packages/server/api/src/app/helper/system/system-props.ts+++ b/packages/server/api/src/app/helper/system/system-props.ts@@ -141,6 +141,7 @@ export enum AppSystemProp {NETWORK_MODE = 'NETWORK_MODE',CONTAINER_TYPE = 'CONTAINER_TYPE',FRONTEND_URL = 'FRONTEND_URL',+ MCP_URL = 'MCP_URL',PORT = 'PORT',CONSOLE_API_SECRET_KEY = 'CONSOLE_API_SECRET_KEY',LOG_SAMPLE_RATE_INFO = 'LOG_SAMPLE_RATE_INFO',diff --git a/packages/server/api/src/app/mcp/mcp-server-controller.ts b/packages/server/api/src/app/mcp/mcp-server-controller.tsindex 130847739dc..afcf74fe073 100644--- a/packages/server/api/src/app/mcp/mcp-server-controller.ts+++ b/packages/server/api/src/app/mcp/mcp-server-controller.ts@@ -6,8 +6,7 @@ import { StatusCodes } from 'http-status-codes'import { z } from 'zod'import { ProjectResourceType } from '../core/security/authorization/common'import { securityAccess } from '../core/security/authorization/fastify-security'-import { system } from '../helper/system/system'-import { AppSystemProp } from '../helper/system/system-props'+import { domainHelper } from '../helper/domain-helper'import { projectService } from '../project/project-service'import { mcpServerService } from './mcp-service'import { mcpOAuthTokenService } from './oauth/token/mcp-oauth-token.service'@@ -50,9 +49,8 @@ export const mcpServerController: FastifyPluginAsyncZod = async (app) => {platformId: req.principal.platform.id,projectId: req.projectId,})- const frontendUrl = system.getOrThrow(AppSystemProp.FRONTEND_URL)return {- mcpServerUrl: `${frontendUrl}/mcp`,+ mcpServerUrl: domainHelper.getMcpUrl({ path: '/mcp' }),mcpToken,}})diff --git a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-authorize.controller.ts b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-authorize.controller.tsindex 49a8af23033..d59f2b5fa90 100644--- a/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-authorize.controller.ts+++ b/packages/server/api/src/app/mcp/oauth/code/mcp-oauth-authorize.controller.ts@@ -4,11 +4,12 @@ import { z } from 'zod'import { securityAccess } from '../../../core/security/authorization/fastify-security'import { domainHelper } from '../../../helper/domain-helper'import { JwtAudience, jwtUtils } from '../../../helper/jwt-utils'+import { networkUtils } from '../../../helper/network-utils'import { mcpOAuthClientService } from '../client/mcp-oauth-client.service'import { DEFAULT_MCP_OAUTH_SCOPES } from '../mcp-oauth-scopes'import { mcpOAuthValidation } from '../mcp-oauth-validation'-const AUTH_REQUEST_TTL_10_MINUTES_SECONDS = 10 * 60+const AUTH_REQUEST_TTL_SECONDS = 30 * 60export const mcpOAuthAuthorizeController: FastifyPluginAsyncZod = async (app) => {@@ -47,11 +48,17 @@ export const mcpOAuthAuthorizeController: FastifyPluginAsyncZod = async (app) =>type: 'mcp_auth_request',},key,- expiresInSeconds: AUTH_REQUEST_TTL_10_MINUTES_SECONDS,+ expiresInSeconds: AUTH_REQUEST_TTL_SECONDS,audience: JwtAudience.MCP_OAUTH_AUTH_REQUEST,})- const authorizePageUrl = new URL(domainHelper.getPublicUrlFromRequest({ req, path: '/mcp-authorize' }))+ if (domainHelper.hasMcpUrl() && domainHelper.isUnconfiguredHostRequest({ req })) {+ req.log.warn({ requestHost: networkUtils.getRequestHost(req) }, '[mcpOAuthAuthorizeController] Request host matches neither AP_MCP_URL nor AP_FRONTEND_URL; the proxy must forward the public hostname in X-Forwarded-Host or keep the Host header')+ }+ const consentPageUrl = domainHelper.isMcpHostRequest({ req })+ ? domainHelper.getBrowserLandingUrl({ path: '/mcp-authorize' })+ : networkUtils.combineUrl(networkUtils.getRequestBaseUrl(req), '/mcp-authorize')+ const authorizePageUrl = new URL(consentPageUrl)authorizePageUrl.searchParams.set('authRequestId', authRequestToken)return reply.redirect(authorizePageUrl.toString())diff --git a/packages/server/api/test/integration/ce/mcp/mcp-oauth-deployment-shapes.test.ts b/packages/server/api/test/integration/ce/mcp/mcp-oauth-deployment-shapes.test.tsindex b0bcc2e2149..6464227e10d 100644--- a/packages/server/api/test/integration/ce/mcp/mcp-oauth-deployment-shapes.test.ts+++ b/packages/server/api/test/integration/ce/mcp/mcp-oauth-deployment-shapes.test.ts@@ -86,7 +86,7 @@ describe('MCP OAuth deployment shapes', () => {expect(metadata.registration_endpoint).toBe('https://apps.customer.example.com/automation/register')})- it('sends the consent redirect under the prefix', async () => {+ it('sends the consent redirect to the hostname root, the only path the app can route', async () => {const client = await mcpOAuthTestHelpers.registerClient({ app, tokenEndpointAuthMethod: 'none' })const { challenge } = mcpOAuthTestHelpers.generatePkce()@@ -97,7 +97,131 @@ describe('MCP OAuth deployment shapes', () => {})expect(res.statusCode).toBe(302)- expect(res.headers.location).toMatch(/^https:\/\/apps\.customer\.example\.com\/automation\/mcp-authorize\?/)+ expect(res.headers.location).toMatch(/^https:\/\/apps\.customer\.example\.com\/mcp-authorize\?/)+ })+ })++ describe('with MCP served from its own hostname', () => {+ const DUAL_FRONTEND_URL = 'https://apps.customer.example.com/automation'+ const DUAL_MCP_URL = 'https://mcp.customer.example.com'+ const mcpHostHeaders = { 'x-forwarded-proto': 'https', 'x-forwarded-host': 'mcp.customer.example.com' }+ const frontendHostHeaders = { 'x-forwarded-proto': 'https', 'x-forwarded-host': 'apps.customer.example.com' }++ beforeAll(() => {+ const realGet = system.get.bind(system)+ const realGetOrThrow = system.getOrThrow.bind(system)+ vi.spyOn(system, 'get').mockImplementation((prop) => {+ if (prop === AppSystemProp.MCP_URL) {+ return DUAL_MCP_URL+ }+ if (prop === AppSystemProp.FRONTEND_URL) {+ return DUAL_FRONTEND_URL+ }+ return realGet(prop)+ })+ vi.spyOn(system, 'getOrThrow').mockImplementation((prop) => prop === AppSystemProp.FRONTEND_URL ? DUAL_FRONTEND_URL : realGetOrThrow(prop))+ })++ it('advertises the MCP host without the frontend path prefix', async () => {+ const metadata = await discovery(mcpHostHeaders)++ expect(metadata.issuer).toBe(DUAL_MCP_URL)+ expect(metadata.token_endpoint).toBe(`${DUAL_MCP_URL}/token`)+ expect(metadata.registration_endpoint).toBe(`${DUAL_MCP_URL}/register`)+ })++ it('keeps advertising the prefixed frontend base on the frontend host', async () => {+ const metadata = await discovery(frontendHostHeaders)++ expect(metadata.issuer).toBe(DUAL_FRONTEND_URL)+ expect(metadata.token_endpoint).toBe(`${DUAL_FRONTEND_URL}/token`)+ })++ it('points protected resource metadata at the MCP host', async () => {+ const res = await app.inject({+ method: 'GET',+ url: '/.well-known/oauth-protected-resource/mcp',+ headers: mcpHostHeaders,+ })++ expect(res.json().resource).toBe(`${DUAL_MCP_URL}/mcp`)+ expect(res.json().authorization_servers).toEqual([DUAL_MCP_URL])+ })++ it('challenges an unauthenticated MCP call on the MCP host with its own metadata URL', async () => {+ const res = await app.inject({ method: 'POST', url: '/mcp', headers: mcpHostHeaders })++ expect(res.statusCode).toBe(401)+ expect(res.headers['www-authenticate']).toContain(`${DUAL_MCP_URL}/.well-known/oauth-protected-resource/mcp`)+ })++ it('sends consent to the frontend origin, so the user signs in on the main host', async () => {+ const client = await mcpOAuthTestHelpers.registerClient({ app, tokenEndpointAuthMethod: 'none' })+ const { challenge } = mcpOAuthTestHelpers.generatePkce()++ const res = await app.inject({+ method: 'GET',+ headers: mcpHostHeaders,+ url: `/authorize?client_id=${client.client_id}&redirect_uri=${encodeURIComponent(MCP_OAUTH_REDIRECT_URI)}&response_type=code&code_challenge=${challenge}&code_challenge_method=S256`,+ })++ expect(res.statusCode).toBe(302)+ expect(res.headers.location).toMatch(/^https:\/\/apps\.customer\.example\.com\/mcp-authorize\?/)+ })++ it('names each host as the OpenID issuer, so workload tokens still match on the frontend host', async () => {+ const onMcpHost = await app.inject({ method: 'GET', url: '/.well-known/openid-configuration', headers: mcpHostHeaders })+ const onFrontendHost = await app.inject({ method: 'GET', url: '/.well-known/openid-configuration', headers: frontendHostHeaders })++ expect(onMcpHost.json().issuer).toBe(DUAL_MCP_URL)+ expect(onFrontendHost.json().issuer).toBe(DUAL_FRONTEND_URL)+ })++ it('recognises the MCP host from an unchanged Host header when the proxy sends no X-Forwarded-Host', async () => {+ const metadata = await discovery({ 'host': 'mcp.customer.example.com', 'x-forwarded-proto': 'https' })++ expect(metadata.issuer).toBe(DUAL_MCP_URL)+ })++ it('leaves consent on the request host for a host matching neither setting', async () => {+ const client = await mcpOAuthTestHelpers.registerClient({ app, tokenEndpointAuthMethod: 'none' })+ const { challenge } = mcpOAuthTestHelpers.generatePkce()++ const res = await app.inject({+ method: 'GET',+ headers: { 'x-forwarded-proto': 'https', 'x-forwarded-host': 'byo.customer.example.com' },+ url: `/authorize?client_id=${client.client_id}&redirect_uri=${encodeURIComponent(MCP_OAUTH_REDIRECT_URI)}&response_type=code&code_challenge=${challenge}&code_challenge_method=S256`,+ })++ expect(res.statusCode).toBe(302)+ expect(res.headers.location).toMatch(/^https:\/\/byo\.customer\.example\.com\/mcp-authorize\?/)+ })+ })++ describe('with an http AP_FRONTEND_URL behind a TLS-terminating proxy', () => {+ const HTTP_FRONTEND_URL = 'http://apps.customer.example.com'++ beforeAll(() => {+ vi.restoreAllMocks()+ const realGet = system.get.bind(system)+ const realGetOrThrow = system.getOrThrow.bind(system)+ vi.spyOn(system, 'get').mockImplementation((prop) => {+ if (prop === AppSystemProp.MCP_URL) {+ return undefined+ }+ if (prop === AppSystemProp.FRONTEND_URL) {+ return HTTP_FRONTEND_URL+ }+ return realGet(prop)+ })+ vi.spyOn(system, 'getOrThrow').mockImplementation((prop) => prop === AppSystemProp.FRONTEND_URL ? HTTP_FRONTEND_URL : realGetOrThrow(prop))+ })++ it('keeps the forwarded https scheme, as it did before AP_MCP_URL existed', async () => {+ const metadata = await discovery({ 'x-forwarded-proto': 'https', 'x-forwarded-host': 'apps.customer.example.com' })++ expect(metadata.issuer).toBe('https://apps.customer.example.com')+ expect(metadata.token_endpoint).toBe('https://apps.customer.example.com/token')})})})diff --git a/packages/server/api/test/integration/ee/saml-acs/saml-acs.test.ts b/packages/server/api/test/integration/ee/saml-acs/saml-acs.test.tsnew file mode 100644index 00000000000..9f3b6a8df69--- /dev/null+++ b/packages/server/api/test/integration/ee/saml-acs/saml-acs.test.ts@@ -0,0 +1,119 @@+import { UserIdentityProvider } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import { databaseConnection } from '../../../../src/app/database/database-connection'+import { system } from '../../../../src/app/helper/system/system'+import { AppSystemProp } from '../../../../src/app/helper/system/system-props'+import { createMockPlatform, createMockPlatformPlan, createMockUser, createMockUserIdentity } from '../../../helpers/mocks'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++vi.mock('../../../../src/app/ee/authentication/saml-authn/saml-client', () => ({+ createSamlClient: async () => ({+ getLoginUrl: () => 'https://idp.example.com/sso',+ parseAndValidateLoginResponse: async () => ({+ email: SSO_EMAIL,+ firstName: 'Sso',+ lastName: 'User',+ }),+ }),+ invalidateSamlClientCache: () => undefined,+}))++const PREFIXED_FRONTEND_URL = 'https://apps.customer.example.com/automation'+const SSO_EMAIL = '[email protected]'++let app: FastifyInstance+let platformId: string++async function createSamlPlatform(): Promise<string> {+ const mockUserIdentity = createMockUserIdentity({ verified: true })+ await databaseConnection().getRepository('user_identity').save(mockUserIdentity)++ const mockOwner = createMockUser({ identityId: mockUserIdentity.id, platformRole: 'ADMIN' })+ await databaseConnection().getRepository('user').save(mockOwner)++ const mockPlatform = createMockPlatform({+ ownerId: mockOwner.id,+ federatedAuthProviders: {+ saml: {+ idpMetadata: '<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"></md:EntityDescriptor>',+ idpCertificate: 'test-cert',+ },+ },+ })+ await databaseConnection().getRepository('platform').save(mockPlatform)++ mockOwner.platformId = mockPlatform.id+ await databaseConnection().getRepository('user').save(mockOwner)++ await databaseConnection().getRepository('platform_plan').save(+ createMockPlatformPlan({ platformId: mockPlatform.id, ssoEnabled: true }),+ )++ const ssoIdentity = createMockUserIdentity({+ email: SSO_EMAIL,+ verified: true,+ provider: UserIdentityProvider.SAML,+ })+ await databaseConnection().getRepository('user_identity').save(ssoIdentity)+ await databaseConnection().getRepository('user').save(createMockUser({+ identityId: ssoIdentity.id,+ platformId: mockPlatform.id,+ platformRole: 'MEMBER',+ }))++ return mockPlatform.id+}++async function acs({ host }: { host: string }): Promise<URL> {+ const response = await app.inject({+ method: 'POST',+ url: `/api/v1/authn/saml/acs?platformId=${platformId}`,+ headers: {+ 'x-forwarded-proto': 'https',+ 'x-forwarded-host': host,+ 'content-type': 'application/x-www-form-urlencoded',+ },+ payload: 'SAMLResponse=stubbed',+ })++ expect(response.statusCode).toBe(302)+ return new URL(String(response.headers.location))+}++describe('SAML ACS redirect', () => {+ beforeAll(async () => {+ app = await setupTestEnvironment({ fresh: true })+ const realGetOrThrow = system.getOrThrow.bind(system)+ vi.spyOn(system, 'getOrThrow').mockImplementation((prop) => prop === AppSystemProp.FRONTEND_URL ? PREFIXED_FRONTEND_URL : realGetOrThrow(prop))+ platformId = await createSamlPlatform()+ })++ afterAll(async () => {+ vi.restoreAllMocks()+ await teardownTestEnvironment()+ })++ it('returns the browser to /authenticate at the origin root, never under the configured prefix', async () => {+ const location = await acs({ host: 'apps.customer.example.com' })++ expect(location.origin).toBe('https://apps.customer.example.com')+ expect(location.pathname).toBe('/authenticate')+ expect(location.searchParams.get('response')).toBeTruthy()+ })++ it('carries the session response so the SPA can consume it on landing', async () => {+ const location = await acs({ host: 'apps.customer.example.com' })+ const response = JSON.parse(location.searchParams.get('response') ?? '')++ expect(response.email).toBe(SSO_EMAIL)+ expect(response.token).toBeTruthy()+ })++ it('follows the host the assertion was posted to, so a custom domain returns to itself', async () => {+ const location = await acs({ host: 'sso.customer.example.com' })++ expect(location.origin).toBe('https://sso.customer.example.com')+ expect(location.pathname).toBe('/authenticate')+ })+})diff --git a/packages/server/api/test/unit/app/helper/domain-helper.test.ts b/packages/server/api/test/unit/app/helper/domain-helper.test.tsnew file mode 100644index 00000000000..93eb3fabc63--- /dev/null+++ b/packages/server/api/test/unit/app/helper/domain-helper.test.ts@@ -0,0 +1,216 @@+import { FastifyRequest } from 'fastify'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { domainHelper } from '../../../../src/app/helper/domain-helper'+import { system } from '../../../../src/app/helper/system/system'+import { AppSystemProp } from '../../../../src/app/helper/system/system-props'++const FRONTEND_URL = 'https://apps.example.com/activepieces'+const MCP_URL = 'https://mcp.example.com'++function request({ host, forwardedProto = 'https' }: {+ host: string+ forwardedProto?: string+}): FastifyRequest {+ return {+ headers: { 'x-forwarded-host': host, 'x-forwarded-proto': forwardedProto },+ hostname: host,+ protocol: 'http',+ } as unknown as FastifyRequest+}++function stubSystemProps({ mcpUrl, frontendUrl = FRONTEND_URL }: {+ mcpUrl?: string+ frontendUrl?: string+}): void {+ const realGet = system.get.bind(system)+ const realGetOrThrow = system.getOrThrow.bind(system)+ vi.spyOn(system, 'get').mockImplementation((prop) => {+ if (prop === AppSystemProp.MCP_URL) {+ return mcpUrl+ }+ if (prop === AppSystemProp.FRONTEND_URL) {+ return frontendUrl+ }+ return realGet(prop)+ })+ vi.spyOn(system, 'getOrThrow').mockImplementation((prop) => {+ if (prop === AppSystemProp.FRONTEND_URL) {+ return frontendUrl+ }+ return realGetOrThrow(prop)+ })+}++describe('domainHelper.getPublicUrlFromRequest', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('serves the MCP base, without the frontend prefix, on the MCP host', () => {+ stubSystemProps({ mcpUrl: MCP_URL })++ const url = domainHelper.getPublicUrlFromRequest({ req: request({ host: 'mcp.example.com' }) })++ expect(url).toBe('https://mcp.example.com')+ })++ it('keeps the configured prefix on the frontend host', () => {+ stubSystemProps({ mcpUrl: MCP_URL })++ const url = domainHelper.getPublicUrlFromRequest({ req: request({ host: 'apps.example.com' }), path: '/token' })++ expect(url).toBe('https://apps.example.com/activepieces/token')+ })++ it('gives the MCP host its own path prefix when AP_MCP_URL carries one', () => {+ stubSystemProps({ mcpUrl: 'https://mcp.example.com/gateway' })++ const url = domainHelper.getPublicUrlFromRequest({ req: request({ host: 'mcp.example.com' }), path: '/authorize' })++ expect(url).toBe('https://mcp.example.com/gateway/authorize')+ })++ it('trusts the configured protocol when the proxy forwards no x-forwarded-proto', () => {+ stubSystemProps({ mcpUrl: MCP_URL })++ const url = domainHelper.getPublicUrlFromRequest({ req: request({ host: 'mcp.example.com', forwardedProto: '' }) })++ expect(url).toBe('https://mcp.example.com')+ })++ it('does not double the slash when a configured URL ends in one', () => {+ stubSystemProps({ mcpUrl: 'https://mcp.example.com/' })++ const url = domainHelper.getPublicUrlFromRequest({ req: request({ host: 'mcp.example.com' }), path: '/mcp' })++ expect(url).toBe('https://mcp.example.com/mcp')+ })++ it('falls back to the request host plus the frontend prefix for an unconfigured host', () => {+ stubSystemProps({ mcpUrl: MCP_URL })++ const url = domainHelper.getPublicUrlFromRequest({ req: request({ host: 'custom.customer.com' }), path: '/token' })++ expect(url).toBe('https://custom.customer.com/activepieces/token')+ })++ it('behaves exactly as before when AP_MCP_URL is unset', () => {+ stubSystemProps({ mcpUrl: undefined })++ expect(domainHelper.getPublicUrlFromRequest({ req: request({ host: 'mcp.example.com' }), path: '/token' }))+ .toBe('https://mcp.example.com/activepieces/token')+ expect(domainHelper.getPublicUrlFromRequest({ req: request({ host: 'apps.example.com' }), path: '/token' }))+ .toBe('https://apps.example.com/activepieces/token')+ })++ it('keeps the forwarded scheme on the frontend host when AP_FRONTEND_URL says http', () => {+ stubSystemProps({ mcpUrl: undefined, frontendUrl: 'http://apps.example.com/activepieces' })++ expect(domainHelper.getPublicUrlFromRequest({ req: request({ host: 'apps.example.com', forwardedProto: 'https' }), path: '/token' }))+ .toBe('https://apps.example.com/activepieces/token')+ })++ it('keeps the forwarded scheme on the frontend host when AP_MCP_URL is set', () => {+ stubSystemProps({ mcpUrl: MCP_URL, frontendUrl: 'http://apps.example.com/activepieces' })++ expect(domainHelper.getPublicUrlFromRequest({ req: request({ host: 'apps.example.com', forwardedProto: 'https' }), path: '/token' }))+ .toBe('https://apps.example.com/activepieces/token')+ })+})++describe('domainHelper.isMcpHostRequest', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('is true only on the MCP host', () => {+ stubSystemProps({ mcpUrl: MCP_URL })++ expect(domainHelper.isMcpHostRequest({ req: request({ host: 'mcp.example.com' }) })).toBe(true)+ expect(domainHelper.isMcpHostRequest({ req: request({ host: 'apps.example.com' }) })).toBe(false)+ expect(domainHelper.isMcpHostRequest({ req: request({ host: 'custom.customer.com' }) })).toBe(false)+ })++ it('is false everywhere when AP_MCP_URL is unset', () => {+ stubSystemProps({ mcpUrl: undefined })++ expect(domainHelper.isMcpHostRequest({ req: request({ host: 'mcp.example.com' }) })).toBe(false)+ expect(domainHelper.isMcpHostRequest({ req: request({ host: 'apps.example.com' }) })).toBe(false)+ })+})++describe('domainHelper.getMcpUrl', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('uses AP_MCP_URL when set', () => {+ stubSystemProps({ mcpUrl: MCP_URL })++ expect(domainHelper.getMcpUrl({ path: '/mcp' })).toBe('https://mcp.example.com/mcp')+ })++ it('falls back to AP_FRONTEND_URL, prefix included, when unset', () => {+ stubSystemProps({ mcpUrl: undefined })++ expect(domainHelper.getMcpUrl({ path: '/mcp' })).toBe('https://apps.example.com/activepieces/mcp')+ })++ it('does not double the slash when AP_FRONTEND_URL ends in one', () => {+ stubSystemProps({ mcpUrl: undefined, frontendUrl: 'https://apps.example.com/' })++ expect(domainHelper.getMcpUrl({ path: '/mcp' })).toBe('https://apps.example.com/mcp')+ })+})++describe('domainHelper.isUnconfiguredHostRequest', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('is false on the MCP host and on the frontend host', () => {+ stubSystemProps({ mcpUrl: MCP_URL })++ expect(domainHelper.isUnconfiguredHostRequest({ req: request({ host: 'mcp.example.com' }) })).toBe(false)+ expect(domainHelper.isUnconfiguredHostRequest({ req: request({ host: 'apps.example.com' }) })).toBe(false)+ })++ it('is true for a host that neither setting names, such as an upstream name a proxy put in Host', () => {+ stubSystemProps({ mcpUrl: MCP_URL })++ expect(domainHelper.isUnconfiguredHostRequest({ req: request({ host: 'activepieces.internal:8080' }) })).toBe(true)+ })+})++describe('domainHelper.getBrowserLandingUrl', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('drops the configured prefix, because the app router has no basename', () => {+ stubSystemProps({ mcpUrl: undefined })++ expect(domainHelper.getBrowserLandingUrl({ path: '/mcp-authorize' }))+ .toBe('https://apps.example.com/mcp-authorize')+ })++ it('is unchanged from getPublicUrl when no prefix is configured', async () => {+ stubSystemProps({ mcpUrl: undefined, frontendUrl: 'https://apps.example.com' })++ expect(domainHelper.getBrowserLandingUrl({ path: '/mcp-authorize' }))+ .toBe(await domainHelper.getPublicUrl({ path: '/mcp-authorize' }))+ })++ it('keeps a non-default port', () => {+ stubSystemProps({ mcpUrl: undefined, frontendUrl: 'https://apps.example.com:8443/activepieces' })++ expect(domainHelper.getBrowserLandingUrl({ path: '/mcp-authorize' }))+ .toBe('https://apps.example.com:8443/mcp-authorize')+ })++ it('returns the bare origin for an empty path', () => {+ stubSystemProps({ mcpUrl: undefined })++ expect(domainHelper.getBrowserLandingUrl({})).toBe('https://apps.example.com')+ })+})diff --git a/packages/server/api/test/unit/app/helper/system-validator.test.ts b/packages/server/api/test/unit/app/helper/system-validator.test.tsnew file mode 100644index 00000000000..8b843d7d23c--- /dev/null+++ b/packages/server/api/test/unit/app/helper/system-validator.test.ts@@ -0,0 +1,47 @@+import Fastify from 'fastify'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { system } from '../../../../src/app/helper/system/system'+import { AppSystemProp } from '../../../../src/app/helper/system/system-props'+import { validateEnvPropsOnStartup } from '../../../../src/app/helper/system-validator'++const FRONTEND_URL = 'https://example.com/activepieces'+const log = Fastify().log++function stubUrls({ mcpUrl }: { mcpUrl: string | undefined }): void {+ const realGet = system.get.bind(system)+ vi.spyOn(system, 'get').mockImplementation((prop) => {+ if (prop === AppSystemProp.MCP_URL) {+ return mcpUrl+ }+ if (prop === AppSystemProp.FRONTEND_URL) {+ return FRONTEND_URL+ }+ return realGet(prop)+ })+}++describe('validateEnvPropsOnStartup with AP_MCP_URL', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ it.each([+ ['the frontend host root', 'https://example.com'],+ ['another path on the frontend host', 'https://example.com/mcp'],+ ['the frontend host in another case', 'https://EXAMPLE.com'],+ ])('refuses to start when AP_MCP_URL shares the frontend hostname at %s', async (_name, mcpUrl) => {+ stubUrls({ mcpUrl })++ await expect(validateEnvPropsOnStartup(log)).rejects.toThrow('AP_MCP_URL and AP_FRONTEND_URL share a hostname')+ })++ it.each([+ ['its own hostname', 'https://mcp.example.com'],+ ['the same value as AP_FRONTEND_URL', `${FRONTEND_URL}/`],+ ['nothing', undefined],+ ])('starts when AP_MCP_URL is set to %s', async (_name, mcpUrl) => {+ stubUrls({ mcpUrl })++ await expect(validateEnvPropsOnStartup(log)).resolves.toBeUndefined()+ })+})diff --git a/packages/web/src/app/routes/authenticate/index.tsx b/packages/web/src/app/routes/authenticate/index.tsxindex da6b288710e..e59e681c8ba 100644--- a/packages/web/src/app/routes/authenticate/index.tsx+++ b/packages/web/src/app/routes/authenticate/index.tsx@@ -2,6 +2,7 @@ import { useEffect } from 'react';import { useNavigate, useLocation } from 'react-router-dom';import { authenticationSession } from '@/lib/authentication-session';+import { federatedLoginRedirect } from '@/lib/federated-login-redirect';const AuthenticatePage = () => {const navigate = useNavigate();@@ -14,7 +15,7 @@ const AuthenticatePage = () => {if (response) {const decodedResponse = JSON.parse(response);authenticationSession.saveResponse(decodedResponse, false);- navigate('/flows');+ navigate(federatedLoginRedirect.consume() ?? '/flows');}}, [response]);diff --git a/packages/web/src/app/routes/mcp-server/mcp-server-url.ts b/packages/web/src/app/routes/mcp-server/mcp-server-url.tsindex cd4786de223..05835a0a062 100644--- a/packages/web/src/app/routes/mcp-server/mcp-server-url.ts+++ b/packages/web/src/app/routes/mcp-server/mcp-server-url.ts@@ -11,8 +11,8 @@ export function useMcpServerUrl({serverUrl: string;isReachableFromInternet: boolean;} {- const { data: publicUrl } = flagsHooks.useFlag<string>(ApFlagId.PUBLIC_URL);- const base = (publicUrl ?? '').replace(/\/$/, '');+ const { data: mcpUrl } = flagsHooks.useFlag<string>(ApFlagId.MCP_URL);+ const base = (mcpUrl ?? '').replace(/\/$/, '');const path = serverType === McpServerType.PLATFORM ? '/mcp/platform' : '/mcp';return {serverUrl: `${base}${path}`,diff --git a/packages/web/src/app/routes/platform/setup/mcp/index.tsx b/packages/web/src/app/routes/platform/setup/mcp/index.tsxindex e27863fc0ec..fbf8d8d5afc 100644--- a/packages/web/src/app/routes/platform/setup/mcp/index.tsx+++ b/packages/web/src/app/routes/platform/setup/mcp/index.tsx@@ -21,7 +21,7 @@ export default function PlatformMcpPage({ section }: PlatformMcpPageProps) {} = platformMcpHooks.usePlatformMcpServer();const { mutate: updateTools, isPending: isToolsUpdating } =platformMcpHooks.useUpdatePlatformMcpTools();- const { data: publicUrl } = flagsHooks.useFlag<string>(ApFlagId.PUBLIC_URL);+ const { data: mcpUrl } = flagsHooks.useFlag<string>(ApFlagId.MCP_URL);if (isLoading) {return (@@ -51,7 +51,7 @@ export default function PlatformMcpPage({ section }: PlatformMcpPageProps) {);}- const serverUrl = `${(publicUrl ?? '').replace(/\/$/, '')}/mcp/platform`;+ const serverUrl = `${(mcpUrl ?? '').replace(/\/$/, '')}/mcp/platform`;const jsonConfiguration = {mcpServers: {diff --git a/packages/web/src/features/authentication/components/auth-landing/auth-drawer-body.tsx b/packages/web/src/features/authentication/components/auth-landing/auth-drawer-body.tsxindex 9ee13ab59d6..930bf4291f6 100644--- a/packages/web/src/features/authentication/components/auth-landing/auth-drawer-body.tsx+++ b/packages/web/src/features/authentication/components/auth-landing/auth-drawer-body.tsx@@ -54,6 +54,7 @@ import { formatUtils } from '@/lib/format-utils';import { useRedirectAfterLogin } from '@/lib/navigation-utils';import { cn } from '@/lib/utils';+import { useStartSamlLogin } from '../../hooks/use-start-saml-login';import { CheckEmailNote } from '../check-email-note';import { SamlLoginForm } from '../saml-login-form';import { SignInForm } from '../sign-in-form';@@ -224,6 +225,7 @@ function AuthStep({const passwordlessAvailable = usePasswordlessAvailable();const showThirdParty = useShowThirdPartyProviders();const thirdParty = useThirdPartyAvailability();+ const startSamlLogin = useStartSamlLogin();// The confirmation is a beat, not a screen: hold it just long enough to read// as "that worked" before the name question replaces it.@@ -425,7 +427,7 @@ function AuthStep({setSamlOpen(true);return;}- window.location.href = '/api/v1/authn/saml/login';+ startSamlLogin();}}className="transition-colors hover:text-foreground">diff --git a/packages/web/src/features/authentication/components/saml-login-form.tsx b/packages/web/src/features/authentication/components/saml-login-form.tsxindex 08fdc53ead9..f84ec64c96f 100644--- a/packages/web/src/features/authentication/components/saml-login-form.tsx+++ b/packages/web/src/features/authentication/components/saml-login-form.tsx@@ -17,6 +17,8 @@ import { Input } from '@/components/ui/input';import { samlSsoApi } from '@/features/platform-admin';import { formatUtils } from '@/lib/format-utils';+import { useStartSamlLogin } from '../hooks/use-start-saml-login';+const FormValues = z.object({email: z.string().regex(formatUtils.emailRegex, t('Email is invalid')),});@@ -34,6 +36,7 @@ export const SamlLoginForm = ({onBack,showBackButton = true,}: SamlLoginFormProps) => {+ const startSamlLogin = useStartSamlLogin();const form = useForm<FormValues>({resolver: zodResolver(FormValues),defaultValues: { email: '' },@@ -47,9 +50,7 @@ export const SamlLoginForm = ({if (!platformId) {throw new Error(t('No SAML provider found for this domain'));}- window.location.href = `/api/v1/authn/saml/login?platformId=${encodeURIComponent(- platformId,- )}`;+ startSamlLogin({ platformId });},onError: (error) => {const message =diff --git a/packages/web/src/features/authentication/components/third-party-logins.tsx b/packages/web/src/features/authentication/components/third-party-logins.tsxindex fefc0986e13..938efab0153 100644--- a/packages/web/src/features/authentication/components/third-party-logins.tsx+++ b/packages/web/src/features/authentication/components/third-party-logins.tsx@@ -17,6 +17,8 @@ import { internalErrorToast } from '@/components/ui/sonner';import { oauth2Utils } from '@/features/connections/utils/oauth2-utils';import { flagsHooks } from '@/hooks/flags-hooks';+import { useStartSamlLogin } from '../hooks/use-start-saml-login';+// Mirrors the render gates below so callers can hide surrounding chrome — an// "or" divider — or place each provider themselves. SAML is offered on cloud// for enterprise SSO, and self-hosted only once a SAML config exists.@@ -63,6 +65,7 @@ const ThirdPartyLogin = React.memo(const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);const isCloud = edition === ApEdition.CLOUD;const thirdPartyLogin = oauth2Utils.useThirdPartyLogin();+ const startSamlLogin = useStartSamlLogin();const { capture } = useTelemetry();const availability = useThirdPartyAvailability();const showProviders =@@ -139,7 +142,7 @@ const ThirdPartyLogin = React.memo(name: TelemetryEventName.FEDERATED_LOGIN_STARTED,payload: { provider: 'saml' },});- window.location.href = '/api/v1/authn/saml/login';+ startSamlLogin();}}><ThirdPartyIcon icon={SamlIcon} />diff --git a/packages/web/src/features/authentication/hooks/use-start-saml-login.ts b/packages/web/src/features/authentication/hooks/use-start-saml-login.tsnew file mode 100644index 00000000000..03e0aca850d--- /dev/null+++ b/packages/web/src/features/authentication/hooks/use-start-saml-login.ts@@ -0,0 +1,21 @@+import { isNil } from '@activepieces/core-utils';+import { useSearchParams } from 'react-router-dom';++import { federatedLoginRedirect } from '@/lib/federated-login-redirect';+import { FROM_QUERY_PARAM } from '@/lib/navigation-utils';++export function useStartSamlLogin() {+ const [searchParams] = useSearchParams();+ return ({ platformId }: StartSamlLoginParams = {}) => {+ federatedLoginRedirect.save(searchParams.get(FROM_QUERY_PARAM));+ window.location.href = isNil(platformId)+ ? SAML_LOGIN_PATH+ : `${SAML_LOGIN_PATH}?platformId=${encodeURIComponent(platformId)}`;+ };+}++const SAML_LOGIN_PATH = '/api/v1/authn/saml/login';++type StartSamlLoginParams = {+ platformId?: string;+};diff --git a/packages/web/src/lib/federated-login-redirect.ts b/packages/web/src/lib/federated-login-redirect.tsnew file mode 100644index 00000000000..9ba2d1f337c--- /dev/null+++ b/packages/web/src/lib/federated-login-redirect.ts@@ -0,0 +1,32 @@+import { isNil, tryCatchSync } from '@activepieces/core-utils';++function save(from: string | null | undefined) {+ if (!isMcpAuthorizePath(from)) {+ tryCatchSync(() => sessionStorage.removeItem(STORAGE_KEY));+ return;+ }+ tryCatchSync(() => sessionStorage.setItem(STORAGE_KEY, from));+}++function consume(): string | null {+ const { data } = tryCatchSync(() => {+ const stored = sessionStorage.getItem(STORAGE_KEY);+ sessionStorage.removeItem(STORAGE_KEY);+ return stored;+ });+ return isMcpAuthorizePath(data) ? data : null;+}++function isMcpAuthorizePath(path: string | null | undefined): path is string {+ if (isNil(path)) {+ return false;+ }+ return (+ path === MCP_AUTHORIZE_PATH || path.startsWith(`${MCP_AUTHORIZE_PATH}?`)+ );+}++const STORAGE_KEY = 'federatedLoginRedirect';+const MCP_AUTHORIZE_PATH = '/mcp-authorize';++export const federatedLoginRedirect = { save, consume };diff --git a/packages/web/test/lib/federated-login-redirect.test.ts b/packages/web/test/lib/federated-login-redirect.test.tsnew file mode 100644index 00000000000..bc27307693e--- /dev/null+++ b/packages/web/test/lib/federated-login-redirect.test.ts@@ -0,0 +1,147 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { federatedLoginRedirect } from '@/lib/federated-login-redirect';++const STORAGE_KEY = 'federatedLoginRedirect';++function makeSessionStorage(): Storage {+ const store = new Map<string, string>();+ return {+ getItem: (key: string) => store.get(key) ?? null,+ setItem: (key: string, value: string) => {+ store.set(key, value);+ },+ removeItem: (key: string) => {+ store.delete(key);+ },+ clear: () => store.clear(),+ key: () => null,+ get length() {+ return store.size;+ },+ };+}++describe('federatedLoginRedirect', () => {+ beforeEach(() => {+ vi.stubGlobal('sessionStorage', makeSessionStorage());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('round-trips the MCP consent path', () => {+ federatedLoginRedirect.save('/mcp-authorize?authRequestId=abc');++ expect(federatedLoginRedirect.consume()).toBe(+ '/mcp-authorize?authRequestId=abc',+ );+ });++ it.each([+ ['flows', '/flows'],+ ['a run deep link', '/projects/abc/runs/def'],+ ['settings', '/settings/general'],+ ['the app root', '/'],+ ])(+ 'leaves an ordinary in-app destination alone, so SSO still lands on the default page (%s)',+ (_name, value) => {+ federatedLoginRedirect.save(value);++ expect(sessionStorage.getItem(STORAGE_KEY)).toBeNull();+ expect(federatedLoginRedirect.consume()).toBeNull();+ },+ );++ it.each([+ ['prefix look-alike', '/mcp-authorized'],+ ['userinfo look-alike', '/[email protected]'],+ ['nested path', '/mcp-authorize/sub'],+ ])('refuses a path that merely starts like the consent route (%s)', (+ _name,+ value,+ ) => {+ federatedLoginRedirect.save(value);++ expect(sessionStorage.getItem(STORAGE_KEY)).toBeNull();+ expect(federatedLoginRedirect.consume()).toBeNull();+ });++ it('clears the value once consumed, so a later login is not hijacked', () => {+ federatedLoginRedirect.save('/mcp-authorize');++ expect(federatedLoginRedirect.consume()).toBe('/mcp-authorize');+ expect(federatedLoginRedirect.consume()).toBeNull();+ });++ it('clears a stored value when a later login has nothing to save', () => {+ federatedLoginRedirect.save('/mcp-authorize?authRequestId=abc');+ federatedLoginRedirect.save(null);++ expect(federatedLoginRedirect.consume()).toBeNull();+ });++ it('clears a stored value when a later login carries an off-site one', () => {+ federatedLoginRedirect.save('/mcp-authorize?authRequestId=abc');+ federatedLoginRedirect.save('//evil.com');++ expect(federatedLoginRedirect.consume()).toBeNull();+ });++ it('returns null when nothing was saved', () => {+ expect(federatedLoginRedirect.consume()).toBeNull();+ });++ it.each([+ ['protocol-relative', '//evil.com'],+ ['backslash-escaped', '/\\evil.com'],+ ['absolute url', 'https://evil.com'],+ ['bare path', 'flows'],+ ['empty', ''],+ ])('refuses to store an off-site redirect (%s)', (_name, value) => {+ federatedLoginRedirect.save(value);++ expect(sessionStorage.getItem(STORAGE_KEY)).toBeNull();+ expect(federatedLoginRedirect.consume()).toBeNull();+ });++ it.each([+ ['protocol-relative', '//evil.com'],+ ['backslash-escaped', '/\\evil.com'],+ ['absolute url', 'https://evil.com'],+ ])(+ 'refuses to return an off-site redirect planted directly in storage (%s)',+ (_name, value) => {+ sessionStorage.setItem(STORAGE_KEY, value);++ expect(federatedLoginRedirect.consume()).toBeNull();+ },+ );++ it('does not throw when sessionStorage is unavailable', () => {+ vi.stubGlobal('sessionStorage', {+ getItem: () => {+ throw new Error('denied');+ },+ setItem: () => {+ throw new Error('denied');+ },+ removeItem: () => {+ throw new Error('denied');+ },+ });++ expect(() =>+ federatedLoginRedirect.save('/mcp-authorize?authRequestId=abc'),+ ).not.toThrow();+ expect(federatedLoginRedirect.consume()).toBeNull();+ });++ it('handles null and undefined without storing anything', () => {+ federatedLoginRedirect.save(null);+ federatedLoginRedirect.save(undefined);++ expect(federatedLoginRedirect.consume()).toBeNull();+ });+});