diff --git a/api/server/controllers/agents/filterAuthorizedTools.spec.js b/api/server/controllers/agents/filterAuthorizedTools.spec.js index 3d6513eba1..5a990aad58 100644 --- a/api/server/controllers/agents/filterAuthorizedTools.spec.js +++ b/api/server/controllers/agents/filterAuthorizedTools.spec.js @@ -823,6 +823,41 @@ describe('MCP Tool Authorization', () => { expect(agentInDb.mcpServerNames).not.toContain('Workspace'); }); + test.each([true, false])( + 'does not grant an unindexed Action key with MCP permission: %s', + async (canUse) => { + const tools = ['lookup_action_x_mcp_pay']; + await Agent.updateOne({ id: existingAgentId }, { tools, mcpServerNames: [] }); + mockReq.user.id = canUse + ? existingAgentAuthorId.toString() + : new mongoose.Types.ObjectId().toString(); + mockUserCanUseMCPServers.mockResolvedValue(canUse); + mockReq.params.id = existingAgentId; + mockReq.body = { tools }; + await updateAgentHandler(mockReq, mockRes); + expect((await Agent.findOne({ id: existingAgentId })).mcpServerNames).toEqual([]); + }, + ); + + test('rejects grants revoked after controller authorization', async () => { + const db = require('~/models'); + mockReq.user.id = existingAgentAuthorId.toString(); + mockReq.params.id = existingAgentId; + mockReq.body = { tools: ['existingTool_mcp_authorizedServer'] }; + const update = db.updateAgent; + const spy = jest.spyOn(db, 'updateAgent').mockImplementationOnce(async (...args) => { + await Agent.updateOne({ id: existingAgentId }, { tools: [], mcpServerNames: [] }); + return update(...args); + }); + try { + await updateAgentHandler(mockReq, mockRes); + expect(mockRes.status).toHaveBeenCalledWith(409); + expect((await Agent.findOne({ id: existingAgentId })).mcpServerNames).toEqual([]); + } finally { + spy.mockRestore(); + } + }); + test('should let persistence derive when an unindexed agent retains MCP tools', async () => { /** A legacy or partially migrated agent can hold MCP tools with no stored * mcpServerNames. Pinning the index to [] here would suppress the derivation diff --git a/api/server/controllers/agents/v1.js b/api/server/controllers/agents/v1.js index 32f16a0aa5..229ffa0275 100644 --- a/api/server/controllers/agents/v1.js +++ b/api/server/controllers/agents/v1.js @@ -1353,17 +1353,16 @@ const updateAgentHandler = async (req, res) => { } } updateData.tools = nextTools; - /** The agent's MCP tools are retained verbatim here, so carry its resolved - * names across too. Left unset when the agent has none stored, so - * `updateAgent` can still derive rather than being pinned to an empty - * index that would strip agent-scoped access. */ - if (existingAgent.mcpServerNames?.length) { - updateData.mcpServerNames = existingAgent.mcpServerNames; - } + /** Retained strings alone cannot authorize a previously unindexed server. */ + updateData.mcpServerNames = existingAgent.mcpServerNames ?? []; } } else if (hasToolUpdate) { const existingToolSet = new Set(existingTools); - const newMCPTools = requestedMCPTools.filter((t) => !existingToolSet.has(t)); + const indexedNames = existingAgent.mcpServerNames ?? []; + const newMCPTools = requestedMCPTools.filter((tool) => { + const [, name] = splitMCPToolKey(tool, indexedNames); + return !existingToolSet.has(tool) || !indexedNames.includes(name); + }); /** Names resolved during authorization of the newly added tools. */ const resolvedServerNames = new Set(); @@ -1405,11 +1404,7 @@ const updateAgentHandler = async (req, res) => { } } } - /** Supplying `[]` would pin the index empty and suppress `updateAgent`'s - * derivation, so only assert it when the result is authoritative: either we - * resolved names, or no MCP tool survives and the index genuinely is empty. */ - const retainsMCPTools = (updateData.tools ?? []).some(isMCPTool); - if (resolvedServerNames.size > 0 || !retainsMCPTools) { + if (hasToolUpdate) { updateData.mcpServerNames = Array.from(resolvedServerNames); } } @@ -1429,6 +1424,10 @@ const updateAgentHandler = async (req, res) => { Object.keys(updateData).length > 0 ? await db.updateAgent({ id }, updateData, { updatingUserId: req.user.id, + expectedMCPAccess: { + names: existingAgent.mcpServerNames ?? [], + updatedAt: existingAgent.updatedAt, + }, }) : existingAgent; diff --git a/api/server/routes/agents/actions.access.spec.js b/api/server/routes/agents/actions.access.spec.js new file mode 100644 index 0000000000..a6a0bbc4a9 --- /dev/null +++ b/api/server/routes/agents/actions.access.spec.js @@ -0,0 +1,370 @@ +const express = require('express'); +const mongoose = require('mongoose'); +const request = require('supertest'); +const mongoSanitize = require('express-mongo-sanitize'); +const { MongoMemoryServer } = require('mongodb-memory-server'); +const { encryptV2 } = require('@librechat/data-schemas'); +const { AccessControlService, MCPServersRegistry } = require('@librechat/api'); +const { + PermissionBits, + PrincipalType, + PrincipalModel, + ResourceType, +} = require('librechat-data-provider'); + +jest.mock('~/models', () => { + const mongoose = require('mongoose'); + const { createModels, createMethods } = require('@librechat/data-schemas'); + createModels(mongoose); + return createMethods(mongoose); +}); + +jest.mock('~/server/services/PermissionService', () => { + const mongoose = require('mongoose'); + const { AccessControlService } = require('@librechat/api'); + const acl = new AccessControlService(mongoose); + return { + checkPermission: (args) => acl.checkPermission(args), + findAccessibleResources: (args) => acl.findAccessibleResources(args), + getResourcePermissionsMap: (args) => acl.getResourcePermissionsMap(args), + }; +}); + +jest.mock('~/server/middleware', () => + jest.requireActual('~/server/middleware/accessResources/canAccessAgentResource'), +); +jest.mock('~/config', () => ({ getActionFlowStateManager: jest.fn() })); +jest.mock('~/cache', () => { + const values = new Map(); + return { + getLogStores: () => ({ + get: async (key) => values.get(key), + set: async (key, value) => values.set(key, value), + delete: async (key) => values.delete(key), + }), + }; +}); +jest.mock('~/server/services/Agents/instructionsPrompt', () => ({ + instructionsPromptAccess: { presentForEditor: async ({ agent }) => agent }, +})); + +const db = require('~/models'); +const router = require('./actions'); +let mongoServer; +let acl; +let actorId; +let ownerId; +let agent; +let serverName; +let app; + +async function grantAgent(agentId, userId) { + await mongoose.models.AclEntry.create({ + principalType: PrincipalType.USER, + principalModel: PrincipalModel.USER, + principalId: new mongoose.Types.ObjectId(userId), + resourceType: ResourceType.AGENT, + resourceId: agentId, + permBits: 15, + }); +} + +const postAction = (domain, agentId = agent.id) => + request(app) + .post(`/api/agents/actions/${agentId}`) + .send({ functions: [{ function: { name: 'lookup' } }], metadata: { domain } }); + +beforeAll(async () => { + mongoServer = await MongoMemoryServer.create(); + await mongoose.connect(mongoServer.getUri()); + await db.seedDefaultRoles(); + await db.initializeRoles(); + await mongoose.models.Role.updateOne( + { name: 'USER' }, + { $set: { 'permissions.AGENTS.USE': true, 'permissions.AGENTS.CREATE': true } }, + ); + acl = new AccessControlService(mongoose); +}, 30000); + +afterAll(async () => { + await mongoose.disconnect(); + await mongoServer?.stop(); +}); + +beforeEach(async () => { + for (const model of ['Agent', 'MCPServer', 'Action', 'AclEntry', 'User', 'Token']) { + await mongoose.models[model].deleteMany({}); + } + actorId = new mongoose.Types.ObjectId().toString(); + ownerId = new mongoose.Types.ObjectId().toString(); + serverName = 'pay'; + await mongoose.models.User.create([ + { _id: actorId, email: `${actorId}@example.test`, role: 'USER', provider: 'local' }, + { _id: ownerId, email: `${ownerId}@example.test`, role: 'USER', provider: 'local' }, + ]); + agent = await db.createAgent({ + id: `agent_${new mongoose.Types.ObjectId()}`, + name: 'Actor agent', + author: actorId, + provider: 'test', + model: 'test-model', + tools: [], + }); + await grantAgent(agent._id, actorId); + await mongoose.models.MCPServer.create({ + serverName, + author: ownerId, + config: { + type: 'sse', + url: 'https://private.example.test/mcp', + apiKey: { + source: 'admin', + authorization_type: 'bearer', + key: await encryptV2('fixture-owner-secret'), + }, + }, + }); + + app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + Object.defineProperty(req, 'query', { value: req.query, writable: true }); + next(); + }); + app.use(mongoSanitize()); + /** Session identity is the fixture; the route's role and resource ACL checks are real. */ + app.use((req, _res, next) => { + req.user = { id: actorId, role: 'USER' }; + req.config = { filters: {} }; + next(); + }); + app.use('/api/agents/actions', router); +}); + +describe('Action writes and agent-mediated MCP access', () => { + const oauthMetadata = { + domain: 'https://api.example.test', + auth: { + type: 'oauth', + authorization_url: 'https://1.1.1.1/authorize', + client_url: 'https://1.1.1.1/token', + }, + oauth_client_id: 'fixture-client', + oauth_client_secret: 'fixture-secret', + }; + + const updateOAuthAction = (actionId, metadata = oauthMetadata) => + request(app) + .post(`/api/agents/actions/${agent.id}`) + .send({ + action_id: actionId, + functions: [{ function: { name: 'lookup' } }], + metadata, + }); + + async function createOAuthAction() { + expect((await updateOAuthAction()).status).toBe(200); + const action = await mongoose.models.Action.findOne({ agent_id: agent.id }); + await Promise.all( + [ + { type: 'oauth', identifier: `${actorId}:${action.action_id}` }, + { type: 'oauth_refresh', identifier: `${actorId}:${action.action_id}:refresh` }, + ].map((token) => + db.createToken({ ...token, userId: actorId, token: 'fixture-token', expiresIn: 3600 }), + ), + ); + return action; + } + + it('does not grant an unrelated private MCP server through an Action key', async () => { + const privateServer = await mongoose.models.MCPServer.findOne({ serverName }); + expect( + await acl.checkPermission({ + userId: actorId, + role: 'USER', + resourceType: ResourceType.MCPSERVER, + resourceId: privateServer._id, + requiredPermission: PermissionBits.VIEW, + }), + ).toBe(false); + + const response = await postAction(`x_mcp_${serverName}`); + expect(response.status).toBe(200); + const stored = await db.getAgent({ id: agent.id }); + expect(stored.tools).toContain(`lookup_action_x_mcp_${serverName}`); + const registry = new MCPServersRegistry(mongoose); + expect(await registry.getAllServerConfigs(actorId, undefined, 'USER')).not.toHaveProperty( + serverName, + ); + expect(stored.mcpServerNames).toEqual([]); + }); + + it('preserves an existing MCP grant across Action creation and deletion', async () => { + await db.updateAgent( + { id: agent.id }, + { tools: [`get_action_version_mcp_${serverName}`], mcpServerNames: [serverName] }, + ); + const response = await postAction('https://api.example.test'); + expect(response.status).toBe(200); + const registry = new MCPServersRegistry(mongoose); + expect( + (await registry.getAllServerConfigs(actorId, undefined, 'USER'))[serverName], + ).toMatchObject({ consumeOnly: true }); + + const action = await mongoose.models.Action.findOne({ agent_id: agent.id }); + const deleted = await request(app).delete( + `/api/agents/actions/${agent.id}/${action.action_id}`, + ); + expect(deleted.status).toBe(200); + expect((await db.getAgent({ id: agent.id })).mcpServerNames).toEqual([serverName]); + }); + + it('encodes long Action domains instead of preserving a crafted MCP suffix', async () => { + const response = await postAction('x_mcp_private-payments-server'); + expect(response.status).toBe(200); + const stored = await db.getAgent({ id: agent.id }); + expect(stored.tools[0]).not.toContain('_mcp_'); + expect(stored.mcpServerNames).toEqual([]); + }); + + it('does not allow an actor to write an Action on an unshared agent', async () => { + const other = await db.createAgent({ + id: `agent_${new mongoose.Types.ObjectId()}`, + name: 'Other agent', + author: ownerId, + provider: 'test', + model: 'test-model', + tools: [], + }); + await grantAgent(other._id, ownerId); + const response = await postAction(`x_mcp_${serverName}`, other.id); + expect(response.status).toBe(403); + expect(await mongoose.models.Action.countDocuments({ agent_id: other.id })).toBe(0); + }); + + it('does not save an Action after a conflicting agent write', async () => { + const write = jest.spyOn(db, 'updateAgent').mockRejectedValueOnce({ statusCode: 409 }); + try { + const response = await postAction('https://api.example.test'); + expect(response.status).toBe(409); + expect(await mongoose.models.Action.countDocuments({ agent_id: agent.id })).toBe(0); + } finally { + write.mockRestore(); + } + }); + + it('preserves OAuth tokens and metadata when the agent write conflicts', async () => { + const action = await createOAuthAction(); + const before = await db.getAgent({ id: agent.id }); + const write = jest.spyOn(db, 'updateAgent').mockRejectedValueOnce({ statusCode: 409 }); + try { + const response = await updateOAuthAction(action.action_id, { + ...oauthMetadata, + domain: 'https://new.example.test', + }); + expect(response.status).toBe(409); + expect(await mongoose.models.Token.countDocuments({ userId: actorId })).toBe(2); + expect((await db.getAgent({ id: agent.id })).tools).toEqual(before.tools); + expect((await mongoose.models.Action.findById(action._id)).metadata).toEqual(action.metadata); + } finally { + write.mockRestore(); + } + }); + + it('preserves OAuth tokens when the agent disappears before the database write reads it', async () => { + const action = await createOAuthAction(); + const updateAgent = db.updateAgent; + const write = jest.spyOn(db, 'updateAgent').mockImplementationOnce(async (...args) => { + await mongoose.models.Agent.deleteOne({ id: agent.id }); + return updateAgent(...args); + }); + try { + const response = await updateOAuthAction(action.action_id, { + ...oauthMetadata, + domain: 'https://new.example.test', + }); + expect(response.status).toBe(409); + expect(await mongoose.models.Token.countDocuments({ userId: actorId })).toBe(2); + expect((await mongoose.models.Action.findById(action._id)).metadata).toEqual(action.metadata); + } finally { + write.mockRestore(); + } + }); + + it.each([false, true])( + 'invalidates OAuth tokens before publishing metadata only when the target changes: %s', + async (targetChanged) => { + const action = await createOAuthAction(); + const metadata = { + ...oauthMetadata, + domain: targetChanged ? 'https://new.example.test' : oauthMetadata.domain, + }; + const updateAction = db.updateAction; + const write = jest.spyOn(db, 'updateAction').mockImplementation(async (...args) => { + expect(await mongoose.models.Token.countDocuments({ userId: actorId })).toBe( + targetChanged ? 0 : 2, + ); + return updateAction(...args); + }); + try { + expect((await updateOAuthAction(action.action_id, metadata)).status).toBe(200); + expect(write).toHaveBeenCalledTimes(1); + expect((await mongoose.models.Action.findById(action._id)).metadata.domain).toBe( + metadata.domain, + ); + } finally { + write.mockRestore(); + } + }, + ); + + it('does not publish new OAuth metadata when token invalidation fails', async () => { + const action = await createOAuthAction(); + const remove = jest.spyOn(db, 'deleteTokens').mockRejectedValue(new Error('fixture failure')); + try { + const response = await updateOAuthAction(action.action_id, { + ...oauthMetadata, + domain: 'https://new.example.test', + }); + expect(response.status).toBe(500); + expect(response.body).toEqual({ message: 'Trouble updating the Agent Action' }); + expect(await mongoose.models.Token.countDocuments({ userId: actorId })).toBe(2); + expect((await mongoose.models.Action.findById(action._id)).metadata).toEqual(action.metadata); + } finally { + remove.mockRestore(); + } + }); + + it('does not delete an Action after a conflicting agent write', async () => { + expect((await postAction('https://api.example.test')).status).toBe(200); + const action = await mongoose.models.Action.findOne({ agent_id: agent.id }); + const write = jest.spyOn(db, 'updateAgent').mockRejectedValueOnce({ statusCode: 409 }); + try { + const response = await request(app).delete( + `/api/agents/actions/${agent.id}/${action.action_id}`, + ); + expect(response.status).toBe(409); + expect(await mongoose.models.Action.countDocuments({ agent_id: agent.id })).toBe(1); + } finally { + write.mockRestore(); + } + }); +}); + +it.each(['registry', 'legacy'])( + 'does not transfer a grant after %s server deletion', + async (mode) => { + await db.updateAgent({ id: agent.id }, { tools: ['lookup_mcp_pay'], mcpServerNames: ['pay'] }); + const registry = new MCPServersRegistry(mongoose); + if (mode === 'registry') await registry.removeServer('pay', 'DB', ownerId); + else await mongoose.models.MCPServer.deleteOne({ serverName: 'pay' }); + const replacement = await db.createMCPServer({ + author: ownerId, + config: { title: 'pay', type: 'sse', url: 'https://replacement.example.test/mcp' }, + }); + expect(replacement.serverName).not.toBe('pay'); + expect(await registry.getAllServerConfigs(actorId, undefined, 'USER')).not.toHaveProperty( + replacement.serverName, + ); + }, +); diff --git a/api/server/routes/agents/actions.js b/api/server/routes/agents/actions.js index ea7f3f42d3..291dd22383 100644 --- a/api/server/routes/agents/actions.js +++ b/api/server/routes/agents/actions.js @@ -3,6 +3,7 @@ const { nanoid } = require('nanoid'); const { logger } = require('@librechat/data-schemas'); const { generateCheckAccess, + getAgentActionWriteStatus, planAgentActionUpdate, isActionDomainAllowed, legacyActionDomainEncode, @@ -224,11 +225,6 @@ router.post( return res.status(400).json({ message: error.message }); } - if (plannedUpdate.deleteOAuthTokens && requestedActionId) { - // Keep the callback URL stable while preventing old OAuth tokens from following a new target. - await deleteActionOAuthTokens(requestedActionId); - } - // Force version update since actions are changing const updatedAgent = await db.updateAgent( { id: agent_id }, @@ -236,8 +232,13 @@ router.post( { updatingUserId: req.user.id, forceVersion: true, + preserveMCPAccess: true, }, ); + if (plannedUpdate.deleteOAuthTokens && requestedActionId) { + // A conflict must preserve tokens; invalidate them before publishing the new target. + await deleteActionOAuthTokens(requestedActionId); + } await attachOwnerContacts([updatedAgent]); // Only update user field for new actions @@ -277,7 +278,7 @@ router.post( } catch (error) { const message = 'Trouble updating the Agent Action'; logger.error(message, error); - res.status(500).json({ message }); + res.status(getAgentActionWriteStatus(error)).json({ message }); } }, ); @@ -329,7 +330,7 @@ router.delete( await db.updateAgent( { id: agent_id }, { tools: updatedTools, actions: updatedActions }, - { updatingUserId: req.user.id, forceVersion: true }, + { updatingUserId: req.user.id, forceVersion: true, preserveMCPAccess: true }, ); const deleted = await db.deleteAction({ actionId: action_id, agentId: agent_id }); if (!deleted) { @@ -342,7 +343,7 @@ router.delete( } catch (error) { const message = 'Trouble deleting the Agent Action'; logger.error(message, error); - res.status(500).json({ message }); + res.status(getAgentActionWriteStatus(error)).json({ message }); } }, ); diff --git a/packages/api/src/actions/update.spec.ts b/packages/api/src/actions/update.spec.ts index ed356100af..c1f59ac60c 100644 --- a/packages/api/src/actions/update.spec.ts +++ b/packages/api/src/actions/update.spec.ts @@ -33,6 +33,7 @@ import { buildActionOAuthTokenDeleteQueries, legacyActionDomainEncode, planAgentActionUpdate, + getAgentActionWriteStatus, } from './update'; const specFor = (serverUrl: string, operationId = 'echoMessage'): string => @@ -56,6 +57,16 @@ const toolFor = (name: string) => ({ }, }); +describe('getAgentActionWriteStatus', () => { + it('maps revision conflicts to 409', () => { + expect(getAgentActionWriteStatus({ statusCode: 409 })).toBe(409); + }); + it.each([undefined, null, new Error('database failure'), { statusCode: 403 }])( + 'maps unexpected failures to a generic 500', + (error) => expect(getAgentActionWriteStatus(error)).toBe(500), + ); +}); + const storedServiceMetadata: ActionMetadata = { domain: 'https://api.example.com', raw_spec: specFor('https://api.example.com/v1'), diff --git a/packages/api/src/actions/update.ts b/packages/api/src/actions/update.ts index 03bb3ba861..7726d736e1 100644 --- a/packages/api/src/actions/update.ts +++ b/packages/api/src/actions/update.ts @@ -7,6 +7,16 @@ import { mergeAgentActionTools } from './tools'; export const ACTION_CREDENTIAL_REFRESH_MESSAGE = 'Action credentials must be re-entered when changing the domain, OpenAPI server URL, or authentication settings'; +/** Map a lost agent revision to a retryable conflict without exposing database errors. */ +export function getAgentActionWriteStatus(error: unknown): 409 | 500 { + return error != null && + typeof error === 'object' && + 'statusCode' in error && + error.statusCode === 409 + ? 409 + : 500; +} + type StoredActionForUpdate = { metadata?: ActionMetadata | null; }; diff --git a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts index ae2d9b3dd6..44fe0e7d9b 100644 --- a/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts +++ b/packages/api/src/mcp/registry/__tests__/ServerConfigsDB.test.ts @@ -1001,7 +1001,7 @@ describe('ServerConfigsDB', () => { ).not.toContain('another-users-secret'); }); - it('does not reuse saved keys when the same server name is recreated at a new URL', async () => { + it('does not reuse the name or saved keys when a deleted server is replaced at a new URL', async () => { const created = await serverConfigsDB.add('temp-name', config, userId); const oldField = Object.keys(created.config.customUserVars!)[0]; const savedVars = await saveUserKey(created.serverName, oldField); @@ -1015,7 +1015,7 @@ describe('ServerConfigsDB', () => { }, userId, ); - expect(recreated.serverName).toBe(created.serverName); + expect(recreated.serverName).not.toBe(created.serverName); expect(getMissingCustomUserVars(recreated.config, savedVars)).toHaveLength(1); expect( JSON.stringify(processMCPEnv({ options: recreated.config, customUserVars: savedVars })), diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.ts index 8456b903c7..fc8776ec76 100644 --- a/packages/data-schemas/src/methods/agent.spec.ts +++ b/packages/data-schemas/src/methods/agent.spec.ts @@ -943,6 +943,152 @@ describe('Agent Methods', () => { expect(updatedAgent!.mcpServerNames).toEqual(['authorizedServer']); }); + test('an Action write cannot derive MCP access from a constructed tool key', async () => { + const { agentId, authorId } = createTestIds(); + await createAgent({ + id: agentId, + name: 'Action-only Agent', + provider: 'test', + model: 'test-model', + author: authorId, + tools: [], + }); + + const updated = await updateAgent( + { id: agentId }, + { tools: ['lookup_action_x_mcp_private-server'] }, + { preserveMCPAccess: true }, + ); + + expect(updated!.mcpServerNames).toEqual([]); + expect(await methods.getAgentIdsByMCPServerName('private-server')).toEqual([]); + }); + + test('an Action write preserves existing MCP access without adding a new server', async () => { + const { agentId, authorId } = createTestIds(); + const mcpTool = `get_action_version${Constants.mcp_delimiter}Google${Constants.mcp_delimiter}Workspace`; + const server = `Google${Constants.mcp_delimiter}Workspace`; + await createAgent({ + id: agentId, + name: 'Mixed Agent', + provider: 'test', + model: 'test-model', + author: authorId, + tools: [mcpTool], + mcpServerNames: [server], + }); + + const updated = await updateAgent( + { id: agentId }, + { + tools: [mcpTool, 'lookup_action_x_mcp_private-server'], + mcpServerNames: ['private-server'], + }, + { preserveMCPAccess: true }, + ); + + expect(updated!.mcpServerNames).toEqual([server]); + expect(await methods.getAgentIdsByMCPServerName('private-server')).toEqual([]); + }); + + test('an Action write fails closed for a legacy agent without an MCP index', async () => { + const { agentId, authorId } = createTestIds(); + await createAgent({ + id: agentId, + name: 'Legacy Action Agent', + provider: 'test', + model: 'test-model', + author: authorId, + tools: [], + }); + await Agent.updateOne({ id: agentId }, { $unset: { mcpServerNames: 1 } }); + + const updated = await updateAgent( + { id: agentId }, + { tools: ['lookup_action_x_mcp_private-server'] }, + { preserveMCPAccess: true }, + ); + + expect(updated!.mcpServerNames).toEqual([]); + }); + + test('an Action write drops existing MCP access when its last tool is removed', async () => { + const { agentId, authorId } = createTestIds(); + await createAgent({ + id: agentId, + name: 'Detached MCP Agent', + provider: 'test', + model: 'test-model', + author: authorId, + tools: ['search_mcp_existing-server'], + mcpServerNames: ['existing-server'], + }); + + const updated = await updateAgent( + { id: agentId }, + { tools: ['lookup_action_api---example---com'] }, + { preserveMCPAccess: true }, + ); + + expect(updated!.mcpServerNames).toEqual([]); + }); + + test.each(['advanced', 'unchanged'])( + 'an Action write cannot restore revoked MCP access with an %s timestamp', + async (revision) => { + const { agentId, authorId } = createTestIds(); + const tools = ['search_mcp_existing-server']; + await createAgent({ + id: agentId, + name: 'Concurrent Action Agent', + provider: 'test', + model: 'test-model', + author: authorId, + tools, + mcpServerNames: ['existing-server'], + }); + const originalFindOne = Agent.findOne.bind(Agent); + const read = jest.spyOn(Agent, 'findOne').mockImplementationOnce((...args) => { + const query = originalFindOne(...args); + const originalExec = query.exec.bind(query); + jest.spyOn(query, 'exec').mockImplementationOnce(async () => { + const snapshot = await originalExec(); + const snapshotRevision = snapshot?.get('updatedAt'); + if (!(snapshotRevision instanceof Date)) { + throw new Error('Agent fixture has no revision'); + } + await Agent.updateOne( + { id: agentId }, + { + $set: { + tools: [], + mcpServerNames: [], + updatedAt: + revision === 'unchanged' ? snapshotRevision : new Date(Date.now() + 1000), + }, + }, + { timestamps: false }, + ); + return snapshot; + }); + return query; + }); + + try { + await expect( + updateAgent( + { id: agentId }, + { tools: [...tools, 'lookup_action_api---example---com'] }, + { preserveMCPAccess: true }, + ), + ).rejects.toThrow('Agent changed during Action update'); + } finally { + read.mockRestore(); + } + expect((await getAgent({ id: agentId }))!.mcpServerNames).toEqual([]); + }, + ); + test('should prune nonexistent skill ids from the allowlist on create', async () => { const { agentId, authorId } = createTestIds(); const realSkill = await mongoose.models.Skill.create({ diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.ts index 17e0c21598..58e2d1a2c6 100644 --- a/packages/data-schemas/src/methods/agent.ts +++ b/packages/data-schemas/src/methods/agent.ts @@ -265,8 +265,8 @@ export interface RevertAgentVersionOptions { export class AgentRevisionConflictError extends Error { readonly statusCode = 409; - constructor() { - super('Agent was modified while reverting; reload and try again'); + constructor(message = 'Agent was modified while reverting; reload and try again') { + super(message); this.name = 'AgentRevisionConflictError'; } } @@ -757,9 +757,13 @@ function extractMCPServerNames(tools: string[] | undefined | null): string[] { * ambiguous trailing-segment derivation, which cannot tell a config server's * suffix from a real DB server name. */ -function rebuildMCPServerNames(tools: string[] | undefined | null, priorNames: string[]): string[] { +function rebuildMCPServerNames( + tools: string[] | undefined | null, + priorNames: string[], + preserveMCPAccess = false, +): string[] { if (priorNames.length === 0) { - return extractMCPServerNames(tools); + return preserveMCPAccess ? [] : extractMCPServerNames(tools); } const retained = new Set(); @@ -778,8 +782,10 @@ function rebuildMCPServerNames(tools: string[] | undefined | null, priorNames: s } } - for (const name of extractMCPServerNames(unmatched)) { - retained.add(name); + if (!preserveMCPAccess) { + for (const name of extractMCPServerNames(unmatched)) { + retained.add(name); + } } return Array.from(retained); } @@ -1110,6 +1116,9 @@ export function createAgentMethods( updatingUserId?: string | null; forceVersion?: boolean; skipVersioning?: boolean; + /** Action edits may retain existing MCP grants, but cannot derive new grants from keys. */ + preserveMCPAccess?: boolean; + expectedMCPAccess?: { names: string[]; updatedAt?: Date }; }, ) => Promise; updateAgentAvatar: (params: { @@ -1500,6 +1509,9 @@ export function createAgentMethods( updatingUserId?: string | null; forceVersion?: boolean; skipVersioning?: boolean; + /** Action edits may retain existing MCP grants, but cannot derive new grants from keys. */ + preserveMCPAccess?: boolean; + expectedMCPAccess?: { names: string[]; updatedAt?: Date }; } = {}, ): Promise { const Agent = mongoose.models.Agent as Model; @@ -1510,6 +1522,11 @@ export function createAgentMethods( let suppressedVersionEntry = false; const currentAgent = await Agent.findOne(searchParameter); + if (!currentAgent && (options.preserveMCPAccess || options.expectedMCPAccess)) { + throw new AgentRevisionConflictError( + 'Agent changed during Action update; reload and try again', + ); + } const currentRevision = (currentAgent as (IAgent & { updatedAt: Date }) | null)?.updatedAt; if (currentAgent) { const currentObject = currentAgent.toObject() as unknown as Record; @@ -1553,11 +1570,13 @@ export function createAgentMethods( | string[] | undefined; const mcpServerNames = - supplied ?? - rebuildMCPServerNames( - (directUpdates as Record).tools as string[], - (currentAgent.mcpServerNames as string[] | undefined) ?? [], - ); + !options.preserveMCPAccess && supplied !== undefined + ? supplied + : rebuildMCPServerNames( + (directUpdates as Record).tools as string[], + (currentAgent.mcpServerNames as string[] | undefined) ?? [], + options.preserveMCPAccess, + ); (directUpdates as Record).mcpServerNames = mcpServerNames; updateData.mcpServerNames = mcpServerNames; } @@ -1677,14 +1696,40 @@ export function createAgentMethods( }), ); } + let updateFilter = searchParameter; + if (currentAgent && (nextEnvironmentIds.length > 0 || options.preserveMCPAccess)) { + updateFilter = { ...searchParameter, _id: currentAgent._id, updatedAt: currentRevision }; + } + if (currentAgent && options.preserveMCPAccess) { + const priorNames = currentAgent.mcpServerNames ?? []; + /** Timestamps can collide within a millisecond; bind the actual grants being retained. */ + updateFilter = { + $and: [ + updateFilter, + priorNames.length > 0 + ? { mcpServerNames: priorNames } + : { $or: [{ mcpServerNames: [] }, { mcpServerNames: null }] }, + ], + }; + } + if (options.expectedMCPAccess) { + const { names, updatedAt } = options.expectedMCPAccess; + updateFilter = { + $and: [ + updateFilter, + ...(updatedAt ? [{ updatedAt }] : []), + names.length > 0 + ? { mcpServerNames: names } + : { $or: [{ mcpServerNames: [] }, { mcpServerNames: null }] }, + ], + }; + } const updatedAgent = await withCodeEnvironmentReferences( mongoose, nextEnvironmentIds, async () => (await Agent.findOneAndUpdate( - currentAgent == null || nextEnvironmentIds.length === 0 - ? searchParameter - : { ...searchParameter, _id: currentAgent._id, updatedAt: currentRevision }, + updateFilter, updateData, mongoOptions, ).lean()) as IAgent | null, @@ -1700,6 +1745,12 @@ export function createAgentMethods( }, ); + if (currentAgent && (options.preserveMCPAccess || options.expectedMCPAccess) && !updatedAgent) { + throw new AgentRevisionConflictError( + 'Agent changed during Action update; reload and try again', + ); + } + /** `version` is a response-only field holding the count of `versions`. It is reported * here so a suppressed entry keeps the shape callers saw before the write was fixed. * It answers "was a version recorded", never "did the update apply". The two stopped diff --git a/packages/data-schemas/src/methods/mcpServer.spec.ts b/packages/data-schemas/src/methods/mcpServer.spec.ts index 138bd7a09a..9dc22e6480 100644 --- a/packages/data-schemas/src/methods/mcpServer.spec.ts +++ b/packages/data-schemas/src/methods/mcpServer.spec.ts @@ -8,6 +8,7 @@ import { } from 'librechat-data-provider'; import type { MCPOptions } from 'librechat-data-provider'; import type * as t from '~/types'; +import { createMCPNameModel } from '../models/mcpName'; import { createMCPServerMethods } from './mcpServer'; import { createAclEntryMethods } from './aclEntry'; import mcpServerSchema from '~/schema/mcpServer'; @@ -22,6 +23,7 @@ let methods: ReturnType; beforeAll(async () => { mongoServer = await MongoMemoryServer.create(); const mongoUri = mongoServer.getUri(); + createMCPNameModel(mongoose); MCPServer = mongoose.models.MCPServer || mongoose.model('MCPServer', mcpServerSchema); if (!mongoose.models.AclEntry) { mongoose.model('AclEntry', aclEntrySchema); @@ -45,6 +47,7 @@ afterAll(async () => { beforeEach(async () => { await mongoose.connection.dropDatabase(); + await mongoose.models.MCPName.syncIndexes(); }); describe('MCPServer Model Tests', () => { @@ -879,3 +882,16 @@ describe('MCPServer Model Tests', () => { }); }); }); + +test.each(['single', 'bulk'])( + 'deleted server names remain reserved after %s deletion', + async (mode) => { + const author = new mongoose.Types.ObjectId(); + const config: MCPOptions = { title: 'Reserved', type: 'sse', url: 'https://example.test/mcp' }; + const first = await methods.createMCPServer({ author, config }); + if (mode === 'single') await methods.deleteMCPServer(first.serverName); + else await methods.deleteMCPServersWithAcl([first._id.toString()]); + const next = await methods.createMCPServer({ author, config }); + expect(next.serverName).not.toBe(first.serverName); + }, +); diff --git a/packages/data-schemas/src/methods/mcpServer.ts b/packages/data-schemas/src/methods/mcpServer.ts index cfcd012f3f..165e5d5e9b 100644 --- a/packages/data-schemas/src/methods/mcpServer.ts +++ b/packages/data-schemas/src/methods/mcpServer.ts @@ -137,7 +137,21 @@ export function createMCPServerMethods( .select('serverName') .lean>(); + const reservations = await mongoose.models.MCPName.find({ + name: { $regex: matchingNamePattern }, + }) + .select('name') + .lean>(); + const referenced = await mongoose.models.Agent?.find({ + mcpServerNames: { $regex: matchingNamePattern }, + }) + .select('mcpServerNames') + .lean>(); const existingNames = new Set([ + ...(referenced ?? []).flatMap((agent) => + agent.mcpServerNames.filter((name) => matchingNamePattern.test(name)), + ), + ...reservations.map((entry) => entry.name), ...existing.map((server) => server.serverName), ...Array.from(reservedServerNames).filter((serverName) => matchingNamePattern.test(serverName), @@ -188,6 +202,8 @@ export function createMCPServerMethods( serverName = `mcp-${nanoid(16)}`; } + await mongoose.models.MCPName.init(); + await mongoose.models.MCPName.create({ name: serverName }); const newServer = await MCPServer.create({ serverName, normalizedServerName: normalizeServerName(serverName), @@ -367,6 +383,12 @@ export function createMCPServerMethods( */ async function deleteMCPServer(serverName: string): Promise { const MCPServer = mongoose.models.MCPServer as Model; + await mongoose.models.MCPName.init(); + await mongoose.models.MCPName.updateOne( + { name: serverName }, + { $setOnInsert: { name: serverName } }, + { upsert: true }, + ); return await MCPServer.findOneAndDelete({ serverName }).lean(); } @@ -528,6 +550,19 @@ export function createMCPServerMethods( } const MCPServer = mongoose.models.MCPServer as Model; const objectIds = ids.map((id) => new mongoose.Types.ObjectId(id)); + const servers = await MCPServer.find({ _id: { $in: objectIds } }) + .select('serverName') + .lean>(); + await mongoose.models.MCPName.init(); + await Promise.all( + servers.map(({ serverName }) => + mongoose.models.MCPName.updateOne( + { name: serverName }, + { $setOnInsert: { name: serverName } }, + { upsert: true }, + ), + ), + ); const result = await MCPServer.deleteMany({ _id: { $in: objectIds } }); /** ACL entries are the retry discovery key for sole-owned servers, so they go last. */ await mongoose.models.AclEntry.deleteMany({ diff --git a/packages/data-schemas/src/models/index.ts b/packages/data-schemas/src/models/index.ts index 6aa56df687..a4be3c5d19 100644 --- a/packages/data-schemas/src/models/index.ts +++ b/packages/data-schemas/src/models/index.ts @@ -43,6 +43,7 @@ import { createConversationModel } from './convo'; import { createToolCallModel } from './toolCall'; import { createAclEntryModel } from './aclEntry'; import { createAuditLogModel } from './auditLog'; +import { createMCPNameModel } from './mcpName'; import { createSessionModel } from './session'; import { createPasskeyModel } from './passkey'; import { createBalanceModel } from './balance'; @@ -91,6 +92,7 @@ export function createModels(mongoose: typeof import('mongoose')): { ChannelFeedbackEvent: ReturnType; ChannelFeedback: ReturnType; AgentCategory: ReturnType; + MCPName: ReturnType; MCPServer: ReturnType; Role: ReturnType; Action: ReturnType; @@ -156,6 +158,7 @@ export function createModels(mongoose: typeof import('mongoose')): { ChannelFeedbackEvent: createChannelFeedbackEventModel(mongoose), ChannelFeedback: createChannelFeedbackModel(mongoose), AgentCategory: createAgentCategoryModel(mongoose), + MCPName: createMCPNameModel(mongoose), MCPServer: createMCPServerModel(mongoose), Role: createRoleModel(mongoose), Action: createActionModel(mongoose), diff --git a/packages/data-schemas/src/models/mcpName.ts b/packages/data-schemas/src/models/mcpName.ts new file mode 100644 index 0000000000..4e6591d2a4 --- /dev/null +++ b/packages/data-schemas/src/models/mcpName.ts @@ -0,0 +1,16 @@ +import { Schema } from 'mongoose'; +import type { Model } from 'mongoose'; +import { applyTenantIsolation } from '~/models/plugins/tenantIsolation'; + +interface MCPName { + name: string; + tenantId?: string; +} + +const schema = new Schema({ name: { type: String, required: true, unique: true } }); + +/** Durable reservations survive server and account deletion. */ +export function createMCPNameModel(mongoose: typeof import('mongoose')): Model { + applyTenantIsolation(schema); + return mongoose.models.MCPName || mongoose.model('MCPName', schema); +}