Skip to content

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

misc: addressed feedback

Sheen Capadngan065ec545cfbb
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.ts
index b90d2a3b0a..5b59d99be4 100644
--- a/backend/src/db/migrations/20261029073000_agent-vault-service-allowed-tools.ts
+++ b/backend/src/db/migrations/20261029073000_agent-vault-service-allowed-tools.ts
@@ -2,6 +2,23 @@ import { Knex } from "knex";
import { TableName } from "../schemas";
+// Each rule column holds NULL (no restriction) or a non-empty list, and only on the service type it applies to: the
+// proxy reads an empty list as "allow nothing", and the Go backend shares this table without the API's checks.
+const RULE_CHECKS = [
+ {
+ name: "agent_vault_services_allowed_tools_check",
+ check: `"allowedTools" IS NULL OR (cardinality("allowedTools") > 0 AND "type" = 'mcp')`
+ },
+ {
+ name: "agent_vault_services_allowed_methods_check",
+ check: `"allowedMethods" IS NULL OR (cardinality("allowedMethods") > 0 AND "type" = 'http')`
+ },
+ {
+ name: "agent_vault_services_allowed_path_prefixes_check",
+ check: `"allowedPathPrefixes" IS NULL OR (cardinality("allowedPathPrefixes") > 0 AND "type" = 'http')`
+ }
+];
+
export async function up(knex: Knex): Promise<void> {
if (!(await knex.schema.hasColumn(TableName.AgentVaultService, "allowedTools"))) {
await knex.schema.alterTable(TableName.AgentVaultService, (t) => {
@@ -9,9 +26,29 @@ export async function up(knex: Knex): Promise<void> {
t.specificType("allowedTools", "text[]");
});
}
+
+ // eslint-disable-next-line no-restricted-syntax
+ for (const { name, check } of RULE_CHECKS) {
+ // eslint-disable-next-line no-await-in-loop
+ await knex.raw(`ALTER TABLE ?? DROP CONSTRAINT IF EXISTS ??`, [TableName.AgentVaultService, name]);
+ // NOT VALID first, so one stray older row can't fail the deploy; new writes are checked either way.
+ // eslint-disable-next-line no-await-in-loop
+ await knex.raw(`ALTER TABLE ?? ADD CONSTRAINT ?? CHECK (${check}) NOT VALID`, [TableName.AgentVaultService, name]);
+ // eslint-disable-next-line no-await-in-loop
+ const violation = await knex(TableName.AgentVaultService).whereRaw(`NOT (${check})`).first("id");
+ if (!violation) {
+ // eslint-disable-next-line no-await-in-loop
+ await knex.raw(`ALTER TABLE ?? VALIDATE CONSTRAINT ??`, [TableName.AgentVaultService, name]);
+ }
+ }
}
export async function down(knex: Knex): Promise<void> {
+ // eslint-disable-next-line no-restricted-syntax
+ for (const { name } of RULE_CHECKS) {
+ // eslint-disable-next-line no-await-in-loop
+ await knex.raw(`ALTER TABLE ?? DROP CONSTRAINT IF EXISTS ??`, [TableName.AgentVaultService, name]);
+ }
if (await knex.schema.hasColumn(TableName.AgentVaultService, "allowedTools")) {
await knex.schema.alterTable(TableName.AgentVaultService, (t) => {
t.dropColumn("allowedTools");
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.ts
index 7ea2484314..13d28412d3 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,6 +35,7 @@ import {
OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE,
TAgentVaultOauthServiceFactory
} from "../agent-vault-oauth/agent-vault-oauth-service";
+import { hashAccessToken } from "../agent-vault-oauth/agent-vault-oauth-token-fns";
import {
AGENT_VAULT_OAUTH_HEADER_NAME,
AGENT_VAULT_OAUTH_HEADER_PREFIX,
@@ -119,7 +120,7 @@ import {
splitCredential,
TCredentialWrite
} from "./agent-vault-credential-write-fns";
-import { listMcpServerTools } from "./agent-vault-mcp-tool-list-fns";
+import { listMcpServerTools, McpListError } 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";
@@ -1718,7 +1719,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
// 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;
+ // Set when the token is the service's saved OAuth token, which can be refreshed if the server refuses it.
+ let refreshSavedToken: ((rejectedTokenHash: string) => Promise<string>) | undefined;
const credentialType = credential?.type ?? (service?.credentialType as AgentVaultCredentialType | undefined);
if (credentialType === AgentVaultCredentialType.OAuth) {
let accessToken: string;
@@ -1736,18 +1738,25 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
// 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."
+ const savedService = service!;
+ const refreshToken = async (rejectedTokenHash?: string) => {
+ const refreshed = await agentVaultOauthService.refreshServiceToken({
+ serviceId: savedService.id,
+ projectId: rest.projectId,
+ expiresWithinSeconds: 60,
+ rejectedTokenHash,
+ destination: { hostPattern: savedService.hostPattern, serverUrl: storedServerUrl }
});
- }
- accessToken = refreshed.credential.value;
+ 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."
+ });
+ }
+ return refreshed.credential.value;
+ };
+ accessToken = await refreshToken();
+ refreshSavedToken = refreshToken;
}
credentialHeader = {
name: AGENT_VAULT_OAUTH_HEADER_NAME,
@@ -1769,7 +1778,6 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
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();
@@ -1799,16 +1807,8 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
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 = [
@@ -1825,16 +1825,26 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBund
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 listWith = (token: string) =>
+ listMcpServerTools({
+ serverUrl,
+ transport,
+ headers: {
+ ...Object.fromEntries(headerValues.map((header) => [header.name, withPrefix(header.prefix, header.value)])),
+ [credentialHeader.name]: withPrefix(credentialHeader.prefix, token)
+ },
+ secrets: [token, ...headerValues.map((header) => header.value)]
+ });
+ try {
+ return { tools: await listWith(credentialValue) };
+ } catch (err) {
+ // A saved token can be refused before it expires (revoked, or no expiry from the provider), so it is refreshed
+ // once, as the proxy does, before the admin is asked to reauthorize.
+ if (!(err instanceof McpListError && err.isCredentialRejected) || !refreshSavedToken) throw err;
+ const refreshedToken = await refreshSavedToken(hashAccessToken(credentialValue));
+ if (refreshedToken === credentialValue) throw err;
+ return { tools: await listWith(refreshedToken) };
+ }
};
const deleteService = async ({ accessBundleId, serviceId, ...rest }: TDeleteServiceDTO) => {
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.ts
index d99bcee759..912622cad8 100644
--- 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.ts
@@ -2,9 +2,14 @@ import { PassThrough, Readable } from "node:stream";
import { describe, expect, test, vi } from "vitest";
+import { BadRequestError } from "@app/lib/errors";
+import { PRIVATE_ADDRESS_REFUSED_MESSAGE } from "@app/lib/validator";
+
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/config/env", () => ({ getConfig: () => ({ isCloud: false }) }));
+
vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
const SERVER_URL = "https://mcp.example.com/mcp";
@@ -99,6 +104,72 @@ describe("listing an MCP server's tools", () => {
).rejects.toThrow("'mcp.example.com' rejected the credential (HTTP 401).");
});
+ test("a rejected credential is told apart, so a refreshable token can be refreshed", async () => {
+ const http: TMcpHttpClient = { request: async () => json(403, {}) };
+ await expect(
+ listMcpServerTools({
+ serverUrl: SERVER_URL,
+ transport: AgentVaultMcpTransport.StreamableHttp,
+ headers: AUTH,
+ secrets: SECRETS,
+ http
+ })
+ ).rejects.toMatchObject({ isCredentialRejected: true });
+ });
+
+ const list = (http: TMcpHttpClient, transport = AgentVaultMcpTransport.StreamableHttp) =>
+ listMcpServerTools({ serverUrl: SERVER_URL, transport, headers: AUTH, secrets: SECRETS, http, budgetMs: 1000 });
+
+ test("an answer whose id is the request's id as a string is matched", async () => {
+ const { http } = streamableServer((message) =>
+ json(200, { jsonrpc: "2.0", id: String(message.id), result: toolsPage(["read_file"]) })
+ );
+ expect(await list(http)).toEqual([{ name: "read_file", description: "Does read_file" }]);
+ });
+
+ test("a refusal says what the server said, without echoing the credential", async () => {
+ const http: TMcpHttpClient = {
+ request: async () =>
+ json(400, { jsonrpc: "2.0", id: null, error: { code: -32000, message: "Session not found secret-token" } })
+ };
+ await expect(list(http)).rejects.toThrow(
+ "'mcp.example.com' refused the request (HTTP 400): Session not found [redacted]."
+ );
+ });
+
+ test("a 405 with nothing to say suggests the other transport", async () => {
+ const http: TMcpHttpClient = {
+ request: async () => ({ status: 405, contentType: "text/html", sessionId: null, body: Readable.from(["<h1>"]) })
+ };
+ await expect(list(http)).rejects.toThrow("If the server uses SSE, choose that transport.");
+ });
+
+ test("a redirect names where it points, without its query string", async () => {
+ const http: TMcpHttpClient = {
+ request: async () => ({
+ status: 307,
+ contentType: "",
+ sessionId: null,
+ location: "/mcp/?token=x",
+ body: Readable.from([])
+ })
+ };
+ await expect(list(http)).rejects.toThrow(
+ "'mcp.example.com' redirected the request to 'https://mcp.example.com/mcp/'. Use that address as the server URL"
+ );
+ });
+
+ test("a server on a private network says so, with the setting a self-hosted instance can change", async () => {
+ const http: TMcpHttpClient = {
+ request: async () => {
+ throw new BadRequestError({ message: PRIVATE_ADDRESS_REFUSED_MESSAGE });
+ }
+ };
+ await expect(list(http)).rejects.toThrow(
+ "Infisical can't reach 'mcp.example.com' because it's on a private network. If you're self-hosting Infisical, set the 'ALLOW_INTERNAL_IP_CONNECTIONS' environment variable to 'true' on your instance to allow it."
+ );
+ });
+
test.each(["bad token Bearer secret-token", "bad token secret-token"])(
"a server error is reported without echoing the credential (%s)",
async (errorMessage) => {
@@ -117,7 +188,7 @@ describe("listing an MCP server's tools", () => {
}
);
- test("a token echoed in a description is redacted and a repeated name is listed once", async () => {
+ test("a description is kept as the server wrote it and a repeated name is listed once", async () => {
const { http } = streamableServer((message) =>
json(200, {
jsonrpc: "2.0",
@@ -137,7 +208,7 @@ describe("listing an MCP server's tools", () => {
secrets: SECRETS,
http
});
- expect(tools).toEqual([{ name: "read_file", description: "Uses [redacted]" }]);
+ expect(tools).toEqual([{ name: "read_file", description: "Uses secret-token" }]);
});
test("a server ping is answered, and its id, the pending one reused, isn't taken for the answer", async () => {
@@ -313,6 +384,53 @@ describe("listing an MCP server's tools", () => {
expect(posts[0].url).toBe("https://mcp.example.com/messages");
});
+ test("legacy SSE reads a long line sent in small pieces, with a CRLF split between them", async () => {
+ const stream = new PassThrough();
+ const description = "x".repeat(5000);
+ const http: TMcpHttpClient = {
+ request: async (request) => {
+ if (request.method === AgentVaultHttpMethod.Get) {
+ stream.write("event: endpoint\r");
+ stream.write("\ndata: /messages\r\n\r\n");
+ return { status: 200, contentType: "text/event-stream", sessionId: null, body: stream };
+ }
+ const message = JSON.parse(request.body!) as TMessage;
+ if (message.id !== undefined) {
+ const result =
+ message.method === "initialize"
+ ? { protocolVersion: "2024-11-05" }
+ : { tools: [{ name: "search", description }] };
+ const text = `event: message\ndata: ${JSON.stringify({ jsonrpc: "2.0", id: message.id, result })}\n\n`;
+ for (let i = 0; i < text.length; i += 7) stream.write(text.slice(i, i + 7));
+ }
+ 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: description.slice(0, 1000) }]);
+ });
+
+ test("legacy SSE gives up early on a stream that never announces an endpoint", async () => {
+ const { http } = sseServer("", ": just a comment\n\n");
+ await expect(
+ listMcpServerTools({
+ serverUrl: "https://mcp.example.com/sse",
+ transport: AgentVaultMcpTransport.Sse,
+ headers: AUTH,
+ secrets: SECRETS,
+ http,
+ sseEndpointTimeoutMs: 20
+ })
+ ).rejects.toThrow("If the server uses Streamable HTTP, choose that transport.");
+ });
+
test("legacy SSE never sends the credential to an endpoint on another host", async () => {
const { http, posts } = sseServer("https://attacker.example/messages");
await expect(
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.ts
index 94823e4e0c..9068cc0a14 100644
--- 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.ts
@@ -5,7 +5,7 @@ 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 { describeServer, privateNetworkHint } 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";
@@ -19,12 +19,23 @@ const MAX_MESSAGE_BYTES = 4 * 1024 * 1024;
const MAX_STREAM_BYTES = 16 * 1024 * 1024;
const MAX_DESCRIPTION_LENGTH = 1000;
const MAX_PING_REPLIES = 20;
+// An SSE server announces its message endpoint as soon as the stream opens, so a stream still silent after this is
+// most likely a Streamable HTTP server.
+const SSE_ENDPOINT_TIMEOUT_MS = 5000;
+const MAX_ERROR_BODY_BYTES = 4096;
+const MAX_ERROR_DETAIL_LENGTH = 300;
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 };
+type TMcpHttpResponse = {
+ status: number;
+ contentType: string;
+ sessionId: string | null;
+ location?: string | null;
+ body: Readable;
+};
// Narrow on purpose, so the client is tested against stubbed servers without a network.
export type TMcpHttpClient = {
@@ -55,17 +66,25 @@ const agentVaultMcpHttpClient: TMcpHttpClient = {
status: response.status,
contentType: headerValue(response.headers["content-type"]).toLowerCase(),
sessionId: headerValue(response.headers["mcp-session-id"]) || null,
+ location: headerValue(response.headers.location) || null,
body: response.data
};
}
};
-class McpListError extends BadRequestError {}
+export class McpListError extends BadRequestError {
+ // The server refused the credential, so a caller holding a refreshable token can refresh it and try once more.
+ isCredentialRejected = false;
+}
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;
+// A server request can reuse a client request's id (ids are unique per sender), so only a response answers one. Some
+// servers echo a numeric id back as a string, which both MCP SDKs accept.
+const isResponseTo = (id: number) => (message: TJsonRpcMessage) =>
+ (typeof message.id === "number" || typeof message.id === "string") &&
+ Number(message.id) === id &&
+ message.method === undefined;
const toMessages = (parsed: unknown): TJsonRpcMessage[] =>
(Array.isArray(parsed) ? parsed : [parsed]).filter(
@@ -87,13 +106,15 @@ const readText = async (body: Readable, tooLarge: () => McpListError) => {
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.
+// One event per yield, in order. An event's data lines are joined with newlines, as the SSE spec says. Only the newly
+// decoded text is scanned for line ends, so a server sending one huge line slowly costs linear time, not quadratic.
async function* readSseEvents(body: Readable, tooLarge: () => McpListError) {
const decoder = new StringDecoder("utf8");
- let buffer = "";
let isStart = true;
let skipLeadingLf = false;
let total = 0;
+ let partial: string[] = [];
+ let partialSize = 0;
let event = "";
let data: string[] = [];
let dataSize = 0;
@@ -102,21 +123,39 @@ async function* readSseEvents(body: Readable, tooLarge: () => McpListError) {
for await (const chunk of body) {
total += (chunk as Buffer).length;
if (total > MAX_STREAM_BYTES) throw tooLarge();
- buffer += decoder.write(chunk as Buffer);
+ let text = 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);
+ if (isStart && text) {
+ if (text.startsWith("\uFEFF")) text = text.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);
+ if (skipLeadingLf && text) {
+ if (text.startsWith("\n")) text = text.slice(1);
skipLeadingLf = false;
}
- if (buffer.endsWith("\r")) skipLeadingLf = true;
- const lines = buffer.split(/\r\n|\r|\n/);
- buffer = lines.pop()!;
+
+ const lines: string[] = [];
+ let lineStart = 0;
+ for (let i = 0; i < text.length; i += 1) {
+ const code = text.charCodeAt(i);
+ if (code === 10 || code === 13) {
+ partial.push(text.slice(lineStart, i));
+ lines.push(partial.join(""));
+ partial = [];
+ partialSize = 0;
+ if (code === 13) {
+ if (i + 1 === text.length) skipLeadingLf = true;
+ else if (text.charCodeAt(i + 1) === 10) i += 1;
+ }
+ lineStart = i + 1;
+ }
+ }
+ if (lineStart < text.length) {
+ partial.push(text.slice(lineStart));
+ partialSize += text.length - lineStart;
+ }
// eslint-disable-next-line no-restricted-syntax
for (const line of lines) {
@@ -138,17 +177,53 @@ async function* readSseEvents(body: Readable, tooLarge: () => McpListError) {
}
}
}
- if (buffer.length > MAX_MESSAGE_BYTES) throw tooLarge();
+ if (partialSize > MAX_MESSAGE_BYTES) throw tooLarge();
}
}
+// What a refusing server said, for the error the admin sees: a JSON-RPC or JSON error message, or a plain-text body.
+// HTML error pages say nothing useful and are left out.
+const readErrorDetail = async (response: TMcpHttpResponse, sensitiveValues: string[]) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ try {
+ // eslint-disable-next-line no-restricted-syntax
+ for await (const chunk of response.body) {
+ const bytes = Buffer.from(chunk as Buffer);
+ chunks.push(bytes);
+ size += bytes.length;
+ if (size >= MAX_ERROR_BODY_BYTES) break;
+ }
+ } catch {
+ return "";
+ } finally {
+ response.body.destroy();
+ }
+ const text = Buffer.concat(chunks).subarray(0, MAX_ERROR_BODY_BYTES).toString("utf-8").trim();
+ let detail: unknown = null;
+ if (response.contentType.startsWith("application/json")) {
+ try {
+ const parsed = JSON.parse(text) as { error?: unknown; message?: unknown };
+ const { error } = parsed;
+ if (typeof error === "object" && error !== null) detail = (error as { message?: unknown }).message;
+ else detail = typeof error === "string" ? error : parsed.message;
+ } catch {
+ detail = null;
+ }
+ } else if (response.contentType.startsWith("text/plain")) {
+ detail = text;
+ }
+ return normalizeProviderText(detail, MAX_ERROR_DETAIL_LENGTH, sensitiveValues).replace(/[.\s]+$/, "");
+};
+
export const listMcpServerTools = async ({
serverUrl,
transport,
headers: authHeaders,
secrets,
http = agentVaultMcpHttpClient,
- budgetMs = MCP_TOOL_LIST_BUDGET_MS
+ budgetMs = MCP_TOOL_LIST_BUDGET_MS,
+ sseEndpointTimeoutMs = SSE_ENDPOINT_TIMEOUT_MS
}: {
serverUrl: string;
transport: AgentVaultMcpTransport;
@@ -158,9 +233,11 @@ export const listMcpServerTools = async ({
secrets: string[];
http?: TMcpHttpClient;
budgetMs?: number;
+ sseEndpointTimeoutMs?: number;
}): Promise<TMcpTool[]> => {
const server = describeServer(serverUrl);
const transportLabel = transport === AgentVaultMcpTransport.Sse ? "SSE" : "Streamable HTTP";
+ const otherTransportLabel = transport === AgentVaultMcpTransport.Sse ? "Streamable HTTP" : "SSE";
const notMcp = (detail = "") =>
new McpListError({
message: `'${server}' didn't answer like an MCP server over ${transportLabel}.${detail ? ` ${detail}` : ""} Check the server URL and transport.`
@@ -171,20 +248,48 @@ export const listMcpServerTools = async ({
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) {
+ const checkStatus = async (response: TMcpHttpResponse, requestUrl: string) => {
+ const { status } = response;
+ if (status >= 200 && status < 300) return;
+ if (status >= 300 && status < 400) {
+ response.body.destroy();
+ let target: URL | null = null;
+ try {
+ target = response.location ? new URL(response.location, requestUrl) : null;
+ } catch {
+ target = null;
+ }
+ // Only the origin and path: a redirect's query string can carry anything.
throw new McpListError({
- message: `'${server}' rejected the credential (HTTP ${response.status}). Check the token or reauthorize the service, then load the tools again.`
+ message: target
+ ? `'${server}' redirected the request to '${target.origin}${target.pathname}'. Use that address as the server URL, then load the tools again.`
+ : `'${server}' redirected the request (HTTP ${status}). Check the server URL.`
});
}
- if (response.status === 429 || response.status >= 500) {
+ const detail = await readErrorDetail(response, sensitiveValues);
+ const said = detail ? `: ${detail}.` : ".";
+ if (status === 401 || status === 403) {
+ throw Object.assign(
+ new McpListError({
+ message: `'${server}' rejected the credential (HTTP ${status})${said} Check the token or reauthorize the service, then load the tools again.`
+ }),
+ { isCredentialRejected: true }
+ );
+ }
+ if (status === 429 || status >= 500) {
throw new McpListError({
- message: `'${server}' couldn't answer right now (HTTP ${response.status}). Try again in a few minutes.`
+ message: `'${server}' couldn't answer right now (HTTP ${status})${said} Try again in a few minutes.`
});
}
- throw notMcp(`It answered with HTTP ${response.status}.`);
+ if (detail) {
+ throw new McpListError({ message: `'${server}' refused the request (HTTP ${status}): ${detail}.` });
+ }
+ if (status === 404 || status === 405) {
+ throw notMcp(
+ `It answered with HTTP ${status}. If the server uses ${otherTransportLabel}, choose that transport.`
+ );
+ }
+ throw notMcp(`It answered with HTTP ${status}.`);
};
const send = async (
@@ -265,7 +370,7 @@ export const listMcpServerTools = async ({
seen.add(name);
tools.push({
name,
- description: normalizeProviderText(description, MAX_DESCRIPTION_LENGTH, sensitiveValues) || null
+ description: normalizeProviderText(description, MAX_DESCRIPTION_LENGTH) || null
});
});
if (tools.length > MCP_TOOL_LIST_MAX_TOOLS) {
@@ -301,7 +406,7 @@ export const listMcpServerTools = async ({
method,
params
});
- checkStatus(response);
+ await checkStatus(response, serverUrl);
if (method === "initialize") sessionId = response.sessionId;
if (response.contentType.startsWith("application/json")) {
@@ -341,7 +446,7 @@ export const listMcpServerTools = async ({
jsonrpc: "2.0",
method: "notifications/initialized"
});
- checkStatus(notified);
+ await checkStatus(notified, serverUrl);
notified.body.destroy();
return await collectTools(request);
@@ -364,7 +469,7 @@ export const listMcpServerTools = async ({
const listOverSse = async () => {
const stream = await send(serverUrl, AgentVaultHttpMethod.Get, { Accept: "text/event-stream" });
- checkStatus(stream);
+ await checkStatus(stream, serverUrl);
if (!stream.contentType.startsWith("text/event-stream")) {
stream.body.destroy();
throw notMcp();
@@ -377,11 +482,32 @@ export const listMcpServerTools = async ({
return value;
};
- let endpointEvent = await next();
- while (endpointEvent.event !== "endpoint") {
- // eslint-disable-next-line no-await-in-loop
- endpointEvent = await next();
- }
+ const awaitEndpoint = async () => {
+ let found = await next();
+ while (found.event !== "endpoint") {
+ // eslint-disable-next-line no-await-in-loop
+ found = await next();
+ }
+ return found;
+ };
+ const endpointWait = awaitEndpoint();
+ // Settles after the race is lost too, once the stream is torn down.
+ endpointWait.catch(() => {});
+ let endpointTimer: NodeJS.Timeout | undefined;
+ const endpointEvent = await Promise.race([
+ endpointWait,
+ new Promise<never>((_, reject) => {
+ endpointTimer = setTimeout(
+ () =>
+ reject(
+ notMcp(
+ `It didn't announce where to send messages, which an SSE server does first. If the server uses ${otherTransportLabel}, choose that transport.`
+ )
+ ),
+ sseEndpointTimeoutMs
+ );
+ })
+ ]).finally(() => clearTimeout(endpointTimer));
let endpoint: URL;
try {
endpoint = new URL(endpointEvent.data.trim(), serverUrl);
@@ -403,7 +529,7 @@ export const listMcpServerTools = async ({
{ Accept: "application/json, text/event-stream" },
message
);
- checkStatus(response);
+ await checkStatus(response, endpoint.toString());
response.body.destroy();
};
@@ -460,7 +586,7 @@ export const listMcpServerTools = async ({
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.`
+ message: `Infisical can't reach '${server}' because it's on a private network.${privateNetworkHint()}`
});
}
if (timedOut) {
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts
index 15afd3503c..d2a78910cb 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.test.ts
@@ -17,6 +17,8 @@ import {
import { TOauthHttpClient } from "./agent-vault-oauth-http-fns";
import { AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";
+vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isCloud: false }) }));
+
vi.mock("@app/lib/logger", async () => ({
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
sanitizeUrlForLog: (
@@ -520,7 +522,7 @@ describe("discovering an MCP server's authorization server", () => {
}
};
await expect(discoverOauthServer(refused, "https://mcp.internal.example.com/mcp")).rejects.toThrow(
- "Infisical can't reach 'mcp.internal.example.com' because it's on a private network. Use a bearer token for this service instead."
+ "Infisical can't reach 'mcp.internal.example.com' because it's on a private network. Use a bearer token for this service instead. If you're self-hosting Infisical, set the 'ALLOW_INTERNAL_IP_CONNECTIONS' environment variable to 'true' on your instance to allow it."
);
});
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts
index c15e11572f..7c937dfadb 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-discovery-fns.ts
@@ -1,5 +1,6 @@
import RE2 from "re2";
+import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors";
import { logger, sanitizeUrlForLog } from "@app/lib/logger";
import { PRIVATE_ADDRESS_REFUSED_MESSAGE } from "@app/lib/validator";
@@ -7,6 +8,12 @@ import { PRIVATE_ADDRESS_REFUSED_MESSAGE } from "@app/lib/validator";
import { TOauthHttpClient, TOauthHttpResponse } from "./agent-vault-oauth-http-fns";
import { AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";
+// Infisical Cloud never reaches private networks, so only a self-hosted instance is told how to allow them.
+export const privateNetworkHint = () =>
+ getConfig().isCloud
+ ? ""
+ : " If you're self-hosting Infisical, set the 'ALLOW_INTERNAL_IP_CONNECTIONS' environment variable to 'true' on your instance to allow it.";
+
export const OFFLINE_ACCESS_SCOPE = "offline_access";
// The spec sets no limit. Slack, the largest real server found, lists 30; this only stops a buggy or hostile
// server from making every authorization store and send an enormous scope list.
@@ -279,7 +286,7 @@ const discover = async (http: TOauthHttpClient, serverUrl: string): Promise<TOau
if (!answered) {
throw new BadRequestError({
message: isPrivateAddress
- ? `Infisical can't reach '${describeServer(serverUrl)}' because it's on a private network. Use a bearer token for this service instead.`
+ ? `Infisical can't reach '${describeServer(serverUrl)}' because it's on a private network. Use a bearer token for this service instead.${privateNetworkHint()}`
: `Couldn't reach '${describeServer(serverUrl)}'. Check the server URL and that the server is online.`
});
}
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts
index a70ee78190..e45fcd7b2c 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.test.ts
@@ -31,6 +31,8 @@ import {
} from "./agent-vault-oauth-token-fns";
import { AgentVaultOauthClientAuthMethod, AgentVaultOauthCompatibility } from "./agent-vault-oauth-types";
+vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isCloud: false }) }));
+
vi.mock("@app/lib/logger", async () => ({
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
sanitizeUrlForLog: (
@@ -449,7 +451,7 @@ describe("token requests", () => {
};
const result = await requestToken({ http, ...tokenArgs });
expect(!result.ok && result.message).toBe(
- "Infisical can't reach the login server 'auth.example.com' because it's on a private network. Use a bearer token for this service instead."
+ "Infisical can't reach the login server 'auth.example.com' because it's on a private network. Use a bearer token for this service instead. If you're self-hosting Infisical, set the 'ALLOW_INTERNAL_IP_CONNECTIONS' environment variable to 'true' on your instance to allow it."
);
});
diff --git a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts
index 7f59ca8d93..262dcd689b 100644
--- a/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts
+++ b/backend/src/ee/services/agent-vault-oauth/agent-vault-oauth-token-fns.ts
@@ -14,6 +14,7 @@ import {
describeServer,
MAX_OAUTH_SCOPES,
OFFLINE_ACCESS_SCOPE,
+ privateNetworkHint,
splitScopes,
stripTrailingSlash
} from "./agent-vault-oauth-discovery-fns";
@@ -352,7 +353,7 @@ export const requestToken = async ({
ok: false,
errorCode: null,
message: isPrivateAddress
- ? `Infisical can't reach the login server '${host}' because it's on a private network. Use a bearer token for this service instead.`
+ ? `Infisical can't reach the login server '${host}' because it's on a private network. Use a bearer token for this service instead.${privateNetworkHint()}`
: `Couldn't reach the login server '${host}'.`,
resourceDropped: !withResource
};
diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.md
index aea147e739..064ebfbaa1 100644
--- a/backend/src/ee/services/agent-vault/AGENTS.md
+++ b/backend/src/ee/services/agent-vault/AGENTS.md
@@ -172,24 +172,25 @@ the matching at runtime and reimplements the same rules, so a change here needs
## 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.
+empty array is never stored. Names are exact and case-sensitive, and the proxy compares them byte for byte.
+`agent-vault-tool-name-schemas.ts` (mirrored in the frontend's `serviceSchema.ts`) holds the MCP spec's SHOULD as a
+must: 1 to 128 of `A-Z a-z 0-9 _ - .`, which keeps out lone surrogates and U+FFFD (node-pg rewrites the first, Go
+folds both). The Tools step drops server tools outside it, since they could never be allowed. The CLI's
+`mcpNamePattern` is wider (it also takes `:` and `/`) and 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.
+ other body (a form-encoded OAuth token request) is forwarded. It fails closed: a compressed body, a charset other
+ than UTF-8, `Mcp-Method`/`Mcp-Name` headers that differ from the 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; a legacy SSE client gets 202 and the error on the event stream whose
+ `endpoint` event named the POST's URL, as the server would answer, and the same body with a 403 only when the proxy
+ hasn't seen that stream.
- **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
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.ts
index 05320b928e..90f95c9335 100644
--- 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.ts
@@ -3,22 +3,18 @@ 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) => {
+ it.each([["read_file"], ["github.create_issue"], ["Tool-v2.beta"], ["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"],
+ [" read_file", "can only contain"],
+ ["read file", "can only contain"],
+ ["ns:tool/v2", "can only contain"],
+ ["read\u0000file", "can only contain"],
+ ["read\ud800file", "can only contain"],
+ ["read\ufffdfile", "can only contain"],
["a".repeat(129), "longer than 128"]
])("refuses %j", (name, message) => {
const result = agentVaultAllowedToolsSchema.safeParse([name]);
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.ts
index e42af02ec9..3f2aa4d309 100644
--- 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.ts
@@ -6,17 +6,16 @@ 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]/);
+// The MCP spec says a tool name SHOULD be 1-128 of these characters; held as a must so a name can't carry characters
+// that Postgres drivers rewrite or that the Go backend folds together. The proxy compares names exactly.
+const TOOL_NAME_RE = new RE2(/^[A-Za-z0-9_.-]+$/);
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.";
+ if (!TOOL_NAME_RE.test(name))
+ return `"${name}" can only contain letters, numbers, underscores (_), hyphens (-), and dots (.).`;
return null;
};
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index df6808f03f..679339a887 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4568,7 +4568,7 @@ export const AGENT_VAULT = {
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.",
+ "The MCP tools agents can call through this service, by exact, case-sensitive name. Each name is 1 to 128 letters, numbers, underscores (_), hyphens (-), or dots (.). `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:
diff --git a/docs/documentation/platform/agent-vault/mcp-servers.mdx b/docs/documentation/platform/agent-vault/mcp-servers.mdx
index 84c3833d68..c5b93c37d9 100644
--- a/docs/documentation/platform/agent-vault/mcp-servers.mdx
+++ b/docs/documentation/platform/agent-vault/mcp-servers.mdx
@@ -99,19 +99,19 @@ By default, agents can call every tool the MCP server offers. To keep agents awa
<Steps>
<Step>
- On the **Tools** step, select **Selected tools**.
+ On the **Tools** step, turn off **All Tools**.
</Step>
<Step>
- Infisical loads the server's list of tools with the service's credential. Select the tools agents can call.
+ Infisical loads the server's list of tools with the service's credential. In **Allowed Tools**, select the tools that 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.
+ To allow a tool that the list doesn't include, type the tool's exact name in **Allowed Tools**, then select the option to add it. A tool name can contain only letters, numbers, underscores, hyphens, and dots, so the list leaves out any server tool with other characters in its name.
</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**.
+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 turn on **All Tools**.
## Connect your agent
@@ -177,7 +177,6 @@ The proxy picks up a changed list within its [poll interval](/documentation/plat
- **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 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
@@ -197,7 +196,12 @@ The proxy picks up a changed list within its [poll interval](/documentation/plat
- `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.
+ If Infisical can't get the server's list of tools, the **Tools** step shows the reason, such as a credential that the server rejected. You can still add tools by typing their names in **Allowed Tools**.
+
+ Infisical can't load the list in these cases:
+
+ - The MCP server is on a private network (if you self-host Infisical on that network, set [`ALLOW_INTERNAL_IP_CONNECTIONS`](/self-hosting/configuration/envars#param-allow-internal-ip-connections) to `true`)
+ - Each member sets the service's token, so Infisical has no token to load the list with
</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.mdx
index 26b99aa6c5..ebd4626ea0 100644
--- a/docs/documentation/platform/agent-vault/proxies.mdx
+++ b/docs/documentation/platform/agent-vault/proxies.mdx
@@ -189,8 +189,8 @@ The proxy also returns a 403 for:
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 call to a tool the service doesn't allow. The agent gets an MCP error that names the tool
+- A request the proxy can't read to check which tools it calls, such as a compressed body, a body in a character set other than UTF-8, or JSON that isn't a valid MCP message or doesn't match its `Mcp-Method` and `Mcp-Name` headers. 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
### Exceptions
diff --git a/frontend/src/components/agent-vault/service-sheet/McpToolsFields.tsx b/frontend/src/components/agent-vault/service-sheet/McpToolsFields.tsx
index e5ad85f8f8..6db23aab27 100644
--- a/frontend/src/components/agent-vault/service-sheet/McpToolsFields.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/McpToolsFields.tsx
@@ -1,6 +1,6 @@
import { useEffect, useId, useMemo, useState } from "react";
import { Controller, useFormContext, useWatch } from "react-hook-form";
-import { CircleXIcon, PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
+import { CircleXIcon, RefreshCwIcon, TriangleAlertIcon } from "lucide-react";
import {
Alert,
@@ -8,32 +8,14 @@ import {
AlertTitle,
Badge,
Button,
- Checkbox,
- Empty,
- EmptyDescription,
- EmptyHeader,
- EmptyTitle,
+ Combobox,
Field,
FieldContent,
FieldDescription,
FieldError,
FieldLabel,
FieldTitle,
- InputGroup,
- InputGroupAddon,
- InputGroupInput,
- Pagination,
- RadioGroup,
- RadioGroupItem,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- Tooltip,
- TooltipContent,
- TooltipTrigger
+ Toggle
} from "@app/components/v3";
import { useListAgentVaultMcpTools } from "@app/hooks/api/agentVault";
import { TAgentVaultMcpTool } from "@app/hooks/api/agentVault/types";
@@ -48,116 +30,76 @@ import { serverMessage } from "./useOAuthAuthorize";
*/
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."
- }
-];
+type TToolOption = { name: string; description: string | null; isUnlisted: boolean };
-const PER_PAGE = 10;
-
-type TToolRow = { name: string; description: string | null; isUnlisted: boolean };
+const formatAddLabel = (inputValue: string) => (
+ <>
+ Add <span className="font-mono">{inputValue}</span>
+ </>
+);
type Props = {
accessBundleId: string;
serviceId?: string;
loaded: TLoadedMcpTools | null;
onLoaded: (loaded: TLoadedMcpTools) => void;
+ // The OAuth sign-in from the Credential step expired, so nothing can load until the admin authorizes again.
+ isAuthorizationExpired: boolean;
+ onGoToCredential: () => void;
};
-export const McpToolsFields = ({ accessBundleId, serviceId, loaded, onLoaded }: Props) => {
+export const McpToolsFields = ({
+ accessBundleId,
+ serviceId,
+ loaded,
+ onLoaded,
+ isAuthorizationExpired,
+ onGoToCredential
+}: 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;
+ // An expired sign-in changes the request, but the list it loaded is still the server's, so it stays on screen.
+ const serverTools =
+ loaded?.source === source || (isAuthorizationExpired && loaded) ? 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 options = useMemo<TToolOption[]>(() => {
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])]
+ const unlisted = [...new Set([...savedNames, ...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);
+ return [...unlisted, ...listed.map((tool) => ({ ...tool, isUnlisted: false }))];
+ }, [serverTools, allowedTools, formState.defaultValues]);
- 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 optionByName = useMemo(
+ () => new Map(options.map((option) => [option.name, option])),
+ [options]
+ );
+ const selectedOptions = allowedTools.map(
+ (name) => optionByName.get(name) ?? { name, description: null, isUnlisted: false }
+ );
+ const selectedNames = new Set(allowedTools);
+ const isAtLimit = allowedTools.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());
@@ -176,35 +118,16 @@ export const McpToolsFields = ({ accessBundleId, serviceId, loaded, onLoaded }:
};
useEffect(() => {
- if (toolScope !== McpToolScope.Selected || serverTools || autoLoadedSource === source) return;
+ if (
+ toolScope !== McpToolScope.Selected ||
+ serverTools ||
+ isAuthorizationExpired ||
+ 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.";
- }
+ }, [toolScope, serverTools, isAuthorizationExpired, autoLoadedSource, source]);
return (
<div className="flex flex-col gap-5">
@@ -212,26 +135,22 @@ export const McpToolsFields = ({ accessBundleId, serviceId, loaded, onLoaded }:
control={control}
name="toolScope"
render={({ field }) => (
- <Field>
- <FieldLabel>Allowed Tools</FieldLabel>
+ <Field orientation="horizontal" className="rounded-md border border-border p-4">
<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>
+ <FieldTitle>All Tools</FieldTitle>
+ <FieldDescription>
+ Agents can call every tool the server offers, including ones it adds later. Turn
+ this off to pick the tools agents can call.
+ </FieldDescription>
</FieldContent>
+ <Toggle
+ id={`${baseId}-all-tools`}
+ variant="av"
+ checked={field.value === McpToolScope.All}
+ onCheckedChange={(checked) =>
+ field.onChange(checked ? McpToolScope.All : McpToolScope.Selected)
+ }
+ />
</Field>
)}
/>
@@ -242,42 +161,99 @@ export const McpToolsFields = ({ accessBundleId, serviceId, loaded, onLoaded }:
name="allowedTools"
render={({ fieldState }) => (
<Field>
- <FieldLabel htmlFor={`${baseId}-query`}>Tools</FieldLabel>
+ <FieldLabel htmlFor={`${baseId}-tools`}>Allowed 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();
+ <div className="flex items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <Combobox
+ id={`${baseId}-tools`}
+ multiple
+ modal
+ isError={Boolean(fieldState.error)}
+ isLoading={listTools.isPending}
+ options={options}
+ value={selectedOptions}
+ onValueChange={(next) => setAllowedTools(next.map((option) => option.name))}
+ getOptionValue={(option) => option.name}
+ getOptionLabel={(option) => option.name}
+ isOptionDisabled={(option) => isAtLimit && !selectedNames.has(option.name)}
+ includeMissingSelectedOptions
+ renderOption={(option) => (
+ <span className="flex min-w-0 flex-col">
+ <span className="flex items-center gap-2">
+ <span className="truncate font-mono">{option.name}</span>
+ {option.isUnlisted && <Badge variant="neutral">Custom</Badge>}
+ </span>
+ {option.description && (
+ <span
+ className="truncate text-xs text-muted"
+ title={option.description}
+ >
+ {option.description}
+ </span>
+ )}
+ </span>
+ )}
+ placeholder="Select tools..."
+ searchPlaceholder="Search or add a tool..."
+ searchAriaLabel="Search tools"
+ clearAriaLabel="Clear all tools"
+ emptyMessage={(inputValue) =>
+ (inputValue && toolNameError(inputValue.trim())) ||
+ (serverTools
+ ? "No tools match your search."
+ : "Type a tool's name to add it.")
+ }
+ creation={{
+ isDisabled: isAtLimit,
+ isValid: (inputValue) => !toolNameError(inputValue),
+ // The proxy matches names exactly, so a name differing only in case from a listed tool
+ // is almost certainly a typo for it.
+ isDuplicate: (inputValue, option) =>
+ option.name.toLowerCase() === inputValue.toLowerCase(),
+ formatLabel: formatAddLabel,
+ onCreate: (inputValue) => setAllowedTools([...allowedTools, inputValue])
}}
- placeholder="Search or add a tool..."
- autoComplete="off"
- spellCheck={false}
/>
- </InputGroup>
+ </div>
<Button
type="button"
variant="outline"
onClick={loadTools}
isPending={listTools.isPending}
+ isDisabled={isAuthorizationExpired}
>
<RefreshCwIcon />
{serverTools ? "Reload Tools" : "Load Tools"}
</Button>
</div>
- {loadError && (
+ <span className="text-xs text-muted">
+ {allowedTools.length} selected
+ {serverTools ? ` of ${serverTools.length} listed by the server` : ""}
+ </span>
+
+ {isAuthorizationExpired && (
+ <Alert variant="warning">
+ <TriangleAlertIcon />
+ <AlertTitle>The authorization expired</AlertTitle>
+ <AlertDescription>
+ Authorize again on the Credential step to reload the tools. Your selection is
+ kept.
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ className="mt-2"
+ onClick={onGoToCredential}
+ >
+ Go to Credential Step
+ </Button>
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {loadError && !isAuthorizationExpired && (
<Alert variant="danger">
<CircleXIcon />
<AlertTitle>Couldn&apos;t load the tools</AlertTitle>
@@ -287,127 +263,6 @@ export const McpToolsFields = ({ accessBundleId, serviceId, loaded, onLoaded }:
</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>
diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
index cc3d2ce0f5..df340a4a87 100644
--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx
@@ -720,11 +720,18 @@ export const ServiceSheet = ({
};
const current = steps[step];
- const [credentialType, serverUrl, oauthAuthorizationId, oauthAuthorizedUrl] = watch([
+ const [
+ credentialType,
+ serverUrl,
+ oauthAuthorizationId,
+ oauthAuthorizedUrl,
+ oauthAuthorizationRejection
+ ] = watch([
"credentialType",
"serverUrl",
"oauthAuthorizationId",
- "oauthAuthorizedUrl"
+ "oauthAuthorizedUrl",
+ "oauthAuthorizationRejection"
]);
useEffect(() => {
@@ -743,18 +750,19 @@ export const ServiceSheet = ({
return () => window.clearTimeout(timeout);
}, [oauthAuthorizationId, getValues, setValue, setError]);
- const isAwaitingAuthorization =
- current.step === ServiceStep.Credential &&
- isOAuthAuthorizationMissing(
- {
- serviceType: isMcp ? AgentVaultServiceType.Mcp : AgentVaultServiceType.Http,
- credentialType,
- serverUrl,
- oauthAuthorizationId,
- oauthAuthorizedUrl
- },
- service
- );
+ const isAuthorizationMissing = isOAuthAuthorizationMissing(
+ {
+ serviceType: isMcp ? AgentVaultServiceType.Mcp : AgentVaultServiceType.Http,
+ credentialType,
+ serverUrl,
+ oauthAuthorizationId,
+ oauthAuthorizedUrl
+ },
+ service
+ );
+ const isAwaitingAuthorization = current.step === ServiceStep.Credential && isAuthorizationMissing;
+ // Set once a sign-in expired or was refused; only authorizing again on the Credential step clears it.
+ const isAuthorizationRejected = isAuthorizationMissing && Boolean(oauthAuthorizationRejection);
const isTemplateStep = current.step === ServiceStep.Template;
const saveLabel = isUpdate ? "Save" : "Add Service";
@@ -819,6 +827,11 @@ export const ServiceSheet = ({
index={index}
title={meta.name}
description={stepDescription(meta)}
+ status={
+ meta.step === ServiceStep.Credential && isAuthorizationRejected
+ ? "error"
+ : undefined
+ }
/>
))}
</StepperList>
@@ -873,6 +886,8 @@ export const ServiceSheet = ({
serviceId={service?.id}
loaded={loadedTools}
onLoaded={setLoadedTools}
+ isAuthorizationExpired={isAuthorizationRejected}
+ onGoToCredential={() => setStep(stepKeys.indexOf(ServiceStep.Credential))}
/>
)}
{current.step === ServiceStep.Review && (
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
index 01940aa854..911f539d45 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.test.ts
@@ -341,32 +341,33 @@ describe("buildServiceSchema with allowed tools", () => {
).toBe(true);
});
- it("accepts any selected tool name, case-sensitive", () => {
+ it("accepts names in the MCP spec's characters, case-sensitive", () => {
expect(
toolIssues({
- allowedTools: [
- "read_file",
- "Read_File",
- "github:issues/create.v2-beta",
- "query+sum",
- "read file"
- ]
+ allowedTools: ["read_file", "Read_File", "issues.create-v2"]
})
).toEqual([]);
});
it("requires at least one selected tool", () => {
expect(toolIssues({ allowedTools: [] })).toEqual([
- ["allowedTools", "Select at least one tool, or allow all tools."]
+ ["allowedTools", "Select at least one tool, or turn on All Tools."]
]);
});
- it("refuses untrimmed names, control characters, names over 128 characters, and duplicates", () => {
+ it("refuses names outside the MCP spec's characters, names over 128 characters, and duplicates", () => {
expect(
toolIssues({
- allowedTools: [" read_file", "a".repeat(129), "read\u0000file", "ok", "ok"]
+ allowedTools: [" read_file", "a".repeat(129), "read\u0000file", "ns:tool", "ok", "ok"]
}).map(([path]) => path)
- ).toEqual(["allowedTools", "allowedTools", "allowedTools", "allowedTools"]);
+ ).toEqual(["allowedTools", "allowedTools", "allowedTools", "allowedTools", "allowedTools"]);
+ expect(toolIssues({ allowedTools: ["read file"] })).toEqual([
+ [
+ "allowedTools",
+ '"read file": A tool name can only contain letters, numbers, underscores (_), hyphens (-), and dots (.).'
+ ]
+ ]);
+ expect(toolIssues({ allowedTools: ["Tool-v2.beta_1"] })).toEqual([]);
expect(toolIssues({ allowedTools: ["ok", "ok"] })).toEqual([
["allowedTools", '"ok" is listed twice.']
]);
diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
index 5b7690a314..2e5493d035 100644
--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts
@@ -106,8 +106,8 @@ export enum McpToolScope {
Selected = "selected"
}
-// Mirrors agent-vault-tool-name-schemas.ts on the backend. The proxy compares names exactly, whatever characters
-// they hold.
+// Mirrors agent-vault-tool-name-schemas.ts on the backend: the MCP spec's recommended tool name characters, held as
+// a must. The proxy compares names exactly.
export const MAX_ALLOWED_TOOLS = 500;
const MAX_TOOL_NAME_LENGTH = 128;
@@ -117,10 +117,8 @@ export const toolNameError = (name: string): string | null => {
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.";
+ if (!/^[A-Za-z0-9_.-]+$/.test(name)) {
+ return "A tool name can only contain letters, numbers, underscores (_), hyphens (-), and dots (.).";
}
return null;
};
@@ -425,7 +423,7 @@ export const buildServiceSchema = (
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["allowedTools"],
- message: "Select at least one tool, or allow all tools."
+ message: "Select at least one tool, or turn on All Tools."
});
} else if (data.allowedTools.length > MAX_ALLOWED_TOOLS) {
ctx.addIssue({
diff --git a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
index bfc7e3bc1d..f50a78131a 100644
--- a/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
+++ b/frontend/src/components/agent-vault/service-sheet/stepMeta.ts
@@ -91,7 +91,7 @@ export const MCP_SERVICE_STEPS: StepMeta[] = [
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."
+ "Turning off All Tools asks the server for its list with the credential from the previous step; Reload Tools asks again. To allow a tool the server doesn't list, type its exact name in Allowed Tools."
},
REVIEW_STEP
];