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
Add support for routing MCP server connections through gateways to reach internal network services
Saif3744ff4eddec
diff --git a/backend/src/db/migrations/20260121000000_add-gateway-id-to-ai-mcp-servers.ts b/backend/src/db/migrations/20260121000000_add-gateway-id-to-ai-mcp-servers.tsnew file mode 100644index 0000000000..c0218fd499--- /dev/null+++ b/backend/src/db/migrations/20260121000000_add-gateway-id-to-ai-mcp-servers.ts@@ -0,0 +1,28 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.AiMcpServer)) {+ const hasGatewayId = await knex.schema.hasColumn(TableName.AiMcpServer, "gatewayId");+ if (!hasGatewayId) {+ await knex.schema.alterTable(TableName.AiMcpServer, (t) => {+ t.uuid("gatewayId").nullable();+ t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2).onDelete("SET NULL");+ t.index("gatewayId");+ });+ }+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasTable(TableName.AiMcpServer)) {+ const hasGatewayId = await knex.schema.hasColumn(TableName.AiMcpServer, "gatewayId");+ if (hasGatewayId) {+ await knex.schema.alterTable(TableName.AiMcpServer, (t) => {+ t.dropIndex("gatewayId");+ t.dropColumn("gatewayId");+ });+ }+ }+}diff --git a/backend/src/db/schemas/ai-mcp-servers.ts b/backend/src/db/schemas/ai-mcp-servers.tsindex bc751c616e..42a5714df2 100644--- a/backend/src/db/schemas/ai-mcp-servers.ts+++ b/backend/src/db/schemas/ai-mcp-servers.ts@@ -21,7 +21,8 @@ export const AiMcpServersSchema = z.object({encryptedOauthConfig: zodBuffer.nullable().optional(),projectId: z.string(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ gatewayId: z.string().uuid().nullable().optional()});export type TAiMcpServers = z.infer<typeof AiMcpServersSchema>;diff --git a/backend/src/ee/routes/v1/ai-mcp-endpoint-router.ts b/backend/src/ee/routes/v1/ai-mcp-endpoint-router.tsindex 9fb6a99798..5fa37387ac 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) =>server: mcpServer,transport,projectId,- endpointName+ endpointName,+ cleanup} = await server.services.aiMcpEndpoint.interactWithMcp({endpointId: req.params.endpointId,userId: req.permission.id,@@ -95,11 +96,18 @@ export const registerAiMcpEndpointRouter = async (server: FastifyZodProvider) =>}});- // Close transport when client disconnects+ // Close transport and cleanup gateway proxies when client disconnectsres.raw.on("close", () => {void transport.close().catch((err) => {logger.error(err, "Failed to close transport for mcp endpoint");});++ // Cleanup gateway proxies+ if (cleanup) {+ void cleanup().catch((err) => {+ logger.error(err, "Failed to cleanup gateway proxies for mcp endpoint");+ });+ }});await mcpServer.connect(transport);diff --git a/backend/src/ee/routes/v1/ai-mcp-server-router.ts b/backend/src/ee/routes/v1/ai-mcp-server-router.tsindex 92289f2d03..e2ae794e70 100644--- a/backend/src/ee/routes/v1/ai-mcp-server-router.ts+++ b/backend/src/ee/routes/v1/ai-mcp-server-router.ts@@ -16,7 +16,8 @@ const CreateMcpServerBaseSchema = z.object({description: z.string().trim().max(256).optional(),credentialMode: z.nativeEnum(AiMcpServerCredentialMode),oauthClientId: z.string().trim().min(1).optional(),- oauthClientSecret: z.string().trim().min(1).optional()+ oauthClientSecret: z.string().trim().min(1).optional(),+ gatewayId: z.string().uuid().optional()});const McpServerCredentialsSchema = z.discriminatedUnion("authMethod", [@@ -56,7 +57,8 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {projectId: z.string().uuid().trim().min(1),url: z.string().trim().url(),clientId: z.string().trim().min(1).optional(),- clientSecret: z.string().trim().min(1).optional()+ clientSecret: z.string().trim().min(1).optional(),+ gatewayId: z.string().uuid().optional()}),response: {200: z.object({@@ -72,6 +74,7 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {url: req.body.url,clientId: req.body.clientId,clientSecret: req.body.clientSecret,+ gatewayId: req.body.gatewayId,actorId: req.permission.id,actor: req.permission.type,actorAuthMethod: req.permission.authMethod,@@ -308,7 +311,8 @@ export const registerAiMcpServerRouter = async (server: FastifyZodProvider) => {}),body: z.object({name: z.string().trim().min(1).max(64).optional(),- description: z.string().trim().max(256).optional()+ description: z.string().trim().max(256).optional(),+ gatewayId: z.string().uuid().nullable().optional()}),response: {200: z.object({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 b4ebb8ac01..3b23409896 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@@ -14,6 +14,8 @@ import { getConfig } from "@app/lib/config/env";import { crypto as cryptoModule } from "@app/lib/crypto";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError, UnauthorizedError } from "@app/lib/errors";+import { GatewayProxyProtocol } from "@app/lib/gateway";+import { setupRelayServer } from "@app/lib/gateway-v2/gateway-v2";import { logger } from "@app/lib/logger";import { ms } from "@app/lib/ms";import { PiiEntityType, redactPiiFromObject } from "@app/lib/pii";@@ -29,6 +31,7 @@ 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 { TAiMcpServerUserCredentialDALFactory } from "../ai-mcp-server/ai-mcp-server-user-credential-dal";+import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import { TPermissionServiceFactory } from "../permission/permission-service-types";import { ProjectPermissionMcpEndpointActions, ProjectPermissionSub } from "../permission/project-permission";import { TAiMcpEndpointDALFactory } from "./ai-mcp-endpoint-dal";@@ -75,6 +78,7 @@ type TAiMcpEndpointServiceFactoryDep = {authTokenService: Pick<TAuthTokenServiceFactory, "getUserTokenSessionById">;userDAL: TUserDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;};// OAuth schemas for parsing cached data@@ -131,8 +135,75 @@ export const aiMcpEndpointServiceFactory = ({keyStore,authTokenService,userDAL,- permissionService+ permissionService,+ gatewayV2Service}: TAiMcpEndpointServiceFactoryDep) => {+ /**+ * Opens a long-lived gateway proxy for MCP sessions.+ *+ * This creates a local TCP server that tunnels connections through a V2 gateway+ * to reach MCP servers on private networks. The proxy remains open until the+ * cleanup function is called.+ *+ * @returns Port to connect to and cleanup function, or null if gateway not found+ */+ const $openGatewayProxy = async (inputs: {+ gatewayId: string;+ targetHost: string;+ targetPort: number;+ }): Promise<{ port: number; cleanup: () => Promise<void> } | null> => {+ const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId: inputs.gatewayId,+ targetHost: inputs.targetHost,+ targetPort: inputs.targetPort+ });++ if (!gatewayV2ConnectionDetails) {+ return null;+ }++ const relayServer = await setupRelayServer({+ protocol: GatewayProxyProtocol.Http,+ relayHost: gatewayV2ConnectionDetails.relayHost,+ gateway: gatewayV2ConnectionDetails.gateway,+ relay: gatewayV2ConnectionDetails.relay+ });++ return {+ port: relayServer.port,+ cleanup: relayServer.cleanup+ };+ };++ /**+ * Wraps an HTTP request to route it through a V2 gateway proxy.+ *+ * Used for short-lived operations like OAuth discovery and tool fetching+ * where the connection doesn't need to persist.+ *+ * @throws NotFoundError if the gateway doesn't exist+ */+ const $gatewayHttpProxyWrapper = async <T>(+ inputs: {+ gatewayId: string;+ targetHost: string;+ targetPort: number;+ },+ gatewayCallback: (host: string, port: number) => Promise<T>+ ): Promise<T> => {+ const proxyResult = await $openGatewayProxy(inputs);++ if (!proxyResult) {+ throw new NotFoundError({ message: `Gateway with ID ${inputs.gatewayId} not found or not available` });+ }++ try {+ return await gatewayCallback("http://localhost", proxyResult.port);+ } finally {+ await proxyResult.cleanup();+ }+ };+const interactWithMcp = async ({endpointId,userId,@@ -202,9 +273,15 @@ export const aiMcpEndpointServiceFactory = ({enableJsonResponse: true});- return { server: emptyServer, transport };+ // No-op cleanup since there are no gateway connections+ const cleanup = async () => {};++ return { server: emptyServer, transport, cleanup };}+ // Track gateway proxy cleanup functions for long-lived MCP sessions+ const gatewayCleanups: Array<() => Promise<void>> = [];+// Connect to each server and get their toolsconst mcpClientTools = await Promise.all(validServers.map(async (mcpServer) => {@@ -232,13 +309,19 @@ export const aiMcpEndpointServiceFactory = ({headers.Authorization = `Bearer ${credentialsResult.accessToken}`;}- try {+ // Helper function to connect to MCP server and get tools+ const connectAndGetTools = async (+ serverUrl: string+ ): Promise<{+ client: Client;+ tools: Array<{ name: string; description?: string; inputSchema?: Record<string, unknown> }>;+ }> => {const client = new Client({name: `infisical-mcp-client-${mcpServer.name}`,version: "1.0.0"});- const clientTransport = new StreamableHTTPClientTransport(new URL(mcpServer.url), {+ const clientTransport = new StreamableHTTPClientTransport(new URL(serverUrl), {requestInit: { headers }});@@ -249,8 +332,58 @@ export const aiMcpEndpointServiceFactory = ({return {client,+ tools: tools as Array<{ name: string; description?: string; inputSchema?: Record<string, unknown> }>+ };+ };++ try {+ let clientResult: {+ client: Client;+ tools: Array<{ name: string; description?: string; inputSchema?: Record<string, unknown> }>;+ };++ if (mcpServer.gatewayId) {+ // Route through gateway proxy - use long-lived proxy for V2 gateways+ const urlObj = new URL(mcpServer.url);+ const targetHost = urlObj.hostname;+ let targetPort = 80;+ if (urlObj.port) {+ targetPort = Number(urlObj.port);+ } else if (urlObj.protocol === "https:") {+ targetPort = 443;+ }++ // Try to open a long-lived V2 gateway proxy+ const proxyResult = await $openGatewayProxy({+ gatewayId: mcpServer.gatewayId,+ targetHost,+ targetPort+ });++ if (proxyResult) {+ // V2 gateway - use long-lived proxy, preserving the path from the original URL+ gatewayCleanups.push(proxyResult.cleanup);+ const proxyUrl = `http://localhost:${proxyResult.port}${urlObj.pathname}${urlObj.search}`;+ clientResult = await connectAndGetTools(proxyUrl);+ } else {+ // Fall back to V1 gateway (short-lived, may not work for all MCP operations)+ clientResult = await $gatewayHttpProxyWrapper(+ { gatewayId: mcpServer.gatewayId, targetHost, targetPort },+ async (host, port) => {+ const proxyUrl = `${host}:${port}${urlObj.pathname}${urlObj.search}`;+ return connectAndGetTools(proxyUrl);+ }+ );+ }+ } else {+ // Direct connection (no gateway)+ clientResult = await connectAndGetTools(mcpServer.url);+ }++ return {+ client: clientResult.client,server: mcpServer,- tools: tools as Array<{ name: string; description?: string; inputSchema?: Record<string, unknown> }>,+ tools: clientResult.tools,toolNameToDbId};} catch (error) {@@ -373,7 +506,18 @@ export const aiMcpEndpointServiceFactory = ({enableJsonResponse: true});- return { server, transport, projectId: endpoint.projectId, endpointName: endpoint.name };+ // Create cleanup function that closes all gateway proxies+ const cleanup = async () => {+ await Promise.all(+ gatewayCleanups.map((fn) =>+ fn().catch((err) => {+ logger.error(err, "Failed to cleanup gateway proxy");+ })+ )+ );+ };++ return { server, transport, projectId: endpoint.projectId, endpointName: endpoint.name, cleanup };};const createMcpEndpoint = async ({@@ -1206,48 +1350,70 @@ export const aiMcpEndpointServiceFactory = ({throw new BadRequestError({ message: "This MCP server is not linked to the specified endpoint" });}- // Verify the token by connecting to the MCP server- let client: Client | undefined;- try {- client = new Client({- name: "infisical-mcp-client",- version: "1.0.0"- });+ // Helper function to verify token by connecting to the MCP server+ const verifyWithUrl = async (targetUrl: string): Promise<{ valid: boolean; message?: string }> => {+ let client: Client | undefined;+ try {+ client = new Client({+ name: "infisical-mcp-client",+ version: "1.0.0"+ });- const transport = new StreamableHTTPClientTransport(new URL(server.url), {- requestInit: {- headers: {- Authorization: `Bearer ${accessToken}`+ const transport = new StreamableHTTPClientTransport(new URL(targetUrl), {+ requestInit: {+ headers: {+ Authorization: `Bearer ${accessToken}`+ }}- }- });+ });- await client.connect(transport);- await client.listTools();- await client.close();+ await client.connect(transport);+ await client.listTools();+ await client.close();- return { valid: true };- } catch (error) {- const err = error as { code?: string | number; cause?: { code?: string } };- const errCode = err?.code || err?.cause?.code;+ return { valid: true };+ } catch (error) {+ const err = error as { code?: string | number; cause?: { code?: string } };+ const errCode = err?.code || err?.cause?.code;++ let message = "An unknown error occurred";+ if (errCode === 401 || errCode === 403) {+ message = "Invalid token";+ } else if (errCode === "ECONNREFUSED" || errCode === "ENOTFOUND" || errCode === "ETIMEDOUT") {+ message = "Server unreachable";+ }- let message = "An unknown error occurred";- if (errCode === 401 || errCode === 403) {- message = "Invalid token";- } else if (errCode === "ECONNREFUSED" || errCode === "ENOTFOUND" || errCode === "ETIMEDOUT") {- message = "Server unreachable";+ return { valid: false, message };+ } finally {+ if (client) {+ try {+ await client.close();+ } catch {+ // Ignore close errors+ }+ }}+ };- return { valid: false, message };- } finally {- if (client) {- try {- await client.close();- } catch {- // Ignore close errors- }+ // Route through gateway if configured+ if (server.gatewayId) {+ const urlObj = new URL(server.url);+ const targetHost = urlObj.hostname;+ let targetPort = 80;+ if (urlObj.port) {+ targetPort = Number(urlObj.port);+ } else if (urlObj.protocol === "https:") {+ targetPort = 443;}++ return $gatewayHttpProxyWrapper({ gatewayId: server.gatewayId, targetHost, targetPort }, async (host, port) => {+ const proxyUrl = `${host}:${port}${urlObj.pathname}${urlObj.search}`;+ return verifyWithUrl(proxyUrl);+ });}++ // Direct connection (no gateway)+ return verifyWithUrl(server.url);};// Save user credentials after OAuth completesdiff --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 33d230123c..c778e36998 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@@ -7,23 +7,28 @@ 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 axios from "axios";-import { ActionProjectType } from "@app/db/schemas";+import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { GatewayProxyProtocol } from "@app/lib/gateway";+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";import { logger } from "@app/lib/logger";import { ActorType, AuthMethod } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";+import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";+import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";+import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";import { TAiMcpServerDALFactory } from "./ai-mcp-server-dal";-import { AiMcpServerCredentialMode, AiMcpServerStatus } from "./ai-mcp-server-enum";+import { AiMcpServerAuthMethod, AiMcpServerCredentialMode, AiMcpServerStatus } from "./ai-mcp-server-enum";import { TAiMcpServerToolDALFactory } from "./ai-mcp-server-tool-dal";import {TAiMcpServerCredentials,@@ -51,7 +56,9 @@ type TAiMcpServerServiceFactoryDep = {aiMcpServerUserCredentialDAL: TAiMcpServerUserCredentialDALFactory;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;};export type TAiMcpServerServiceFactory = ReturnType<typeof aiMcpServerServiceFactory>;@@ -150,41 +157,111 @@ export const aiMcpServerServiceFactory = ({aiMcpServerUserCredentialDAL,kmsService,keyStore,- permissionService+ permissionService,+ gatewayV2DAL,+ gatewayV2Service}: TAiMcpServerServiceFactoryDep) => {+ /**+ * Wraps an HTTP request to route it through a V2 gateway proxy.+ *+ * Used for short-lived operations like OAuth discovery and tool fetching+ * where the connection doesn't need to persist.+ *+ * @throws NotFoundError if the gateway doesn't exist+ */+ const $gatewayHttpProxyWrapper = async <T>(+ inputs: {+ gatewayId: string;+ targetHost: string;+ targetPort: number;+ },+ gatewayCallback: (host: string, port: number) => Promise<T>+ ): Promise<T> => {+ const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId: inputs.gatewayId,+ targetHost: inputs.targetHost,+ targetPort: inputs.targetPort+ });++ if (!gatewayV2ConnectionDetails) {+ throw new NotFoundError({ message: `Gateway with ID ${inputs.gatewayId} not found or not available` });+ }++ const callbackResult = await withGatewayV2Proxy(+ async (port) => {+ return gatewayCallback("http://localhost", port);+ },+ {+ relayHost: gatewayV2ConnectionDetails.relayHost,+ gateway: gatewayV2ConnectionDetails.gateway,+ relay: gatewayV2ConnectionDetails.relay,+ protocol: GatewayProxyProtocol.Http+ }+ );++ return callbackResult;+ };+/* eslint-disable @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 */- const fetchMcpTools = async (serverUrl: string, accessToken: string): Promise<TMcpTool[]> => {- let client: Client | undefined;- try {- client = new Client({- name: "infisical-mcp-client",- version: "1.0.0"- });+ const fetchMcpTools = async (serverUrl: string, accessToken: string, gatewayId?: string): Promise<TMcpTool[]> => {+ const fetchToolsCallback = async (host: string, port: number): Promise<TMcpTool[]> => {+ let client: Client | undefined;+ try {+ client = new Client({+ name: "infisical-mcp-client",+ version: "1.0.0"+ });- const transport = new StreamableHTTPClientTransport(new URL(serverUrl), {- requestInit: {- headers: {- Authorization: `Bearer ${accessToken}`+ // When using gateway, construct the URL with localhost and the proxy port, preserving the path+ let targetUrl = serverUrl;+ if (gatewayId) {+ const originalUrl = new URL(serverUrl);+ targetUrl = new URL(`${originalUrl.pathname}${originalUrl.search}`, `${host}:${port}`).toString();+ }++ const transport = new StreamableHTTPClientTransport(new URL(targetUrl), {+ requestInit: {+ headers: {+ Authorization: `Bearer ${accessToken}`+ }}+ });++ await client.connect(transport);+ const { tools } = await client.listTools();++ return tools.map((tool: { name: string; description?: string; inputSchema?: unknown }) => ({+ name: tool.name,+ description: tool.description,+ inputSchema: tool.inputSchema as Record<string, unknown> | undefined+ }));+ } finally {+ if (client) {+ await client.close();}- });+ }+ };- await client.connect(transport);- const { tools } = await client.listTools();+ try {+ if (gatewayId) {+ // Route through gateway proxy+ const urlObj = new URL(serverUrl);+ const targetHost = urlObj.hostname;+ let targetPort = 80;+ if (urlObj.port) {+ targetPort = Number(urlObj.port);+ } else if (urlObj.protocol === "https:") {+ targetPort = 443;+ }- return tools.map((tool: { name: string; description?: string; inputSchema?: unknown }) => ({- name: tool.name,- description: tool.description,- inputSchema: tool.inputSchema as Record<string, unknown> | undefined- }));+ return await $gatewayHttpProxyWrapper({ gatewayId, targetHost, targetPort }, fetchToolsCallback);+ }+ // Direct connection (no gateway)+ return await fetchToolsCallback(serverUrl, 0);} catch (error) {// Log but don't fail - tools can be fetched laterlogger.error(error, "Failed to fetch tools from MCP server");return [];- } finally {- if (client) {- await client.close();- }}};/* 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 */@@ -198,6 +275,71 @@ export const aiMcpServerServiceFactory = ({return match ? match[1] : null;};+ /**+ * Helper to create a gateway-aware HTTP request function+ * Returns a function that can make requests either directly or through a gateway proxy+ */+ const createGatewayAwareRequest = (+ gatewayId: string | undefined,+ mcpUrlObj: URL+ ): {+ get: <T>(url: string) => Promise<{ data: T }>;+ // getRaw returns full response including status and headers (for OAuth discovery that needs 401 headers)+ getRaw: <T>(url: string) => Promise<{ data: T; status: number; headers: Record<string, unknown> }>;+ post: <T>(url: string, data: unknown, config?: { headers?: Record<string, string> }) => Promise<{ data: T }>;+ } => {+ if (!gatewayId) {+ // Direct requests (no gateway)+ return {+ get: <T>(url: string) => request.get<T>(url),+ getRaw: async <T>(url: string) => {+ const response = await request.get<T>(url, { validateStatus: () => true });+ return { data: response.data, status: response.status, headers: response.headers as Record<string, unknown> };+ },+ post: <T>(url: string, data: unknown, config?: { headers?: Record<string, string> }) =>+ request.post<T>(url, data, config)+ };+ }++ // Gateway-proxied requests+ const targetHost = mcpUrlObj.hostname;+ let targetPort = 80;+ if (mcpUrlObj.port) {+ targetPort = Number(mcpUrlObj.port);+ } else if (mcpUrlObj.protocol === "https:") {+ targetPort = 443;+ }++ return {+ get: async <T>(url: string) => {+ return $gatewayHttpProxyWrapper({ gatewayId, targetHost, targetPort }, async (host, port) => {+ // Replace the original host/port with the proxy host/port+ const originalUrl = new URL(url);+ const proxyUrl = new URL(`${originalUrl.pathname}${originalUrl.search}`, `${host}:${port}`).toString();+ return request.get<T>(proxyUrl);+ });+ },+ getRaw: async <T>(url: string) => {+ return $gatewayHttpProxyWrapper({ gatewayId, targetHost, targetPort }, async (host, port) => {+ // Replace the original host/port with the proxy host/port+ const originalUrl = new URL(url);+ const proxyUrl = new URL(`${originalUrl.pathname}${originalUrl.search}`, `${host}:${port}`).toString();+ // Use validateStatus to accept all responses (including 401) so we can access headers+ const response = await request.get<T>(proxyUrl, { validateStatus: () => true });+ return { data: response.data, status: response.status, headers: response.headers as Record<string, unknown> };+ });+ },+ post: async <T>(url: string, data: unknown, config?: { headers?: Record<string, string> }) => {+ return $gatewayHttpProxyWrapper({ gatewayId, targetHost, targetPort }, async (host, port) => {+ // Replace the original host/port with the proxy host/port+ const originalUrl = new URL(url);+ const proxyUrl = new URL(`${originalUrl.pathname}${originalUrl.search}`, `${host}:${port}`).toString();+ return request.post<T>(proxyUrl, data, config);+ });+ }+ };+ };+/*** 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@@ -206,7 +348,8 @@ export const aiMcpServerServiceFactory = ({* 4. Fetch the authorization server metadata*/const discoverOAuthMetadata = async (- mcpUrl: string+ mcpUrl: string,+ gatewayId?: string): Promise<{protectedResource: TOAuthProtectedResourceMetadata;authServer: TOAuthAuthorizationServerMetadata;@@ -216,28 +359,29 @@ export const aiMcpServerServiceFactory = ({const url = new URL(mcpUrl);await verifyHostInputValidity({ host: url.hostname, isGateway: true, isDynamicSecret: false });+ // Create gateway-aware request helper+ const gatewayRequest = createGatewayAwareRequest(gatewayId, url);+// 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)+ // Use getRaw to get full response including status and headers (needed for 401 with WWW-Authenticate)+ const initialResponse = await gatewayRequest.getRaw(mcpUrl);++ if (initialResponse.status === 401) {+ // Extract WWW-Authenticate header from 401 response+ const wwwAuth = initialResponse.headers["www-authenticate"] as string | undefined;+ if (wwwAuth) {+ resourceMetadataUrl = parseWwwAuthenticateHeader(wwwAuth);+ }+ } else if (initialResponse.status >= 200 && initialResponse.status < 300) {+ // If we get a success response, 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;- }+ } else {+ // Other error status codes+ throw new BadRequestError({+ message: `MCP server returned unexpected status: ${initialResponse.status}`+ });}const urlObj = new URL(mcpUrl);@@ -254,7 +398,7 @@ export const aiMcpServerServiceFactory = ({for (const path of possiblePaths) {try {// eslint-disable-next-line no-await-in-loop- const { data } = await request.get<TOAuthProtectedResourceMetadata>(path);+ const { data } = await gatewayRequest.get<TOAuthProtectedResourceMetadata>(path);if (data.authorization_servers?.length > 0) {resourceMetadataUrl = path;break;@@ -270,7 +414,7 @@ export const aiMcpServerServiceFactory = ({// that don't support RFC 9728 Protected Resource Metadata)try {const authServerMetadataUrl = `${urlObj.origin}/.well-known/oauth-authorization-server`;- const { data: authServer } = await request.get<TOAuthAuthorizationServerMetadata>(authServerMetadataUrl);+ const { data: authServer } = await gatewayRequest.get<TOAuthAuthorizationServerMetadata>(authServerMetadataUrl);if (authServer.authorization_endpoint && authServer.token_endpoint) {return {protectedResource: {@@ -293,7 +437,7 @@ export const aiMcpServerServiceFactory = ({}// 2. Fetch protected resource metadata- const { data: protectedResource } = await request.get<TOAuthProtectedResourceMetadata>(resourceMetadataUrl);+ const { data: protectedResource } = await gatewayRequest.get<TOAuthProtectedResourceMetadata>(resourceMetadataUrl);if (!protectedResource.authorization_servers?.length) {throw new BadRequestError({@@ -311,12 +455,12 @@ export const aiMcpServerServiceFactory = ({try {// First try: origin-only formatconst originOnlyUrl = `${authServerUrlObj.origin}/.well-known/oauth-authorization-server`;- const { data } = await request.get<TOAuthAuthorizationServerMetadata>(originOnlyUrl);+ const { data } = await gatewayRequest.get<TOAuthAuthorizationServerMetadata>(originOnlyUrl);authServer = data;} catch {// Second try: origin + pathname formatconst pathnameUrl = `${authServerUrlObj.origin}/.well-known/oauth-authorization-server${authServerUrlObj.pathname !== "/" ? authServerUrlObj.pathname : ""}`;- const { data } = await request.get<TOAuthAuthorizationServerMetadata>(pathnameUrl);+ const { data } = await gatewayRequest.get<TOAuthAuthorizationServerMetadata>(pathnameUrl);authServer = data;}@@ -334,6 +478,7 @@ export const aiMcpServerServiceFactory = ({actorId,clientId,clientSecret,+ gatewayId,actor,actorAuthMethod,actorOrgId@@ -352,13 +497,38 @@ export const aiMcpServerServiceFactory = ({});ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.McpServers);++ // Validate gateway exists and user has permission to attach it+ if (gatewayId) {+ const [gateway] = await gatewayV2DAL.find({ id: gatewayId, orgId: actorOrgId });+ if (!gateway) {+ throw new NotFoundError({ message: `Gateway with ID ${gatewayId} not found` });+ }++ const { permission: orgPermission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor: actor as ActorType,+ actorId,+ orgId: actorOrgId,+ actorAuthMethod: actorAuthMethod as AuthMethod,+ actorOrgId+ });++ ForbiddenError.from(orgPermission).throwUnlessCan(+ OrgPermissionGatewayActions.AttachGateways,+ OrgPermissionSubjects.Gateway+ );+ }}const urlObj = new URL(url);await verifyHostInputValidity({ host: urlObj.hostname, isGateway: true, isDynamicSecret: false });- // 1. Discover OAuth metadata following RFC 9728 flow- const { protectedResource, authServer } = await discoverOAuthMetadata(url);+ // Create gateway-aware request helper for DCR+ const gatewayRequest = createGatewayAwareRequest(gatewayId, urlObj);++ // 1. Discover OAuth metadata following RFC 9728 flow (route through gateway if configured)+ const { protectedResource, authServer } = await discoverOAuthMetadata(url, gatewayId);// 2. Generate session IDconst sessionId = crypto.randomUUID();@@ -382,7 +552,8 @@ export const aiMcpServerServiceFactory = ({});}- const { data: clientMetadata } = await request.post<TOAuthDynamicClientMetadata>(+ // Route DCR request through gateway when configured+ const { data: clientMetadata } = await gatewayRequest.post<TOAuthDynamicClientMetadata>(authServer.registration_endpoint,{redirect_uris: [redirectUri],@@ -406,7 +577,7 @@ export const aiMcpServerServiceFactory = ({const codeVerifier = crypto.randomBytes(32).toString("base64url");const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");- // 6. Store session data in keystore (include auth server token endpoint for callback)+ // 6. Store session data in keystore (include auth server token endpoint and gateway for callback)const sessionData: TOAuthSession = {actorId,codeVerifier,@@ -417,6 +588,7 @@ export const aiMcpServerServiceFactory = ({serverUrl: url,redirectUri,tokenEndpoint: authServer.token_endpoint,+ gatewayId,authorized: false};@@ -467,6 +639,10 @@ export const aiMcpServerServiceFactory = ({});}+ // Create gateway-aware request helper using the stored gatewayId+ const serverUrlObj = new URL(sessionData.serverUrl);+ const gatewayRequest = createGatewayAwareRequest(sessionData.gatewayId, serverUrlObj);+// 2. Exchange code for tokens using the stored token endpointconst tokenParams: Record<string, string> = {grant_type: "authorization_code",@@ -481,7 +657,8 @@ export const aiMcpServerServiceFactory = ({tokenParams.client_secret = sessionData.clientSecret;}- const { data: tokenResponse } = await request.post<TOAuthTokenResponse>(+ // Route token exchange through gateway when configured+ const { data: tokenResponse } = await gatewayRequest.post<TOAuthTokenResponse>(sessionData.tokenEndpoint,new URLSearchParams(tokenParams).toString(),{@@ -563,6 +740,7 @@ export const aiMcpServerServiceFactory = ({credentials,oauthClientId,oauthClientSecret,+ gatewayId,actor,actorId,actorAuthMethod,@@ -579,6 +757,36 @@ export const aiMcpServerServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.McpServers);+ // Block OAuth + Gateway combination (OAuth requires external redirect which doesn't work through gateway)+ if (gatewayId && authMethod === AiMcpServerAuthMethod.OAUTH) {+ throw new BadRequestError({+ message:+ "OAuth authentication is not supported when using a gateway. Please use Bearer or Basic authentication."+ });+ }++ // Validate gateway exists and user has permission to attach it+ if (gatewayId) {+ const [gateway] = await gatewayV2DAL.find({ id: gatewayId, orgId: actorOrgId });+ if (!gateway) {+ throw new NotFoundError({ message: `Gateway with ID ${gatewayId} not found` });+ }++ const { permission: orgPermission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor,+ actorId,+ orgId: actorOrgId,+ actorAuthMethod,+ actorOrgId+ });++ ForbiddenError.from(orgPermission).throwUnlessCan(+ OrgPermissionGatewayActions.AttachGateways,+ OrgPermissionSubjects.Gateway+ );+ }+const encryptedCredentials = await encryptCredentials({projectId,credentials,@@ -606,6 +814,7 @@ export const aiMcpServerServiceFactory = ({authMethod,encryptedCredentials,encryptedOauthConfig,+ gatewayId,status: AiMcpServerStatus.ACTIVE});@@ -619,7 +828,7 @@ export const aiMcpServerServiceFactory = ({}if (accessToken) {- const tools = await fetchMcpTools(url, accessToken);+ const tools = await fetchMcpTools(url, accessToken, gatewayId);if (tools.length > 0) {await aiMcpServerToolDAL.insertMany(@@ -673,7 +882,7 @@ export const aiMcpServerServiceFactory = ({};const updateMcpServer = async (dto: TUpdateAiMcpServerDTO) => {- const { serverId, name, description, actor, actorId, actorAuthMethod, actorOrgId } = dto;+ const { serverId, name, description, gatewayId, actor, actorId, actorAuthMethod, actorOrgId } = dto;const server = await aiMcpServerDAL.findById(serverId);if (!server) {@@ -691,9 +900,32 @@ export const aiMcpServerServiceFactory = ({ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.McpServers);- const updateData: { name?: string; description?: string } = {};+ // Validate gateway if changing to a new gateway+ if (gatewayId !== undefined && gatewayId !== null && gatewayId !== server.gatewayId) {+ const [gateway] = await gatewayV2DAL.find({ id: gatewayId, orgId: actorOrgId });+ if (!gateway) {+ throw new NotFoundError({ message: `Gateway with ID ${gatewayId} not found` });+ }++ const { permission: orgPermission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor,+ actorId,+ orgId: actorOrgId,+ actorAuthMethod,+ actorOrgId+ });++ ForbiddenError.from(orgPermission).throwUnlessCan(+ OrgPermissionGatewayActions.AttachGateways,+ OrgPermissionSubjects.Gateway+ );+ }++ const updateData: { name?: string; description?: string; gatewayId?: string | null } = {};if (name !== undefined) updateData.name = name;if (description !== undefined) updateData.description = description;+ if (gatewayId !== undefined) updateData.gatewayId = gatewayId;const updatedServer = await aiMcpServerDAL.updateById(serverId, updateData);@@ -797,8 +1029,8 @@ export const aiMcpServerServiceFactory = ({throw new BadRequestError({ message: "No access token available for this server" });}- // Fetch tools from MCP server- const fetchedTools = await fetchMcpTools(server.url, accessToken);+ // Fetch tools from MCP server (route through gateway if configured)+ const fetchedTools = await fetchMcpTools(server.url, accessToken, server.gatewayId ?? undefined);// Delete existing toolsawait aiMcpServerToolDAL.delete({ aiMcpServerId: serverId });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 6007d56d38..09aea362d7 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@@ -76,6 +76,7 @@ export type TOAuthSession = {serverUrl: string;redirectUri: string;tokenEndpoint: string; // Stored from OAuth discovery for token exchange+ gatewayId?: string;// Set after callbackaccessToken?: string;refreshToken?: string;@@ -90,6 +91,7 @@ export type TInitiateOAuthDTO = {actorId: string;clientId?: string;clientSecret?: string;+ gatewayId?: string;actor?: string;actorAuthMethod?: ActorAuthMethod;actorOrgId?: string;@@ -113,6 +115,7 @@ export type TCreateAiMcpServerDTO = {credentials: TBasicCredentials | TBearerCredentials | TOAuthCredentials;oauthClientId?: string;oauthClientSecret?: string;+ gatewayId?: string;} & TProjectPermission;export type TListMcpServersDTO = TProjectPermission;@@ -125,6 +128,7 @@ export type TUpdateAiMcpServerDTO = {serverId: string;name?: string;description?: string;+ gatewayId?: string | null;} & Omit<TProjectPermission, "projectId">;export type TDeleteMcpServerDTO = {diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.tsindex ef6b459f83..445af3d683 100644--- a/backend/src/lib/gateway-v2/gateway-v2.ts+++ b/backend/src/lib/gateway-v2/gateway-v2.ts@@ -12,7 +12,7 @@ import { BadRequestError } from "../errors";import { GatewayProxyProtocol } from "../gateway/types";import { logger } from "../logger";-interface IGatewayRelayServer {+export interface IGatewayRelayServer {server: net.Server;port: number;cleanup: () => Promise<void>;@@ -132,7 +132,7 @@ const createGatewayConnection = async (});};-const setupRelayServer = async ({+export const setupRelayServer = async ({protocol,relayHost,gateway,diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 2fb26a5756..29c306bcac 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2518,7 +2518,9 @@ export const registerRoutes = async (aiMcpServerUserCredentialDAL,kmsService,keyStore,- permissionService+ permissionService,+ gatewayV2DAL,+ gatewayV2Service});const aiMcpActivityLogService = aiMcpActivityLogServiceFactory({@@ -2539,7 +2541,8 @@ export const registerRoutes = async (authTokenService: tokenService,aiMcpActivityLogService,userDAL,- permissionService+ permissionService,+ gatewayV2Service});const migrationService = externalMigrationServiceFactory({diff --git a/frontend/src/hooks/api/aiMcpServers/types.ts b/frontend/src/hooks/api/aiMcpServers/types.tsindex 0e8aac7d8a..a13fb0c54e 100644--- a/frontend/src/hooks/api/aiMcpServers/types.ts+++ b/frontend/src/hooks/api/aiMcpServers/types.ts@@ -56,6 +56,7 @@ export type TAiMcpServer = {status: AiMcpServerStatus;credentialMode: AiMcpServerCredentialMode;authMethod: AiMcpServerAuthMethod;+ gatewayId?: string;projectId: string;toolsCount?: number;createdAt: string;@@ -71,6 +72,7 @@ export type TCreateAiMcpServerDTO = {credentialMode: AiMcpServerCredentialMode;oauthClientId?: string;oauthClientSecret?: string;+ gatewayId?: string;} & TAiMcpServerCredentials;// OAuth initiate DTO@@ -79,6 +81,7 @@ export type TInitiateOAuthDTO = {url: string;clientId?: string;clientSecret?: string;+ gatewayId?: string;};export type TInitiateOAuthResponse = {@@ -117,6 +120,7 @@ export type TUpdateAiMcpServerDTO = {serverId: string;name?: string;description?: string;+ gatewayId?: string | null;};export type TAiMcpServerTool = {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 a4398de38c..178fc1f5f4 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@@ -50,7 +50,8 @@ export const AddMCPServerFormSchema = zurl: z.string().trim().min(1, "Endpoint URL is required").url("Must be a valid URL"),credentialMode: z.nativeEnum(MCPServerCredentialMode),oauthClientId: z.string().trim().optional(),- oauthClientSecret: z.string().trim().optional()+ oauthClientSecret: z.string().trim().optional(),+ gatewayId: z.string().uuid().optional().nullable()}).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 d042409558..0924907b12 100644--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx@@ -113,7 +113,8 @@ export const AddMCPServerModal = ({ isOpen, onOpenChange }: Props) => {authMethod: data.authMethod as unknown as AiMcpServerAuthMethod,credentials: data.credentials,oauthClientId: data.oauthClientId || undefined,- oauthClientSecret: data.oauthClientSecret || undefined+ oauthClientSecret: data.oauthClientSecret || undefined,+ gatewayId: data.gatewayId || undefined} as TCreateAiMcpServerDTO);createNotification({diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsxindex 6781fbaf87..14a3b3eebc 100644--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx@@ -33,8 +33,14 @@ export const AuthenticationStep = ({ onOAuthSuccess }: Props) => {const { control, watch, setValue, getValues } = useFormContext<TAddMCPServerForm>();const authMethod = watch("authMethod");const credentialMode = watch("credentialMode");+ const gatewayId = watch("gatewayId");const isPersonalMode = credentialMode === MCPServerCredentialMode.PERSONAL;+ // Filter out OAuth when gateway is selected (OAuth requires browser access to auth page)+ const availableAuthMethods = gatewayId+ ? AUTH_METHOD_OPTIONS.filter((opt) => opt.value !== MCPServerAuthMethod.OAUTH)+ : AUTH_METHOD_OPTIONS;+// OAuth stateconst [oauthSessionId, setOauthSessionId] = useState<string | null>(null);const [isOAuthPending, setIsOAuthPending] = useState(false);@@ -139,6 +145,13 @@ export const AuthenticationStep = ({ onOAuthSuccess }: Props) => {[setValue]);+ // Auto-switch from OAuth to Bearer when gateway is selected+ useEffect(() => {+ if (gatewayId && authMethod === MCPServerAuthMethod.OAUTH) {+ handleAuthMethodChange(MCPServerAuthMethod.BEARER);+ }+ }, [gatewayId, authMethod, handleAuthMethodChange]);+const handleOAuthAuthorize = async () => {const serverUrl = getValues("url");if (!serverUrl) {@@ -160,16 +173,18 @@ export const AuthenticationStep = ({ onOAuthSuccess }: Props) => {try {setIsOAuthPending(true);- // Get optional client credentials+ // Get optional client credentials and gatewayconst clientId = getValues("oauthClientId");const clientSecret = getValues("oauthClientSecret");+ const selectedGatewayId = getValues("gatewayId");// 1. Call backend to initiate OAuth and get auth URLconst { authUrl, sessionId } = await initiateOAuth.mutateAsync({url: serverUrl,projectId: currentProject.id,clientId: clientId || undefined,- clientSecret: clientSecret || undefined+ clientSecret: clientSecret || undefined,+ gatewayId: selectedGatewayId || undefined});setOauthSessionId(sessionId);@@ -235,6 +250,15 @@ export const AuthenticationStep = ({ onOAuthSuccess }: Props) => {</p>)}+ {gatewayId && (+ <div className="mb-4 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> OAuth is not available when+ using a gateway.+ </p>+ </div>+ )}+<Controllercontrol={control}name="authMethod"@@ -254,7 +278,7 @@ export const AuthenticationStep = ({ onOAuthSuccess }: Props) => {position="popper"dropdownContainerClassName="max-w-none">- {AUTH_METHOD_OPTIONS.map((option) => (+ {availableAuthMethods.map((option) => (<SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/BasicInfoStep.tsx b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/BasicInfoStep.tsxindex 4e681da937..a4f9429fca 100644--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/BasicInfoStep.tsx+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/BasicInfoStep.tsx@@ -1,6 +1,11 @@import { Controller, useFormContext } from "react-hook-form";+import { useQuery } from "@tanstack/react-query";-import { FormControl, Input, Select, SelectItem, TextArea } from "@app/components/v2";+import { OrgPermissionCan } from "@app/components/permissions";+import { FormControl, Input, Select, SelectItem, TextArea, Tooltip } from "@app/components/v2";+import { OrgPermissionSubjects } from "@app/context/OrgPermissionContext";+import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";+import { gatewaysQueryKeys } from "@app/hooks/api";import { MCPServerCredentialMode, TAddMCPServerForm } from "./AddMCPServerForm.schema";@@ -27,6 +32,8 @@ export const BasicInfoStep = () => {(option) => option.value === credentialMode);+ const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+return (<><p className="mb-4 text-sm text-bunker-300">@@ -78,6 +85,51 @@ export const BasicInfoStep = () => {)}/>+ <OrgPermissionCan+ I={OrgGatewayPermissionActions.AttachGateways}+ a={OrgPermissionSubjects.Gateway}+ >+ {(isAllowed) => (+ <Controller+ control={control}+ name="gatewayId"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error?.message)}+ errorText={error?.message}+ label="Gateway"+ helperText="Select a gateway to route connections through a private network"+ >+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <Select+ isDisabled={!isAllowed}+ value={value ?? "__none__"}+ onValueChange={(val) => onChange(val === "__none__" ? null : val)}+ className="w-full border border-mineshaft-500"+ dropdownContainerClassName="max-w-none"+ isLoading={isGatewaysLoading}+ placeholder="Default: Internet Gateway"+ position="popper"+ >+ <SelectItem value="__none__">Internet Gateway</SelectItem>+ {gateways?.map((el) => (+ <SelectItem value={el.id} key={el.id}>+ {el.name}+ </SelectItem>+ ))}+ </Select>+ </div>+ </Tooltip>+ </FormControl>+ )}+ />+ )}+ </OrgPermissionCan>+<Controllercontrol={control}name="credentialMode"diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/EditMCPServerModal.tsx b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/EditMCPServerModal.tsxindex 463b7fe921..70cde3aa9d 100644--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/EditMCPServerModal.tsx+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/EditMCPServerModal.tsx@@ -1,15 +1,30 @@import { useEffect } from "react";import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";+import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { createNotification } from "@app/components/notifications";-import { Button, FormControl, Input, Modal, ModalContent, TextArea } from "@app/components/v2";-import { TAiMcpServer, useUpdateAiMcpServer } from "@app/hooks/api";+import { OrgPermissionCan } from "@app/components/permissions";+import {+ Button,+ FormControl,+ Input,+ Modal,+ ModalContent,+ Select,+ SelectItem,+ TextArea,+ Tooltip+} from "@app/components/v2";+import { OrgPermissionSubjects } from "@app/context/OrgPermissionContext";+import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";+import { gatewaysQueryKeys, TAiMcpServer, useUpdateAiMcpServer } from "@app/hooks/api";const EditMCPServerFormSchema = z.object({name: z.string().trim().min(1, "Name is required").max(64, "Name must be 64 characters or less"),- description: z.string().trim().max(256, "Description must be 256 characters or less").optional()+ description: z.string().trim().max(256, "Description must be 256 characters or less").optional(),+ gatewayId: z.string().uuid().nullable().optional()});type TEditMCPServerForm = z.infer<typeof EditMCPServerFormSchema>;@@ -22,6 +37,7 @@ type Props = {export const EditMCPServerModal = ({ isOpen, onOpenChange, server }: Props) => {const updateMcpServer = useUpdateAiMcpServer();+ const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const {control,@@ -32,7 +48,8 @@ export const EditMCPServerModal = ({ isOpen, onOpenChange, server }: Props) => {resolver: zodResolver(EditMCPServerFormSchema),defaultValues: {name: "",- description: ""+ description: "",+ gatewayId: null}});@@ -41,7 +58,8 @@ export const EditMCPServerModal = ({ isOpen, onOpenChange, server }: Props) => {if (server) {reset({name: server.name,- description: server.description || ""+ description: server.description || "",+ gatewayId: server.gatewayId || null});}}, [server, reset]);@@ -58,7 +76,8 @@ export const EditMCPServerModal = ({ isOpen, onOpenChange, server }: Props) => {await updateMcpServer.mutateAsync({serverId: server.id,name: data.name,- description: data.description || undefined+ description: data.description || undefined,+ gatewayId: data.gatewayId});createNotification({@@ -113,6 +132,51 @@ export const EditMCPServerModal = ({ isOpen, onOpenChange, server }: Props) => {)}/>+ <OrgPermissionCan+ I={OrgGatewayPermissionActions.AttachGateways}+ a={OrgPermissionSubjects.Gateway}+ >+ {(isAllowed) => (+ <Controller+ control={control}+ name="gatewayId"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ isError={Boolean(error?.message)}+ errorText={error?.message}+ label="Gateway"+ helperText="Select a gateway to route connections through a private network"+ >+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <Select+ isDisabled={!isAllowed}+ value={value ?? "__none__"}+ onValueChange={(val) => onChange(val === "__none__" ? null : val)}+ className="w-full border border-mineshaft-500"+ dropdownContainerClassName="max-w-none"+ isLoading={isGatewaysLoading}+ placeholder="Default: Internet Gateway"+ position="popper"+ >+ <SelectItem value="__none__">Internet Gateway</SelectItem>+ {gateways?.map((el) => (+ <SelectItem value={el.id} key={el.id}>+ {el.name}+ </SelectItem>+ ))}+ </Select>+ </div>+ </Tooltip>+ </FormControl>+ )}+ />+ )}+ </OrgPermissionCan>+<div className="mt-6 flex justify-end gap-4"><Button onClick={handleClose} colorSchema="secondary" type="button">Cancel