Skip to content

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

Merge remote-tracking branch 'origin/main' into sheensantoscapadngan/feat-agent-vault-mcp-proxy

Sheen Capadngan824e63dfa159
diff --cc backend/package-lock.json
index c76e36210d,90c9aa8b5f..d28df710a3
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@@ -121,8 -121,7 +121,8 @@@
"nanoid": "^3.3.18",
"netmask": "^2.0.2",
"node-forge": "^1.4.0",
- "nodemailer": "^8.0.9",
+ "nodemailer": "^10.0.16",
+ "oauth4webapi": "3.8.8",
"oci-common": "^2.108.0",
"oci-identity": "^2.108.0",
"oci-keymanagement": "^2.108.0",
diff --cc backend/package.json
index 1cfb60a231,9a05dc9828..3dd4f82d61
--- a/backend/package.json
+++ b/backend/package.json
@@@ -263,8 -262,7 +262,8 @@@
"nanoid": "^3.3.18",
"netmask": "^2.0.2",
"node-forge": "^1.4.0",
- "nodemailer": "^8.0.9",
+ "nodemailer": "^10.0.16",
+ "oauth4webapi": "3.8.8",
"oci-common": "^2.108.0",
"oci-identity": "^2.108.0",
"oci-keymanagement": "^2.108.0",
diff --cc backend/src/@types/fastify.d.ts
index a6afac37fa,dc9074f969..ed6d7493e0
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@@ -386,7 -386,7 +387,8 @@@ declare module "fastify"
secretScanningV2ProjectResolver: TSecretScanningV2ProjectResolverFactory;
agentVaultProjectResolver: TAgentVaultProjectResolverFactory;
agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;
+ agentVaultOauth: TAgentVaultOauthServiceFactory;
+ agentVaultVariable: TAgentVaultVariableServiceFactory;
agentVaultProxy: TAgentVaultProxyServiceFactory;
agentVaultSession: TAgentVaultSessionServiceFactory;
agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;
diff --cc backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
index d83db32005,f6780f89eb..e885472e2b
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts
@@@ -11,9 -11,7 +11,8 @@@ import { parseHostPatterns } from "@app
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { AGENT_VAULT } from "@app/lib/api-docs";
import { ApiDocsTags } from "@app/lib/api-docs/constants";
- import { readLimit, secretsLimit, writeLimit } from "@app/server/config/rateLimiter";
- import { addNoCacheHeaders } from "@app/server/lib/caching";
+ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { openApiHidden } from "@app/server/lib/schemas";
import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@@ -36,12 -34,9 +35,9 @@@ import
AgentVaultMemberSchema,
AgentVaultNameSchema,
AgentVaultProductMemberSchema,
+ AgentVaultServerUrlSchema,
AgentVaultServiceSchema,
- AgentVaultSubstitutionsUpdateSchema,
- AgentVaultVariableKeySchema,
- AgentVaultVariableSchema,
- AgentVaultVariableValueSchema
- AgentVaultSubstitutionsInputSchema,
+ AgentVaultSubstitutionsUpdateSchema
} from "./agent-vault-schemas";
const AccessBundleDescriptionSchema = z
diff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
index 1e4725b17e,aa8ce81636..9edb70f160
--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts
@@@ -50,29 -48,14 +49,29 @@@ import
AgentVaultVariableReferenceField
} from "../agent-vault/agent-vault-enums";
import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";
+import {
+ assertCredentialTypeSupported,
+ assertServiceFieldsSupported,
+ buildServiceConfig,
+ getAgentVaultServiceType,
+ resolveServiceHostPattern,
+ TAgentVaultServiceConfig
+} from "../agent-vault/agent-vault-service-types";
import {
- AGENT_VAULT_MAX_VARIABLES,
findStoredVariableIds,
findVariableKeys,
toStoredVariableReferences,
toVariableReference
} from "../agent-vault/agent-vault-variable-fns";
import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";
+import {
+ checkOauthClaimUnderLock,
+ checkOauthServerUnderLock,
+ OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE,
+ TAgentVaultOauthServiceFactory
+} from "../agent-vault-oauth/agent-vault-oauth-service";
+import { AGENT_VAULT_OAUTH_HEADER_NAME, TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";
+ import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";
import { TAgentVaultAccessBundleActorRef, TAgentVaultAccessBundleDALFactory } from "./agent-vault-access-bundle-dal";
import {
TAddMembersDTO,
diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts
index b27633f8ab,0000000000..297ac11ef0
mode 100644,000000..100644
--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts
@@@ -1,185 -1,0 +1,184 @@@
+import { createMongoAbility } from "@casl/ability";
+import { describe, expect, test, vi } from "vitest";
+
+import {
+ ProjectPermissionAgentVaultSessionActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { ConflictError } from "@app/lib/errors";
+
+import {
+ AgentVaultCredentialType,
+ AgentVaultOauthStatus,
+ AgentVaultServiceType
+} from "../agent-vault/agent-vault-enums";
+import { AGENT_VAULT_SERVICE_MOVED_MESSAGE } from "../agent-vault-oauth/agent-vault-oauth-service";
+import { TRefreshServiceTokenDTO } from "../agent-vault-oauth/agent-vault-oauth-types";
+import { agentVaultProxyServiceFactory } from "./agent-vault-proxy-service";
+import { TResolveServiceRow } from "./agent-vault-resolve-dal";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
+}));
+
+const PROJECT_ID = "11111111-1111-4111-8111-111111111111";
+const SERVICE_ID = "33333333-3333-4333-8333-333333333333";
+const SERVER_URL = "https://mcp.linear.app/mcp";
+
+const serviceRow = (overrides: Partial<TResolveServiceRow> = {}): TResolveServiceRow => ({
+ id: SERVICE_ID,
+ name: "linear",
- accessBundleId: "22222222-2222-4222-8222-222222222222",
+ accessBundleName: "bundle",
+ type: AgentVaultServiceType.Mcp,
+ hostPattern: "mcp.linear.app",
+ config: { serverUrl: SERVER_URL, transport: "streamable-http" },
+ credentialType: AgentVaultCredentialType.OAuth,
+ credentialConfig: {
+ status: AgentVaultOauthStatus.Connected,
+ // Inside the refresh horizon, so resolve refreshes it.
+ expiresAt: new Date(Date.now() + 10_000).toISOString()
+ },
+ encryptedCredential: Buffer.from(JSON.stringify({ accessToken: "snapshot-access" })),
+ allowedMethods: null,
+ allowedPathPrefixes: null,
+ position: 0,
+ ...overrides
+});
+
+const setup = (refresh: (dto: TRefreshServiceTokenDTO) => Promise<unknown>, rows = [serviceRow()]) => {
+ const refreshServiceToken = vi.fn(refresh);
+ const service = agentVaultProxyServiceFactory({
+ agentVaultProxyDAL: {
+ findByIdWithOrg: async () => ({ projectId: PROJECT_ID, orgId: "org-1", pollInterval: 60 })
+ } as never,
+ agentVaultResolveDAL: { findResolvableServices: async () => rows },
+ agentVaultServiceCustomHeaderDAL: { findByServiceIds: async () => [] },
+ agentVaultServiceSubstitutionDAL: { findByServiceIds: async () => [] },
+ agentVaultVariableDAL: { findValuesForResolve: async () => [] },
+ agentVaultSessionDAL: {
+ findByTokenHash: async () =>
+ ({ id: "session-1", projectId: PROJECT_ID, userId: "user-1", revokedAt: null, expiresAt: null }) as never
+ },
+ agentVaultSessionLogConfigDAL: {
+ findOne: async () => ({
+ id: "logs-config",
+ projectId: PROJECT_ID,
+ enabled: false,
+ createdAt: new Date(),
+ updatedAt: new Date()
+ })
+ },
+ membershipDAL: { findResourceMembershipsForActor: async () => [] },
+ orgDAL: { findEffectiveOrgMembership: async () => ({ isActive: true }) as never },
+ permissionService: {
+ getProjectPermission: async () =>
+ ({
+ permission: createMongoAbility([
+ {
+ action: ProjectPermissionAgentVaultSessionActions.Read,
+ subject: ProjectPermissionSub.AgentVaultSessions
+ }
+ ]),
+ hasRole: () => true,
+ memberships: []
+ }) as never
+ },
+ kmsService: {
+ createCipherPairWithDataKey: async () =>
+ ({ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob }) as never
+ },
+ licenseService: {} as never,
+ resourceAuthMethodService: {} as never,
+ agentVaultOauthService: { refreshServiceToken: refreshServiceToken as never }
+ });
+ return { service, refreshServiceToken };
+};
+
+const refreshed = {
+ credential: {
+ type: "bearer",
+ headerName: "Authorization",
+ headerPrefix: "Bearer",
+ value: "refreshed-access",
+ source: "oauth",
+ expiresAt: null
+ },
+ status: AgentVaultOauthStatus.Connected
+};
+
+const refreshArgs = {
+ proxyId: "proxy-1",
+ orgId: "org-1",
+ sessionToken: "token",
+ serviceId: SERVICE_ID,
+ rejectedTokenHash: "a".repeat(64)
+};
+
+describe("credential refresh", () => {
+ test("a host pattern that no longer matches the service is a 409, before any refresh", async () => {
+ const { service, refreshServiceToken } = setup(async () => refreshed);
+ const result = service.refreshCredential({ ...refreshArgs, hostPattern: "old.example.com" });
+ await expect(result).rejects.toThrow(ConflictError);
+ await expect(result).rejects.toThrow(AGENT_VAULT_SERVICE_MOVED_MESSAGE);
+ expect(refreshServiceToken).not.toHaveBeenCalled();
+ });
+
+ test("a matching host pattern is passed on, so the refresh re-checks it on the rows it reads", async () => {
+ const { service, refreshServiceToken } = setup(async () => refreshed);
+ await expect(service.refreshCredential({ ...refreshArgs, hostPattern: "mcp.linear.app" })).resolves.toEqual(
+ refreshed
+ );
+ expect(refreshServiceToken.mock.calls[0][0].destination).toEqual({ hostPattern: "mcp.linear.app" });
+ });
+});
+
+describe("resolve's lazy refresh", () => {
+ const resolve = (service: ReturnType<typeof setup>["service"]) =>
+ service.resolveSession({ proxyId: "proxy-1", orgId: "org-1", sessionToken: "token", hasSessionLogKey: false });
+
+ test("pins the refresh to the snapshot's host and server URL, and sends what it returns", async () => {
+ const { service, refreshServiceToken } = setup(async () => refreshed);
+ const { services } = await resolve(service);
+ expect(refreshServiceToken.mock.calls[0][0].destination).toEqual({
+ hostPattern: "mcp.linear.app",
+ serverUrl: SERVER_URL
+ });
+ expect(services[0]).toMatchObject({ hostPattern: "mcp.linear.app", credential: { value: "refreshed-access" } });
+ });
+
+ test("a service that moved during the refresh keeps the snapshot's host with the snapshot's own token", async () => {
+ const { service } = setup(async () => {
+ throw new ConflictError({ message: AGENT_VAULT_SERVICE_MOVED_MESSAGE });
+ });
+ const { services } = await resolve(service);
+ expect(services[0]).toMatchObject({
+ hostPattern: "mcp.linear.app",
+ credential: { type: "bearer", value: "snapshot-access", source: "oauth" }
+ });
+ });
+
+ test("an OAuth token is always sent as Authorization: Bearer, whatever its config holds", async () => {
+ const { service } = setup(
+ async () => refreshed,
+ [
+ serviceRow({
+ credentialConfig: {
+ headerName: "X-Api-Key",
+ headerPrefix: "Token",
+ status: AgentVaultOauthStatus.Connected,
+ expiresAt: null
+ }
+ })
+ ]
+ );
+ const { services } = await resolve(service);
+ expect(services[0].credential).toEqual({
+ type: "bearer",
+ headerName: "Authorization",
+ headerPrefix: "Bearer",
+ value: "snapshot-access",
+ source: "oauth",
+ expiresAt: null
+ });
+ });
+});
diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
index 199b4b7a7e,367fe1ca56..648f90fcc2
--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts
@@@ -35,16 -28,6 +35,15 @@@ import { TAgentVaultServiceConfig } fro
import { expandStoredVariableReferences, findStoredVariableIds } from "../agent-vault/agent-vault-variable-fns";
import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";
import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";
- import { TAgentVaultVariableDALFactory } from "../agent-vault-access-bundle/agent-vault-variable-dal";
+import {
+ AGENT_VAULT_SERVICE_MOVED_MESSAGE,
+ TAgentVaultOauthServiceFactory
+} from "../agent-vault-oauth/agent-vault-oauth-service";
+import {
+ AGENT_VAULT_OAUTH_HEADER_NAME,
+ AGENT_VAULT_OAUTH_HEADER_PREFIX,
+ TAgentVaultOauthConfig
+} from "../agent-vault-oauth/agent-vault-oauth-types";
import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";
import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";
import { TAgentVaultSessionLogConfigDALFactory } from "../agent-vault-session-log/agent-vault-session-log-config-dal";
@@@ -383,14 -350,12 +384,13 @@@ export const agentVaultProxyServiceFact
decryptValue
}: {
sessionId: string;
+ projectId: string;
services: TResolvedService[];
- accessBundleIdOf: Map<string, string>;
decryptValue: (encryptedValue: Buffer) => string;
}): Promise<TResolvedService[]> => {
+ // An OAuth token is issued by the provider, never typed, so it holds no reference to expand.
const sealedTextsOf = ({ credential, customHeaders, substitutions }: TResolvedService) => [
- ...(credential.type === AgentVaultCredentialType.Bearer ? [credential.value] : []),
+ ...(credential.type === AgentVaultCredentialType.Bearer && !credential.source ? [credential.value] : []),
...(credential.type === AgentVaultCredentialType.Basic ? [credential.username, credential.password] : []),
...customHeaders.map((header) => header.value),
...substitutions.map((substitution) => substitution.value)
diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
index 857bd0996a,9728fc4129..61bbb11df2
--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts
@@@ -9,11 -9,8 +9,10 @@@ export type TAgentVaultResolveDALFactor
export type TResolveServiceRow = {
id: string;
name: string;
- accessBundleId: string;
accessBundleName: string;
+ type: string;
hostPattern: string;
+ config: unknown;
credentialType: string;
credentialConfig: unknown;
encryptedCredential: Buffer | null;
diff --cc backend/src/server/routes/index.ts
index 740492798c,6b4adffc49..99069652ff
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@@ -30,10 -30,8 +30,9 @@@ import { agentVaultServiceCustomHeaderD
import { agentVaultServiceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-dal";
import { agentVaultServiceSubstitutionDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-substitution-dal";
import { agentVaultServiceVariableReferenceDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-service-variable-reference-dal";
- import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-access-bundle/agent-vault-variable-dal";
import { agentVaultMemberDALFactory } from "@app/ee/services/agent-vault-member/agent-vault-member-dal";
import { agentVaultMembershipServiceFactory } from "@app/ee/services/agent-vault-member/agent-vault-membership-service";
+import { agentVaultOauthServiceFactory } from "@app/ee/services/agent-vault-oauth/agent-vault-oauth-service";
import { agentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-project/agent-vault-project-resolver";
import { agentVaultProxyDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-dal";
import { agentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";
@@@ -1982,15 -2001,12 +2002,21 @@@ export const registerRoutes = async
const agentVaultResolveDAL = agentVaultResolveDALFactory(db);
const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);
+ const agentVaultOauthService = agentVaultOauthServiceFactory({
+ keyStore,
+ kmsService,
+ agentVaultServiceDAL,
+ agentVaultAccessBundleDAL,
+ permissionService,
+ membershipDAL
+ });
+
+ const agentVaultVariableService = agentVaultVariableServiceFactory({
+ agentVaultVariableDAL,
+ permissionService,
+ kmsService
+ });
+
const agentVaultAccessBundleService = agentVaultAccessBundleServiceFactory({
agentVaultAccessBundleDAL,
agentVaultServiceDAL,
@@@ -4671,7 -4700,7 +4712,8 @@@
pamProjectResolver,
agentVaultProjectResolver,
agentVaultAccessBundle: agentVaultAccessBundleService,
+ agentVaultOauth: agentVaultOauthService,
+ agentVaultVariable: agentVaultVariableService,
agentVaultProxy: agentVaultProxyService,
agentVaultSession: agentVaultSessionService,
agentVaultSessionLog: agentVaultSessionLogService,
diff --cc docs/documentation/platform/agent-vault/overview.mdx
index 182362de07,2bf91a8d42..6739a83d52
--- a/docs/documentation/platform/agent-vault/overview.mdx
+++ b/docs/documentation/platform/agent-vault/overview.mdx
@@@ -45,10 -45,10 +45,10 @@@ Set up Agent Vault for the agent you us
Lists of services that AI agents can access during a session.
</Card>
<Card title="Services" icon="plug" href="/documentation/platform/agent-vault/services">
- External APIs that an AI agent can securely call during a session.
+ Anything an AI agent talks to during a session, such as an API or an MCP server.
</Card>
<Card title="Variables" icon="braces" href="/documentation/platform/agent-vault/variables">
- Values you store once in an access bundle and use in any of its services.
+ Values you store once and use in any service in Agent Vault.
</Card>
<Card title="Sessions" icon="monitor" href="/documentation/platform/agent-vault/sessions">
Time-bound grants that let AI agents access services without holding real credentials.
diff --cc docs/documentation/platform/agent-vault/variables.mdx
index e4a551ffff,df208d8668..d9fc7340ab
--- a/docs/documentation/platform/agent-vault/variables.mdx
+++ b/docs/documentation/platform/agent-vault/variables.mdx
@@@ -67,10 -67,10 +67,10 @@@ To use a variable
<Steps>
<Step>
- [Add a service](/documentation/platform/agent-vault/services#add-a-service), or open an existing service's actions menu and select **Edit**. Then go to the **Credential** step.
+ [Add a service](/documentation/platform/agent-vault/services), or open an existing service's actions menu and select **Edit**. Then go to the **Credential** step.
</Step>
<Step>
- In a field that accepts variables, type `{{`. A list of the bundle's variables appears.
+ In a field that accepts variables, type `{{`. A list of your variables appears.
<Frame>
<img src="/images/platform/agent-vault/service-variable-picker.png" alt="The Credential step of a GitHub service, with a partly typed reference in the Token field and a list showing GITHUB_TOKEN and Create GITHUB_" />
diff --cc frontend/src/components/agent-vault/ServiceIconStack.tsx
index f9612b9dc6,29d35d677d..39af88e60a
--- a/frontend/src/components/agent-vault/ServiceIconStack.tsx
+++ b/frontend/src/components/agent-vault/ServiceIconStack.tsx
@@@ -4,8 -4,7 +4,7 @@@ import { GlobeIcon } from "lucide-react
import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";
import { cn } from "@app/components/v3/utils";
-import { findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";
+import { findAnyTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";
- import { TAgentVaultService } from "@app/hooks/api/agentVault/types";
type TServiceIcon = {
label: string;
diff --cc frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
index 7bdd92bd6a,20afa08ac4..254d08ddf9
--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
@@@ -21,20 -21,14 +21,21 @@@ import
} from "@app/components/v3";
import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";
import { hostError } from "@app/helpers/agentVaultHostPattern";
-import { AgentVaultTemplate, findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";
+import {
+ AgentVaultHttpTemplate,
+ AgentVaultMcpTemplate,
+ AgentVaultTemplate,
+ findTemplateForHostPattern
+} from "@app/helpers/agentVaultTemplates";
- import { useDiscardChangesGuard, useWizardSteps } from "@app/hooks";
+ import { findVariableReferences, VARIABLE_KEY_RE } from "@app/helpers/agentVaultVariables";
+ import { useDebounce, useDiscardChangesGuard, useWizardSteps } from "@app/hooks";
import {
AgentVaultCredentialType,
+ AgentVaultMcpTransport,
+ AgentVaultServiceType,
AgentVaultVariableReferenceField,
+ useAgentVaultVariableKeyStatus,
useCreateAgentVaultService,
- useListAgentVaultVariables,
useUpdateAgentVaultService
} from "@app/hooks/api/agentVault";
import {
@@@ -64,8 -54,12 +65,12 @@@ import
TServiceForm,
UNCHANGED_SECRET
} from "./serviceSchema";
- import { NO_STORED_KEYS, ServiceVariablesContext } from "./ServiceVariablesContext";
+ import {
+ NO_MISSING_KEYS,
+ NO_STORED_KEYS,
+ ServiceVariablesContext
+ } from "./ServiceVariablesContext";
-import { SERVICE_DOCS_URL, SERVICE_STEPS } from "./stepMeta";
+import { MCP_SERVICE_STEPS, SERVICE_DOCS_URL, SERVICE_STEPS } from "./stepMeta";
import { ADVANCED_ITEM, TransformationsFields } from "./TransformationsFields";
const BLANK_SERVICE_FORM: TServiceForm = {
@@@ -243,9 -201,35 +247,38 @@@ export const ServiceSheet = (
formState: { errors, isDirty, isSubmitting }
} = formMethods;
+ const isMcp = watch("serviceType") === AgentVaultServiceType.Mcp;
+ const stepFields = isMcp ? MCP_SERVICE_STEP_FIELDS : SERVICE_STEP_FIELDS;
+
+ // Only the keys the form references are looked up, never the whole list.
+ const [secret, username, customHeaders, substitutions] = useWatch({
+ control,
+ name: ["secret", "username", "customHeaders", "substitutions"]
+ });
+ const referencedKeys = useMemo(() => {
+ const texts = [
+ secret,
+ username,
+ ...(customHeaders ?? []).map((header) => header.value),
+ ...(substitutions ?? []).map((substitution) => substitution.value)
+ ];
+ const keys = texts.flatMap((text) =>
+ text && text !== UNCHANGED_SECRET ? findVariableReferences(text) : []
+ );
+ return [...new Set(keys.filter((key) => VARIABLE_KEY_RE.test(key)))].sort().join(",");
+ }, [secret, username, customHeaders, substitutions]);
+ const [debouncedReferencedKeys] = useDebounce(referencedKeys, 300);
+ const { missing: missingKeys } = useAgentVaultVariableKeyStatus(
+ debouncedReferencedKeys ? debouncedReferencedKeys.split(",") : [],
+ { enabled: isOpen }
+ );
+ missingKeysRef.current = missingKeys;
+
+ const serviceVariables = useMemo(
+ () => ({ missingKeys, storedKeys, requestVariable }),
+ [missingKeys, storedKeys, requestVariable]
+ );
+
const discardActionRef = useRef<VoidFunction>(() => onOpenChange(false));
const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =
useDiscardChangesGuard({ isDirty, onDiscard: () => discardActionRef.current() });
diff --cc frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
index 98996cc84b,ad89f006c6..1c38349e98
--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
@@@ -162,75 -104,17 +162,81 @@@ export const SERVICE_STEP_FIELDS: Recor
[ServiceStep.Review]: []
};
+export const MCP_SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {
+ [ServiceStep.Template]: [],
+ [ServiceStep.Details]: ["name", "serverUrl", "transport"],
+ [ServiceStep.Credential]: [
+ "credentialType",
+ "headerName",
+ "headerPrefix",
+ "secret",
+ "oauthAuthorizationId",
+ "oauthClientId",
+ "oauthClientSecret",
+ "customHeaders"
+ ],
+ [ServiceStep.Review]: []
+};
+
+// Spelled out rather than picked from TServiceForm, which is inferred from the schema that calls these.
+type TOAuthFormState = {
+ serverUrl: string;
+ oauthAuthorizationId: string;
+ oauthAuthorizedUrl: string;
+};
+
+// Reusing an authorization after the server URL changes could attach its tokens to another host.
+export const newOAuthAuthorizationId = (form: TOAuthFormState) =>
+ form.oauthAuthorizationId && form.oauthAuthorizedUrl === form.serverUrl.trim()
+ ? form.oauthAuthorizationId
+ : undefined;
+
+export const storedOAuthCredential = (
+ service: TAgentVaultService | null | undefined,
+ serverUrl: string
+): TAgentVaultOAuthCredentialSummary | null =>
+ service?.type === AgentVaultServiceType.Mcp &&
+ service.credential.type === AgentVaultCredentialType.OAuth &&
+ service.config.serverUrl === serverUrl.trim()
+ ? service.credential
+ : null;
+
+export const isOAuthAuthorizationMissing = (
+ form: TOAuthFormState & {
+ serviceType: AgentVaultServiceType;
+ credentialType: AgentVaultCredentialType;
+ },
+ service?: TAgentVaultService | null
+) => {
+ if (
+ form.serviceType !== AgentVaultServiceType.Mcp ||
+ form.credentialType !== AgentVaultCredentialType.OAuth
+ ) {
+ return false;
+ }
+ return !newOAuthAuthorizationId(form) && !storedOAuthCredential(service, form.serverUrl);
+};
+
+export const oauthStatusLabel = (form: TOAuthFormState, service?: TAgentVaultService | null) => {
+ const stored = storedOAuthCredential(service, form.serverUrl);
+ if (newOAuthAuthorizationId(form)) return stored ? "Reauthorized" : "Authorized";
+ return stored ? OAUTH_STATUS_LABELS[stored.status] : "Not authorized";
+};
+
- /** `variableKeys` stays undefined while the list loads, so only the shape of a reference is checked. */
- export const buildServiceSchema = (service?: TAgentVaultService | null, variableKeys?: string[]) =>
+ /**
+ * Missing keys are read when the form validates rather than when the schema is built, since they arrive as each
+ * lookup answers. A key still being checked passes here; the API refuses it on save if it doesn't exist.
+ */
+ export const buildServiceSchema = (
+ service?: TAgentVaultService | null,
+ getMissingKeys?: () => ReadonlySet<string>
+ ) =>
z
.object({
+ serviceType: z.nativeEnum(AgentVaultServiceType),
name: slugSchema({ max: 64, field: "Name" }),
+ serverUrl: z.string(),
+ transport: z.nativeEnum(AgentVaultMcpTransport),
hosts: z.array(z.string()),
// In the form rather than component state so the resolver sees it: trigger() wipes anything set with
// setError, so a refusal held outside the form would let the step advance.
diff --cc frontend/src/components/agent-vault/service-sheet/stepMeta.ts
index cda7daac5a,948a31dfa5..a883763971
--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
@@@ -15,9 -15,6 +15,9 @@@ type StepMeta =
rightTip?: string;
};
+const VARIABLE_TIP =
- "To use one of this bundle's variables, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place.";
++ "To use a variable, type {{ in any value and pick it from the list. The proxy puts the variable's value in its place.";
+
export const SERVICE_STEPS: StepMeta[] = [
{
step: ServiceStep.Template,
diff --cc frontend/src/hooks/api/agentVault/mutations.tsx
index 027c4bc693,e9febb7bc4..5ce907fd7f
--- a/frontend/src/hooks/api/agentVault/mutations.tsx
+++ b/frontend/src/hooks/api/agentVault/mutations.tsx
@@@ -21,12 -20,8 +21,11 @@@ import
TAgentVaultService,
TAgentVaultSessionLogSettings,
TAgentVaultVariable,
- TAgentVaultVariableRef,
TAgentVaultWrittenMember,
+ TCompleteAgentVaultOAuthAuthorizationDTO,
TCreateAgentVaultAccessBundleDTO,
+ TCreateAgentVaultOAuthAuthorizationDTO,
+ TCreateAgentVaultOAuthAuthorizationResponse,
TCreateAgentVaultServiceDTO,
TCreateAgentVaultSessionDTO,
TCreateAgentVaultVariableDTO,
diff --cc frontend/src/hooks/api/agentVault/queries.tsx
index 85086103f4,d21cda2c84..9e179e8932
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@@ -4,8 -4,9 +4,9 @@@ import axios from "axios"
import { apiRequest } from "@app/config/request";
import { useOrganization } from "@app/context";
+ import { VARIABLE_KEY_MAX_LENGTH, VARIABLE_KEY_RE } from "@app/helpers/agentVaultVariables";
-import { AgentVaultMemberType } from "./enums";
+import { AgentVaultMemberType, AgentVaultOAuthAuthorizationStatus } from "./enums";
import {
createSessionLogChunkCache,
decryptSessionLogPage,
diff --cc frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
index cc3f216613,9fe5248afe..f94c68e89b
--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx
@@@ -128,33 -125,19 +127,26 @@@ export const AgentVaultAccessBundleDeta
)}
</PageHeader>
- <div className="flex flex-col gap-8">
- <ServicesCard
- accessBundleId={accessBundle.id}
- services={accessBundle.services}
- canManage={isAdmin}
- onAdd={() => {
- setServiceToEdit(null);
- setServiceSheetStep(undefined);
- setIsServiceSheetOpen(true);
- }}
- onEdit={(service) => {
- setServiceToEdit(service);
- setServiceSheetStep(undefined);
- setIsServiceSheetOpen(true);
- }}
- onReauthorize={(service) => {
- setServiceToEdit(service);
- setServiceSheetStep(ServiceStep.Credential);
- setIsServiceSheetOpen(true);
- }}
- />
-
- {/* The variables routes are admin only. */}
- {isAdmin && (
- <VariablesCard accessBundleId={accessBundle.id} services={accessBundle.services} />
- )}
- </div>
+ <ServicesCard
+ accessBundleId={accessBundle.id}
+ services={accessBundle.services}
+ canManage={isAdmin}
+ onAdd={() => {
+ setServiceToEdit(null);
++ setServiceSheetStep(undefined);
+ setIsServiceSheetOpen(true);
+ }}
+ onEdit={(service) => {
+ setServiceToEdit(service);
++ setServiceSheetStep(undefined);
++ setIsServiceSheetOpen(true);
++ }}
++ onReauthorize={(service) => {
++ setServiceToEdit(service);
++ setServiceSheetStep(ServiceStep.Credential);
+ setIsServiceSheetOpen(true);
+ }}
+ />
<ManageAccessSheet
accessBundle={isManageAccessOpen ? accessBundle : null}