Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

Add support for Bearer Token authentication for MCP servers

Saif94146a9d3fc2
diff --git a/backend/src/ee/routes/v1/ai-mcp-endpoint-router.ts b/backend/src/ee/routes/v1/ai-mcp-endpoint-router.ts
index 9d76833f92..a225e0d3fb 100644
--- a/backend/src/ee/routes/v1/ai-mcp-endpoint-router.ts
+++ b/backend/src/ee/routes/v1/ai-mcp-endpoint-router.ts
@@ -776,7 +776,8 @@ export const registerAiMcpEndpointRouter = async (server: FastifyZodProvider) =>
id: z.string(),
name: z.string(),
url: z.string(),
- hasCredentials: z.boolean()
+ hasCredentials: z.boolean(),
+ authMethod: z.string()
})
)
})
@@ -830,6 +831,44 @@ export const registerAiMcpEndpointRouter = async (server: FastifyZodProvider) =>
}
});
+ // Verify bearer token against MCP server
+ server.route({
+ method: "POST",
+ url: "/:endpointId/servers/:serverId/verify-token",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ endpointId: z.string().uuid().trim().min(1),
+ serverId: z.string().uuid().trim().min(1)
+ }),
+ body: z.object({
+ accessToken: z.string().min(1)
+ }),
+ response: {
+ 200: z.object({
+ valid: z.boolean(),
+ message: z.string().optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const result = await server.services.aiMcpEndpoint.verifyServerBearerToken({
+ endpointId: req.params.endpointId,
+ serverId: req.params.serverId,
+ accessToken: req.body.accessToken,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ return result;
+ }
+ });
+
// Save user credentials after OAuth completes
server.route({
method: "POST",
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.ts
index 9d695a7640..7416ea4c69 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
@@ -52,7 +52,8 @@ import {
TOAuthTokenExchangeDTO,
TSaveUserServerCredentialDTO,
TServerAuthStatus,
- TUpdateAiMcpEndpointDTO
+ TUpdateAiMcpEndpointDTO,
+ TVerifyServerBearerTokenDTO
} from "./ai-mcp-endpoint-types";
type TAiMcpEndpointServiceFactoryDep = {
@@ -1044,7 +1045,8 @@ export const aiMcpEndpointServiceFactory = ({
id: server.id,
name: server.name,
url: server.url,
- hasCredentials: Boolean(existingCredential)
+ hasCredentials: Boolean(existingCredential),
+ authMethod: server.authMethod || "oauth"
};
})
);
@@ -1112,6 +1114,97 @@ export const aiMcpEndpointServiceFactory = ({
});
};
+ // Verify bearer token against MCP server
+ const verifyServerBearerToken = async ({
+ endpointId,
+ serverId,
+ accessToken,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TVerifyServerBearerTokenDTO): Promise<{ valid: boolean; message?: string }> => {
+ const endpoint = await aiMcpEndpointDAL.findById(endpointId);
+ if (!endpoint) {
+ throw new NotFoundError({ message: `MCP endpoint with ID '${endpointId}' not found` });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: endpoint.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.AI
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionMcpEndpointActions.Connect,
+ ProjectPermissionSub.McpEndpoints
+ );
+
+ const server = await aiMcpServerDAL.findById(serverId);
+ if (!server) {
+ throw new NotFoundError({ message: `MCP server with ID '${serverId}' not found` });
+ }
+
+ // Check that the server is linked to this endpoint
+ const serverLink = await aiMcpEndpointServerDAL.findOne({
+ aiMcpEndpointId: endpointId,
+ aiMcpServerId: serverId
+ });
+
+ if (!serverLink) {
+ 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"
+ });
+
+ const transport = new StreamableHTTPClientTransport(new URL(server.url), {
+ requestInit: {
+ headers: {
+ Authorization: `Bearer ${accessToken}`
+ }
+ }
+ });
+
+ await client.connect(transport);
+ await client.listTools();
+ await client.close();
+
+ return { valid: true };
+ } catch (error) {
+ // INFO level as we don't want to spam logs with token verification failures
+ logger.info({ error, serverId, serverUrl: server.url }, "Bearer token verification failed");
+
+ 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";
+ }
+
+ return { valid: false, message };
+ } finally {
+ if (client) {
+ try {
+ await client.close();
+ } catch {
+ // Ignore close errors
+ }
+ }
+ }
+ };
+
// Save user credentials after OAuth completes
const saveUserServerCredential = async ({
endpointId,
@@ -1208,6 +1301,7 @@ export const aiMcpEndpointServiceFactory = ({
oauthTokenExchange,
getServersRequiringAuth,
initiateServerOAuth,
+ verifyServerBearerToken,
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.ts
index ae7a092d79..6b8db4849a 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
@@ -133,6 +133,7 @@ export type TServerAuthStatus = {
name: string;
url: string;
hasCredentials: boolean;
+ authMethod: string;
oauthClientId?: string;
oauthClientSecret?: string;
};
@@ -150,3 +151,9 @@ export type TSaveUserServerCredentialDTO = {
expiresAt?: number;
tokenType?: string;
} & Omit<TProjectPermission, "projectId">;
+
+export type TVerifyServerBearerTokenDTO = {
+ endpointId: string;
+ serverId: string;
+ accessToken: string;
+} & Omit<TProjectPermission, "projectId">;
diff --git a/frontend/src/hooks/api/aiMcpEndpoints/index.ts b/frontend/src/hooks/api/aiMcpEndpoints/index.ts
index f5d69e9cd0..86a46e391f 100644
--- a/frontend/src/hooks/api/aiMcpEndpoints/index.ts
+++ b/frontend/src/hooks/api/aiMcpEndpoints/index.ts
@@ -7,7 +7,8 @@ export {
useFinalizeMcpEndpointOAuth,
useInitiateServerOAuth,
useSaveUserServerCredential,
- useUpdateAiMcpEndpoint
+ useUpdateAiMcpEndpoint,
+ useVerifyServerBearerToken
} from "./mutations";
export {
aiMcpEndpointKeys,
diff --git a/frontend/src/hooks/api/aiMcpEndpoints/mutations.tsx b/frontend/src/hooks/api/aiMcpEndpoints/mutations.tsx
index 8fcdf1fddf..9f45a79117 100644
--- a/frontend/src/hooks/api/aiMcpEndpoints/mutations.tsx
+++ b/frontend/src/hooks/api/aiMcpEndpoints/mutations.tsx
@@ -14,7 +14,9 @@ import {
TFinalizeMcpEndpointOAuthDTO,
TInitiateServerOAuthDTO,
TSaveUserServerCredentialDTO,
- TUpdateAiMcpEndpointDTO
+ TUpdateAiMcpEndpointDTO,
+ TVerifyServerBearerTokenDTO,
+ TVerifyServerBearerTokenResponse
} from "./types";
export const useCreateAiMcpEndpoint = () => {
@@ -151,6 +153,18 @@ export const useInitiateServerOAuth = () => {
});
};
+export const useVerifyServerBearerToken = () => {
+ return useMutation({
+ mutationFn: async ({ endpointId, serverId, accessToken }: TVerifyServerBearerTokenDTO) => {
+ const { data } = await apiRequest.post<TVerifyServerBearerTokenResponse>(
+ `/api/v1/ai/mcp/endpoints/${endpointId}/servers/${serverId}/verify-token`,
+ { accessToken }
+ );
+ return data;
+ }
+ });
+};
+
export const useSaveUserServerCredential = () => {
const queryClient = useQueryClient();
diff --git a/frontend/src/hooks/api/aiMcpEndpoints/types.ts b/frontend/src/hooks/api/aiMcpEndpoints/types.ts
index 13be5040f2..7ba0d8e0e5 100644
--- a/frontend/src/hooks/api/aiMcpEndpoints/types.ts
+++ b/frontend/src/hooks/api/aiMcpEndpoints/types.ts
@@ -88,6 +88,7 @@ export type TServerAuthStatus = {
name: string;
url: string;
hasCredentials: boolean;
+ authMethod: string;
};
export type TInitiateServerOAuthDTO = {
@@ -103,3 +104,14 @@ export type TSaveUserServerCredentialDTO = {
expiresAt?: number;
tokenType?: string;
};
+
+export type TVerifyServerBearerTokenDTO = {
+ endpointId: string;
+ serverId: string;
+ accessToken: string;
+};
+
+export type TVerifyServerBearerTokenResponse = {
+ valid: boolean;
+ message?: string;
+};
diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx
index 97ac7cdf14..d042409558 100644
--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx
+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AddMCPServerModal.tsx
@@ -67,14 +67,22 @@ export const AddMCPServerModal = ({ isOpen, onOpenChange }: Props) => {
const isFinalStep = selectedTabIndex === FORM_TABS.length - 1;
- // Check if OAuth is completed (has access token)
+ // Check if authentication is complete based on method
const authMethod = watch("authMethod");
const credentials = watch("credentials");
+
const isOAuthCompleted =
authMethod === MCPServerAuthMethod.OAUTH &&
"accessToken" in credentials &&
Boolean(credentials.accessToken);
+ const isBearerCompleted =
+ authMethod === MCPServerAuthMethod.BEARER &&
+ "token" in credentials &&
+ Boolean(credentials.token);
+
+ const isAuthCompleted = isOAuthCompleted || isBearerCompleted;
+
const isStepValid = async (index: number) => {
const { fields } = FORM_TABS[index];
return trigger(fields as unknown as (keyof TAddMCPServerForm)[]);
@@ -212,7 +220,7 @@ export const AddMCPServerModal = ({ isOpen, onOpenChange }: Props) => {
onClick={handleNext}
colorSchema="primary"
isLoading={createMcpServer.isPending}
- isDisabled={createMcpServer.isPending || (isFinalStep && !isOAuthCompleted)}
+ isDisabled={createMcpServer.isPending || (isFinalStep && !isAuthCompleted)}
>
{isFinalStep ? "Add MCP Server" : "Next"}
</Button>
diff --git a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx
index 81da3f6e76..6781fbaf87 100644
--- a/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx
+++ b/frontend/src/pages/ai/MCPPage/components/MCPServersTab/AddMCPServerModal/AuthenticationStep.tsx
@@ -14,8 +14,10 @@ import {
TAddMCPServerForm
} from "./AddMCPServerForm.schema";
-// Only OAuth is supported for now - other methods are defined in schema for future use
-const AUTH_METHOD_OPTIONS = [{ value: MCPServerAuthMethod.OAUTH, label: "OAuth" }];
+const AUTH_METHOD_OPTIONS = [
+ { value: MCPServerAuthMethod.OAUTH, label: "OAuth" },
+ { value: MCPServerAuthMethod.BEARER, label: "Bearer Token" }
+];
const OAUTH_POPUP_WIDTH = 600;
const OAUTH_POPUP_HEIGHT = 700;
diff --git a/frontend/src/pages/organization/McpEndpointFinalizePage/McpEndpointFinalizePage.tsx b/frontend/src/pages/organization/McpEndpointFinalizePage/McpEndpointFinalizePage.tsx
index 1bc5933c1c..57a600c0f5 100644
--- a/frontend/src/pages/organization/McpEndpointFinalizePage/McpEndpointFinalizePage.tsx
+++ b/frontend/src/pages/organization/McpEndpointFinalizePage/McpEndpointFinalizePage.tsx
@@ -14,9 +14,14 @@ import {
useGetAiMcpEndpointById,
useGetServersRequiringAuth,
useInitiateServerOAuth,
- useSaveUserServerCredential
+ useSaveUserServerCredential,
+ useVerifyServerBearerToken
} from "@app/hooks/api";
+import { TServerAuthStatus } from "@app/hooks/api/aiMcpEndpoints/types";
import { useGetOAuthStatus } from "@app/hooks/api/aiMcpServers/queries";
+import { AiMcpServerAuthMethod } from "@app/hooks/api/aiMcpServers/types";
+
+import { BearerTokenModal } from "./components/BearerTokenModal";
const OAUTH_POPUP_WIDTH = 600;
const OAUTH_POPUP_HEIGHT = 700;
@@ -38,8 +43,10 @@ export const McpEndpointFinalizePage = () => {
const [isRedirecting, setIsRedirecting] = useState(false);
const [serverStates, setServerStates] = useState<Map<string, ServerOAuthState>>(new Map());
const [activeServerId, setActiveServerId] = useState<string | null>(null);
-
- console.log("I AM A VERSION INDICATOR");
+ const [bearerModalServer, setBearerModalServer] = useState<{ id: string; name: string } | null>(
+ null
+ );
+ const [bearerTokenError, setBearerTokenError] = useState<string | undefined>(undefined);
const search = useSearch({
from: "/_authenticate/organization/mcp-endpoint-finalize"
@@ -56,6 +63,7 @@ export const McpEndpointFinalizePage = () => {
const { mutateAsync: finalizeOAuth, isPending } = useFinalizeMcpEndpointOAuth();
const initiateServerOAuth = useInitiateServerOAuth();
const saveUserCredential = useSaveUserServerCredential();
+ const verifyBearerToken = useVerifyServerBearerToken();
// Get active server's state for polling
const activeState = activeServerId ? serverStates.get(activeServerId) : null;
@@ -236,6 +244,75 @@ export const McpEndpointFinalizePage = () => {
[search.endpointId, initiateServerOAuth]
);
+ const handleServerAuth = useCallback(
+ (server: TServerAuthStatus) => {
+ if (server.authMethod === AiMcpServerAuthMethod.BEARER) {
+ setBearerTokenError(undefined);
+ setBearerModalServer({ id: server.id, name: server.name });
+ } else {
+ // OAuth flow (default for oauth and basic auth types)
+ handleServerOAuth(server.id);
+ }
+ },
+ [handleServerOAuth]
+ );
+
+ const handleBearerTokenSubmit = useCallback(
+ async (token: string) => {
+ if (!bearerModalServer) return;
+
+ setBearerTokenError(undefined);
+
+ try {
+ // First verify the token
+ const { valid, message } = await verifyBearerToken.mutateAsync({
+ endpointId: search.endpointId,
+ serverId: bearerModalServer.id,
+ accessToken: token
+ });
+
+ if (!valid) {
+ setBearerTokenError(message || "Invalid token");
+ return;
+ }
+
+ // Token is valid, save credentials
+ await saveUserCredential.mutateAsync({
+ endpointId: search.endpointId,
+ serverId: bearerModalServer.id,
+ accessToken: token,
+ tokenType: "Bearer"
+ });
+
+ setServerStates((prev) => {
+ const newMap = new Map(prev);
+ newMap.set(bearerModalServer.id, {
+ sessionId: null,
+ isPending: false,
+ isAuthorized: true
+ });
+ return newMap;
+ });
+
+ createNotification({
+ text: "Server authentication successful",
+ type: "success"
+ });
+
+ setBearerModalServer(null);
+ } catch (error) {
+ console.error("Failed to verify/save bearer token:", error);
+ // Extract error message from axios error if available
+ const axiosError = error as { response?: { data?: { message?: string } } };
+ const errorMessage =
+ axiosError?.response?.data?.message ||
+ "Failed to verify token. Please check your token and try again.";
+ setBearerTokenError(errorMessage);
+ }
+ },
+ [bearerModalServer, search.endpointId, verifyBearerToken, saveUserCredential]
+ );
+
const allServersAuthenticated =
!serversRequiringAuth ||
serversRequiringAuth.length === 0 ||
@@ -290,10 +367,6 @@ export const McpEndpointFinalizePage = () => {
}
const hasServersRequiringAuth = serversRequiringAuth && serversRequiringAuth.length > 0;
- const pendingServers = serversRequiringAuth?.filter((server) => {
- const state = serverStates.get(server.id);
- return !state?.isAuthorized && !server.hasCredentials;
- });
return (
<div className="flex min-h-screen flex-col items-center justify-center bg-bunker-800">
@@ -342,13 +415,14 @@ export const McpEndpointFinalizePage = () => {
{/* Servers requiring authentication */}
{!isServersLoading && hasServersRequiringAuth && (
<div className="mt-6 mb-6 space-y-2">
- {pendingServers && pendingServers.length > 0 && (
- <p className="text-xs text-bunker-300">
- {pendingServers.length === 1
+ <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>{" "}
+ {serversRequiringAuth.length === 1
? "The following server uses personal credentials. Authenticate with your own account to access its tools."
: "The following servers use personal credentials. Authenticate with your own accounts to access their tools."}
</p>
- )}
+ </div>
{serversRequiringAuth.map((server) => {
const state = serverStates.get(server.id);
const isAuthorized = state?.isAuthorized || server.hasCredentials;
@@ -366,9 +440,18 @@ export const McpEndpointFinalizePage = () => {
<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">
+ <div className="ml-3 flex shrink-0 items-center gap-2">
{isAuthorized && (
- <FontAwesomeIcon icon={faCheckCircle} className="text-green-500" />
+ <>
+ <FontAwesomeIcon icon={faCheckCircle} className="text-green-500" />
+ <Button
+ size="xs"
+ variant="outline_bg"
+ onClick={() => handleServerAuth(server)}
+ >
+ Re-authenticate
+ </Button>
+ </>
)}
{!isAuthorized && isServerPending && (
<FontAwesomeIcon icon={faSpinner} className="animate-spin text-yellow-500" />
@@ -377,7 +460,7 @@ export const McpEndpointFinalizePage = () => {
<Button
size="xs"
variant="outline_bg"
- onClick={() => handleServerOAuth(server.id)}
+ onClick={() => handleServerAuth(server)}
isLoading={initiateServerOAuth.isPending && activeServerId === server.id}
leftIcon={<FontAwesomeIcon icon={faExternalLink} />}
>
@@ -434,6 +517,15 @@ export const McpEndpointFinalizePage = () => {
</>
)}
</div>
+
+ <BearerTokenModal
+ isOpen={bearerModalServer !== null}
+ onOpenChange={(isOpen) => !isOpen && setBearerModalServer(null)}
+ serverName={bearerModalServer?.name || ""}
+ isLoading={verifyBearerToken.isPending || saveUserCredential.isPending}
+ errorMessage={bearerTokenError}
+ onSubmit={handleBearerTokenSubmit}
+ />
</div>
);
};
diff --git a/frontend/src/pages/organization/McpEndpointFinalizePage/components/BearerTokenModal.tsx b/frontend/src/pages/organization/McpEndpointFinalizePage/components/BearerTokenModal.tsx
new file mode 100644
index 0000000000..0ae3a59d0d
--- /dev/null
+++ b/frontend/src/pages/organization/McpEndpointFinalizePage/components/BearerTokenModal.tsx
@@ -0,0 +1,82 @@
+import { useEffect, useState } from "react";
+
+import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ serverName: string;
+ isLoading?: boolean;
+ errorMessage?: string;
+ onSubmit: (token: string) => void;
+};
+
+export const BearerTokenModal = ({
+ isOpen,
+ onOpenChange,
+ serverName,
+ isLoading,
+ errorMessage,
+ onSubmit
+}: Props) => {
+ const [token, setToken] = useState("");
+
+ // Clear token when modal closes
+ useEffect(() => {
+ if (!isOpen) {
+ setToken("");
+ }
+ }, [isOpen]);
+
+ const handleSubmit = () => {
+ if (token) {
+ onSubmit(token);
+ }
+ };
+
+ return (
+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
+ <ModalContent title="Enter Bearer Token" subTitle={`Authenticate with ${serverName}`}>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleSubmit();
+ }}
+ >
+ <FormControl
+ label="Bearer Token"
+ helperText="This credential will be securely stored in Infisical"
+ isError={Boolean(errorMessage)}
+ errorText={errorMessage}
+ >
+ <Input
+ type="password"
+ value={token}
+ onChange={(e) => setToken(e.target.value)}
+ placeholder="ghp_1a2b3c4d5e6f7g8h9i0j"
+ autoComplete="off"
+ />
+ </FormControl>
+ <div className="flex items-center justify-end">
+ <Button
+ colorSchema="secondary"
+ variant="plain"
+ className="py-2"
+ onClick={() => onOpenChange(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ isDisabled={!token || isLoading}
+ isLoading={isLoading}
+ className="ml-4"
+ >
+ Submit
+ </Button>
+ </div>
+ </form>
+ </ModalContent>
+ </Modal>
+ );
+};