Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: mcp tool filtering
Sheen Capadngan5dcaf059e1ce
diff --git a/backend/src/db/migrations/20261029073000_agent-vault-service-allowed-tools.ts b/backend/src/db/migrations/20261029073000_agent-vault-service-allowed-tools.tsnew file mode 100644index 0000000000..b90d2a3b0a--- /dev/null+++ b/backend/src/db/migrations/20261029073000_agent-vault-service-allowed-tools.ts@@ -0,0 +1,20 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.AgentVaultService, "allowedTools"))) {+ await knex.schema.alterTable(TableName.AgentVaultService, (t) => {+ // NULL allows every tool, like allowedMethods: an empty array is never stored.+ t.specificType("allowedTools", "text[]");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.AgentVaultService, "allowedTools")) {+ await knex.schema.alterTable(TableName.AgentVaultService, (t) => {+ t.dropColumn("allowedTools");+ });+ }+}diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yamlindex 2e03d367dc..3feda1bc3a 100644--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@ -89,6 +89,7 @@ tables:- credentialType- allowedMethods- allowedPathPrefixes+ - allowedTools- type- memberProvidedFields- createdAtdiff --git a/backend/src/db/schemas/agent-vault-services.ts b/backend/src/db/schemas/agent-vault-services.tsindex fb84730d2e..cc880207c7 100644--- a/backend/src/db/schemas/agent-vault-services.ts+++ b/backend/src/db/schemas/agent-vault-services.ts@@ -23,7 +23,8 @@ export const AgentVaultServicesSchema = z.object({allowedPathPrefixes: z.string().array().nullable().optional(),memberProvidedFields: z.string().array().nullable().optional(),type: z.string().default("http"),- config: z.unknown().nullable().optional()+ config: z.unknown().nullable().optional(),+ allowedTools: z.string().array().nullable().optional()});export type TAgentVaultServices = z.infer<typeof AgentVaultServicesSchema>;diff --git 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.tsindex e305b0a408..b5e7632b13 100644--- 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@@ -22,6 +22,7 @@ import {AgentVaultActorRefSchema,AgentVaultCreatedMemberSchema,AgentVaultCreateServiceBodySchema,+ AgentVaultListMcpToolsBodySchema,agentVaultListQuery,AgentVaultMemberIdsSchema,AgentVaultMemberRevokeIdsSchema,@@ -335,6 +336,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProservice.credential.type === AgentVaultCredentialType.OAuth ? service.credential.grantedScopes : undefined,allowedMethods: service.allowedMethods,allowedPathPrefixes: service.allowedPathPrefixes,+ allowedTools: service.allowedTools,memberProvidedFields:service.credential.type === AgentVaultCredentialType.Bearer ||service.credential.type === AgentVaultCredentialType.Basic@@ -357,6 +359,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProhostPatternCount: parseHostPatterns(service.hostPattern).patterns.length,allowedMethodCount: service.allowedMethods?.length ?? 0,allowedPathPrefixCount: service.allowedPathPrefixes?.length ?? 0,+ allowedToolCount: service.allowedTools?.length ?? 0,customHeaderCount: service.customHeaders.length,substitutionCount: service.substitutions.length,variableReferenceCount: service.variableReferences.length@@ -433,6 +436,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro: undefined,allowedMethods: update.allowedMethods,allowedPathPrefixes: update.allowedPathPrefixes,+ allowedTools: update.allowedTools,// The setting after the update, present whenever the update touched the credential.memberProvidedFields:req.body.credential &&@@ -469,6 +473,7 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodProhostPatternCount: parseHostPatterns(service.hostPattern).patterns.length,allowedMethodCount: service.allowedMethods?.length ?? 0,allowedPathPrefixCount: service.allowedPathPrefixes?.length ?? 0,+ allowedToolCount: service.allowedTools?.length ?? 0,customHeaderCount: service.customHeaders.length,substitutionCount: service.substitutions.length,variableReferenceCount: service.variableReferences.length@@ -479,6 +484,42 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}});+ // An action route rather than a GET on the service: on create there is no service yet, and the body carries a+ // credential, which can't go in a query string.+ server.route({+ method: "POST",+ url: "/:accessBundleId/mcp-tools/list",+ config: { rateLimit: writeLimit },+ schema: {+ hide: true,+ operationId: "listAgentVaultMcpTools",+ description: "List the tools an MCP server offers, to choose which ones a service allows",+ tags: [ApiDocsTags.AgentVaultAccessBundles],+ params: z.object({+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)+ }),+ body: AgentVaultListMcpToolsBodySchema,+ response: {+ 200: z.object({+ tools: z+ .object({+ name: z.string().describe(AGENT_VAULT.SERVICE.mcpToolName),+ description: z.string().nullable().describe(AGENT_VAULT.SERVICE.mcpToolDescription)+ })+ .array()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) =>+ server.services.agentVaultAccessBundle.listMcpTools({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ accessBundleId: req.params.accessBundleId,+ ...req.body+ })+ });+server.route({method: "DELETE",url: "/:accessBundleId/services/:serviceId",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.tsindex 3b0b9cb086..6f2c921a71 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-proxy-agent-router.ts@@ -164,6 +164,7 @@ export const registerAgentVaultProxyAgentRouter = async (server: FastifyZodProvihostPattern: z.string(),allowedMethods: z.string().array().nullable(),allowedPathPrefixes: z.string().array().nullable(),+ allowedTools: z.string().array().nullable(),credential: z.discriminatedUnion("type", [ResolvedBearerCredentialSchema,zdiff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex 62acfd26dc..82f15df9bc 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts@@ -22,6 +22,7 @@ import {import { hostPatternSchema } from "@app/ee/services/agent-vault/agent-vault-host-pattern-fns";import { agentVaultPathPrefixListSchema } from "@app/ee/services/agent-vault/agent-vault-path-prefix-schemas";import { agentVaultMcpServerUrlSchema } from "@app/ee/services/agent-vault/agent-vault-service-type-fns";+import { agentVaultAllowedToolsSchema } from "@app/ee/services/agent-vault/agent-vault-tool-name-schemas";import {acceptsVariableReferences,addDuplicateCustomHeaderNameIssues,@@ -286,6 +287,8 @@ export const AgentVaultAllowedPathPrefixesSchema = agentVaultPathPrefixListSchemAGENT_VAULT.SERVICE.allowedPathPrefixes);+export const AgentVaultAllowedToolsSchema = agentVaultAllowedToolsSchema.describe(AGENT_VAULT.SERVICE.allowedTools);+export const AgentVaultCustomHeadersInputSchema = AgentVaultCustomHeaderInputSchema.array().max(AGENT_VAULT_MAX_CUSTOM_HEADERS).superRefine(addDuplicateCustomHeaderNameIssues)@@ -324,7 +327,8 @@ export const AgentVaultCreateServiceBodySchema = z.discriminatedUnion("type", [customHeaders: AgentVaultCustomHeadersInputSchema.optional(),substitutions: AgentVaultSubstitutionsInputSchema.optional(),serverUrl: AgentVaultServerUrlSchema.optional().describe(openApiHidden()),- transport: AgentVaultMcpTransportSchema.optional().describe(openApiHidden())+ transport: AgentVaultMcpTransportSchema.optional().describe(openApiHidden()),+ allowedTools: AgentVaultAllowedToolsSchema.optional().describe(openApiHidden())}).describe(JSON.stringify({ title: "HTTP service" })),z@@ -334,6 +338,7 @@ export const AgentVaultCreateServiceBodySchema = z.discriminatedUnion("type", [serverUrl: AgentVaultServerUrlSchema,transport: AgentVaultMcpTransportSchema,credential: AgentVaultMcpCredentialInputSchema.describe(AGENT_VAULT.SERVICE.mcpCredential),+ allowedTools: AgentVaultAllowedToolsSchema.optional(),customHeaders: AgentVaultCustomHeadersInputSchema.optional(),hostPattern: AgentVaultHostPatternSchema.optional().describe(openApiHidden()),allowedMethods: AgentVaultAllowedMethodsSchema.optional().describe(openApiHidden()),@@ -359,7 +364,8 @@ export const AgentVaultUpdateServiceBodySchema = zcustomHeaders: AgentVaultCustomHeadersUpdateSchema.optional(),substitutions: AgentVaultSubstitutionsUpdateSchema.optional(),serverUrl: AgentVaultServerUrlSchema.nullable().optional().describe(openApiHidden()),- transport: AgentVaultMcpTransportSchema.nullable().optional().describe(openApiHidden())+ transport: AgentVaultMcpTransportSchema.nullable().optional().describe(openApiHidden()),+ allowedTools: AgentVaultAllowedToolsSchema.optional().describe(openApiHidden())}).describe(JSON.stringify({ title: "HTTP service" })),z@@ -369,6 +375,7 @@ export const AgentVaultUpdateServiceBodySchema = zserverUrl: AgentVaultServerUrlSchema.optional(),transport: AgentVaultMcpTransportSchema.optional(),credential: AgentVaultMcpCredentialUpdateSchema.optional().describe(AGENT_VAULT.SERVICE.mcpCredential),+ allowedTools: AgentVaultAllowedToolsSchema.optional(),customHeaders: AgentVaultCustomHeadersUpdateSchema.optional(),hostPattern: AgentVaultHostPatternSchema.optional().describe(openApiHidden()),allowedMethods: AgentVaultAllowedMethodsSchema.optional().describe(openApiHidden()),@@ -382,6 +389,16 @@ export const AgentVaultUpdateServiceBodySchema = z"Provide at least one field besides 'type' to update");+// The service sheet's unsaved values, so the tools are listed with the credential a save would store. `serviceId`+// names the saved service whose stored values fill in what is left out.+export const AgentVaultListMcpToolsBodySchema = z.object({+ serviceId: z.string().uuid().optional().describe(AGENT_VAULT.SERVICE.serviceId),+ serverUrl: AgentVaultServerUrlSchema,+ transport: AgentVaultMcpTransportSchema,+ credential: AgentVaultMcpCredentialUpdateSchema.optional().describe(AGENT_VAULT.SERVICE.mcpCredential),+ customHeaders: AgentVaultCustomHeadersUpdateSchema.optional()+});+const variableReferenceBase = {variableId: z.string().uuid().describe(AGENT_VAULT.VARIABLE.variableId),key: z.string().describe(AGENT_VAULT.VARIABLE.key)@@ -423,6 +440,7 @@ export const AgentVaultServiceSchema = z.object({hostPattern: z.string().describe(AGENT_VAULT.SERVICE.hostPattern),allowedMethods: z.nativeEnum(AgentVaultHttpMethod).array().nullable().describe(AGENT_VAULT.SERVICE.allowedMethods),allowedPathPrefixes: z.string().array().nullable().describe(AGENT_VAULT.SERVICE.allowedPathPrefixes),+ allowedTools: z.string().array().nullable().describe(AGENT_VAULT.SERVICE.allowedTools),credential: AgentVaultCredentialSummarySchema,customHeaders: z.object({diff --git 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.tsindex b904a1385a..7ea2484314 100644--- 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@@ -35,7 +35,11 @@ import {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 {+ AGENT_VAULT_OAUTH_HEADER_NAME,+ AGENT_VAULT_OAUTH_HEADER_PREFIX,+ TAgentVaultOauthConfig+} from "../agent-vault-oauth/agent-vault-oauth-types";import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";import {clearPersonalValuesAfterRevoke,@@ -56,6 +60,7 @@ import {AgentVaultCredentialType,AgentVaultHttpMethod,AgentVaultMemberType,+ AgentVaultOauthStatus,AgentVaultResourceRole,AgentVaultServiceType,AgentVaultSubstitutionSurface,@@ -75,6 +80,7 @@ import {TAgentVaultServiceConfig} from "../agent-vault/agent-vault-service-type-fns";import {+ expandStoredVariableReferences,findStoredVariableIds,findVariableKeys,toStoredVariableReferences,@@ -91,6 +97,7 @@ import {TAgentVaultBearerMemberField,TAgentVaultCredentialSummary,TAgentVaultCredentialUpdate,+ TAgentVaultCustomHeaderUpdate,TAgentVaultVariableReferenceSummary,TCreateAccessBundleDTO,TCreateServiceDTO,@@ -98,6 +105,7 @@ import {TDeleteServiceDTO,TGetAccessBundleDTO,TListAccessBundlesDTO,+ TListMcpToolsDTO,TListMembersDTO,TRevokeMembersDTO,TUpdateAccessBundleDTO,@@ -111,6 +119,7 @@ import {splitCredential,TCredentialWrite} from "./agent-vault-credential-write-fns";+import { listMcpServerTools } from "./agent-vault-mcp-tool-list-fns";import { TAgentVaultServiceCustomHeaderDALFactory } from "./agent-vault-service-custom-header-dal";import { TAgentVaultServiceDALFactory } from "./agent-vault-service-dal";import { TAgentVaultServiceSubstitutionDALFactory } from "./agent-vault-service-substitution-dal";@@ -118,14 +127,18 @@ import {TAgentVaultServiceVariableReferenceDALFactory,TAgentVaultVariableReferenceWithKey} from "./agent-vault-service-variable-reference-dal";-import { planTransformationDiff, TTransformationWrite } from "./agent-vault-transformation-fns";+import {+ matchTransformationRows,+ planTransformationDiff,+ TTransformationWrite+} from "./agent-vault-transformation-fns";type TAgentVaultAccessBundleServiceFactoryDep = {agentVaultAccessBundleDAL: TAgentVaultAccessBundleDALFactory;agentVaultServiceDAL: TAgentVaultServiceDALFactory;agentVaultServiceCustomHeaderDAL: TAgentVaultServiceCustomHeaderDALFactory;agentVaultServiceSubstitutionDAL: TAgentVaultServiceSubstitutionDALFactory;- agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findKeys" | "lockForReference">;+ agentVaultVariableDAL: Pick<TAgentVaultVariableDALFactory, "findKeys" | "lockForReference" | "findValuesForResolve">;agentVaultServiceVariableReferenceDAL: TAgentVaultServiceVariableReferenceDALFactory;agentVaultPersonalValueDAL: Pick<TAgentVaultPersonalValueDALFactory,@@ -144,7 +157,7 @@ type TAgentVaultAccessBundleServiceFactoryDep = {identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;agentVaultOauthService: Pick<TAgentVaultOauthServiceFactory,- "claimAuthorization" | "buildCredentialFromAuthorization"+ "claimAuthorization" | "buildCredentialFromAuthorization" | "readAuthorizationAccessToken" | "refreshServiceToken">;} & TAgentVaultActorNameDALs;@@ -427,6 +440,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundhostPattern: service.hostPattern,allowedMethods: (service.allowedMethods ?? null) as AgentVaultHttpMethod[] | null,allowedPathPrefixes: service.allowedPathPrefixes ?? null,+ allowedTools: service.allowedTools ?? null,credential: summarizeCredential(service),customHeaders: customHeaders.map((header) => ({ id: header.id, name: header.name, prefix: header.prefix })),substitutions: substitutions.map((substitution) => ({@@ -933,6 +947,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundtransport,allowedMethods,allowedPathPrefixes,+ allowedTools,credential,customHeaders,substitutions,@@ -950,6 +965,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundhostPattern: requestedHostPattern,allowedMethods,allowedPathPrefixes,+ allowedTools,customHeaders,substitutions,serverUrl,@@ -1039,6 +1055,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundhostPattern,allowedMethods: allowedMethods ?? null,allowedPathPrefixes: allowedPathPrefixes ?? null,+ allowedTools: allowedTools ?? null,credentialType: credential.type,credentialConfig,encryptedCredential,@@ -1130,6 +1147,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundtransport: sentTransport,allowedMethods: sentAllowedMethods,allowedPathPrefixes: sentAllowedPathPrefixes,+ allowedTools: sentAllowedTools,substitutions: sentSubstitutions,...rest}: TUpdateServiceDTO) => {@@ -1157,6 +1175,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundtransport: sentTransport,allowedMethods: sentAllowedMethods,allowedPathPrefixes: sentAllowedPathPrefixes,+ allowedTools: sentAllowedTools,substitutions: sentSubstitutions},service.hostPattern@@ -1166,13 +1185,20 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundif ([name, credential, customHeaders, ...Object.values(sentFields)].every((value) => value === undefined)) {throw new BadRequestError({ message: "Provide at least one field besides 'type' to update" });}- const { hostPattern: requestedHostPattern, allowedMethods, allowedPathPrefixes, substitutions } = sentFields;+ const {+ hostPattern: requestedHostPattern,+ allowedMethods,+ allowedPathPrefixes,+ allowedTools,+ substitutions+ } = sentFields;const serverUrl = sentFields.serverUrl ?? undefined;const transport = sentFields.transport ?? undefined;assertServiceFieldsSupported(serviceType, {hostPattern: requestedHostPattern,allowedMethods,allowedPathPrefixes,+ allowedTools,customHeaders,substitutions,serverUrl,@@ -1451,6 +1477,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundreconciled.serviceConfig !== undefined ||allowedMethods !== undefined ||allowedPathPrefixes !== undefined ||+ allowedTools !== undefined ||Object.keys(reconciled.credentialUpdate).length > 0;const updatedService = hasColumnUpdate@@ -1463,6 +1490,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund// `null` clears the restriction, `undefined` leaves the column alone....(allowedMethods === undefined ? {} : { allowedMethods }),...(allowedPathPrefixes === undefined ? {} : { allowedPathPrefixes }),+ ...(allowedTools === undefined ? {} : { allowedTools }),...reconciled.credentialUpdate},tx@@ -1636,12 +1664,179 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundtransport,allowedMethods,allowedPathPrefixes,+ allowedTools,substitutions},credentialReplaced};};+ // Unaudited: it changes nothing, and the save that follows is audited.+ const listMcpTools = async ({+ accessBundleId,+ serviceId,+ serverUrl,+ transport,+ credential,+ customHeaders,+ ...rest+ }: TListMcpToolsDTO) => {+ const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultAccessBundleActions.Edit,+ ProjectPermissionSub.AgentVaultAccessBundles+ );+ assertOauthConnectedByUser(rest.ctx, credential);+ if (credential) assertCredentialTypeSupported(getAgentVaultServiceType(AgentVaultServiceType.Mcp), credential.type);++ const service = serviceId+ ? await agentVaultServiceDAL.findByIdInAccessBundle({ id: serviceId, accessBundleId: bundle.id })+ : undefined;+ if (serviceId && !service) throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });+ if (service && service.type !== AgentVaultServiceType.Mcp) {+ throw new BadRequestError({ message: `The service '${service.name}' isn't an MCP service, so it has no tools.` });+ }++ const { decryptor } = await getProjectCipher(rest.projectId);+ const openValue = (sealed: Buffer) =>+ (JSON.parse(decryptor({ cipherTextBlob: sealed }).toString("utf-8")) as { value: string }).value;+ const withPrefix = (prefix: string | undefined, value: string) => (prefix ? `${prefix} ${value}` : value);+ const noAdminTokenError = () =>+ new BadRequestError({+ message: "Each member sets this service's token, so Infisical has no token to load its tools with."+ });++ // Typed values name variables by key and stored ones by id, so typed ones are stored first and every value is+ // filled in the way resolve fills it in.+ const { idOfKey } = await loadProjectVariables(rest.projectId, [+ ...(credential ? credentialReferenceTexts(credential) : []),+ ...(customHeaders ?? []).flatMap((header) =>+ header.value === undefined ? [] : [{ label: `The custom header '${header.name}'`, text: header.value }]+ )+ ]);+ const store = (text: string) => toStoredVariableReferences(text, idOfKey);++ // An OAuth token is issued by the provider, never typed, so like resolve this never expands one.+ let credentialHeader: { name: string; prefix?: string; value: string; isTyped: boolean };+ let usesStoredSecret = false;+ const credentialType = credential?.type ?? (service?.credentialType as AgentVaultCredentialType | undefined);+ if (credentialType === AgentVaultCredentialType.OAuth) {+ let accessToken: string;+ if (credential?.type === AgentVaultCredentialType.OAuth) {+ accessToken = await agentVaultOauthService.readAuthorizationAccessToken({+ authorizationId: credential.authorizationId,+ projectId: rest.projectId,+ accessBundleId: bundle.id,+ serviceId: service?.id,+ ctx: rest.ctx,+ serverUrl+ });+ } else {+ const storedServerUrl = getServiceServerUrl(service!.config);+ // The stored tokens only ever go to the server they were authorized for.+ if (serverUrl !== storedServerUrl)+ throw new BadRequestError({ message: OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE });+ const refreshed = await agentVaultOauthService.refreshServiceToken({+ serviceId: service!.id,+ projectId: rest.projectId,+ expiresWithinSeconds: 60,+ destination: { hostPattern: service!.hostPattern, serverUrl: storedServerUrl }+ });+ if (refreshed.status === AgentVaultOauthStatus.NeedsReauthorization) {+ throw new BadRequestError({+ message: "This service's sign-in is no longer accepted. Reauthorize the service, then load the tools again."+ });+ }+ accessToken = refreshed.credential.value;+ }+ credentialHeader = {+ name: AGENT_VAULT_OAUTH_HEADER_NAME,+ prefix: AGENT_VAULT_OAUTH_HEADER_PREFIX,+ value: accessToken,+ isTyped: false+ };+ } else if (credentialType === AgentVaultCredentialType.Bearer) {+ const stored = service?.credentialType === AgentVaultCredentialType.Bearer ? service : undefined;+ let write: TCredentialWrite;+ if (!credential)+ write = {+ config: stored!.credentialConfig as TAgentVaultCredentialConfig,+ secret: undefined,+ memberProvidedFields: stored!.memberProvidedFields as TAgentVaultMemberProvidedField[] | null+ };+ else if (service) write = mergeCredential(storeCredentialReferences(credential, store), service, null);+ else write = splitCredential(storeCredentialReferences(credential, store));+ if (write.memberProvidedFields?.length) throw noAdminTokenError();++ const config = write.config as Extract<TAgentVaultCredentialConfig, { type: AgentVaultCredentialType.Bearer }>;+ usesStoredSecret = write.secret?.value === undefined;+ const value =+ write.secret?.value ?? (stored?.encryptedCredential ? openValue(stored.encryptedCredential) : undefined);+ if (value === undefined) throw noAdminTokenError();+ credentialHeader = { name: config.headerName, prefix: config.headerPrefix, value, isTyped: true };+ } else {+ throw new BadRequestError({ message: "Add the service's credential, then load the tools." });+ }++ const storedCustomHeaders = service ? await agentVaultServiceCustomHeaderDAL.findByServiceIds([service.id]) : [];+ // Matched the way a save matches them, so the tools load with exactly the headers that save would store.+ const matchedHeaders = customHeaders+ ? matchTransformationRows({+ existing: storedCustomHeaders,+ incoming: customHeaders.map((header) => ({ id: header.id, naturalKey: header.name.toLowerCase() })),+ naturalKeyOfRow: (row) => row.name.toLowerCase(),+ subject: "custom header"+ })+ : storedCustomHeaders;+ const headerSource: (TAgentVaultCustomHeaderUpdate | TAgentVaultServiceCustomHeaders)[] =+ customHeaders ?? storedCustomHeaders;+ const headerTexts = headerSource.map((header, index) => {+ if ("value" in header && header.value !== undefined)+ return { name: header.name, prefix: header.prefix, text: store(header.value) };+ const match = matchedHeaders[index];+ if (!match) {+ throw new BadRequestError({+ message: `Enter a value for the custom header '${header.name}', then load the tools.`+ });+ }+ usesStoredSecret = true;+ return { name: header.name, prefix: header.prefix, text: openValue(match.encryptedValue) };+ });+ // Like the OAuth tokens, saved values only go to the saved server, so a changed URL can't pull them elsewhere.+ if (usesStoredSecret && service && serverUrl !== getServiceServerUrl(service.config)) {+ throw new BadRequestError({+ message:+ "The server URL changed, so Infisical won't send the saved credential or custom header values to it. Enter them again, then load the tools."+ });+ }+ assertCustomHeadersDoNotShadowCredential({ type: credentialType, headerName: credentialHeader.name }, headerTexts);++ const texts = [+ ...(credentialHeader.isTyped ? [credentialHeader.value] : []),+ ...headerTexts.map((header) => header.text)+ ];+ const variableIds = [...new Set(texts.flatMap(findStoredVariableIds))];+ const variableValues = new Map(+ (await agentVaultVariableDAL.findValuesForResolve({ variableIds, projectId: rest.projectId, owner: null })).map(+ (row) => [row.id, openValue(row.encryptedValue)]+ )+ );+ const expand = (text: string) => expandStoredVariableReferences(text, (id) => variableValues.get(id));++ const headerValues = headerTexts.map((header) => ({ ...header, value: expand(header.text) }));+ const credentialValue = credentialHeader.isTyped ? expand(credentialHeader.value) : credentialHeader.value;+ const tools = await listMcpServerTools({+ serverUrl,+ transport,+ headers: {+ ...Object.fromEntries(headerValues.map((header) => [header.name, withPrefix(header.prefix, header.value)])),+ [credentialHeader.name]: withPrefix(credentialHeader.prefix, credentialValue)+ },+ secrets: [credentialValue, ...headerValues.map((header) => header.value)]+ });+ return { tools };+ };+const deleteService = async ({ accessBundleId, serviceId, ...rest }: TDeleteServiceDTO) => {const { bundle, permission } = await resolveReachableBundle({ ...rest, accessBundleId });ForbiddenError.from(permission).throwUnlessCan(@@ -1853,6 +2048,7 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBunddeleteAccessBundle,createService,updateService,+ listMcpTools,deleteService,listMembers,listAvailableMembers,diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.tsindex dba68e7432..0895f4c826 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts@@ -122,6 +122,7 @@ export type TCreateServiceDTO = TAgentVaultProjectScoped & {transport?: AgentVaultMcpTransport;allowedMethods?: AgentVaultHttpMethod[] | null;allowedPathPrefixes?: string[] | null;+ allowedTools?: string[] | null;credential: TAgentVaultCredentialInput;customHeaders?: TAgentVaultCustomHeaderInput[];substitutions?: TAgentVaultSubstitutionInput[];@@ -139,11 +140,23 @@ export type TUpdateServiceDTO = TAgentVaultProjectScoped & {transport?: AgentVaultMcpTransport | null;allowedMethods?: AgentVaultHttpMethod[] | null;allowedPathPrefixes?: string[] | null;+ allowedTools?: string[] | null;credential?: TAgentVaultCredentialUpdate;customHeaders?: TAgentVaultCustomHeaderUpdate[];substitutions?: TAgentVaultSubstitutionUpdate[];};+// What the service sheet would save, so the tools are listed with the credential agents will use. On edit, a value+// left out falls back to what the saved service stores, as on update.+export type TListMcpToolsDTO = TAgentVaultProjectScoped & {+ accessBundleId: string;+ serviceId?: string;+ serverUrl: string;+ transport: AgentVaultMcpTransport;+ credential?: TAgentVaultCredentialUpdate;+ customHeaders?: TAgentVaultCustomHeaderUpdate[];+};+export type TDeleteServiceDTO = TAgentVaultProjectScoped & {accessBundleId: string;serviceId: string;diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-mcp-tool-list-fns.test.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-mcp-tool-list-fns.test.tsnew file mode 100644index 0000000000..ec527c2e9d--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-mcp-tool-list-fns.test.ts@@ -0,0 +1,314 @@+import { PassThrough, Readable } from "node:stream";++import { describe, expect, test, vi } from "vitest";++import { AgentVaultHttpMethod, AgentVaultMcpTransport } from "../agent-vault/agent-vault-enums";+import { listMcpServerTools, MCP_TOOL_LIST_MAX_TOOLS, TMcpHttpClient } from "./agent-vault-mcp-tool-list-fns";++vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++const SERVER_URL = "https://mcp.example.com/mcp";+const AUTH = { Authorization: "Bearer secret-token" };+const SECRETS = ["secret-token"];++type TRequest = Parameters<TMcpHttpClient["request"]>[0];+type TMessage = { id?: number; method?: string; params?: { cursor?: string } };++const json = (status: number, body: unknown, sessionId: string | null = null) => ({+ status,+ contentType: "application/json",+ sessionId,+ body: Readable.from([Buffer.from(JSON.stringify(body))])+});++const sse = (messages: unknown[]) => ({+ status: 200,+ contentType: "text/event-stream",+ sessionId: null,+ body: Readable.from([+ Buffer.from(messages.map((message) => `event: message\r\ndata: ${JSON.stringify(message)}\r\n\r\n`).join(""))+ ])+});++const event = (message: unknown) => `event: message\ndata: ${JSON.stringify(message)}\n\n`;++const accepted = () => ({ status: 202, contentType: "", sessionId: null, body: Readable.from([]) });++const toolsPage = (names: string[], nextCursor?: string) => ({+ tools: names.map((name) => ({ name, description: `Does ${name}`, inputSchema: {} })),+ ...(nextCursor ? { nextCursor } : {})+});++// A streamable HTTP server whose tools/list answer is chosen per request.+const streamableServer = (answerToolsList: (message: TMessage) => ReturnType<typeof json | typeof sse>) => {+ const requests: TRequest[] = [];+ const http: TMcpHttpClient = {+ request: async (request) => {+ requests.push(request);+ if (request.method === AgentVaultHttpMethod.Delete) return accepted();+ const message = JSON.parse(request.body!) as TMessage;+ if (message.method === "initialize") {+ return json(200, { jsonrpc: "2.0", id: message.id, result: { protocolVersion: "2025-06-18" } }, "session-1");+ }+ if (message.method === "notifications/initialized") return accepted();+ return answerToolsList(message);+ }+ };+ return { http, requests };+};++describe("listing an MCP server's tools", () => {+ test("streamable HTTP follows pagination, sends the session and credential, and reads JSON and SSE answers", async () => {+ const { http, requests } = streamableServer((message) =>+ message.params?.cursor+ ? sse([{ jsonrpc: "2.0", id: message.id, result: toolsPage(["write_file"]) }])+ : json(200, { jsonrpc: "2.0", id: message.id, result: toolsPage(["read_file", " bad name"], "page-2") })+ );++ const tools = await listMcpServerTools({+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ headers: AUTH,+ secrets: SECRETS,+ http+ });++ expect(tools).toEqual([+ { name: "read_file", description: "Does read_file" },+ { name: "write_file", description: "Does write_file" }+ ]);+ const listCalls = requests.filter((request) => request.body?.includes("tools/list"));+ expect(listCalls).toHaveLength(2);+ expect(listCalls[1].headers).toMatchObject({+ Authorization: "Bearer secret-token",+ "Mcp-Session-Id": "session-1",+ "MCP-Protocol-Version": "2025-06-18"+ });+ });++ test("a rejected credential says so", async () => {+ const http: TMcpHttpClient = { request: async () => json(401, {}) };+ await expect(+ listMcpServerTools({+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ headers: AUTH,+ secrets: SECRETS,+ http+ })+ ).rejects.toThrow("'mcp.example.com' rejected the credential (HTTP 401).");+ });++ test.each(["bad token Bearer secret-token", "bad token secret-token"])(+ "a server error is reported without echoing the credential (%s)",+ async (errorMessage) => {+ const { http } = streamableServer((message) =>+ json(200, { jsonrpc: "2.0", id: message.id, error: { code: -32000, message: errorMessage } })+ );+ const error = await listMcpServerTools({+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ headers: AUTH,+ secrets: SECRETS,+ http+ }).catch((err: Error) => err);+ expect((error as Error).message).toContain("returned an error");+ expect((error as Error).message).not.toContain("secret-token");+ }+ );++ test("a token echoed in a description is redacted and a repeated name is listed once", async () => {+ const { http } = streamableServer((message) =>+ json(200, {+ jsonrpc: "2.0",+ id: message.id,+ result: {+ tools: [+ { name: "read_file", description: "Uses secret-token" },+ { name: "read_file", description: "Again" }+ ]+ }+ })+ );+ const tools = await listMcpServerTools({+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ headers: AUTH,+ secrets: SECRETS,+ http+ });+ expect(tools).toEqual([{ name: "read_file", description: "Uses [redacted]" }]);+ });++ test("a server ping is answered, and its id, the pending one reused, isn't taken for the answer", async () => {+ const stream = new PassThrough();+ let listId: number | undefined;+ const { http, requests } = streamableServer((message) => {+ if (message.method === "tools/list") {+ listId = message.id;+ stream.write(event({ jsonrpc: "2.0", id: message.id, method: "ping" }));+ return { ...sse([]), body: stream };+ }+ // The ping's answer: only then does this server send the tool list.+ stream.end(event({ jsonrpc: "2.0", id: listId, result: toolsPage(["read_file"]) }));+ return accepted();+ });+ const tools = await listMcpServerTools({+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ headers: AUTH,+ secrets: SECRETS,+ http,+ budgetMs: 1000+ });+ expect(tools.map((tool) => tool.name)).toEqual(["read_file"]);+ const pong = requests.find((request) => request.body?.includes('"result"'));+ expect(JSON.parse(pong!.body!)).toEqual({ jsonrpc: "2.0", id: listId, result: {} });+ expect(pong!.headers).toMatchObject({ "Mcp-Session-Id": "session-1" });+ });++ test("a temporary server failure asks to try again and still ends the session", async () => {+ const { http, requests } = streamableServer(() => json(503, {}));+ await expect(+ listMcpServerTools({+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ headers: AUTH,+ secrets: SECRETS,+ http+ })+ ).rejects.toThrow("couldn't answer right now (HTTP 503). Try again in a few minutes.");+ expect(requests.some((request) => request.method === AgentVaultHttpMethod.Delete)).toBe(true);+ });++ test("more tools than the cap are refused", async () => {+ const names = Array.from({ length: MCP_TOOL_LIST_MAX_TOOLS + 1 }, (_, index) => `tool_${index}`);+ const { http } = streamableServer((message) =>+ json(200, { jsonrpc: "2.0", id: message.id, result: toolsPage(names) })+ );+ await expect(+ listMcpServerTools({+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ headers: AUTH,+ secrets: SECRETS,+ http+ })+ ).rejects.toThrow(`more than ${MCP_TOOL_LIST_MAX_TOOLS} tools`);+ });++ test("a server that never answers runs out the budget", async () => {+ const http: TMcpHttpClient = { request: () => new Promise(() => {}) };+ await expect(+ listMcpServerTools({+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ headers: AUTH,+ secrets: SECRETS,+ http,+ budgetMs: 50+ })+ ).rejects.toThrow("didn't send its tool list within 0.05 seconds");+ });++ const sseServer = (endpoint: string, opening = `event: endpoint\ndata: ${endpoint}\n\n`) => {+ const stream = new PassThrough();+ const posts: TRequest[] = [];+ const http: TMcpHttpClient = {+ request: async (request) => {+ if (request.method === AgentVaultHttpMethod.Get) {+ stream.write(opening);+ return { status: 200, contentType: "text/event-stream", sessionId: null, body: stream };+ }+ posts.push(request);+ const message = JSON.parse(request.body!) as TMessage;+ const result = message.method === "initialize" ? { protocolVersion: "2024-11-05" } : toolsPage(["search"]);+ if (message.id !== undefined) {+ stream.write(`event: message\ndata: ${JSON.stringify({ jsonrpc: "2.0", id: message.id, result })}\n\n`);+ }+ return accepted();+ }+ };+ return { http, posts };+ };++ test("legacy SSE posts to the announced endpoint and reads answers off the stream", async () => {+ const { http, posts } = sseServer("/messages?sessionId=abc");+ const tools = await listMcpServerTools({+ serverUrl: "https://mcp.example.com/sse",+ transport: AgentVaultMcpTransport.Sse,+ headers: AUTH,+ secrets: SECRETS,+ http+ });+ expect(tools).toEqual([{ name: "search", description: "Does search" }]);+ expect(posts.map((post) => post.url)).toEqual(+ Array(3).fill("https://mcp.example.com/messages?sessionId=abc") as string[]+ );+ });++ test("legacy SSE answers a server ping on the announced endpoint", async () => {+ const stream = new PassThrough();+ const posts: TRequest[] = [];+ let listId: number | undefined;+ const http: TMcpHttpClient = {+ request: async (request) => {+ if (request.method === AgentVaultHttpMethod.Get) {+ stream.write("event: endpoint\ndata: /messages\n\n");+ return { status: 200, contentType: "text/event-stream", sessionId: null, body: stream };+ }+ posts.push(request);+ const message = JSON.parse(request.body!) as TMessage;+ if (message.method === "initialize") {+ stream.write(event({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: "2024-11-05" } }));+ } else if (message.method === "tools/list") {+ listId = message.id;+ stream.write(event({ jsonrpc: "2.0", id: "server-ping", method: "ping" }));+ } else if (message.method === undefined) {+ stream.write(event({ jsonrpc: "2.0", id: listId, result: toolsPage(["search"]) }));+ }+ return accepted();+ }+ };+ const tools = await listMcpServerTools({+ serverUrl: "https://mcp.example.com/sse",+ transport: AgentVaultMcpTransport.Sse,+ headers: AUTH,+ secrets: SECRETS,+ http,+ budgetMs: 1000+ });+ expect(tools).toEqual([{ name: "search", description: "Does search" }]);+ const pong = posts.find((post) => post.body?.includes("server-ping"));+ expect(pong!.url).toBe("https://mcp.example.com/messages");+ expect(JSON.parse(pong!.body!)).toEqual({ jsonrpc: "2.0", id: "server-ping", result: {} });+ });++ test("legacy SSE reads an endpoint event after a BOM and ended by bare CRs", async () => {+ const { http, posts } = sseServer("", "\uFEFFevent: endpoint\rdata: /messages\r\r");+ const tools = await listMcpServerTools({+ serverUrl: "https://mcp.example.com/sse",+ transport: AgentVaultMcpTransport.Sse,+ headers: AUTH,+ secrets: SECRETS,+ http,+ budgetMs: 1000+ });+ expect(tools).toEqual([{ name: "search", description: "Does search" }]);+ expect(posts[0].url).toBe("https://mcp.example.com/messages");+ });++ test("legacy SSE never sends the credential to an endpoint on another host", async () => {+ const { http, posts } = sseServer("https://attacker.example/messages");+ await expect(+ listMcpServerTools({+ serverUrl: "https://mcp.example.com/sse",+ transport: AgentVaultMcpTransport.Sse,+ headers: AUTH,+ secrets: SECRETS,+ http+ })+ ).rejects.toThrow("asked for messages to be sent to another host");+ expect(posts).toHaveLength(0);+ });+});diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-mcp-tool-list-fns.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-mcp-tool-list-fns.tsnew file mode 100644index 0000000000..34bb08b261--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-mcp-tool-list-fns.ts@@ -0,0 +1,478 @@+import { Readable } from "node:stream";+import { StringDecoder } from "node:string_decoder";++import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { PRIVATE_ADDRESS_REFUSED_MESSAGE, safeRequest } from "@app/lib/validator";++import { describeServer } from "../agent-vault-oauth/agent-vault-oauth-discovery-fns";+import { headerValue, MCP_CLIENT_INFO, MCP_PROTOCOL_VERSION } from "../agent-vault-oauth/agent-vault-oauth-http-fns";+import { normalizeProviderText } from "../agent-vault-oauth/agent-vault-oauth-token-fns";+import { AgentVaultHttpMethod, AgentVaultMcpTransport } from "../agent-vault/agent-vault-enums";+import { toolNameSchema } from "../agent-vault/agent-vault-tool-name-schemas";++const MCP_TOOL_LIST_BUDGET_MS = 20_000;+export const MCP_TOOL_LIST_MAX_TOOLS = 1000;+const MAX_PAGES = 50;+const SESSION_END_TIMEOUT_MS = 3000;+const MAX_MESSAGE_BYTES = 4 * 1024 * 1024;+const MAX_STREAM_BYTES = 16 * 1024 * 1024;+const MAX_DESCRIPTION_LENGTH = 1000;++type TMcpHttpMethod = AgentVaultHttpMethod.Get | AgentVaultHttpMethod.Post | AgentVaultHttpMethod.Delete;++type TMcpTool = { name: string; description: string | null };++type TMcpHttpResponse = { status: number; contentType: string; sessionId: string | null; body: Readable };++// Narrow on purpose, so the client is tested against stubbed servers without a network.+export type TMcpHttpClient = {+ request: (args: {+ method: TMcpHttpMethod;+ url: string;+ headers: Record<string, string>;+ body?: string;+ signal: AbortSignal;+ }) => Promise<TMcpHttpResponse>;+};++// Redirects are never followed (safeRequest pins maxRedirects to 0), so a server can't bounce the credential to+// another host.+const agentVaultMcpHttpClient: TMcpHttpClient = {+ request: async ({ method, url, headers, body, signal }) => {+ const response = await safeRequest.request<Readable>({+ method,+ url,+ data: body,+ headers,+ signal,+ "axios-retry": { retries: 0 },+ responseType: "stream",+ validateStatus: () => true+ });+ return {+ status: response.status,+ contentType: headerValue(response.headers["content-type"]).toLowerCase(),+ sessionId: headerValue(response.headers["mcp-session-id"]) || null,+ body: response.data+ };+ }+};++class McpListError extends BadRequestError {}++type TJsonRpcMessage = { id?: unknown; method?: unknown; result?: unknown; error?: { message?: unknown } };++// A server request can reuse a client request's id (ids are unique per sender), so only a response answers one.+const isResponseTo = (id: number) => (message: TJsonRpcMessage) => message.id === id && message.method === undefined;++// MCP has the receiver answer a ping promptly, and a server may drop a client that doesn't. Not awaited, so the+// pending response is still read while the answer is in flight.+const answerPings = (+ messages: TJsonRpcMessage[],+ reply: (message: Record<string, unknown>) => Promise<TMcpHttpResponse>+) => {+ messages+ .filter((message) => message.method === "ping" && message.id !== undefined)+ .forEach((message) => {+ void reply({ jsonrpc: "2.0", id: message.id, result: {} })+ .then((response) => response.body.destroy())+ .catch(() => {});+ });+};++const toMessages = (parsed: unknown): TJsonRpcMessage[] =>+ (Array.isArray(parsed) ? parsed : [parsed]).filter(+ (message): message is TJsonRpcMessage => typeof message === "object" && message !== null+ );++const readText = async (body: Readable, tooLarge: () => McpListError) => {+ const chunks: Buffer[] = [];+ let size = 0;+ // eslint-disable-next-line no-restricted-syntax+ for await (const chunk of body) {+ size += (chunk as Buffer).length;+ if (size > MAX_MESSAGE_BYTES) {+ body.destroy();+ throw tooLarge();+ }+ chunks.push(chunk as Buffer);+ }+ return Buffer.concat(chunks).toString("utf-8");+};++// One event per yield, in order. An event's data lines are joined with newlines, as the SSE spec says.+async function* readSseEvents(body: Readable, tooLarge: () => McpListError) {+ const decoder = new StringDecoder("utf8");+ let buffer = "";+ let isStart = true;+ let skipLeadingLf = false;+ let total = 0;+ let event = "";+ let data: string[] = [];+ let dataSize = 0;++ // eslint-disable-next-line no-restricted-syntax+ for await (const chunk of body) {+ total += (chunk as Buffer).length;+ if (total > MAX_STREAM_BYTES) throw tooLarge();+ buffer += decoder.write(chunk as Buffer);+ // The stream may start with one BOM, which isn't part of the first field name.+ if (isStart && buffer) {+ if (buffer.startsWith("\uFEFF")) buffer = buffer.slice(1);+ isStart = false;+ }+ // A CR ends its line at once, so an event ending in CRs isn't held until the server sends more. When it+ // ended the last chunk, an LF opening this one is the rest of that CRLF.+ if (skipLeadingLf && buffer) {+ if (buffer.startsWith("\n")) buffer = buffer.slice(1);+ skipLeadingLf = false;+ }+ if (buffer.endsWith("\r")) skipLeadingLf = true;+ const lines = buffer.split(/\r\n|\r|\n/);+ buffer = lines.pop()!;++ // eslint-disable-next-line no-restricted-syntax+ for (const line of lines) {+ if (line === "") {+ if (data.length) yield { event: event || "message", data: data.join("\n") };+ event = "";+ data = [];+ dataSize = 0;+ } else if (!line.startsWith(":")) {+ const colon = line.indexOf(":");+ const field = colon === -1 ? line : line.slice(0, colon);+ let value = colon === -1 ? "" : line.slice(colon + 1);+ if (value.startsWith(" ")) value = value.slice(1);+ if (field === "event") event = value;+ if (field === "data") {+ dataSize += value.length;+ if (dataSize > MAX_MESSAGE_BYTES) throw tooLarge();+ data.push(value);+ }+ }+ }+ if (buffer.length > MAX_MESSAGE_BYTES) throw tooLarge();+ }+}++export const listMcpServerTools = async ({+ serverUrl,+ transport,+ headers: authHeaders,+ secrets,+ http = agentVaultMcpHttpClient,+ budgetMs = MCP_TOOL_LIST_BUDGET_MS+}: {+ serverUrl: string;+ transport: AgentVaultMcpTransport;+ // The credential and custom headers, filled in exactly as the proxy would send them.+ headers: Record<string, string>;+ // The same values without their header prefixes, so a server echoing a bare token has it redacted too.+ secrets: string[];+ http?: TMcpHttpClient;+ budgetMs?: number;+}): Promise<TMcpTool[]> => {+ const server = describeServer(serverUrl);+ const transportLabel = transport === AgentVaultMcpTransport.Sse ? "SSE" : "Streamable HTTP";+ const notMcp = (detail = "") =>+ new McpListError({+ message: `'${server}' didn't answer like an MCP server over ${transportLabel}.${detail ? ` ${detail}` : ""} Check the server URL and transport.`+ });+ const tooLarge = () => new McpListError({ message: `'${server}' sent a response too large to read.` });++ const controller = new AbortController();+ const openBodies: Readable[] = [];+ const sensitiveValues = [...Object.values(authHeaders), ...secrets];++ const checkStatus = (response: TMcpHttpResponse) => {+ if (response.status >= 200 && response.status < 300) return;+ response.body.destroy();+ if (response.status === 401 || response.status === 403) {+ throw new McpListError({+ message: `'${server}' rejected the credential (HTTP ${response.status}). Check the token or reauthorize the service, then load the tools again.`+ });+ }+ if (response.status === 429 || response.status >= 500) {+ throw new McpListError({+ message: `'${server}' couldn't answer right now (HTTP ${response.status}). Try again in a few minutes.`+ });+ }+ throw notMcp(`It answered with HTTP ${response.status}.`);+ };++ const send = async (+ url: string,+ method: TMcpHttpMethod,+ extraHeaders: Record<string, string>,+ body?: unknown,+ signal: AbortSignal = controller.signal+ ) => {+ const response = await http.request({+ method,+ url,+ headers: {+ ...authHeaders,+ ...extraHeaders,+ ...(body === undefined ? {} : { "Content-Type": "application/json" })+ },+ body: body === undefined ? undefined : JSON.stringify(body),+ signal+ });+ openBodies.push(response.body);+ return response;+ };++ const resultOf = (message: TJsonRpcMessage) => {+ if (message.error) {+ const detail = normalizeProviderText(message.error.message, undefined, sensitiveValues);+ throw new McpListError({+ message: `'${server}' returned an error${detail ? `: ${detail}` : ""}.`+ });+ }+ return message.result;+ };++ const parseJson = (text: string) => {+ try {+ return JSON.parse(text) as unknown;+ } catch {+ throw notMcp();+ }+ };++ const collectTools = async (request: (method: string, params: Record<string, unknown>) => Promise<unknown>) => {+ const tools: TMcpTool[] = [];+ const seen = new Set<string>();+ let cursor: string | undefined;+ for (let page = 0; page < MAX_PAGES; page += 1) {+ // eslint-disable-next-line no-await-in-loop+ const result = (await request("tools/list", cursor ? { cursor } : {})) as {+ tools?: unknown;+ nextCursor?: unknown;+ } | null;+ if (!result || !Array.isArray(result.tools)) throw notMcp("Its tool list wasn't readable.");+ result.tools.forEach((tool: unknown) => {+ const { name, description } = (tool ?? {}) as { name?: unknown; description?: unknown };+ // A name the allowlist would refuse to store could never be allowed, so it isn't offered.+ if (typeof name !== "string" || !toolNameSchema.safeParse(name).success || seen.has(name)) return;+ seen.add(name);+ tools.push({+ name,+ description: normalizeProviderText(description, MAX_DESCRIPTION_LENGTH, sensitiveValues) || null+ });+ });+ if (tools.length > MCP_TOOL_LIST_MAX_TOOLS) {+ throw new McpListError({+ message: `'${server}' lists more than ${MCP_TOOL_LIST_MAX_TOOLS} tools, too many to load.`+ });+ }+ if (typeof result.nextCursor !== "string" || !result.nextCursor) return tools;+ cursor = result.nextCursor;+ }+ throw new McpListError({ message: `'${server}' kept returning more pages of tools.` });+ };++ const initializeParams = { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: MCP_CLIENT_INFO };++ const listOverStreamableHttp = async () => {+ let sessionId: string | null = null;+ let protocolVersion: string | null = null;+ let nextId = 1;++ const sessionHeaders = (): Record<string, string> => ({+ Accept: "application/json, text/event-stream",+ ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}),+ ...(protocolVersion ? { "MCP-Protocol-Version": protocolVersion } : {})+ });++ const request = async (method: string, params: Record<string, unknown>) => {+ const id = nextId;+ nextId += 1;+ const response = await send(serverUrl, AgentVaultHttpMethod.Post, sessionHeaders(), {+ jsonrpc: "2.0",+ id,+ method,+ params+ });+ checkStatus(response);+ if (method === "initialize") sessionId = response.sessionId;++ if (response.contentType.startsWith("application/json")) {+ const match = toMessages(parseJson(await readText(response.body, tooLarge))).find(isResponseTo(id));+ if (!match) throw notMcp();+ return resultOf(match);+ }+ if (response.contentType.startsWith("text/event-stream")) {+ // eslint-disable-next-line no-restricted-syntax+ for await (const { data } of readSseEvents(response.body, tooLarge)) {+ let parsed: unknown;+ try {+ parsed = JSON.parse(data);+ } catch {+ // eslint-disable-next-line no-continue+ continue;+ }+ const messages = toMessages(parsed);+ answerPings(messages, (reply) => send(serverUrl, AgentVaultHttpMethod.Post, sessionHeaders(), reply));+ const match = messages.find(isResponseTo(id));+ if (match) {+ response.body.destroy();+ return resultOf(match);+ }+ }+ throw notMcp();+ }+ response.body.destroy();+ throw notMcp();+ };++ try {+ const initialized = (await request("initialize", initializeParams)) as { protocolVersion?: unknown } | null;+ if (typeof initialized?.protocolVersion === "string") protocolVersion = initialized.protocolVersion;++ const notified = await send(serverUrl, AgentVaultHttpMethod.Post, sessionHeaders(), {+ jsonrpc: "2.0",+ method: "notifications/initialized"+ });+ checkStatus(notified);+ notified.body.destroy();++ return await collectTools(request);+ } finally {+ if (sessionId) {+ // Best effort: a server that doesn't support ending sessions answers 405, and one that never answers+ // isn't waited on.+ void send(+ serverUrl,+ AgentVaultHttpMethod.Delete,+ sessionHeaders(),+ undefined,+ AbortSignal.timeout(SESSION_END_TIMEOUT_MS)+ )+ .then((response) => response.body.destroy())+ .catch(() => {});+ }+ }+ };++ const listOverSse = async () => {+ const stream = await send(serverUrl, AgentVaultHttpMethod.Get, { Accept: "text/event-stream" });+ checkStatus(stream);+ if (!stream.contentType.startsWith("text/event-stream")) {+ stream.body.destroy();+ throw notMcp();+ }+ const events = readSseEvents(stream.body, tooLarge);++ const next = async () => {+ const { value, done } = await events.next();+ if (done) throw notMcp("It closed the event stream early.");+ return value;+ };++ let endpointEvent = await next();+ while (endpointEvent.event !== "endpoint") {+ // eslint-disable-next-line no-await-in-loop+ endpointEvent = await next();+ }+ let endpoint: URL;+ try {+ endpoint = new URL(endpointEvent.data.trim(), serverUrl);+ } catch {+ throw notMcp("It announced an endpoint that isn't a URL.");+ }+ // The credential goes only to the server the admin named.+ if (endpoint.origin !== new URL(serverUrl).origin) {+ throw new McpListError({+ message: `'${server}' asked for messages to be sent to another host, so Infisical didn't send the credential there.`+ });+ }++ let nextId = 1;+ const post = async (message: Record<string, unknown>) => {+ const response = await send(+ endpoint.toString(),+ AgentVaultHttpMethod.Post,+ { Accept: "application/json, text/event-stream" },+ message+ );+ checkStatus(response);+ response.body.destroy();+ };++ const request = async (method: string, params: Record<string, unknown>) => {+ const id = nextId;+ nextId += 1;+ await post({ jsonrpc: "2.0", id, method, params });+ for (;;) {+ // eslint-disable-next-line no-await-in-loop+ const { event, data } = await next();+ if (event === "message") {+ let parsed: unknown = null;+ try {+ parsed = JSON.parse(data);+ } catch {+ parsed = null;+ }+ const messages = toMessages(parsed);+ answerPings(messages, (reply) =>+ send(+ endpoint.toString(),+ AgentVaultHttpMethod.Post,+ { Accept: "application/json, text/event-stream" },+ reply+ )+ );+ const match = messages.find(isResponseTo(id));+ if (match) return resultOf(match);+ }+ }+ };++ await request("initialize", initializeParams);+ await post({ jsonrpc: "2.0", method: "notifications/initialized" });+ return collectTools(request);+ };++ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ controller.abort();+ }, budgetMs);+ // Host validation and stream reads don't all watch the signal, so the budget is also enforced here.+ const aborted = new Promise<never>((_, reject) => {+ controller.signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });+ });++ try {+ return await Promise.race([+ transport === AgentVaultMcpTransport.Sse ? listOverSse() : listOverStreamableHttp(),+ aborted+ ]);+ } catch (err) {+ if (err instanceof McpListError) throw err;+ if (err instanceof BadRequestError && err.message === PRIVATE_ADDRESS_REFUSED_MESSAGE) {+ throw new BadRequestError({+ message: `Infisical can't reach '${server}' because it's on a private network.`+ });+ }+ if (timedOut) {+ throw new BadRequestError({+ message: `'${server}' didn't send its tool list within ${budgetMs / 1000} seconds. Try again.`+ });+ }+ // Only the message: an axios error carries the request config, credential headers included.+ const reason = normalizeProviderText(err instanceof Error ? err.message : String(err), undefined, sensitiveValues);+ logger.warn(+ `agentVaultMcpTools: listing tools failed [server=${server}] [transport=${transport}] [reason=${reason}]`+ );+ throw new BadRequestError({+ message: `Couldn't reach '${server}'. Check the server URL and that the server is online.`+ });+ } finally {+ clearTimeout(timer);+ controller.abort();+ openBodies.forEach((body) => body.destroy());+ }+};diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.test.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.test.tsnew file mode 100644index 0000000000..211edb2a94--- /dev/null+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.test.ts@@ -0,0 +1,43 @@+import { describe, expect, test } from "vitest";++import { matchTransformationRows } from "./agent-vault-transformation-fns";++const row = (id: string, name: string) => ({ id, name, encryptedValue: Buffer.from(id) });++const match = (existing: ReturnType<typeof row>[], incoming: { id?: string; name: string }[]) =>+ matchTransformationRows({+ existing,+ incoming: incoming.map((header) => ({ id: header.id, naturalKey: header.name.toLowerCase() })),+ naturalKeyOfRow: (stored) => stored.name.toLowerCase(),+ subject: "custom header"+ });++describe("matchTransformationRows", () => {+ test("matches by id first, then by natural key", () => {+ const existing = [row("a", "X-Tenant"), row("b", "X-Region")];+ expect(match(existing, [{ name: "x-region" }, { id: "a", name: "X-Renamed" }])).toEqual([existing[1], existing[0]]);+ });++ test("a row claimed by id can't also be claimed by name", () => {+ const existing = [row("a", "X-Tenant")];+ expect(match(existing, [{ id: "a", name: "X-Renamed" }, { name: "X-Tenant" }])).toEqual([existing[0], undefined]);+ });++ test("refuses an unknown id rather than falling back to the name", () => {+ expect(() => match([row("a", "X-Tenant")], [{ id: "missing", name: "X-Tenant" }])).toThrow(+ "No custom header with ID 'missing' belongs to this service"+ );+ });++ test("refuses an id listed twice", () => {+ expect(() =>+ match(+ [row("a", "X-Tenant")],+ [+ { id: "a", name: "X-One" },+ { id: "a", name: "X-Two" }+ ]+ )+ ).toThrow("The custom header with ID 'a' is listed twice");+ });+});diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.tsindex 3b05f52956..1356e68980 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-transformation-fns.ts@@ -34,17 +34,17 @@ const isUnchanged = (stored: Record<string, unknown>, columns: Record<string, un* hand-written call edit one row without first fetching the service for its ids. Ids are claimed in a first* pass, or swapping two rows' names would let the second claim the row the first was already given.*/-export const planTransformationDiff = <TRow extends TStoredRow, TColumns>({+export const matchTransformationRows = <TRow extends TStoredRow>({existing,incoming,naturalKeyOfRow,subject}: {existing: TRow[];- incoming: TTransformationWrite<TColumns>[];+ incoming: { id?: string; naturalKey: string }[];naturalKeyOfRow: (row: TRow) => string;subject: string;-}): TTransformationPlan<TColumns> => {+}): (TRow | undefined)[] => {const byId = new Map(existing.map((row) => [row.id, row]));const claimed = new Set<string>();const resolved = new Array<TRow | undefined>(incoming.length);@@ -73,10 +73,26 @@ export const planTransformationDiff = <TRow extends TStoredRow, TColumns>({const stored = byKey.get(row.naturalKey);if (!stored) return;byKey.delete(row.naturalKey);- claimed.add(stored.id);resolved[index] = stored;});+ return resolved;+};++export const planTransformationDiff = <TRow extends TStoredRow, TColumns>({+ existing,+ incoming,+ naturalKeyOfRow,+ subject+}: {+ existing: TRow[];+ incoming: TTransformationWrite<TColumns>[];+ naturalKeyOfRow: (row: TRow) => string;+ subject: string;+}): TTransformationPlan<TColumns> => {+ const resolved = matchTransformationRows({ existing, incoming, naturalKeyOfRow, subject });+ const claimed = new Set(resolved.flatMap((row) => (row ? [row.id] : [])));+const plan: TTransformationPlan<TColumns> = { creates: [], updates: [], deleteIds: [] };incoming.forEach((row, index) => {diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-http-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-http-fns.tsindex d5a70cd838..a5e71f6a51 100644--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-http-fns.ts+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-http-fns.ts@@ -24,6 +24,9 @@ export type TOauthHttpClient = {const TIMEOUT_MS = 10_000;+export const MCP_PROTOCOL_VERSION = "2025-06-18";+export const MCP_CLIENT_INFO = { name: "Infisical Agent Vault", version: "1.0.0" };+// Also bounds what the HTTP client's own timeout doesn't cover, such as resolving and validating the host.export const withTimeout = <T>(promise: Promise<T>, ms: number) => {let timer: NodeJS.Timeout | undefined;@@ -36,7 +39,7 @@ export const withTimeout = <T>(promise: Promise<T>, ms: number) => {};const MAX_BODY_BYTES = 1024 * 1024;-const headerValue = (value: unknown): string => {+export const headerValue = (value: unknown): string => {if (Array.isArray(value)) return value.join(", ");return typeof value === "string" ? value : "";};@@ -104,9 +107,9 @@ export const agentVaultOauthHttpClient: TOauthHttpClient = {id: 1,method: "initialize",params: {- protocolVersion: "2025-06-18",+ protocolVersion: MCP_PROTOCOL_VERSION,capabilities: {},- clientInfo: { name: "Infisical Agent Vault", version: "1.0.0" }+ clientInfo: MCP_CLIENT_INFO}}),{diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.tsindex 583565117c..1753311f7f 100644--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.ts+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-service.ts@@ -581,20 +581,12 @@ export const agentVaultOauthServiceFactory = ({authorization: toView(await loadOwnAuthorization(authorizationId, ctx, projectId))});- // Single use: the save that deletes the record wins, so two saves racing for one authorization end with one- // winner. A save that then fails (a name conflict, say) restores it, so it can be retried without authorizing- // again. Only an authorized record is consumed, and completion never rewrites one, so the record validated- // here is the one deleted.- const claimAuthorization = async ({- authorizationId,- projectId,- accessBundleId,- serviceId,- ctx,- serverUrl- }: TClaimAuthorizationDTO) => {- const recordKey = KeyStorePrefixes.AgentVaultOauthAuthorization(authorizationId);- const { record, raw } = await loadOwnStoredAuthorization(authorizationId, ctx, projectId);+ const loadUsableAuthorization = async (+ { authorizationId, projectId, accessBundleId, serviceId, ctx, serverUrl }: TClaimAuthorizationDTO,+ action: string+ ) => {+ const stored = await loadOwnStoredAuthorization(authorizationId, ctx, projectId);+ const { record } = stored;if (record.accessBundleId.toLowerCase() !== accessBundleId.toLowerCase()) {throw new BadRequestError({message: "This authorization was started for a different access bundle. Authorize again here."@@ -610,12 +602,24 @@ export const agentVaultOauthServiceFactory = ({}if (record.status === AgentVaultOauthAuthorizationStatus.Failed) {throw new BadRequestError({- message: `This authorization failed, so it can't be saved. Start a new one. ${record.error ?? ""}`.trim()+ message: `This authorization failed, so it can't be used. Start a new one. ${record.error ?? ""}`.trim()});}if (record.status !== AgentVaultOauthAuthorizationStatus.Authorized || !record.sealedCredential) {- throw new BadRequestError({ message: "This authorization hasn't finished yet. Finish signing in, then save." });+ throw new BadRequestError({+ message: `This authorization hasn't finished yet. Finish signing in, then ${action}.`+ });}+ return stored;+ };++ // Single use: the save that deletes the record wins, so two saves racing for one authorization end with one+ // winner. A save that then fails (a name conflict, say) restores it, so it can be retried without authorizing+ // again. Only an authorized record is consumed, and completion never rewrites one, so the record validated+ // here is the one deleted.+ const claimAuthorization = async (dto: TClaimAuthorizationDTO) => {+ const recordKey = KeyStorePrefixes.AgentVaultOauthAuthorization(dto.authorizationId);+ const { record, raw } = await loadUsableAuthorization(dto, "save");const remainingTtlSeconds = await keyStore.ttl(recordKey);if ((await keyStore.deleteItem(recordKey)) !== 1) {@@ -632,7 +636,7 @@ export const agentVaultOauthServiceFactory = ({} catch (error) {logger.warn(error,- `agentVaultOauth: could not restore the authorization after a failed save [authorizationId=${authorizationId}]`+ `agentVaultOauth: could not restore the authorization after a failed save [authorizationId=${dto.authorizationId}]`);}};@@ -640,6 +644,14 @@ export const agentVaultOauthServiceFactory = ({return { record, restore };};+ // Loading a server's tools before the service is saved. Reads the authorization without claiming it, so the save+ // that follows still can, and applies the same checks the save will.+ const readAuthorizationAccessToken = async (dto: TClaimAuthorizationDTO) => {+ const { record } = await loadUsableAuthorization(dto, "load the tools");+ const secret = await open<TAgentVaultOauthSecret>(dto.projectId, Buffer.from(record.sealedCredential!, "base64"));+ return secret.accessToken;+ };+// The non-secret half goes to credentialConfig and the record's sealed blob becomes encryptedCredential as is:// both are the project cipher over the same JSON shape, so nothing is opened to move it.const buildCredentialFromAuthorization = (@@ -936,6 +948,7 @@ export const agentVaultOauthServiceFactory = ({completeAuthorization,getAuthorization,claimAuthorization,+ readAuthorizationAccessToken,buildCredentialFromAuthorization,refreshServiceToken,reportMissingScopesdiff --git 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.tsindex 00f94f3e52..46686c64dd 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@@ -45,6 +45,7 @@ const serviceRow = (overrides: Partial<TResolveServiceRow> = {}): TResolveServicencryptedCredential: Buffer.from(JSON.stringify({ accessToken: "snapshot-access" })),allowedMethods: null,allowedPathPrefixes: null,+ allowedTools: null,memberProvidedFields: null,position: 0,...overrides@@ -267,6 +268,18 @@ describe("resolve's lazy refresh", () => {expect(services[1].credential).toMatchObject({ value: "bearer-expanded" });});+ test("sends each service's allowed tools, and null for one that allows every tool", async () => {+ const { service } = setup(+ async () => refreshed,+ [+ serviceRow({ allowedTools: ["read_file", "search"] }),+ serviceRow({ id: "55555555-5555-4555-8555-555555555555", allowedTools: null })+ ]+ );+ const { services } = await resolve(service);+ expect(services.map((resolved) => resolved.allowedTools)).toEqual([["read_file", "search"], null]);+ });+test("an OAuth token is always sent as Authorization: Bearer, whatever its config holds", async () => {const { service } = setup(async () => refreshed,diff --git 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.tsindex 26f9e084df..00e38178bd 100644--- 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@@ -855,6 +855,7 @@ export const agentVaultProxyServiceFactory = ({hostPattern: row.hostPattern,allowedMethods: row.allowedMethods,allowedPathPrefixes: row.allowedPathPrefixes,+ allowedTools: row.allowedTools,credential: refreshedCredentials.get(row.id) ?? $decryptCredential(row, decryptor),customHeaders: customHeaderRows.filter((header) => header.serviceId === row.id)diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex 82c7326408..4c6c9de6e3 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts@@ -83,6 +83,7 @@ export type TResolvedService = {hostPattern: string;allowedMethods: string[] | null;allowedPathPrefixes: string[] | null;+ allowedTools: string[] | null;credential:| {type: AgentVaultCredentialType.Bearer;diff --git 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.tsindex ff1fff4566..1fdca47ac6 100644--- 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@@ -18,6 +18,7 @@ export type TResolveServiceRow = {encryptedCredential: Buffer | null;allowedMethods: string[] | null;allowedPathPrefixes: string[] | null;+ allowedTools: string[] | null;memberProvidedFields: string[] | null;position: number;};@@ -78,6 +79,7 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {db.ref("encryptedCredential").withSchema(TableName.AgentVaultService),db.ref("allowedMethods").withSchema(TableName.AgentVaultService),db.ref("allowedPathPrefixes").withSchema(TableName.AgentVaultService),+ db.ref("allowedTools").withSchema(TableName.AgentVaultService),db.ref("memberProvidedFields").withSchema(TableName.AgentVaultService),// Resolve only reaches live bundles, so the current name is always the truthful one here.db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName"),diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex cf14cedb83..aea147e739 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -169,6 +169,39 @@ the matching at runtime and reimplements the same rules, so a change here needsset. Same bundle: hard reject. Across bundles: allowed, since a session carries one bundle they never meet.- Patterns are stored as typed and normalised at match time. `*.com` is accepted; settled as not a bug.+## Tool allowlist++`allowedTools` on an MCP service names the tools agents may call. Like `allowedMethods`, NULL is every tool and an+empty array is never stored. Names are exact and case-sensitive, and the proxy compares them byte for byte whatever+characters they hold. `agent-vault-tool-name-schemas.ts` (mirrored in the frontend's `serviceSchema.ts`) only refuses+what is never a real tool name: empty, over 128 characters, edge whitespace, control characters. The CLI's+`mcpNamePattern` is narrower but only decides whether the session log records a name; a call outside it is logged+unparsed and still checked against the list.++- **The proxy's `tools/call` check is the control.** While a list is set it reads every POST to the service, up to+ 32 MiB, logs on or off, and refuses the whole request when any call names an unlisted tool, before the credential is+ attached. A larger body gets a 413. The check goes by the body, not the `Content-Type`: a body declared+ `application/json`, or one whose first byte after whitespace or a BOM is `{` or `[`, is parsed strictly, and any+ other body (a form-encoded OAuth token request) is forwarded. It fails closed: a compressed body, JSON it can't parse+ strictly (duplicate or case-variant keys) and a `tools/call` with no tool name get a 400, and so does any other+ method that carries a body. In a refused batch only the entries that call an unlisted tool name it. A Streamable HTTP+ client (its `Accept` lists both `application/json` and `text/event-stream`) gets the refusal as a JSON-RPC error+ with status 200, since MCP clients read a 403 as an auth failure; any other client, legacy SSE included, gets the+ same body with a 403, because those clients ignore the body of a successful POST. When a body substitution rewrites+ the request, the rewritten body is checked again, and a refusal there is a 403 that doesn't name the tool, since the+ body can now hold a real value.+- **Hiding unlisted tools from `tools/list` is only a convenience.** The proxy filters any result shaped like a tool+ list, in JSON and SSE responses, by shape rather than by request id. It drops the agent's `Accept-Encoding` so the+ response arrives uncompressed. A response it can't rewrite (still compressed, over 1 MiB, unparseable) passes+ through, and a tool entry without a readable name is dropped.+- An older proxy enforces nothing, as with methods and paths.+- **Loading a server's tools for the service sheet** is `POST .../mcp-tools/list`, an action route on purpose: on+ create there is no service yet and the body carries a credential. It sends what a save of the same body would store+ (omitted values fall back to the saved service, variables expanded as resolve does), reads a pending OAuth+ authorization without claiming it, and refreshes a stored OAuth token through the usual refresh. The client is+ hand-rolled on `safeRequest`, not the MCP SDK, which would bypass the SSRF guard. It is not audited, and a+ member-provided bearer token can't load tools (the admin types names instead).+## TransformationsTwo child tables, `agent_vault_service_custom_headers` and `agent_vault_service_substitutions`. "Customdiff --git a/backend/src/ee/services/agent-vault/agent-vault-list-schema-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-list-schema-fns.tsnew file mode 100644index 0000000000..33c17e6b3c--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-list-schema-fns.ts@@ -0,0 +1,11 @@+import { z } from "zod";++export const refineNoDuplicates = (values: string[], ctx: z.RefinementCtx) => {+ const seen = new Set<string>();+ values.forEach((value, index) => {+ if (seen.has(value)) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: `"${value}" is listed twice.`, path: [index] });+ }+ seen.add(value);+ });+};diff --git a/backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.tsindex 9f6486ba14..3cf3379d22 100644--- a/backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-path-prefix-schemas.ts@@ -1,6 +1,8 @@import RE2 from "re2";import { z } from "zod";+import { refineNoDuplicates } from "./agent-vault-list-schema-fns";+export const AGENT_VAULT_MAX_PATH_PREFIX_LENGTH = 512;export const AGENT_VAULT_MAX_PATH_PREFIXES = 20;@@ -48,13 +50,5 @@ export const agentVaultPathPrefixListSchema = z.array(pathPrefixSchema).min(1, "Add at least one path prefix, or leave this unset to allow every path.").max(AGENT_VAULT_MAX_PATH_PREFIXES)- .superRefine((prefixes, ctx) => {- const seen = new Set<string>();- prefixes.forEach((prefix, index) => {- if (seen.has(prefix)) {- ctx.addIssue({ code: z.ZodIssueCode.custom, message: `"${prefix}" is listed twice.`, path: [index] });- }- seen.add(prefix);- });- })+ .superRefine(refineNoDuplicates).nullable();diff --git a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.tsindex 2770ad3e99..25e36bc75a 100644--- a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.test.ts@@ -115,6 +115,7 @@ describe("fields a type does not take", () => {allowedPathPrefixes: ["/v1"],substitutions: [],customHeaders: [],+ allowedTools: ["read_file"],serverUrl: "https://mcp.example.com/mcp",transport: AgentVaultMcpTransport.Sse})@@ -130,12 +131,13 @@ describe("fields a type does not take", () => {hostPattern: "api.github.com",allowedMethods: ["GET"],substitutions: [],+ allowedTools: ["read_file"],serverUrl: "https://mcp.example.com/mcp",transport: AgentVaultMcpTransport.Sse})- ).toEqual(["serverUrl", "transport"]);+ ).toEqual(["allowedTools", "serverUrl", "transport"]);expect(() => assertServiceFieldsSupported(http, { serverUrl: "x", transport: "sse" })).toThrow(- "An HTTP service doesn't take 'serverUrl' or 'transport'. A server URL and transport apply only to MCP services."+ "An HTTP service doesn't take 'serverUrl' or 'transport'. A server URL, transport and allowed tools apply only to MCP services.");});@@ -158,9 +160,12 @@ describe("fields read back unchanged on an update", () => {allowedPathPrefixes: undefined,substitutions: undefined});- expect(dropReadBackServiceFields(http, { serverUrl: null, transport: null }, "api.example.com")).toEqual({+ expect(+ dropReadBackServiceFields(http, { serverUrl: null, transport: null, allowedTools: null }, "api.example.com")+ ).toEqual({serverUrl: undefined,- transport: undefined+ transport: undefined,+ allowedTools: undefined});});diff --git a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.tsindex 0daa6ab1a6..79130e11d8 100644--- a/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts+++ b/backend/src/ee/services/agent-vault/agent-vault-service-type-fns.ts@@ -103,6 +103,7 @@ export type TAgentVaultServiceTypeDefinition = {// Null when the caller enters the host pattern itself.deriveHostPattern: ((config: Record<string, unknown>) => string) | null;supportsRequestRules: boolean;+ supportsToolRules: boolean;supportsTransformations: { customHeaders: boolean; substitutions: boolean };// Appended to the refusal when a request sends a field this type does not take.unsupportedFieldHint: string;@@ -120,8 +121,9 @@ export const AGENT_VAULT_SERVICE_TYPES: Record<AgentVaultServiceType, TAgentVaul],deriveHostPattern: null,supportsRequestRules: true,+ supportsToolRules: false,supportsTransformations: { customHeaders: true, substitutions: true },- unsupportedFieldHint: "A server URL and transport apply only to MCP services."+ unsupportedFieldHint: "A server URL, transport and allowed tools apply only to MCP services."},[AgentVaultServiceType.Mcp]: {type: AgentVaultServiceType.Mcp,@@ -130,6 +132,7 @@ export const AGENT_VAULT_SERVICE_TYPES: Record<AgentVaultServiceType, TAgentVaulallowedCredentialTypes: [AgentVaultCredentialType.Bearer, AgentVaultCredentialType.OAuth],deriveHostPattern: (config) => deriveMcpHostPattern((config as TAgentVaultMcpServiceConfig).serverUrl),supportsRequestRules: false,+ supportsToolRules: true,supportsTransformations: { customHeaders: true, substitutions: false },unsupportedFieldHint:"Its host comes from 'serverUrl', and method, path and substitution rules apply only to HTTP services."@@ -154,6 +157,7 @@ export type TAgentVaultServiceTypedFields = {hostPattern?: unknown;allowedMethods?: unknown;allowedPathPrefixes?: unknown;+ allowedTools?: unknown;customHeaders?: unknown;substitutions?: unknown;} & Record<string, unknown>;@@ -166,6 +170,7 @@ export const findUnsupportedServiceFields = (hostPattern: definition.deriveHostPattern === null,allowedMethods: definition.supportsRequestRules,allowedPathPrefixes: definition.supportsRequestRules,+ allowedTools: definition.supportsToolRules,customHeaders: definition.supportsTransformations.customHeaders,substitutions: definition.supportsTransformations.substitutions,...Object.fromEntries(CONFIG_FIELDS.map((field) => [field, field in definition.configSchema.shape]))diff --git a/backend/src/ee/services/agent-vault/agent-vault-tool-name-schemas.test.ts b/backend/src/ee/services/agent-vault/agent-vault-tool-name-schemas.test.tsnew file mode 100644index 0000000000..05320b928e--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-tool-name-schemas.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";++import { AGENT_VAULT_MAX_ALLOWED_TOOLS, agentVaultAllowedToolsSchema } from "./agent-vault-tool-name-schemas";++describe("agent vault allowed tools", () => {+ it.each([+ ["read_file"],+ ["github.create_issue"],+ ["ns:tool/v2-beta"],+ ["query+sum"],+ ["read file"],+ ["a".repeat(128)]+ ])("accepts %s", (name) => {+ expect(agentVaultAllowedToolsSchema.parse([name])).toEqual([name]);+ });++ it.each([+ ["", "can't be empty"],+ [" read_file", "start or end with a space"],+ ["read_file\t", "start or end with a space"],+ ["read\u0000file", "control characters"],+ ["a".repeat(129), "longer than 128"]+ ])("refuses %j", (name, message) => {+ const result = agentVaultAllowedToolsSchema.safeParse([name]);+ expect(result.success).toBe(false);+ expect(result.error?.issues[0].message).toContain(message);+ });++ it("keeps null as every tool and refuses an empty list", () => {+ expect(agentVaultAllowedToolsSchema.parse(null)).toBeNull();+ expect(agentVaultAllowedToolsSchema.safeParse([]).success).toBe(false);+ });++ it("refuses duplicates but not names differing only by case", () => {+ expect(agentVaultAllowedToolsSchema.safeParse(["read", "read"]).error?.issues[0].message).toBe(+ '"read" is listed twice.'+ );+ expect(agentVaultAllowedToolsSchema.parse(["read", "Read"])).toEqual(["read", "Read"]);+ });++ it("caps the count", () => {+ const names = Array.from({ length: AGENT_VAULT_MAX_ALLOWED_TOOLS + 1 }, (_, index) => `tool_${index}`);+ expect(agentVaultAllowedToolsSchema.safeParse(names).success).toBe(false);+ expect(agentVaultAllowedToolsSchema.safeParse(names.slice(1)).success).toBe(true);+ });+});diff --git a/backend/src/ee/services/agent-vault/agent-vault-tool-name-schemas.ts b/backend/src/ee/services/agent-vault/agent-vault-tool-name-schemas.tsnew file mode 100644index 0000000000..e42af02ec9--- /dev/null+++ b/backend/src/ee/services/agent-vault/agent-vault-tool-name-schemas.ts@@ -0,0 +1,36 @@+import RE2 from "re2";+import { z } from "zod";++import { refineNoDuplicates } from "./agent-vault-list-schema-fns";++const AGENT_VAULT_MAX_TOOL_NAME_LENGTH = 128;+export const AGENT_VAULT_MAX_ALLOWED_TOOLS = 500;++// The proxy compares names exactly, whatever characters they hold. Edge whitespace is refused as a likely typo, and+// control characters because the name is shown in the UI and audit logs.+// eslint-disable-next-line no-control-regex+const CONTROL_CHARACTER_RE = new RE2(/[\u0000-\u001f\u007f-\u009f]/);++const toolNameError = (name: string) => {+ if (!name) return "A tool name can't be empty.";+ if (name.length > AGENT_VAULT_MAX_TOOL_NAME_LENGTH)+ return `"${name.slice(0, 40)}…" is longer than ${AGENT_VAULT_MAX_TOOL_NAME_LENGTH} characters.`;+ if (name !== name.trim()) return `"${name}" can't start or end with a space.`;+ if (CONTROL_CHARACTER_RE.test(name)) return "A tool name can't contain control characters.";+ return null;+};++// Not trimmed: names are exact and case-sensitive, so " read_file" is refused rather than quietly changed.+export const toolNameSchema = z.string().superRefine((name, ctx) => {+ const message = toolNameError(name);+ if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, message });+});++// NULL is the only "every tool". `.nullable()` without `.optional()`, so a PATCH omitting the field leaves the+// column alone and an explicit null clears it.+export const agentVaultAllowedToolsSchema = z+ .array(toolNameSchema)+ .min(1, "Send at least one tool name, or null to allow every tool.")+ .max(AGENT_VAULT_MAX_ALLOWED_TOOLS, `A service can allow at most ${AGENT_VAULT_MAX_ALLOWED_TOOLS} tools.`)+ .superRefine(refineNoDuplicates)+ .nullable();diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 785a2f83f3..f757098597 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6586,6 +6586,7 @@ interface AgentVaultServiceCreateEvent {headerPrefix?: string;allowedMethods?: string[] | null;allowedPathPrefixes?: string[] | null;+ allowedTools?: string[] | null;// The fields each member sets for themselves, such as credential-value or credential-username.memberProvidedFields?: string[];// Names and placeholders only. A sealed value must never reach an audit row.@@ -6615,6 +6616,7 @@ interface AgentVaultServiceUpdateEvent {headerPrefix?: string;allowedMethods?: string[] | null;allowedPathPrefixes?: string[] | null;+ allowedTools?: string[] | null;// The fields each member sets for themselves after the update, present when it touched the credential.memberProvidedFields?: string[];customHeaderNames?: string[];diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex aae6ff5b7e..df6808f03f 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4567,6 +4567,10 @@ export const AGENT_VAULT = {"The HTTP methods this service allows. Null allows every method. Anything else is refused by the proxy with a 403.",allowedPathPrefixes:"The path prefixes this service allows, matched on whole segments, so `/repos` covers `/repos/octo` but not `/repositories`. `null` allows every path. A path-restricted service also refuses any request whose path would have to be normalised to judge.",+ allowedTools:+ "The MCP tools agents can call through this service, by exact, case-sensitive name. `null` allows every tool. The proxy refuses a call to any other tool and leaves it out of the server's tool list. MCP services only.",+ mcpToolName: "The tool's name, as the MCP server reports it.",+ mcpToolDescription: "The server's description of the tool, or null if it gave none.",customHeaders:"Additional headers the proxy attaches to every request to this service, on top of the credential. Send the full list. A header you leave out is deleted. Send a header's `id` to change it in place and keep its stored value. Without an `id`, a header is matched by name.",customHeaderId: "The ID of the custom header. Send it to change that header in place. Omit it to match by name.",diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex c9435c897b..71af76dde3 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -2471,6 +2471,7 @@ export type TAgentVaultServiceCreatedEvent = {hostPatternCount: number;allowedMethodCount: number;allowedPathPrefixCount: number;+ allowedToolCount: number;customHeaderCount: number;substitutionCount: number;variableReferenceCount: number;@@ -2487,6 +2488,7 @@ export type TAgentVaultServiceUpdatedEvent = {hostPatternCount: number;allowedMethodCount: number;allowedPathPrefixCount: number;+ allowedToolCount: number;customHeaderCount: number;substitutionCount: number;variableReferenceCount: number;diff --git a/docs/documentation/platform/agent-vault/mcp-servers.mdx b/docs/documentation/platform/agent-vault/mcp-servers.mdxindex c57513a68d..84c3833d68 100644--- a/docs/documentation/platform/agent-vault/mcp-servers.mdx+++ b/docs/documentation/platform/agent-vault/mcp-servers.mdx@@ -29,6 +29,9 @@ You add the MCP server to your agent with its real URL and no credentials. When<Step>On the **Credential** step, pick a **Credential Type** and set up the [credential](#credential-types). Select **Continue**.</Step>+ <Step>+ On the **Tools** step, choose which of the server's [tools agents can call](#allowed-tools). Select **Continue**.+ </Step><Step>On the **Review** step, select **Add Service**. The service appears in the bundle's list with the type **MCP Server**.</Step>@@ -90,6 +93,26 @@ If the MCP server needs another header besides the credential, such as an organiInfisical won't save a custom header with the same name as the credential's header, which is `Authorization` unless you changed a Bearer token's **Header Name**. Infisical also won't save a header that the proxy sets itself, such as `Host` or `Content-Length`.+## Allowed tools++By default, agents can call every tool the MCP server offers. To keep agents away from tools they shouldn't use, such as tools that delete data, allow only the tools you select. The list applies to every session that uses the service.++<Steps>+ <Step>+ On the **Tools** step, select **Selected tools**.+ </Step>+ <Step>+ Infisical loads the server's list of tools with the service's credential. Select the tools agents can call.+ </Step>+ <Step>+ To allow a tool that the list doesn't include, such as a tool the credential lacks the scope for, type its exact name in the search field and press Enter.+ </Step>+</Steps>++When an agent calls a tool you didn't allow, the proxy refuses the call and doesn't send it to the server. The agent gets an error that names the tool, and the call appears in the [session's logs](/documentation/platform/agent-vault/session-logs) as blocked. The proxy also leaves the tools you didn't allow out of the list of tools the server returns to the agent.++The proxy picks up a changed list within its [poll interval](/documentation/platform/agent-vault/proxies#poll-interval) (60 seconds by default) and refuses calls to the tools you removed from then on. Most agents fetch the list of tools only when they connect, so a running agent shows the new list after you restart it or reconnect the MCP server. To allow every tool again, edit the service and select **All tools**.+## Connect your agent<Steps>@@ -153,8 +176,8 @@ Infisical won't save a custom header with the same name as the credential's head- **Remote servers only:** An MCP service covers MCP servers that the agent reaches over HTTPS. A local MCP server that the agent starts as a process isn't an MCP service, but you can add [HTTP services](/documentation/platform/agent-vault/http-apis) for the APIs that the local server calls- **No OAuth on private networks:** Infisical connects to the MCP server and to the provider to set up OAuth and refresh the access token, so if either one is on a private network, use a [Bearer token](#bearer-token) instead, or set [`ALLOW_INTERNAL_IP_CONNECTIONS`](/self-hosting/configuration/envars#param-allow-internal-ip-connections) to `true` if you self-host Infisical on that network-- **No tool filtering:** The agent can call every tool the server offers to the credential, so limit what the agent can do through the credential's own permissions- **No connectors that run in a vendor's cloud:** Custom connectors in claude.ai or ChatGPT connect from the vendor's servers, so their traffic never reaches your proxy+- **Refusals on the SSE transport:** An agent built on the Python MCP SDK that connects over the SSE transport gets no error when it calls a tool you didn't allow, and waits until the call times out. Use the Streamable HTTP transport if the server supports it- **No WebSocket transports:** The proxy doesn't support [WebSocket connections](/documentation/platform/agent-vault/proxies#supported-connections)## Troubleshooting@@ -173,6 +196,9 @@ Infisical won't save a custom header with the same name as the credential's head- `SITE_URL` is set to the URL you use to open Infisical- `SITE_URL` uses `https://` (providers such as Linear refuse a redirect URI on plain `http://` unless the host is `localhost`)</Accordion>+ <Accordion title="The tools don't load">+ If Infisical can't get the server's list of tools, the **Tools** step shows the reason, such as a credential the server rejected or a server on a private network. You can still add tools by typing their names in the search field.+ </Accordion><Accordion title="The agent asks you to sign in to the MCP server">The request reached the server without a credential. Check that:diff --git a/docs/documentation/platform/agent-vault/proxies.mdx b/docs/documentation/platform/agent-vault/proxies.mdxindex 7da9e934c6..26b99aa6c5 100644--- a/docs/documentation/platform/agent-vault/proxies.mdx+++ b/docs/documentation/platform/agent-vault/proxies.mdx@@ -187,6 +187,12 @@ The proxy also returns a 403 for:- A request that breaks the service's [method or path rules](/documentation/platform/agent-vault/http-apis#methods-and-paths), under either traffic policy- A request to a service that needs the session owner's [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values), before they set them up+For an [MCP service that allows only some tools](/documentation/platform/agent-vault/mcp-servers#allowed-tools), the proxy also blocks:++- A call to a tool the service doesn't allow. An agent on the Streamable HTTP transport gets an MCP error that names the tool, and any other agent, such as one on the SSE transport, gets a 403 with the same message+- A request the proxy can't read to check which tools it calls, such as a compressed body or JSON that isn't a valid MCP message. The proxy also blocks a request with a body that isn't a `POST`. The agent gets a 400+- A request with a body larger than 32 MiB. The agent gets a 413+### ExceptionsExceptions allow your agents to access hosts that aren't covered by any service in an access bundle, even when your proxy uses **Access bundle hosts only**. Use exceptions for hosts every agent needs, such as a package registry or a documentation site.diff --git a/docs/documentation/platform/agent-vault/session-logs.mdx b/docs/documentation/platform/agent-vault/session-logs.mdxindex e74dd99add..7dd0446e6c 100644--- a/docs/documentation/platform/agent-vault/session-logs.mdx+++ b/docs/documentation/platform/agent-vault/session-logs.mdx@@ -74,7 +74,7 @@ You can view a session's logs if you created the session or you're an Agent Vaul- `serviceType`: `http` or `mcp`, or `null` if no service matched the request- `mcp`: left out for other requests to an MCP service, such as the `GET` that opens an event stream- - `mcp.parsed`: `false` if the proxy couldn't read the calls from the request body, such as a compressed body+ - `mcp.parsed`: `false` if the proxy couldn't read the calls from the request body, such as a compressed body, or if a method or tool name holds characters other than letters, digits, and `_ . : / -` or is longer than 128 characters- `mcp.truncated`: `true` if the request held more than 8 calls and the rest weren't recorded (left out otherwise)</Step></Steps>diff --git a/frontend/src/components/agent-vault/service-sheet/ExpandableValueList.tsx b/frontend/src/components/agent-vault/service-sheet/ExpandableValueList.tsxnew file mode 100644index 0000000000..f65351471a--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/ExpandableValueList.tsx@@ -0,0 +1,39 @@+import { Fragment, useState } from "react";+import { twMerge } from "tailwind-merge";++import { Button } from "@app/components/v3";++const PREVIEW_COUNT = 10;++export const ExpandableValueList = ({+ values,+ className+}: {+ values: string[];+ className?: string;+}) => {+ const [isExpanded, setIsExpanded] = useState(false);+ const shown = isExpanded ? values : values.slice(0, PREVIEW_COUNT);+ const hidden = values.length - shown.length;+ return (+ <span className={twMerge("min-w-0", className)}>+ {shown.map((value, index) => (+ <Fragment key={value}>+ <span className="whitespace-nowrap">{value}</span>+ {index < shown.length - 1 ? ", " : ""}+ </Fragment>+ ))}+ {hidden > 0 && (+ <Button+ type="button"+ variant="link"+ size="sm"+ className="ml-1.5 align-baseline text-xs"+ onClick={() => setIsExpanded(true)}+ >+ +{hidden} more+ </Button>+ )}+ </span>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/McpToolsFields.tsx b/frontend/src/components/agent-vault/service-sheet/McpToolsFields.tsxnew file mode 100644index 0000000000..e5ad85f8f8--- /dev/null+++ b/frontend/src/components/agent-vault/service-sheet/McpToolsFields.tsx@@ -0,0 +1,419 @@+import { useEffect, useId, useMemo, useState } from "react";+import { Controller, useFormContext, useWatch } from "react-hook-form";+import { CircleXIcon, PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-react";++import {+ Alert,+ AlertDescription,+ AlertTitle,+ Badge,+ Button,+ Checkbox,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ FieldTitle,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Pagination,+ RadioGroup,+ RadioGroupItem,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { useListAgentVaultMcpTools } from "@app/hooks/api/agentVault";+import { TAgentVaultMcpTool } from "@app/hooks/api/agentVault/types";++import { buildListMcpToolsRequest } from "./serviceRequest";+import { MAX_ALLOWED_TOOLS, McpToolScope, toolNameError, TServiceForm } from "./serviceSchema";+import { serverMessage } from "./useOAuthAuthorize";++/**+ * A loaded list belongs to the request that loaded it, so a changed URL, transport, credential or custom+ * header needs a new load.+ */+export type TLoadedMcpTools = { source: string; tools: TAgentVaultMcpTool[] };++const SCOPE_CHOICES = [+ {+ value: McpToolScope.All,+ title: "All tools",+ description: "Agents can call every tool the server offers, including ones it adds later."+ },+ {+ value: McpToolScope.Selected,+ title: "Selected tools",+ description: "Agents can call only the tools you select."+ }+];++const PER_PAGE = 10;++type TToolRow = { name: string; description: string | null; isUnlisted: boolean };++type Props = {+ accessBundleId: string;+ serviceId?: string;+ loaded: TLoadedMcpTools | null;+ onLoaded: (loaded: TLoadedMcpTools) => void;+};++export const McpToolsFields = ({ accessBundleId, serviceId, loaded, onLoaded }: Props) => {+ const { control, getValues, setValue, clearErrors, formState } = useFormContext<TServiceForm>();+ const form = useWatch({ control }) as TServiceForm;+ const { toolScope, allowedTools } = form;+ const listTools = useListAgentVaultMcpTools();+ const [loadError, setLoadError] = useState<string | null>(null);+ const [query, setQuery] = useState("");+ const [currentPage, setCurrentPage] = useState(1);+ // Unchecking a tool the server doesn't list keeps its row, so a slip is undone without retyping the name.+ const [addedNames, setAddedNames] = useState<string[]>([]);+ const baseId = useId();++ const toolsSource = (data: TServiceForm) =>+ JSON.stringify(buildListMcpToolsRequest(accessBundleId, serviceId, data));+ const source = toolsSource(form);+ const serverTools = loaded?.source === source ? loaded.tools : null;+ // Each connection is loaded on its own once; after a failure the admin retries with the button.+ const [autoLoadedSource, setAutoLoadedSource] = useState<string | null>(null);++ // Selected tools go first in the order they were in when the list loaded, not live, so a row doesn't jump away+ // from under the pointer when it is checked.+ const [pinnedNames, setPinnedNames] = useState(() => new Set(allowedTools));+ useEffect(() => {+ setPinnedNames(new Set(getValues("allowedTools")));+ }, [serverTools, getValues]);++ const rows = useMemo<TToolRow[]>(() => {+ const listed = serverTools ?? [];+ const listedNames = new Set(listed.map((tool) => tool.name));+ // First, so a saved tool the server dropped is the first thing the admin sees.+ const savedNames = (formState.defaultValues?.allowedTools ?? []).filter(+ (name): name is string => Boolean(name)+ );+ const unlisted = [...new Set([...savedNames, ...addedNames, ...allowedTools])]+ .filter((name) => !listedNames.has(name))+ .map((name) => ({ name, description: null, isUnlisted: serverTools !== null }));+ const listedRows = listed.map((tool) => ({ ...tool, isUnlisted: false }));+ return [+ ...unlisted,+ ...listedRows.filter((row) => pinnedNames.has(row.name)),+ ...listedRows.filter((row) => !pinnedNames.has(row.name))+ ];+ }, [serverTools, allowedTools, addedNames, formState.defaultValues, pinnedNames]);++ const term = query.trim();+ const shownRows = useMemo(() => {+ const lowered = term.toLowerCase();+ if (!lowered) return rows;+ return rows.filter((row) =>+ [row.name, row.description ?? ""].some((text) => text.toLowerCase().includes(lowered))+ );+ }, [rows, term]);+ // What was typed becomes a tool only when no row already has that exact name.+ const termError = term ? toolNameError(term) : null;+ const canAdd = Boolean(term) && !termError && !rows.some((row) => row.name === term);++ const pageCount = Math.max(1, Math.ceil(shownRows.length / PER_PAGE));+ useEffect(() => {+ if (currentPage > pageCount) setCurrentPage(pageCount);+ }, [currentPage, pageCount]);+ const pageRows = shownRows.slice((currentPage - 1) * PER_PAGE, currentPage * PER_PAGE);++ const selected = new Set(allowedTools);+ const pageUnselectedNames = pageRows.map((row) => row.name).filter((name) => !selected.has(name));+ const pageSelectedCount = pageRows.length - pageUnselectedNames.length;+ const canSelectPage = allowedTools.length + pageUnselectedNames.length <= MAX_ALLOWED_TOOLS;++ const setAllowedTools = (next: string[]) => {+ setValue("allowedTools", next, { shouldDirty: true });+ clearErrors("allowedTools");+ };++ const toggleTool = (name: string, isChecked: boolean) =>+ setAllowedTools(+ isChecked ? [...allowedTools, name] : allowedTools.filter((tool) => tool !== name)+ );++ const togglePage = (isChecked: boolean) => {+ const pageNames = new Set(pageRows.map((row) => row.name));+ setAllowedTools(+ isChecked+ ? [...allowedTools, ...pageUnselectedNames]+ : allowedTools.filter((name) => !pageNames.has(name))+ );+ };++ const loadTools = async () => {+ setLoadError(null);+ const request = buildListMcpToolsRequest(accessBundleId, serviceId, getValues());+ // Serialized before the request: field edits mutate nested form values in place.+ const requestSource = JSON.stringify(request);+ // A response for a connection the admin has since changed would replace the current one's list.+ const isCurrent = () => toolsSource(getValues()) === requestSource;+ try {+ const tools = await listTools.mutateAsync(request);+ if (isCurrent()) onLoaded({ source: requestSource, tools });+ } catch (error) {+ if (isCurrent()) {+ setLoadError(serverMessage(error) ?? "The server's tools couldn't be loaded. Try again.");+ }+ }+ };++ useEffect(() => {+ if (toolScope !== McpToolScope.Selected || serverTools || autoLoadedSource === source) return;+ setAutoLoadedSource(source);+ loadTools();+ }, [toolScope, serverTools, autoLoadedSource, source]);++ const addTyped = () => {+ if (!canAdd) return;+ setAllowedTools([...allowedTools, term]);+ setAddedNames((names) => [...names, term]);+ setQuery("");+ };++ const selectedCount = (+ <span className="text-xs whitespace-nowrap text-muted">{allowedTools.length} selected</span>+ );++ let emptyTitle = "No tools selected";+ let emptyDescription =+ "Load the server's tools to pick from them, or type a tool's name above to add it.";+ if (listTools.isPending && !term) {+ emptyTitle = "Loading the server's tools";+ emptyDescription = "You can type a tool's name above to add it in the meantime.";+ } else if (term) {+ emptyTitle = `No tools match "${term}"`;+ emptyDescription = termError ?? "Try a different search.";+ } else if (serverTools) {+ emptyTitle = "The server lists no tools";+ emptyDescription = "Type a tool's name above to add it.";+ }++ return (+ <div className="flex flex-col gap-5">+ <Controller+ control={control}+ name="toolScope"+ render={({ field }) => (+ <Field>+ <FieldLabel>Allowed Tools</FieldLabel>+ <FieldContent>+ <RadioGroup value={field.value} onValueChange={field.onChange}>+ {SCOPE_CHOICES.map((choice) => {+ const id = `${baseId}-scope-${choice.value}`;+ return (+ <FieldLabel key={choice.value} htmlFor={id} variant="av">+ <Field orientation="horizontal">+ <FieldContent>+ <FieldTitle>{choice.title}</FieldTitle>+ <FieldDescription>{choice.description}</FieldDescription>+ </FieldContent>+ <RadioGroupItem id={id} value={choice.value} />+ </Field>+ </FieldLabel>+ );+ })}+ </RadioGroup>+ </FieldContent>+ </Field>+ )}+ />++ {toolScope === McpToolScope.Selected && (+ <Controller+ control={control}+ name="allowedTools"+ render={({ fieldState }) => (+ <Field>+ <FieldLabel htmlFor={`${baseId}-query`}>Tools</FieldLabel>+ <FieldContent className="gap-3">+ <div className="flex items-center gap-2">+ <InputGroup className="flex-1">+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ id={`${baseId}-query`}+ value={query}+ onChange={(e) => {+ setQuery(e.target.value);+ setCurrentPage(1);+ }}+ onKeyDown={(e) => {+ if (e.key !== "Enter") return;+ e.preventDefault();+ addTyped();+ }}+ placeholder="Search or add a tool..."+ autoComplete="off"+ spellCheck={false}+ />+ </InputGroup>+ <Button+ type="button"+ variant="outline"+ onClick={loadTools}+ isPending={listTools.isPending}+ >+ <RefreshCwIcon />+ {serverTools ? "Reload Tools" : "Load Tools"}+ </Button>+ </div>++ {loadError && (+ <Alert variant="danger">+ <CircleXIcon />+ <AlertTitle>Couldn't load the tools</AlertTitle>+ <AlertDescription>+ {loadError} You can still add a tool by typing its name.+ </AlertDescription>+ </Alert>+ )}++ {shownRows.length === 0 && !canAdd ? (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>{emptyTitle}</EmptyTitle>+ <EmptyDescription>{emptyDescription}</EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <div aria-invalid={Boolean(fieldState.error)} className="flex flex-col gap-3">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-10">+ {/* In a form, Radix adds a hidden input after the checkbox; a flex parent keeps it level+ with the checkbox instead of below it, where it overflows the table. */}+ <div className="flex">+ <Checkbox+ id={`${baseId}-all`}+ aria-label="Select every tool on this page"+ isChecked={pageSelectedCount > 0}+ isIndeterminate={+ pageSelectedCount > 0 && pageSelectedCount < pageRows.length+ }+ isDisabled={+ pageRows.length === 0 ||+ (pageSelectedCount < pageRows.length && !canSelectPage)+ }+ onCheckedChange={() =>+ togglePage(pageSelectedCount < pageRows.length)+ }+ />+ </div>+ </TableHead>+ <TableHead className="w-2/5">Name</TableHead>+ <TableHead>Description</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {canAdd && (+ <TableRow className="cursor-pointer" onClick={addTyped}>+ <TableCell>+ <PlusIcon className="size-4 text-accent" aria-hidden="true" />+ </TableCell>+ <TableCell colSpan={2} className="max-w-0">+ <button+ type="button"+ className="block w-full truncate text-left"+ onClick={(e) => {+ e.stopPropagation();+ addTyped();+ }}+ >+ Add <span className="font-mono">{term}</span>+ </button>+ </TableCell>+ </TableRow>+ )}+ {pageRows.map((row) => {+ const isSelected = selected.has(row.name);+ return (+ <TableRow+ key={row.name}+ data-state={isSelected ? "selected" : undefined}+ className="cursor-pointer"+ onClick={() => toggleTool(row.name, !isSelected)}+ >+ <TableCell onClick={(e) => e.stopPropagation()}>+ <div className="flex">+ <Checkbox+ id={`${baseId}-tool-${row.name}`}+ aria-label={`Select ${row.name}`}+ isChecked={isSelected}+ onCheckedChange={(checked) =>+ toggleTool(row.name, checked === true)+ }+ />+ </div>+ </TableCell>+ <TableCell className="max-w-0">+ <div className="flex items-center gap-2">+ <span className="truncate font-mono" title={row.name}>+ {row.name}+ </span>+ {row.isUnlisted && <Badge variant="neutral">Custom</Badge>}+ </div>+ </TableCell>+ <TableCell className="max-w-0">+ {row.description ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <div className="truncate text-muted">{row.description}</div>+ </TooltipTrigger>+ <TooltipContent className="max-w-lg">+ {row.description}+ </TooltipContent>+ </Tooltip>+ ) : (+ <span className="text-muted">-</span>+ )}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ {shownRows.length > PER_PAGE ? (+ <Pagination+ count={shownRows.length}+ page={currentPage}+ perPage={PER_PAGE}+ perPageList={[PER_PAGE]}+ onChangePage={setCurrentPage}+ onChangePerPage={() => {}}+ startAdornment={selectedCount}+ />+ ) : (+ selectedCount+ )}+ </div>+ )}++ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ )}+ </div>+ );+};diff --git a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsxindex 8161ad1819..001e18ff9c 100644--- a/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx+++ b/frontend/src/components/agent-vault/service-sheet/OAuthAuthorizeCard.tsx@@ -1,4 +1,4 @@-import { Fragment, ReactNode, useEffect, useId, useState } from "react";+import { ReactNode, useEffect, useId, useState } from "react";import { useFormContext, useWatch } from "react-hook-form";import { CheckIcon, CircleAlertIcon, CircleXIcon, InfoIcon, TriangleAlertIcon } from "lucide-react";import { twMerge } from "tailwind-merge";@@ -27,6 +27,7 @@ import {import { AgentVaultOauthStatus } from "@app/hooks/api/agentVault";import { TAgentVaultService } from "@app/hooks/api/agentVault/types";+import { ExpandableValueList } from "./ExpandableValueList";import {newOAuthAuthorizationId,OAUTH_STATUS_LABELS,@@ -87,43 +88,18 @@ const Status = ({</div>);-const SCOPE_PREVIEW = 10;--const ScopeValues = ({ scopes, className }: { scopes: string[]; className?: string }) => {- const [isExpanded, setIsExpanded] = useState(false);- const shown = isExpanded ? scopes : scopes.slice(0, SCOPE_PREVIEW);- const hidden = scopes.length - shown.length;- return (- <span className={twMerge("min-w-0", className)}>- {shown.map((scope, index) => (- <Fragment key={scope}>- <span className="whitespace-nowrap">{scope}</span>- {index < shown.length - 1 ? ", " : ""}- </Fragment>- ))}- {hidden > 0 && (- <Button- type="button"- variant="link"- size="sm"- className="ml-1.5 align-baseline text-xs"- onClick={() => setIsExpanded(true)}- >- +{hidden} more- </Button>- )}- </span>- );-};-const Scopes = ({ granted, requested }: { granted: string[]; requested: string[] }) => (<div className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs"><span className="text-muted">Scopes</span>- {granted.length ? <ScopeValues scopes={granted} /> : <span className="text-muted">None</span>}+ {granted.length ? (+ <ExpandableValueList values={granted} />+ ) : (+ <span className="text-muted">None</span>+ )}{requested.length > 0 && (<><span className="text-muted">Requested</span>- <ScopeValues scopes={requested} className="text-warning" />+ <ExpandableValueList values={requested} className="text-warning" /></>)}</div>diff --git a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsxindex 4dce664f7f..9d9af5f01c 100644--- a/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ReviewFields.tsx@@ -16,9 +16,11 @@ import {} from "@app/hooks/api/agentVault";import { TAgentVaultService } from "@app/hooks/api/agentVault/types";+import { ExpandableValueList } from "./ExpandableValueList";import {CREDENTIAL_LABELS,isAllMethods,+ McpToolScope,oauthStatusLabel,SURFACE_LABELS,TRANSPORT_LABELS,@@ -72,6 +74,7 @@ export const ReviewFields = ({ isUpdate, service, storedType, storedMemberFieldsconst isMcp = form.serviceType === AgentVaultServiceType.Mcp;const isBasic = form.credentialType === AgentVaultCredentialType.Basic;const isOAuth = form.credentialType === AgentVaultCredentialType.OAuth;+ const isAllTools = form.toolScope === McpToolScope.All;const secretLabel = isBasic ? "Password" : "Token";const sends = credentialPreview(form);@@ -207,6 +210,20 @@ export const ReviewFields = ({ isUpdate, service, storedType, storedMemberFields</div>)}</DetailGroup>++ {isMcp && (+ <DetailGroup>+ <DetailGroupHeader className="border-b border-border pb-2">Tools</DetailGroupHeader>+ <Detail className="w-full min-w-0">+ <DetailLabel>+ {isAllTools ? "Allowed" : `Allowed (${form.allowedTools.length})`}+ </DetailLabel>+ <DetailValue>+ {isAllTools ? "All" : <ExpandableValueList values={form.allowedTools} />}+ </DetailValue>+ </Detail>+ </DetailGroup>+ )}</div>);};diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex 56f1434a71..cc3d2ce0f5 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -65,6 +65,7 @@ import { CredentialFields } from "./CredentialFields";import { DetailsFields } from "./DetailsFields";import { McpCredentialFields } from "./McpCredentialFields";import { McpDetailsFields } from "./McpDetailsFields";+import { McpToolsFields, TLoadedMcpTools } from "./McpToolsFields";import { ReviewFields } from "./ReviewFields";import { buildCreateServiceRequest, buildUpdateServiceRequest } from "./serviceRequest";import {@@ -73,6 +74,7 @@ import {HTTP_METHODS,isOAuthAuthorizationMissing,MCP_SERVICE_STEP_FIELDS,+ McpToolScope,SERVICE_STEP_FIELDS,SERVICE_TYPE_LABELS,ServiceStep,@@ -96,6 +98,8 @@ const BLANK_SERVICE_FORM: TServiceForm = {hosts: [],hostDraft: "",pathDraft: "",+ toolScope: McpToolScope.All,+ allowedTools: [],credentialType: AgentVaultCredentialType.Passthrough,headerName: "Authorization",headerPrefix: "Bearer",@@ -400,6 +404,8 @@ export const ServiceSheet = ({const panelRef = useRef<HTMLDivElement>(null);const [openItem, setOpenItem] = useState(ADVANCED_ITEM);const [isSigningIn, setIsSigningIn] = useState(false);+ // Held here rather than in the Tools step, so going to Review and back doesn't drop the list.+ const [loadedTools, setLoadedTools] = useState<TLoadedMcpTools | null>(null);// The stand-in for formState.submitCount, which only counts handleSubmit and so never moves for a// wizard that gates its steps with trigger. Without it a second Continue reveals nothing, because// the errors it finds are the ones already there.@@ -443,6 +449,7 @@ export const ServiceSheet = ({setStep(0);setTemplate(null);+ setLoadedTools(null);setOpenItem(service?.type === AgentVaultServiceType.Mcp ? "" : ADVANCED_ITEM);if (service?.type === AgentVaultServiceType.Mcp) {@@ -453,6 +460,8 @@ export const ServiceSheet = ({name: service.name,serverUrl: service.serverUrl,transport: service.transport,+ toolScope: service.allowedTools ? McpToolScope.Selected : McpToolScope.All,+ allowedTools: service.allowedTools ?? [],credentialType: isBearer ? AgentVaultCredentialType.Bearer : AgentVaultCredentialType.OAuth,headerName: isBearer ? credential.headerName : "Authorization",headerPrefix: isBearer ? credential.headerPrefix : "Bearer",@@ -628,6 +637,7 @@ export const ServiceSheet = ({transport: ServiceStep.Details,allowedMethods: ServiceStep.Details,allowedPathPrefixes: ServiceStep.Details,+ allowedTools: ServiceStep.Tools,credential: ServiceStep.Credential,customHeaders: ServiceStep.Credential,substitutions: ServiceStep.Credential@@ -857,6 +867,14 @@ export const ServiceSheet = ({</div></ServiceVariablesContext.Provider>)}+ {current.step === ServiceStep.Tools && (+ <McpToolsFields+ accessBundleId={accessBundleId}+ serviceId={service?.id}+ loaded={loadedTools}+ onLoaded={setLoadedTools}+ />+ )}{current.step === ServiceStep.Review && (<ReviewFieldsisUpdate={isUpdate}diff --git a/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.tsindex ec07b38a97..8d00c86f3f 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.test.ts@@ -8,8 +8,12 @@ import {AgentVaultSubstitutionSurface} from "@app/hooks/api/agentVault";-import { buildCreateServiceRequest, buildUpdateServiceRequest } from "./serviceRequest";-import { HTTP_METHODS, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";+import {+ buildCreateServiceRequest,+ buildListMcpToolsRequest,+ buildUpdateServiceRequest+} from "./serviceRequest";+import { HTTP_METHODS, McpToolScope, TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";const SERVER_URL = "https://mcp.linear.app/mcp";@@ -21,6 +25,8 @@ const form = (overrides: Partial<TServiceForm> = {}): TServiceForm => ({hosts: ["api.stripe.com"],hostDraft: "",pathDraft: "",+ toolScope: McpToolScope.All,+ allowedTools: [],credentialType: AgentVaultCredentialType.Bearer,headerName: "Authorization",headerPrefix: "Bearer",@@ -131,11 +137,36 @@ describe("buildCreateServiceRequest", () => {name: "linear-mcp",serverUrl: SERVER_URL,transport: AgentVaultMcpTransport.StreamableHttp,+ allowedTools: null,customHeaders: [],credential: { type: AgentVaultCredentialType.OAuth, authorizationId: "auth-1" }});});+ it("sends the selected tools for an MCP service, and null for all tools even with picks kept", () => {+ expect(+ buildCreateServiceRequest(+ "bundle-1",+ mcpForm({ toolScope: McpToolScope.Selected, allowedTools: ["read_file", "list_issues"] })+ )+ ).toMatchObject({ allowedTools: ["read_file", "list_issues"] });+ expect(+ buildCreateServiceRequest(+ "bundle-1",+ mcpForm({ toolScope: McpToolScope.All, allowedTools: ["read_file"] })+ )+ ).toMatchObject({ allowedTools: null });+ });++ it("never sends allowed tools for an HTTP service", () => {+ expect(+ buildCreateServiceRequest(+ "bundle-1",+ form({ toolScope: McpToolScope.Selected, allowedTools: ["read_file"] })+ )+ ).not.toHaveProperty("allowedTools");+ });+it("sends an empty authorization when it was made for another URL", () => {const request = buildCreateServiceRequest("bundle-1",@@ -237,6 +268,7 @@ describe("buildUpdateServiceRequest", () => {name: "linear-mcp",serverUrl: SERVER_URL,transport: AgentVaultMcpTransport.StreamableHttp,+ allowedTools: null,customHeaders: []});expect(@@ -255,6 +287,26 @@ describe("buildUpdateServiceRequest", () => {).toEqual({ type: AgentVaultCredentialType.OAuth, authorizationId: "auth-2" });});+ it("clears allowed tools with null, sends a changed list, and never sends them for HTTP", () => {+ expect(+ buildUpdateServiceRequest(+ "bundle-1",+ "service-1",+ mcpForm({ toolScope: McpToolScope.Selected, allowedTools: ["read_file"] })+ )+ ).toMatchObject({ allowedTools: ["read_file"] });+ expect(buildUpdateServiceRequest("bundle-1", "service-1", mcpForm())).toMatchObject({+ allowedTools: null+ });+ expect(+ buildUpdateServiceRequest(+ "bundle-1",+ "service-1",+ form({ toolScope: McpToolScope.Selected, allowedTools: ["read_file"] })+ )+ ).not.toHaveProperty("allowedTools");+ });+it("never sends a header name or prefix for OAuth", () => {expect(buildUpdateServiceRequest(@@ -270,3 +322,74 @@ describe("buildUpdateServiceRequest", () => {).toEqual({ type: AgentVaultCredentialType.OAuth, authorizationId: "auth-2" });});});++describe("buildListMcpToolsRequest", () => {+ it("sends a typed token and header values for a new service", () => {+ expect(+ buildListMcpToolsRequest(+ "bundle-1",+ undefined,+ mcpForm({+ credentialType: AgentVaultCredentialType.Bearer,+ secret: "{{LINEAR_TOKEN}}",+ transport: AgentVaultMcpTransport.Sse,+ customHeaders: [{ name: "X-Org", prefix: "", value: "acme" }],+ toolScope: McpToolScope.Selected,+ allowedTools: ["read_file"]+ })+ )+ ).toEqual({+ accessBundleId: "bundle-1",+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.Sse,+ customHeaders: [{ name: "X-Org", prefix: "", value: "acme" }],+ credential: {+ type: AgentVaultCredentialType.Bearer,+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: "{{LINEAR_TOKEN}}",+ memberProvidedFields: []+ }+ });+ });++ it("leaves untouched values out on edit, so the saved service's are used", () => {+ expect(+ buildListMcpToolsRequest(+ "bundle-1",+ "service-1",+ mcpForm({+ credentialType: AgentVaultCredentialType.Bearer,+ secret: UNCHANGED_SECRET,+ customHeaders: [{ id: "h-1", name: "X-Org", prefix: "", value: UNCHANGED_SECRET }]+ })+ )+ ).toEqual({+ accessBundleId: "bundle-1",+ serviceId: "service-1",+ serverUrl: SERVER_URL,+ transport: AgentVaultMcpTransport.StreamableHttp,+ customHeaders: [{ id: "h-1", name: "X-Org", prefix: "" }],+ credential: {+ type: AgentVaultCredentialType.Bearer,+ headerName: "Authorization",+ headerPrefix: "Bearer",+ value: undefined,+ memberProvidedFields: []+ }+ });+ });++ it("sends a pending OAuth authorization for the current URL, and none otherwise", () => {+ expect(+ buildListMcpToolsRequest(+ "bundle-1",+ undefined,+ mcpForm({ oauthAuthorizationId: "auth-1", oauthAuthorizedUrl: SERVER_URL })+ ).credential+ ).toEqual({ type: AgentVaultCredentialType.OAuth, authorizationId: "auth-1" });+ expect(buildListMcpToolsRequest("bundle-1", "service-1", mcpForm())).not.toHaveProperty(+ "credential"+ );+ });+});diff --git a/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts b/frontend/src/components/agent-vault/service-sheet/serviceRequest.tsindex 877864fdfd..ad50340c85 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceRequest.ts@@ -8,11 +8,13 @@ import {TAgentVaultCredentialInput,TAgentVaultCredentialUpdate,TCreateAgentVaultServiceDTO,+ TListAgentVaultMcpToolsDTO,TUpdateAgentVaultServiceDTO} from "@app/hooks/api/agentVault/types";import {isAllMethods,+ McpToolScope,newOAuthAuthorizationId,TServiceForm,UNCHANGED_SECRET@@ -144,13 +146,18 @@ const buildHttpFields = (data: TServiceForm) => ({substitutions: buildSubstitutions(data)});-const buildMcpFields = (data: TServiceForm) => ({- name: data.name,+const buildMcpConnection = (data: TServiceForm) => ({serverUrl: data.serverUrl.trim(),transport: data.transport,customHeaders: buildCustomHeaders(data)});+const buildMcpFields = (data: TServiceForm) => ({+ name: data.name,+ ...buildMcpConnection(data),+ allowedTools: data.toolScope === McpToolScope.Selected ? data.allowedTools : null+});+export const buildCreateServiceRequest = (accessBundleId: string,data: TServiceForm@@ -189,3 +196,16 @@ export const buildUpdateServiceRequest = (...buildHttpFields(data),credential: buildHttpCredentialPatch(data)};++// The credential and headers go as an update sends them, so on edit a value left untouched falls back to+// the saved service's.+export const buildListMcpToolsRequest = (+ accessBundleId: string,+ serviceId: string | undefined,+ data: TServiceForm+): TListAgentVaultMcpToolsDTO => ({+ accessBundleId,+ ...(serviceId ? { serviceId } : {}),+ ...buildMcpConnection(data),+ ...withCredential(buildMcpCredentialPatch(data))+});diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.tsindex b6231ad8ac..01940aa854 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts@@ -11,6 +11,8 @@ import { TAgentVaultService } from "@app/hooks/api/agentVault/types";import {buildServiceSchema,isOAuthAuthorizationMissing,+ MAX_ALLOWED_TOOLS,+ McpToolScope,newOAuthAuthorizationId,OAUTH_CLIENT_VARIABLES_MESSAGE,oauthStatusLabel,@@ -29,6 +31,8 @@ const mcpForm = (overrides: Partial<TServiceForm> = {}): TServiceForm => ({hosts: [],hostDraft: "",pathDraft: "",+ toolScope: McpToolScope.All,+ allowedTools: [],credentialType: AgentVaultCredentialType.OAuth,headerName: "Authorization",headerPrefix: "Bearer",@@ -56,6 +60,7 @@ const storedOAuthService = (serverUrl = SERVER_URL) =>transport: AgentVaultMcpTransport.StreamableHttp,allowedMethods: null,allowedPathPrefixes: null,+ allowedTools: null,credential: {type: AgentVaultCredentialType.OAuth,status: AgentVaultOauthStatus.NeedsReauthorization,@@ -320,3 +325,59 @@ describe("buildServiceSchema with OAuth", () => {]);});});++describe("buildServiceSchema with allowed tools", () => {+ const authorized = { oauthAuthorizationId: "auth-1", oauthAuthorizedUrl: SERVER_URL };+ const toolIssues = (overrides: Partial<TServiceForm>) =>+ buildServiceSchema()+ .safeParse(mcpForm({ ...authorized, toolScope: McpToolScope.Selected, ...overrides }))+ .error?.issues.map(({ path, message }) => [path.join("."), message]) ?? [];++ it("accepts all tools with nothing selected, and keeps picks made before switching to all", () => {+ expect(buildServiceSchema().safeParse(mcpForm(authorized)).success).toBe(true);+ expect(+ buildServiceSchema().safeParse(mcpForm({ ...authorized, allowedTools: [" bad name"] }))+ .success+ ).toBe(true);+ });++ it("accepts any selected tool name, case-sensitive", () => {+ expect(+ toolIssues({+ allowedTools: [+ "read_file",+ "Read_File",+ "github:issues/create.v2-beta",+ "query+sum",+ "read file"+ ]+ })+ ).toEqual([]);+ });++ it("requires at least one selected tool", () => {+ expect(toolIssues({ allowedTools: [] })).toEqual([+ ["allowedTools", "Select at least one tool, or allow all tools."]+ ]);+ });++ it("refuses untrimmed names, control characters, names over 128 characters, and duplicates", () => {+ expect(+ toolIssues({+ allowedTools: [" read_file", "a".repeat(129), "read\u0000file", "ok", "ok"]+ }).map(([path]) => path)+ ).toEqual(["allowedTools", "allowedTools", "allowedTools", "allowedTools"]);+ expect(toolIssues({ allowedTools: ["ok", "ok"] })).toEqual([+ ["allowedTools", '"ok" is listed twice.']+ ]);+ expect(toolIssues({ allowedTools: ["a".repeat(128)] })).toEqual([]);+ });++ it("caps the list at the API's limit", () => {+ const names = (count: number) => Array.from({ length: count }, (_, index) => `tool_${index}`);+ expect(toolIssues({ allowedTools: names(MAX_ALLOWED_TOOLS) })).toEqual([]);+ expect(toolIssues({ allowedTools: names(MAX_ALLOWED_TOOLS + 1) })).toEqual([+ ["allowedTools", `You can select at most ${MAX_ALLOWED_TOOLS} tools.`]+ ]);+ });+});diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.tsindex 98a3717cbf..5b7690a314 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts@@ -101,6 +101,30 @@ const AGENT_VAULT_MAX_HOST_PATTERN_LENGTH = 1024;const MAX_SERVER_URL_LENGTH = 2048;+export enum McpToolScope {+ All = "all",+ Selected = "selected"+}++// Mirrors agent-vault-tool-name-schemas.ts on the backend. The proxy compares names exactly, whatever characters+// they hold.+export const MAX_ALLOWED_TOOLS = 500;+const MAX_TOOL_NAME_LENGTH = 128;++// Not trimmed: names are exact and case-sensitive, so a stray space is refused rather than quietly dropped.+export const toolNameError = (name: string): string | null => {+ if (!name) return "Enter a tool name.";+ if (name.length > MAX_TOOL_NAME_LENGTH) {+ return `A tool name can be at most ${MAX_TOOL_NAME_LENGTH} characters.`;+ }+ if (name !== name.trim()) return "A tool name can't start or end with a space.";+ // eslint-disable-next-line no-control-regex+ if (/[\u0000-\u001f\u007f-\u009f]/.test(name)) {+ return "A tool name can't contain control characters.";+ }+ return null;+};+export const serverUrlError = (value: string): string | null => {const trimmed = value.trim();if (!trimmed) return "Enter the server URL.";@@ -192,6 +216,7 @@ export enum ServiceStep {Template = "template",Details = "details",Credential = "credential",+ Tools = "tools",Review = "review"}@@ -208,6 +233,7 @@ export const SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {"customHeaders","substitutions"],+ [ServiceStep.Tools]: [],[ServiceStep.Review]: []};@@ -224,6 +250,7 @@ export const MCP_SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {"oauthClientSecret","customHeaders"],+ [ServiceStep.Tools]: ["toolScope", "allowedTools"],[ServiceStep.Review]: []};@@ -291,6 +318,9 @@ export const buildServiceSchema = (// setError, so a refusal held outside the form would let the step advance.hostDraft: z.string(),pathDraft: z.string(),+ // Kept while All is chosen, so switching back restores the picks. Only Selected sends them.+ toolScope: z.nativeEnum(McpToolScope),+ allowedTools: z.array(z.string()),credentialType: z.nativeEnum(AgentVaultCredentialType),// Checked in superRefine, only while Bearer is selected: switching away hides these fields but keeps them.headerName: z.string().trim().optional(),@@ -390,6 +420,33 @@ export const buildServiceSchema = (}}+ if (isMcp && data.toolScope === McpToolScope.Selected) {+ if (data.allowedTools.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["allowedTools"],+ message: "Select at least one tool, or allow all tools."+ });+ } else if (data.allowedTools.length > MAX_ALLOWED_TOOLS) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["allowedTools"],+ message: `You can select at most ${MAX_ALLOWED_TOOLS} tools.`+ });+ }+ const seenTools = new Set<string>();+ data.allowedTools.forEach((name) => {+ const nameError = toolNameError(name);+ let message: string | null = null;+ if (nameError) message = name ? `"${name}": ${nameError}` : nameError;+ else if (seenTools.has(name)) message = `"${name}" is listed twice.`;+ seenTools.add(name);+ if (message) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["allowedTools"], message });+ }+ });+ }+if (!isMcp) addHostIssues(data.hosts, ctx, ["hosts"]);const hostDraft = isMcp ? "" : data.hostDraft.trim();if (hostDraft) {diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.tsindex c2eeae6ac6..bfc7e3bc1d 100644--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts@@ -78,8 +78,20 @@ export const MCP_SERVICE_STEPS: StepMeta[] = [subtitle: "How the proxy authenticates to this MCP server.",rightLabel: "CREDENTIAL",rightDescription:- "The proxy authenticates to the MCP server for the agent. The agent can call any tool the server exposes to this credential.",+ "The proxy authenticates to the MCP server for the agent. You choose which of its tools the agent can call on the next step.",rightTip: MCP_VARIABLE_TIP},+ {+ step: ServiceStep.Tools,+ name: "Tools",+ shortDescription: "Tools agents can call",+ title: "Tools",+ subtitle: "Which of the server's tools agents can call through this service.",+ rightLabel: "TOOLS",+ rightDescription:+ "The proxy refuses a call to any tool that isn't selected and hides it from the agent's tool list. The rule applies to every member and session using this service.",+ rightTip:+ "Choosing Selected tools asks the server for its list with the credential from the previous step; Reload Tools asks again. A tool the server doesn't list, such as one the credential lacks the scope for, can be added by typing its exact name in the search field."+ },REVIEW_STEP];diff --git a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.tsindex 80ac6ecd72..6f87e80a07 100644--- a/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts+++ b/frontend/src/components/agent-vault/service-sheet/useOAuthAuthorize.ts@@ -23,7 +23,7 @@ type TOAuthAuthorizeState =| { status: "authorized" }| { status: "failed"; message: string };-const serverMessage = (error: unknown) => {+export const serverMessage = (error: unknown) => {if (!axios.isAxiosError<{ message?: unknown }>(error)) return null;const message = error.response?.data?.message;return typeof message === "string" ? message : null;diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 24c5cd4d8f..fcfe997309 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -13,6 +13,7 @@ import {TAgentVaultActorIdsDTO,TAgentVaultActorRef,TAgentVaultGrantedMember,+ TAgentVaultMcpTool,TAgentVaultMemberWriteResult,TAgentVaultMintedSession,TAgentVaultOauthAuthorization,@@ -33,6 +34,7 @@ import {TCreateAgentVaultSessionDTO,TCreateAgentVaultVariableDTO,TDeleteAgentVaultPersonalValuesDTO,+ TListAgentVaultMcpToolsDTO,TSetAgentVaultPersonalValuesDTO,TUpdateAgentVaultAccessBundleDTO,TUpdateAgentVaultMemberRolesDTO,@@ -521,6 +523,20 @@ export const useCompleteAgentVaultOauthAuthorization = () =>}});+// A read, but its body can carry a credential, and it only runs when the admin asks.+export const useListAgentVaultMcpTools = () =>+ useMutation({+ // The Tools step shows the server's failure in place.+ meta: { skipErrorToast: true },+ mutationFn: async ({ accessBundleId, ...params }: TListAgentVaultMcpToolsDTO) => {+ const { data } = await apiRequest.post<{ tools: TAgentVaultMcpTool[] }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/mcp-tools/list`,+ params+ );+ return data.tools;+ }+ });+// The status shows on the bundle read and the bundle list, and Used By on personal variables follows the references.const invalidatePersonalValues = (queryClient: ReturnType<typeof useQueryClient>,diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 4ee16f0af4..bfb2be9c87 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -122,6 +122,8 @@ export type TAgentVaultService = TAgentVaultServiceConfig & {// null means unrestricted.allowedMethods: AgentVaultHttpMethod[] | null;allowedPathPrefixes: string[] | null;+ // Only an MCP service ever has a list.+ allowedTools: string[] | null;credential: TAgentVaultCredentialSummary;customHeaders: TAgentVaultCustomHeaderSummary[];substitutions: TAgentVaultSubstitutionSummary[];@@ -337,6 +339,7 @@ export type TCreateAgentVaultServiceDTO =name: string;serverUrl: string;transport: AgentVaultMcpTransport;+ allowedTools?: string[] | null;credential:| Extract<TAgentVaultCredentialInput, { type: AgentVaultCredentialType.Bearer }>| TAgentVaultOauthCredentialInput;@@ -354,11 +357,27 @@ export type TUpdateAgentVaultServiceDTO = {allowedPathPrefixes?: string[] | null;serverUrl?: string;transport?: AgentVaultMcpTransport;+ allowedTools?: string[] | null;credential?: TAgentVaultCredentialUpdate;customHeaders?: TAgentVaultCustomHeaderInput[];substitutions?: TAgentVaultSubstitutionInput[];};+/** Credential and header values left out fall back to what the saved service stores, as on update. */+export type TListAgentVaultMcpToolsDTO = {+ accessBundleId: string;+ serviceId?: string;+ serverUrl: string;+ transport: AgentVaultMcpTransport;+ credential?: TAgentVaultCredentialUpdate;+ customHeaders?: TAgentVaultCustomHeaderInput[];+};++export type TAgentVaultMcpTool = {+ name: string;+ description: string | null;+};+export type TAgentVaultOauthAuthorization = {id: string;status: AgentVaultOauthAuthorizationStatus;