Skip to content

The open alternative to Salesforce, designed for AI.

Implement OAuth 2.0 Dynamic Client Registration (RFC 7591) (#18608)

Félix Malfait95a35f8a1d05
diff --git a/packages/twenty-docs/docs.json b/packages/twenty-docs/docs.json
index ec68711031c..60ba3cd4c78 100644
--- a/packages/twenty-docs/docs.json
+++ b/packages/twenty-docs/docs.json
@@ -6302,6 +6302,10 @@
"source": "/developers/extend/capabilities/apps",
"destination": "/developers/extend/apps/getting-started"
},
+ {
+ "source": "/developers/extend/mcp",
+ "destination": "/user-guide/ai/capabilities/mcp"
+ },
{
"source": "/developers/local-setup",
"destination": "/developers/contribute/capabilities/local-setup"
diff --git a/packages/twenty-docs/user-guide/ai/capabilities/mcp.mdx b/packages/twenty-docs/user-guide/ai/capabilities/mcp.mdx
new file mode 100644
index 00000000000..4867dbb0faa
--- /dev/null
+++ b/packages/twenty-docs/user-guide/ai/capabilities/mcp.mdx
@@ -0,0 +1,139 @@
+---
+title: MCP Server
+description: Connect AI assistants to your Twenty workspace using the Model Context Protocol.
+---
+
+<Warning>
+MCP is currently in **alpha** and is only available on some workspaces. It may not be enabled for your workspace yet.
+</Warning>
+
+Twenty exposes an [MCP](https://modelcontextprotocol.io/) server so that AI assistants — Claude Desktop, Claude Code, Cursor, ChatGPT, and others — can read and write your CRM data through natural language.
+
+Use your **workspace URL** (the URL you use to access Twenty) as the MCP endpoint. On Twenty Cloud, your workspace URL might be `https://{mycompany}.twenty.com` or a custom domain. The server is available at:
+
+| Environment | MCP Endpoint |
+|-------------|-------------|
+| **Cloud** | `https://{your-workspace-url}/mcp` (e.g. `https://mycompany.twenty.com/mcp`) |
+| **Self-Hosted** | `https://{your-domain}/mcp` |
+
+## Authentication Methods
+
+You have two ways to authenticate your MCP client: **OAuth** (recommended) or **API Key**.
+
+### Option A — OAuth (Recommended)
+
+With OAuth, your MCP client opens a browser window for you to log in. No secrets are stored in config files, and tokens refresh automatically.
+
+<Note>
+OAuth requires an MCP client that supports the [MCP Authorization specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization). Claude Desktop, Claude Code, Cursor, and ChatGPT support it.
+</Note>
+
+Add this to your MCP client configuration, replacing `{your-workspace-url}` with your workspace host (e.g. `mycompany.twenty.com`):
+
+```json
+{
+ "mcpServers": {
+ "twenty": {
+ "type": "streamable-http",
+ "url": "https://{your-workspace-url}/mcp"
+ }
+ }
+}
+```
+
+That's it — no API key needed. When the client connects for the first time it will:
+
+1. Discover Twenty's OAuth metadata via `/.well-known/oauth-protected-resource` and `/.well-known/oauth-authorization-server`
+2. Register itself as an OAuth client via dynamic client registration (RFC 7591)
+3. Open your browser to authorize access
+4. Receive tokens and connect to the MCP server
+
+Subsequent connections reuse the stored tokens and refresh them automatically.
+
+### Option B — API Key
+
+If your MCP client does not support OAuth, or you prefer static credentials, pass an API key in the `Authorization` header:
+
+```json
+{
+ "mcpServers": {
+ "twenty": {
+ "type": "streamable-http",
+ "url": "https://{your-workspace-url}/mcp",
+ "headers": {
+ "Authorization": "Bearer YOUR_API_KEY"
+ }
+ }
+ }
+}
+```
+
+<Warning>
+Your API key grants access to workspace data. Keep it out of version control and shared dotfiles.
+</Warning>
+
+To create an API key, go to **Settings > APIs & Webhooks > + Create key**. See [APIs](/developers/extend/api#create-an-api-key) for details.
+
+## Quick Start
+
+### 1. Copy the config
+
+Go to **Settings > AI > More > MCP Server** in Twenty. Choose your authentication method (OAuth or API Key), copy the JSON snippet (it will already use your workspace URL), and paste it into your MCP client's config file.
+
+| Client | Config file location |
+|--------|---------------------|
+| **Claude Desktop** | `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows) |
+| **Claude Code** | `~/.claude.json` (user) or `.mcp.json` (project) |
+| **Cursor** | `.cursor/mcp.json` in your project, or `~/.cursor/mcp.json` globally |
+| **ChatGPT** | Turn on Developer Mode in **Settings > Apps & Connectors > Advanced settings**, then use **Create** in **Settings > Apps & Connectors** to add the MCP server |
+
+### 2. Connect
+
+Restart your MCP client (or reload the config). If using OAuth you will be redirected to Twenty to authorize access. If using an API key the connection is immediate.
+
+### 3. Start using it
+
+Ask your AI assistant to interact with your CRM:
+
+- *"Show me the 5 most recently created companies"*
+- *"Create a new person named Jane Doe at Acme Corp"*
+- *"Find all open opportunities worth more than $10k"*
+
+## Available Tools
+
+Once connected, the MCP server exposes tools that mirror the Twenty API. The recommended workflow is:
+
+1. **`get_tool_catalog`** — discover all available tools
+2. **`learn_tools`** — get the input schema for specific tools
+3. **`execute_tool`** — run a tool
+
+You don't need to remember tool names. Ask your AI assistant what it can do and it will call `get_tool_catalog` automatically.
+
+## Permissions
+
+MCP connections inherit the permissions of the authenticated user (OAuth) or the role assigned to the API key. To restrict what the MCP server can do:
+
+- **OAuth**: The user's workspace role applies.
+- **API Key**: Assign a role to the API key under **Settings > Roles**. See [Permissions](/user-guide/permissions-access/capabilities/permissions).
+
+## Self-Hosted Configuration
+
+For self-hosted instances, replace `{your-workspace-url}` with your server URL. Make sure `SERVER_URL` in your environment matches the public URL of your Twenty instance — this is used to generate the OAuth discovery metadata.
+
+```bash
+SERVER_URL=https://twenty.yourcompany.com
+```
+
+The MCP endpoint, OAuth endpoints, and discovery metadata all derive from this value.
+
+## Troubleshooting
+
+**"Unauthorized" or 401 errors**
+- OAuth: re-authorize by clearing the stored tokens in your MCP client and reconnecting.
+- API Key: verify the key is valid and hasn't expired. Regenerate it if needed.
+
+**OAuth flow doesn't open a browser**
+- Ensure your MCP client supports MCP Authorization. Fall back to the API Key method if it doesn't.
+
+**Connection timeout**
+- Confirm the MCP endpoint URL is reachable from your machine. For self-hosted instances, check that the server is running and `SERVER_URL` is set correctly.
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 959fc0bdc6e..95040531b75 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -373,6 +373,7 @@ export type ApplicationRegistration = {
export enum ApplicationRegistrationSourceType {
LOCAL = 'LOCAL',
NPM = 'NPM',
+ OAUTH_ONLY = 'OAUTH_ONLY',
TARBALL = 'TARBALL'
}
@@ -6016,6 +6017,7 @@ export type AuthorizeAppMutationVariables = Exact<{
clientId: Scalars['String'];
codeChallenge?: InputMaybe<Scalars['String']>;
redirectUrl: Scalars['String'];
+ state?: InputMaybe<Scalars['String']>;
}>;
@@ -6194,6 +6196,13 @@ export type CheckUserExistsQueryVariables = Exact<{
export type CheckUserExistsQuery = { __typename?: 'Query', checkUserExists: { __typename?: 'CheckUserExist', exists: boolean, availableWorkspacesCount: number, isEmailVerified: boolean } };
+export type FindApplicationRegistrationByClientIdQueryVariables = Exact<{
+ clientId: Scalars['String'];
+}>;
+
+
+export type FindApplicationRegistrationByClientIdQuery = { __typename?: 'Query', findApplicationRegistrationByClientId?: { __typename?: 'PublicApplicationRegistration', id: string, logoUrl?: string | null, name: string, oAuthScopes: Array<string>, websiteUrl?: string | null } | null };
+
export type GetPublicWorkspaceDataByDomainQueryVariables = Exact<{
origin: Scalars['String'];
}>;
@@ -6765,13 +6774,6 @@ export type ApplicationRegistrationTarballUrlQueryVariables = Exact<{
export type ApplicationRegistrationTarballUrlQuery = { __typename?: 'Query', applicationRegistrationTarballUrl?: string | null };
-export type FindApplicationRegistrationByClientIdQueryVariables = Exact<{
- clientId: Scalars['String'];
-}>;
-
-
-export type FindApplicationRegistrationByClientIdQuery = { __typename?: 'Query', findApplicationRegistrationByClientId?: { __typename?: 'PublicApplicationRegistration', id: string, name: string, oAuthScopes: Array<string>, websiteUrl?: string | null, logoUrl?: string | null } | null };
-
export type FindApplicationRegistrationStatsQueryVariables = Exact<{
id: Scalars['String'];
}>;
@@ -7630,7 +7632,7 @@ export const UpdateOneApplicationVariableDocument = {"kind":"Document","definiti
export const FindManyApplicationsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyApplications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"version"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistrationId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}}]}}]}}]}}]} as unknown as DocumentNode<FindManyApplicationsQuery, FindManyApplicationsQueryVariables>;
export const FindOneApplicationDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneApplication"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneApplication"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ApplicationFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Agent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"prompt"}},{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"responseFormat"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"modelConfiguration"}},{"kind":"Field","name":{"kind":"Name","value":"evaluationInputs"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ObjectMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Object"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}},{"kind":"Field","name":{"kind":"Name","value":"labelSingular"}},{"kind":"Field","name":{"kind":"Name","value":"labelPlural"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isRemote"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isUIReadOnly"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"labelIdentifierFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"imageIdentifierFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"shortcut"}},{"kind":"Field","name":{"kind":"Name","value":"isLabelSyncedWithName"}},{"kind":"Field","name":{"kind":"Name","value":"isSearchable"}},{"kind":"Field","name":{"kind":"Name","value":"duplicateCriteria"}},{"kind":"Field","name":{"kind":"Name","value":"indexMetadataList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"indexWhereClause"}},{"kind":"Field","name":{"kind":"Name","value":"indexType"}},{"kind":"Field","name":{"kind":"Name","value":"isUnique"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"indexFieldMetadataList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"order"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"fieldsList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isUIReadOnly"}},{"kind":"Field","name":{"kind":"Name","value":"isNullable"}},{"kind":"Field","name":{"kind":"Name","value":"isUnique"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"defaultValue"}},{"kind":"Field","name":{"kind":"Name","value":"options"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"isLabelSyncedWithName"}},{"kind":"Field","name":{"kind":"Name","value":"morphId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"relation"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"sourceObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"sourceFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"morphRelations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"sourceObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"sourceFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"LogicFunctionFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LogicFunction"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"runtime"}},{"kind":"Field","name":{"kind":"Name","value":"timeoutSeconds"}},{"kind":"Field","name":{"kind":"Name","value":"sourceHandlerPath"}},{"kind":"Field","name":{"kind":"Name","value":"handlerName"}},{"kind":"Field","name":{"kind":"Name","value":"toolInputSchema"}},{"kind":"Field","name":{"kind":"Name","value":"isTool"}},{"kind":"Field","name":{"kind":"Name","value":"cronTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"databaseEventTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"httpRouteTriggerSettings"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ApplicationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Application"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"version"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistrationId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationRegistration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}}]}},{"kind":"Field","name":{"kind":"Name","value":"canBeUninstalled"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRoleId"}},{"kind":"Field","name":{"kind":"Name","value":"settingsCustomTabFrontComponentId"}},{"kind":"Field","name":{"kind":"Name","value":"availablePackages"}},{"kind":"Field","name":{"kind":"Name","value":"applicationVariables"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"isSecret"}}]}},{"kind":"Field","name":{"kind":"Name","value":"agents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"objects"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ObjectMetadataFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logicFunctions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"LogicFunctionFields"}}]}}]}}]} as unknown as DocumentNode<FindOneApplicationQuery, FindOneApplicationQueryVariables>;
export const FindOneApplicationByUniversalIdentifierDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindOneApplicationByUniversalIdentifier"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findOneApplication"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<FindOneApplicationByUniversalIdentifierQuery, FindOneApplicationByUniversalIdentifierQueryVariables>;
-export const AuthorizeAppDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"authorizeApp"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"codeChallenge"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"redirectUrl"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"authorizeApp"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"clientId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}}},{"kind":"Argument","name":{"kind":"Name","value":"codeChallenge"},"value":{"kind":"Variable","name":{"kind":"Name","value":"codeChallenge"}}},{"kind":"Argument","name":{"kind":"Name","value":"redirectUrl"},"value":{"kind":"Variable","name":{"kind":"Name","value":"redirectUrl"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"redirectUrl"}}]}}]}}]} as unknown as DocumentNode<AuthorizeAppMutation, AuthorizeAppMutationVariables>;
+export const AuthorizeAppDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"authorizeApp"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"codeChallenge"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"redirectUrl"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"state"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"authorizeApp"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"clientId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}}},{"kind":"Argument","name":{"kind":"Name","value":"codeChallenge"},"value":{"kind":"Variable","name":{"kind":"Name","value":"codeChallenge"}}},{"kind":"Argument","name":{"kind":"Name","value":"redirectUrl"},"value":{"kind":"Variable","name":{"kind":"Name","value":"redirectUrl"}}},{"kind":"Argument","name":{"kind":"Name","value":"state"},"value":{"kind":"Variable","name":{"kind":"Name","value":"state"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"redirectUrl"}}]}}]}}]} as unknown as DocumentNode<AuthorizeAppMutation, AuthorizeAppMutationVariables>;
export const EmailPasswordResetLinkDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"EmailPasswordResetLink"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"email"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"emailPasswordResetLink"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"email"},"value":{"kind":"Variable","name":{"kind":"Name","value":"email"}}},{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}}]}}]}}]} as unknown as DocumentNode<EmailPasswordResetLinkMutation, EmailPasswordResetLinkMutationVariables>;
export const GenerateApiKeyTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GenerateApiKeyToken"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"apiKeyId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"expiresAt"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"generateApiKeyToken"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"apiKeyId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"apiKeyId"}}},{"kind":"Argument","name":{"kind":"Name","value":"expiresAt"},"value":{"kind":"Variable","name":{"kind":"Name","value":"expiresAt"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}}]}}]}}]} as unknown as DocumentNode<GenerateApiKeyTokenMutation, GenerateApiKeyTokenMutationVariables>;
export const GenerateTransientTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"generateTransientToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"generateTransientToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"transientToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}}]}}]}}]}}]} as unknown as DocumentNode<GenerateTransientTokenMutation, GenerateTransientTokenMutationVariables>;
@@ -7652,6 +7654,7 @@ export const UpdatePasswordViaResetTokenDocument = {"kind":"Document","definitio
export const VerifyEmailAndGetLoginTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"VerifyEmailAndGetLoginToken"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"emailVerificationToken"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"email"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"origin"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"verifyEmailAndGetLoginToken"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"emailVerificationToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"emailVerificationToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"email"},"value":{"kind":"Variable","name":{"kind":"Name","value":"email"}}},{"kind":"Argument","name":{"kind":"Name","value":"captchaToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"origin"},"value":{"kind":"Variable","name":{"kind":"Name","value":"origin"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"loginToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceUrlsFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthToken"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceUrlsFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceUrls"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}}]} as unknown as DocumentNode<VerifyEmailAndGetLoginTokenMutation, VerifyEmailAndGetLoginTokenMutationVariables>;
export const VerifyEmailAndGetWorkspaceAgnosticTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"VerifyEmailAndGetWorkspaceAgnosticToken"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"emailVerificationToken"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"email"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"verifyEmailAndGetWorkspaceAgnosticToken"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"emailVerificationToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"emailVerificationToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"email"},"value":{"kind":"Variable","name":{"kind":"Name","value":"email"}}},{"kind":"Argument","name":{"kind":"Name","value":"captchaToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"availableWorkspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspacesFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"tokens"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenPairFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspaceFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspace"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"loginToken"}},{"kind":"Field","name":{"kind":"Name","value":"inviteHash"}},{"kind":"Field","name":{"kind":"Name","value":"personalInviteToken"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"sso"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthToken"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AvailableWorkspacesFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AvailableWorkspaces"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignIn"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesForSignUp"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AvailableWorkspaceFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenPairFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthTokenPair"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessOrWorkspaceAgnosticToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"refreshToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}}]}}]} as unknown as DocumentNode<VerifyEmailAndGetWorkspaceAgnosticTokenMutation, VerifyEmailAndGetWorkspaceAgnosticTokenMutationVariables>;
export const CheckUserExistsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"CheckUserExists"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"email"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"checkUserExists"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"email"},"value":{"kind":"Variable","name":{"kind":"Name","value":"email"}}},{"kind":"Argument","name":{"kind":"Name","value":"captchaToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"exists"}},{"kind":"Field","name":{"kind":"Name","value":"availableWorkspacesCount"}},{"kind":"Field","name":{"kind":"Name","value":"isEmailVerified"}}]}}]}}]} as unknown as DocumentNode<CheckUserExistsQuery, CheckUserExistsQueryVariables>;
+export const FindApplicationRegistrationByClientIdDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindApplicationRegistrationByClientId"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findApplicationRegistrationByClientId"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"clientId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthScopes"}},{"kind":"Field","name":{"kind":"Name","value":"websiteUrl"}}]}}]}}]} as unknown as DocumentNode<FindApplicationRegistrationByClientIdQuery, FindApplicationRegistrationByClientIdQueryVariables>;
export const GetPublicWorkspaceDataByDomainDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetPublicWorkspaceDataByDomain"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"origin"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getPublicWorkspaceDataByDomain"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"origin"},"value":{"kind":"Variable","name":{"kind":"Name","value":"origin"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceUrlsFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"authProviders"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sso"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}}]}},{"kind":"Field","name":{"kind":"Name","value":"google"}},{"kind":"Field","name":{"kind":"Name","value":"magicLink"}},{"kind":"Field","name":{"kind":"Name","value":"password"}},{"kind":"Field","name":{"kind":"Name","value":"microsoft"}}]}},{"kind":"Field","name":{"kind":"Name","value":"authBypassProviders"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"google"}},{"kind":"Field","name":{"kind":"Name","value":"password"}},{"kind":"Field","name":{"kind":"Name","value":"microsoft"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceUrlsFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceUrls"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}}]} as unknown as DocumentNode<GetPublicWorkspaceDataByDomainQuery, GetPublicWorkspaceDataByDomainQueryVariables>;
export const ValidatePasswordResetTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ValidatePasswordResetToken"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"token"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"validatePasswordResetToken"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"passwordResetToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"token"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"hasPassword"}}]}}]}}]} as unknown as DocumentNode<ValidatePasswordResetTokenQuery, ValidatePasswordResetTokenQueryVariables>;
export const CancelSwitchBillingIntervalDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CancelSwitchBillingInterval"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cancelSwitchBillingInterval"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentBillingSubscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"price"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhase"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"start_date"}},{"kind":"Field","name":{"kind":"Name","value":"end_date"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptionItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasReachedCurrentPeriodCap"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"billingProduct"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}}]}}]} as unknown as DocumentNode<CancelSwitchBillingIntervalMutation, CancelSwitchBillingIntervalMutationVariables>;
@@ -7733,7 +7736,6 @@ export const TransferApplicationRegistrationOwnershipDocument = {"kind":"Documen
export const UpdateApplicationRegistrationDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateApplicationRegistration"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateApplicationRegistrationInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateApplicationRegistration"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ApplicationRegistrationFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ApplicationRegistrationFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ApplicationRegistration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"author"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthClientId"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthRedirectUris"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthScopes"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"websiteUrl"}},{"kind":"Field","name":{"kind":"Name","value":"termsUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isListed"}},{"kind":"Field","name":{"kind":"Name","value":"isFeatured"}},{"kind":"Field","name":{"kind":"Name","value":"ownerWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<UpdateApplicationRegistrationMutation, UpdateApplicationRegistrationMutationVariables>;
export const UpdateApplicationRegistrationVariableDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateApplicationRegistrationVariable"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateApplicationRegistrationVariableInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateApplicationRegistrationVariable"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"isSecret"}},{"kind":"Field","name":{"kind":"Name","value":"isRequired"}},{"kind":"Field","name":{"kind":"Name","value":"isFilled"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<UpdateApplicationRegistrationVariableMutation, UpdateApplicationRegistrationVariableMutationVariables>;
export const ApplicationRegistrationTarballUrlDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ApplicationRegistrationTarballUrl"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"applicationRegistrationTarballUrl"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}]}}]} as unknown as DocumentNode<ApplicationRegistrationTarballUrlQuery, ApplicationRegistrationTarballUrlQueryVariables>;
-export const FindApplicationRegistrationByClientIdDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindApplicationRegistrationByClientId"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findApplicationRegistrationByClientId"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"clientId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"clientId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthScopes"}},{"kind":"Field","name":{"kind":"Name","value":"websiteUrl"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}}]}}]}}]} as unknown as DocumentNode<FindApplicationRegistrationByClientIdQuery, FindApplicationRegistrationByClientIdQueryVariables>;
export const FindApplicationRegistrationStatsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindApplicationRegistrationStats"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findApplicationRegistrationStats"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"activeInstalls"}},{"kind":"Field","name":{"kind":"Name","value":"mostInstalledVersion"}},{"kind":"Field","name":{"kind":"Name","value":"versionDistribution"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"version"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}}]}}]}}]} as unknown as DocumentNode<FindApplicationRegistrationStatsQuery, FindApplicationRegistrationStatsQueryVariables>;
export const FindApplicationRegistrationVariablesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindApplicationRegistrationVariables"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"applicationRegistrationId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findApplicationRegistrationVariables"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"applicationRegistrationId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"applicationRegistrationId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"isSecret"}},{"kind":"Field","name":{"kind":"Name","value":"isRequired"}},{"kind":"Field","name":{"kind":"Name","value":"isFilled"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<FindApplicationRegistrationVariablesQuery, FindApplicationRegistrationVariablesQueryVariables>;
export const FindManyApplicationRegistrationsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyApplicationRegistrations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyApplicationRegistrations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ApplicationRegistrationFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ApplicationRegistrationFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ApplicationRegistration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"author"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthClientId"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthRedirectUris"}},{"kind":"Field","name":{"kind":"Name","value":"oAuthScopes"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"websiteUrl"}},{"kind":"Field","name":{"kind":"Name","value":"termsUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isListed"}},{"kind":"Field","name":{"kind":"Name","value":"isFeatured"}},{"kind":"Field","name":{"kind":"Name","value":"ownerWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<FindManyApplicationRegistrationsQuery, FindManyApplicationRegistrationsQueryVariables>;
diff --git a/packages/twenty-front/src/modules/auth/graphql/mutations/authorizeApp.ts b/packages/twenty-front/src/modules/auth/graphql/mutations/authorizeApp.ts
index ab2ec03e299..6e1f870d2f2 100644
--- a/packages/twenty-front/src/modules/auth/graphql/mutations/authorizeApp.ts
+++ b/packages/twenty-front/src/modules/auth/graphql/mutations/authorizeApp.ts
@@ -5,11 +5,13 @@ export const AUTHORIZE_APP = gql`
$clientId: String!
$codeChallenge: String
$redirectUrl: String!
+ $state: String
) {
authorizeApp(
clientId: $clientId
codeChallenge: $codeChallenge
redirectUrl: $redirectUrl
+ state: $state
) {
redirectUrl
}
diff --git a/packages/twenty-front/src/modules/settings/application-registrations/graphql/queries/findApplicationRegistrationByClientId.ts b/packages/twenty-front/src/modules/auth/graphql/queries/findApplicationRegistrationByClientId.ts
similarity index 100%
rename from packages/twenty-front/src/modules/settings/application-registrations/graphql/queries/findApplicationRegistrationByClientId.ts
rename to packages/twenty-front/src/modules/auth/graphql/queries/findApplicationRegistrationByClientId.ts
index f125b42c7a0..dff83a6df6d 100644
--- a/packages/twenty-front/src/modules/settings/application-registrations/graphql/queries/findApplicationRegistrationByClientId.ts
+++ b/packages/twenty-front/src/modules/auth/graphql/queries/findApplicationRegistrationByClientId.ts
@@ -4,10 +4,10 @@ export const FIND_APPLICATION_REGISTRATION_BY_CLIENT_ID = gql`
query FindApplicationRegistrationByClientId($clientId: String!) {
findApplicationRegistrationByClientId(clientId: $clientId) {
id
+ logoUrl
name
oAuthScopes
websiteUrl
- logoUrl
}
}
`;
diff --git a/packages/twenty-front/src/pages/auth/Authorize.tsx b/packages/twenty-front/src/pages/auth/Authorize.tsx
index d69debbc319..539b4fad881 100644
--- a/packages/twenty-front/src/pages/auth/Authorize.tsx
+++ b/packages/twenty-front/src/pages/auth/Authorize.tsx
@@ -99,9 +99,13 @@ export const Authorize = () => {
profile: t`Read your profile`,
};
- const clientId = searchParam.get('clientId');
- const codeChallenge = searchParam.get('codeChallenge');
- const redirectUrl = searchParam.get('redirectUrl');
+ // Support both camelCase (legacy) and standard OAuth snake_case params
+ const clientId = searchParam.get('client_id') ?? searchParam.get('clientId');
+ const codeChallenge =
+ searchParam.get('code_challenge') ?? searchParam.get('codeChallenge');
+ const redirectUrl =
+ searchParam.get('redirect_uri') ?? searchParam.get('redirectUrl');
+ const state = searchParam.get('state');
const {
data,
@@ -137,6 +141,7 @@ export const Authorize = () => {
clientId,
codeChallenge: codeChallenge ?? undefined,
redirectUrl,
+ state: state ?? undefined,
},
onCompleted: (responseData) => {
redirect(responseData.authorizeApp.redirectUrl);
diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAIMCP.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAIMCP.tsx
index 7ffcc58caac..5c624bde39f 100644
--- a/packages/twenty-front/src/pages/settings/ai/components/SettingsAIMCP.tsx
+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAIMCP.tsx
@@ -1,16 +1,22 @@
+import { useState } from 'react';
+
+import { SettingsOptionCardContentSelect } from '@/settings/components/SettingsOptions/SettingsOptionCardContentSelect';
+import { Select } from '@/ui/input/components/Select';
+import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { H2Title, IconCopy } from 'twenty-ui/display';
+import { H2Title, IconCopy, IconPlug } from 'twenty-ui/display';
import { Button, CodeEditor } from 'twenty-ui/input';
-import { Section } from 'twenty-ui/layout';
+import { Card, Section } from 'twenty-ui/layout';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { REACT_APP_SERVER_BASE_URL } from '~/config';
import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
-const StyledWrapper = styled.div`
+const StyledConfigWrapper = styled.div`
background-color: ${themeCssVariables.background.secondary};
border: 1px solid ${themeCssVariables.border.color.light};
border-radius: ${themeCssVariables.border.radius.md};
+ margin: 0 ${themeCssVariables.spacing[4]} ${themeCssVariables.spacing[4]};
`;
const StyledCopyButton = styled.div`
@@ -32,11 +38,27 @@ const StyledEditorContainer = styled.div`
}
`;
+type McpAuthMethod = 'oauth' | 'api-key';
+
export const SettingsAIMCP = () => {
const { t } = useLingui();
const { copyToClipboard } = useCopyToClipboard();
+ const [authMethod, setAuthMethod] = useState<McpAuthMethod>('oauth');
- const mcpConfig = JSON.stringify(
+ const oauthConfig = JSON.stringify(
+ {
+ mcpServers: {
+ twenty: {
+ type: 'streamable-http',
+ url: `${REACT_APP_SERVER_BASE_URL}/mcp`,
+ },
+ },
+ },
+ null,
+ 2,
+ );
+
+ const apiKeyConfig = JSON.stringify(
{
mcpServers: {
twenty: {
@@ -52,54 +74,79 @@ export const SettingsAIMCP = () => {
2,
);
+ const isOAuth = authMethod === 'oauth';
+ const activeConfig = isOAuth ? oauthConfig : apiKeyConfig;
+ const editorHeight = isOAuth ? 170 : 230;
+
+ const codeEditorOptions = {
+ readOnly: true,
+ domReadOnly: true,
+ renderLineHighlight: 'none' as const,
+ renderLineHighlightOnlyWhenFocus: false,
+ lineNumbers: 'off' as const,
+ folding: false,
+ selectionHighlight: false,
+ occurrencesHighlight: 'off' as const,
+ hover: {
+ enabled: false,
+ },
+ guides: {
+ indentation: false,
+ bracketPairs: false,
+ bracketPairsHorizontal: false,
+ },
+ padding: {
+ top: 12,
+ },
+ };
+
return (
<Section>
<H2Title
title={t`MCP Server`}
- description={t`Access your workspace data from your favorite MCP client like Claude Desktop, Windsurf or Cursor.`}
+ description={t`Access your workspace data from your favorite MCP client like Claude Desktop, Claude Code, Cursor, or ChatGPT. Once connected, try: "Show me the 5 most recently created companies" or "Create a new person named Jane Doe".`}
/>
- <StyledWrapper>
- <StyledEditorContainer style={{ position: 'relative' }}>
- <StyledCopyButton>
- <Button
- Icon={IconCopy}
- onClick={() => {
- copyToClipboard(
- mcpConfig,
- t`MCP Configuration copied to clipboard`,
- );
- }}
- type="button"
- />
- </StyledCopyButton>
- <CodeEditor
- value={mcpConfig}
- language="application/json"
- options={{
- readOnly: true,
- domReadOnly: true,
- renderLineHighlight: 'none',
- renderLineHighlightOnlyWhenFocus: false,
- lineNumbers: 'off',
- folding: false,
- selectionHighlight: false,
- occurrencesHighlight: 'off',
- hover: {
- enabled: false,
- },
- guides: {
- indentation: false,
- bracketPairs: false,
- bracketPairsHorizontal: false,
- },
- padding: {
- top: 12,
- },
- }}
- height={230}
+ <Card rounded>
+ <SettingsOptionCardContentSelect
+ Icon={IconPlug}
+ title={t`Authentication method`}
+ description={t`OAuth or API Key`}
+ >
+ <Select
+ dropdownId="mcp-auth-method-select"
+ value={authMethod}
+ onChange={(value) => setAuthMethod(value as McpAuthMethod)}
+ options={[
+ { label: t`OAuth`, value: 'oauth' },
+ { label: t`API Key`, value: 'api-key' },
+ ]}
+ selectSizeVariant="small"
+ dropdownWidth={GenericDropdownContentWidth.Medium}
/>
- </StyledEditorContainer>
- </StyledWrapper>
+ </SettingsOptionCardContentSelect>
+ <StyledConfigWrapper>
+ <StyledEditorContainer style={{ position: 'relative' }}>
+ <StyledCopyButton>
+ <Button
+ Icon={IconCopy}
+ onClick={() => {
+ copyToClipboard(
+ activeConfig,
+ t`MCP Configuration copied to clipboard`,
+ );
+ }}
+ type="button"
+ />
+ </StyledCopyButton>
+ <CodeEditor
+ value={activeConfig}
+ language="application/json"
+ options={codeEditorOptions}
+ height={editorHeight}
+ />
+ </StyledEditorContainer>
+ </StyledConfigWrapper>
+ </Card>
</Section>
);
};
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsDeveloperTab.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsDeveloperTab.tsx
index 1b1f5ae95c0..dd5af8e606c 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsDeveloperTab.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationsDeveloperTab.tsx
@@ -53,6 +53,10 @@ const SOURCE_TYPE_BADGE_CONFIG: Record<
label: 'Internal',
color: 'green',
},
+ [ApplicationRegistrationSourceType.OAUTH_ONLY]: {
+ label: 'OAuth',
+ color: 'blue',
+ },
};
export const SettingsApplicationsDeveloperTab = () => {
diff --git a/packages/twenty-sdk/src/clients/generated/metadata/schema.graphql b/packages/twenty-sdk/src/clients/generated/metadata/schema.graphql
index 7f626f55172..69e44e1e0fc 100644
--- a/packages/twenty-sdk/src/clients/generated/metadata/schema.graphql
+++ b/packages/twenty-sdk/src/clients/generated/metadata/schema.graphql
@@ -60,6 +60,7 @@ enum ApplicationRegistrationSourceType {
NPM
TARBALL
LOCAL
+ OAUTH_ONLY
}
type TwoFactorAuthenticationMethodSummary {
diff --git a/packages/twenty-sdk/src/clients/generated/metadata/schema.ts b/packages/twenty-sdk/src/clients/generated/metadata/schema.ts
index e0d7f47fe14..c6dc1576bad 100644
--- a/packages/twenty-sdk/src/clients/generated/metadata/schema.ts
+++ b/packages/twenty-sdk/src/clients/generated/metadata/schema.ts
@@ -61,7 +61,7 @@ export interface ApplicationRegistration {
__typename: 'ApplicationRegistration'
}
-export type ApplicationRegistrationSourceType = 'NPM' | 'TARBALL' | 'LOCAL'
+export type ApplicationRegistrationSourceType = 'NPM' | 'TARBALL' | 'LOCAL' | 'OAUTH_ONLY'
export interface TwoFactorAuthenticationMethodSummary {
twoFactorAuthenticationMethodId: Scalars['UUID']
@@ -8307,7 +8307,8 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
export const enumApplicationRegistrationSourceType = {
NPM: 'NPM' as const,
TARBALL: 'TARBALL' as const,
- LOCAL: 'LOCAL' as const
+ LOCAL: 'LOCAL' as const,
+ OAUTH_ONLY: 'OAUTH_ONLY' as const
}
export const enumRowLevelPermissionPredicateGroupLogicalOperator = {
diff --git a/packages/twenty-server/src/database/commands/cron-register-all.command.ts b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
index 7a6352c688e..760fea5242a 100644
--- a/packages/twenty-server/src/database/commands/cron-register-all.command.ts
+++ b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
@@ -3,6 +3,7 @@ import { Logger } from '@nestjs/common';
import { Command, CommandRunner } from 'nest-commander';
import { MarketplaceCatalogSyncCronCommand } from 'src/engine/core-modules/application/application-marketplace/crons/commands/marketplace-catalog-sync.cron.command';
+import { StaleRegistrationCleanupCronCommand } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/commands/stale-registration-cleanup.cron.command';
import { ApplicationVersionCheckCronCommand } from 'src/engine/core-modules/application/application-upgrade/crons/commands/application-version-check.cron.command';
import { EnterpriseKeyValidationCronCommand } from 'src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command';
import { EventLogCleanupCronCommand } from 'src/engine/core-modules/event-logs/cleanup/commands/event-log-cleanup.cron.command';
@@ -60,6 +61,7 @@ export class CronRegisterAllCommand extends CommandRunner {
private readonly twentyConfigService: TwentyConfigService,
private readonly marketplaceCatalogSyncCronCommand: MarketplaceCatalogSyncCronCommand,
private readonly applicationVersionCheckCronCommand: ApplicationVersionCheckCronCommand,
+ private readonly staleRegistrationCleanupCronCommand: StaleRegistrationCleanupCronCommand,
) {
super();
}
@@ -156,6 +158,10 @@ export class CronRegisterAllCommand extends CommandRunner {
name: 'EnterpriseKeyValidation',
command: this.enterpriseKeyValidationCronCommand,
},
+ {
+ name: 'StaleRegistrationCleanup',
+ command: this.staleRegistrationCleanupCronCommand,
+ },
];
let successCount = 0;
diff --git a/packages/twenty-server/src/database/commands/database-command.module.ts b/packages/twenty-server/src/database/commands/database-command.module.ts
index 7cad024640d..b06ab6db826 100644
--- a/packages/twenty-server/src/database/commands/database-command.module.ts
+++ b/packages/twenty-server/src/database/commands/database-command.module.ts
@@ -10,6 +10,7 @@ import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
import { ApiKeyModule } from 'src/engine/core-modules/api-key/api-key.module';
import { GenerateApiKeyCommand } from 'src/engine/core-modules/api-key/commands/generate-api-key.command';
import { MarketplaceModule } from 'src/engine/core-modules/application/application-marketplace/marketplace.module';
+import { StaleRegistrationCleanupModule } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/stale-registration-cleanup.module';
import { ApplicationUpgradeModule } from 'src/engine/core-modules/application/application-upgrade/application-upgrade.module';
import { EnterpriseKeyValidationCronCommand } from 'src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command';
import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
@@ -64,6 +65,7 @@ import { AutomatedTriggerModule } from 'src/modules/workflow/workflow-trigger/au
TwentyConfigModule,
MarketplaceModule,
ApplicationUpgradeModule,
+ StaleRegistrationCleanupModule,
],
providers: [
DataSeedWorkspaceCommand,
diff --git a/packages/twenty-server/src/engine/api/mcp/controllers/__tests__/mcp-core.controller.spec.ts b/packages/twenty-server/src/engine/api/mcp/controllers/__tests__/mcp-core.controller.spec.ts
index cce0bdaf54b..96fe5d0bee7 100644
--- a/packages/twenty-server/src/engine/api/mcp/controllers/__tests__/mcp-core.controller.spec.ts
+++ b/packages/twenty-server/src/engine/api/mcp/controllers/__tests__/mcp-core.controller.spec.ts
@@ -5,12 +5,15 @@ import { DEFAULT_TOOL_INPUT_SCHEMA } from 'twenty-shared/logic-function';
import { MCP_SERVER_METADATA } from 'src/engine/api/mcp/constants/mcp.const';
import { McpCoreController } from 'src/engine/api/mcp/controllers/mcp-core.controller';
import { type JsonRpc } from 'src/engine/api/mcp/dtos/json-rpc';
+import { McpAuthGuard } from 'src/engine/api/mcp/guards/mcp-auth.guard';
import { McpProtocolService } from 'src/engine/api/mcp/services/mcp-protocol.service';
import { type ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
import { AccessTokenService } from 'src/engine/core-modules/auth/token/services/access-token.service';
import { HttpExceptionHandlerService } from 'src/engine/core-modules/exception-handler/http-exception-handler.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { type UserEntity } from 'src/engine/core-modules/user/user.entity';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
import { WorkspaceCacheStorageService } from 'src/engine/workspace-cache-storage/workspace-cache-storage.service';
describe('McpCoreController', () => {
@@ -43,6 +46,15 @@ describe('McpCoreController', () => {
handleError: jest.fn(),
},
},
+ {
+ provide: JwtAuthGuard,
+ useValue: { canActivate: jest.fn().mockReturnValue(true) },
+ },
+ {
+ provide: TwentyConfigService,
+ useValue: { get: jest.fn().mockReturnValue('http://localhost:3000') },
+ },
+ McpAuthGuard,
],
}).compile();
diff --git a/packages/twenty-server/src/engine/api/mcp/controllers/mcp-core.controller.ts b/packages/twenty-server/src/engine/api/mcp/controllers/mcp-core.controller.ts
index 6d665506301..a32709c7ef0 100644
--- a/packages/twenty-server/src/engine/api/mcp/controllers/mcp-core.controller.ts
+++ b/packages/twenty-server/src/engine/api/mcp/controllers/mcp-core.controller.ts
@@ -9,6 +9,7 @@ import {
} from '@nestjs/common';
import { JsonRpc } from 'src/engine/api/mcp/dtos/json-rpc';
+import { McpAuthGuard } from 'src/engine/api/mcp/guards/mcp-auth.guard';
import { McpProtocolService } from 'src/engine/api/mcp/services/mcp-protocol.service';
import { RestApiExceptionFilter } from 'src/engine/api/rest/rest-api-exception.filter';
import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
@@ -18,12 +19,11 @@ import { AuthApiKey } from 'src/engine/decorators/auth/auth-api-key.decorator';
import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';
import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
-import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
@Controller('mcp')
-@UseGuards(JwtAuthGuard, WorkspaceAuthGuard, NoPermissionGuard)
+@UseGuards(McpAuthGuard, WorkspaceAuthGuard, NoPermissionGuard)
@UseFilters(RestApiExceptionFilter)
export class McpCoreController {
constructor(private readonly mcpProtocolService: McpProtocolService) {}
diff --git a/packages/twenty-server/src/engine/api/mcp/guards/__tests__/mcp-auth.guard.spec.ts b/packages/twenty-server/src/engine/api/mcp/guards/__tests__/mcp-auth.guard.spec.ts
new file mode 100644
index 00000000000..24d54cea7d6
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/guards/__tests__/mcp-auth.guard.spec.ts
@@ -0,0 +1,53 @@
+import { type ExecutionContext, UnauthorizedException } from '@nestjs/common';
+
+import { McpAuthGuard } from 'src/engine/api/mcp/guards/mcp-auth.guard';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
+
+describe('McpAuthGuard', () => {
+ let guard: McpAuthGuard;
+ let jwtAuthGuard: jest.Mocked<JwtAuthGuard>;
+ let twentyConfigService: jest.Mocked<TwentyConfigService>;
+
+ const mockSetHeader = jest.fn();
+ const mockContext = {
+ switchToHttp: () => ({
+ getResponse: () => ({ setHeader: mockSetHeader }),
+ getRequest: () => ({}),
+ }),
+ } as unknown as ExecutionContext;
+
+ beforeEach(() => {
+ jwtAuthGuard = {
+ canActivate: jest.fn(),
+ } as unknown as jest.Mocked<JwtAuthGuard>;
+ twentyConfigService = {
+ get: jest.fn().mockReturnValue('https://crm.example.com'),
+ } as unknown as jest.Mocked<TwentyConfigService>;
+
+ guard = new McpAuthGuard(jwtAuthGuard, twentyConfigService);
+ mockSetHeader.mockClear();
+ });
+
+ it('should return true when JwtAuthGuard passes', async () => {
+ jwtAuthGuard.canActivate.mockResolvedValue(true);
+
+ const result = await guard.canActivate(mockContext);
+
+ expect(result).toBe(true);
+ expect(mockSetHeader).not.toHaveBeenCalled();
+ });
+
+ it('should set WWW-Authenticate header and throw when auth fails', async () => {
+ jwtAuthGuard.canActivate.mockResolvedValue(false);
+
+ await expect(guard.canActivate(mockContext)).rejects.toThrow(
+ UnauthorizedException,
+ );
+
+ expect(mockSetHeader).toHaveBeenCalledWith(
+ 'WWW-Authenticate',
+ 'Bearer resource_metadata="https://crm.example.com/.well-known/oauth-protected-resource"',
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/api/mcp/guards/mcp-auth.guard.ts b/packages/twenty-server/src/engine/api/mcp/guards/mcp-auth.guard.ts
new file mode 100644
index 00000000000..3682a67802d
--- /dev/null
+++ b/packages/twenty-server/src/engine/api/mcp/guards/mcp-auth.guard.ts
@@ -0,0 +1,43 @@
+import {
+ type CanActivate,
+ type ExecutionContext,
+ Injectable,
+ UnauthorizedException,
+} from '@nestjs/common';
+
+import { type Response } from 'express';
+
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
+
+// RFC 9728: When the MCP endpoint returns 401, include a WWW-Authenticate
+// header pointing to the Protected Resource Metadata URL.
+@Injectable()
+export class McpAuthGuard implements CanActivate {
+ constructor(
+ private readonly jwtAuthGuard: JwtAuthGuard,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ async canActivate(context: ExecutionContext): Promise<boolean> {
+ const isAuthenticated = await this.jwtAuthGuard.canActivate(context);
+
+ if (!isAuthenticated) {
+ const serverUrl = this.twentyConfigService.get('SERVER_URL');
+ const resourceMetadataUrl = `${serverUrl}/.well-known/oauth-protected-resource`;
+
+ // Set the header on the response before throwing, because exception
+ // filters may not preserve custom headers from the exception payload.
+ const response = context.switchToHttp().getResponse<Response>();
+
+ response.setHeader(
+ 'WWW-Authenticate',
+ `Bearer resource_metadata="${resourceMetadataUrl}"`,
+ );
+
+ throw new UnauthorizedException();
+ }
+
+ return true;
+ }
+}
diff --git a/packages/twenty-server/src/engine/api/mcp/mcp.module.ts b/packages/twenty-server/src/engine/api/mcp/mcp.module.ts
index 4ced94e9300..cc557007a46 100644
--- a/packages/twenty-server/src/engine/api/mcp/mcp.module.ts
+++ b/packages/twenty-server/src/engine/api/mcp/mcp.module.ts
@@ -1,12 +1,15 @@
import { Module } from '@nestjs/common';
import { McpCoreController } from 'src/engine/api/mcp/controllers/mcp-core.controller';
+import { McpAuthGuard } from 'src/engine/api/mcp/guards/mcp-auth.guard';
import { McpProtocolService } from 'src/engine/api/mcp/services/mcp-protocol.service';
import { McpToolExecutorService } from 'src/engine/api/mcp/services/mcp-tool-executor.service';
import { ApiKeyModule } from 'src/engine/core-modules/api-key/api-key.module';
import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
-import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
+import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
import { ToolProviderModule } from 'src/engine/core-modules/tool-provider/tool-provider.module';
+import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
import { SkillModule } from 'src/engine/metadata-modules/skill/skill.module';
import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';
import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/workspace-cache-storage.module';
@@ -16,13 +19,19 @@ import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/
ApiKeyModule,
TokenModule,
WorkspaceCacheStorageModule,
- FeatureFlagModule,
UserRoleModule,
ToolProviderModule,
SkillModule,
+ TwentyConfigModule,
],
controllers: [McpCoreController],
exports: [McpProtocolService],
- providers: [McpProtocolService, McpToolExecutorService],
+ providers: [
+ JwtAuthGuard,
+ McpAuthGuard,
+ WorkspaceAuthGuard,
+ McpProtocolService,
+ McpToolExecutorService,
+ ],
})
export class McpModule {}
diff --git a/packages/twenty-server/src/engine/api/mcp/services/__tests__/mcp-protocol.service.spec.ts b/packages/twenty-server/src/engine/api/mcp/services/__tests__/mcp-protocol.service.spec.ts
index d63e251d03e..53906ff923b 100644
--- a/packages/twenty-server/src/engine/api/mcp/services/__tests__/mcp-protocol.service.spec.ts
+++ b/packages/twenty-server/src/engine/api/mcp/services/__tests__/mcp-protocol.service.spec.ts
@@ -1,15 +1,12 @@
import { HttpException, HttpStatus } from '@nestjs/common';
import { Test, type TestingModule } from '@nestjs/testing';
-import { FeatureFlagKey } from 'twenty-shared/types';
-
import { MCP_SERVER_METADATA } from 'src/engine/api/mcp/constants/mcp.const';
import { type JsonRpc } from 'src/engine/api/mcp/dtos/json-rpc';
import { McpProtocolService } from 'src/engine/api/mcp/services/mcp-protocol.service';
import { McpToolExecutorService } from 'src/engine/api/mcp/services/mcp-tool-executor.service';
import { type ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
-import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { EXECUTE_TOOL_TOOL_NAME } from 'src/engine/core-modules/tool-provider/tools/execute-tool.tool';
import { GET_TOOL_CATALOG_TOOL_NAME } from 'src/engine/core-modules/tool-provider/tools/get-tool-catalog.tool';
import { LEARN_TOOLS_TOOL_NAME } from 'src/engine/core-modules/tool-provider/tools/learn-tools.tool';
@@ -21,7 +18,6 @@ import { UserRoleService } from 'src/engine/metadata-modules/user-role/user-role
describe('McpProtocolService', () => {
let service: McpProtocolService;
- let featureFlagService: jest.Mocked<FeatureFlagService>;
let _toolRegistryService: jest.Mocked<ToolRegistryService>;
let userRoleService: jest.Mocked<UserRoleService>;
let mcpToolExecutorService: jest.Mocked<McpToolExecutorService>;
@@ -54,10 +50,6 @@ describe('McpProtocolService', () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
McpProtocolService,
- {
- provide: FeatureFlagService,
- useValue: { isFeatureEnabled: jest.fn() },
- },
{
provide: ToolRegistryService,
useValue: {
@@ -94,7 +86,6 @@ describe('McpProtocolService', () => {
}).compile();
service = module.get<McpProtocolService>(McpProtocolService);
- featureFlagService = module.get(FeatureFlagService);
_toolRegistryService = module.get(ToolRegistryService);
userRoleService = module.get(UserRoleService);
mcpToolExecutorService = module.get(McpToolExecutorService);
@@ -105,31 +96,6 @@ describe('McpProtocolService', () => {
expect(service).toBeDefined();
});
- describe('checkAiEnabled', () => {
- it('should not throw when AI is enabled', async () => {
- featureFlagService.isFeatureEnabled.mockResolvedValue(true);
-
- await expect(
- service.checkAiEnabled('workspace-1'),
- ).resolves.not.toThrow();
- expect(featureFlagService.isFeatureEnabled).toHaveBeenCalledWith(
- FeatureFlagKey.IS_AI_ENABLED,
- 'workspace-1',
- );
- });
-
- it('should throw when AI is disabled', async () => {
- featureFlagService.isFeatureEnabled.mockResolvedValue(false);
-
- await expect(service.checkAiEnabled('workspace-1')).rejects.toThrow(
- new HttpException(
- 'AI feature is not enabled for this workspace',
- HttpStatus.FORBIDDEN,
- ),
- );
- });
- });
-
describe('handleInitialize', () => {
it('should return correct initialization response', () => {
const requestId = '123';
@@ -198,8 +164,6 @@ describe('McpProtocolService', () => {
describe('handleMCPCoreQuery', () => {
it('should handle initialize method', async () => {
- featureFlagService.isFeatureEnabled.mockResolvedValue(true);
-
const mockRequest: JsonRpc = {
jsonrpc: '2.0',
method: 'initialize',
@@ -227,7 +191,6 @@ describe('McpProtocolService', () => {
});
it('should build a ToolSet with exactly 5 tools and pass it to executor for tools/call', async () => {
- featureFlagService.isFeatureEnabled.mockResolvedValue(true);
userRoleService.getRoleIdForUserWorkspace.mockResolvedValue(mockRoleId);
const mockToolCallResponse = {
@@ -278,7 +241,6 @@ describe('McpProtocolService', () => {
});
it('should build a ToolSet with exactly 5 tools and pass it to executor for tools/list', async () => {
- featureFlagService.isFeatureEnabled.mockResolvedValue(true);
userRoleService.getRoleIdForUserWorkspace.mockResolvedValue(mockRoleId);
mcpToolExecutorService.handleToolsListing.mockReturnValue({
@@ -315,8 +277,6 @@ describe('McpProtocolService', () => {
});
it('should handle tools/call with apiKey authentication', async () => {
- featureFlagService.isFeatureEnabled.mockResolvedValue(true);
-
const mockToolCallResponse = {
id: '123',
jsonrpc: '2.0',
@@ -346,34 +306,7 @@ describe('McpProtocolService', () => {
);
});
- it('should handle error when AI is disabled', async () => {
- featureFlagService.isFeatureEnabled.mockResolvedValue(false);
-
- const mockRequest: JsonRpc = {
- jsonrpc: '2.0',
- method: 'tools/list',
- id: '123',
- };
-
- const result = await service.handleMCPCoreQuery(mockRequest, {
- workspace: mockWorkspace,
- userWorkspaceId: mockUserWorkspaceId,
- apiKey: undefined,
- });
-
- expect(result).toEqual({
- id: '123',
- jsonrpc: '2.0',
- error: {
- ...MCP_SERVER_METADATA,
- code: HttpStatus.FORBIDDEN,
- message: 'AI feature is not enabled for this workspace',
- },
- });
- });
-
it('should handle error when tool execution fails', async () => {
- featureFlagService.isFeatureEnabled.mockResolvedValue(true);
userRoleService.getRoleIdForUserWorkspace.mockResolvedValue(mockRoleId);
mcpToolExecutorService.handleToolCall.mockRejectedValue(
diff --git a/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts b/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
index 8d4247416a6..b6b0586bf07 100644
--- a/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
+++ b/packages/twenty-server/src/engine/api/mcp/services/mcp-protocol.service.ts
@@ -2,7 +2,6 @@ import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { type ToolSet, zodSchema } from 'ai';
import { isDefined } from 'twenty-shared/utils';
-import { FeatureFlagKey } from 'twenty-shared/types';
import { type JsonRpc } from 'src/engine/api/mcp/dtos/json-rpc';
import { McpToolExecutorService } from 'src/engine/api/mcp/services/mcp-tool-executor.service';
@@ -11,7 +10,6 @@ import { type ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entit
import { ApiKeyRoleService } from 'src/engine/core-modules/api-key/services/api-key-role.service';
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
import { buildApiKeyAuthContext } from 'src/engine/core-modules/auth/utils/build-api-key-auth-context.util';
-import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { COMMON_PRELOAD_TOOLS } from 'src/engine/core-modules/tool-provider/constants/common-preload-tools.const';
import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
import {
@@ -43,7 +41,6 @@ const MCP_EXCLUDED_TOOLS = new Set(['code_interpreter', 'http_request']);
@Injectable()
export class McpProtocolService {
constructor(
- private readonly featureFlagService: FeatureFlagService,
private readonly toolRegistry: ToolRegistryService,
private readonly userRoleService: UserRoleService,
private readonly mcpToolExecutorService: McpToolExecutorService,
@@ -51,20 +48,6 @@ export class McpProtocolService {
private readonly skillService: SkillService,
) {}
- async checkAiEnabled(workspaceId: string): Promise<void> {
- const isAiEnabled = await this.featureFlagService.isFeatureEnabled(
- FeatureFlagKey.IS_AI_ENABLED,
- workspaceId,
- );
-
- if (!isAiEnabled) {
- throw new HttpException(
- 'AI feature is not enabled for this workspace',
- HttpStatus.FORBIDDEN,
- );
- }
- }
-
handleInitialize(requestId: string | number) {
return wrapJsonRpcResponse(requestId, {
result: {
@@ -184,8 +167,6 @@ export class McpProtocolService {
},
): Promise<Record<string, unknown>> {
try {
- await this.checkAiEnabled(workspace.id);
-
if (method === 'initialize') {
return this.handleInitialize(id);
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts
index fd9c98d4943..784632b88c8 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-install/application-install.service.ts
@@ -65,6 +65,17 @@ export class ApplicationInstallService {
return true;
}
+ if (
+ appRegistration.sourceType ===
+ ApplicationRegistrationSourceType.OAUTH_ONLY
+ ) {
+ this.logger.log(
+ `Skipping install for OAUTH_ONLY app ${appRegistration.universalIdentifier} (OAuth-only clients have no code artifacts)`,
+ );
+
+ return true;
+ }
+
const lockKey = `app-install:${params.workspaceId}:${appRegistration.universalIdentifier}`;
return this.cacheLockService.withLock(
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/application-oauth.module.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/application-oauth.module.ts
index 2281fffef97..e7fbc9460cc 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/application-oauth.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/application-oauth.module.ts
@@ -3,14 +3,17 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';
import { ApplicationInstallModule } from 'src/engine/core-modules/application/application-install/application-install.module';
+import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { ApplicationModule as ApplicationCoreModule } from 'src/engine/core-modules/application/application.module';
import { ApplicationOAuthResolver } from 'src/engine/core-modules/application/application-oauth/application-oauth.resolver';
import { OAuthDiscoveryController } from 'src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller';
+import { OAuthRegistrationController } from 'src/engine/core-modules/application/application-oauth/controllers/oauth-registration.controller';
import { OAuthTokenController } from 'src/engine/core-modules/application/application-oauth/controllers/oauth-token.controller';
import { OAuthService } from 'src/engine/core-modules/application/application-oauth/oauth.service';
import { ApplicationRegistrationModule } from 'src/engine/core-modules/application/application-registration/application-registration.module';
import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
+import { DomainServerConfigModule } from 'src/engine/core-modules/domain/domain-server-config/domain-server-config.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
@@ -23,19 +26,25 @@ import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/
TypeOrmModule.forFeature([
AppTokenEntity,
ApplicationEntity,
+ ApplicationRegistrationEntity,
UserWorkspaceEntity,
]),
ApplicationRegistrationModule,
ApplicationCoreModule,
ApplicationInstallModule,
TokenModule,
+ DomainServerConfigModule,
FeatureFlagModule,
PermissionsModule,
ThrottlerModule,
TwentyConfigModule,
WorkspaceCacheStorageModule,
],
- controllers: [OAuthTokenController, OAuthDiscoveryController],
+ controllers: [
+ OAuthTokenController,
+ OAuthDiscoveryController,
+ OAuthRegistrationController,
+ ],
providers: [OAuthService, ApplicationOAuthResolver],
exports: [OAuthService],
})
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
index d1a60d9e630..b3e5592491a 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts
@@ -1,23 +1,29 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ALL_OAUTH_SCOPES } from 'src/engine/core-modules/application/application-oauth/constants/oauth-scopes';
+import { DomainServerConfigService } from 'src/engine/core-modules/domain/domain-server-config/services/domain-server-config.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
@Controller('.well-known')
export class OAuthDiscoveryController {
- constructor(private readonly twentyConfigService: TwentyConfigService) {}
+ constructor(
+ private readonly twentyConfigService: TwentyConfigService,
+ private readonly domainServerConfigService: DomainServerConfigService,
+ ) {}
@Get('oauth-authorization-server')
@UseGuards(PublicEndpointGuard, NoPermissionGuard)
getAuthorizationServerMetadata() {
const serverUrl = this.twentyConfigService.get('SERVER_URL');
+ const frontUrl = this.domainServerConfigService.getFrontUrl().toString();
return {
issuer: serverUrl,
- authorization_endpoint: `${serverUrl}/authorize`,
+ authorization_endpoint: `${frontUrl.replace(/\/$/, '')}/authorize`,
token_endpoint: `${serverUrl}/oauth/token`,
+ registration_endpoint: `${serverUrl}/oauth/register`,
revocation_endpoint: `${serverUrl}/oauth/revoke`,
introspection_endpoint: `${serverUrl}/oauth/introspect`,
scopes_supported: ALL_OAUTH_SCOPES,
@@ -33,4 +39,18 @@ export class OAuthDiscoveryController {
introspection_endpoint_auth_methods_supported: ['client_secret_post'],
};
}
+
+ // RFC 9728: OAuth 2.0 Protected Resource Metadata
+ @Get('oauth-protected-resource')
+ @UseGuards(PublicEndpointGuard, NoPermissionGuard)
+ getProtectedResourceMetadata() {
+ const serverUrl = this.twentyConfigService.get('SERVER_URL');
+
+ return {
+ resource: `${serverUrl}/mcp`,
+ authorization_servers: [serverUrl],
+ scopes_supported: ALL_OAUTH_SCOPES,
+ bearer_methods_supported: ['header'],
+ };
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-registration.controller.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-registration.controller.ts
new file mode 100644
index 00000000000..4b9b75f72aa
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-registration.controller.ts
@@ -0,0 +1,199 @@
+import {
+ Body,
+ Controller,
+ HttpCode,
+ Post,
+ Req,
+ Res,
+ UseFilters,
+ UseGuards,
+ UsePipes,
+ ValidationPipe,
+} from '@nestjs/common';
+
+import { type Request, type Response } from 'express';
+import { v4 } from 'uuid';
+
+import { InjectRepository } from '@nestjs/typeorm';
+import {
+ ALL_OAUTH_SCOPES,
+ type OAuthScope,
+} from 'src/engine/core-modules/application/application-oauth/constants/oauth-scopes';
+import { OAuthRegisterInput } from 'src/engine/core-modules/application/application-oauth/dtos/oauth-register.input';
+import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
+import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
+import { AuthRestApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-rest-api-exception.filter';
+import { validateRedirectUri } from 'src/engine/core-modules/auth/utils/validate-redirect-uri.util';
+import { ThrottlerException } from 'src/engine/core-modules/throttler/throttler.exception';
+import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
+import { NodeEnvironment } from 'src/engine/core-modules/twenty-config/interfaces/node-environment.interface';
+import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
+import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
+import { Repository } from 'typeorm';
+
+// RFC 7591: 10 registrations per hour per IP
+const REGISTRATION_RATE_LIMIT_MAX =
+ process.env.NODE_ENV === NodeEnvironment.DEVELOPMENT ? 100 : 10;
+const REGISTRATION_RATE_LIMIT_WINDOW_MS = 3_600_000;
+
+const ALLOWED_GRANT_TYPES = ['authorization_code', 'refresh_token'];
+const ALLOWED_RESPONSE_TYPES = ['code'];
+
+@Controller('oauth')
+@UseFilters(AuthRestApiExceptionFilter)
+export class OAuthRegistrationController {
+ constructor(
+ @InjectRepository(ApplicationRegistrationEntity)
+ private readonly applicationRegistrationRepository: Repository<ApplicationRegistrationEntity>,
+ private readonly throttlerService: ThrottlerService,
+ ) {}
+
+ @Post('register')
+ @HttpCode(201)
+ @UseGuards(PublicEndpointGuard, NoPermissionGuard)
+ @UsePipes(new ValidationPipe())
+ async register(
+ @Body() body: OAuthRegisterInput,
+ @Req() req: Request,
+ @Res({ passthrough: true }) res: Response,
+ ) {
+ const rateLimitResult = await this.applyRateLimit(req);
+
+ if (rateLimitResult) {
+ res.status(429);
+
+ return rateLimitResult;
+ }
+
+ // Validate redirect URIs
+ for (const uri of body.redirect_uris) {
+ const result = validateRedirectUri(uri);
+
+ if (!result.valid) {
+ res.status(400);
+
+ return {
+ error: 'invalid_client_metadata',
+ error_description: result.reason,
+ };
+ }
+ }
+
+ if (body.redirect_uris.length === 0) {
+ res.status(400);
+
+ return {
+ error: 'invalid_client_metadata',
+ error_description: 'At least one redirect_uri is required',
+ };
+ }
+
+ // Validate grant_types — only authorization_code allowed for dynamic clients
+ const grantTypes = body.grant_types ?? ['authorization_code'];
+
+ for (const grantType of grantTypes) {
+ if (!ALLOWED_GRANT_TYPES.includes(grantType)) {
+ res.status(400);
+
+ return {
+ error: 'invalid_client_metadata',
+ error_description: `Unsupported grant_type: ${grantType}. Only authorization_code and refresh_token are allowed for dynamic registrations.`,
+ };
+ }
+ }
+
+ // Validate response_types
+ const responseTypes = body.response_types ?? ['code'];
+
+ for (const responseType of responseTypes) {
+ if (!ALLOWED_RESPONSE_TYPES.includes(responseType)) {
+ res.status(400);
+
+ return {
+ error: 'invalid_client_metadata',
+ error_description: `Unsupported response_type: ${responseType}`,
+ };
+ }
+ }
+
+ // Validate token_endpoint_auth_method — only 'none' for public clients
+ const tokenEndpointAuthMethod = body.token_endpoint_auth_method ?? 'none';
+
+ if (tokenEndpointAuthMethod !== 'none') {
+ res.status(400);
+
+ return {
+ error: 'invalid_client_metadata',
+ error_description:
+ 'Only token_endpoint_auth_method "none" is supported for dynamic registrations (public clients with PKCE)',
+ };
+ }
+
+ // Parse and validate scopes — cap to allowed scopes
+ const validScopes: readonly string[] = ALL_OAUTH_SCOPES;
+ const requestedScopes = body.scope
+ ? body.scope.split(' ').filter((s) => validScopes.includes(s))
+ : [...ALL_OAUTH_SCOPES];
+
+ const clientId = v4();
+
+ const registration = this.applicationRegistrationRepository.create({
+ universalIdentifier: v4(),
+ name: body.client_name,
+ description: null,
+ logoUrl: body.logo_uri ?? null,
+ author: null,
+ oAuthClientId: clientId,
+ oAuthClientSecretHash: null,
+ oAuthRedirectUris: body.redirect_uris,
+ oAuthScopes: requestedScopes as OAuthScope[],
+ createdByUserId: null,
+ ownerWorkspaceId: null,
+ sourceType: ApplicationRegistrationSourceType.OAUTH_ONLY,
+ websiteUrl: body.client_uri ?? null,
+ });
+
+ await this.applicationRegistrationRepository.save(registration);
+
+ res.setHeader('Cache-Control', 'no-store');
+ res.setHeader('Pragma', 'no-cache');
+
+ return {
+ client_id: clientId,
+ client_name: body.client_name,
+ redirect_uris: body.redirect_uris,
+ grant_types: grantTypes,
+ response_types: responseTypes,
+ token_endpoint_auth_method: tokenEndpointAuthMethod,
+ scope: requestedScopes.join(' '),
+ client_id_issued_at: Math.floor(Date.now() / 1000),
+ };
+ }
+
+ private async applyRateLimit(
+ req: Request,
+ ): Promise<{ error: string; error_description: string } | null> {
+ const rateLimitKey = `oauth-register:${req.ip}`;
+
+ try {
+ await this.throttlerService.tokenBucketThrottleOrThrow(
+ rateLimitKey,
+ 1,
+ REGISTRATION_RATE_LIMIT_MAX,
+ REGISTRATION_RATE_LIMIT_WINDOW_MS,
+ );
+
+ return null;
+ } catch (error) {
+ if (error instanceof ThrottlerException) {
+ return {
+ error: 'rate_limit_exceeded',
+ error_description:
+ 'Too many registration requests, please try again later',
+ };
+ }
+
+ throw error;
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/dtos/oauth-register.input.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/dtos/oauth-register.input.ts
new file mode 100644
index 00000000000..42e3792675f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/dtos/oauth-register.input.ts
@@ -0,0 +1,52 @@
+import {
+ ArrayMaxSize,
+ IsArray,
+ IsOptional,
+ IsString,
+ MaxLength,
+} from 'class-validator';
+
+// RFC 7591: OAuth 2.0 Dynamic Client Registration
+export class OAuthRegisterInput {
+ @IsString()
+ @MaxLength(256)
+ client_name: string;
+
+ @IsArray()
+ @IsString({ each: true })
+ @ArrayMaxSize(20)
+ @MaxLength(2048, { each: true })
+ redirect_uris: string[];
+
+ @IsOptional()
+ @IsArray()
+ @IsString({ each: true })
+ @ArrayMaxSize(5)
+ grant_types?: string[];
+
+ @IsOptional()
+ @IsArray()
+ @IsString({ each: true })
+ @ArrayMaxSize(5)
+ response_types?: string[];
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(50)
+ token_endpoint_auth_method?: string;
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(256)
+ scope?: string;
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(2048)
+ client_uri?: string;
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(2048)
+ logo_uri?: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/commands/stale-registration-cleanup.cron.command.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/commands/stale-registration-cleanup.cron.command.ts
new file mode 100644
index 00000000000..a731431582a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/commands/stale-registration-cleanup.cron.command.ts
@@ -0,0 +1,33 @@
+import { Command, CommandRunner } from 'nest-commander';
+
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { STALE_REGISTRATION_CLEANUP_CRON_PATTERN } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-cron-pattern.constant';
+import { StaleRegistrationCleanupCronJob } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/crons/stale-registration-cleanup.cron.job';
+
+@Command({
+ name: 'cron:stale-registration-cleanup',
+ description:
+ 'Starts a cron job to clean up stale OAuth-only application registrations',
+})
+export class StaleRegistrationCleanupCronCommand extends CommandRunner {
+ constructor(
+ @InjectMessageQueue(MessageQueue.cronQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {
+ super();
+ }
+
+ async run(): Promise<void> {
+ await this.messageQueueService.addCron<undefined>({
+ jobName: StaleRegistrationCleanupCronJob.name,
+ data: undefined,
+ options: {
+ repeat: {
+ pattern: STALE_REGISTRATION_CLEANUP_CRON_PATTERN,
+ },
+ },
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-batch-size.constant.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-batch-size.constant.ts
new file mode 100644
index 00000000000..43e28ad0fb1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-batch-size.constant.ts
@@ -0,0 +1 @@
+export const STALE_REGISTRATION_CLEANUP_BATCH_SIZE = 100;
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-cron-pattern.constant.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-cron-pattern.constant.ts
new file mode 100644
index 00000000000..7b7dcf9075a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-cron-pattern.constant.ts
@@ -0,0 +1,2 @@
+// Runs daily at 02:30 AM UTC
+export const STALE_REGISTRATION_CLEANUP_CRON_PATTERN = '30 2 * * *';
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-grace-period-days.constant.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-grace-period-days.constant.ts
new file mode 100644
index 00000000000..25b2bb195a2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-grace-period-days.constant.ts
@@ -0,0 +1 @@
+export const STALE_REGISTRATION_GRACE_PERIOD_DAYS = 30;
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/crons/stale-registration-cleanup.cron.job.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/crons/stale-registration-cleanup.cron.job.ts
new file mode 100644
index 00000000000..60d9bf69177
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/crons/stale-registration-cleanup.cron.job.ts
@@ -0,0 +1,41 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { STALE_REGISTRATION_CLEANUP_CRON_PATTERN } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-cron-pattern.constant';
+import { StaleRegistrationCleanupService } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/services/stale-registration-cleanup.service';
+
+@Injectable()
+@Processor(MessageQueue.cronQueue)
+export class StaleRegistrationCleanupCronJob {
+ private readonly logger = new Logger(StaleRegistrationCleanupCronJob.name);
+
+ constructor(
+ private readonly staleRegistrationCleanupService: StaleRegistrationCleanupService,
+ private readonly exceptionHandlerService: ExceptionHandlerService,
+ ) {}
+
+ @Process(StaleRegistrationCleanupCronJob.name)
+ @SentryCronMonitor(
+ StaleRegistrationCleanupCronJob.name,
+ STALE_REGISTRATION_CLEANUP_CRON_PATTERN,
+ )
+ async handle(): Promise<void> {
+ this.logger.log('Starting stale OAuth registration cleanup');
+
+ try {
+ const deletedCount =
+ await this.staleRegistrationCleanupService.cleanupStaleRegistrations();
+
+ this.logger.log(
+ `Stale OAuth registration cleanup completed: ${deletedCount} registration(s) deleted`,
+ );
+ } catch (error) {
+ this.exceptionHandlerService.captureExceptions([error]);
+ throw error;
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/services/stale-registration-cleanup.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/services/stale-registration-cleanup.service.ts
new file mode 100644
index 00000000000..6a50107b355
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/services/stale-registration-cleanup.service.ts
@@ -0,0 +1,131 @@
+import { Injectable, Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { In, Repository } from 'typeorm';
+
+import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
+import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
+import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
+import { STALE_REGISTRATION_CLEANUP_BATCH_SIZE } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-cleanup-batch-size.constant';
+import { STALE_REGISTRATION_GRACE_PERIOD_DAYS } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/constants/stale-registration-grace-period-days.constant';
+
+@Injectable()
+export class StaleRegistrationCleanupService {
+ private readonly logger = new Logger(StaleRegistrationCleanupService.name);
+
+ constructor(
+ @InjectRepository(ApplicationRegistrationEntity)
+ private readonly applicationRegistrationRepository: Repository<ApplicationRegistrationEntity>,
+ @InjectRepository(ApplicationEntity)
+ private readonly applicationRepository: Repository<ApplicationEntity>,
+ ) {}
+
+ async cleanupStaleRegistrations(): Promise<number> {
+ const cutoffDate = this.calculateCutoffDate();
+ let totalDeleted = 0;
+ let lastCreatedAt: Date | undefined;
+
+ while (true) {
+ const staleRegistrations = await this.findStaleRegistrationBatch(
+ cutoffDate,
+ STALE_REGISTRATION_CLEANUP_BATCH_SIZE,
+ lastCreatedAt,
+ );
+
+ if (staleRegistrations.length === 0) {
+ break;
+ }
+
+ lastCreatedAt =
+ staleRegistrations[staleRegistrations.length - 1].createdAt;
+
+ const staleIds = staleRegistrations.map(
+ (registration) => registration.id,
+ );
+
+ // Filter out registrations that have active (non-deleted) installations
+ const registrationsWithInstallations = await this.applicationRepository
+ .createQueryBuilder('application')
+ .select('application.applicationRegistrationId')
+ .where(
+ 'application.applicationRegistrationId IN (:...registrationIds)',
+ { registrationIds: staleIds },
+ )
+ .andWhere('application.deletedAt IS NULL')
+ .groupBy('application.applicationRegistrationId')
+ .getRawMany<{ application_applicationRegistrationId: string }>();
+
+ const registrationIdsWithInstallations = new Set(
+ registrationsWithInstallations.map(
+ (row) => row.application_applicationRegistrationId,
+ ),
+ );
+
+ const idsToDelete = staleIds.filter(
+ (id) => !registrationIdsWithInstallations.has(id),
+ );
+
+ if (idsToDelete.length > 0) {
+ await this.applicationRegistrationRepository.softDelete({
+ id: In(idsToDelete),
+ });
+
+ this.logger.log(
+ `Deleted ${idsToDelete.length} stale OAuth registration(s)`,
+ );
+
+ totalDeleted += idsToDelete.length;
+ }
+
+ if (staleRegistrations.length < STALE_REGISTRATION_CLEANUP_BATCH_SIZE) {
+ break;
+ }
+ }
+
+ return totalDeleted;
+ }
+
+ private async findStaleRegistrationBatch(
+ cutoffDate: Date,
+ batchSize: number,
+ afterCreatedAt?: Date,
+ ): Promise<Array<{ id: string; createdAt: Date }>> {
+ const queryBuilder = this.applicationRegistrationRepository
+ .createQueryBuilder('registration')
+ .select('registration.id', 'id')
+ .addSelect('registration.createdAt', 'createdAt')
+ .where('registration.sourceType = :sourceType', {
+ sourceType: ApplicationRegistrationSourceType.OAUTH_ONLY,
+ })
+ .andWhere('registration.createdAt < :cutoffDate', { cutoffDate })
+ .orderBy('registration.createdAt', 'ASC')
+ .take(batchSize);
+
+ if (afterCreatedAt) {
+ queryBuilder.andWhere('registration.createdAt > :afterCreatedAt', {
+ afterCreatedAt,
+ });
+ }
+
+ const rows = await queryBuilder.getRawMany<{
+ id: string;
+ createdAt: Date;
+ }>();
+
+ return rows.map((row) => ({
+ id: row.id,
+ createdAt: new Date(row.createdAt),
+ }));
+ }
+
+ private calculateCutoffDate(): Date {
+ const cutoffDate = new Date();
+
+ cutoffDate.setUTCHours(0, 0, 0, 0);
+ cutoffDate.setUTCDate(
+ cutoffDate.getUTCDate() - STALE_REGISTRATION_GRACE_PERIOD_DAYS,
+ );
+
+ return cutoffDate;
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/stale-registration-cleanup.module.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/stale-registration-cleanup.module.ts
new file mode 100644
index 00000000000..1047dcb79da
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/stale-registration-cleanup/stale-registration-cleanup.module.ts
@@ -0,0 +1,24 @@
+import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
+
+import { ApplicationRegistrationEntity } from 'src/engine/core-modules/application/application-registration/application-registration.entity';
+import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
+import { StaleRegistrationCleanupCronCommand } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/commands/stale-registration-cleanup.cron.command';
+import { StaleRegistrationCleanupCronJob } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/crons/stale-registration-cleanup.cron.job';
+import { StaleRegistrationCleanupService } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/services/stale-registration-cleanup.service';
+
+@Module({
+ imports: [
+ TypeOrmModule.forFeature([
+ ApplicationRegistrationEntity,
+ ApplicationEntity,
+ ]),
+ ],
+ providers: [
+ StaleRegistrationCleanupService,
+ StaleRegistrationCleanupCronJob,
+ StaleRegistrationCleanupCronCommand,
+ ],
+ exports: [StaleRegistrationCleanupCronCommand],
+})
+export class StaleRegistrationCleanupModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-package/application-package-fetcher.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-package/application-package-fetcher.service.ts
index 21e9bfb5033..1e6fb73aa14 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-package/application-package-fetcher.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-package/application-package-fetcher.service.ts
@@ -92,6 +92,7 @@ export class ApplicationPackageFetcherService implements OnModuleInit {
case ApplicationRegistrationSourceType.TARBALL:
return this.resolveFromTarball(appRegistration);
case ApplicationRegistrationSourceType.LOCAL:
+ case ApplicationRegistrationSourceType.OAUTH_ONLY:
return null;
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum.ts
index 2a4b755faa8..7a262f1e923 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum.ts
@@ -4,6 +4,7 @@ export enum ApplicationRegistrationSourceType {
NPM = 'npm',
TARBALL = 'tarball',
LOCAL = 'local',
+ OAUTH_ONLY = 'oauth-only',
}
registerEnumType(ApplicationRegistrationSourceType, {
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-upgrade/application-upgrade.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-upgrade/application-upgrade.service.ts
index 325e285e0fe..6e7cce3702c 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-upgrade/application-upgrade.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-upgrade/application-upgrade.service.ts
@@ -101,10 +101,13 @@ export class ApplicationUpgradeService {
if (
appRegistration.sourceType === ApplicationRegistrationSourceType.LOCAL ||
- appRegistration.sourceType === ApplicationRegistrationSourceType.TARBALL
+ appRegistration.sourceType ===
+ ApplicationRegistrationSourceType.TARBALL ||
+ appRegistration.sourceType ===
+ ApplicationRegistrationSourceType.OAUTH_ONLY
) {
throw new ApplicationException(
- 'Cannot upgrade an app installed from a tarball or local source',
+ 'Cannot upgrade an app installed from a tarball, local source, or OAuth-only registration',
ApplicationExceptionCode.UPGRADE_FAILED,
);
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/validate-redirect-uri.util.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/validate-redirect-uri.util.spec.ts
index 75e94d186c0..761b1eaa300 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/validate-redirect-uri.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/validate-redirect-uri.util.spec.ts
@@ -53,6 +53,30 @@ describe('validateRedirectUri', () => {
}
});
+ it('should accept cursor:// custom scheme for desktop app OAuth', () => {
+ const result = validateRedirectUri(
+ 'cursor://anysphere.cursor-mcp/oauth/callback',
+ );
+
+ expect(result.valid).toBe(true);
+ });
+
+ it('should accept vscode:// custom scheme', () => {
+ const result = validateRedirectUri('vscode://vscode.github/oauth/callback');
+
+ expect(result.valid).toBe(true);
+ });
+
+ it('should reject unknown custom schemes', () => {
+ const result = validateRedirectUri('evilapp://callback');
+
+ expect(result.valid).toBe(false);
+
+ if (!result.valid) {
+ expect(result.reason).toContain('allowed custom scheme');
+ }
+ });
+
it('should accept HTTPS with query parameters', () => {
const result = validateRedirectUri(
'https://example.com/callback?state=abc',
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/validate-redirect-uri.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/validate-redirect-uri.util.ts
index acb39fb2c34..357e5ed4d3d 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/utils/validate-redirect-uri.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/validate-redirect-uri.util.ts
@@ -1,4 +1,7 @@
// RFC 6749 redirect URI validation: must be absolute, HTTPS (except localhost), no fragments
+// Custom URI schemes (cursor://, vscode://) allowed for desktop app OAuth flows
+const ALLOWED_CUSTOM_SCHEMES = ['cursor:', 'vscode:', 'code:'];
+
export const validateRedirectUri = (
uri: string,
): { valid: true; parsed: URL } | { valid: false; reason: string } => {
@@ -12,11 +15,14 @@ export const validateRedirectUri = (
const isLocalhost =
parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';
+ const isAllowedCustomScheme = ALLOWED_CUSTOM_SCHEMES.includes(
+ parsed.protocol,
+ );
- if (parsed.protocol !== 'https:' && !isLocalhost) {
+ if (parsed.protocol !== 'https:' && !isLocalhost && !isAllowedCustomScheme) {
return {
valid: false,
- reason: `Redirect URIs must use HTTPS (except localhost): ${uri}`,
+ reason: `Redirect URIs must use HTTPS (except localhost) or an allowed custom scheme: ${uri}`,
};
}
diff --git a/packages/twenty-server/src/engine/guards/jwt-auth.guard.ts b/packages/twenty-server/src/engine/guards/jwt-auth.guard.ts
index 62f532e10fd..a5aaadf0a8f 100644
--- a/packages/twenty-server/src/engine/guards/jwt-auth.guard.ts
+++ b/packages/twenty-server/src/engine/guards/jwt-auth.guard.ts
@@ -48,7 +48,10 @@ export class JwtAuthGuard implements CanActivate {
return true;
} catch (error) {
- this.logger.warn(`Auth failed with error: ${error}`);
+ const errorMessage =
+ error instanceof Error ? error.message : String(error);
+
+ this.logger.warn(`Auth failed: ${errorMessage}`);
return false;
}
diff --git a/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts b/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts
index 24f61a0f5d9..6842535a515 100644
--- a/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts
+++ b/packages/twenty-server/src/engine/guards/workspace-auth.guard.ts
@@ -1,15 +1,28 @@
-import { type CanActivate, type ExecutionContext } from '@nestjs/common';
-import { GqlExecutionContext } from '@nestjs/graphql';
+import {
+ type CanActivate,
+ type ExecutionContext,
+ Injectable,
+} from '@nestjs/common';
import { type Observable } from 'rxjs';
+import { getRequest } from 'src/utils/extract-request';
+
+@Injectable()
export class WorkspaceAuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
- const ctx = GqlExecutionContext.create(context);
- const request = ctx.getContext().req;
+ const request = getRequest(context);
+
+ if (!request) {
+ return false;
+ }
+
+ if (!request.workspace) {
+ return false;
+ }
- return request.workspace !== undefined;
+ return true;
}
}