diff --git a/api/server/controllers/agents/filterAuthorizedTools.spec.js b/api/server/controllers/agents/filterAuthorizedTools.spec.js index 92d5ea5174..a138fe65cb 100644 --- a/api/server/controllers/agents/filterAuthorizedTools.spec.js +++ b/api/server/controllers/agents/filterAuthorizedTools.spec.js @@ -148,6 +148,41 @@ describe('MCP Tool Authorization', () => { expect(result).not.toContain(`toolB${d}forbiddenServer`); }); + test('should run admission checks for distinct servers concurrently and keep tool order', async () => { + mockGetAllServerConfigs.mockResolvedValue({ + serverA: { type: 'sse', source: 'user', dbId: 'a' }, + serverB: { type: 'sse', source: 'user', dbId: 'b' }, + }); + const started = []; + const settle = {}; + const admissions = {}; + const admitMCPTool = jest.fn((tool, serverName) => { + started.push(serverName); + admissions[serverName] ??= new Promise((resolve) => { + settle[serverName] = resolve; + }); + return admissions[serverName]; + }); + const resolvedServerNames = new Set(); + + const pending = filterAuthorizedTools({ + tools: [`one${d}serverA`, 'web_search', `two${d}serverB`, `three${d}serverA`], + userId, + user: testUser, + availableTools, + resolvedServerNames, + admitMCPTool, + }); + await new Promise((resolve) => setImmediate(resolve)); + + expect(started).toEqual(['serverA', 'serverB', 'serverA']); + settle.serverB(true); + settle.serverA(false); + + expect(await pending).toEqual(['web_search', `two${d}serverB`]); + expect([...resolvedServerNames]).toEqual(['serverB']); + }); + test('should strip MCP tools when user lacks MCP server use permission', async () => { mockUserCanUseMCPServers.mockResolvedValue(false); @@ -998,16 +1033,19 @@ describe('MCP Tool Authorization', () => { expect(result.tools).toContain(`tool${d}authorizedServer`); }); - test('should preserve version MCP tools when registry is unavailable on revert', async () => { + test('should keep only MCP tools already on the agent when registry is unavailable on revert', async () => { await Agent.updateOne( { id: existingAgentId }, { $set: { + tools: ['web_search', `validTool${d}authorizedServer`], + mcpServerNames: ['authorizedServer'], 'versions.0.tools': [ 'web_search', `validTool${d}authorizedServer`, `otherTool${d}anotherServer`, ], + 'versions.0.mcpServerNames': ['authorizedServer', 'anotherServer'], }, }, ); @@ -1026,11 +1064,11 @@ describe('MCP Tool Authorization', () => { const result = mockRes.json.mock.calls[0][0]; expect(result.tools).toContain('web_search'); expect(result.tools).toContain(`validTool${d}authorizedServer`); - expect(result.tools).toContain(`otherTool${d}anotherServer`); + expect(result.tools).not.toContain(`otherTool${d}anotherServer`); const agentInDb = await Agent.findOne({ id: existingAgentId }); - expect(agentInDb.tools).toContain(`validTool${d}authorizedServer`); - expect(agentInDb.tools).toContain(`otherTool${d}anotherServer`); + expect(agentInDb.tools).toEqual(['web_search', `validTool${d}authorizedServer`]); + expect(agentInDb.mcpServerNames).toEqual(['authorizedServer']); }); }); }); diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.js index e8292bf687..e1998f278b 100644 --- a/api/server/controllers/agents/v1.js +++ b/api/server/controllers/agents/v1.js @@ -52,6 +52,7 @@ const { checkInstructionsPromptWrite, applyInstructionsPromptUnset, instructionsContentForScan, + authorizeAgentRestore, } = require('@librechat/api'); const { Time, @@ -544,6 +545,7 @@ const getSubagentReferenceError = async (subagents, req, allowedMissingIds = new * @param {Record} params.availableTools - Global non-MCP tool cache * @param {string[]} [params.existingTools] - Tools already persisted on the agent document * @param {Record} [params.configServers] - Config-source MCP servers resolved from appConfig overrides + * @param {(tool: string, serverName: string, config: object | undefined) => Promise} [params.admitMCPTool] - Final gate for each MCP tool the registry approved * @returns {Promise} Only the authorized subset of tools */ const filterAuthorizedTools = async ({ @@ -556,6 +558,7 @@ const filterAuthorizedTools = async ({ existingTools, configServers, resolvedServerNames, + admitMCPTool, }) => { const filteredTools = []; let mcpServerConfigs; @@ -571,6 +574,8 @@ const filterAuthorizedTools = async ({ : userCanUseMCPServers(user)) : true; let loggedMCPDenied = false; + /** @type {Array<{ position: number, tool: string, serverName: string, admitted: Promise }>} */ + const pendingAdmissions = []; for (const tool of tools) { const isActionToolName = typeof tool === 'string' && isActionTool(tool); @@ -649,11 +654,41 @@ const filterAuthorizedTools = async ({ continue; } + if (admitMCPTool) { + pendingAdmissions.push({ + position: filteredTools.length, + tool, + serverName, + admitted: admitMCPTool(tool, serverName, mcpServerConfigs[serverName]), + }); + filteredTools.push(tool); + continue; + } + resolvedServerNames?.add(serverName); filteredTools.push(tool); } - return filteredTools; + if (pendingAdmissions.length === 0) { + return filteredTools; + } + + /** Admission lookups for distinct servers run concurrently; positions keep tool order. */ + const admissionResults = await Promise.all(pendingAdmissions.map(({ admitted }) => admitted)); + const rejectedPositions = new Set(); + pendingAdmissions.forEach(({ position, tool, serverName }, i) => { + if (admissionResults[i]) { + resolvedServerNames?.add(serverName); + return; + } + logger.warn( + `[filterAuthorizedTools] Rejected MCP tool "${tool}" — no live access to server "${serverName}" for user ${userId} outside the agent being changed`, + ); + rejectedPositions.add(position); + }); + return rejectedPositions.size > 0 + ? filteredTools.filter((_, i) => !rejectedPositions.has(i)) + : filteredTools; }; /** @@ -2134,7 +2169,35 @@ const revertAgentVersionHandler = async (req, res) => { return; } - let updatedAgent = await db.revertAgentVersion({ id }, version_index); + const revertOptions = await authorizeAgentRestore({ + agent: existingAgent, + versionTools: revertVersion.tools, + authorizeTools: async (request) => { + const [availableTools, configServers] = await Promise.all([ + getCachedTools().then((t) => t ?? {}), + resolveConfigServers(req), + ]); + return filterAuthorizedTools({ + ...request, + userId: req.user.id, + role: req.user.role, + user: req.user, + mcpPermissionContext: createMCPPermissionContext(req), + availableTools, + configServers, + }); + }, + listAgentIdsForServer: db.getAgentIdsByMCPServerName, + getPermissions: (resourceType, resourceIds) => + getResourcePermissionsMap({ + userId: req.user.id, + role: req.user.role, + resourceType, + resourceIds, + }), + }); + + let updatedAgent = await db.revertAgentVersion({ id }, version_index, revertOptions); const revertUpdates = {}; if ( hasLegacyEdgeSource || @@ -2143,28 +2206,7 @@ const revertAgentVersionHandler = async (req, res) => { revertUpdates.edges = revertEdges; } - if (updatedAgent.tools?.length) { - const [availableTools, configServers] = await Promise.all([ - getCachedTools().then((t) => t ?? {}), - resolveConfigServers(req), - ]); - const mcpPermissionContext = createMCPPermissionContext(req); - const filteredTools = await filterAuthorizedTools({ - tools: updatedAgent.tools, - userId: req.user.id, - role: req.user.role, - user: req.user, - mcpPermissionContext, - availableTools, - existingTools: updatedAgent.tools, - configServers, - }); - if (filteredTools.length !== updatedAgent.tools.length) { - revertUpdates.tools = filteredTools; - } - } - - const effectiveRevertTools = revertUpdates.tools ?? updatedAgent.tools; + const effectiveRevertTools = updatedAgent.tools; const hasCodeExecutionCaller = Object.values(updatedAgent.tool_options ?? {}).some((options) => options.allowed_callers?.includes('code_execution'), ); diff --git a/api/server/routes/agents/__tests__/revert.mcp.spec.js b/api/server/routes/agents/__tests__/revert.mcp.spec.js new file mode 100644 index 0000000000..f19a7c4c66 --- /dev/null +++ b/api/server/routes/agents/__tests__/revert.mcp.spec.js @@ -0,0 +1,355 @@ +/** Short registry memo so a test can observe access after it would have expired. */ +process.env.MCP_REGISTRY_CACHE_TTL = '50'; +const waitForRegistryCache = () => new Promise((resolve) => setTimeout(resolve, 100)); + +/** The shared jest setup stubs `~/config`; the route must reach the real MCP registry. */ +jest.mock('~/config', () => jest.requireActual('~/config')); +jest.mock('~/server/services/Config', () => ({ + ...jest.requireActual('~/server/services/Config'), + getAppConfig: jest.fn().mockResolvedValue({}), + getCachedTools: jest.fn().mockResolvedValue({}), +})); + +const express = require('express'); +const request = require('supertest'); +const mongoose = require('mongoose'); +const { MongoMemoryServer } = require('mongodb-memory-server'); +const { MCPServersRegistry } = require('@librechat/api'); +const { createModels, createMethods } = require('@librechat/data-schemas'); +const { + Constants, + SystemRoles, + ResourceType, + PrincipalType, + AccessRoleIds, +} = require('librechat-data-provider'); + +describe('POST /agents/:id/revert - MCP server authorization', () => { + let app; + let mongoServer; + let methods; + let registry; + let grantPermission; + let alice; + let bob; + let currentUser; + + const asUser = (user) => ({ id: user._id.toString(), role: SystemRoles.USER }); + const mcpTool = (serverName) => `search${Constants.mcp_delimiter}${serverName}`; + + beforeAll(async () => { + mongoServer = await MongoMemoryServer.create(); + await mongoose.connect(mongoServer.getUri()); + Object.assign(mongoose.models, createModels(mongoose)); + methods = createMethods(mongoose); + await methods.seedDefaultRoles(); + registry = MCPServersRegistry.createInstance(mongoose, null, null); + ({ grantPermission } = require('~/server/services/PermissionService')); + + app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.user = currentUser; + next(); + }); + app.use('/agents', require('~/server/routes/agents/v1').v1); + }, 60_000); + + afterAll(async () => { + await mongoose.disconnect(); + await mongoServer.stop(); + }); + + beforeEach(async () => { + const { User, Agent, AclEntry, MCPServer } = mongoose.models; + await Promise.all([ + User.deleteMany({}), + Agent.deleteMany({}), + AclEntry.deleteMany({}), + MCPServer.deleteMany({}), + ]); + alice = await User.create({ username: 'alice', email: 'alice@test.com' }); + bob = await User.create({ username: 'bob', email: 'bob@test.com' }); + }); + + /** Alice owns a private DB MCP server; Bob has no grant on it. */ + async function createPrivateServer() { + const server = await methods.createMCPServer({ + config: { title: 'Secret DB', type: 'streamable-http', url: 'https://mcp.example.com/mcp' }, + author: alice._id, + }); + await grantPermission({ + principalType: PrincipalType.USER, + principalId: alice._id, + resourceType: ResourceType.MCPSERVER, + resourceId: server._id, + accessRoleId: AccessRoleIds.MCPSERVER_OWNER, + grantedBy: alice._id, + }); + return server.serverName; + } + + /** Alice owns the agent and shares EDIT with Bob. */ + async function shareAgent(agent) { + await grantPermission({ + principalType: PrincipalType.USER, + principalId: alice._id, + resourceType: ResourceType.AGENT, + resourceId: agent._id, + accessRoleId: AccessRoleIds.AGENT_OWNER, + grantedBy: alice._id, + }); + await grantPermission({ + principalType: PrincipalType.USER, + principalId: bob._id, + resourceType: ResourceType.AGENT, + resourceId: agent._id, + accessRoleId: AccessRoleIds.AGENT_EDITOR, + grantedBy: alice._id, + }); + } + + const bobsServers = async () => + Object.keys( + await registry.getAllServerConfigs(bob._id.toString(), undefined, SystemRoles.USER), + ); + + it('control: Bob cannot attach the private server through the update route', async () => { + const serverName = await createPrivateServer(); + const agent = await methods.createAgent({ + id: 'agent_update_control', + name: 'Shared', + provider: 'openai', + model: 'gpt-4o', + author: alice._id, + tools: [], + }); + await shareAgent(agent); + + currentUser = asUser(bob); + const res = await request(app) + .patch(`/agents/${agent.id}`) + .send({ tools: [mcpTool(serverName)] }); + + expect(res.status).toBe(200); + const stored = await methods.getAgent({ id: agent.id }); + expect(stored.tools).toEqual([]); + expect(stored.mcpServerNames ?? []).not.toContain(serverName); + expect(await bobsServers()).not.toContain(serverName); + }); + + it('revert does not let an editor re-attach a server the agent no longer uses', async () => { + const serverName = await createPrivateServer(); + const agent = await methods.createAgent({ + id: 'agent_revert_reattach', + name: 'Shared', + provider: 'openai', + model: 'gpt-4o', + author: alice._id, + tools: [mcpTool(serverName)], + mcpServerNames: [serverName], + }); + await methods.updateAgent( + { id: agent.id }, + { tools: [] }, + { updatingUserId: alice._id.toString() }, + ); + await shareAgent(agent); + + expect(await bobsServers()).not.toContain(serverName); + + await waitForRegistryCache(); + currentUser = asUser(bob); + const res = await request(app).post(`/agents/${agent.id}/revert`).send({ version_index: 0 }); + + expect(res.status).toBe(200); + const stored = await methods.getAgent({ id: agent.id }); + expect(stored.tools).not.toContain(mcpTool(serverName)); + expect(stored.mcpServerNames ?? []).not.toContain(serverName); + expect(await bobsServers()).not.toContain(serverName); + }); + + it('revert to a version without MCP tools drops the server from the agent index', async () => { + const serverName = await createPrivateServer(); + const agent = await methods.createAgent({ + id: 'agent_revert_stale', + name: 'Shared', + provider: 'openai', + model: 'gpt-4o', + author: alice._id, + tools: [], + }); + await methods.updateAgent( + { id: agent.id }, + { tools: [mcpTool(serverName)], mcpServerNames: [serverName] }, + { updatingUserId: alice._id.toString() }, + ); + await shareAgent(agent); + + currentUser = asUser(alice); + const res = await request(app).post(`/agents/${agent.id}/revert`).send({ version_index: 0 }); + + expect(res.status).toBe(200); + const stored = await methods.getAgent({ id: agent.id }); + expect(stored.tools).toEqual([]); + expect(stored.mcpServerNames ?? []).not.toContain(serverName); + await waitForRegistryCache(); + expect(await bobsServers()).not.toContain(serverName); + }); + /** Alice's agent used the server in version 0 and dropped it in version 1. */ + async function createDetachedAgent(id, serverName) { + const agent = await methods.createAgent({ + id, + name: 'Shared', + provider: 'openai', + model: 'gpt-4o', + author: alice._id, + tools: [mcpTool(serverName)], + mcpServerNames: [serverName], + }); + await methods.updateAgent( + { id: agent.id }, + { tools: [] }, + { updatingUserId: alice._id.toString() }, + ); + await shareAgent(agent); + return agent; + } + + it('a stale index on the target agent does not authorize the restore', async () => { + const serverName = await createPrivateServer(); + const agent = await createDetachedAgent('agent_revert_stale_index', serverName); + /** The state an earlier revert left behind: no tool uses the server, the index still names it. */ + await mongoose.models.Agent.updateOne( + { id: agent.id }, + { $set: { mcpServerNames: [serverName] } }, + ); + await waitForRegistryCache(); + + currentUser = asUser(bob); + const res = await request(app).post(`/agents/${agent.id}/revert`).send({ version_index: 0 }); + + expect(res.status).toBe(200); + const stored = await methods.getAgent({ id: agent.id }); + expect(stored.tools).toEqual([]); + expect(stored.mcpServerNames).toEqual([]); + await waitForRegistryCache(); + expect(await bobsServers()).not.toContain(serverName); + }); + + it('access cached from before the owner detached the server does not authorize the restore', async () => { + const serverName = await createPrivateServer(); + const agent = await methods.createAgent({ + id: 'agent_revert_cached', + name: 'Shared', + provider: 'openai', + model: 'gpt-4o', + author: alice._id, + tools: [mcpTool(serverName)], + mcpServerNames: [serverName], + }); + await shareAgent(agent); + expect(await bobsServers()).toContain(serverName); + await methods.updateAgent( + { id: agent.id }, + { tools: [] }, + { updatingUserId: alice._id.toString() }, + ); + + currentUser = asUser(bob); + const res = await request(app).post(`/agents/${agent.id}/revert`).send({ version_index: 0 }); + + expect(res.status).toBe(200); + const stored = await methods.getAgent({ id: agent.id }); + expect(stored.tools).toEqual([]); + expect(stored.mcpServerNames).toEqual([]); + }); + + it('an editor who reaches the server through another agent can restore it', async () => { + const serverName = await createPrivateServer(); + const agent = await createDetachedAgent('agent_revert_other_grant', serverName); + const other = await methods.createAgent({ + id: 'agent_other_grant', + name: 'Other', + provider: 'openai', + model: 'gpt-4o', + author: alice._id, + tools: [mcpTool(serverName)], + mcpServerNames: [serverName], + }); + await grantPermission({ + principalType: PrincipalType.USER, + principalId: bob._id, + resourceType: ResourceType.AGENT, + resourceId: other._id, + accessRoleId: AccessRoleIds.AGENT_VIEWER, + grantedBy: alice._id, + }); + await waitForRegistryCache(); + + currentUser = asUser(bob); + const res = await request(app).post(`/agents/${agent.id}/revert`).send({ version_index: 0 }); + + expect(res.status).toBe(200); + const stored = await methods.getAgent({ id: agent.id }); + expect(stored.tools).toEqual([mcpTool(serverName)]); + expect(stored.mcpServerNames).toEqual([serverName]); + }); + + it('a direct grant revoked while the registry still caches it does not authorize the restore', async () => { + const serverName = await createPrivateServer(); + const server = await methods.findMCPServerByServerName(serverName); + await grantPermission({ + principalType: PrincipalType.USER, + principalId: bob._id, + resourceType: ResourceType.MCPSERVER, + resourceId: server._id, + accessRoleId: AccessRoleIds.MCPSERVER_VIEWER, + grantedBy: alice._id, + }); + const agent = await createDetachedAgent('agent_revert_revoked', serverName); + expect(await bobsServers()).toContain(serverName); + await mongoose.models.AclEntry.deleteMany({ + principalId: bob._id, + resourceType: ResourceType.MCPSERVER, + }); + + currentUser = asUser(bob); + const res = await request(app).post(`/agents/${agent.id}/revert`).send({ version_index: 0 }); + + expect(res.status).toBe(200); + const stored = await methods.getAgent({ id: agent.id }); + expect(stored.tools).toEqual([]); + expect(stored.mcpServerNames).toEqual([]); + }); + + it('an editor can restore another tool from a server the agent still uses', async () => { + const serverName = await createPrivateServer(); + const kept = mcpTool(serverName); + const restored = `fetch${Constants.mcp_delimiter}${serverName}`; + const agent = await methods.createAgent({ + id: 'agent_revert_still_used', + name: 'Shared', + provider: 'openai', + model: 'gpt-4o', + author: alice._id, + tools: [kept, restored], + mcpServerNames: [serverName], + }); + await methods.updateAgent( + { id: agent.id }, + { tools: [kept] }, + { updatingUserId: alice._id.toString() }, + ); + await shareAgent(agent); + await waitForRegistryCache(); + + currentUser = asUser(bob); + const res = await request(app).post(`/agents/${agent.id}/revert`).send({ version_index: 0 }); + + expect(res.status).toBe(200); + const stored = await methods.getAgent({ id: agent.id }); + expect(stored.tools).toEqual([kept, restored]); + expect(stored.mcpServerNames).toEqual([serverName]); + }); +}); diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.ts index 834b335059..67106a3789 100644 --- a/packages/api/src/agents/index.ts +++ b/packages/api/src/agents/index.ts @@ -41,6 +41,7 @@ export * from './marketplace'; export * from './reads'; export * from './updates'; export * from './mcpIdentity'; +export * from './restore'; export * from './orphans'; export * from './ownerContact'; export * from './migration'; diff --git a/packages/api/src/agents/restore.spec.ts b/packages/api/src/agents/restore.spec.ts new file mode 100644 index 0000000000..ff968c0bb3 --- /dev/null +++ b/packages/api/src/agents/restore.spec.ts @@ -0,0 +1,318 @@ +import { Constants, ResourceType, PermissionBits } from 'librechat-data-provider'; +import type { RestoredToolsAuthorization, RestoredServerConfig } from './restore'; +import { authorizeAgentRestore, resolveRestoredMCPServerNames } from './restore'; + +const mcpTool = (serverName: string): string => `search${Constants.mcp_delimiter}${serverName}`; + +describe('resolveRestoredMCPServerNames', () => { + it('keeps names resolved during authorization', () => { + expect( + resolveRestoredMCPServerNames({ + tools: [mcpTool('docs')], + existingTools: [], + resolvedServerNames: new Set(['docs']), + priorNames: [], + }), + ).toEqual(['docs']); + }); + + it('carries a prior name forward only while a tool the agent already had resolves to it', () => { + expect( + resolveRestoredMCPServerNames({ + tools: [mcpTool('docs'), 'web_search'], + existingTools: [mcpTool('docs')], + resolvedServerNames: [], + priorNames: ['docs', 'detached'], + }), + ).toEqual(['docs']); + }); + + it('matches a prior raw name through its normalized tool-key form', () => { + const tool = mcpTool('Connector__Company'); + expect( + resolveRestoredMCPServerNames({ + tools: [tool], + existingTools: [tool], + resolvedServerNames: [], + priorNames: ['Connector: Company'], + }), + ).toEqual(['Connector: Company']); + }); + + it('does not let a newly restored tool claim a prior name', () => { + expect( + resolveRestoredMCPServerNames({ + tools: [mcpTool('docs'), mcpTool('kept')], + existingTools: [mcpTool('kept')], + resolvedServerNames: ['kept'], + priorNames: ['docs', 'kept'], + }), + ).toEqual(['kept']); + }); + + it('returns an empty index when no MCP tool is restored', () => { + expect( + resolveRestoredMCPServerNames({ + tools: ['web_search'], + existingTools: [mcpTool('docs')], + resolvedServerNames: [], + priorNames: ['docs'], + }), + ).toEqual([]); + }); + + it('keeps the pre-restore index rather than deriving names when nothing resolves', () => { + expect( + resolveRestoredMCPServerNames({ + tools: [mcpTool('legacy')], + existingTools: [mcpTool('legacy')], + resolvedServerNames: [], + priorNames: ['other'], + }), + ).toEqual(['other']); + }); + + it('ignores action tools that contain the MCP delimiter', () => { + const actionTool = `sync${Constants.mcp_delimiter}state_action_api---example---com`; + expect( + resolveRestoredMCPServerNames({ + tools: [actionTool], + existingTools: [], + resolvedServerNames: [], + priorNames: [], + }), + ).toEqual([]); + }); +}); + +describe('authorizeAgentRestore', () => { + const agentId = 'agent-object-id'; + const otherAgentId = 'other-agent-object-id'; + const updatedAt = new Date('2026-11-05T00:00:00Z'); + const dbConfig = (serverName: string): RestoredServerConfig => ({ + source: 'user', + dbId: `server-${serverName}`, + }); + const noPermissions = (): Promise> => Promise.resolve(new Map()); + + /** Approves every tool, routing each MCP tool through the restore gate. */ + const authorizeThroughGate = + (configFor: (serverName: string) => RestoredServerConfig = dbConfig) => + async ({ + tools, + resolvedServerNames, + admitMCPTool, + }: RestoredToolsAuthorization): Promise => { + const approved: string[] = []; + for (const tool of tools) { + if (!tool.includes(Constants.mcp_delimiter)) { + approved.push(tool); + continue; + } + const serverName = tool.split(Constants.mcp_delimiter).pop() as string; + if (await admitMCPTool(tool, serverName, configFor(serverName))) { + resolvedServerNames.add(serverName); + approved.push(tool); + } + } + return approved; + }; + + it('pins the restore to the revision it read and skips authorization with no tools', async () => { + const authorizeTools = jest.fn(); + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [], updatedAt }, + versionTools: undefined, + authorizeTools, + listAgentIdsForServer: jest.fn(), + getPermissions: jest.fn(), + }); + expect(plan).toEqual({ expectedUpdatedAt: updatedAt }); + expect(authorizeTools).not.toHaveBeenCalled(); + }); + + it('restores an explicit empty set when the snapshot array holds no valid tools', async () => { + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [mcpTool('docs')], mcpServerNames: ['docs'], updatedAt }, + versionTools: [42, null, { name: 'tool' }], + authorizeTools: jest.fn(), + listAgentIdsForServer: jest.fn(), + getPermissions: jest.fn(), + }); + expect(plan).toEqual({ expectedUpdatedAt: updatedAt, tools: [], mcpServerNames: [] }); + }); + + it('passes the current tools as existing, not the restored ones', async () => { + const authorizeTools = jest.fn().mockResolvedValue(['web_search']); + await authorizeAgentRestore({ + agent: { _id: agentId, tools: ['web_search'], updatedAt }, + versionTools: ['web_search', mcpTool('docs')], + authorizeTools, + listAgentIdsForServer: jest.fn(), + getPermissions: jest.fn(), + }); + expect(authorizeTools).toHaveBeenCalledWith( + expect.objectContaining({ + tools: ['web_search', mcpTool('docs')], + existingTools: ['web_search'], + }), + ); + }); + + it('rejects a new tool whose only grant is the target agent', async () => { + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [], mcpServerNames: ['docs'], updatedAt }, + versionTools: [mcpTool('docs')], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer: jest.fn().mockResolvedValue([agentId]), + getPermissions: noPermissions, + }); + expect(plan.tools).toEqual([]); + expect(plan.mcpServerNames).toEqual([]); + }); + + it('admits a new tool the user reaches through another viewable agent', async () => { + const getPermissions = jest.fn(async (resourceType: ResourceType) => + resourceType === ResourceType.AGENT + ? new Map([[otherAgentId, PermissionBits.VIEW]]) + : new Map(), + ); + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [], updatedAt }, + versionTools: [mcpTool('docs')], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer: jest.fn().mockResolvedValue([agentId, otherAgentId]), + getPermissions, + }); + expect(getPermissions).toHaveBeenCalledWith(ResourceType.AGENT, [otherAgentId]); + expect(plan.tools).toEqual([mcpTool('docs')]); + expect(plan.mcpServerNames).toEqual(['docs']); + }); + + it('admits a new tool on a live direct server grant', async () => { + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [], updatedAt }, + versionTools: [mcpTool('docs')], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer: jest.fn().mockResolvedValue([]), + getPermissions: async (resourceType) => + resourceType === ResourceType.MCPSERVER + ? new Map([['server-docs', PermissionBits.VIEW]]) + : new Map(), + }); + expect(plan.tools).toEqual([mcpTool('docs')]); + }); + + it('rejects a new tool when no live grant remains, whatever the registry cached', async () => { + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [], updatedAt }, + versionTools: [mcpTool('docs')], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer: jest.fn().mockResolvedValue([otherAgentId]), + getPermissions: noPermissions, + }); + expect(plan.tools).toEqual([]); + }); + + it('admits another tool from a server the agent still uses, without a lookup', async () => { + const listAgentIdsForServer = jest.fn(); + const fetchTool = `fetch${Constants.mcp_delimiter}docs`; + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [mcpTool('docs')], mcpServerNames: ['docs'], updatedAt }, + versionTools: [mcpTool('docs'), fetchTool], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer, + getPermissions: noPermissions, + }); + expect(listAgentIdsForServer).not.toHaveBeenCalled(); + expect(plan.tools).toEqual([mcpTool('docs'), fetchTool]); + expect(plan.mcpServerNames).toEqual(['docs']); + }); + + it('does not treat a stale index entry as a server the agent still uses', async () => { + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: ['web_search'], mcpServerNames: ['docs'], updatedAt }, + versionTools: [mcpTool('docs')], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer: jest.fn().mockResolvedValue([agentId]), + getPermissions: noPermissions, + }); + expect(plan.tools).toEqual([]); + }); + + it('looks up each server once however many of its tools are restored', async () => { + const listAgentIdsForServer = jest.fn().mockResolvedValue([otherAgentId]); + const getPermissions = jest.fn(async (resourceType: ResourceType) => + resourceType === ResourceType.AGENT + ? new Map([[otherAgentId, PermissionBits.VIEW]]) + : new Map(), + ); + await authorizeAgentRestore({ + agent: { _id: agentId, tools: [], updatedAt }, + versionTools: [ + mcpTool('docs'), + `fetch${Constants.mcp_delimiter}docs`, + `list${Constants.mcp_delimiter}docs`, + ], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer, + getPermissions, + }); + expect(listAgentIdsForServer).toHaveBeenCalledTimes(1); + expect(getPermissions).toHaveBeenCalledTimes(2); + }); + + it('admits operator-managed servers without a database lookup', async () => { + const listAgentIdsForServer = jest.fn(); + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [], updatedAt }, + versionTools: [mcpTool('yamlServer')], + authorizeTools: authorizeThroughGate(() => ({ source: 'yaml' })), + listAgentIdsForServer, + getPermissions: noPermissions, + }); + expect(listAgentIdsForServer).not.toHaveBeenCalled(); + expect(plan.tools).toEqual([mcpTool('yamlServer')]); + }); + + it('rechecks a legacy cached DB config that carries a dbId but no source', async () => { + const listAgentIdsForServer = jest.fn().mockResolvedValue([]); + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [], updatedAt }, + versionTools: [mcpTool('docs')], + authorizeTools: authorizeThroughGate(() => ({ dbId: 'server-docs' })), + listAgentIdsForServer, + getPermissions: noPermissions, + }); + expect(listAgentIdsForServer).toHaveBeenCalledWith('docs'); + expect(plan.tools).toEqual([]); + }); + + it('rechecks a tool the agent holds without an index entry for its server', async () => { + const listAgentIdsForServer = jest.fn().mockResolvedValue([agentId]); + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [mcpTool('docs')], mcpServerNames: [], updatedAt }, + versionTools: [mcpTool('docs')], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer, + getPermissions: noPermissions, + }); + expect(listAgentIdsForServer).toHaveBeenCalledWith('docs'); + expect(plan.tools).toEqual([]); + expect(plan.mcpServerNames).toEqual([]); + }); + + it('keeps an indexed tool the agent already has without a further lookup', async () => { + const listAgentIdsForServer = jest.fn(); + const plan = await authorizeAgentRestore({ + agent: { _id: agentId, tools: [mcpTool('docs')], mcpServerNames: ['docs'], updatedAt }, + versionTools: [mcpTool('docs')], + authorizeTools: authorizeThroughGate(), + listAgentIdsForServer, + getPermissions: noPermissions, + }); + expect(listAgentIdsForServer).not.toHaveBeenCalled(); + expect(plan.tools).toEqual([mcpTool('docs')]); + expect(plan.mcpServerNames).toEqual(['docs']); + }); +}); diff --git a/packages/api/src/agents/restore.ts b/packages/api/src/agents/restore.ts new file mode 100644 index 0000000000..5bb4bd46c2 --- /dev/null +++ b/packages/api/src/agents/restore.ts @@ -0,0 +1,228 @@ +import { + Constants, + isActionTool, + ResourceType, + PermissionBits, + splitMCPToolKey, + buildServerNameAliases, +} from 'librechat-data-provider'; +import type { ParsedServerConfig } from '~/mcp/types'; +import { isUserSourced } from '~/mcp/utils'; + +type ResourceId = { toString(): string }; + +/** The registry fields the restore gate reads for an approved MCP tool. */ +export type RestoredServerConfig = Pick; + +/** The agent a version is restored onto, as read before the restore. */ +export interface AgentRestoreTarget { + _id: { toString(): string }; + tools?: string[] | null; + mcpServerNames?: string[] | null; + updatedAt?: Date; +} + +/** What the caller's tool authorizer receives for a restore. */ +export interface RestoredToolsAuthorization { + tools: string[]; + /** The agent's current tools; only these may survive a registry outage. */ + existingTools: string[]; + /** Filled with the raw server name of every approved MCP tool. */ + resolvedServerNames: Set; + /** + * Final gate for every MCP tool the registry approved. Re-checks tools on DB-backed servers + * the agent's current index does not cover, live and without the target agent's own grant. + */ + admitMCPTool: ( + tool: string, + serverName: string, + config: RestoredServerConfig | undefined, + ) => Promise; +} + +export interface AuthorizeAgentRestoreParams { + agent: AgentRestoreTarget; + /** The snapshot's `tools`, unvalidated. */ + versionTools: unknown; + authorizeTools: (request: RestoredToolsAuthorization) => Promise; + /** Ids of agents whose `mcpServerNames` include the server, read fresh from the database. */ + listAgentIdsForServer: (serverName: string) => Promise; + /** The requesting user's live effective permission bits per resource id. */ + getPermissions: ( + resourceType: ResourceType, + resourceIds: ResourceId[], + ) => Promise>; +} + +/** Options for `revertAgentVersion` that pin the restore to what was authorized. */ +export interface AgentRestorePlan { + tools?: string[]; + mcpServerNames?: string[]; + expectedUpdatedAt?: Date; +} + +export interface RestoredMCPServerNamesParams { + /** Tools the restore will persist, already authorized for the requesting user. */ + tools: readonly string[]; + /** The agent's tools before the restore. */ + existingTools: readonly string[]; + /** Server names resolved while authorizing the restored tools. */ + resolvedServerNames: Iterable; + /** The agent's index before the restore; never the snapshot's, which is unverified. */ + priorNames: readonly string[]; +} + +const isMCPToolKey = (tool: unknown): tool is string => + typeof tool === 'string' && tool.includes(Constants.mcp_delimiter) && !isActionTool(tool); + +/** Prior raw server names that some MCP tool in `tools` resolves to, via normalized aliases. */ +function matchPriorServerNames( + tools: readonly string[], + priorNames: readonly string[], +): Set { + const matched = new Set(); + const aliases = buildServerNameAliases(priorNames); + const aliasKeys = Array.from(aliases.keys()); + if (aliasKeys.length === 0) { + return matched; + } + for (const tool of tools) { + if (!isMCPToolKey(tool)) { + continue; + } + const [, serverName] = splitMCPToolKey(tool, aliasKeys); + const rawName = serverName != null ? aliases.get(serverName) : undefined; + if (rawName) { + matched.add(rawName); + } + } + return matched; +} + +/** + * Builds the `mcpServerNames` index for a version restore from authorized sources only: + * names resolved while authorizing the restored tools, plus the agent's pre-restore names + * that a tool it already had still resolves to. Tool keys embed normalized server names, + * so prior raw names are matched through their normalized aliases. + * + * When MCP tools survive but none resolves (only possible while the registry is + * unavailable, which admits nothing beyond the agent's current tools), the pre-restore + * index is kept: it grants nothing the agent did not already grant, whereas deriving + * names from tool keys could name an unrelated server. + */ +export function resolveRestoredMCPServerNames({ + tools, + existingTools, + resolvedServerNames, + priorNames, +}: RestoredMCPServerNamesParams): string[] { + const existingToolSet = new Set(existingTools); + const names = new Set(resolvedServerNames); + for (const name of matchPriorServerNames( + tools.filter((tool) => existingToolSet.has(tool)), + priorNames, + )) { + names.add(name); + } + if (names.size === 0 && tools.some(isMCPToolKey)) { + return [...priorNames]; + } + return Array.from(names); +} + +const canView = (permissions: Map, id: ResourceId): boolean => + ((permissions.get(id.toString()) ?? 0) & PermissionBits.VIEW) !== 0; + +/** + * Authorizes a version restore against the agent as it stands, before anything is written. + * + * Agent-scoped MCP access is granted from `mcpServerNames`, so the restore must not be + * judged against the snapshot's index (it would vouch for itself), and a tool whose server + * the agent's index does not already cover must not be admitted on a cached registry view + * or on the target agent's own grant. A tool on a DB-backed server is admitted when a current tool on that + * server is still indexed on the agent, or when the user holds a live grant on the server + * itself or on another agent that uses it. + */ +export async function authorizeAgentRestore({ + agent, + versionTools, + authorizeTools, + listAgentIdsForServer, + getPermissions, +}: AuthorizeAgentRestoreParams): Promise { + const plan: AgentRestorePlan = { expectedUpdatedAt: agent.updatedAt }; + const existingTools = agent.tools ?? []; + const snapshotHasTools = Array.isArray(versionTools); + const restoredTools = snapshotHasTools + ? versionTools.filter((tool): tool is string => typeof tool === 'string') + : existingTools; + if (restoredTools.length === 0) { + return snapshotHasTools ? { ...plan, tools: [], mcpServerNames: [] } : plan; + } + + const agentId = agent._id.toString(); + const priorNames = agent.mcpServerNames ?? []; + /** Servers the agent demonstrably uses now: a current tool still resolves to the name. + * Holding a tool is not enough on its own: an unindexed tool (a legacy agent) would + * otherwise skip the live check and have its server added to the index. */ + const activeServerNames = matchPriorServerNames(existingTools, priorNames); + + const hasLiveServerAccess = async ( + serverName: string, + dbId: string | undefined, + ): Promise => { + if (activeServerNames.has(serverName)) { + return true; + } + const [direct, viaOtherAgent] = await Promise.all([ + dbId + ? getPermissions(ResourceType.MCPSERVER, [dbId]).then((map) => canView(map, dbId)) + : Promise.resolve(false), + listAgentIdsForServer(serverName).then(async (ids) => { + const otherIds = ids.filter((id) => id.toString() !== agentId); + if (otherIds.length === 0) { + return false; + } + const permissions = await getPermissions(ResourceType.AGENT, otherIds); + return otherIds.some((id) => canView(permissions, id)); + }), + ]); + return direct || viaOtherAgent; + }; + + const admissions = new Map>(); + const admitMCPTool = ( + tool: string, + serverName: string, + config: RestoredServerConfig | undefined, + ): Promise => { + if (!config || !isUserSourced(config)) { + return Promise.resolve(true); + } + let admission = admissions.get(serverName); + if (!admission) { + admission = hasLiveServerAccess(serverName, config.dbId); + admissions.set(serverName, admission); + } + return admission; + }; + + const resolvedServerNames = new Set(); + const tools = await authorizeTools({ + tools: restoredTools, + existingTools, + resolvedServerNames, + admitMCPTool, + }); + + return { + ...plan, + tools, + mcpServerNames: resolveRestoredMCPServerNames({ + tools, + existingTools, + resolvedServerNames, + priorNames, + }), + }; +} diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.ts index 1434f20b8a..6dcf5852be 100644 --- a/packages/data-schemas/src/methods/agent.spec.ts +++ b/packages/data-schemas/src/methods/agent.spec.ts @@ -3228,6 +3228,98 @@ describe('Agent Methods', () => { expect(revertedAgent.code_environment_id).toBeUndefined(); }); + test('should rebuild the MCP index when the restored version predates it', async () => { + const agentId = `agent_${uuidv4()}`; + await createAgent({ + id: agentId, + name: 'No MCP Yet', + provider: 'test', + model: 'test-model', + author: new mongoose.Types.ObjectId(), + tools: [], + }); + await updateAgent( + { id: agentId }, + { tools: [`search${Constants.mcp_delimiter}private`], mcpServerNames: ['private'] }, + ); + + const revertedAgent = await revertAgentVersion({ id: agentId }, 0); + + expect(revertedAgent.tools).toEqual([]); + expect(revertedAgent.mcpServerNames).toEqual([]); + }); + + test('should persist caller-authorized tools and index in place of the snapshot', async () => { + const agentId = `agent_${uuidv4()}`; + const kept = `search${Constants.mcp_delimiter}shared`; + const dropped = `search${Constants.mcp_delimiter}private`; + await createAgent({ + id: agentId, + name: 'Two Servers', + provider: 'test', + model: 'test-model', + author: new mongoose.Types.ObjectId(), + tools: [kept, dropped], + mcpServerNames: ['shared', 'private'], + }); + await updateAgent({ id: agentId }, { tools: [] }); + + const revertedAgent = await revertAgentVersion({ id: agentId }, 0, { + tools: [kept], + mcpServerNames: ['shared'], + }); + + expect(revertedAgent.tools).toEqual([kept]); + expect(revertedAgent.mcpServerNames).toEqual(['shared']); + }); + + test('should refuse a restore authorized against an older revision', async () => { + const agentId = `agent_${uuidv4()}`; + const created = await createAgent({ + id: agentId, + name: 'Original', + provider: 'test', + model: 'test-model', + author: new mongoose.Types.ObjectId(), + }); + const staleRevision = (created as IAgent & { updatedAt: Date }).updatedAt; + await new Promise((resolve) => setTimeout(resolve, 5)); + await updateAgent({ id: agentId }, { name: 'Edited' }); + + await expect( + revertAgentVersion({ id: agentId }, 0, { expectedUpdatedAt: staleRevision }), + ).rejects.toMatchObject({ statusCode: 409 }); + expect((await getAgent({ id: agentId }))?.name).toBe('Edited'); + }); + + test('should report a write that lands between the read and the restore as a conflict', async () => { + const agentId = `agent_${uuidv4()}`; + await createAgent({ + id: agentId, + name: 'Original', + provider: 'test', + model: 'test-model', + author: new mongoose.Types.ObjectId(), + }); + await updateAgent({ id: agentId }, { name: 'Edited' }); + + const realFindOne = Agent.findOne.bind(Agent); + const spy = jest.spyOn(Agent, 'findOne').mockImplementationOnce((( + filter: RootFilterQuery, + ) => + realFindOne(filter).then(async (agent) => { + await new Promise((resolve) => setTimeout(resolve, 5)); + await Agent.updateOne({ id: agentId }, { $set: { name: 'Concurrent' } }); + return agent; + })) as typeof Agent.findOne); + + await expect(revertAgentVersion({ id: agentId }, 0)).rejects.toMatchObject({ + statusCode: 409, + }); + spy.mockRestore(); + expect((await getAgent({ id: agentId }))?.name).toBe('Concurrent'); + }); + test('should unset a linked prompt-group instructions selection absent from the restored version', async () => { const agentId = `agent_${uuidv4()}`; const authorId = new mongoose.Types.ObjectId(); diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts index 1162ba0210..66bb88c939 100644 --- a/packages/data-schemas/src/methods/agent.ts +++ b/packages/data-schemas/src/methods/agent.ts @@ -253,6 +253,24 @@ export class AgentSortCursorError extends Error { } } +/** Options a caller passes after authorizing a restore against the agent it read. */ +export interface RevertAgentVersionOptions { + /** Authorized tools; replace the snapshot's, which were never checked for this user. */ + tools?: string[]; + /** Index resolved for `tools`. Derived from the restored tools when omitted. */ + mcpServerNames?: string[]; + /** The revision the caller authorized against; the restore is refused once it moves. */ + expectedUpdatedAt?: Date; +} + +export class AgentRevisionConflictError extends Error { + readonly statusCode = 409; + constructor() { + super('Agent was modified while reverting; reload and try again'); + this.name = 'AgentRevisionConflictError'; + } +} + type AgentSortCursorDecodeResult = | { kind: 'usable'; cursor: AgentSortCursor } | { kind: 'ordering-mismatch' } @@ -1101,6 +1119,7 @@ export function createAgentMethods( revertAgentVersion: ( searchParameter: FilterQuery, versionIndex: number, + options?: RevertAgentVersionOptions, ) => Promise; countPromotedAgents: () => Promise; addAgentResourceFile: ({ @@ -2658,10 +2677,15 @@ export function createAgentMethods( /** * Reverts an agent to a specific version in its version history. + * + * The MCP server index is always rewritten for the restored tools rather than taken from + * the snapshot: a snapshot may predate the index or name servers its tools no longer use, + * and agent-scoped MCP access is granted from this index. */ async function revertAgentVersion( searchParameter: FilterQuery, versionIndex: number, + options: RevertAgentVersionOptions = {}, ): Promise { const Agent = mongoose.models.Agent as Model; const agent = await Agent.findOne(searchParameter); @@ -2675,6 +2699,12 @@ export function createAgentMethods( const revertToVersion = { ...(agent.versions[versionIndex] as Record) }; const originalRevision = (agent as unknown as IAgent & { updatedAt: Date }).updatedAt; + if ( + options.expectedUpdatedAt != null && + new Date(options.expectedUpdatedAt).getTime() !== new Date(originalRevision).getTime() + ) { + throw new AgentRevisionConflictError(); + } delete revertToVersion._id; delete revertToVersion.id; delete revertToVersion.versions; @@ -2700,6 +2730,21 @@ export function createAgentMethods( } } + if (options.tools) { + revertToVersion.tools = options.tools; + } + const restoredTools = Array.isArray(revertToVersion.tools) + ? (revertToVersion.tools as string[]) + : (agent.tools ?? []); + revertToVersion.mcpServerNames = + options.mcpServerNames ?? + rebuildMCPServerNames( + restoredTools, + Array.isArray(revertToVersion.mcpServerNames) + ? (revertToVersion.mcpServerNames as string[]) + : (agent.mcpServerNames ?? []), + ); + const unsetOnRestore: Record = {}; for (const field of [ 'code_environment_id', @@ -2741,7 +2786,8 @@ export function createAgentMethods( }, ); if (!revertedAgent) { - throw new Error('Agent not found'); + /** The agent was read above, so a miss is the revision filter refusing a newer write. */ + throw new AgentRevisionConflictError(); } return revertedAgent; }