Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: completed credential type handling
Sheen Capadnganc68e73a51f78
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 462c2c8e94..057c77d58a 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -35,6 +35,9 @@ import {TAiMcpServerTools,TAiMcpServerToolsInsert,TAiMcpServerToolsUpdate,+ TAiMcpServerUserCredentials,+ TAiMcpServerUserCredentialsInsert,+ TAiMcpServerUserCredentialsUpdate,TApiKeys,TApiKeysInsert,TApiKeysUpdate,@@ -1511,5 +1514,10 @@ declare module "knex/types/tables" {TAiMcpEndpointServerToolsInsert,TAiMcpEndpointServerToolsUpdate>;+ [TableName.AiMcpServerUserCredential]: KnexOriginal.CompositeTableType<+ TAiMcpServerUserCredentials,+ TAiMcpServerUserCredentialsInsert,+ TAiMcpServerUserCredentialsUpdate+ >;}}diff --git a/backend/src/db/migrations/20251204160117_add-ai-mcp-product.ts b/backend/src/db/migrations/20251204160117_add-ai-mcp-product.tsindex f67d53bd65..9b58a673fa 100644--- a/backend/src/db/migrations/20251204160117_add-ai-mcp-product.ts+++ b/backend/src/db/migrations/20251204160117_add-ai-mcp-product.ts@@ -14,6 +14,7 @@ export async function up(knex: Knex): Promise<void> {t.string("credentialMode");t.string("authMethod");t.binary("encryptedCredentials");+ t.binary("encryptedOauthConfig"); // Stores client ID/secret for OAuth servers without DCRt.string("projectId").notNullable();t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");t.timestamps(true, true, true);@@ -69,9 +70,28 @@ export async function up(knex: Knex): Promise<void> {t.unique(["aiMcpEndpointId", "aiMcpServerToolId"]);});}++ // Store user OAuth credentials for MCP servers with "personal" credential mode+ if (!(await knex.schema.hasTable(TableName.AiMcpServerUserCredential))) {+ await knex.schema.createTable(TableName.AiMcpServerUserCredential, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("userId").notNullable();+ t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");+ t.uuid("aiMcpServerId").notNullable();+ t.foreign("aiMcpServerId").references("id").inTable(TableName.AiMcpServer).onDelete("CASCADE");+ t.binary("encryptedCredentials").notNullable();+ t.timestamps(true, true, true);+ t.unique(["userId", "aiMcpServerId"]);+ });++ await createOnUpdateTrigger(knex, TableName.AiMcpServerUserCredential);+ }}export async function down(knex: Knex): Promise<void> {+ // await dropOnUpdateTrigger(knex, TableName.AiMcpServerUserCredential);+ await knex.schema.dropTableIfExists(TableName.AiMcpServerUserCredential);+await knex.schema.dropTableIfExists(TableName.AiMcpEndpointServerTool);await knex.schema.dropTableIfExists(TableName.AiMcpEndpointServer);diff --git a/backend/src/db/schemas/ai-mcp-server-user-credentials.ts b/backend/src/db/schemas/ai-mcp-server-user-credentials.tsnew file mode 100644index 0000000000..cc247d60f9--- /dev/null+++ b/backend/src/db/schemas/ai-mcp-server-user-credentials.ts@@ -0,0 +1,28 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const AiMcpServerUserCredentialsSchema = z.object({+ id: z.string().uuid(),+ userId: z.string().uuid(),+ aiMcpServerId: z.string().uuid(),+ encryptedCredentials: zodBuffer,+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAiMcpServerUserCredentials = z.infer<typeof AiMcpServerUserCredentialsSchema>;+export type TAiMcpServerUserCredentialsInsert = Omit<+ z.input<typeof AiMcpServerUserCredentialsSchema>,+ TImmutableDBKeys+>;+export type TAiMcpServerUserCredentialsUpdate = Partial<+ Omit<z.input<typeof AiMcpServerUserCredentialsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/ai-mcp-servers.ts b/backend/src/db/schemas/ai-mcp-servers.tsindex ea92a450d6..bc751c616e 100644--- a/backend/src/db/schemas/ai-mcp-servers.ts+++ b/backend/src/db/schemas/ai-mcp-servers.ts@@ -18,6 +18,7 @@ export const AiMcpServersSchema = z.object({credentialMode: z.string().nullable().optional(),authMethod: z.string().nullable().optional(),encryptedCredentials: zodBuffer.nullable().optional(),+ encryptedOauthConfig: zodBuffer.nullable().optional(),projectId: z.string(),createdAt: z.date(),updatedAt: z.date()diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 4d19832f44..f8fc79bbaa 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -8,6 +8,7 @@ export * from "./ai-mcp-endpoint-server-tools";export * from "./ai-mcp-endpoint-servers";export * from "./ai-mcp-endpoints";export * from "./ai-mcp-server-tools";+export * from "./ai-mcp-server-user-credentials";export * from "./ai-mcp-servers";export * from "./api-keys";export * from "./app-connections";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex b4b2b7d2cd..b6cf879de3 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -228,6 +228,7 @@ export enum TableName {// AIAiMcpServer = "ai_mcp_servers",AiMcpServerTool = "ai_mcp_server_tools",+ AiMcpServerUserCredential = "ai_mcp_server_user_credentials",AiMcpEndpoint = "ai_mcp_endpoints",AiMcpEndpointServer = "ai_mcp_endpoint_servers",AiMcpEndpointServerTool = "ai_mcp_endpoint_server_tools"diff --git a/backend/src/ee/routes/v1/ai-mcp-endpoint-router.ts b/backend/src/ee/routes/v1/ai-mcp-endpoint-router.tsindex f76d6642cd..2841b0aa89 100644--- a/backend/src/ee/routes/v1/ai-mcp-endpoint-router.ts+++ b/backend/src/ee/routes/v1/ai-mcp-endpoint-router.ts@@ -72,7 +72,8 @@ export const registerAiMcpEndpointRouter = async (server: FastifyZodProvider) =>}const { server: mcpServer, transport } = await server.services.aiMcpEndpoint.interactWithMcp({- endpointId: req.params.endpointId+ endpointId: req.params.endpointId,+ userId: req.permission.id});// Close transport when client disconnects@@ -548,4 +549,110 @@ export const registerAiMcpEndpointRouter = async (server: FastifyZodProvider) =>return payload;}});++ // Get servers requiring personal authentication+ server.route({+ method: "GET",+ url: "/:endpointId/servers-requiring-auth",+ config: {+ rateLimit: readLimit+ },+ schema: {+ params: z.object({+ endpointId: z.string().trim().min(1)+ }),+ response: {+ 200: z.object({+ servers: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ url: z.string(),+ hasCredentials: z.boolean()+ })+ )+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const servers = await server.services.aiMcpEndpoint.getServersRequiringAuth({+ endpointId: req.params.endpointId,+ userId: req.permission.id+ });++ return { servers };+ }+ });++ // Initiate OAuth for a server (personal credential mode)+ server.route({+ method: "POST",+ url: "/:endpointId/servers/:serverId/oauth/initiate",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ params: z.object({+ endpointId: z.string().trim().min(1),+ serverId: z.string().trim().min(1)+ }),+ response: {+ 200: z.object({+ authUrl: z.string(),+ sessionId: z.string()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const result = await server.services.aiMcpEndpoint.initiateServerOAuth({+ endpointId: req.params.endpointId,+ serverId: req.params.serverId,+ actorId: req.permission.id,+ actor: req.permission.type,+ actorAuthMethod: req.permission.authMethod as string,+ actorOrgId: req.permission.orgId+ });++ return result;+ }+ });++ // Save user credentials after OAuth completes+ server.route({+ method: "POST",+ url: "/:endpointId/servers/:serverId/credentials",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ params: z.object({+ endpointId: z.string().trim().min(1),+ serverId: z.string().trim().min(1)+ }),+ body: z.object({+ accessToken: z.string().min(1),+ refreshToken: z.string().optional(),+ expiresAt: z.number().optional(),+ tokenType: z.string().optional()+ }),+ response: {+ 200: z.object({+ success: z.boolean()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const result = await server.services.aiMcpEndpoint.saveUserServerCredential({+ endpointId: req.params.endpointId,+ serverId: req.params.serverId,+ userId: req.permission.id,+ ...req.body+ });++ return result;+ }+ });};diff --git a/backend/src/ee/routes/v1/ai-mcp-server-router.ts b/backend/src/ee/routes/v1/ai-mcp-server-router.tsindex 9535290306..0d655b96a4 100644--- a/backend/src/ee/routes/v1/ai-mcp-server-router.ts+++ b/backend/src/ee/routes/v1/ai-mcp-server-router.ts@@ -13,7 +13,9 @@ const CreateMcpServerBaseSchema = z.object({name: z.string().trim().min(1).max(64),url: z.string().trim().url(),description: z.string().trim().max(256).optional(),- credentialMode: z.nativeEnum(AiMcpServerCredentialMode)+ credentialMode: z.nativeEnum(AiMcpServerCredentialMode),+ oauthClientId: z.string().trim().min(1).optional(),+ oauthClientSecret: z.string().trim().min(1).optional()});const McpServerCredentialsSchema = z.discriminatedUnion("authMethod", [@@ -51,7 +53,9 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {schema: {body: z.object({projectId: z.string().trim().min(1),- url: z.string().trim().url()+ url: z.string().trim().url(),+ clientId: z.string().trim().min(1).optional(),+ clientSecret: z.string().trim().min(1).optional()}),response: {200: z.object({@@ -65,6 +69,8 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {const result = await server.services.aiMcpServer.initiateOAuth({projectId: req.body.projectId,url: req.body.url,+ clientId: req.body.clientId,+ clientSecret: req.body.clientSecret,actorId: req.permission.id,actor: req.permission.type,actorAuthMethod: req.permission.authMethod!,@@ -164,7 +170,7 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {body: CreateMcpServerBaseSchema.and(McpServerCredentialsSchema),response: {200: z.object({- server: AiMcpServersSchema.omit({ encryptedCredentials: true })+ server: AiMcpServersSchema.omit({ encryptedCredentials: true, encryptedOauthConfig: true })})}},@@ -196,7 +202,7 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {}),response: {200: z.object({- servers: z.array(AiMcpServersSchema.omit({ encryptedCredentials: true })),+ servers: z.array(AiMcpServersSchema.omit({ encryptedCredentials: true, encryptedOauthConfig: true })),totalCount: z.number()})}@@ -226,7 +232,7 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {}),response: {200: z.object({- server: AiMcpServersSchema.omit({ encryptedCredentials: true })+ server: AiMcpServersSchema.omit({ encryptedCredentials: true, encryptedOauthConfig: true })})}},@@ -256,7 +262,7 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {}),response: {200: z.object({- server: AiMcpServersSchema.omit({ encryptedCredentials: true })+ server: AiMcpServersSchema.omit({ encryptedCredentials: true, encryptedOauthConfig: true })})}},@@ -335,7 +341,7 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {}),response: {200: z.object({- server: AiMcpServersSchema.omit({ encryptedCredentials: true })+ server: AiMcpServersSchema.omit({ encryptedCredentials: true, encryptedOauthConfig: true })})}},diff --git a/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-service.ts b/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-service.tsindex 8d16057aa7..ec1d72c550 100644--- a/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-service.ts+++ b/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-service.ts@@ -11,6 +11,7 @@ import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto as cryptoModule } from "@app/lib/crypto";import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";import { ms } from "@app/lib/ms";import { AuthTokenType } from "@app/services/auth/auth-type";import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";@@ -18,8 +19,10 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { TAiMcpServerDALFactory } from "../ai-mcp-server/ai-mcp-server-dal";+import { AiMcpServerCredentialMode } from "../ai-mcp-server/ai-mcp-server-enum";+import { TAiMcpServerServiceFactory } from "../ai-mcp-server/ai-mcp-server-service";import { TAiMcpServerToolDALFactory } from "../ai-mcp-server/ai-mcp-server-tool-dal";-import { TAiMcpServerCredentials } from "../ai-mcp-server/ai-mcp-server-types";+import { TAiMcpServerUserCredentialDALFactory } from "../ai-mcp-server/ai-mcp-server-user-credential-dal";import { TAiMcpEndpointDALFactory } from "./ai-mcp-endpoint-dal";import { TAiMcpEndpointServerDALFactory } from "./ai-mcp-endpoint-server-dal";import { TAiMcpEndpointServerToolDALFactory } from "./ai-mcp-endpoint-server-tool-dal";@@ -31,6 +34,8 @@ import {TDisableEndpointToolDTO,TEnableEndpointToolDTO,TGetAiMcpEndpointDTO,+ TGetServersRequiringAuthDTO,+ TInitiateServerOAuthDTO,TInteractWithMcpDTO,TListAiMcpEndpointsDTO,TListEndpointToolsDTO,@@ -38,6 +43,8 @@ import {TOAuthFinalizeDTO,TOAuthRegisterClientDTO,TOAuthTokenExchangeDTO,+ TSaveUserServerCredentialDTO,+ TServerAuthStatus,TUpdateAiMcpEndpointDTO} from "./ai-mcp-endpoint-types";@@ -47,6 +54,11 @@ type TAiMcpEndpointServiceFactoryDep = {aiMcpEndpointServerToolDAL: TAiMcpEndpointServerToolDALFactory;aiMcpServerDAL: TAiMcpServerDALFactory;aiMcpServerToolDAL: TAiMcpServerToolDALFactory;+ aiMcpServerUserCredentialDAL: TAiMcpServerUserCredentialDALFactory;+ aiMcpServerService: Pick<+ TAiMcpServerServiceFactory,+ "getCredentialsForServer" | "initiateOAuth" | "getOAuthStatus" | "getServerOAuthConfig"+ >;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "deleteItem">;authTokenService: Pick<TAuthTokenServiceFactory, "getUserTokenSessionById">;@@ -100,11 +112,13 @@ export const aiMcpEndpointServiceFactory = ({aiMcpEndpointServerToolDAL,aiMcpServerDAL,aiMcpServerToolDAL,+ aiMcpServerUserCredentialDAL,+ aiMcpServerService,kmsService,keyStore,authTokenService}: TAiMcpEndpointServiceFactoryDep) => {- const interactWithMcp = async ({ endpointId }: TInteractWithMcpDTO) => {+ const interactWithMcp = async ({ endpointId, userId }: TInteractWithMcpDTO) => {const appCfg = getConfig();// Get the endpoint@@ -151,12 +165,6 @@ export const aiMcpEndpointServiceFactory = ({return { server: emptyServer, transport };}- // Create cipher pair for decryption- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId: endpoint.projectId- });-// Connect to each server and get their toolsconst mcpClientTools = await Promise.all(validServers.map(async (mcpServer) => {@@ -165,25 +173,23 @@ export const aiMcpEndpointServiceFactory = ({// Create a map from tool name to database tool ID for this specific serverconst toolNameToDbId = new Map(dbServerTools.map((t) => [t.name, t.id]));- if (!mcpServer.encryptedCredentials) {- return { client: null, server: mcpServer, tools: [], toolNameToDbId };- }-- const decryptedCredentials = JSON.parse(- decryptor({ cipherTextBlob: mcpServer.encryptedCredentials }).toString()- ) as TAiMcpServerCredentials;+ // Get credentials based on server's credential mode+ const credentialsResult = await aiMcpServerService.getCredentialsForServer({+ serverId: mcpServer.id,+ serverUrl: mcpServer.url,+ credentialMode: mcpServer.credentialMode,+ projectId: endpoint.projectId,+ userId+ });- // Get access token from credentials- let accessToken: string | undefined;- if ("accessToken" in decryptedCredentials) {- accessToken = decryptedCredentials.accessToken;- } else if ("token" in decryptedCredentials) {- accessToken = decryptedCredentials.token;+ if (!credentialsResult) {+ logger.warn(`No credentials found for MCP server ${mcpServer.name} (mode: ${mcpServer.credentialMode})`);+ return { client: null, server: mcpServer, tools: [], toolNameToDbId };}const headers: Record<string, string> = {};- if (accessToken) {- headers.Authorization = `Bearer ${accessToken}`;+ if (credentialsResult.accessToken) {+ headers.Authorization = `Bearer ${credentialsResult.accessToken}`;}try {@@ -207,8 +213,9 @@ export const aiMcpEndpointServiceFactory = ({tools: tools as Array<{ name: string; description?: string; inputSchema?: Record<string, unknown> }>,toolNameToDbId};- } catch {+ } catch (error) {// If connection fails, return empty tools for this server+ logger.error(error, `Failed to connect to MCP server ${mcpServer.name} (${mcpServer.url})`);return { client: null, server: mcpServer, tools: [], toolNameToDbId };}})@@ -652,6 +659,140 @@ export const aiMcpEndpointServiceFactory = ({};};+ // Get servers that require personal authentication for an endpoint+ const getServersRequiringAuth = async ({+ endpointId,+ userId+ }: TGetServersRequiringAuthDTO): Promise<TServerAuthStatus[]> => {+ const endpoint = await aiMcpEndpointDAL.findById(endpointId);+ if (!endpoint) {+ throw new NotFoundError({ message: `MCP endpoint with ID '${endpointId}' not found` });+ }++ // Get connected servers+ const connectedServerLinks = await aiMcpEndpointServerDAL.find({ aiMcpEndpointId: endpointId });+ const serverIds = connectedServerLinks.map((link) => link.aiMcpServerId);++ if (serverIds.length === 0) {+ return [];+ }++ // Get server details+ const servers = await Promise.all(serverIds.map((id) => aiMcpServerDAL.findById(id)));+ const validServers = servers.filter((s) => s !== null && s !== undefined);++ // Filter to only servers with personal credential mode+ const personalServers = validServers.filter((s) => s.credentialMode === AiMcpServerCredentialMode.PERSONAL);++ if (personalServers.length === 0) {+ return [];+ }++ // Check which servers the user already has credentials for+ const serversWithAuthStatus = await Promise.all(+ personalServers.map(async (server) => {+ const existingCredential = await aiMcpServerUserCredentialDAL.findByUserAndServer(userId, server.id);++ return {+ id: server.id,+ name: server.name,+ url: server.url,+ hasCredentials: Boolean(existingCredential)+ };+ })+ );++ return serversWithAuthStatus;+ };++ // Initiate OAuth for a server (personal credential mode)+ const initiateServerOAuth = async ({+ endpointId,+ serverId,+ actorId,+ actor,+ actorAuthMethod,+ actorOrgId+ }: TInitiateServerOAuthDTO) => {+ // Verify endpoint exists and server is connected+ const endpoint = await aiMcpEndpointDAL.findById(endpointId);+ if (!endpoint) {+ throw new NotFoundError({ message: `MCP endpoint with ID '${endpointId}' not found` });+ }++ const server = await aiMcpServerDAL.findById(serverId);+ if (!server) {+ throw new NotFoundError({ message: `MCP server with ID '${serverId}' not found` });+ }++ if (server.credentialMode !== AiMcpServerCredentialMode.PERSONAL) {+ throw new BadRequestError({ message: "This server does not use personal credentials" });+ }++ // Get stored OAuth config (client ID/secret) if available+ const oauthConfig = await aiMcpServerService.getServerOAuthConfig(serverId);++ // Use the existing MCP server OAuth initiate with stored client credentials+ return aiMcpServerService.initiateOAuth({+ projectId: endpoint.projectId,+ url: server.url,+ actorId,+ actor,+ actorAuthMethod,+ actorOrgId,+ clientId: oauthConfig?.clientId,+ clientSecret: oauthConfig?.clientSecret+ });+ };++ // Save user credentials after OAuth completes+ const saveUserServerCredential = async ({+ endpointId,+ serverId,+ userId,+ accessToken,+ refreshToken,+ expiresAt,+ tokenType+ }: TSaveUserServerCredentialDTO) => {+ // Verify endpoint and server exist+ const endpoint = await aiMcpEndpointDAL.findById(endpointId);+ if (!endpoint) {+ throw new NotFoundError({ message: `MCP endpoint with ID '${endpointId}' not found` });+ }++ const server = await aiMcpServerDAL.findById(serverId);+ if (!server) {+ throw new NotFoundError({ message: `MCP server with ID '${serverId}' not found` });+ }++ // Encrypt the credentials+ const credentials = {+ accessToken,+ refreshToken,+ expiresAt,+ tokenType: tokenType || "Bearer"+ };++ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId: endpoint.projectId+ });++ const encryptedCredentials = encryptor({+ plainText: Buffer.from(JSON.stringify(credentials))+ }).cipherTextBlob;++ // Upsert the credential+ await aiMcpServerUserCredentialDAL.upsertCredential({+ userId,+ aiMcpServerId: serverId,+ encryptedCredentials+ });++ return { success: true };+ };+return {interactWithMcp,createMcpEndpoint,@@ -666,6 +807,9 @@ export const aiMcpEndpointServiceFactory = ({oauthRegisterClient,oauthAuthorizeClient,oauthFinalize,- oauthTokenExchange+ oauthTokenExchange,+ getServersRequiringAuth,+ initiateServerOAuth,+ saveUserServerCredential};};diff --git a/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-types.ts b/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-types.tsindex 2ecb2df515..341716305e 100644--- a/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-types.ts+++ b/backend/src/ee/services/ai-mcp-endpoint/ai-mcp-endpoint-types.ts@@ -22,6 +22,7 @@ export type TGetAiMcpEndpointDTO = {export type TInteractWithMcpDTO = {endpointId: string;+ userId: string;};export type TListAiMcpEndpointsDTO = {@@ -121,3 +122,37 @@ export type TOAuthTokenExchangeDTO = {code_verifier: string;client_id: string;};++// Personal credentials types+export type TGetServersRequiringAuthDTO = {+ endpointId: string;+ userId: string;+};++export type TServerAuthStatus = {+ id: string;+ name: string;+ url: string;+ hasCredentials: boolean;+ oauthClientId?: string;+ oauthClientSecret?: string;+};++export type TInitiateServerOAuthDTO = {+ endpointId: string;+ serverId: string;+ actorId: string;+ actor: string;+ actorAuthMethod: string;+ actorOrgId: string;+};++export type TSaveUserServerCredentialDTO = {+ endpointId: string;+ serverId: string;+ userId: string;+ accessToken: string;+ refreshToken?: string;+ expiresAt?: number;+ tokenType?: string;+};diff --git a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.tsindex 77c667d30e..58d04987d1 100644--- a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts+++ b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-service.ts@@ -6,6 +6,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignore - MCP SDK uses ESM with .js extensions which don't resolve types with moduleResolution: "Node"import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";+import axios, { AxiosError } from "axios";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";@@ -16,7 +17,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { TAiMcpServerDALFactory } from "./ai-mcp-server-dal";-import { AiMcpServerStatus } from "./ai-mcp-server-enum";+import { AiMcpServerCredentialMode, AiMcpServerStatus } from "./ai-mcp-server-enum";import { TAiMcpServerToolDALFactory } from "./ai-mcp-server-tool-dal";import {TAiMcpServerCredentials,@@ -26,14 +27,17 @@ import {TInitiateOAuthDTO,TOAuthAuthorizationServerMetadata,TOAuthDynamicClientMetadata,+ TOAuthProtectedResourceMetadata,TOAuthSession,TOAuthTokenResponse,TUpdateAiMcpServerDTO} from "./ai-mcp-server-types";+import { TAiMcpServerUserCredentialDALFactory } from "./ai-mcp-server-user-credential-dal";type TAiMcpServerServiceFactoryDep = {aiMcpServerDAL: TAiMcpServerDALFactory;aiMcpServerToolDAL: TAiMcpServerToolDALFactory;+ aiMcpServerUserCredentialDAL: TAiMcpServerUserCredentialDALFactory;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;};@@ -42,6 +46,41 @@ export type TAiMcpServerServiceFactory = ReturnType<typeof aiMcpServerServiceFacconst OAUTH_SESSION_TTL_SECONDS = 10 * 60; // 10 minutes+// Buffer time before token expiry to trigger refresh (5 minutes)+const TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1000;++/**+ * Refresh an OAuth access token using the refresh token+ */+const refreshOAuthToken = async (+ serverUrl: string,+ refreshToken: string+): Promise<{ accessToken: string; refreshToken?: string; expiresAt?: number }> => {+ const issuer = new URL(serverUrl).origin;+ const { data: serverMetadata } = await request.get<TOAuthAuthorizationServerMetadata>(+ `${issuer}/.well-known/oauth-authorization-server`+ );++ const { data: tokenResponse } = await request.post<TOAuthTokenResponse>(+ serverMetadata.token_endpoint,+ new URLSearchParams({+ grant_type: "refresh_token",+ refresh_token: refreshToken+ }).toString(),+ {+ headers: {+ "Content-Type": "application/x-www-form-urlencoded"+ }+ }+ );++ return {+ accessToken: tokenResponse.access_token,+ refreshToken: tokenResponse.refresh_token,+ expiresAt: tokenResponse.expires_in ? Date.now() + tokenResponse.expires_in * 1000 : undefined+ };+};+// Helper to encrypt credentialsconst encryptCredentials = async ({projectId,@@ -74,6 +113,7 @@ type TMcpTool = {export const aiMcpServerServiceFactory = ({aiMcpServerDAL,aiMcpServerToolDAL,+ aiMcpServerUserCredentialDAL,kmsService,keyStore}: TAiMcpServerServiceFactoryDep) => {@@ -115,60 +155,174 @@ export const aiMcpServerServiceFactory = ({/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-redundant-type-constituents *//**- * Initiate OAuth flow for MCP server- * Returns the authorization URL and session ID+ * Parse WWW-Authenticate header to extract resource_metadata URL+ * Format: Bearer resource_metadata="https://..."*/- const initiateOAuth = async ({ projectId, url, actorId }: TInitiateOAuthDTO) => {- const appCfg = getConfig();- const issuer = new URL(url).origin;+ const parseWwwAuthenticateHeader = (header: string): string | null => {+ const match = header.match(/resource_metadata="([^"]+)"/);+ return match ? match[1] : null;+ };- // 1. Get OAuth metadata from the MCP server- const { data: serverMetadata } = await request.get<TOAuthAuthorizationServerMetadata>(- `${issuer}/.well-known/oauth-authorization-server`- );+ /**+ * Discover OAuth metadata by following the RFC 9728 Protected Resource Metadata flow:+ * 1. Try to access the MCP server URL → get 401 with WWW-Authenticate header+ * 2. Parse the protected resource metadata URL from the header+ * 3. Fetch the protected resource metadata to get authorization_servers+ * 4. Fetch the authorization server metadata+ */+ const discoverOAuthMetadata = async (+ mcpUrl: string+ ): Promise<{+ protectedResource: TOAuthProtectedResourceMetadata;+ authServer: TOAuthAuthorizationServerMetadata;+ }> => {+ let resourceMetadataUrl: string | null = null;++ // 1. Try to access the MCP server to get WWW-Authenticate header+ try {+ await request.get(mcpUrl);+ // If we get here without error, the server doesn't require auth (unusual)+ throw new BadRequestError({+ message: "MCP server did not return authentication requirements"+ });+ } catch (error) {+ // Check if it's an axios error with 401 status+ if (axios.isAxiosError(error)) {+ const axiosErr = error as AxiosError;+ if (axiosErr.response?.status === 401) {+ const wwwAuth = axiosErr.response.headers["www-authenticate"] as string | undefined;+ if (wwwAuth) {+ resourceMetadataUrl = parseWwwAuthenticateHeader(wwwAuth);+ }+ } else {+ throw error;+ }+ } else {+ throw error;+ }+ }- if (!serverMetadata.registration_endpoint) {+ if (!resourceMetadataUrl) {+ // Fallback: Try common .well-known paths+ const urlObj = new URL(mcpUrl);+ const possiblePaths = [+ `${urlObj.origin}/.well-known/oauth-protected-resource${urlObj.pathname}`,+ `${urlObj.origin}/.well-known/oauth-protected-resource`+ ];++ // Try paths sequentially (using Promise.allSettled would change semantics)+ // eslint-disable-next-line no-restricted-syntax+ for (const path of possiblePaths) {+ try {+ // eslint-disable-next-line no-await-in-loop+ const { data } = await request.get<TOAuthProtectedResourceMetadata>(path);+ if (data.authorization_servers?.length > 0) {+ resourceMetadataUrl = path;+ break;+ }+ } catch {+ // Continue to next path+ }+ }+ }++ if (!resourceMetadataUrl) {throw new BadRequestError({- message: "MCP server does not support Dynamic Client Registration"+ message: "Could not discover OAuth metadata for MCP server. WWW-Authenticate header not found."});}+ // 2. Fetch protected resource metadata+ const { data: protectedResource } = await request.get<TOAuthProtectedResourceMetadata>(resourceMetadataUrl);++ if (!protectedResource.authorization_servers?.length) {+ throw new BadRequestError({+ message: "Protected resource metadata does not specify any authorization servers"+ });+ }++ // 3. Get the authorization server URL and fetch its metadata+ const authServerUrl = protectedResource.authorization_servers[0];++ // Authorization server metadata is at /.well-known/oauth-authorization-server relative to the issuer+ const authServerUrlObj = new URL(authServerUrl);+ const authServerMetadataUrl = `${authServerUrlObj.origin}/.well-known/oauth-authorization-server${authServerUrlObj.pathname !== "/" ? authServerUrlObj.pathname : ""}`;++ const { data: authServer } = await request.get<TOAuthAuthorizationServerMetadata>(authServerMetadataUrl);++ return { protectedResource, authServer };+ };++ /**+ * Initiate OAuth flow for MCP server+ * Returns the authorization URL and session ID+ * Supports both DCR (Dynamic Client Registration) and hardcoded client credentials+ */+ const initiateOAuth = async ({ projectId, url, actorId, clientId, clientSecret }: TInitiateOAuthDTO) => {+ const appCfg = getConfig();++ // 1. Discover OAuth metadata following RFC 9728 flow+ const { protectedResource, authServer } = await discoverOAuthMetadata(url);++ logger.info({ protectedResource, authServer }, "Discovered OAuth metadata for MCP server");+// 2. Generate session IDconst sessionId = crypto.randomUUID();// 3. Build redirect URIconst redirectUri = `${appCfg.SITE_URL}/api/v1/ai/mcp-servers/oauth/callback`;- // 4. Register client via DCR- const { data: clientMetadata } = await request.post<TOAuthDynamicClientMetadata>(- serverMetadata.registration_endpoint,- {- redirect_uris: [redirectUri],- token_endpoint_auth_method: "none",- grant_types: ["authorization_code"],- response_types: ["code"],- client_name: `Infisical MCP Client - ${actorId}`- },- {- headers: {- "Content-Type": "application/json"- }+ // 4. Get client credentials - either from DCR or hardcoded+ let resolvedClientId: string;+ let resolvedClientSecret: string | undefined;++ if (clientId) {+ // Use hardcoded client credentials (for servers like GitHub that don't support DCR)+ resolvedClientId = clientId;+ resolvedClientSecret = clientSecret;+ } else {+ // Use Dynamic Client Registration+ if (!authServer.registration_endpoint) {+ throw new BadRequestError({+ message: "MCP server does not support Dynamic Client Registration. Please provide a client ID and secret."+ });}- );++ const { data: clientMetadata } = await request.post<TOAuthDynamicClientMetadata>(+ authServer.registration_endpoint,+ {+ redirect_uris: [redirectUri],+ token_endpoint_auth_method: "none",+ grant_types: ["authorization_code"],+ response_types: ["code"],+ client_name: `Infisical MCP Client - ${actorId}`+ },+ {+ headers: {+ "Content-Type": "application/json"+ }+ }+ );++ resolvedClientId = clientMetadata.client_id;+ resolvedClientSecret = clientMetadata.client_secret;+ }// 5. Generate PKCE code verifier and challengeconst codeVerifier = crypto.randomBytes(32).toString("base64url");const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");- // 6. Store session data in keystore+ // 6. Store session data in keystore (include auth server token endpoint for callback)const sessionData: TOAuthSession = {actorId,codeVerifier,codeChallenge,- clientId: clientMetadata.client_id,+ clientId: resolvedClientId,+ clientSecret: resolvedClientSecret,projectId,serverUrl: url,redirectUri,+ tokenEndpoint: authServer.token_endpoint,authorized: false};@@ -179,11 +333,15 @@ export const aiMcpServerServiceFactory = ({);// 7. Build authorization URL- const authUrl = new URL(serverMetadata.authorization_endpoint);- authUrl.searchParams.set("client_id", clientMetadata.client_id);+ const authUrl = new URL(authServer.authorization_endpoint);+ authUrl.searchParams.set("client_id", resolvedClientId);authUrl.searchParams.set("redirect_uri", redirectUri);authUrl.searchParams.set("response_type", "code");- authUrl.searchParams.set("scope", "read write");++ // Use scopes from protected resource if available, otherwise default+ const scopes = protectedResource.scopes_supported?.join(" ") || "read write";+ authUrl.searchParams.set("scope", scopes);+authUrl.searchParams.set("code_challenge", codeChallenge);authUrl.searchParams.set("code_challenge_method", "S256");authUrl.searchParams.set("state", sessionId);@@ -215,25 +373,27 @@ export const aiMcpServerServiceFactory = ({});}- // 2. Get OAuth metadata again- const issuer = new URL(sessionData.serverUrl).origin;- const { data: serverMetadata } = await request.get<TOAuthAuthorizationServerMetadata>(- `${issuer}/.well-known/oauth-authorization-server`- );+ // 2. Exchange code for tokens using the stored token endpoint+ const tokenParams: Record<string, string> = {+ grant_type: "authorization_code",+ code,+ redirect_uri: sessionData.redirectUri,+ client_id: sessionData.clientId,+ code_verifier: sessionData.codeVerifier+ };++ // Add client_secret if available+ if (sessionData.clientSecret) {+ tokenParams.client_secret = sessionData.clientSecret;+ }- // 3. Exchange code for tokensconst { data: tokenResponse } = await request.post<TOAuthTokenResponse>(- serverMetadata.token_endpoint,- new URLSearchParams({- grant_type: "authorization_code",- code,- redirect_uri: sessionData.redirectUri,- client_id: sessionData.clientId,- code_verifier: sessionData.codeVerifier- }).toString(),+ sessionData.tokenEndpoint,+ new URLSearchParams(tokenParams).toString(),{headers: {- "Content-Type": "application/x-www-form-urlencoded"+ "Content-Type": "application/x-www-form-urlencoded",+ Accept: "application/json" // GitHub returns form-urlencoded by default without this}});@@ -293,7 +453,9 @@ export const aiMcpServerServiceFactory = ({description,credentialMode,authMethod,- credentials+ credentials,+ oauthClientId,+ oauthClientSecret}: TCreateAiMcpServerDTO) => {const encryptedCredentials = await encryptCredentials({projectId,@@ -301,6 +463,18 @@ export const aiMcpServerServiceFactory = ({kmsService});+ // Encrypt OAuth config (client ID/secret) if provided+ let encryptedOauthConfig: Buffer | undefined;+ if (oauthClientId) {+ const { encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });+ encryptedOauthConfig = encryptor({+ plainText: Buffer.from(JSON.stringify({ clientId: oauthClientId, clientSecret: oauthClientSecret }))+ }).cipherTextBlob;+ }+const server = await aiMcpServerDAL.create({projectId,name,@@ -309,6 +483,7 @@ export const aiMcpServerServiceFactory = ({credentialMode,authMethod,encryptedCredentials,+ encryptedOauthConfig,status: AiMcpServerStatus.ACTIVE});@@ -444,6 +619,181 @@ export const aiMcpServerServiceFactory = ({return tools;};+ /**+ * Get decrypted credentials for an MCP server, automatically refreshing OAuth tokens if expired.+ * This is the single source of truth for getting valid credentials.+ */+ const getServerCredentials = async ({+ serverId,+ projectId+ }: {+ serverId: string;+ projectId: string;+ }): Promise<{ credentials: TAiMcpServerCredentials; accessToken: string | undefined } | null> => {+ const server = await aiMcpServerDAL.findById(serverId);+ if (!server || !server.encryptedCredentials) {+ return null;+ }++ // Create cipher pair for decryption (and encryption if we need to refresh)+ const { decryptor, encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ let credentials = JSON.parse(+ decryptor({ cipherTextBlob: server.encryptedCredentials }).toString()+ ) as TAiMcpServerCredentials;++ // Handle OAuth credentials with potential token refresh+ if ("accessToken" in credentials) {+ const isExpired =+ "expiresAt" in credentials &&+ credentials.expiresAt &&+ Date.now() >= credentials.expiresAt - TOKEN_REFRESH_BUFFER_MS;++ if (isExpired && "refreshToken" in credentials && credentials.refreshToken) {+ try {+ const refreshedTokens = await refreshOAuthToken(server.url, credentials.refreshToken);++ credentials = {+ ...credentials,+ accessToken: refreshedTokens.accessToken,+ refreshToken: refreshedTokens.refreshToken || credentials.refreshToken,+ expiresAt: refreshedTokens.expiresAt+ };++ // Persist the refreshed credentials+ const { cipherTextBlob: newEncryptedCredentials } = encryptor({+ plainText: Buffer.from(JSON.stringify(credentials))+ });++ await aiMcpServerDAL.updateById(serverId, {+ encryptedCredentials: newEncryptedCredentials+ });++ logger.info({ serverId }, "Refreshed OAuth token for MCP server");+ } catch (refreshError) {+ logger.error(refreshError, `Failed to refresh OAuth token for MCP server ${serverId}`);+ // Return expired token - caller can decide how to handle the error+ }+ }++ return { credentials, accessToken: credentials.accessToken };+ }++ // Handle bearer token credentials+ if ("token" in credentials) {+ return { credentials, accessToken: credentials.token };+ }++ // Basic auth or other types - no access token+ return { credentials, accessToken: undefined };+ };++ // Get user's personal credentials for a server (with token refresh)+ const getUserServerCredentials = async ({+ serverId,+ userId,+ projectId,+ serverUrl+ }: {+ serverId: string;+ userId: string;+ projectId: string;+ serverUrl: string;+ }): Promise<{ accessToken: string } | null> => {+ const userCredential = await aiMcpServerUserCredentialDAL.findByUserAndServer(userId, serverId);+ if (!userCredential) {+ return null;+ }++ // Create cipher pair for decryption (and encryption if we need to refresh)+ const { decryptor, encryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });++ let credentials = JSON.parse(decryptor({ cipherTextBlob: userCredential.encryptedCredentials }).toString()) as {+ accessToken: string;+ refreshToken?: string;+ expiresAt?: number;+ tokenType?: string;+ };++ // Check if token is expired and needs refresh+ const isExpired = credentials.expiresAt && Date.now() >= credentials.expiresAt - TOKEN_REFRESH_BUFFER_MS;++ if (isExpired && credentials.refreshToken) {+ try {+ const refreshedTokens = await refreshOAuthToken(serverUrl, credentials.refreshToken);++ credentials = {+ ...credentials,+ accessToken: refreshedTokens.accessToken,+ refreshToken: refreshedTokens.refreshToken || credentials.refreshToken,+ expiresAt: refreshedTokens.expiresAt+ };++ // Persist the refreshed credentials+ const { cipherTextBlob: newEncryptedCredentials } = encryptor({+ plainText: Buffer.from(JSON.stringify(credentials))+ });++ await aiMcpServerUserCredentialDAL.upsertCredential({+ userId,+ aiMcpServerId: serverId,+ encryptedCredentials: newEncryptedCredentials+ });++ logger.info({ serverId, userId }, "Refreshed OAuth token for user's MCP server credentials");+ } catch (refreshError) {+ logger.error(refreshError, `Failed to refresh OAuth token for user ${userId} on MCP server ${serverId}`);+ // Return expired token - caller can decide how to handle the error+ }+ }++ return { accessToken: credentials.accessToken };+ };++ // Unified method to get credentials based on credential mode+ const getCredentialsForServer = async ({+ serverId,+ serverUrl,+ credentialMode,+ projectId,+ userId+ }: {+ serverId: string;+ serverUrl: string;+ credentialMode?: string | null;+ projectId: string;+ userId: string;+ }): Promise<{ accessToken?: string } | null> => {+ if (credentialMode === AiMcpServerCredentialMode.PERSONAL) {+ return getUserServerCredentials({ serverId, userId, projectId, serverUrl });+ }+ return getServerCredentials({ serverId, projectId });+ };++ // Get stored OAuth config (client ID/secret) for a server+ const getServerOAuthConfig = async (+ serverId: string+ ): Promise<{ clientId: string; clientSecret?: string } | null> => {+ const server = await aiMcpServerDAL.findById(serverId);+ if (!server || !server.encryptedOauthConfig) {+ return null;+ }++ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId: server.projectId+ });++ const decrypted = decryptor({ cipherTextBlob: server.encryptedOauthConfig });+ return JSON.parse(decrypted.toString()) as { clientId: string; clientSecret?: string };+ };+return {initiateOAuth,handleOAuthCallback,@@ -454,6 +804,10 @@ export const aiMcpServerServiceFactory = ({listMcpServers,deleteMcpServer,listMcpServerTools,- syncMcpServerTools+ syncMcpServerTools,+ getServerCredentials,+ getUserServerCredentials,+ getCredentialsForServer,+ getServerOAuthConfig};};diff --git a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-types.ts b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-types.tsindex c9eba78f82..97e5da0cba 100644--- a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-types.ts+++ b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-types.ts@@ -1,13 +1,23 @@import { AiMcpServerAuthMethod, AiMcpServerCredentialMode } from "./ai-mcp-server-enum";// OAuth types from MCP server+// Protected Resource Metadata (RFC 9728)+export type TOAuthProtectedResourceMetadata = {+ resource: string;+ resource_name?: string;+ authorization_servers: string[];+ bearer_methods_supported?: string[];+ scopes_supported?: string[];+};++// Authorization Server Metadata (RFC 8414)export type TOAuthAuthorizationServerMetadata = {issuer: string;authorization_endpoint: string;token_endpoint: string;- registration_endpoint: string;+ registration_endpoint?: string; // Optional - not all servers support DCRscopes_supported?: string[];- response_types_supported: string[];+ response_types_supported?: string[];grant_types_supported?: string[];token_endpoint_auth_methods_supported?: string[];code_challenge_methods_supported?: string[];@@ -58,9 +68,11 @@ export type TOAuthSession = {codeVerifier: string;codeChallenge: string;clientId: string;+ clientSecret?: string; // For servers that don't support DCR (like GitHub)projectId: string;serverUrl: string;redirectUri: string;+ tokenEndpoint: string; // Stored from OAuth discovery for token exchange// Set after callbackaccessToken?: string;refreshToken?: string;@@ -69,7 +81,6 @@ export type TOAuthSession = {authorized?: boolean;};-// DTO typesexport type TInitiateOAuthDTO = {projectId: string;url: string;@@ -77,6 +88,8 @@ export type TInitiateOAuthDTO = {actor: string;actorAuthMethod: string;actorOrgId: string;+ clientId?: string;+ clientSecret?: string;};export type THandleOAuthCallbackDTO = {@@ -97,6 +110,8 @@ export type TCreateAiMcpServerDTO = {credentialMode: AiMcpServerCredentialMode;authMethod: AiMcpServerAuthMethod;credentials: TBasicCredentials | TBearerCredentials | TOAuthCredentials;+ oauthClientId?: string;+ oauthClientSecret?: string;actorId: string;actor: string;actorAuthMethod: string;diff --git a/backend/src/ee/services/ai-mcp-server/ai-mcp-server-user-credential-dal.ts b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-user-credential-dal.tsnew file mode 100644index 0000000000..59d10d0068--- /dev/null+++ b/backend/src/ee/services/ai-mcp-server/ai-mcp-server-user-credential-dal.ts@@ -0,0 +1,26 @@+import { TDbClient } from "@app/db";+import { TableName, TAiMcpServerUserCredentialsInsert } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TAiMcpServerUserCredentialDALFactory = ReturnType<typeof aiMcpServerUserCredentialDALFactory>;++export const aiMcpServerUserCredentialDALFactory = (db: TDbClient) => {+ const aiMcpServerUserCredentialOrm = ormify(db, TableName.AiMcpServerUserCredential);++ const findByUserAndServer = async (userId: string, aiMcpServerId: string) => {+ return aiMcpServerUserCredentialOrm.findOne({ userId, aiMcpServerId });+ };++ const upsertCredential = async (data: TAiMcpServerUserCredentialsInsert) => {+ const [result] = await aiMcpServerUserCredentialOrm.upsert([data], ["userId", "aiMcpServerId"], undefined, [+ "encryptedCredentials"+ ]);+ return result;+ };++ return {+ ...aiMcpServerUserCredentialOrm,+ findByUserAndServer,+ upsertCredential+ };+};diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex d728649e78..3b937b39cb 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -28,6 +28,7 @@ import { aiMcpEndpointServiceFactory } from "@app/ee/services/ai-mcp-endpoint/aiimport { aiMcpServerDALFactory } from "@app/ee/services/ai-mcp-server/ai-mcp-server-dal";import { aiMcpServerServiceFactory } from "@app/ee/services/ai-mcp-server/ai-mcp-server-service";import { aiMcpServerToolDALFactory } from "@app/ee/services/ai-mcp-server/ai-mcp-server-tool-dal";+import { aiMcpServerUserCredentialDALFactory } from "@app/ee/services/ai-mcp-server/ai-mcp-server-user-credential-dal";import { assumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-service";import { auditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";import { auditLogQueueServiceFactory } from "@app/ee/services/audit-log/audit-log-queue";@@ -2410,6 +2411,7 @@ export const registerRoutes = async (const pamSessionDAL = pamSessionDALFactory(db);const aiMcpServerDAL = aiMcpServerDALFactory(db);const aiMcpServerToolDAL = aiMcpServerToolDALFactory(db);+ const aiMcpServerUserCredentialDAL = aiMcpServerUserCredentialDALFactory(db);const aiMcpEndpointDAL = aiMcpEndpointDALFactory(db);const aiMcpEndpointServerDAL = aiMcpEndpointServerDALFactory(db);const aiMcpEndpointServerToolDAL = aiMcpEndpointServerToolDALFactory(db);@@ -2458,6 +2460,7 @@ export const registerRoutes = async (const aiMcpServerService = aiMcpServerServiceFactory({aiMcpServerDAL,aiMcpServerToolDAL,+ aiMcpServerUserCredentialDAL,kmsService,keyStore});@@ -2468,6 +2471,8 @@ export const registerRoutes = async (aiMcpEndpointServerToolDAL,aiMcpServerDAL,aiMcpServerToolDAL,+ aiMcpServerUserCredentialDAL,+ aiMcpServerService,kmsService,keyStore,authTokenService: tokenServicediff --git a/frontend/src/hooks/api/aiMcpEndpoints/index.ts b/frontend/src/hooks/api/aiMcpEndpoints/index.tsindex f7ad39276b..f5d69e9cd0 100644--- a/frontend/src/hooks/api/aiMcpEndpoints/index.ts+++ b/frontend/src/hooks/api/aiMcpEndpoints/index.ts@@ -5,11 +5,14 @@ export {useDisableEndpointTool,useEnableEndpointTool,useFinalizeMcpEndpointOAuth,+ useInitiateServerOAuth,+ useSaveUserServerCredential,useUpdateAiMcpEndpoint} from "./mutations";export {aiMcpEndpointKeys,useGetAiMcpEndpointById,+ useGetServersRequiringAuth,useListAiMcpEndpoints,useListEndpointTools} from "./queries";diff --git a/frontend/src/hooks/api/aiMcpEndpoints/mutations.tsx b/frontend/src/hooks/api/aiMcpEndpoints/mutations.tsxindex 2c9318c778..a239fed554 100644--- a/frontend/src/hooks/api/aiMcpEndpoints/mutations.tsx+++ b/frontend/src/hooks/api/aiMcpEndpoints/mutations.tsx@@ -12,6 +12,8 @@ import {TDisableEndpointToolDTO,TEnableEndpointToolDTO,TFinalizeMcpEndpointOAuthDTO,+ TInitiateServerOAuthDTO,+ TSaveUserServerCredentialDTO,TUpdateAiMcpEndpointDTO} from "./types";@@ -137,3 +139,33 @@ export const useFinalizeMcpEndpointOAuth = () => {}});};++export const useInitiateServerOAuth = () => {+ return useMutation({+ mutationFn: async ({ endpointId, serverId }: TInitiateServerOAuthDTO) => {+ const { data } = await apiRequest.post<{ authUrl: string; sessionId: string }>(+ `/api/v1/ai/mcp-endpoints/${endpointId}/servers/${serverId}/oauth/initiate`+ );+ return data;+ }+ });+};++export const useSaveUserServerCredential = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async ({ endpointId, serverId, ...body }: TSaveUserServerCredentialDTO) => {+ const { data } = await apiRequest.post<{ success: boolean }>(+ `/api/v1/ai/mcp-endpoints/${endpointId}/servers/${serverId}/credentials`,+ body+ );+ return data;+ },+ onSuccess: (_, variables) => {+ queryClient.invalidateQueries({+ queryKey: aiMcpEndpointKeys.serversRequiringAuth(variables.endpointId)+ });+ }+ });+};diff --git a/frontend/src/hooks/api/aiMcpEndpoints/queries.tsx b/frontend/src/hooks/api/aiMcpEndpoints/queries.tsxindex a0cc35e6c7..492dec26f6 100644--- a/frontend/src/hooks/api/aiMcpEndpoints/queries.tsx+++ b/frontend/src/hooks/api/aiMcpEndpoints/queries.tsx@@ -6,14 +6,17 @@ import {TAiMcpEndpoint,TAiMcpEndpointToolConfig,TAiMcpEndpointWithServerIds,- TListAiMcpEndpointsDTO+ TListAiMcpEndpointsDTO,+ TServerAuthStatus} from "./types";export const aiMcpEndpointKeys = {all: ["aiMcpEndpoints"] as const,list: (projectId: string) => [...aiMcpEndpointKeys.all, "list", projectId] as const,byId: (endpointId: string) => [...aiMcpEndpointKeys.all, "byId", endpointId] as const,- tools: (endpointId: string) => [...aiMcpEndpointKeys.all, "tools", endpointId] as const+ tools: (endpointId: string) => [...aiMcpEndpointKeys.all, "tools", endpointId] as const,+ serversRequiringAuth: (endpointId: string) =>+ [...aiMcpEndpointKeys.all, "serversRequiringAuth", endpointId] as const};export const useListAiMcpEndpoints = ({ projectId }: TListAiMcpEndpointsDTO) => {@@ -57,3 +60,16 @@ export const useListEndpointTools = ({ endpointId }: { endpointId: string }) =>enabled: Boolean(endpointId)});};++export const useGetServersRequiringAuth = ({ endpointId }: { endpointId: string }) => {+ return useQuery({+ queryKey: aiMcpEndpointKeys.serversRequiringAuth(endpointId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ servers: TServerAuthStatus[] }>(+ `/api/v1/ai/mcp-endpoints/${endpointId}/servers-requiring-auth`+ );+ return data.servers;+ },+ enabled: Boolean(endpointId)+ });+};diff --git a/frontend/src/hooks/api/aiMcpEndpoints/types.ts b/frontend/src/hooks/api/aiMcpEndpoints/types.tsindex 89ed8c23d5..34dbef6b3e 100644--- a/frontend/src/hooks/api/aiMcpEndpoints/types.ts+++ b/frontend/src/hooks/api/aiMcpEndpoints/types.ts@@ -79,3 +79,25 @@ export type TFinalizeMcpEndpointOAuthDTO = {resource: string;expireIn: string;};++// Personal credentials types+export type TServerAuthStatus = {+ id: string;+ name: string;+ url: string;+ hasCredentials: boolean;+};++export type TInitiateServerOAuthDTO = {+ endpointId: string;+ serverId: string;+};++export type TSaveUserServerCredentialDTO = {+ endpointId: string;+ serverId: string;+ accessToken: string;+ refreshToken?: string;+ expiresAt?: number;+ tokenType?: string;+};diff --git a/frontend/src/hooks/api/aiMcpServers/types.ts b/frontend/src/hooks/api/aiMcpServers/types.tsindex 377c91a41b..96066d71f7 100644--- a/frontend/src/hooks/api/aiMcpServers/types.ts+++ b/frontend/src/hooks/api/aiMcpServers/types.ts@@ -69,12 +69,16 @@ export type TCreateAiMcpServerDTO = {url: string;description?: string;credentialMode: AiMcpServerCredentialMode;+ oauthClientId?: string;+ oauthClientSecret?: string;} & TAiMcpServerCredentials;// OAuth initiate DTOexport type TInitiateOAuthDTO = {projectId: string;url: string;+ clientId?: string;+ clientSecret?: string;};export type TInitiateOAuthResponse = {diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerForm.schema.ts b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerForm.schema.tsindex bea2d4b841..a4398de38c 100644--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerForm.schema.ts+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerForm.schema.ts@@ -48,7 +48,9 @@ export const AddMCPServerFormSchema = zname: z.string().trim().min(1, "Name is required").max(64, "Name cannot exceed 64 characters"),description: z.string().trim().max(256, "Description cannot exceed 256 characters").optional(),url: z.string().trim().min(1, "Endpoint URL is required").url("Must be a valid URL"),- credentialMode: z.nativeEnum(MCPServerCredentialMode)+ credentialMode: z.nativeEnum(MCPServerCredentialMode),+ oauthClientId: z.string().trim().optional(),+ oauthClientSecret: z.string().trim().optional()}).and(MCPServerCredentialsSchema);diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsxindex f887b043ed..828d37bb2e 100644--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx@@ -54,7 +54,9 @@ export const AddMCPServerModal = ({ isOpen, onOpenChange }: Props) => {accessToken: "",refreshToken: "",tokenType: "Bearer"- }+ },+ oauthClientId: "",+ oauthClientSecret: ""} as TAddMCPServerForm});@@ -98,7 +100,9 @@ export const AddMCPServerModal = ({ isOpen, onOpenChange }: Props) => {description: data.description || undefined,credentialMode: data.credentialMode as unknown as AiMcpServerCredentialMode,authMethod: data.authMethod as unknown as AiMcpServerAuthMethod,- credentials: data.credentials+ credentials: data.credentials,+ oauthClientId: data.oauthClientId || undefined,+ oauthClientSecret: data.oauthClientSecret || undefined} as TCreateAiMcpServerDTO);createNotification({@@ -179,7 +183,7 @@ export const AddMCPServerModal = ({ isOpen, onOpenChange }: Props) => {<BasicInfoStep /></Tab.Panel><Tab.Panel>- <AuthenticationStep />+ <AuthenticationStep onOAuthSuccess={() => handleSubmit(onSubmit)()} /></Tab.Panel></Tab.Panels></Tab.Group>diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsxindex 28df3ae7b6..240d1fb9c0 100644--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx@@ -8,7 +8,11 @@ import { Button, FormControl, Input, Select, SelectItem } from "@app/components/import { useProject } from "@app/context";import { useGetOAuthStatus, useInitiateOAuth } from "@app/hooks/api";-import { MCPServerAuthMethod, TAddMCPServerForm } from "./AddMCPServerForm.schema";+import {+ MCPServerAuthMethod,+ MCPServerCredentialMode,+ TAddMCPServerForm+} from "./AddMCPServerForm.schema";// Only OAuth is supported for now - other methods are defined in schema for future useconst AUTH_METHOD_OPTIONS = [{ value: MCPServerAuthMethod.OAUTH, label: "OAuth" }];@@ -17,10 +21,16 @@ const OAUTH_POPUP_WIDTH = 600;const OAUTH_POPUP_HEIGHT = 700;const OAUTH_POLL_INTERVAL = 2000; // Poll every 2 seconds-export const AuthenticationStep = () => {+type Props = {+ onOAuthSuccess?: () => void;+};++export const AuthenticationStep = ({ onOAuthSuccess }: Props) => {const { currentProject } = useProject();const { control, watch, setValue, getValues } = useFormContext<TAddMCPServerForm>();const authMethod = watch("authMethod");+ const credentialMode = watch("credentialMode");+ const isPersonalMode = credentialMode === MCPServerCredentialMode.PERSONAL;// OAuth stateconst [oauthSessionId, setOauthSessionId] = useState<string | null>(null);@@ -50,13 +60,17 @@ export const AuthenticationStep = () => {// Mark OAuth as succeeded (for popup close detection)oauthSucceededRef.current = true;- // OAuth completed successfully- setValue("credentials", {- accessToken: oauthStatus.accessToken,- refreshToken: oauthStatus.refreshToken,- expiresAt: oauthStatus.expiresAt,- tokenType: oauthStatus.tokenType || "Bearer"- });+ // OAuth completed successfully - use shouldDirty and shouldTouch to trigger re-renders+ setValue(+ "credentials",+ {+ accessToken: oauthStatus.accessToken,+ refreshToken: oauthStatus.refreshToken,+ expiresAt: oauthStatus.expiresAt,+ tokenType: oauthStatus.tokenType || "Bearer"+ },+ { shouldDirty: true, shouldTouch: true, shouldValidate: true }+ );setIsOAuthPending(false);setOauthSessionId(null);@@ -71,8 +85,16 @@ export const AuthenticationStep = () => {text: "OAuth authorization successful",type: "success"});++ // Auto-submit the form after OAuth succeeds+ if (onOAuthSuccess) {+ // Small delay to ensure form state is updated+ setTimeout(() => {+ onOAuthSuccess();+ }, 100);+ }}- }, [oauthStatus, setValue]);+ }, [oauthStatus, setValue, onOAuthSuccess]);// Cleanup on unmountuseEffect(() => {@@ -162,10 +184,16 @@ export const AuthenticationStep = () => {try {setIsOAuthPending(true);+ // Get optional client credentials+ const clientId = getValues("oauthClientId");+ const clientSecret = getValues("oauthClientSecret");+// 1. Call backend to initiate OAuth and get auth URLconst { authUrl, sessionId } = await initiateOAuth.mutateAsync({url: serverUrl,- projectId: currentProject.id+ projectId: currentProject.id,+ clientId: clientId || undefined,+ clientSecret: clientSecret || undefined});setOauthSessionId(sessionId);@@ -216,9 +244,25 @@ export const AuthenticationStep = () => {return (<>- <p className="mb-4 text-sm text-bunker-300">- Configure shared authentication credentials for the MCP server.- </p>+ {isPersonalMode ? (+ <div className="mb-4 space-y-2">+ <p className="text-sm text-bunker-300">+ Authorize once to discover available tools from the MCP server.+ </p>+ <div className="rounded-md border border-primary-500/30 bg-primary-500/10 p-3">+ <p className="text-xs text-mineshaft-200">+ <span className="font-medium text-primary-400">Note:</span> Since you selected+ Personal Credentials, each user will authenticate with their own credentials when+ accessing this server. This authorization is only used to fetch the list of available+ tools.+ </p>+ </div>+ </div>+ ) : (+ <p className="mb-4 text-sm text-bunker-300">+ Configure shared authentication credentials for the MCP server.+ </p>+ )}<Controllercontrol={control}@@ -301,10 +345,63 @@ export const AuthenticationStep = () => {{authMethod === MCPServerAuthMethod.OAUTH && (<div className="mt-2 space-y-4">+ {/* Optional client credentials for servers without DCR support (like GitHub) */}+ <div className="space-y-3 rounded-md border border-mineshaft-600 bg-mineshaft-700/50 p-4">+ <p className="text-xs text-bunker-300">+ Optional: For MCP servers that don't support Dynamic Client Registration, enter+ your OAuth app credentials below.+ {isPersonalMode &&+ " These will be saved so users don't need to provide them when authenticating."}+ </p>+ <Controller+ control={control}+ name="oauthClientId"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Client ID"+ isError={Boolean(error)}+ errorText={error?.message}+ className="mb-0"+ >+ <Input+ {...field}+ value={field.value || ""}+ placeholder="Optional client ID"+ isDisabled={isOAuthPending || !!isOAuthAuthorized}+ />+ </FormControl>+ )}+ />+ <Controller+ control={control}+ name="oauthClientSecret"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Client Secret"+ isError={Boolean(error)}+ errorText={error?.message}+ className="mb-0"+ >+ <Input+ {...field}+ value={field.value || ""}+ type="password"+ placeholder="Optional client secret"+ isDisabled={isOAuthPending || !!isOAuthAuthorized}+ />+ </FormControl>+ )}+ />+ </div>+{isOAuthAuthorized && (<div className="flex items-center gap-2 rounded-md border border-green/30 bg-green/10 p-3"><FontAwesomeIcon icon={faCheck} className="text-green" />- <span className="text-sm text-green">OAuth authorization successful</span>+ <span className="text-sm text-green">+ {isPersonalMode+ ? "Authorization successful — tools can now be discovered"+ : "OAuth authorization successful"}+ </span></div>)}{!isOAuthAuthorized && isOAuthPending && (@@ -331,7 +428,7 @@ export const AuthenticationStep = () => {isLoading={initiateOAuth.isPending}isDisabled={initiateOAuth.isPending}>- Authorize with OAuth+ {isPersonalMode ? "Authorize to Discover Tools" : "Authorize with OAuth"}</Button>)}</div>diff --git a/frontend/src/pages/organization/McpEndpointFinalizePage/McpEndpointFinalizePage.tsx b/frontend/src/pages/organization/McpEndpointFinalizePage/McpEndpointFinalizePage.tsxindex 2e8c499bab..8bc0b8a429 100644--- a/frontend/src/pages/organization/McpEndpointFinalizePage/McpEndpointFinalizePage.tsx+++ b/frontend/src/pages/organization/McpEndpointFinalizePage/McpEndpointFinalizePage.tsx@@ -1,7 +1,13 @@-import { useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { Helmet } from "react-helmet";import { Controller, useForm } from "react-hook-form";-import { faCheckCircle, faPlug, faSpinner } from "@fortawesome/free-solid-svg-icons";+import {+ faCheckCircle,+ faExternalLink,+ faPlug,+ faSpinner,+ faWarning+} from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";import { Link, useSearch } from "@tanstack/react-router";@@ -9,7 +15,18 @@ import { z } from "zod";import { createNotification } from "@app/components/notifications";import { Button, FormControl, Input } from "@app/components/v2";-import { useFinalizeMcpEndpointOAuth, useGetAiMcpEndpointById } from "@app/hooks/api";+import {+ useFinalizeMcpEndpointOAuth,+ useGetAiMcpEndpointById,+ useGetServersRequiringAuth,+ useInitiateServerOAuth,+ useSaveUserServerCredential+} from "@app/hooks/api";+import { useGetOAuthStatus } from "@app/hooks/api/aiMcpServers/queries";++const OAUTH_POPUP_WIDTH = 600;+const OAUTH_POPUP_HEIGHT = 700;+const OAUTH_POLL_INTERVAL = 2000;const FinalizeFormSchema = z.object({expireIn: z.string().min(1, "Expiration is required")@@ -17,8 +34,20 @@ const FinalizeFormSchema = z.object({type FormData = z.infer<typeof FinalizeFormSchema>;+type ServerOAuthState = {+ serverId: string;+ sessionId: string | null;+ isPending: boolean;+ isAuthorized: boolean;+};+export const McpEndpointFinalizePage = () => {const [isRedirecting, setIsRedirecting] = useState(false);+ const [serverOAuthStates, setServerOAuthStates] = useState<Map<string, ServerOAuthState>>(+ new Map()+ );+ const [activeOAuthServerId, setActiveOAuthServerId] = useState<string | null>(null);+ const popupRef = useRef<Window | null>(null);const search = useSearch({from: "/_authenticate/organization/mcp-endpoint-finalize"@@ -28,7 +57,24 @@ export const McpEndpointFinalizePage = () => {endpointId: search.endpointId});+ const { data: serversRequiringAuth, isLoading: isServersLoading } = useGetServersRequiringAuth({+ endpointId: search.endpointId+ });+const { mutateAsync: finalizeOAuth, isPending } = useFinalizeMcpEndpointOAuth();+ const initiateServerOAuth = useInitiateServerOAuth();+ const saveUserCredential = useSaveUserServerCredential();++ // Get the active session ID for OAuth polling+ const activeServerState = activeOAuthServerId ? serverOAuthStates.get(activeOAuthServerId) : null;++ const { data: oauthStatus } = useGetOAuthStatus(+ { sessionId: activeServerState?.sessionId || "" },+ {+ enabled: Boolean(activeServerState?.sessionId) && activeServerState?.isPending === true,+ refetchInterval: OAUTH_POLL_INTERVAL+ }+ );const {handleSubmit,@@ -41,6 +87,190 @@ export const McpEndpointFinalizePage = () => {}});+ // Initialize server OAuth states when data loads+ useEffect(() => {+ if (serversRequiringAuth && serversRequiringAuth.length > 0) {+ const initialStates = new Map<string, ServerOAuthState>();+ serversRequiringAuth.forEach((server) => {+ initialStates.set(server.id, {+ serverId: server.id,+ sessionId: null,+ isPending: false,+ isAuthorized: server.hasCredentials+ });+ });+ setServerOAuthStates(initialStates);+ }+ }, [serversRequiringAuth]);++ // Handle OAuth status updates+ useEffect(() => {+ if (oauthStatus?.authorized && oauthStatus.accessToken && activeOAuthServerId) {+ // Save the credentials+ saveUserCredential.mutate(+ {+ endpointId: search.endpointId,+ serverId: activeOAuthServerId,+ accessToken: oauthStatus.accessToken,+ refreshToken: oauthStatus.refreshToken,+ expiresAt: oauthStatus.expiresAt,+ tokenType: oauthStatus.tokenType+ },+ {+ onSuccess: () => {+ // Update the state to mark as authorized+ setServerOAuthStates((prev) => {+ const newMap = new Map(prev);+ const state = newMap.get(activeOAuthServerId);+ if (state) {+ newMap.set(activeOAuthServerId, {+ ...state,+ isPending: false,+ isAuthorized: true,+ sessionId: null+ });+ }+ return newMap;+ });++ setActiveOAuthServerId(null);++ createNotification({+ text: "Server authentication successful",+ type: "success"+ });+ },+ onError: () => {+ createNotification({+ text: "Failed to save credentials",+ type: "error"+ });+ }+ }+ );+ }+ }, [oauthStatus, activeOAuthServerId, search.endpointId, saveUserCredential]);++ // Check if popup was closed manually+ useEffect(() => {+ let checkPopupClosed: NodeJS.Timeout | null = null;++ if (activeOAuthServerId && activeServerState?.isPending) {+ checkPopupClosed = setInterval(() => {+ if (popupRef.current?.closed) {+ if (checkPopupClosed) {+ clearInterval(checkPopupClosed);+ }+ // Give some time for the callback to process+ setTimeout(() => {+ const currentState = serverOAuthStates.get(activeOAuthServerId);+ if (currentState && !currentState.isAuthorized) {+ setServerOAuthStates((prev) => {+ const newMap = new Map(prev);+ newMap.set(activeOAuthServerId, {+ ...currentState,+ isPending: false,+ sessionId: null+ });+ return newMap;+ });+ setActiveOAuthServerId(null);+ }+ }, 3000);+ }+ }, 500);+ }++ return () => {+ if (checkPopupClosed) {+ clearInterval(checkPopupClosed);+ }+ };+ }, [activeOAuthServerId, activeServerState?.isPending, serverOAuthStates]);++ const handleServerOAuth = useCallback(+ async (serverId: string) => {+ try {+ // Update state to pending+ setServerOAuthStates((prev) => {+ const newMap = new Map(prev);+ const state = newMap.get(serverId);+ if (state) {+ newMap.set(serverId, { ...state, isPending: true });+ }+ return newMap;+ });+ setActiveOAuthServerId(serverId);++ const { authUrl, sessionId } = await initiateServerOAuth.mutateAsync({+ endpointId: search.endpointId,+ serverId+ });++ // Update state with session ID+ setServerOAuthStates((prev) => {+ const newMap = new Map(prev);+ const state = newMap.get(serverId);+ if (state) {+ newMap.set(serverId, { ...state, sessionId });+ }+ return newMap;+ });++ // Open popup+ const left = window.screenX + (window.outerWidth - OAUTH_POPUP_WIDTH) / 2;+ const top = window.screenY + (window.outerHeight - OAUTH_POPUP_HEIGHT) / 2;++ popupRef.current = window.open(+ authUrl,+ "MCP Server OAuth",+ `width=${OAUTH_POPUP_WIDTH},height=${OAUTH_POPUP_HEIGHT},left=${left},top=${top},scrollbars=yes,resizable=yes`+ );++ if (!popupRef.current) {+ createNotification({+ text: "Failed to open OAuth popup. Please allow popups for this site.",+ type: "error"+ });+ setServerOAuthStates((prev) => {+ const newMap = new Map(prev);+ const state = newMap.get(serverId);+ if (state) {+ newMap.set(serverId, { ...state, isPending: false, sessionId: null });+ }+ return newMap;+ });+ setActiveOAuthServerId(null);+ }+ } catch (error) {+ console.error("Failed to initiate OAuth:", error);+ createNotification({+ text: "Failed to initiate authentication",+ type: "error"+ });+ setServerOAuthStates((prev) => {+ const newMap = new Map(prev);+ const state = newMap.get(serverId);+ if (state) {+ newMap.set(serverId, { ...state, isPending: false, sessionId: null });+ }+ return newMap;+ });+ setActiveOAuthServerId(null);+ }+ },+ [search.endpointId, initiateServerOAuth]+ );++ // Check if all servers requiring auth have been authenticated+ const allServersAuthenticated =+ !serversRequiringAuth ||+ serversRequiringAuth.length === 0 ||+ serversRequiringAuth.every((server) => {+ const state = serverOAuthStates.get(server.id);+ return state?.isAuthorized || server.hasCredentials;+ });+const onSubmit = async ({ expireIn }: FormData) => {try {const { callbackUrl } = await finalizeOAuth({@@ -57,7 +287,6 @@ export const McpEndpointFinalizePage = () => {setIsRedirecting(true);window.location.href = callbackUrl;- // Fallback: try to close the window after 3 seconds if redirect doesn't navigate awaysetTimeout(() => {window.close();}, 3000);@@ -87,6 +316,12 @@ export const McpEndpointFinalizePage = () => {);}+ const hasServersRequiringAuth = serversRequiringAuth && serversRequiringAuth.length > 0;+ const pendingServers = serversRequiringAuth?.filter((server) => {+ const state = serverOAuthStates.get(server.id);+ return !state?.isAuthorized && !server.hasCredentials;+ });+return (<div className="flex min-h-screen flex-col items-center justify-center bg-bunker-800"><Helmet>@@ -134,6 +369,57 @@ export const McpEndpointFinalizePage = () => {</div>)}+ {/* Servers requiring authentication */}+ {!isServersLoading && hasServersRequiringAuth && (+ <div className="mb-6 space-y-2">+ {pendingServers && pendingServers.length > 0 && (+ <p className="flex items-center gap-2 text-xs text-yellow-500">+ <FontAwesomeIcon icon={faWarning} />+ <span>Authenticate with personal credential servers to continue</span>+ </p>+ )}+ {serversRequiringAuth.map((server) => {+ const state = serverOAuthStates.get(server.id);+ const isAuthorized = state?.isAuthorized || server.hasCredentials;+ const isServerPending = state?.isPending;++ return (+ <div+ key={server.id}+ className={`flex items-center justify-between rounded-md border px-3 py-2 ${+ isAuthorized+ ? "border-green-500/30 bg-green-500/5"+ : "border-mineshaft-600 bg-mineshaft-700/50"+ }`}+ >+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium text-mineshaft-100">{server.name}</p>+ </div>+ <div className="ml-3 flex-shrink-0">+ {isAuthorized && (+ <FontAwesomeIcon icon={faCheckCircle} className="text-green-500" />+ )}+ {!isAuthorized && isServerPending && (+ <FontAwesomeIcon icon={faSpinner} className="animate-spin text-yellow-500" />+ )}+ {!isAuthorized && !isServerPending && (+ <Button+ size="xs"+ variant="outline_bg"+ onClick={() => handleServerOAuth(server.id)}+ isLoading={initiateServerOAuth.isPending}+ leftIcon={<FontAwesomeIcon icon={faExternalLink} />}+ >+ Authenticate+ </Button>+ )}+ </div>+ </div>+ );+ })}+ </div>+ )}+<form onSubmit={handleSubmit(onSubmit)}><Controllercontrol={control}@@ -155,7 +441,7 @@ export const McpEndpointFinalizePage = () => {type="submit"className="flex-1"isLoading={isSubmitting || isPending}- isDisabled={isSubmitting || isPending || !endpoint}+ isDisabled={isSubmitting || isPending || !endpoint || !allServersAuthenticated}>Authorize</Button>