mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-08-28 04:37:37 +00:00
🛂 fix: Enforce MCP Permissions for Agent Tools (#13174)
Some checks are pending
Docker Dev Branch Images Build / build (Dockerfile, lc-dev, node) (push) Waiting to run
Docker Dev Branch Images Build / build (Dockerfile.multi, lc-dev-api, api-build) (push) Waiting to run
GitNexus Index / index (push) Waiting to run
GitNexus Index / post-index (push) Blocked by required conditions
Some checks are pending
Docker Dev Branch Images Build / build (Dockerfile, lc-dev, node) (push) Waiting to run
Docker Dev Branch Images Build / build (Dockerfile.multi, lc-dev-api, api-build) (push) Waiting to run
GitNexus Index / index (push) Waiting to run
GitNexus Index / post-index (push) Blocked by required conditions
* fix: Enforce MCP Permissions for Agent Tools
* fix: Measure MCP Image Limit by Decoded Size
* fix: gate cached MCP tools and tighten remote image URL detection
Addresses Codex review findings on the MCP permissions PR:
- filterAuthorizedTools previously fast-accepted any tool present in the
global tool cache before reaching the MCP-use permission gate. App-level
MCP tools (keyed `name_mcp_server` by MCPServerInspector and merged into
the cache via mergeAppTools) therefore bypassed the canUseMCP check,
letting a user without MCP_SERVERS.USE persist/bind them. Route all
MCP-delimited tools through the permission + server-access gate
regardless of cache presence.
- assertImageDataWithinLimit / image formatter used startsWith("http")
to skip the size cap, which also matched base64 payloads that happen to
begin with those chars. Require http:// or https:// via a shared
isRemoteImageUrl helper so oversized inline base64 can no longer bypass
MCP_IMAGE_DATA_MAX_BYTES.
Adds regression tests for both paths.
* fix: address Codex round-2 findings on MCP permissions PR
- parsers.ts: parseAsString dropped the image payload for unrecognized
providers, returning only `Image result: <mimeType>`. Pre-PR these
items survived via JSON.stringify(item). Keep the size guard but fall
through to JSON.stringify so the data/URL is preserved.
- MCP.js: the runtime MCP-use check only read `configurable.user`, so
paths that propagate `user_id` only (e.g. the OpenAI-compatible API in
agents/openai/service.ts) rejected every MCP tool call for an
authenticated user. Add resolveMCPPermissionUser: use the safe user
directly when it already carries a role (no extra DB call), otherwise
fall back to loading the role by user_id. Update fail-closed tests to
the resolved behavior.
- v1.js: the update path only re-filtered newly added MCP tools, so a
user who lost MCP_SERVERS.USE kept existing MCP bindings on edit while
create/duplicate/revert stripped them. Strip all MCP tools on update
when the permission is revoked; keep the narrower new-tool gating (and
disconnect/registry preservation) when it is intact.
Updates and adds regression tests for all three paths.
* fix: populate safe user at producer instead of resolving in runtime MCP check
Corrects the Finding B approach from the previous commit. Rather than
loading the user by id inside the runtime MCP permission check, populate
`configurable.user` (and createRun's `user`) with the full safe user at
the producer, matching the in-repo agent controllers
(responses.js / openai.js) which already pass `createSafeUser(req.user)`.
- service.ts: derive `safeUser` via createSafeUser(req.user) and pass it
to both createRun and processStream's configurable, so the role-bearing
identity reaches the runtime `userCanUseMCPServers(configurable.user)`
check. Falls back to a bare id when the host app attached no user,
which correctly leaves MCP gated (fail closed).
- MCP.js: revert the resolveMCPPermissionUser DB-load fallback; the
runtime check again reads configurable.user directly and fails closed
when absent (defense in depth).
- MCP.spec.js: revert to the matching runtime test expectations.
* test: cover safe-user propagation in createAgentChatCompletion
Adds a focused spec for the OpenAI-compatible chat completion service
(the producer fixed for Codex Finding B). Injects mocked deps and asserts
that createRun and processStream's configurable.user carry the role from
req.user (with sensitive fields stripped by createSafeUser), and that an
unauthenticated request falls back to a bare { id: 'api-user' } so the
runtime MCP check fails closed.
* fix: address Codex round-3 findings + TS6133
- MCP.js (P1): the assistants required-action path invokes tool._call(
toolInput) with no LangChain config, so the runtime check saw no
configurable.user and rejected authorized users. createToolInstance now
captures the creation-time user (req.user via createMCPTool) and _call
falls back to it for both the permission check and userId. Still fails
closed when neither config nor captured user carries a role.
- v1.js (P2): the update-path isMCPTool used a bare mcp_delimiter substring
check, misclassifying action tools whose operationId contains "_mcp_"
(e.g. sync_mcp_state_action_...) as MCP and dropping them on a
permission-revoked edit. Delegate to the canonical isActionTool so only
real MCP tools are gated. Regression test added.
- service.ts: drop the now-unused IUser import (TS6133); derive reqUser's
type from createSafeUser's own parameter instead.
* fix: resolve TS7022 self-reference in service.spec mock res
The mock response object referenced `res` inside its own `status`/`json`
initializers without a type annotation, so tsc inferred `res` as `any`
(TS7022). Annotate the object and assign the self-referencing chainable
methods after declaration.
* fix: correct round-4 findings (isActionTool import, captured user, partial-update)
- v1.js: import isActionTool from librechat-data-provider (its real export;
@librechat/api does not export it, so the prior import was undefined and
threw TypeError). Exclude action tools from MCP classification in both the
main filterAuthorizedTools loop and the update path, so action tools whose
operationId contains _mcp_ (e.g. sync_mcp_state_action_...) are preserved
regardless of MCP permission.
- v1.js: evaluate the effective tool set (updateData.tools ?? existingAgent.tools)
so a tools-less PATCH by a user who lost MCP_SERVERS.USE still strips stale
MCP bindings, matching create/duplicate/revert.
- MCP.js: createToolInstance now receives the construction-time user and _call
falls back to it (permissionUser) when configurable.user is absent, fixing the
assistants required-action path that invokes _call without a config and
resolving the capturedUser no-undef/ReferenceError.
- Tests: action-tool preservation (authorized + denied), tools-less revocation
PATCH, updated revocation test to expect all MCP tools stripped.
Affected specs pass locally: MCP 49/49, filterAuthorizedTools 49/49.
* fix: guard isActionTool against non-string tools; correct actionDelimiter import
Two test regressions from the prior commit:
- The main filterAuthorizedTools loop called isActionTool(tool) directly,
but isActionTool does toolName.indexOf(...) and throws on null/undefined.
Compute isActionToolName = typeof tool === 'string' && isActionTool(tool)
once and reuse it, restoring graceful null/undefined handling.
- The action-tool test referenced Constants.actionDelimiter (undefined);
actionDelimiter is a standalone librechat-data-provider export. Import and
use it directly.
filterAuthorizedTools 36/36 and MCP 40/40 pass locally.
* fix: address MCP permission review follow-ups
* fix: preserve shared agent MCP tools
This commit is contained in:
parent
5bfef51ed2
commit
100871c3ec
15 changed files with 786 additions and 44 deletions
|
|
@ -1,12 +1,13 @@
|
|||
const mongoose = require('mongoose');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const { Constants } = require('librechat-data-provider');
|
||||
const { Constants, actionDelimiter } = require('librechat-data-provider');
|
||||
const { agentSchema } = require('@librechat/data-schemas');
|
||||
const { MongoMemoryServer } = require('mongodb-memory-server');
|
||||
|
||||
const d = Constants.mcp_delimiter;
|
||||
|
||||
const mockGetAllServerConfigs = jest.fn();
|
||||
const mockUserCanUseMCPServers = jest.fn();
|
||||
|
||||
jest.mock('~/server/services/Config', () => ({
|
||||
getCachedTools: jest.fn().mockResolvedValue({
|
||||
|
|
@ -24,6 +25,7 @@ jest.mock('~/config', () => ({
|
|||
|
||||
jest.mock('~/server/services/MCP', () => ({
|
||||
resolveConfigServers: jest.fn().mockResolvedValue({}),
|
||||
userCanUseMCPServers: (...args) => mockUserCanUseMCPServers(...args),
|
||||
}));
|
||||
|
||||
jest.mock('~/server/services/Files/strategies', () => ({
|
||||
|
|
@ -106,6 +108,7 @@ describe('MCP Tool Authorization', () => {
|
|||
authorizedServer: { type: 'sse', url: 'https://authorized.example.com' },
|
||||
anotherServer: { type: 'sse', url: 'https://another.example.com' },
|
||||
});
|
||||
mockUserCanUseMCPServers.mockResolvedValue(true);
|
||||
|
||||
mockReq = {
|
||||
user: {
|
||||
|
|
@ -127,11 +130,13 @@ describe('MCP Tool Authorization', () => {
|
|||
describe('filterAuthorizedTools', () => {
|
||||
const availableTools = { web_search: true, custom_tool: true };
|
||||
const userId = 'test-user-123';
|
||||
const testUser = { id: userId, role: 'USER' };
|
||||
|
||||
test('should keep authorized MCP tools and strip unauthorized ones', async () => {
|
||||
const result = await filterAuthorizedTools({
|
||||
tools: [`toolA${d}authorizedServer`, `toolB${d}forbiddenServer`, 'web_search'],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
});
|
||||
|
||||
|
|
@ -140,6 +145,39 @@ describe('MCP Tool Authorization', () => {
|
|||
expect(result).not.toContain(`toolB${d}forbiddenServer`);
|
||||
});
|
||||
|
||||
test('should strip MCP tools when user lacks MCP server use permission', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
|
||||
const result = await filterAuthorizedTools({
|
||||
tools: [
|
||||
`toolA${d}authorizedServer`,
|
||||
`${Constants.mcp_all}${d}authorizedServer`,
|
||||
'web_search',
|
||||
],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
});
|
||||
|
||||
expect(result).toEqual(['web_search']);
|
||||
expect(mockUserCanUseMCPServers).toHaveBeenCalledWith({ id: userId, role: 'USER' });
|
||||
expect(mockGetAllServerConfigs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('should strip MCP tools when user context is missing', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValueOnce(false);
|
||||
|
||||
const result = await filterAuthorizedTools({
|
||||
tools: [`toolA${d}authorizedServer`, 'web_search'],
|
||||
userId,
|
||||
availableTools,
|
||||
});
|
||||
|
||||
expect(result).toEqual(['web_search']);
|
||||
expect(mockUserCanUseMCPServers).toHaveBeenCalledWith(undefined);
|
||||
expect(mockGetAllServerConfigs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('should keep system tools without querying MCP registry', async () => {
|
||||
const result = await filterAuthorizedTools({
|
||||
tools: ['execute_code', 'file_search', 'web_search'],
|
||||
|
|
@ -170,6 +208,7 @@ describe('MCP Tool Authorization', () => {
|
|||
const result = await filterAuthorizedTools({
|
||||
tools: [`toolA${d}someServer`, 'web_search'],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
});
|
||||
|
||||
|
|
@ -188,6 +227,7 @@ describe('MCP Tool Authorization', () => {
|
|||
`steal${d}nonexistent`,
|
||||
],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
});
|
||||
|
||||
|
|
@ -224,6 +264,7 @@ describe('MCP Tool Authorization', () => {
|
|||
await filterAuthorizedTools({
|
||||
tools: [`tool${d}authorizedServer`],
|
||||
userId: 'specific-user-id',
|
||||
user: { id: 'specific-user-id', role: 'USER' },
|
||||
availableTools,
|
||||
});
|
||||
|
||||
|
|
@ -241,6 +282,7 @@ describe('MCP Tool Authorization', () => {
|
|||
const result = await filterAuthorizedTools({
|
||||
tools: [`tool${d}config-override-server`, `tool${d}unauthorizedServer`],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
configServers,
|
||||
});
|
||||
|
|
@ -254,6 +296,7 @@ describe('MCP Tool Authorization', () => {
|
|||
await filterAuthorizedTools({
|
||||
tools: [`tool1${d}authorizedServer`, `tool2${d}anotherServer`, `tool3${d}unknownServer`],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
});
|
||||
|
||||
|
|
@ -270,6 +313,7 @@ describe('MCP Tool Authorization', () => {
|
|||
const result = await filterAuthorizedTools({
|
||||
tools: [...existingTools, `newTool${d}unknownServer`, 'web_search'],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
existingTools,
|
||||
});
|
||||
|
|
@ -288,6 +332,7 @@ describe('MCP Tool Authorization', () => {
|
|||
const result = await filterAuthorizedTools({
|
||||
tools: [`toolA${d}serverA`, 'web_search'],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
});
|
||||
|
||||
|
|
@ -303,6 +348,7 @@ describe('MCP Tool Authorization', () => {
|
|||
const result = await filterAuthorizedTools({
|
||||
tools: [malformedTool, `legit${d}serverA`, 'web_search'],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
existingTools: [malformedTool, `legit${d}serverA`],
|
||||
});
|
||||
|
|
@ -312,6 +358,43 @@ describe('MCP Tool Authorization', () => {
|
|||
expect(result).not.toContain(malformedTool);
|
||||
});
|
||||
|
||||
test('should gate app-level MCP tools present in the global tool cache', async () => {
|
||||
const appMcpTool = `appTool${d}authorizedServer`;
|
||||
const forbiddenAppMcpTool = `appTool${d}forbiddenServer`;
|
||||
const cacheWithMCPTools = {
|
||||
...availableTools,
|
||||
[appMcpTool]: true,
|
||||
[forbiddenAppMcpTool]: true,
|
||||
};
|
||||
|
||||
const result = await filterAuthorizedTools({
|
||||
tools: [appMcpTool, forbiddenAppMcpTool, 'web_search'],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools: cacheWithMCPTools,
|
||||
});
|
||||
|
||||
expect(result).toContain(appMcpTool);
|
||||
expect(result).toContain('web_search');
|
||||
expect(result).not.toContain(forbiddenAppMcpTool);
|
||||
});
|
||||
|
||||
test('should strip app-level MCP tools from the cache when user lacks MCP server use permission', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
const appMcpTool = `appTool${d}authorizedServer`;
|
||||
const cacheWithMCPTools = { ...availableTools, [appMcpTool]: true };
|
||||
|
||||
const result = await filterAuthorizedTools({
|
||||
tools: [appMcpTool, 'web_search'],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools: cacheWithMCPTools,
|
||||
});
|
||||
|
||||
expect(result).toEqual(['web_search']);
|
||||
expect(mockGetAllServerConfigs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('should reject malformed MCP tool keys with multiple delimiters', async () => {
|
||||
const result = await filterAuthorizedTools({
|
||||
tools: [
|
||||
|
|
@ -321,6 +404,7 @@ describe('MCP Tool Authorization', () => {
|
|||
'web_search',
|
||||
],
|
||||
userId,
|
||||
user: testUser,
|
||||
availableTools,
|
||||
});
|
||||
|
||||
|
|
@ -348,6 +432,27 @@ describe('MCP Tool Authorization', () => {
|
|||
expect(agent.tools).not.toContain(`attack${d}forbiddenServer`);
|
||||
});
|
||||
|
||||
test('should strip all MCP tools on create when user lacks MCP server use permission', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
mockReq.body = {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
name: 'MCP Denied Test Agent',
|
||||
tools: [
|
||||
'web_search',
|
||||
`validTool${d}authorizedServer`,
|
||||
`${Constants.mcp_all}${d}authorizedServer`,
|
||||
],
|
||||
};
|
||||
|
||||
await createAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.status).toHaveBeenCalledWith(201);
|
||||
const agent = mockRes.json.mock.calls[0][0];
|
||||
expect(agent.tools).toEqual(['web_search']);
|
||||
expect(agent.mcpServerNames).toEqual([]);
|
||||
});
|
||||
|
||||
test('should not 500 when MCP registry is uninitialized', async () => {
|
||||
getMCPServersRegistry.mockImplementation(() => {
|
||||
throw new Error('MCPServersRegistry has not been initialized.');
|
||||
|
|
@ -446,6 +551,129 @@ describe('MCP Tool Authorization', () => {
|
|||
expect(updatedAgent.tools).not.toContain(`attack${d}forbiddenServer`);
|
||||
});
|
||||
|
||||
test('should strip all MCP tools, including retained ones, when user lacks MCP server use permission', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
mockReq.user.id = existingAgentAuthorId.toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
mockReq.body = {
|
||||
tools: ['web_search', `existingTool${d}authorizedServer`, `newTool${d}anotherServer`],
|
||||
};
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.json).toHaveBeenCalled();
|
||||
const updatedAgent = mockRes.json.mock.calls[0][0];
|
||||
// Permission revoked: update must not preserve stale MCP bindings, matching
|
||||
// the create/duplicate/revert paths.
|
||||
expect(updatedAgent.tools).toEqual(['web_search']);
|
||||
expect(mockGetAllServerConfigs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('should strip retained MCP tools on an unrelated owner edit after permission revocation', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
mockReq.user.id = existingAgentAuthorId.toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
mockReq.body = {
|
||||
name: 'Renamed After Revocation',
|
||||
};
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.json).toHaveBeenCalled();
|
||||
const updatedAgent = mockRes.json.mock.calls[0][0];
|
||||
expect(updatedAgent.tools).toEqual(['web_search']);
|
||||
expect(updatedAgent.name).toBe('Renamed After Revocation');
|
||||
});
|
||||
|
||||
test('should not strip shared agent MCP tools on unrelated editor changes after revocation', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
mockReq.user.id = new mongoose.Types.ObjectId().toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
mockReq.body = {
|
||||
name: 'Shared Rename After Revocation',
|
||||
};
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.json).toHaveBeenCalled();
|
||||
const updatedAgent = mockRes.json.mock.calls[0][0];
|
||||
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||
expect(updatedAgent.tools).toContain(`existingTool${d}authorizedServer`);
|
||||
expect(updatedAgent.name).toBe('Shared Rename After Revocation');
|
||||
expect(agentInDb.tools).toContain(`existingTool${d}authorizedServer`);
|
||||
expect(agentInDb.mcpServerNames).toEqual(['authorizedServer']);
|
||||
});
|
||||
|
||||
test('should not strip shared agent MCP tools on frontend-style full tools save after revocation', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
mockReq.user.id = new mongoose.Types.ObjectId().toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
mockReq.body = {
|
||||
name: 'Shared Full Save After Revocation',
|
||||
tools: ['web_search', `existingTool${d}authorizedServer`],
|
||||
};
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.json).toHaveBeenCalled();
|
||||
const updatedAgent = mockRes.json.mock.calls[0][0];
|
||||
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||
expect(updatedAgent.tools).toContain(`existingTool${d}authorizedServer`);
|
||||
expect(updatedAgent.name).toBe('Shared Full Save After Revocation');
|
||||
expect(agentInDb.tools).toContain(`existingTool${d}authorizedServer`);
|
||||
expect(agentInDb.mcpServerNames).toEqual(['authorizedServer']);
|
||||
expect(mockGetAllServerConfigs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('should reject new shared-agent MCP tools after revocation while retaining existing MCP tools', async () => {
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
mockReq.user.id = new mongoose.Types.ObjectId().toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
mockReq.body = {
|
||||
tools: ['web_search', `existingTool${d}authorizedServer`, `newTool${d}anotherServer`],
|
||||
};
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.json).toHaveBeenCalled();
|
||||
const updatedAgent = mockRes.json.mock.calls[0][0];
|
||||
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||
expect(updatedAgent.tools).toContain(`existingTool${d}authorizedServer`);
|
||||
expect(updatedAgent.tools).not.toContain(`newTool${d}anotherServer`);
|
||||
expect(agentInDb.tools).toContain(`existingTool${d}authorizedServer`);
|
||||
expect(agentInDb.tools).not.toContain(`newTool${d}anotherServer`);
|
||||
expect(agentInDb.mcpServerNames).toEqual(['authorizedServer']);
|
||||
expect(mockGetAllServerConfigs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('should not strip action tools whose operationId contains the MCP delimiter on revocation', async () => {
|
||||
// `sync_mcp_state_action_...` contains the `_mcp_` substring but is a
|
||||
// genuine OpenAPI action tool (isActionTool === true). Losing
|
||||
// MCP_SERVERS.USE must not drop it — action use is unrelated to MCP.
|
||||
const actionTool = `sync_mcp_state${actionDelimiter}api---example---com`;
|
||||
await Agent.updateOne(
|
||||
{ id: existingAgentId },
|
||||
{ $set: { tools: ['web_search', actionTool] } },
|
||||
);
|
||||
|
||||
mockUserCanUseMCPServers.mockResolvedValue(false);
|
||||
mockReq.user.id = existingAgentAuthorId.toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
mockReq.body = {
|
||||
name: 'Edited Without MCP Permission',
|
||||
tools: ['web_search', actionTool],
|
||||
};
|
||||
|
||||
await updateAgentHandler(mockReq, mockRes);
|
||||
|
||||
expect(mockRes.json).toHaveBeenCalled();
|
||||
const updatedAgent = mockRes.json.mock.calls[0][0];
|
||||
const agentInDb = await Agent.findOne({ id: existingAgentId });
|
||||
expect(updatedAgent.tools).toContain(actionTool);
|
||||
expect(updatedAgent.tools).toContain('web_search');
|
||||
expect(agentInDb.mcpServerNames).toEqual([]);
|
||||
});
|
||||
|
||||
test('should allow adding authorized MCP tools', async () => {
|
||||
mockReq.user.id = existingAgentAuthorId.toString();
|
||||
mockReq.params.id = existingAgentId;
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ const {
|
|||
AccessRoleIds,
|
||||
PrincipalType,
|
||||
EToolResources,
|
||||
isActionTool,
|
||||
PermissionBits,
|
||||
actionDelimiter,
|
||||
AgentCapabilities,
|
||||
|
|
@ -42,7 +43,7 @@ const { resizeAvatar } = require('~/server/services/Files/images/avatar');
|
|||
const { getFileStrategy } = require('~/server/utils/getFileStrategy');
|
||||
const { filterFile } = require('~/server/services/Files/process');
|
||||
const { getCachedTools } = require('~/server/services/Config');
|
||||
const { resolveConfigServers } = require('~/server/services/MCP');
|
||||
const { resolveConfigServers, userCanUseMCPServers } = require('~/server/services/MCP');
|
||||
const { getMCPServersRegistry } = require('~/config');
|
||||
const { getLogStores } = require('~/cache');
|
||||
const db = require('~/models');
|
||||
|
|
@ -190,6 +191,7 @@ const isSubagentsCapabilityEnabled = (req) => {
|
|||
* @param {string[]} params.tools - Raw tool strings from the request
|
||||
* @param {string} params.userId - Requesting user ID for MCP server access check
|
||||
* @param {string} [params.role] - Requesting user's role for ACL principal resolution
|
||||
* @param {object} [params.user] - Requesting user for MCP server use permission checks
|
||||
* @param {Record<string, unknown>} params.availableTools - Global non-MCP tool cache
|
||||
* @param {string[]} [params.existingTools] - Tools already persisted on the agent document
|
||||
* @param {Record<string, unknown>} [params.configServers] - Config-source MCP servers resolved from appConfig overrides
|
||||
|
|
@ -199,6 +201,7 @@ const filterAuthorizedTools = async ({
|
|||
tools,
|
||||
userId,
|
||||
role,
|
||||
user,
|
||||
availableTools,
|
||||
existingTools,
|
||||
configServers,
|
||||
|
|
@ -207,14 +210,26 @@ const filterAuthorizedTools = async ({
|
|||
let mcpServerConfigs;
|
||||
let registryUnavailable = false;
|
||||
const existingToolSet = existingTools?.length ? new Set(existingTools) : null;
|
||||
const hasMCPTools = tools.some((tool) => tool?.includes(Constants.mcp_delimiter));
|
||||
const canUseMCP = hasMCPTools ? await userCanUseMCPServers(user) : true;
|
||||
let loggedMCPDenied = false;
|
||||
|
||||
for (const tool of tools) {
|
||||
if (availableTools[tool] || systemTools[tool]) {
|
||||
filteredTools.push(tool);
|
||||
const isActionToolName = typeof tool === 'string' && isActionTool(tool);
|
||||
const isMCPTool = tool?.includes(Constants.mcp_delimiter) && !isActionToolName;
|
||||
|
||||
if (!isMCPTool) {
|
||||
if (availableTools[tool] || systemTools[tool] || isActionToolName) {
|
||||
filteredTools.push(tool);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!tool?.includes(Constants.mcp_delimiter)) {
|
||||
if (!canUseMCP) {
|
||||
if (!loggedMCPDenied) {
|
||||
logger.warn(`[filterAuthorizedTools] User ${userId} lacks MCP server use permission`);
|
||||
loggedMCPDenied = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -392,6 +407,7 @@ const createAgentHandler = async (req, res) => {
|
|||
tools,
|
||||
userId,
|
||||
role: req.user.role,
|
||||
user: req.user,
|
||||
availableTools,
|
||||
configServers,
|
||||
});
|
||||
|
|
@ -611,27 +627,53 @@ const updateAgentHandler = async (req, res) => {
|
|||
});
|
||||
}
|
||||
|
||||
if (updateData.tools) {
|
||||
const existingToolSet = new Set(existingAgent.tools ?? []);
|
||||
const newMCPTools = updateData.tools.filter(
|
||||
(t) => !existingToolSet.has(t) && t?.includes(Constants.mcp_delimiter),
|
||||
);
|
||||
const isMCPTool = (t) =>
|
||||
typeof t === 'string' && t.includes(Constants.mcp_delimiter) && !isActionTool(t);
|
||||
const hasToolUpdate = updateData.tools !== undefined;
|
||||
const editingOwnAgent = existingAgent.author?.toString() === req.user.id;
|
||||
const existingTools = existingAgent.tools ?? [];
|
||||
const effectiveTools = (hasToolUpdate ? updateData.tools : existingAgent.tools) ?? [];
|
||||
const requestedMCPTools = effectiveTools.filter(isMCPTool);
|
||||
const existingMCPTools = existingTools.filter(isMCPTool);
|
||||
|
||||
if (newMCPTools.length > 0) {
|
||||
const [availableTools, configServers] = await Promise.all([
|
||||
getCachedTools().then((t) => t ?? {}),
|
||||
resolveConfigServers(req),
|
||||
]);
|
||||
const approvedNew = await filterAuthorizedTools({
|
||||
tools: newMCPTools,
|
||||
userId: req.user.id,
|
||||
role: req.user.role,
|
||||
availableTools,
|
||||
configServers,
|
||||
});
|
||||
const rejectedSet = new Set(newMCPTools.filter((t) => !approvedNew.includes(t)));
|
||||
if (rejectedSet.size > 0) {
|
||||
updateData.tools = updateData.tools.filter((t) => !rejectedSet.has(t));
|
||||
if (requestedMCPTools.length > 0 || (hasToolUpdate && existingMCPTools.length > 0)) {
|
||||
if (!(await userCanUseMCPServers(req.user))) {
|
||||
if (editingOwnAgent) {
|
||||
updateData.tools = effectiveTools.filter((t) => !isMCPTool(t));
|
||||
} else if (hasToolUpdate) {
|
||||
const existingMCPToolSet = new Set(existingMCPTools);
|
||||
const nextTools = updateData.tools.filter(
|
||||
(t) => !isMCPTool(t) || existingMCPToolSet.has(t),
|
||||
);
|
||||
const nextToolSet = new Set(nextTools);
|
||||
for (const existingMCPTool of existingMCPTools) {
|
||||
if (!nextToolSet.has(existingMCPTool)) {
|
||||
nextTools.push(existingMCPTool);
|
||||
}
|
||||
}
|
||||
updateData.tools = nextTools;
|
||||
}
|
||||
} else if (hasToolUpdate) {
|
||||
const existingToolSet = new Set(existingTools);
|
||||
const newMCPTools = requestedMCPTools.filter((t) => !existingToolSet.has(t));
|
||||
|
||||
if (newMCPTools.length > 0) {
|
||||
const [availableTools, configServers] = await Promise.all([
|
||||
getCachedTools().then((t) => t ?? {}),
|
||||
resolveConfigServers(req),
|
||||
]);
|
||||
const approvedNew = await filterAuthorizedTools({
|
||||
tools: newMCPTools,
|
||||
userId: req.user.id,
|
||||
role: req.user.role,
|
||||
user: req.user,
|
||||
availableTools,
|
||||
configServers,
|
||||
});
|
||||
const rejectedSet = new Set(newMCPTools.filter((t) => !approvedNew.includes(t)));
|
||||
if (rejectedSet.size > 0) {
|
||||
updateData.tools = updateData.tools.filter((t) => !rejectedSet.has(t));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -788,6 +830,7 @@ const duplicateAgentHandler = async (req, res) => {
|
|||
tools: newAgentData.tools,
|
||||
userId,
|
||||
role: req.user.role,
|
||||
user: req.user,
|
||||
availableTools,
|
||||
existingTools: newAgentData.tools,
|
||||
configServers,
|
||||
|
|
@ -1163,6 +1206,7 @@ const revertAgentVersionHandler = async (req, res) => {
|
|||
tools: updatedAgent.tools,
|
||||
userId: req.user.id,
|
||||
role: req.user.role,
|
||||
user: req.user,
|
||||
availableTools,
|
||||
existingTools: updatedAgent.tools,
|
||||
configServers,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue