Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(agent-builder): install marketplace MCPs from the server as connectors (#23028)

Lobehub Coder02f0ea74ff63
diff --git a/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts b/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts
index b397061f8e1..3f33153e3bf 100644
--- a/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/composio.workspaceScope.test.ts
@@ -61,6 +61,7 @@ describe('composioRouter β€” workspace scoping (workspace-agent connector bug)',
workspaceMocks.getConnectorMemberManage.mockResolvedValue('all_members');
connectorModelMock = {
create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
+ createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'conn-new' } }),
findScopedByIdentifier: vi.fn().mockResolvedValue(null),
update: vi.fn().mockResolvedValue(undefined),
};
@@ -178,7 +179,7 @@ describe('composioRouter β€” workspace scoping (workspace-agent connector bug)',
memberCaller().createConnection({ appSlug: 'gmail', identifier: 'gmail', label: 'Gmail' }),
).rejects.toMatchObject({ code: 'FORBIDDEN' });
- expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
});
it('still lets a workspace admin connect when members are restricted', async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/connector.managePolicy.test.ts b/apps/server/src/routers/lambda/__tests__/connector.managePolicy.test.ts
index bb0012fec9b..346cab1c794 100644
--- a/apps/server/src/routers/lambda/__tests__/connector.managePolicy.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/connector.managePolicy.test.ts
@@ -68,6 +68,7 @@ describe('connectorRouter manage policy', () => {
mocks.getConnectorMemberManage.mockResolvedValue('all_members');
connectorModelMock = {
create: vi.fn().mockResolvedValue({ id: 'created' }),
+ createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'created' } }),
findById: vi.fn(),
findScopedByIdentifier: vi.fn().mockResolvedValue(null),
update: vi.fn(),
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
index 269c032aadd..b7a9de4760d 100644
--- a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
@@ -64,7 +64,7 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
vi.clearAllMocks();
connectorModelMock = {
- create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
+ createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'conn-new' } }),
queryByIdentifiers: vi.fn().mockResolvedValue([]),
update: vi.fn(),
};
@@ -103,7 +103,7 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
const result = await callerFor().syncPluginTools({ identifier: 'dockpit' });
expect(result).toEqual({ connectorId: null, toolCount: 0 });
- expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
});
@@ -130,7 +130,7 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
expect(result.connectorId).toBe('conn-new');
expect(result.toolCount).toBe(1);
- expect(connectorModelMock.create).toHaveBeenCalledTimes(1);
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledTimes(1);
expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(
'conn-new',
expect.arrayContaining([expect.objectContaining({ toolName: 'web_search' })]),
@@ -162,7 +162,7 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
const result = await callerFor().syncPluginTools({ identifier: 'github' });
expect(result).toEqual({ connectorId: null, toolCount: 0 });
- expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
});
@@ -177,7 +177,7 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
await callerFor().syncPluginTools({ identifier: 'gmail' });
- expect(connectorModelMock.create).toHaveBeenCalledWith(
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
expect.objectContaining({
metadata: expect.objectContaining({
composio: expect.objectContaining({ connectedAccountId: 'ca-gmail' }),
@@ -250,7 +250,7 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
expect(result).toEqual({ connectorId: 'conn-installed', toolCount: 0 });
expect(connectorModelMock.update).not.toHaveBeenCalled();
- expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
});
@@ -267,7 +267,7 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
const result = await callerFor().syncPluginTools({ identifier: 'x' });
expect(result).toEqual({ connectorId: null, toolCount: 0 });
- expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
});
it('throws NOT_FOUND when the plugin row does not exist (unchanged behavior)', async () => {
@@ -292,7 +292,7 @@ describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
const result = await callerFor().syncPluginTools({ identifier: 'dockpit' });
expect(result).toEqual({ connectorId: null, toolCount: 0 });
- expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
});
it('still throws NOT_FOUND for non-customPlugin rows with no manifest', async () => {
@@ -326,10 +326,10 @@ describe('connectorRouter.create β€” sourceType handling on existing rows', () =
beforeEach(() => {
vi.clearAllMocks();
connectorModelMock = {
- create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
+ createUnlessIdentifierHeld: vi.fn().mockResolvedValue({ created: { id: 'conn-new' } }),
findScopedByIdentifier: vi.fn().mockResolvedValue(null),
queryByIdentifiers: vi.fn().mockResolvedValue([]),
- update: vi.fn().mockResolvedValue(undefined),
+ update: vi.fn().mockResolvedValue(true),
};
connectorToolModelMock = { upsertMany: vi.fn() };
pluginModelMock = { findById: vi.fn() };
@@ -371,7 +371,7 @@ describe('connectorRouter.create β€” sourceType handling on existing rows', () =
const result = await caller().create(baseCustomInput);
expect(result).toEqual({ id: 'conn-existing', isNew: false });
- expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
expect(connectorModelMock.update).toHaveBeenCalledTimes(1);
expect(connectorModelMock.update).toHaveBeenCalledWith(
'conn-existing',
@@ -403,11 +403,92 @@ describe('connectorRouter.create β€” sourceType handling on existing rows', () =
const result = await caller().create(baseCustomInput);
expect(result).toEqual({ id: 'conn-new', isNew: true });
- expect(connectorModelMock.create).toHaveBeenCalledWith(
+ expect(connectorModelMock.createUnlessIdentifierHeld).toHaveBeenCalledWith(
expect.objectContaining({ identifier: 'legacy-mcp', sourceType: 'custom' }),
);
expect(connectorModelMock.update).not.toHaveBeenCalled();
});
+
+ it('re-adds over a base row another writer claimed after the lookup, adding none', async () => {
+ // An Agent Builder install claimed the identifier between this lookup and
+ // the insert: the add takes the claimed row, as if the lookup had found it.
+ connectorModelMock.findScopedByIdentifier.mockResolvedValueOnce(null);
+ connectorModelMock.createUnlessIdentifierHeld.mockResolvedValueOnce({
+ holder: { agentId: null, id: 'conn-claimed', identifier: 'legacy-mcp', userId: 'user_test' },
+ });
+
+ const result = await caller().create(baseCustomInput);
+
+ expect(result).toEqual({ id: 'conn-claimed', isNew: false });
+ expect(connectorModelMock.create).toBeUndefined();
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ 'conn-claimed',
+ expect.objectContaining({ mcpServerUrl: 'https://mcp.example.com', sourceType: 'custom' }),
+ );
+ });
+
+ it('re-adds over the row that replaced the one it read, not over the deleted one', async () => {
+ // An Agent Builder install took over the stale unfinished row this add read
+ // (deleting it) before the update: the add lands on the install's new row.
+ const stale = {
+ agentId: null,
+ id: 'conn-stale',
+ identifier: 'legacy-mcp',
+ userId: 'user_test',
+ };
+ connectorModelMock.findScopedByIdentifier
+ .mockResolvedValueOnce(stale)
+ .mockResolvedValueOnce({ ...stale, id: 'conn-replacement' });
+ connectorModelMock.update.mockResolvedValueOnce(false);
+
+ const result = await caller().create(baseCustomInput);
+
+ expect(result).toEqual({ id: 'conn-replacement', isNew: false });
+ expect(connectorModelMock.update).toHaveBeenLastCalledWith(
+ 'conn-replacement',
+ expect.objectContaining({ mcpServerUrl: 'https://mcp.example.com' }),
+ );
+ expect(connectorModelMock.createUnlessIdentifierHeld).not.toHaveBeenCalled();
+ });
+
+ it('reports a conflict instead of a deleted id when the retry misses too', async () => {
+ connectorModelMock.findScopedByIdentifier.mockResolvedValue({
+ agentId: null,
+ id: 'conn-gone',
+ identifier: 'legacy-mcp',
+ userId: 'user_test',
+ });
+ connectorModelMock.update.mockResolvedValue(false);
+
+ await expect(caller().create(baseCustomInput)).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect(connectorModelMock.update).toHaveBeenCalledTimes(2);
+ });
+
+ it('moves an agent connector to the base scope only through the identifier lock', async () => {
+ const AGENT_ROW_ID = '9f1f6f30-0000-4000-8000-000000000003';
+ connectorModelMock.findById = vi.fn().mockResolvedValue({
+ agentId: 'agent-1',
+ id: AGENT_ROW_ID,
+ identifier: 'legacy-mcp',
+ userId: 'user_test',
+ });
+ connectorModelMock.moveToBaseUnlessIdentifierHeld = vi
+ .fn()
+ .mockResolvedValueOnce({ moved: true })
+ .mockResolvedValueOnce({ holder: { id: 'conn-base' } });
+
+ await expect(caller().unbindAgent({ connectorId: AGENT_ROW_ID })).resolves.toEqual({
+ id: AGENT_ROW_ID,
+ });
+ await expect(caller().unbindAgent({ connectorId: AGENT_ROW_ID })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(connectorModelMock.moveToBaseUnlessIdentifierHeld).toHaveBeenCalledWith(
+ AGENT_ROW_ID,
+ 'legacy-mcp',
+ );
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
});
describe('connectorRouter.delete β€” agent connector unpins from the owning agent ', () => {
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts
index 9132d6290df..9bf9a16379e 100644
--- a/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/connector.syncToolsFromClientById.test.ts
@@ -128,6 +128,40 @@ describe('connectorRouter.syncToolsFromClientById', () => {
]);
});
+ it("holds a desktop's listing of an agent-installed server to the market tool policies", async () => {
+ connectorModelMock.findById.mockResolvedValue({
+ id: CONNECTOR_ID,
+ identifier: 'remote-mcp',
+ metadata: { marketplaceToolPolicies: { search: null, send: 'required' } },
+ userId: 'user_test',
+ });
+
+ await caller().syncToolsFromClientById({
+ id: CONNECTOR_ID,
+ tools: [
+ { toolName: 'search' },
+ { humanIntervention: 'never', toolName: 'send' },
+ { humanIntervention: 'never', toolName: 'exfiltrate' },
+ ],
+ });
+
+ expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(CONNECTOR_ID, [
+ expect.objectContaining({ defaultPermission: 'auto', metadata: null, toolName: 'search' }),
+ // The market's policy, not the listing's
+ expect.objectContaining({
+ defaultPermission: 'needs_approval',
+ metadata: null,
+ toolName: 'send',
+ }),
+ // Whatever the listing says, the market never vouched for it
+ expect.objectContaining({
+ defaultPermission: 'needs_approval',
+ metadata: { mandatoryApproval: true },
+ toolName: 'exfiltrate',
+ }),
+ ]);
+ });
+
// The connector manifest carries one permission per tool, so a rule list that
// asks for approval for some arguments must not land as `auto`
it('makes a new tool need approval when any of its intervention rules requires it', async () => {
diff --git a/apps/server/src/routers/lambda/_helpers/clientToolSyncInputs.ts b/apps/server/src/routers/lambda/_helpers/clientToolSyncInputs.ts
index c620837716c..d7a100e6cc6 100644
--- a/apps/server/src/routers/lambda/_helpers/clientToolSyncInputs.ts
+++ b/apps/server/src/routers/lambda/_helpers/clientToolSyncInputs.ts
@@ -1,4 +1,8 @@
-import { withMandatoryApprovalMark } from '@lobechat/const';
+import {
+ marketplaceToolIntervention,
+ marketplaceToolPoliciesOf,
+ withMandatoryApprovalMark,
+} from '@lobechat/const';
import { buildMcpToolMetadata } from '@lobechat/const/mcpApp';
import { inferCrudType } from '@/libs/mcp/utils';
@@ -22,25 +26,39 @@ export interface ClientListedTool {
* The tool rows a client's listing syncs. The client's MCP Apps metadata is
* kept only while the caller's `mcp_apps` flag is on; otherwise a row keeps
* the visibility alone, as before MCP Apps.
+ *
+ * `connectorMetadata` is the target row's: when it stores market tool
+ * policies (an HTTP marketplace MCP an agent installed), each tool takes its
+ * approval from them, not from the listing, and a tool they do not declare is
+ * synced as `always`, as a server-side sync does.
*/
export const toClientToolSyncInputs = async (
tools: ClientListedTool[],
userId: string | null | undefined,
+ connectorMetadata?: unknown,
) => {
const mcpApps = await isMcpAppsEnabled(userId);
+ const marketPolicies = marketplaceToolPoliciesOf(connectorMetadata);
- return tools.map((t) => ({
- crudType: inferCrudType(t.toolName),
- // Applies to new tools only: a synced tool keeps the permission it has
- defaultPermission: resolveConnectorToolPermission(t.humanIntervention),
- description: t.description,
- inputSchema: t.inputSchema,
- // Refreshed on every sync, unlike the permission: an `always` the
- // manifest asks for stays mandatory whatever the permission is
- metadata: withMandatoryApprovalMark(
- mcpApps && t.mcpAppMeta ? t.mcpAppMeta : buildMcpToolMetadata(t.visibility),
+ return tools.map((t) => {
+ const humanIntervention = marketplaceToolIntervention(
+ marketPolicies,
+ t.toolName,
t.humanIntervention,
- ),
- toolName: t.toolName,
- }));
+ );
+ return {
+ crudType: inferCrudType(t.toolName),
+ // Applies to new tools only: a synced tool keeps the permission it has
+ defaultPermission: resolveConnectorToolPermission(humanIntervention),
+ description: t.description,
+ inputSchema: t.inputSchema,
+ // Refreshed on every sync, unlike the permission: an `always` the
+ // manifest asks for stays mandatory whatever the permission is
+ metadata: withMandatoryApprovalMark(
+ mcpApps && t.mcpAppMeta ? t.mcpAppMeta : buildMcpToolMetadata(t.visibility),
+ humanIntervention,
+ ),
+ toolName: t.toolName,
+ };
+ });
};
diff --git a/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts b/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts
index 143b6d8898e..3c9582b5981 100644
--- a/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts
+++ b/apps/server/src/routers/lambda/_helpers/upsertConnectorEntry.ts
@@ -1,6 +1,6 @@
import { TRPCError } from '@trpc/server';
-import type { ConnectorModel } from '@/database/models/connector';
+import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';
import type { ConnectorMetadata } from '@/database/schemas';
import { ConnectorStatus } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
@@ -54,9 +54,7 @@ export async function upsertConnectorEntry(
workspaceId: ctx.workspaceId,
});
- const existing = await ctx.connectorModel.queryByIdentifiers([params.identifier]);
- if (existing.length > 0) {
- const row = existing[0];
+ const refresh = async (row: Pick<DecryptedConnector, 'id' | 'metadata' | 'userId'>) => {
const writable = canWrite && (!isWorkspaceNonOwner(ctx) || row.userId === ctx.userId);
if (writable) {
// Preserve runtime-owned metadata (especially Composio account identity)
@@ -64,13 +62,18 @@ export async function upsertConnectorEntry(
await ctx.connectorModel.update(row.id, { metadata: { ...row.metadata, ...metadata } });
}
return { connectorId: row.id, writable };
- }
+ };
+
+ const [existing] = await ctx.connectorModel.queryByIdentifiers([params.identifier]);
+ if (existing) return refresh(existing);
if (!canWrite) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Viewers cannot install connectors' });
}
- const created = await ctx.connectorModel.create({
+ // Claimed under the identifier lock every base-row writer takes, so a
+ // concurrent install of the same identifier never adds a second base row.
+ const claim = await ctx.connectorModel.createUnlessIdentifierHeld({
identifier: params.identifier,
isEnabled: true,
metadata,
@@ -78,5 +81,6 @@ export async function upsertConnectorEntry(
sourceType: params.sourceType as any,
status: ConnectorStatus.connected,
});
- return { connectorId: created.id, writable: true };
+ if ('holder' in claim) return refresh(claim.holder);
+ return { connectorId: claim.created.id, writable: true };
}
diff --git a/apps/server/src/routers/lambda/composio.test.ts b/apps/server/src/routers/lambda/composio.test.ts
index 071cc678df2..c5043fefa16 100644
--- a/apps/server/src/routers/lambda/composio.test.ts
+++ b/apps/server/src/routers/lambda/composio.test.ts
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
connectedAccountsLink: vi.fn(),
connectedAccountsList: vi.fn(),
connectorCreate: vi.fn(),
+ connectorCreateUnlessIdentifierHeld: vi.fn(),
connectorDelete: vi.fn(),
connectorFindScopedByIdentifier: vi.fn(),
connectorToolDeleteToolsNotIn: vi.fn(),
@@ -48,6 +49,7 @@ vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn().mockImplementation(function () {
return {
create: mocks.connectorCreate,
+ createUnlessIdentifierHeld: mocks.connectorCreateUnlessIdentifierHeld,
delete: mocks.connectorDelete,
findScopedByIdentifier: mocks.connectorFindScopedByIdentifier,
update: mocks.connectorUpdate,
@@ -83,6 +85,7 @@ beforeEach(() => {
vi.clearAllMocks();
mocks.connectorFindScopedByIdentifier.mockResolvedValue(null);
mocks.connectorCreate.mockResolvedValue({ id: 'conn-new' });
+ mocks.connectorCreateUnlessIdentifierHeld.mockResolvedValue({ created: { id: 'conn-new' } });
mocks.pluginFindById.mockResolvedValue(undefined);
});
@@ -139,7 +142,7 @@ describe('composioRouter.createConnection dual-write', () => {
expect(mocks.authConfigsList).not.toHaveBeenCalled();
expect(mocks.connectedAccountsLink).not.toHaveBeenCalled();
- expect(mocks.connectorCreate).not.toHaveBeenCalled();
+ expect(mocks.connectorCreateUnlessIdentifierHeld).not.toHaveBeenCalled();
});
it('mirrors a pending connection into user_connectors + tools', async () => {
@@ -154,8 +157,8 @@ describe('composioRouter.createConnection dual-write', () => {
// plugin write kept (backward compat)
expect(mocks.pluginCreate).toHaveBeenCalledTimes(1);
// connector projection created with PENDING composio metadata
- expect(mocks.connectorCreate).toHaveBeenCalledTimes(1);
- expect(mocks.connectorCreate.mock.calls[0][0]).toMatchObject({
+ expect(mocks.connectorCreateUnlessIdentifierHeld).toHaveBeenCalledTimes(1);
+ expect(mocks.connectorCreateUnlessIdentifierHeld.mock.calls[0][0]).toMatchObject({
identifier: 'gmail',
metadata: { composio: { connectedAccountId: 'ca-1', status: 'PENDING' } },
status: 'disconnected',
@@ -186,8 +189,8 @@ describe('composioRouter.updateComposioPlugin dual-write', () => {
const res = await caller().updateComposioPlugin(input);
expect(res).toEqual({ savedCount: 1 });
- expect(mocks.connectorCreate).toHaveBeenCalledTimes(1);
- expect(mocks.connectorCreate.mock.calls[0][0]).toMatchObject({
+ expect(mocks.connectorCreateUnlessIdentifierHeld).toHaveBeenCalledTimes(1);
+ expect(mocks.connectorCreateUnlessIdentifierHeld.mock.calls[0][0]).toMatchObject({
metadata: { composio: { connectedAccountId: 'ca-1', status: 'ACTIVE' } },
status: 'connected',
});
diff --git a/apps/server/src/routers/lambda/composio.ts b/apps/server/src/routers/lambda/composio.ts
index 343f9dddd31..e23716537fb 100644
--- a/apps/server/src/routers/lambda/composio.ts
+++ b/apps/server/src/routers/lambda/composio.ts
@@ -152,27 +152,26 @@ async function upsertComposioConnector(
// Exact-scope idempotency: an agent connection updates/creates the agent's own
// row, a personal connection the base row β€” never crossing scopes.
+ const fields = {
+ metadata,
+ name: params.label,
+ sourceType: ConnectorSourceType.marketplace,
+ status,
+ };
const existing = await connectorModel.findScopedByIdentifier(params.identifier, params.agentId);
let connectorId: string;
if (existing) {
- await connectorModel.update(existing.id, {
- metadata,
- name: params.label,
- sourceType: ConnectorSourceType.marketplace,
- status,
- });
+ await connectorModel.update(existing.id, fields);
connectorId = existing.id;
} else {
- const created = await connectorModel.create({
- agentId: params.agentId ?? null,
- identifier: params.identifier,
- isEnabled: true,
- metadata,
- name: params.label,
- sourceType: ConnectorSourceType.marketplace,
- status,
- });
- connectorId = created.id;
+ const newRow = { ...fields, identifier: params.identifier, isEnabled: true };
+ const claim = params.agentId
+ ? { created: await connectorModel.create({ ...newRow, agentId: params.agentId }) }
+ : // A base row is claimed under the identifier lock every base-row writer
+ // takes; one a concurrent writer added meanwhile is updated as if found.
+ await connectorModel.createUnlessIdentifierHeld(newRow);
+ if ('holder' in claim) await connectorModel.update(claim.holder.id, fields);
+ connectorId = 'holder' in claim ? claim.holder.id : claim.created.id;
}
if (params.tools) {
diff --git a/apps/server/src/routers/lambda/connector.evalEdits.test.ts b/apps/server/src/routers/lambda/connector.evalEdits.test.ts
index d43c9681819..1f4c771b983 100644
--- a/apps/server/src/routers/lambda/connector.evalEdits.test.ts
+++ b/apps/server/src/routers/lambda/connector.evalEdits.test.ts
@@ -6,7 +6,7 @@ import { EvalConnectorUpdateError } from '@/database/models/connectorEval';
import { connectorRouter } from './connector';
const mocks = vi.hoisted(() => ({
- create: vi.fn(),
+ createUnlessIdentifierHeld: vi.fn(),
findById: vi.fn(),
findScopedByIdentifier: vi.fn(),
update: vi.fn(),
@@ -45,7 +45,7 @@ beforeEach(() => {
vi.resetAllMocks();
mocks.findById.mockResolvedValue({ id, userId: 'creator' });
mocks.findScopedByIdentifier.mockResolvedValue(null);
- mocks.create.mockResolvedValue({ id });
+ mocks.createUnlessIdentifierHeld.mockResolvedValue({ created: { id } });
});
describe('imported evaluation connector edit boundary', () => {
@@ -56,7 +56,7 @@ describe('imported evaluation connector edit boundary', () => {
sourceType: 'custom',
metadata: { agentEval: { datasetId: 'spoofed' }, description: 'Keep this' },
});
- expect(mocks.create).toHaveBeenCalledWith(
+ expect(mocks.createUnlessIdentifierHeld).toHaveBeenCalledWith(
expect.objectContaining({ metadata: { description: 'Keep this' } }),
);
});
diff --git a/apps/server/src/routers/lambda/connector/agentScope.ts b/apps/server/src/routers/lambda/connector/agentScope.ts
index b33ca89fbc5..7f328154f81 100644
--- a/apps/server/src/routers/lambda/connector/agentScope.ts
+++ b/apps/server/src/routers/lambda/connector/agentScope.ts
@@ -64,15 +64,16 @@ export const connectorAgentScopeRouter = router({
await assertConnectorCredentialsManageable(ctx, connector);
if (!connector.agentId) return { id: input.connectorId }; // already base β€” no-op
- const existingBase = await ctx.connectorModel.findScopedByIdentifier(connector.identifier);
- if (existingBase) {
+ const moved = await ctx.connectorModel.moveToBaseUnlessIdentifierHeld(
+ input.connectorId,
+ connector.identifier,
+ );
+ if ('holder' in moved) {
throw new TRPCError({
code: 'CONFLICT',
message: `A personal "${connector.identifier}" connector already exists; delete the agent connector instead`,
});
}
-
- await ctx.connectorModel.update(input.connectorId, { agentId: null });
return { id: input.connectorId };
}),
diff --git a/apps/server/src/routers/lambda/connector/index.ts b/apps/server/src/routers/lambda/connector/index.ts
index 479cac9985f..ca07c9d6293 100644
--- a/apps/server/src/routers/lambda/connector/index.ts
+++ b/apps/server/src/routers/lambda/connector/index.ts
@@ -36,8 +36,8 @@ import { getConnectorLocalCallToken } from '@/server/services/connector/localCal
import { getConnectorRedirectUri } from '@/server/services/connector/oauth';
import { loadConnectorPresentation } from '@/server/services/connector/presentation';
import {
- pruneMissingAutoConnectorTools,
syncConnectorToolsById,
+ writeConnectorToolSyncInputs,
} from '@/server/services/connector/sync';
import {
DeviceMcpManifestInputSchema,
@@ -431,38 +431,73 @@ const connectorCoreRouter = router({
// enforcing "one connector per identifier per agent" at the app layer (the
// DB indexes are non-unique so multiple same-identifier rows can coexist
// across scopes).
- const existing = await ctx.connectorModel.findScopedByIdentifier(input.identifier, agentId);
+ const row = {
+ ...fields,
+ isEnabled: input.isEnabled ?? true,
+ sourceType: input.sourceType,
+ status: ConnectorStatus.disconnected,
+ };
// Adding a workspace connector follows the member policy. Re-adding over
// someone else's row rewrites its server/command while the row stays theirs
// (their runs would execute it, and they could read the new credentials), so
// that keeps the creator-or-owner rule.
- if (existing && existing.userId !== ctx.userId)
- await assertConnectorCredentialsManageable(ctx, existing);
- else await assertConnectorMaintainable(ctx, { agentId, userId: existing?.userId });
- await assertConnectorDeviceBindingAllowed(ctx, input.metadata, existing?.metadata);
- if (existing) {
- await ctx.connectorModel.update(existing.id, {
- ...fields,
- isEnabled: input.isEnabled ?? true,
- sourceType: input.sourceType,
- status: ConnectorStatus.disconnected,
+ const assertWritable = async (existing?: {
+ agentId: string | null;
+ metadata?: Record<string, unknown> | null;
+ userId: string;
+ }) => {
+ if (existing && existing.userId !== ctx.userId)
+ await assertConnectorCredentialsManageable(ctx, existing);
+ else await assertConnectorMaintainable(ctx, { agentId, userId: existing?.userId });
+ await assertConnectorDeviceBindingAllowed(ctx, input.metadata, existing?.metadata);
+ };
+ // `isNew` lets clients tell a fresh row from an updated pre-existing one β€”
+ // client-side caches can't answer this reliably (the connector list may
+ // not be fetched yet), and rollback-on-sync-failure must never delete a
+ // connector the user already had.
+ // Nothing when the row is gone by its update (see the retry below).
+ const reAdd = async (existing: {
+ agentId: string | null;
+ id: string;
+ metadata?: Record<string, unknown> | null;
+ userId: string;
+ }) => {
+ await assertWritable(existing);
+ const updated = await ctx.connectorModel.update(existing.id, row);
+ return updated ? { id: existing.id, isNew: false } : undefined;
+ };
+
+ const add = async () => {
+ const existing = await ctx.connectorModel.findScopedByIdentifier(input.identifier, agentId);
+ if (existing) return reAdd(existing);
+ await assertWritable();
+
+ if (agentId) {
+ const created = await ctx.connectorModel.create({
+ ...row,
+ agentId,
+ identifier: input.identifier,
+ });
+ return { id: created.id, isNew: true };
+ }
+ // A base row is claimed under the identifier lock every base-row writer
+ // takes (an Agent Builder install among them), so concurrent adds create it once.
+ const claim = await ctx.connectorModel.createUnlessIdentifierHeld({
+ ...row,
+ identifier: input.identifier,
});
- // `isNew` lets clients tell a fresh row from an updated pre-existing one β€”
- // client-side caches can't answer this reliably (the connector list may
- // not be fetched yet), and rollback-on-sync-failure must never delete a
- // connector the user already had.
- return { id: existing.id, isNew: false };
- }
+ if ('holder' in claim) return reAdd(claim.holder);
+ return { id: claim.created.id, isNew: true };
+ };
- const created = await ctx.connectorModel.create({
- ...fields,
- agentId: agentId ?? null,
- identifier: input.identifier,
- isEnabled: input.isEnabled ?? true,
- sourceType: input.sourceType,
- status: ConnectorStatus.disconnected,
- });
- return { id: created.id, isNew: true };
+ const added = await add();
+ if (added) return added;
+ // The row the re-add read was deleted before its update (an Agent Builder
+ // install replaces a stale unfinished one under the identifier lock): start
+ // over once, against the fresh replacement no install takes over in turn.
+ const retried = await add();
+ if (retried) return retried;
+ throw new TRPCError({ code: 'CONFLICT', message: 'Connector changed, try again' });
}),
/** Update connector configuration while preserving server-resolved OAuth state. */
@@ -853,18 +888,12 @@ const connectorCoreRouter = router({
// Same gate as `syncTools` β€” rewrites the connector's tool rows.
await assertConnectorMaintainable(ctx, target);
- const syncInputs = await toClientToolSyncInputs(input.tools, ctx.userId);
-
- await ctx.connectorToolModel.upsertMany(input.id, syncInputs);
- if (input.pruneMissingAutoTools) {
- await pruneMissingAutoConnectorTools(
- ctx.connectorToolModel,
- input.id,
- syncInputs.map((tool) => tool.toolName),
- );
- }
- await ctx.connectorModel.updateStatus(input.id, ConnectorStatus.connected);
- return { toolCount: syncInputs.length };
+ return writeConnectorToolSyncInputs(
+ input.id,
+ await toClientToolSyncInputs(input.tools, ctx.userId, target.metadata),
+ ctx,
+ { pruneMissingAutoTools: input.pruneMissingAutoTools },
+ );
}),
/**
diff --git a/apps/server/src/services/connector/marketplaceInstall.test.ts b/apps/server/src/services/connector/marketplaceInstall.test.ts
new file mode 100644
index 00000000000..9311dece6c3
--- /dev/null
+++ b/apps/server/src/services/connector/marketplaceInstall.test.ts
@@ -0,0 +1,976 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import {
+ userConnectors,
+ userConnectorTools,
+ userInstalledPlugins,
+ users,
+ workspaceMembers,
+ workspaces,
+} from '@/database/schemas';
+import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
+import { mcpService } from '@/server/services/mcp';
+import { listMcpToolsOnDevice } from '@/server/services/mcp/deviceTunnel';
+
+import {
+ installMarketplaceMcpConnector,
+ type MarketMcpManifest,
+ MARKETPLACE_INSTALL_LEASE_MS,
+ pickMarketplaceDeployment,
+} from './marketplaceInstall';
+import { syncConnectorToolsById } from './sync';
+
+vi.mock('@/server/services/mcp', () => ({ mcpService: { listRawTools: vi.fn() } }));
+const gateway = vi.hoisted(() => ({ isConfigured: false }));
+vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: gateway }));
+vi.mock('@/server/services/mcp/deviceTunnel', () => ({ listMcpToolsOnDevice: vi.fn() }));
+vi.mock('@/server/services/mcp/featureGate', () => ({
+ isMcpAppsEnabled: vi.fn().mockResolvedValue(false),
+}));
+
+const db = await getTestDB();
+const userId = 'market-install-user';
+const memberId = 'market-install-member';
+const workspaceId = 'market-install-ws';
+
+const stdioOption = { connection: { args: ['-y', 'fetch-mcp'], command: 'npx', type: 'stdio' } };
+const httpOption = (connection: Record<string, unknown> = {}) => ({
+ connection: { type: 'http', url: 'https://mcp.example.com/mcp', ...connection },
+});
+
+const cloudManifest: MarketMcpManifest = {
+ deploymentOptions: [stdioOption],
+ description: 'Fetch web pages',
+ haveCloudEndpoint: true,
+ icon: 'https://example.com/icon.png',
+ name: 'Fetch',
+ tools: [
+ { description: 'Fetch a URL', inputSchema: { type: 'object' }, name: 'fetch' },
+ { description: 'Delete a cache entry', name: 'purge' },
+ ],
+ version: '1.2.0',
+};
+
+const httpManifest: MarketMcpManifest = {
+ deploymentOptions: [httpOption()],
+ name: 'Remote MCP',
+ version: '0.3.0',
+};
+
+const scope = { serverDB: db, userId };
+
+const connectorRows = () => db.select().from(userConnectors);
+const pluginRows = () => db.select().from(userInstalledPlugins);
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ await db.delete(users);
+ await db.insert(users).values([{ id: userId }, { id: memberId }]);
+});
+
+afterEach(async () => {
+ gateway.isConfigured = false;
+ await db.delete(users);
+});
+
+describe('pickMarketplaceDeployment', () => {
+ const noGateway = { deviceGatewayConfigured: false };
+ const withGateway = { deviceGatewayConfigured: true };
+
+ it('uses the market-hosted endpoint of a stdio server first, as the web install does', () => {
+ expect(
+ pickMarketplaceDeployment(
+ {
+ deploymentOptions: [httpOption(), stdioOption],
+ haveCloudEndpoint: 'https://cloud.example.com',
+ },
+ noGateway,
+ ),
+ ).toEqual({
+ deployment: { cloudEndPoint: 'https://cloud.example.com', headers: undefined, type: 'cloud' },
+ });
+ });
+
+ it('uses an HTTP endpoint, typed or untyped', () => {
+ expect(
+ pickMarketplaceDeployment({ deploymentOptions: [stdioOption, httpOption()] }, withGateway),
+ ).toEqual({
+ deployment: {
+ auth: undefined,
+ headers: undefined,
+ type: 'http',
+ url: 'https://mcp.example.com/mcp',
+ },
+ });
+ expect(
+ pickMarketplaceDeployment(
+ { deploymentOptions: [{ connection: { url: 'https://a.dev' } }] },
+ withGateway,
+ ),
+ ).toMatchObject({ deployment: { type: 'http', url: 'https://a.dev' } });
+ });
+
+ describe('an HTTP endpoint on localhost or a private network', () => {
+ const privateUrls = [
+ 'http://localhost:3000/mcp',
+ 'http://127.0.0.1:8080/mcp',
+ 'http://10.0.0.2/mcp',
+ ];
+
+ it.each(privateUrls)(
+ 'is refused with a device gateway, which would reach %s from the user device',
+ (url) => {
+ expect(
+ pickMarketplaceDeployment(
+ { deploymentOptions: [stdioOption, httpOption({ url })] },
+ withGateway,
+ ),
+ ).toEqual({ blocker: 'private-network' });
+ },
+ );
+
+ it('gives way to one the server reaches', () => {
+ expect(
+ pickMarketplaceDeployment(
+ {
+ deploymentOptions: [
+ httpOption({ url: 'http://192.168.1.10:8080/mcp' }),
+ { connection: { url: 'https://a.dev' } },
+ ],
+ },
+ withGateway,
+ ),
+ ).toMatchObject({ deployment: { type: 'http', url: 'https://a.dev' } });
+ });
+
+ it('is used without a gateway: the server connects itself, through the SSRF-safe fetch', () => {
+ expect(
+ pickMarketplaceDeployment(
+ { deploymentOptions: [httpOption({ url: 'http://10.0.0.2/mcp' })] },
+ noGateway,
+ ),
+ ).toMatchObject({ deployment: { type: 'http', url: 'http://10.0.0.2/mcp' } });
+ });
+ });
+
+ it.each([
+ ['a stdio-only server', { deploymentOptions: [stdioOption] }, 'local-only'],
+ ['no deployment options', {}, 'local-only'],
+ [
+ 'an OAuth HTTP server',
+ { deploymentOptions: [httpOption({ auth: { type: 'oauth2' } })] },
+ 'oauth',
+ ],
+ [
+ 'an HTTP server that needs config',
+ {
+ deploymentOptions: [
+ httpOption({ configSchema: { properties: { KEY: {} }, required: ['KEY'] } }),
+ ],
+ },
+ 'config',
+ ],
+ [
+ 'a hosted server that needs config',
+ {
+ deploymentOptions: [
+ {
+ connection: {
+ ...stdioOption.connection,
+ configSchema: { properties: { KEY: { required: true } } },
+ },
+ },
+ ],
+ haveCloudEndpoint: true,
+ },
+ 'config',
+ ],
+ ])('refuses %s', (_, manifest, blocker) => {
+ expect(pickMarketplaceDeployment(manifest as MarketMcpManifest, withGateway)).toEqual({
+ blocker,
+ });
+ });
+});
+
+describe('installMarketplaceMcpConnector', () => {
+ it('stores a hosted server as a marked cloud connector with its manifest tools', async () => {
+ const outcome = await installMarketplaceMcpConnector(scope, 'fetch-mcp', {
+ ...cloudManifest,
+ api: [
+ { description: 'Fetch a URL', name: 'fetch', parameters: { type: 'object' } },
+ { description: 'Purge', humanIntervention: 'required', name: 'purge', parameters: {} },
+ ],
+ });
+
+ expect(outcome).toEqual({ status: 'installed' });
+ expect(await pluginRows()).toEqual([]);
+ const [connector, ...others] = await connectorRows();
+ expect(others).toEqual([]);
+ expect(connector).toMatchObject({
+ agentId: null,
+ identifier: 'fetch-mcp',
+ isEnabled: true,
+ mcpConnectionType: 'cloud',
+ mcpServerUrl: null,
+ name: 'Fetch',
+ sourceType: 'marketplace',
+ status: 'connected',
+ });
+ expect(connector.metadata).toEqual({
+ avatar: 'https://example.com/icon.png',
+ cloudEndPoint: true,
+ description: 'Fetch web pages',
+ marketplaceInstalled: true,
+ version: '1.2.0',
+ });
+
+ const tools = await db
+ .select()
+ .from(userConnectorTools)
+ .where(eq(userConnectorTools.userConnectorId, connector.id));
+ expect(
+ tools
+ .map(({ permission, toolName }) => ({ permission, toolName }))
+ .sort((a, b) => a.toolName.localeCompare(b.toolName)),
+ ).toEqual([
+ { permission: 'auto', toolName: 'fetch' },
+ // The manifest's `humanIntervention` carries over, as in the web install
+ { permission: 'needs_approval', toolName: 'purge' },
+ ]);
+ expect(mcpService.listRawTools).not.toHaveBeenCalled();
+ });
+
+ it('stores an HTTP server as a marked connector with the tools it lists', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { description: 'Search', inputSchema: { type: 'object' }, name: 'search' },
+ ] as never);
+
+ const outcome = await installMarketplaceMcpConnector(scope, 'remote-mcp', {
+ ...httpManifest,
+ deploymentOptions: [httpOption({ headers: { 'X-Client': 'lobehub' } })],
+ });
+
+ expect(outcome).toEqual({ status: 'installed' });
+ expect(mcpService.listRawTools).toHaveBeenCalledWith(
+ expect.objectContaining({
+ headers: { 'X-Client': 'lobehub' },
+ name: 'remote-mcp',
+ type: 'http',
+ url: 'https://mcp.example.com/mcp',
+ }),
+ { mcpApps: false },
+ );
+ const [connector] = await connectorRows();
+ expect(connector).toMatchObject({
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ sourceType: 'marketplace',
+ status: 'connected',
+ });
+ expect(connector.metadata).toMatchObject({
+ customHeaders: { 'X-Client': 'lobehub' },
+ marketplaceInstalled: true,
+ });
+ expect(await pluginRows()).toEqual([]);
+ });
+
+ it("keeps the approval the marketplace manifest asks for on an HTTP server's tools", async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { name: 'search' },
+ { name: 'send' },
+ { name: 'delete' },
+ ] as never);
+
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', {
+ ...httpManifest,
+ api: [
+ { name: 'search', parameters: {} },
+ { humanIntervention: 'required', name: 'send', parameters: {} },
+ { humanIntervention: 'always', name: 'delete', parameters: {} },
+ ],
+ });
+
+ const [row] = await connectorRows();
+ const tools = await db
+ .select()
+ .from(userConnectorTools)
+ .where(eq(userConnectorTools.userConnectorId, row.id));
+ expect(
+ tools
+ .map(({ metadata, permission, toolName }) => ({ metadata, permission, toolName }))
+ .sort((a, b) => a.toolName.localeCompare(b.toolName)),
+ ).toEqual([
+ // An `always` stays mandatory past auto-run
+ { metadata: { mandatoryApproval: true }, permission: 'needs_approval', toolName: 'delete' },
+ { metadata: null, permission: 'auto', toolName: 'search' },
+ { metadata: null, permission: 'needs_approval', toolName: 'send' },
+ ]);
+
+ // Runs build the connector's manifest from those rows
+ const connector = (await new ConnectorModel(db, userId).findById(row.id))!;
+ const [manifest] = buildConnectorManifests([connector], tools);
+ expect(
+ Object.fromEntries(manifest.api.map((api) => [api.name, api.humanIntervention])),
+ ).toEqual({ delete: 'always', search: undefined, send: 'required' });
+ });
+
+ it("keeps the approval a tools-format manifest asks for on an HTTP server's tools", async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { name: 'search' },
+ { name: 'delete' },
+ ] as never);
+
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', {
+ ...httpManifest,
+ tools: [{ name: 'search' }, { humanIntervention: 'always', name: 'delete' }],
+ });
+
+ const tools = await db.select().from(userConnectorTools);
+ expect(
+ tools
+ .map(({ metadata, permission, toolName }) => ({ metadata, permission, toolName }))
+ .sort((a, b) => a.toolName.localeCompare(b.toolName)),
+ ).toEqual([
+ { metadata: { mandatoryApproval: true }, permission: 'needs_approval', toolName: 'delete' },
+ { metadata: null, permission: 'auto', toolName: 'search' },
+ ]);
+ });
+
+ it('keeps an `always` tool mandatory through the refreshes that follow the install', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { name: 'search' },
+ { name: 'delete' },
+ ] as never);
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', {
+ ...httpManifest,
+ api: [
+ { name: 'search', parameters: {} },
+ { humanIntervention: 'always', name: 'delete', parameters: {} },
+ ],
+ });
+ const [row] = await connectorRows();
+
+ // The background (and manual) refresh syncs the listing alone, without the manifest
+ await syncConnectorToolsById(row.id, {
+ connectorModel: new ConnectorModel(db, userId),
+ connectorToolModel: new ConnectorToolModel(db, userId),
+ serverDB: undefined,
+ userId,
+ });
+
+ const tools = await db
+ .select()
+ .from(userConnectorTools)
+ .where(eq(userConnectorTools.userConnectorId, row.id));
+ const connector = (await new ConnectorModel(db, userId).findById(row.id))!;
+ const [manifest] = buildConnectorManifests([connector], tools);
+ // `always` is the approval auto-run and headless runs still ask for
+ expect(
+ Object.fromEntries(manifest.api.map((api) => [api.name, api.humanIntervention])),
+ ).toEqual({ delete: 'always', search: undefined });
+ });
+
+ describe('a tool the marketplace manifest does not list', () => {
+ const syncedTools = async () =>
+ (await db.select().from(userConnectorTools))
+ .map(({ metadata, permission, toolName }) => ({ metadata, permission, toolName }))
+ .sort((a, b) => a.toolName.localeCompare(b.toolName));
+ const runApprovals = async () => {
+ const [row] = await connectorRows();
+ const connector = (await new ConnectorModel(db, userId).findById(row.id))!;
+ const [manifest] = buildConnectorManifests(
+ [connector],
+ await db.select().from(userConnectorTools),
+ );
+ return Object.fromEntries(manifest.api.map((api) => [api.name, api.humanIntervention]));
+ };
+
+ it('needs approval on every call from the install on', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { name: 'search' },
+ { name: 'exfiltrate' },
+ ] as never);
+
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', {
+ ...httpManifest,
+ tools: [{ name: 'search' }],
+ });
+
+ const [row] = await connectorRows();
+ // The market's per-tool policies are kept for the syncs that follow
+ expect(row.metadata).toMatchObject({ marketplaceToolPolicies: { search: null } });
+ expect(await syncedTools()).toEqual([
+ {
+ metadata: { mandatoryApproval: true },
+ permission: 'needs_approval',
+ toolName: 'exfiltrate',
+ },
+ { metadata: null, permission: 'auto', toolName: 'search' },
+ ]);
+ // `always` is the approval auto-run and headless runs still ask for
+ expect(await runApprovals()).toEqual({ exfiltrate: 'always', search: undefined });
+ });
+
+ it('needs approval on every call when the server adds or renames one after the install', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([{ name: 'search' }] as never);
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', {
+ ...httpManifest,
+ tools: [{ name: 'search' }],
+ });
+ const [row] = await connectorRows();
+
+ // The background (and manual) refresh syncs the listing alone, without the manifest
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { name: 'search' },
+ { name: 'search_v2' },
+ { name: 'exfiltrate' },
+ ] as never);
+ await syncConnectorToolsById(row.id, {
+ connectorModel: new ConnectorModel(db, userId),
+ connectorToolModel: new ConnectorToolModel(db, userId),
+ serverDB: undefined,
+ userId,
+ });
+
+ expect(await runApprovals()).toEqual({
+ exfiltrate: 'always',
+ search: undefined,
+ search_v2: 'always',
+ });
+ });
+
+ it("keeps the manifest's approval for a declared tool the server only lists after the install", async () => {
+ // At the install the server lists just one of the tools the manifest declares
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([{ name: 'search' }] as never);
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', {
+ ...httpManifest,
+ api: [
+ { name: 'search', parameters: {} },
+ { humanIntervention: 'required', name: 'send', parameters: {} },
+ { humanIntervention: 'always', name: 'delete', parameters: {} },
+ ],
+ });
+ const [row] = await connectorRows();
+ expect(row.metadata).toMatchObject({
+ marketplaceToolPolicies: { delete: 'always', search: null, send: 'required' },
+ });
+
+ // The background refresh lists the rest, without the manifest
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { name: 'search' },
+ { name: 'send' },
+ { name: 'delete' },
+ ] as never);
+ await syncConnectorToolsById(row.id, {
+ connectorModel: new ConnectorModel(db, userId),
+ connectorToolModel: new ConnectorToolModel(db, userId),
+ serverDB: undefined,
+ userId,
+ });
+
+ expect(await syncedTools()).toEqual([
+ { metadata: { mandatoryApproval: true }, permission: 'needs_approval', toolName: 'delete' },
+ { metadata: null, permission: 'auto', toolName: 'search' },
+ { metadata: null, permission: 'needs_approval', toolName: 'send' },
+ ]);
+ expect(await runApprovals()).toEqual({
+ delete: 'always',
+ search: undefined,
+ send: 'required',
+ });
+ });
+
+ it('covers every tool of a manifest that lists none', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([{ name: 'search' }] as never);
+
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', httpManifest);
+
+ const [row] = await connectorRows();
+ expect(row.metadata).toMatchObject({ marketplaceToolPolicies: {} });
+ expect(await runApprovals()).toEqual({ search: 'always' });
+ });
+ });
+
+ it('reads whether the market hosts the server only when a stdio option makes it decide', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([{ name: 'search' }] as never);
+ const readHostedEndpoint = vi.fn().mockResolvedValue(true);
+
+ // An HTTP-only server: nothing to decide
+ expect(
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', httpManifest, {
+ readHostedEndpoint,
+ }),
+ ).toEqual({ status: 'installed' });
+ // A finished install of a stdio server: nothing to place
+ expect(
+ await installMarketplaceMcpConnector(
+ scope,
+ 'remote-mcp',
+ { ...cloudManifest, haveCloudEndpoint: undefined },
+ { readHostedEndpoint },
+ ),
+ ).toEqual({ status: 'exists' });
+ expect(readHostedEndpoint).not.toHaveBeenCalled();
+
+ // A stdio server to place: hosted by the market, so a cloud connector
+ expect(
+ await installMarketplaceMcpConnector(
+ scope,
+ 'fetch-mcp',
+ { ...cloudManifest, haveCloudEndpoint: undefined },
+ { readHostedEndpoint },
+ ),
+ ).toEqual({ status: 'installed' });
+ expect(readHostedEndpoint).toHaveBeenCalledTimes(1);
+ expect((await connectorRows()).find((row) => row.identifier === 'fetch-mcp')).toMatchObject({
+ mcpConnectionType: 'cloud',
+ });
+ });
+
+ it('removes the connector it created when the server cannot be reached', async () => {
+ vi.mocked(mcpService.listRawTools).mockRejectedValue(new Error('connect ECONNREFUSED'));
+
+ await expect(installMarketplaceMcpConnector(scope, 'remote-mcp', httpManifest)).rejects.toThrow(
+ 'ECONNREFUSED',
+ );
+
+ expect(await connectorRows()).toEqual([]);
+ expect(await pluginRows()).toEqual([]);
+ });
+
+ it.each([
+ ['fails', () => Promise.reject(new Error('connect ECONNREFUSED')), 'connect ECONNREFUSED'],
+ ['lists no tools', () => Promise.resolve([]), { blocker: 'no-tools', status: 'blocked' }],
+ ])(
+ 'keeps a connector the web re-added and finished while its listing %s',
+ async (_, listing, reported) => {
+ vi.mocked(mcpService.listRawTools).mockImplementation(async () => {
+ // The web install re-adds the identifier over this install's row
+ // (`connector.create` updates it), syncs its tools and marks it
+ const [row] = await connectorRows();
+ await new ConnectorModel(db, userId).update(row.id, {
+ metadata: { marketplaceInstalled: true, version: '0.3.0' },
+ status: 'connected',
+ });
+ await db.insert(userConnectorTools).values({
+ crudType: 'read',
+ permission: 'auto',
+ toolName: 'search',
+ userConnectorId: row.id,
+ userId,
+ });
+ return listing() as never;
+ });
+
+ // This install still reports its own failure
+ expect(
+ await installMarketplaceMcpConnector(scope, 'remote-mcp', httpManifest).catch(
+ (error: Error) => error.message,
+ ),
+ ).toEqual(reported);
+
+ const [connector, ...others] = await connectorRows();
+ expect(others).toEqual([]);
+ expect(connector.metadata).toEqual({ marketplaceInstalled: true, version: '0.3.0' });
+ expect((await db.select().from(userConnectorTools)).map((tool) => tool.toolName)).toEqual([
+ 'search',
+ ]);
+ },
+ );
+
+ it.each([
+ [
+ 'finished',
+ { customHeaders: { 'X-Team': 'web' }, marketplaceInstalled: true, version: '0.3.0' },
+ 'connected',
+ { status: 'exists' },
+ ],
+ [
+ 'still running',
+ { customHeaders: { 'X-Team': 'web' }, version: '0.3.0' },
+ 'disconnected',
+ { blocker: 'in-progress', status: 'blocked' },
+ ],
+ ] as const)(
+ 'leaves a connector the web re-added while its listing succeeds to that install (%s)',
+ async (_, webMetadata, webStatus, reported) => {
+ vi.mocked(mcpService.listRawTools).mockImplementation(async () => {
+ // The web install re-adds the identifier over this install's row with
+ // the headers its user entered (`connector.create` updates the row),
+ // and syncs the tools its own endpoint lists
+ const [row] = await connectorRows();
+ await new ConnectorModel(db, userId).update(row.id, {
+ metadata: webMetadata,
+ status: webStatus,
+ });
+ await db.insert(userConnectorTools).values({
+ crudType: 'read',
+ description: 'Search (web endpoint)',
+ metadata: { mandatoryApproval: true },
+ permission: 'needs_approval',
+ toolName: 'search',
+ userConnectorId: row.id,
+ userId,
+ });
+ // What this install's endpoint listed
+ return [
+ { description: 'Search (old endpoint)', name: 'search' },
+ { name: 'purge' },
+ ] as never;
+ });
+
+ expect(await installMarketplaceMcpConnector(scope, 'remote-mcp', httpManifest)).toEqual(
+ reported,
+ );
+
+ const [connector, ...others] = await connectorRows();
+ expect(others).toEqual([]);
+ // Neither its metadata, status nor tools are replaced by this install's own
+ expect(connector.metadata).toEqual(webMetadata);
+ expect(connector.status).toBe(webStatus);
+ expect(
+ (await db.select().from(userConnectorTools)).map(
+ ({ description, metadata, permission, toolName }) => ({
+ description,
+ metadata,
+ permission,
+ toolName,
+ }),
+ ),
+ ).toEqual([
+ {
+ description: 'Search (web endpoint)',
+ metadata: { mandatoryApproval: true },
+ permission: 'needs_approval',
+ toolName: 'search',
+ },
+ ]);
+ },
+ );
+
+ it('writes nothing for a server that lists no tools', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([]);
+
+ expect(await installMarketplaceMcpConnector(scope, 'remote-mcp', httpManifest)).toEqual({
+ blocker: 'no-tools',
+ status: 'blocked',
+ });
+ expect(
+ await installMarketplaceMcpConnector(scope, 'fetch-mcp', { ...cloudManifest, tools: [] }),
+ ).toEqual({ blocker: 'no-tools', status: 'blocked' });
+ expect(await connectorRows()).toEqual([]);
+ });
+
+ it('installs a hosted server from its tools list when the api list beside it is empty', async () => {
+ expect(
+ await installMarketplaceMcpConnector(scope, 'fetch-mcp', { ...cloudManifest, api: [] }),
+ ).toEqual({ status: 'installed' });
+ expect(
+ (await db.select().from(userConnectorTools)).map((tool) => tool.toolName).sort(),
+ ).toEqual(['fetch', 'purge']);
+ });
+
+ it('writes nothing for a server only the user can install', async () => {
+ expect(
+ await installMarketplaceMcpConnector(scope, 'local-mcp', {
+ deploymentOptions: [stdioOption],
+ }),
+ ).toEqual({ blocker: 'local-only', status: 'blocked' });
+ expect(await connectorRows()).toEqual([]);
+ });
+
+ it("never has the user's device connect to a private address a market listing gives", async () => {
+ // A device gateway would tunnel a private-network listing to the user's device
+ gateway.isConfigured = true;
+ vi.mocked(listMcpToolsOnDevice).mockResolvedValue([{ name: 'probe' }] as never);
+
+ expect(
+ await installMarketplaceMcpConnector(scope, 'lan-mcp', {
+ deploymentOptions: [httpOption({ url: 'http://192.168.1.10:8080/mcp' })],
+ name: 'LAN MCP',
+ }),
+ ).toEqual({ blocker: 'private-network', status: 'blocked' });
+ expect(listMcpToolsOnDevice).not.toHaveBeenCalled();
+ expect(mcpService.listRawTools).not.toHaveBeenCalled();
+ expect(await connectorRows()).toEqual([]);
+ });
+
+ it('leaves a finished install as it is', async () => {
+ await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest);
+ const [before] = await connectorRows();
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ status: 'exists',
+ });
+ expect(await connectorRows()).toEqual([before]);
+ });
+
+ it('creates the connector once for concurrent installs of one server', async () => {
+ const outcomes = await Promise.all([
+ installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest),
+ installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest),
+ ]);
+
+ expect(outcomes.filter((outcome) => outcome.status === 'installed')).toHaveLength(1);
+ const rows = await connectorRows();
+ expect(rows).toHaveLength(1);
+ expect(rows[0].metadata).toMatchObject({ marketplaceInstalled: true });
+ expect(await db.select().from(userConnectorTools)).toHaveLength(2);
+ });
+
+ describe('over duplicate base rows a writer from before the identifier lock left', () => {
+ const finishedRow = {
+ identifier: 'fetch-mcp',
+ mcpConnectionType: 'cloud',
+ metadata: { cloudEndPoint: true, marketplaceInstalled: true },
+ name: 'Fetch',
+ sourceType: 'marketplace',
+ status: 'connected',
+ userId,
+ } as const;
+ const seed = async (...rows: (typeof userConnectors.$inferInsert)[]) => {
+ // One by one, so the finished install is the oldest row
+ for (const row of rows) await db.insert(userConnectors).values(row);
+ return connectorRows();
+ };
+
+ it('reports a conflict while a custom connector holds the identifier beside a finished install', async () => {
+ const before = await seed(finishedRow, {
+ ...finishedRow,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://custom.example.com/mcp',
+ metadata: {},
+ sourceType: 'custom',
+ });
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ blocker: 'conflict',
+ status: 'blocked',
+ });
+ expect(await connectorRows()).toEqual(before);
+ });
+
+ it('reports an install in progress beside a finished one as in progress', async () => {
+ const before = await seed(finishedRow, {
+ ...finishedRow,
+ metadata: { cloudEndPoint: true },
+ status: 'disconnected',
+ });
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ blocker: 'in-progress',
+ status: 'blocked',
+ });
+ expect(await connectorRows()).toEqual(before);
+ });
+
+ it('leaves finished installs beside an interrupted one as they are', async () => {
+ const before = await seed(
+ {
+ ...finishedRow,
+ metadata: { cloudEndPoint: true },
+ status: 'disconnected',
+ updatedAt: new Date(Date.now() - MARKETPLACE_INSTALL_LEASE_MS - 60_000),
+ },
+ finishedRow,
+ );
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ status: 'exists',
+ });
+ expect(await connectorRows()).toEqual(before);
+ });
+ });
+
+ describe('over an unfinished marketplace install', () => {
+ const staleAt = () => new Date(Date.now() - MARKETPLACE_INSTALL_LEASE_MS - 60_000);
+ const seedUnfinished = async (row: Partial<typeof userConnectors.$inferInsert> = {}) => {
+ const [seeded] = await db
+ .insert(userConnectors)
+ .values({
+ identifier: 'fetch-mcp',
+ mcpConnectionType: 'cloud',
+ metadata: { cloudEndPoint: true },
+ name: 'Interrupted',
+ sourceType: 'marketplace',
+ status: 'disconnected',
+ userId,
+ ...row,
+ })
+ .returning();
+ return seeded;
+ };
+
+ it('reports an install still inside its lease as in progress and leaves it', async () => {
+ const seeded = await seedUnfinished();
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ blocker: 'in-progress',
+ status: 'blocked',
+ });
+ expect(await connectorRows()).toEqual([seeded]);
+ });
+
+ it('takes over an interrupted install once its lease has run out', async () => {
+ const seeded = await seedUnfinished({ updatedAt: staleAt() });
+ await db.insert(userConnectorTools).values({
+ crudType: 'read',
+ permission: 'auto',
+ toolName: 'half-synced',
+ userConnectorId: seeded.id,
+ userId,
+ });
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ status: 'installed',
+ });
+ const [connector] = await connectorRows();
+ expect(connector.id).not.toBe(seeded.id);
+ expect(connector).toMatchObject({ name: 'Fetch', status: 'connected' });
+ expect(connector.metadata).toMatchObject({ marketplaceInstalled: true });
+ expect(
+ (await db.select().from(userConnectorTools)).map((tool) => tool.toolName).sort(),
+ ).toEqual(['fetch', 'purge']);
+ });
+
+ it('leaves a connected pre-connector install its bare plugin row makes callable', async () => {
+ const seeded = await seedUnfinished({ status: 'connected', updatedAt: staleAt() });
+ await db
+ .insert(userInstalledPlugins)
+ .values({ identifier: 'fetch-mcp', type: 'plugin', userId });
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ status: 'exists',
+ });
+ expect(await connectorRows()).toEqual([seeded]);
+ });
+
+ it('takes over an interrupted install a bare plugin row cannot make callable', async () => {
+ // A manifest-less plugin row only lets runs call a connected row
+ const seeded = await seedUnfinished({ updatedAt: staleAt() });
+ await db
+ .insert(userInstalledPlugins)
+ .values({ identifier: 'fetch-mcp', type: 'plugin', userId });
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ status: 'installed',
+ });
+ const [connector] = await connectorRows();
+ expect(connector.id).not.toBe(seeded.id);
+ expect(connector.metadata).toMatchObject({ marketplaceInstalled: true });
+ });
+ });
+
+ it.each([
+ ['a custom connector', { sourceType: 'custom' }],
+ // A row without an endpoint only projects tools another executor runs
+ [
+ 'an endpoint-less marketplace row',
+ { mcpConnectionType: null, mcpServerUrl: null, sourceType: 'marketplace' },
+ ],
+ ])('refuses to overwrite %s of the same identifier', async (_, row) => {
+ await db.insert(userConnectors).values({
+ identifier: 'fetch-mcp',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ name: 'Existing',
+ status: 'disconnected',
+ // Past the lease, so only the kind of row keeps it
+ updatedAt: new Date(Date.now() - MARKETPLACE_INSTALL_LEASE_MS - 60_000),
+ userId,
+ ...row,
+ } as typeof userConnectors.$inferInsert);
+ const [before] = await connectorRows();
+
+ expect(await installMarketplaceMcpConnector(scope, 'fetch-mcp', cloudManifest)).toEqual({
+ blocker: 'conflict',
+ status: 'blocked',
+ });
+ expect(await connectorRows()).toEqual([before]);
+ });
+
+ describe('in a workspace', () => {
+ const seedWorkspace = async (memberManage: 'admins_only' | 'all_members') => {
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Team',
+ primaryOwnerId: userId,
+ settings: { connector: { memberManage } },
+ slug: 'market-install-team',
+ });
+ await db.insert(workspaceMembers).values([
+ { role: 'owner', userId, workspaceId },
+ { role: 'member', userId: memberId, workspaceId },
+ ]);
+ };
+
+ afterEach(async () => {
+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ });
+
+ it('lets a member add the connector when members manage connectors', async () => {
+ await seedWorkspace('all_members');
+
+ expect(
+ await installMarketplaceMcpConnector(
+ { serverDB: db, userId: memberId, workspaceId },
+ 'fetch-mcp',
+ cloudManifest,
+ ),
+ ).toEqual({ status: 'installed' });
+ expect(await connectorRows()).toEqual([
+ expect.objectContaining({ userId: memberId, workspaceId }),
+ ]);
+ });
+
+ it("leaves another member's interrupted install for them or an admin to remove", async () => {
+ await seedWorkspace('all_members');
+ await db.insert(userConnectors).values({
+ identifier: 'fetch-mcp',
+ mcpConnectionType: 'cloud',
+ name: 'Interrupted',
+ sourceType: 'marketplace',
+ status: 'disconnected',
+ updatedAt: new Date(Date.now() - MARKETPLACE_INSTALL_LEASE_MS - 60_000),
+ userId,
+ workspaceId,
+ });
+ const before = await connectorRows();
+
+ expect(
+ await installMarketplaceMcpConnector(
+ { serverDB: db, userId: memberId, workspaceId },
+ 'fetch-mcp',
+ cloudManifest,
+ ),
+ ).toEqual({ blocker: 'conflict', status: 'blocked' });
+ expect(await connectorRows()).toEqual(before);
+ });
+
+ it('applies the admins-only connector policy', async () => {
+ await seedWorkspace('admins_only');
+
+ expect(
+ await installMarketplaceMcpConnector(
+ { serverDB: db, userId: memberId, workspaceId },
+ 'fetch-mcp',
+ cloudManifest,
+ ),
+ ).toEqual({ blocker: 'forbidden', status: 'blocked' });
+ expect(await connectorRows()).toEqual([]);
+
+ expect(
+ await installMarketplaceMcpConnector(
+ { serverDB: db, userId, workspaceId },
+ 'fetch-mcp',
+ cloudManifest,
+ ),
+ ).toEqual({ status: 'installed' });
+ });
+ });
+});
diff --git a/apps/server/src/services/connector/marketplaceInstall.ts b/apps/server/src/services/connector/marketplaceInstall.ts
new file mode 100644
index 00000000000..c452781c596
--- /dev/null
+++ b/apps/server/src/services/connector/marketplaceInstall.ts
@@ -0,0 +1,450 @@
+import { randomUUID } from 'node:crypto';
+
+import {
+ hasCallableMcpEndpoint,
+ isMarketplaceInstallCompleted,
+ MARKETPLACE_INSTALL_COMPLETED_KEY,
+ MARKETPLACE_TOOL_POLICIES_KEY,
+} from '@lobechat/const';
+import { shouldConnectViaDevice } from '@lobechat/utils/mcpEndpoint';
+import debug from 'debug';
+
+import type { DecryptedConnector } from '@/database/models/connector';
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { PluginModel } from '@/database/models/plugin';
+import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
+import {
+ ConnectorMcpConnectionType,
+ ConnectorSourceType,
+ ConnectorStatus,
+} from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { buildCloudMcpManifest, cloudManifestTools } from '@/libs/mcp/cloudManifest';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { toClientToolSyncInputs } from '@/server/routers/lambda/_helpers/clientToolSyncInputs';
+import { canManageWorkspaceConnectors } from '@/server/routers/lambda/_helpers/connectorManagePolicy';
+import { deviceGateway } from '@/server/services/deviceGateway';
+
+import { listConnectorToolSyncInputs, writeConnectorToolSyncInputs } from './sync';
+
+const log = debug('lobe-server:connector:marketplace-install');
+
+interface MarketConnection {
+ auth?: { token?: string; type?: string };
+ configSchema?: unknown;
+ headers?: Record<string, string>;
+ type?: string;
+ url?: string;
+}
+
+/** The parts of a marketplace MCP manifest (`market.getMcpManifest`) an install reads. */
+export interface MarketMcpManifest {
+ api?: unknown[];
+ deploymentOptions?: { connection?: MarketConnection }[];
+ description?: string;
+ /**
+ * The market's hosted endpoint for a stdio server, when it runs one. The
+ * market serves it on the MCP's detail (`market.getMcpDetail`), not in the
+ * manifest: see {@link MarketplaceInstallOptions.readHostedEndpoint}.
+ */
+ haveCloudEndpoint?: unknown;
+ icon?: string;
+ name?: string;
+ tools?: unknown[];
+ version?: string;
+}
+
+export type MarketplaceDeployment =
+ | { auth?: MarketConnection['auth']; headers?: Record<string, string>; type: 'http'; url: string }
+ | { cloudEndPoint: unknown; headers?: Record<string, string>; type: 'cloud' };
+
+/**
+ * Why a marketplace MCP cannot be installed without the user:
+ * - `config`: it needs settings (an API key…) only the user can fill in;
+ * - `oauth`: it signs in with OAuth, which the user authorizes in a browser;
+ * - `local-only`: it has no remote endpoint, only a local (stdio) process;
+ * - `private-network`: its only HTTP endpoint is on localhost or a private
+ * network, which the server would reach through the user's device;
+ * - `no-tools`: it lists no tools, so the install would load nothing;
+ * - `conflict`: another connector already holds the identifier;
+ * - `in-progress`: an install of it started under
+ * {@link MARKETPLACE_INSTALL_LEASE_MS} ago and has not finished;
+ * - `forbidden`: the workspace lets only owners and admins add connectors.
+ */
+export type MarketplaceInstallBlocker =
+ | 'config'
+ | 'conflict'
+ | 'forbidden'
+ | 'in-progress'
+ | 'local-only'
+ | 'no-tools'
+ | 'oauth'
+ | 'private-network';
+
+export type MarketplaceInstallOutcome =
+ /** A connector was created, its tools synced, and the install marked finished. */
+ | { status: 'installed' }
+ /** A finished marketplace install already holds the identifier; nothing was written. */
+ | { status: 'exists' }
+ | { blocker: MarketplaceInstallBlocker; status: 'blocked' };
+
+export interface MarketplaceInstallScope {
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
+
+const doesConfigSchemaRequireInput = (configSchema: unknown) => {
+ if (!configSchema || typeof configSchema !== 'object') return false;
+ const { properties, required } = configSchema as {
+ properties?: Record<string, unknown>;
+ required?: unknown;
+ };
+
+ return (
+ (Array.isArray(required) && required.some(Boolean)) ||
+ (!!properties &&
+ Object.values(properties).some(
+ (property) => (property as { required?: unknown } | null)?.required === true,
+ ))
+ );
+};
+
+/**
+ * Pick the connection a server-side install uses, by the rules the web
+ * `installMCPPlugin` applies outside the desktop app: a market-hosted (`cloud`)
+ * endpoint for a stdio server first, then an HTTP endpoint. A stdio-only server
+ * needs a local process, which a server run cannot start.
+ *
+ * An HTTP endpoint the server would reach through the user's device (localhost
+ * or a private network, with a device gateway: `shouldConnectViaDevice`) is
+ * never taken: a listing could have that device reach its loopback or LAN
+ * services. Without a gateway the server connects to it itself, through the
+ * SSRF-safe fetch.
+ */
+const deploymentOptionsOf = (manifest: MarketMcpManifest) =>
+ Array.isArray(manifest.deploymentOptions) ? manifest.deploymentOptions : [];
+
+/** A stdio option: typed so, or neither typed nor given a URL. */
+const findStdioOption = (manifest: MarketMcpManifest) =>
+ deploymentOptionsOf(manifest).find(
+ (option) =>
+ option?.connection?.type === 'stdio' ||
+ (!option?.connection?.type && !option?.connection?.url),
+ );
+
+export const pickMarketplaceDeployment = (
+ manifest: MarketMcpManifest,
+ { deviceGatewayConfigured }: { deviceGatewayConfigured: boolean },
+): { deployment: MarketplaceDeployment } | { blocker: MarketplaceInstallBlocker } => {
+ const options = deploymentOptionsOf(manifest);
+ const httpOptions = options.filter(
+ (option) =>
+ option?.connection?.url && (option.connection.type === 'http' || !option.connection.type),
+ );
+ const serverReached = httpOptions.filter(
+ ({ connection }) =>
+ !shouldConnectViaDevice({ type: 'http', url: connection?.url }, { deviceGatewayConfigured }),
+ );
+ const httpOption =
+ serverReached.find((option) => option.connection?.type === 'http') ?? serverReached[0];
+ const stdioOption = findStdioOption(manifest);
+
+ if (stdioOption && manifest.haveCloudEndpoint) {
+ const connection = stdioOption.connection ?? {};
+ if (doesConfigSchemaRequireInput(connection.configSchema)) return { blocker: 'config' };
+ return {
+ deployment: {
+ cloudEndPoint: manifest.haveCloudEndpoint,
+ headers: connection.headers,
+ type: 'cloud',
+ },
+ };
+ }
+
+ if (httpOption?.connection?.url) {
+ const { auth, configSchema, headers, url } = httpOption.connection;
+ if (doesConfigSchemaRequireInput(configSchema)) return { blocker: 'config' };
+ if (auth?.type === 'oauth2') return { blocker: 'oauth' };
+ return { deployment: { auth, headers, type: 'http', url } };
+ }
+
+ return { blocker: httpOptions.length > 0 ? 'private-network' : 'local-only' };
+};
+
+/**
+ * How long an unfinished marketplace install may hold its row: past it, the
+ * install is taken for dead (its process stopped between creating the row and
+ * marking it), and the next install of the same server replaces the row. It is
+ * well beyond the time one server run may take.
+ */
+export const MARKETPLACE_INSTALL_LEASE_MS = 10 * 60 * 1000;
+
+type HolderVerdict =
+ 'exists' | 'replace' | Extract<MarketplaceInstallBlocker, 'conflict' | 'in-progress'>;
+
+/**
+ * What an install does about the base row already holding its identifier:
+ * - `exists`: a finished marketplace install, left as it is. That includes a
+ * connected pre-connector install, which its plugin row (with or without a
+ * manifest) lets runs call, as `isMarketplaceInstallRunnable` does;
+ * - `in-progress`: an unfinished marketplace install inside the lease, which
+ * its install (this server's, or the web's) may still finish;
+ * - `replace`: the caller's own unfinished marketplace install past the lease,
+ * which no run can call: a retry takes it over;
+ * - `conflict`: anything else (a custom or builtin connector, a row without an
+ * endpoint, another member's row).
+ */
+const judgeHolder = (
+ holder: {
+ mcpConnectionType?: string | null;
+ mcpServerUrl?: string | null;
+ metadata?: unknown;
+ sourceType?: string | null;
+ status?: string | null;
+ updatedAt: Date;
+ userId: string;
+ },
+ { hasPluginRow, userId }: { hasPluginRow: boolean; userId: string },
+): HolderVerdict => {
+ if (holder.sourceType !== ConnectorSourceType.marketplace || !hasCallableMcpEndpoint(holder))
+ return 'conflict';
+ if (isMarketplaceInstallCompleted(holder.metadata)) return 'exists';
+ if (hasPluginRow && holder.status === ConnectorStatus.connected) return 'exists';
+ if (Date.now() - holder.updatedAt.getTime() < MARKETPLACE_INSTALL_LEASE_MS) return 'in-progress';
+ return holder.userId === userId ? 'replace' : 'conflict';
+};
+
+const holderOutcome = (verdict: Exclude<HolderVerdict, 'replace'>): MarketplaceInstallOutcome =>
+ verdict === 'exists' ? { status: 'exists' } : { blocker: verdict, status: 'blocked' };
+
+const VERDICT_PRECEDENCE: HolderVerdict[] = ['conflict', 'in-progress', 'exists', 'replace'];
+
+/**
+ * What an install does about every base row holding its identifier: rows
+ * written before the identifier lock may duplicate it, and a run resolves to
+ * one of them, so the install answers `exists` only when no duplicate is a
+ * conflict or an install in progress, and replaces only when every one may go
+ * (as the claim does). `undefined` without a holder.
+ */
+const judgeHolders = (
+ holders: Parameters<typeof judgeHolder>[0][],
+ context: Parameters<typeof judgeHolder>[1],
+): HolderVerdict | undefined => {
+ const verdicts = new Set(holders.map((holder) => judgeHolder(holder, context)));
+ return VERDICT_PRECEDENCE.find((verdict) => verdicts.has(verdict));
+};
+
+/**
+ * The outcome of an install that lost the row to a live holder (read after the
+ * claim, or after a re-add): no holder left, or a lease that ran out since, is
+ * the next try's to take.
+ */
+const liveHolderOutcome = (
+ holders: Parameters<typeof judgeHolder>[0][],
+ context: Parameters<typeof judgeHolder>[1],
+): MarketplaceInstallOutcome => {
+ const verdict = judgeHolders(holders, context) ?? 'in-progress';
+ return holderOutcome(verdict === 'replace' ? 'in-progress' : verdict);
+};
+
+/** The member policy the connector router's `create` applies to a workspace connector. */
+const canAddConnector = async ({ serverDB, userId, workspaceId }: MarketplaceInstallScope) => {
+ if (!workspaceId) return true;
+ const member = await new WorkspaceMemberModel(serverDB, userId).getMember(workspaceId, userId);
+ if (!member) return false;
+ return canManageWorkspaceConnectors({
+ serverDB,
+ userId,
+ workspaceId,
+ workspaceRole: member.role,
+ });
+};
+
+/**
+ * Tags the row an install creates until it marks it finished, so a rollback
+ * only deletes a row that is still this install's: a re-add of the identifier
+ * meanwhile (the web install) rewrites the metadata, and the row is its own.
+ */
+const INSTALL_ATTEMPT_KEY = 'marketplaceInstallAttempt';
+
+/**
+ * Install a marketplace MCP from the server (Agent Builder / Agent Management)
+ * the way the web install does: a `marketplace` row in `user_connectors` with
+ * its tools, then the `marketplaceInstalled` mark, which alone makes the row
+ * callable. No `user_installed_plugins` row is written.
+ *
+ * The row is claimed in one serialized step (`createUnlessIdentifierHeld`), so
+ * concurrent installs of one server create it once. The install never
+ * overwrites a row someone may still use, only an interrupted install's (see
+ * {@link judgeHolder}), so a failed tool sync only has to delete the row it
+ * created. Its rollback and its finishing writes (tools, status, mark) apply
+ * only while no one has re-added the identifier over the row.
+ *
+ * An HTTP server's tools are the ones it lists, each with the approval the
+ * marketplace manifest gives it: the listing cannot carry one. The row keeps
+ * those per-tool policies, so every later sync applies them too, and a tool
+ * the manifest does not declare needs approval on every call.
+ */
+export interface MarketplaceInstallOptions {
+ /**
+ * Reads whether the market hosts the server (its detail's
+ * `haveCloudEndpoint`), which the manifest does not say. Called only when it
+ * decides the deployment: an install still to place, of a server with a
+ * stdio option. A rejection fails the install before anything is written.
+ */
+ readHostedEndpoint?: () => Promise<unknown>;
+}
+
+export const installMarketplaceMcpConnector = async (
+ scope: MarketplaceInstallScope,
+ identifier: string,
+ manifest: MarketMcpManifest,
+ { readHostedEndpoint }: MarketplaceInstallOptions = {},
+): Promise<MarketplaceInstallOutcome> => {
+ const { serverDB, userId, workspaceId } = scope;
+
+ const [holders, pluginRow] = await Promise.all([
+ new ConnectorModel(serverDB, userId, workspaceId).queryBaseHolders(identifier),
+ new PluginModel(serverDB, userId, workspaceId).findById(identifier),
+ ]);
+ const holderContext = { hasPluginRow: !!pluginRow, userId };
+ // Answered before any write; the claim below judges the holders again under its lock.
+ const verdict = judgeHolders(holders, holderContext);
+ if (verdict && verdict !== 'replace') return holderOutcome(verdict);
+
+ if (!(await canAddConnector(scope))) return { blocker: 'forbidden', status: 'blocked' };
+
+ const picked = pickMarketplaceDeployment(
+ readHostedEndpoint && manifest.haveCloudEndpoint === undefined && findStdioOption(manifest)
+ ? { ...manifest, haveCloudEndpoint: await readHostedEndpoint() }
+ : manifest,
+ { deviceGatewayConfigured: deviceGateway.isConfigured },
+ );
+ if ('blocker' in picked) return { blocker: picked.blocker, status: 'blocked' };
+ const { deployment } = picked;
+
+ // The tools the market lists, each with the approval its manifest asks for: a
+ // cloud server's whole tool list, and what an HTTP server's own listing lacks.
+ const marketTools =
+ manifest.api || manifest.tools
+ ? cloudManifestTools(
+ buildCloudMcpManifest({
+ data: manifest,
+ plugin: { description: manifest.description, icon: manifest.icon, identifier },
+ }),
+ )
+ : [];
+ // Checked before writing
+ if (deployment.type === 'cloud' && marketTools.length === 0)
+ return { blocker: 'no-tools', status: 'blocked' };
+
+ const token =
+ deployment.type === 'http' && deployment.auth?.type === 'bearer'
+ ? deployment.auth.token
+ : undefined;
+ // Only stored credentials need the vault key.
+ const gateKeeper = token ? await KeyVaultsGateKeeper.initWithEnvKey() : undefined;
+ const connectorModel = new ConnectorModel(serverDB, userId, workspaceId, gateKeeper);
+ const connectorToolModel = new ConnectorToolModel(serverDB, userId, workspaceId);
+
+ // The version goes with each call the market is told about.
+ const metadata: NonNullable<DecryptedConnector['metadata']> = {
+ avatar: manifest.icon,
+ description: manifest.description,
+ version: manifest.version,
+ };
+ if (deployment.headers) metadata.customHeaders = deployment.headers;
+ if (deployment.type === 'cloud') {
+ metadata.cloudEndPoint = deployment.cloudEndPoint;
+ } else {
+ // The manifest's approval of each tool, for this sync and every later one:
+ // nor may its server add tools the market never declared that run unasked
+ metadata[MARKETPLACE_TOOL_POLICIES_KEY] = Object.fromEntries(
+ marketTools.map((tool) => [tool.toolName, tool.humanIntervention ?? null]),
+ );
+ }
+
+ const attempt = { [INSTALL_ATTEMPT_KEY]: randomUUID() };
+ const claim = await connectorModel.createUnlessIdentifierHeld(
+ {
+ credentials: token ? JSON.stringify({ token, type: 'bearer' }) : null,
+ identifier,
+ isEnabled: true,
+ mcpConnectionType:
+ deployment.type === 'cloud'
+ ? ConnectorMcpConnectionType.cloud
+ : ConnectorMcpConnectionType.http,
+ mcpServerUrl: deployment.type === 'http' ? deployment.url : null,
+ metadata: { ...metadata, ...attempt },
+ name: manifest.name || identifier,
+ sourceType: ConnectorSourceType.marketplace,
+ status: ConnectorStatus.disconnected,
+ },
+ { canReplace: (holder) => judgeHolder(holder, holderContext) === 'replace' },
+ );
+ if ('holder' in claim)
+ return liveHolderOutcome(await connectorModel.queryBaseHolders(identifier), holderContext);
+ const { created } = claim;
+ // The identifier may be re-added over the row meanwhile (the web install),
+ // which then owns it: the rollback leaves a re-added row as it is.
+ const rollback = () => connectorModel.deleteIfMetadataContains(created.id, attempt);
+
+ try {
+ // Listed before anything is written to the row (the server's MCP client
+ // sends every HTTP request through the SSRF-safe fetch), held to the market
+ // tool policies it stores. Never on a device (no `serverDB`): the picked
+ // endpoint is one the server lists itself, or the listing fails.
+ const syncInputs =
+ deployment.type === 'cloud'
+ ? await toClientToolSyncInputs(marketTools, userId)
+ : (
+ await listConnectorToolSyncInputs(
+ created.id,
+ { connectorModel, connectorToolModel, serverDB: undefined, userId },
+ {
+ humanInterventions: new Map(
+ marketTools.map((tool) => [tool.toolName, tool.humanIntervention]),
+ ),
+ },
+ )
+ ).syncInputs;
+
+ if (syncInputs.length === 0) {
+ await rollback();
+ return { blocker: 'no-tools', status: 'blocked' };
+ }
+
+ // The tools, the status and the mark, which alone makes the row callable,
+ // land together, and only while the row is still this install's: the
+ // conditional mark write holds the row's lock to the commit, so a re-add
+ // (the web install, which takes the same lock) either waits for it or, made
+ // before, leaves this install nothing to write over its metadata (headers
+ // its user entered…), tools or status.
+ const finished = await serverDB.transaction(async (tx) => {
+ const txDB = tx as unknown as LobeChatDatabase;
+ const txConnectorModel = new ConnectorModel(txDB, userId, workspaceId);
+ const marked = await txConnectorModel.updateMetadataIfContains(created.id, attempt, {
+ ...metadata,
+ [MARKETPLACE_INSTALL_COMPLETED_KEY]: true,
+ });
+ if (!marked) return false;
+ await writeConnectorToolSyncInputs(created.id, syncInputs, {
+ connectorModel: txConnectorModel,
+ connectorToolModel: new ConnectorToolModel(txDB, userId, workspaceId),
+ });
+ return true;
+ });
+ if (!finished)
+ return liveHolderOutcome(await connectorModel.queryBaseHolders(identifier), holderContext);
+ } catch (error) {
+ // A failed rollback is only logged: an unmarked row stays uncallable.
+ await rollback().catch((rollbackError) => {
+ log('rollback of connector %s (%s) failed: %O', created.id, identifier, rollbackError);
+ });
+ throw error;
+ }
+
+ return { status: 'installed' };
+};
diff --git a/apps/server/src/services/connector/sync.test.ts b/apps/server/src/services/connector/sync.test.ts
index d0c3f8d86a0..cdf1be2ee16 100644
--- a/apps/server/src/services/connector/sync.test.ts
+++ b/apps/server/src/services/connector/sync.test.ts
@@ -18,7 +18,10 @@ vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: gateway }));
vi.mock('@/server/services/mcp/deviceTunnel', () => ({ listMcpToolsOnDevice: vi.fn() }));
const mcpAppsEnabled = vi.hoisted(() => vi.fn().mockResolvedValue(false));
vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mcpAppsEnabled }));
-vi.mock('./tokens', () => ({ ensureFreshConnectorToken: async (connector: unknown) => connector }));
+vi.mock('./tokens', () => ({
+ ensureFreshConnectorToken: async (connector: unknown) => connector,
+ ensureFreshLinkToken: async (_connector: unknown, link: unknown) => link,
+}));
const httpConnector = (
credentials: ConnectorCredentials | null,
@@ -253,7 +256,7 @@ describe('a connector bound to a device', () => {
findById: async () => stdioConnector({ boundDeviceId: 'ws-nas' }, 'ws1'),
updateStatus: vi.fn(),
} as any,
- connectorToolModel: { upsertMany: vi.fn() } as any,
+ connectorToolModel: { queryByConnector: async () => [], upsertMany: vi.fn() } as any,
serverDB: {} as any,
userId: 'another-member',
});
@@ -312,7 +315,7 @@ describe('syncConnectorToolsById', () => {
findById: async () => httpConnector(null),
updateStatus,
} as any,
- connectorToolModel: { upsertMany } as any,
+ connectorToolModel: { queryByConnector: async () => [], upsertMany } as any,
});
expect(result).toEqual({ toolCount: 2 });
@@ -322,6 +325,175 @@ describe('syncConnectorToolsById', () => {
]);
});
+ it('applies the approval a marketplace manifest gives a listed tool', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { inputSchema: { type: 'object' }, name: 'search' },
+ { inputSchema: { type: 'object' }, name: 'send' },
+ { inputSchema: { type: 'object' }, name: 'delete' },
+ ]);
+ const upsertMany = vi.fn();
+
+ await syncConnectorToolsById(
+ 'c1',
+ {
+ connectorModel: { findById: async () => httpConnector(null), updateStatus: vi.fn() } as any,
+ connectorToolModel: { upsertMany } as any,
+ },
+ {
+ humanInterventions: new Map([
+ ['send', 'required'],
+ ['delete', 'always'],
+ ]),
+ },
+ );
+
+ expect(upsertMany).toHaveBeenCalledWith('c1', [
+ expect.objectContaining({ defaultPermission: 'auto', metadata: null, toolName: 'search' }),
+ expect.objectContaining({
+ defaultPermission: 'needs_approval',
+ metadata: null,
+ toolName: 'send',
+ }),
+ // An `always` stays mandatory past auto-run
+ expect.objectContaining({
+ defaultPermission: 'needs_approval',
+ metadata: { mandatoryApproval: true },
+ toolName: 'delete',
+ }),
+ ]);
+ });
+
+ it('keeps the mandatory mark a tool has when no marketplace policy is supplied', async () => {
+ // A refresh (background, manual, OAuth callback) only has the server's
+ // listing, which cannot say whether the manifest's `always` still applies
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { inputSchema: { type: 'object' }, name: 'search' },
+ { _meta: { ui: { visibility: ['model'] } }, inputSchema: { type: 'object' }, name: 'delete' },
+ ]);
+ const upsertMany = vi.fn();
+
+ await syncConnectorToolsById('c1', {
+ connectorModel: { findById: async () => httpConnector(null), updateStatus: vi.fn() } as any,
+ connectorToolModel: {
+ queryByConnector: async () => [
+ { metadata: null, permission: 'auto', toolName: 'search' },
+ { metadata: { mandatoryApproval: true }, permission: 'auto', toolName: 'delete' },
+ ],
+ upsertMany,
+ } as any,
+ });
+
+ expect(upsertMany).toHaveBeenCalledWith('c1', [
+ expect.objectContaining({ metadata: null, toolName: 'search' }),
+ expect.objectContaining({
+ metadata: { mandatoryApproval: true, visibility: ['model'] },
+ toolName: 'delete',
+ }),
+ ]);
+ });
+
+ it.each([
+ [
+ 'an install applies the manifest policy',
+ { humanInterventions: new Map([['board', 'always']]) },
+ ],
+ ['a refresh keeps the stored mark', {}],
+ ])(
+ "keeps a mandatory tool's MCP App metadata under the mcp_apps flag: %s",
+ async (_case, options) => {
+ mcpAppsEnabled.mockResolvedValueOnce(true);
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ {
+ _meta: {
+ 'lobehub/ui': { entrypoints: [{ type: 'thread' }] },
+ 'ui': { resourceUri: 'ui://board', visibility: ['model', 'app'] },
+ },
+ inputSchema: { type: 'object' },
+ name: 'board',
+ },
+ ]);
+ const upsertMany = vi.fn();
+
+ await syncConnectorToolsById(
+ 'c1',
+ {
+ connectorModel: {
+ findById: async () => httpConnector(null),
+ updateStatus: vi.fn(),
+ } as any,
+ connectorToolModel: {
+ queryByConnector: async () => [
+ { metadata: { mandatoryApproval: true }, permission: 'auto', toolName: 'board' },
+ ],
+ upsertMany,
+ } as any,
+ userId: 'user-1',
+ },
+ options,
+ );
+
+ expect(upsertMany).toHaveBeenCalledWith('c1', [
+ expect.objectContaining({
+ metadata: expect.objectContaining({
+ entrypoints: [{ type: 'thread' }],
+ mandatoryApproval: true,
+ threadEntry: expect.objectContaining({ toolName: 'board' }),
+ visibility: ['model', 'app'],
+ }),
+ toolName: 'board',
+ }),
+ ]);
+ },
+ );
+
+ it.each([
+ [
+ 'an install, with the manifest policy',
+ { humanInterventions: new Map<string, unknown>([['send', 'required']]) },
+ ],
+ ['a refresh, with the listing alone', {}],
+ ])(
+ 'applies the market policies the connector stores, always for an undeclared tool: %s',
+ async (_case, options) => {
+ // The server lists a tool the market never did, and one it renamed
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { inputSchema: { type: 'object' }, name: 'search' },
+ { inputSchema: { type: 'object' }, name: 'send' },
+ { inputSchema: { type: 'object' }, name: 'exfiltrate' },
+ { inputSchema: { type: 'object' }, name: 'search_v2' },
+ ]);
+ const upsertMany = vi.fn();
+
+ await syncConnectorToolsById(
+ 'c1',
+ {
+ connectorModel: {
+ findById: async () =>
+ httpConnector(null, {
+ marketplaceToolPolicies: { search: null, send: 'required' },
+ }),
+ updateStatus: vi.fn(),
+ } as any,
+ connectorToolModel: { queryByConnector: async () => [], upsertMany } as any,
+ },
+ options,
+ );
+
+ const [, inputs] = upsertMany.mock.calls[0];
+ expect(
+ Object.fromEntries(
+ inputs.map((tool: any) => [tool.toolName, [tool.defaultPermission, tool.metadata]]),
+ ),
+ ).toEqual({
+ exfiltrate: ['needs_approval', { mandatoryApproval: true }],
+ search: ['auto', null],
+ search_v2: ['needs_approval', { mandatoryApproval: true }],
+ // The stored policy holds without the install's manifest too
+ send: ['needs_approval', null],
+ });
+ },
+ );
+
it('drops only the auto tools the server no longer lists when asked to', async () => {
vi.mocked(mcpService.listRawTools).mockResolvedValue([
{ description: 'Kept', inputSchema: { type: 'object' }, name: 'kept' },
@@ -360,7 +532,7 @@ describe('syncConnectorToolsById', () => {
findById: async () => httpConnector(null),
updateStatus: vi.fn(),
} as any,
- connectorToolModel: { upsertMany: vi.fn() } as any,
+ connectorToolModel: { queryByConnector: async () => [], upsertMany: vi.fn() } as any,
userId: 'user-1',
});
@@ -370,4 +542,88 @@ describe('syncConnectorToolsById', () => {
});
},
);
+
+ describe('an OAuth connector with accounts', () => {
+ const oauthConnector = () =>
+ ({ ...httpConnector(null), oidcConfig: { clientId: 'client-1' } }) as DecryptedConnector;
+ const account = (id: string, accessToken: string) => ({
+ credentials: { accessToken, type: 'oauth2' },
+ id,
+ name: id,
+ status: 'connected',
+ tokenExpiresAt: null,
+ userConnectorId: 'c1',
+ });
+ const setup = (links: ReturnType<typeof account>[]) => {
+ const connectorModel = { findById: async () => oauthConnector(), updateStatus: vi.fn() };
+ const connectorLinkModel = { listByConnectorIds: async () => links, updateStatus: vi.fn() };
+ const connectorToolModel = { queryByConnector: async () => [], upsertMany: vi.fn() };
+ const ctx = { connectorLinkModel, connectorModel, connectorToolModel } as any;
+ return { connectorLinkModel, connectorModel, connectorToolModel, ctx };
+ };
+
+ it('lists as the account asked for and marks it, and the connector, connected', async () => {
+ vi.mocked(mcpService.listRawTools).mockResolvedValue([
+ { inputSchema: { type: 'object' }, name: 'search' },
+ ]);
+ const { connectorLinkModel, connectorModel, connectorToolModel, ctx } = setup([
+ account('lnk_a', 'token-a'),
+ account('lnk_b', 'token-b'),
+ ]);
+
+ await expect(syncConnectorToolsById('c1', ctx, { linkId: 'lnk_b' })).resolves.toEqual({
+ toolCount: 1,
+ });
+
+ expect(mcpService.listRawTools).toHaveBeenLastCalledWith(
+ expect.objectContaining({ auth: { accessToken: 'token-b', type: 'oauth2' } }),
+ expect.anything(),
+ );
+ expect(connectorToolModel.upsertMany).toHaveBeenCalledWith('c1', [
+ expect.objectContaining({ toolName: 'search' }),
+ ]);
+ expect(connectorLinkModel.updateStatus).toHaveBeenCalledWith('c1', 'lnk_b', 'connected');
+ expect(connectorModel.updateStatus).toHaveBeenCalledWith('c1', 'connected');
+ });
+
+ it('marks only the failing account when the connector has others', async () => {
+ vi.mocked(mcpService.listRawTools).mockRejectedValue(new Error('unauthorized'));
+ const { connectorLinkModel, connectorModel, connectorToolModel, ctx } = setup([
+ account('lnk_a', 'token-a'),
+ account('lnk_b', 'token-b'),
+ ]);
+
+ await expect(syncConnectorToolsById('c1', ctx, { linkId: 'lnk_b' })).rejects.toThrow(
+ 'unauthorized',
+ );
+
+ expect(connectorLinkModel.updateStatus).toHaveBeenCalledExactlyOnceWith(
+ 'c1',
+ 'lnk_b',
+ 'error',
+ );
+ expect(connectorModel.updateStatus).not.toHaveBeenCalled();
+ expect(connectorToolModel.upsertMany).not.toHaveBeenCalled();
+ });
+
+ it('marks the connector failed too when the failing account is its only one', async () => {
+ vi.mocked(mcpService.listRawTools).mockRejectedValue(new Error('unauthorized'));
+ const { connectorLinkModel, connectorModel, ctx } = setup([account('lnk_a', 'token-a')]);
+
+ await expect(syncConnectorToolsById('c1', ctx)).rejects.toThrow('unauthorized');
+
+ expect(connectorLinkModel.updateStatus).toHaveBeenCalledWith('c1', 'lnk_a', 'error');
+ expect(connectorModel.updateStatus).toHaveBeenCalledWith('c1', 'error');
+ });
+
+ it('refuses an account the connector no longer has before listing', async () => {
+ vi.mocked(mcpService.listRawTools).mockClear();
+ const { ctx } = setup([account('lnk_a', 'token-a')]);
+
+ await expect(syncConnectorToolsById('c1', ctx, { linkId: 'lnk_gone' })).rejects.toThrow(
+ 'Connector account no longer exists',
+ );
+ expect(mcpService.listRawTools).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.ts
index d7de77168d2..38d38dc4ed6 100644
--- a/apps/server/src/services/connector/sync.ts
+++ b/apps/server/src/services/connector/sync.ts
@@ -1,3 +1,10 @@
+import {
+ hasMandatoryApproval,
+ MANDATORY_APPROVAL_KEY,
+ marketplaceToolIntervention,
+ marketplaceToolPoliciesOf,
+ withMandatoryApprovalMark,
+} from '@lobechat/const';
import {
buildMcpToolMetadata,
getMcpAppEntrypoints,
@@ -12,8 +19,8 @@ import {
} from '@lobechat/utils/mcpEndpoint';
import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';
-import type { ConnectorLinkModel } from '@/database/models/connectorLink';
-import type { ConnectorToolModel } from '@/database/models/connectorTool';
+import type { ConnectorLinkModel, DecryptedConnectorLink } from '@/database/models/connectorLink';
+import type { ConnectorToolModel, SyncToolInput } from '@/database/models/connectorTool';
import type { ConnectorCredentials } from '@/database/schemas';
import {
ConnectorMcpConnectionType,
@@ -22,6 +29,7 @@ import {
} from '@/database/schemas';
import type { AuthConfig, McpTool } from '@/libs/mcp';
import { inferCrudType } from '@/libs/mcp/utils';
+import { resolveConnectorToolPermission } from '@/server/routers/lambda/_helpers/connectorToolPermission';
import { deviceGateway } from '@/server/services/deviceGateway';
import { mcpService } from '@/server/services/mcp';
import { listMcpToolsOnDevice } from '@/server/services/mcp/deviceTunnel';
@@ -122,8 +130,6 @@ export const buildHttpAuthFromCredentials = (
};
export interface ConnectorToolSyncOptions {
- /** List with this account's credentials instead of the connector's primary one. */
- linkId?: string;
/**
* Drop the `auto` tools the server no longer lists, so they stop being
* advertised: eval contracts, and an MCP install or reinstall, whose tool
@@ -146,6 +152,36 @@ export const pruneMissingAutoConnectorTools = async (
await connectorToolModel.deleteToolsNotIn(connectorId, [...listedToolNames, ...tombstones]);
};
+type ConnectorToolWriteContext = {
+ connectorModel: Pick<ConnectorModel, 'updateStatus'>;
+ connectorToolModel: Pick<
+ ConnectorToolModel,
+ 'deleteToolsNotIn' | 'queryByConnector' | 'upsertMany'
+ >;
+};
+
+/**
+ * Store the connector's tool sync inputs and mark it `connected`. A tool
+ * synced before keeps the permission it has.
+ */
+export const writeConnectorToolSyncInputs = async (
+ connectorId: string,
+ syncInputs: SyncToolInput[],
+ ctx: ConnectorToolWriteContext,
+ options: ConnectorToolSyncOptions = {},
+): Promise<{ toolCount: number }> => {
+ await ctx.connectorToolModel.upsertMany(connectorId, syncInputs);
+ if (options.pruneMissingAutoTools) {
+ await pruneMissingAutoConnectorTools(
+ ctx.connectorToolModel,
+ connectorId,
+ syncInputs.map((tool) => tool.toolName),
+ );
+ }
+ await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.connected);
+ return { toolCount: syncInputs.length };
+};
+
/**
* A connector this server must not connect to itself (stdio, local network, or
* set to connect through the device) is listed on a device through the device
@@ -187,28 +223,55 @@ const listOnDevice = async (
});
};
+export interface ConnectorToolListOptions {
+ /**
+ * By tool name, the `humanIntervention` a marketplace manifest gives a tool
+ * the server lists, which an MCP listing cannot carry (an HTTP marketplace
+ * install). It applies as a client-listed tool's does in
+ * `toClientToolSyncInputs`. Without it (a refresh), a synced tool keeps the
+ * mandatory approval it has. Either way, market policies the connector
+ * stores (`marketplaceToolPoliciesOf`) take precedence over it.
+ */
+ humanInterventions?: ReadonlyMap<string, unknown>;
+ /** List with this account's credentials instead of the connector's primary one. */
+ linkId?: string;
+}
+
+/** The OAuth account a listing ran as, which a sync marks with the outcome. */
+export interface ConnectorToolListingAccount {
+ /** The account listed as; none for a connector without accounts. */
+ link?: DecryptedConnectorLink;
+ /** The connector's accounts: with two or more, one account's failure leaves the connector's status as it is. */
+ linkCount: number;
+}
+
+export interface ConnectorToolListing extends ConnectorToolListingAccount {
+ syncInputs: SyncToolInput[];
+}
+
/**
- * Connect to a connector's MCP server, fetch its tool list, and sync it into
- * `user_connector_tools`. Refreshes the OAuth token first when needed, and
- * updates the connector status (`connected` on success, `error` on failure).
- *
- * Shared by the `syncTools` tRPC mutation and the OAuth callback so a connector
- * has its tools immediately after authorization β€” no client round-trip needed.
+ * Connect to a connector's MCP server and build the sync inputs of the tools
+ * it lists, refreshing the OAuth token first when needed. Writes no tool and
+ * no status: {@link syncConnectorToolsById} does, as does a caller that must
+ * write them only while the row is still its own (a marketplace install).
*/
-export const syncConnectorToolsById = async (
+export const listConnectorToolSyncInputs = async (
connectorId: string,
/**
* `userId` decides the `mcp_apps` flag: with it on, view-only tools are listed
* too. `serverDB` finds the user's device for a connector the server can't
* reach itself (`shouldConnectViaDevice`). Required, so each caller decides:
- * `undefined` fails such a sync instead of tunneling it to a device.
+ * `undefined` fails such a listing instead of tunneling it to a device.
*/
ctx: ConnectorToolSyncContext & {
serverDB: LobeChatDatabase | undefined;
userId?: string | null;
},
- options: ConnectorToolSyncOptions = {},
-): Promise<{ toolCount: number }> => {
+ options: ConnectorToolListOptions & {
+ /** Called when the server cannot be reached or refuses the listing, before it rethrows. */
+ onListError?: (account: ConnectorToolListingAccount) => Promise<void>;
+ } = {},
+): Promise<ConnectorToolListing> => {
let connector = await ctx.connectorModel.findById(connectorId);
if (!connector) throw new Error('Connector not found');
@@ -240,40 +303,94 @@ export const syncConnectorToolsById = async (
mcpApps,
}));
} catch (err) {
- if (link) await getConnectorLinkModel(ctx).updateStatus(connectorId, link.id, 'error');
- if (links.length < 2) await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.error);
+ await options.onListError?.({ link, linkCount: links.length });
throw err;
}
- const syncInputs = rawTools.map((t) => ({
- crudType: inferCrudType(t.name),
- description: t.description,
- inputSchema: t.inputSchema as Record<string, unknown>,
+ // Only an install holds the marketplace's policy. Any other sync (the
+ // background refresh, a manual one, the OAuth callback) has the listing
+ // alone, which cannot tell whether a manifest's `always` still holds: the
+ // tools it marked mandatory stay so, or auto-run would skip their approval.
+ const keptMandatory = options.humanInterventions
+ ? new Set<string>()
+ : new Set(
+ (await ctx.connectorToolModel.queryByConnector(connectorId))
+ .filter((tool) => hasMandatoryApproval(tool.metadata))
+ .map((tool) => tool.toolName),
+ );
+
+ // The market's per-tool policies, stored at the install, decide every sync:
+ // a declared tool the server only lists later keeps its policy, and one the
+ // market never declared (added since, or renamed) gets no auto-run
+ const marketPolicies = marketplaceToolPoliciesOf(connector.metadata);
+
+ const syncInputs = rawTools.map((t) => {
+ const humanIntervention = marketplaceToolIntervention(
+ marketPolicies,
+ t.name,
+ options.humanInterventions?.get(t.name),
+ );
// Kept even for view-only tools: a view's call must find the tool synced,
// while the manifest build leaves it out of the model's tool list.
- metadata: buildMcpToolMetadata(
- resolveMcpUiToolMeta(t._meta, false).visibility,
- mcpApps
- ? {
- ...resolveMcpUiToolMeta(t._meta),
- entrypoints: resolveMcpUiToolMeta(t._meta).entrypoints ?? [],
- threadEntry: getMcpAppEntrypoints([t], true)[0],
- }
- : undefined,
- ),
- toolName: t.name,
- }));
-
- await ctx.connectorToolModel.upsertMany(connectorId, syncInputs);
- if (options.pruneMissingAutoTools) {
- await pruneMissingAutoConnectorTools(
- ctx.connectorToolModel,
- connectorId,
- syncInputs.map((tool) => tool.toolName),
+ const metadata = withMandatoryApprovalMark(
+ buildMcpToolMetadata(
+ resolveMcpUiToolMeta(t._meta, false).visibility,
+ mcpApps
+ ? {
+ ...resolveMcpUiToolMeta(t._meta),
+ entrypoints: resolveMcpUiToolMeta(t._meta).entrypoints ?? [],
+ threadEntry: getMcpAppEntrypoints([t], true)[0],
+ }
+ : undefined,
+ ),
+ humanIntervention,
);
- }
- if (link) await getConnectorLinkModel(ctx).updateStatus(connectorId, link.id, 'connected');
- await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.connected);
+ return {
+ crudType: inferCrudType(t.name),
+ defaultPermission: resolveConnectorToolPermission(humanIntervention),
+ description: t.description,
+ inputSchema: t.inputSchema as Record<string, unknown>,
+ metadata: keptMandatory.has(t.name)
+ ? { ...metadata, [MANDATORY_APPROVAL_KEY]: true }
+ : metadata,
+ toolName: t.name,
+ };
+ });
- return { toolCount: syncInputs.length };
+ return { link, linkCount: links.length, syncInputs };
+};
+
+/**
+ * Connect to a connector's MCP server, fetch its tool list, and sync it into
+ * `user_connector_tools`. Refreshes the OAuth token first when needed, and
+ * updates the connector status (`connected` on success, `error` on failure),
+ * and that of the account it listed as.
+ *
+ * Shared by the `syncTools` tRPC mutation and the OAuth callback so a connector
+ * has its tools immediately after authorization β€” no client round-trip needed.
+ */
+export const syncConnectorToolsById = async (
+ connectorId: string,
+ /** As {@link listConnectorToolSyncInputs} takes it. */
+ ctx: ConnectorToolSyncContext & {
+ serverDB: LobeChatDatabase | undefined;
+ userId?: string | null;
+ },
+ options: ConnectorToolSyncOptions & ConnectorToolListOptions = {},
+): Promise<{ toolCount: number }> => {
+ const { pruneMissingAutoTools, ...listOptions } = options;
+ const { link, syncInputs } = await listConnectorToolSyncInputs(connectorId, ctx, {
+ ...listOptions,
+ onListError: async (account) => {
+ if (account.link)
+ await getConnectorLinkModel(ctx).updateStatus(connectorId, account.link.id, 'error');
+ if (account.linkCount < 2)
+ await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.error);
+ },
+ });
+ const result = await writeConnectorToolSyncInputs(connectorId, syncInputs, ctx, {
+ pruneMissingAutoTools,
+ });
+ if (link) await getConnectorLinkModel(ctx).updateStatus(connectorId, link.id, 'connected');
+ return result;
};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts
index 28f2bda5253..64cd5cd5072 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts
@@ -8,6 +8,7 @@ const {
mockCreatePlugin,
mockFindById,
mockGetMcpManifest,
+ mockInstallMarketplaceConnector,
mockQueryPlugins,
mockResolveConnectors,
mockUpdatePlugin,
@@ -23,6 +24,7 @@ const {
mockCreatePlugin: vi.fn(),
mockFindById: vi.fn(),
mockGetMcpManifest: vi.fn(),
+ mockInstallMarketplaceConnector: vi.fn(),
mockQueryPlugins: vi.fn(),
mockResolveConnectors: vi.fn(),
mockUpdatePlugin: vi.fn(),
@@ -71,10 +73,14 @@ vi.mock('@/database/models/plugin', () => ({
vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn(function () {
- return { resolveAll: mockResolveConnectors };
+ return { queryAvailableForAgent: mockResolveConnectors, resolveAll: mockResolveConnectors };
}),
}));
+vi.mock('@/server/services/connector/marketplaceInstall', () => ({
+ installMarketplaceMcpConnector: mockInstallMarketplaceConnector,
+}));
+
vi.mock('@/database/repositories/aiInfra', () => ({
AiInfraRepos: vi.fn(function () {
return {
@@ -86,7 +92,8 @@ vi.mock('@/database/repositories/aiInfra', () => ({
vi.mock('@/server/services/discover', () => ({
DiscoverService: vi.fn(function () {
- return { getMcpManifest: mockGetMcpManifest };
+ // The market's detail of an MCP it does not host
+ return { getMcpDetail: async () => ({}), getMcpManifest: mockGetMcpManifest };
}),
}));
@@ -117,6 +124,7 @@ describe('agentBuilderRuntime', () => {
mockQueryPlugins.mockResolvedValue([]);
mockFindById.mockResolvedValue(undefined);
mockGetMcpManifest.mockRejectedValue(new Error('not in marketplace'));
+ mockInstallMarketplaceConnector.mockResolvedValue({ status: 'installed' });
});
it('does not persist a model change rejected by the shared-agent policy', async () => {
@@ -499,35 +507,84 @@ describe('agentBuilderRuntime', () => {
expect(result.success).toBe(false);
expect(result.error).toMatchObject({ type: 'PluginNotFound' });
+ expect(mockInstallMarketplaceConnector).not.toHaveBeenCalled();
expect(mockCreatePlugin).not.toHaveBeenCalled();
expect(mockUpdateConfig).not.toHaveBeenCalled();
});
- it('installs the marketplace plugin even when a same-named connector exists', async () => {
- const manifest = { api: [{ name: 'send' }], identifier: 'gmail' };
+ it('installs a marketplace MCP as a connector, not a plugin row, and says it loads next run', async () => {
+ const manifest = { deploymentOptions: [], identifier: 'ads-mcp', tools: [{ name: 'list' }] };
mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });
+ mockGetMcpManifest.mockResolvedValue(manifest);
+ // The connector the install wrote, as the agent's runs resolve it
mockResolveConnectors.mockResolvedValue([
- { identifier: 'gmail', isEnabled: false, status: 'disconnected' },
+ { identifier: 'ads-mcp', isEnabled: true, status: 'connected' },
]);
- mockGetMcpManifest.mockResolvedValue(manifest);
const result = await createRuntime().installPlugin(
- { identifier: 'gmail', source: 'market' },
+ { identifier: 'ads-mcp', source: 'market' },
{ editingAgentId: 'agent-1', toolManifestMap: {} },
);
expect(result.success).toBe(true);
- expect(mockCreatePlugin).toHaveBeenCalledWith({
- identifier: 'gmail',
+ expect(result.content).toContain('next run');
+ expect(mockInstallMarketplaceConnector).toHaveBeenCalledWith(
+ { serverDB: {}, userId: 'user-1', workspaceId: undefined },
+ 'ads-mcp',
manifest,
- type: 'plugin',
+ { readHostedEndpoint: expect.any(Function) },
+ );
+ expect(mockCreatePlugin).not.toHaveBeenCalled();
+ expect(mockUpdatePlugin).not.toHaveBeenCalled();
+ expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
+ plugins: [{ identifier: 'ads-mcp', mode: 'pinned' }],
});
});
- it('installs a marketplace plugin with its manifest and says it loads next run', async () => {
- const manifest = { api: [{ name: 'listCampaigns' }], identifier: 'ads-mcp' };
+ it("refuses, installing nothing, an install the agent's own disconnected connector would shadow", async () => {
mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });
- mockGetMcpManifest.mockResolvedValue(manifest);
+ mockGetMcpManifest.mockResolvedValue({ identifier: 'ads-mcp' });
+ // The agent owns a row of the identifier, which its runs pick over the base install
+ mockResolveConnectors.mockResolvedValue([
+ { agentId: 'agent-1', identifier: 'ads-mcp', isEnabled: true, status: 'disconnected' },
+ ]);
+
+ const result = await createRuntime().installPlugin(
+ { identifier: 'ads-mcp', source: 'market' },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(mockInstallMarketplaceConnector).not.toHaveBeenCalled();
+ expect(mockResolveConnectors).toHaveBeenCalledWith('agent-1');
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('not connected');
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ });
+
+ it('installs into the run workspace', async () => {
+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });
+ mockGetMcpManifest.mockResolvedValue({ identifier: 'ads-mcp' });
+
+ await createWorkspaceRuntime().installPlugin(
+ { identifier: 'ads-mcp', source: 'market' },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(mockInstallMarketplaceConnector).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user-1', workspaceId: 'workspace-1' }),
+ 'ads-mcp',
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('pins a finished connector install without installing it again', async () => {
+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });
+ mockGetMcpManifest.mockResolvedValue({ identifier: 'ads-mcp' });
+ mockInstallMarketplaceConnector.mockResolvedValue({ status: 'exists' });
+ mockResolveConnectors.mockResolvedValue([
+ { identifier: 'ads-mcp', isEnabled: true, status: 'connected' },
+ ]);
const result = await createRuntime().installPlugin(
{ identifier: 'ads-mcp', source: 'market' },
@@ -535,16 +592,55 @@ describe('agentBuilderRuntime', () => {
);
expect(result.success).toBe(true);
- expect(result.content).toContain('next run');
- expect(mockCreatePlugin).toHaveBeenCalledWith({
- identifier: 'ads-mcp',
- manifest,
- type: 'plugin',
- });
+ expect(result.content).not.toContain('next run');
expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
plugins: [{ identifier: 'ads-mcp', mode: 'pinned' }],
});
});
+
+ it.each([
+ ['oauth', 'PluginNeedsAuthorization', 'OAuth'],
+ ['config', 'PluginNeedsConfig', 'settings'],
+ ['local-only', 'PluginNeedsDesktop', 'desktop app'],
+ ['private-network', 'PluginNeedsDesktop', 'private-network address'],
+ ['conflict', 'PluginIdentifierConflict', 'already exists'],
+ ['forbidden', 'PluginInstallForbidden', 'admins'],
+ ['in-progress', 'PluginInstallInProgress', 'already being installed'],
+ ['no-tools', 'PluginHasNoTools', 'lists no tools'],
+ ])(
+ 'refuses a marketplace MCP it cannot install (%s) and pins nothing',
+ async (blocker, type, hint) => {
+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });
+ mockGetMcpManifest.mockResolvedValue({ identifier: 'gmail' });
+ mockInstallMarketplaceConnector.mockResolvedValue({ blocker, status: 'blocked' });
+
+ const result = await createRuntime().installPlugin(
+ { identifier: 'gmail', source: 'market' },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ type });
+ expect(result.content).toContain(hint);
+ expect(result.content).toContain('Nothing was changed');
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ },
+ );
+
+ it('reports a failed install and pins nothing', async () => {
+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });
+ mockGetMcpManifest.mockResolvedValue({ identifier: 'ads-mcp' });
+ mockInstallMarketplaceConnector.mockRejectedValue(new Error('connect ECONNREFUSED'));
+
+ const result = await createRuntime().installPlugin(
+ { identifier: 'ads-mcp', source: 'market' },
+ { editingAgentId: 'agent-1', toolManifestMap: {} },
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('ECONNREFUSED');
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ });
});
// Regression guard for `searchMarketTools` returning `unauthorized`: built
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
index ec2c7efbd2c..1fb0534efde 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
@@ -20,6 +20,8 @@ const {
mockCreatePlugin,
mockGetMcpList,
mockGetMcpManifest,
+ mockInstallMarketplaceConnector,
+ mockQueryConnectorsByIdentifiers,
mockQueryPlugins,
mockResolveConnectors,
mockUpdatePlugin,
@@ -29,6 +31,8 @@ const {
mockFindById: vi.fn(),
mockGetMcpList: vi.fn(),
mockGetMcpManifest: vi.fn(),
+ mockInstallMarketplaceConnector: vi.fn(),
+ mockQueryConnectorsByIdentifiers: vi.fn(),
mockQueryPlugins: vi.fn(),
mockResolveConnectors: vi.fn(),
mockUpdatePlugin: vi.fn(),
@@ -74,15 +78,25 @@ vi.mock('@/database/models/plugin', () => ({
vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn(function () {
- return { resolveAll: mockResolveConnectors };
+ return {
+ queryAvailableForAgent: mockResolveConnectors,
+ queryByIdentifiers: mockQueryConnectorsByIdentifiers,
+ resolveAll: mockResolveConnectors,
+ };
}),
}));
+vi.mock('@/server/services/connector/marketplaceInstall', () => ({
+ installMarketplaceMcpConnector: mockInstallMarketplaceConnector,
+}));
+
vi.mock('@/server/services/discover', () => ({
DiscoverService: vi.fn(function () {
return {
getAssistantDetail: mockGetAssistantDetail,
getAssistantList: mockGetAssistantList,
+ // The market's detail of an MCP it does not host
+ getMcpDetail: async () => ({}),
getMcpList: mockGetMcpList,
getMcpManifest: mockGetMcpManifest,
};
@@ -119,8 +133,10 @@ describe('agentManagementRuntime', () => {
mockExistsById.mockResolvedValue(true);
mockServiceUpdateConfig.mockImplementation((...args) => mockUpdateConfig(...args));
mockResolveConnectors.mockResolvedValue([]);
+ mockQueryConnectorsByIdentifiers.mockResolvedValue([]);
mockQueryPlugins.mockResolvedValue([]);
mockGetMcpManifest.mockRejectedValue(new Error('not in marketplace'));
+ mockInstallMarketplaceConnector.mockResolvedValue({ status: 'installed' });
});
it('does not persist a model change rejected by the shared-agent policy', async () => {
@@ -551,6 +567,43 @@ describe('agentManagementRuntime', () => {
]);
});
+ it('marks marketplace MCPs installed as connectors, once their install finished', async () => {
+ mockGetMcpList.mockResolvedValue({
+ items: [
+ { identifier: 'fetch-mcp', name: 'Fetch' },
+ { identifier: 'half-mcp', name: 'Half' },
+ { identifier: 'custom-mcp', name: 'Custom' },
+ ],
+ totalCount: 3,
+ });
+ const connector = {
+ mcpConnectionType: 'cloud',
+ metadata: { marketplaceInstalled: true },
+ sourceType: 'marketplace',
+ };
+ mockQueryConnectorsByIdentifiers.mockResolvedValue([
+ { ...connector, identifier: 'fetch-mcp' },
+ // An install still running (or interrupted) is not one yet
+ { ...connector, identifier: 'half-mcp', metadata: {} },
+ // A custom connector is not this marketplace MCP
+ { ...connector, identifier: 'custom-mcp', sourceType: 'custom' },
+ ]);
+
+ const result = await createRuntime().searchMarketTools({ query: 'mcp' });
+
+ expect(mockQueryConnectorsByIdentifiers).toHaveBeenCalledWith([
+ 'fetch-mcp',
+ 'half-mcp',
+ 'custom-mcp',
+ ]);
+ expect(result.content).toContain('- Fetch (fetch-mcp) [installed]');
+ expect(result.state.tools.map((t: any) => [t.identifier, t.installed])).toEqual([
+ ['fetch-mcp', true],
+ ['half-mcp', false],
+ ['custom-mcp', false],
+ ]);
+ });
+
it('caps the page size at the advertised max', async () => {
mockGetMcpList.mockResolvedValue({ items: [], totalCount: 0 });
@@ -576,13 +629,17 @@ describe('agentManagementRuntime', () => {
});
describe('installPlugin', () => {
- it('installs a marketplace plugin with its manifest and pins it', async () => {
- const manifest = { api: [{ name: 'run' }], identifier: 'plugin-b' };
+ it('installs a marketplace MCP as a connector, not a plugin row, and pins it', async () => {
+ const manifest = { identifier: 'plugin-b', tools: [{ name: 'run' }] };
mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: ['plugin-a'] });
mockFindById.mockResolvedValue(undefined);
mockGetMcpManifest.mockResolvedValue(manifest);
+ // The connector the install wrote, as the agent's runs resolve it
+ mockResolveConnectors.mockResolvedValue([
+ { identifier: 'plugin-b', isEnabled: true, status: 'connected' },
+ ]);
- const runtime = createRuntime();
+ const runtime = createWorkspaceRuntime();
const result = await runtime.installPlugin({
agentId: 'agent-1',
identifier: 'plugin-b',
@@ -591,16 +648,39 @@ describe('agentManagementRuntime', () => {
expect(result.success).toBe(true);
expect(result.content).toContain('next run');
- expect(mockCreatePlugin).toHaveBeenCalledWith({
- identifier: 'plugin-b',
+ expect(mockInstallMarketplaceConnector).toHaveBeenCalledWith(
+ { serverDB: {}, userId: 'user-1', workspaceId: 'workspace-1' },
+ 'plugin-b',
manifest,
- type: 'plugin',
- });
+ { readHostedEndpoint: expect.any(Function) },
+ );
+ expect(mockCreatePlugin).not.toHaveBeenCalled();
+ expect(mockUpdatePlugin).not.toHaveBeenCalled();
expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {
plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }],
});
});
+ it('refuses a marketplace MCP the server cannot install and pins nothing', async () => {
+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });
+ mockFindById.mockResolvedValue(undefined);
+ mockGetMcpManifest.mockResolvedValue({ identifier: 'local-mcp' });
+ mockInstallMarketplaceConnector.mockResolvedValue({
+ blocker: 'local-only',
+ status: 'blocked',
+ });
+
+ const result = await createRuntime().installPlugin({
+ agentId: 'agent-1',
+ identifier: 'local-mcp',
+ source: 'market',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ type: 'PluginNeedsDesktop' });
+ expect(mockUpdateConfig).not.toHaveBeenCalled();
+ });
+
// Vent msg_f46kelJyavbcB2Xkz9: `adkit` was a custom MCP behind OAuth whose
// manifest never listed tools; installPlugin reported success while every
// activateTools call returned "Not found".
@@ -636,6 +716,7 @@ describe('agentManagementRuntime', () => {
expect(result.success).toBe(false);
expect(result.error).toMatchObject({ type: 'PluginNotFound' });
+ expect(mockInstallMarketplaceConnector).not.toHaveBeenCalled();
expect(mockCreatePlugin).not.toHaveBeenCalled();
expect(mockUpdateConfig).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/installPluginApproval.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/installPluginApproval.test.ts
new file mode 100644
index 00000000000..0d657899791
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/installPluginApproval.test.ts
@@ -0,0 +1,98 @@
+import type { AgentRuntimeContext } from '@lobechat/agent-runtime';
+import { AgentRuntime, GeneralChatAgent } from '@lobechat/agent-runtime';
+import {
+ AgentBuilderApiName,
+ AgentBuilderIdentifier,
+ AgentBuilderManifest,
+} from '@lobechat/builtin-tool-agent-builder';
+import {
+ AgentManagementApiName,
+ AgentManagementIdentifier,
+ AgentManagementManifest,
+} from '@lobechat/builtin-tool-agent-management';
+import type { ChatToolPayload, UserInterventionConfig } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+/**
+ * `installPlugin` with source `market` installs a connector the agent's later
+ * runs call without asking (a listing's tools default to `auto`). The install
+ * must therefore wait for the user's approval, which no approval mode waives:
+ * a rejected call never reaches the runtime, so nothing is written.
+ */
+describe('installPlugin approval', () => {
+ const cases = [
+ {
+ apiName: AgentBuilderApiName.installPlugin,
+ args: { identifier: 'remote-mcp', source: 'market' },
+ identifier: AgentBuilderIdentifier,
+ manifest: AgentBuilderManifest,
+ name: 'Agent Builder',
+ },
+ {
+ apiName: AgentManagementApiName.installPlugin,
+ args: { agentId: 'agt_target', identifier: 'remote-mcp', source: 'market' },
+ identifier: AgentManagementIdentifier,
+ manifest: AgentManagementManifest,
+ name: 'Agent Management',
+ },
+ ];
+
+ const route = async (
+ { apiName, args, identifier, manifest }: (typeof cases)[number],
+ userInterventionConfig: UserInterventionConfig,
+ ) => {
+ const toolCall: ChatToolPayload = {
+ apiName,
+ arguments: JSON.stringify(args),
+ id: 'call_install',
+ identifier,
+ type: 'builtin',
+ };
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 10 },
+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },
+ operationId: 'op_install',
+ });
+ const state = AgentRuntime.createInitialState({
+ operationId: 'op_install',
+ status: 'running',
+ toolManifestMap: { [identifier]: manifest as never },
+ userInterventionConfig,
+ });
+ const context: AgentRuntimeContext = {
+ payload: {
+ hasToolsCalling: true,
+ parentMessageId: 'msg_assistant',
+ toolsCalling: [toolCall],
+ },
+ phase: 'llm_result',
+ session: { messageCount: 0, sessionId: 'op_install', status: 'running', stepCount: 0 },
+ };
+
+ return { instructions: await agent.runner(context, state), toolCall };
+ };
+
+ it.each(cases)('$name asks for approval even in auto-run mode', async (testCase) => {
+ const { instructions, toolCall } = await route(testCase, { approvalMode: 'auto-run' });
+
+ expect(instructions).toEqual([
+ {
+ parentMessageId: 'msg_assistant',
+ pendingToolsCalling: [toolCall],
+ reason: 'human_intervention_required',
+ type: 'request_human_approve',
+ },
+ ]);
+ });
+
+ it.each(cases)('$name never installs in a run no one can approve', async (testCase) => {
+ const { instructions } = await route(testCase, { approvalMode: 'headless' });
+
+ expect(instructions).toEqual([
+ expect.objectContaining({
+ payload: expect.objectContaining({ blockedReason: 'human_intervention_unavailable' }),
+ type: 'resolve_blocked_tools',
+ }),
+ ]);
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts
new file mode 100644
index 00000000000..9c68616055e
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/pluginResolution.marketInstall.test.ts
@@ -0,0 +1,377 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { PluginModel } from '@/database/models/plugin';
+import {
+ agents,
+ userConnectors,
+ userInstalledPlugins,
+ users,
+ workspaceMembers,
+ workspaces,
+} from '@/database/schemas';
+import { discoverTools } from '@/server/services/aiAgent/pipeline/toolDiscovery';
+import {
+ installMarketplaceMcpConnector,
+ type MarketMcpManifest,
+} from '@/server/services/connector/marketplaceInstall';
+
+import { searchMarketTools } from '../marketToolSearch';
+import { resolveOrInstallMarketPlugin } from '../pluginResolution';
+
+vi.mock('@/business/client/model-bank/loadModels', () => ({
+ loadModels: vi.fn().mockResolvedValue([]),
+}));
+// The background stale-tool refresh reaches for the request-scoped `after()`,
+// which does not exist in a bare unit-test runtime.
+vi.mock('@/server/services/connector/refresh', () => ({
+ buildLastSyncedAtMap: vi.fn().mockReturnValue(new Map()),
+ scheduleStaleConnectorToolsRefresh: vi.fn(),
+}));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { isConfigured: false, queryDeviceList: vi.fn().mockResolvedValue([]) },
+}));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue(undefined) },
+}));
+
+const db = await getTestDB();
+const userId = 'server-market-install-user';
+const AGENT_ID = 'agent-1';
+const IDENTIFIER = 'fetch-mcp';
+const WORKSPACE_ID = 'server-market-install-ws';
+
+/**
+ * A stdio MCP, the way `market.getMcpManifest` serves it: whether the market
+ * hosts it is on its detail (`haveCloudEndpoint`), not in the manifest.
+ */
+const manifest: MarketMcpManifest = {
+ deploymentOptions: [{ connection: { args: ['-y', IDENTIFIER], command: 'npx', type: 'stdio' } }],
+ name: 'Fetch',
+ tools: [{ description: 'Fetch a URL', inputSchema: { type: 'object' }, name: 'fetch' }],
+ version: '1.2.0',
+};
+
+const pluginModel = new PluginModel(db, userId);
+const connectorModel = new ConnectorModel(db, userId);
+
+const installFromServer = (
+ served: MarketMcpManifest = manifest,
+ /** The market's detail of the MCP, or the error reading it fails with. */
+ detail: { haveCloudEndpoint?: unknown } | Error = { haveCloudEndpoint: true },
+ workspaceId?: string,
+) =>
+ resolveOrInstallMarketPlugin(
+ IDENTIFIER,
+ {
+ connectorModel: workspaceId ? new ConnectorModel(db, userId, workspaceId) : connectorModel,
+ discoverService: {
+ getMcpDetail:
+ detail instanceof Error
+ ? vi.fn().mockRejectedValue(detail)
+ : vi.fn().mockResolvedValue(detail),
+ getMcpManifest: vi.fn().mockResolvedValue(served),
+ },
+ installMarketplaceConnector: (identifier, fetched, options) =>
+ installMarketplaceMcpConnector(
+ { serverDB: db, userId, workspaceId },
+ identifier,
+ fetched,
+ options,
+ ),
+ pluginModel,
+ },
+ { agentId: AGENT_ID, source: 'market' },
+ );
+
+/** The next run of the agent the install pinned the MCP on. */
+const nextRun = () =>
+ discoverTools(
+ {
+ agentDocumentsService: { hasDocuments: vi.fn().mockResolvedValue(false) },
+ composioService: { getComposioManifests: vi.fn().mockResolvedValue([]) },
+ connectorModel,
+ connectorToolModel: new ConnectorToolModel(db, userId),
+ db,
+ getMarketService: vi.fn().mockResolvedValue({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ }),
+ messageModel: { update: vi.fn() },
+ pluginModel,
+ userId,
+ } as never,
+ {
+ agentConfig: { chatConfig: {}, plugins: [IDENTIFIER] },
+ appContext: undefined,
+ canUseDevice: false,
+ model: 'test-model',
+ prompt: 'fetch https://example.com',
+ provider: 'test-provider',
+ resolvedAgentId: AGENT_ID,
+ runFacts: {
+ deviceSystemInfo: vi.fn().mockResolvedValue(undefined),
+ userPreference: vi.fn().mockResolvedValue(undefined),
+ },
+ } as never,
+ {
+ disabledPluginIds: [],
+ globalMemoryEnabled: false,
+ hasMentionedAgents: false,
+ isFixedDeviceTarget: false,
+ loadHistoryMessages: vi.fn().mockResolvedValue([]),
+ throwIfExecutionAborted: vi.fn(),
+ } as never,
+ );
+
+beforeEach(async () => {
+ await db.delete(users);
+ await db.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await db.delete(workspaces);
+ await db.delete(users);
+});
+
+describe('resolveOrInstallMarketPlugin β€” server-side marketplace install', () => {
+ it.each([
+ { label: 'MCP tools', served: manifest },
+ // The shape the server used to store as a manifest-only plugin row
+ {
+ label: 'an API list',
+ served: {
+ ...manifest,
+ api: [{ description: 'Fetch a URL', name: 'fetch', parameters: { type: 'object' } }],
+ },
+ },
+ ])(
+ 'installs a manifest with $label into user_connectors only, and the next run can call it',
+ async ({ served }) => {
+ const { installedNow, resolution } = await installFromServer(served);
+
+ expect(installedNow).toBe(true);
+ expect(resolution).toEqual({ source: 'connector', status: 'loadable' });
+ expect(await db.select().from(userInstalledPlugins)).toEqual([]);
+ expect(await db.select().from(userConnectors)).toEqual([
+ expect.objectContaining({
+ identifier: IDENTIFIER,
+ metadata: expect.objectContaining({ marketplaceInstalled: true }),
+ sourceType: 'marketplace',
+ status: 'connected',
+ }),
+ ]);
+
+ const run = await nextRun();
+ expect(run.toolManifestMap[IDENTIFIER]).toMatchObject({
+ api: [expect.objectContaining({ name: 'fetch' })],
+ mcpParams: expect.objectContaining({ type: 'cloud' }),
+ });
+ expect(run.toolsResult.enabledToolIds).toContain(IDENTIFIER);
+ // The model is offered the connector's tool by name
+ expect((run.tools ?? []).map((tool) => tool.function.name)).toContain(
+ `${IDENTIFIER}____fetch____mcp`,
+ );
+ },
+ );
+
+ it('refuses a stdio MCP the market does not host, writing nothing', async () => {
+ const { installedNow, resolution } = await installFromServer(manifest, {
+ haveCloudEndpoint: false,
+ });
+
+ expect(installedNow).toBe(false);
+ expect(resolution).toEqual({ blocker: 'local-only', status: 'needs-user-install' });
+ expect(await db.select().from(userConnectors)).toEqual([]);
+ expect(await db.select().from(userInstalledPlugins)).toEqual([]);
+ });
+
+ it('fails, writing nothing, when it cannot read whether the market hosts the MCP', async () => {
+ // Not knowing is not "not hosted": a hosted server must not be refused as desktop-only
+ await expect(installFromServer(manifest, new Error('market unavailable'))).rejects.toThrow(
+ 'market unavailable',
+ );
+
+ expect(await db.select().from(userConnectors)).toEqual([]);
+ expect(await db.select().from(userInstalledPlugins)).toEqual([]);
+ });
+
+ it("pins a finished install again even when the market's detail cannot be read", async () => {
+ await installFromServer();
+ const before = await db.select().from(userConnectors);
+
+ // Whether the market hosts it only matters for an install still to place
+ const { installedNow, resolution } = await installFromServer(
+ manifest,
+ new Error('market unavailable'),
+ );
+
+ expect(installedNow).toBe(false);
+ expect(resolution).toEqual({ source: 'connector', status: 'loadable' });
+ expect(await db.select().from(userConnectors)).toEqual(before);
+ });
+
+ it('pins a finished install again without writing anything', async () => {
+ await installFromServer();
+ const before = await db.select().from(userConnectors);
+
+ const { installedNow, resolution } = await installFromServer();
+
+ expect(installedNow).toBe(false);
+ expect(resolution).toEqual({ source: 'connector', status: 'loadable' });
+ expect(await db.select().from(userConnectors)).toEqual(before);
+ expect(await db.select().from(userInstalledPlugins)).toEqual([]);
+ });
+
+ it.each([
+ { label: 'disconnected', resolved: { status: 'not-connected' }, status: 'disconnected' },
+ {
+ label: 'connected',
+ resolved: { source: 'connector', status: 'loadable' },
+ status: 'connected',
+ },
+ ] as const)(
+ "reports the agent's own $label connector, which its runs pick, and installs nothing",
+ async ({ resolved, status }) => {
+ await db.insert(agents).values({ id: AGENT_ID, userId });
+ await db.insert(userConnectors).values({
+ agentId: AGENT_ID,
+ identifier: IDENTIFIER,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ name: 'Agent copy',
+ sourceType: 'custom',
+ status,
+ userId,
+ });
+
+ const { installedNow, resolution } = await installFromServer();
+
+ expect(installedNow).toBe(false);
+ expect(resolution).toEqual(resolved);
+ // No base connector its runs would never reach
+ expect(await db.select().from(userConnectors)).toEqual([
+ expect.objectContaining({ agentId: AGENT_ID, name: 'Agent copy' }),
+ ]);
+ },
+ );
+
+ it.each([
+ {
+ label: 'private',
+ resolved: { status: 'not-connected' },
+ row: { status: 'disconnected', visibility: 'private', workspaceId: WORKSPACE_ID },
+ },
+ {
+ label: 'personal',
+ resolved: { source: 'connector', status: 'loadable' },
+ row: { status: 'connected', workspaceId: null },
+ },
+ ] as const)(
+ "reports the owner's $label connector its private agent's own conversation picks, and adds no shared one",
+ async ({ resolved, row }) => {
+ await db
+ .insert(workspaces)
+ .values({ id: WORKSPACE_ID, name: 'WS', primaryOwnerId: userId, slug: WORKSPACE_ID });
+ await db
+ .insert(workspaceMembers)
+ .values({ role: 'owner', userId, workspaceId: WORKSPACE_ID });
+ await db
+ .insert(agents)
+ .values({ id: AGENT_ID, userId, visibility: 'private', workspaceId: WORKSPACE_ID });
+ await db.insert(userConnectors).values({
+ identifier: IDENTIFIER,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ name: 'Owner copy',
+ sourceType: 'custom',
+ userId,
+ ...row,
+ });
+
+ const { installedNow, resolution } = await installFromServer(
+ manifest,
+ { haveCloudEndpoint: true },
+ WORKSPACE_ID,
+ );
+
+ expect(installedNow).toBe(false);
+ expect(resolution).toEqual(resolved);
+ // No shared connector that the agent's own runs rank below the owner's row
+ expect(await db.select().from(userConnectors)).toEqual([
+ expect.objectContaining({ name: 'Owner copy' }),
+ ]);
+ },
+ );
+
+ it('installs a shared connector for a private agent whose owner has none of it', async () => {
+ await db
+ .insert(workspaces)
+ .values({ id: WORKSPACE_ID, name: 'WS', primaryOwnerId: userId, slug: WORKSPACE_ID });
+ await db.insert(workspaceMembers).values({ role: 'owner', userId, workspaceId: WORKSPACE_ID });
+ await db
+ .insert(agents)
+ .values({ id: AGENT_ID, userId, visibility: 'private', workspaceId: WORKSPACE_ID });
+
+ const { installedNow, resolution } = await installFromServer(
+ manifest,
+ { haveCloudEndpoint: true },
+ WORKSPACE_ID,
+ );
+
+ expect(installedNow).toBe(true);
+ expect(resolution).toEqual({ source: 'connector', status: 'loadable' });
+ expect(await db.select().from(userConnectors)).toEqual([
+ expect.objectContaining({
+ identifier: IDENTIFIER,
+ visibility: 'public',
+ workspaceId: WORKSPACE_ID,
+ }),
+ ]);
+ });
+
+ it('reports the install as installed in the next marketplace search', async () => {
+ const search = () =>
+ searchMarketTools(
+ {
+ connectorModel,
+ discoverService: {
+ getMcpList: vi.fn().mockResolvedValue({
+ items: [{ identifier: IDENTIFIER, name: 'Fetch' }],
+ totalCount: 1,
+ }),
+ },
+ pluginModel,
+ },
+ { query: 'fetch' },
+ );
+ expect((await search()).state.tools).toEqual([
+ expect.objectContaining({ identifier: IDENTIFIER, installed: false }),
+ ]);
+
+ await installFromServer();
+
+ const result = await search();
+ expect(result.state.tools).toEqual([
+ expect.objectContaining({ identifier: IDENTIFIER, installed: true }),
+ ]);
+ expect(result.content).toContain(`(${IDENTIFIER}) [installed]`);
+ });
+
+ it('keeps reading a plugin row an earlier server install wrote', async () => {
+ await db.insert(userInstalledPlugins).values({
+ identifier: IDENTIFIER,
+ manifest: { api: [{ name: 'fetch' }], identifier: IDENTIFIER } as never,
+ type: 'plugin',
+ userId,
+ });
+
+ const { installedNow, resolution } = await installFromServer();
+
+ expect(installedNow).toBe(false);
+ expect(resolution).toEqual({ source: 'installed', status: 'loadable' });
+ expect(await db.select().from(userConnectors)).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
index a4e68fa4e5a..ca2886720c0 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts
@@ -18,6 +18,11 @@ import { ConnectorModel } from '@/database/models/connector';
import { PluginModel } from '@/database/models/plugin';
import { AiInfraRepos } from '@/database/repositories/aiInfra';
import { AgentService } from '@/server/services/agent';
+import {
+ installMarketplaceMcpConnector,
+ type MarketMcpManifest,
+ type MarketplaceInstallOptions,
+} from '@/server/services/connector/marketplaceInstall';
import { DiscoverService } from '@/server/services/discover';
import { filterHiddenProviderModels } from '@/utils/aiProvider';
@@ -74,6 +79,12 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
const discoverService = new DiscoverService({
userInfo: { userId, workspaceId: context.workspaceId },
});
+ const installScope = { serverDB: context.serverDB, userId, workspaceId: context.workspaceId };
+ const installMarketplaceConnector = (
+ identifier: string,
+ manifest: MarketMcpManifest,
+ options?: MarketplaceInstallOptions,
+ ) => installMarketplaceMcpConnector(installScope, identifier, manifest, options);
return {
getAvailableModels: async (
@@ -166,7 +177,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
},
searchMarketTools: (params: SearchMarketToolsParams): Promise<ToolExecutionResult> =>
- searchMarketTools({ discoverService, pluginModel }, params),
+ searchMarketTools({ connectorModel, discoverService, pluginModel }, params),
updateConfig: async (
params: UpdateAgentConfigParams,
@@ -340,7 +351,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {
const { installedNow, resolution } = await resolveOrInstallMarketPlugin(
identifier,
- { connectorModel, discoverService, pluginModel },
+ { connectorModel, discoverService, installMarketplaceConnector, pluginModel },
{ agentId, source: 'market' },
);
if (resolution.status !== 'loadable')
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
index 85b03f84b94..2b8773edc76 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
@@ -25,6 +25,11 @@ import { AgentModel } from '@/database/models/agent';
import { ConnectorModel } from '@/database/models/connector';
import { PluginModel } from '@/database/models/plugin';
import { AgentService } from '@/server/services/agent';
+import {
+ installMarketplaceMcpConnector,
+ type MarketMcpManifest,
+ type MarketplaceInstallOptions,
+} from '@/server/services/connector/marketplaceInstall';
import { DiscoverService } from '@/server/services/discover';
import { type ToolExecutionContext, type ToolExecutionResult } from '../types';
@@ -67,6 +72,16 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
const discoverService = new DiscoverService({
userInfo: { userId: context.userId, workspaceId: context.workspaceId },
});
+ const installScope = {
+ serverDB: context.serverDB,
+ userId: context.userId,
+ workspaceId: context.workspaceId,
+ };
+ const installMarketplaceConnector = (
+ identifier: string,
+ manifest: MarketMcpManifest,
+ options?: MarketplaceInstallOptions,
+ ) => installMarketplaceMcpConnector(installScope, identifier, manifest, options);
return {
callAgent: async (
@@ -312,13 +327,13 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
return { content: `Agent "${agentId}" not found.`, success: false };
}
- // Pin only an id the runtime can load: a builtin, a connector, or a
- // plugin whose manifest lists its APIs (fetched from the marketplace
- // when not installed yet). Registering a bare row here used to report
- // success for ids that never produced a tool.
+ // Pin only an id the runtime can load: a builtin, a connector, or an
+ // installed plugin whose manifest lists its APIs. A marketplace MCP
+ // not installed yet is installed as a connector first. Registering a
+ // bare row here used to report success for ids that never produced a tool.
const { installedNow, resolution } = await resolveOrInstallMarketPlugin(
identifier,
- { connectorModel, discoverService, pluginModel },
+ { connectorModel, discoverService, installMarketplaceConnector, pluginModel },
{ agentId, source },
);
if (resolution.status !== 'loadable')
@@ -445,7 +460,7 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
},
searchMarketTools: (params: SearchMarketToolsParams): Promise<ToolExecutionResult> =>
- searchMarketTools({ discoverService, pluginModel }, params),
+ searchMarketTools({ connectorModel, discoverService, pluginModel }, params),
updateAgent: async (params: UpdateAgentParams): Promise<ToolExecutionResult> => {
try {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/marketToolSearch.ts b/apps/server/src/services/toolExecution/serverRuntimes/marketToolSearch.ts
index 4594774c4fa..d12f04f5394 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/marketToolSearch.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/marketToolSearch.ts
@@ -1,6 +1,9 @@
import type { MarketToolItem, SearchMarketToolsParams } from '@lobechat/builtin-tool-agent-builder';
+import { hasCallableMcpEndpoint, isMarketplaceInstallCompleted } from '@lobechat/const';
+import type { ConnectorModel } from '@/database/models/connector';
import type { PluginModel } from '@/database/models/plugin';
+import { ConnectorSourceType } from '@/database/schemas';
import type { DiscoverService } from '@/server/services/discover';
import type { ToolExecutionResult } from '../types';
@@ -9,18 +12,31 @@ import type { ToolExecutionResult } from '../types';
export const MAX_MARKET_TOOLS_PAGE_SIZE = 20;
export interface MarketToolSearchDeps {
+ connectorModel: Pick<ConnectorModel, 'queryByIdentifiers'>;
discoverService: Pick<DiscoverService, 'getMcpList'>;
pluginModel: Pick<PluginModel, 'query'>;
}
+/** A marketplace connector whose install finished: the row `installPlugin` answers `exists` for. */
+const isFinishedMarketplaceConnector = (connector: {
+ mcpConnectionType?: string | null;
+ mcpServerUrl?: string | null;
+ metadata?: unknown;
+ sourceType?: string | null;
+}) =>
+ connector.sourceType === ConnectorSourceType.marketplace &&
+ hasCallableMcpEndpoint(connector) &&
+ isMarketplaceInstallCompleted(connector.metadata);
+
/**
* Server-side `searchMarketTools`, shared by Agent Builder and Agent Management.
*
- * Each result is marked `installed` against the caller's installed plugins so
- * the model can skip a redundant install and go straight to pinning the id.
+ * Each result is marked `installed` against the caller's installs, a finished
+ * marketplace connector or a plugin row from before connectors, so the model
+ * can skip a redundant install and go straight to pinning the id.
*/
export const searchMarketTools = async (
- { discoverService, pluginModel }: MarketToolSearchDeps,
+ { connectorModel, discoverService, pluginModel }: MarketToolSearchDeps,
params: SearchMarketToolsParams,
): Promise<ToolExecutionResult> => {
try {
@@ -29,7 +45,13 @@ export const searchMarketTools = async (
discoverService.getMcpList({ category: params.category, pageSize, q: params.query }),
pluginModel.query(),
]);
- const installedIds = new Set(installedPlugins.map((plugin) => plugin.identifier));
+ const connectors = await connectorModel.queryByIdentifiers(
+ response.items.map((item) => item.identifier),
+ );
+ const installedIds = new Set([
+ ...installedPlugins.map((plugin) => plugin.identifier),
+ ...connectors.filter(isFinishedMarketplaceConnector).map((connector) => connector.identifier),
+ ]);
const tools: MarketToolItem[] = response.items.map((item) => ({
author: item.author,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts b/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts
index e23e7379b96..898a75a59bb 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/pluginResolution.ts
@@ -3,6 +3,12 @@ import { getConnectorCatalog } from '@lobechat/const';
import type { ConnectorModel } from '@/database/models/connector';
import type { PluginModel } from '@/database/models/plugin';
+import type {
+ MarketMcpManifest,
+ MarketplaceInstallBlocker,
+ MarketplaceInstallOptions,
+ MarketplaceInstallOutcome,
+} from '@/server/services/connector/marketplaceInstall';
import type { ToolExecutionResult } from '../types';
@@ -17,6 +23,8 @@ import type { ToolExecutionResult } from '../types';
* - `no-tools`: installed, but the manifest has no API list, so the tool pool
* drops it on every run (e.g. a custom MCP behind OAuth that was never
* connected).
+ * - `needs-user-install`: a marketplace MCP the server cannot install by
+ * itself (`blocker` says why), so the user installs it from the marketplace.
* - `unknown`: nothing by that id; `suggestions` holds near matches such as
* `tg-mcp` for `tg_mcp`.
*/
@@ -24,6 +32,7 @@ export type PluginResolution =
| { source: 'builtin' | 'connector' | 'installed'; status: 'loadable' }
| { status: 'no-tools' }
| { status: 'not-connected' }
+ | { blocker: MarketplaceInstallBlocker; status: 'needs-user-install' }
| { status: 'unknown'; suggestions: string[] };
export interface PluginResolverDeps {
@@ -42,6 +51,15 @@ export const hasLoadableApis = (manifest: unknown): boolean =>
const normalize = (id: string) => id.toLowerCase().replaceAll(/[\s_.]+/g, '-');
+/** A connector contributes tools only once it is enabled and connected. */
+const connectorResolution = (connector: {
+ isEnabled: boolean;
+ status: string;
+}): PluginResolution =>
+ connector.isEnabled && connector.status === 'connected'
+ ? { source: 'connector', status: 'loadable' }
+ : { status: 'not-connected' };
+
export const resolvePluginIdentifier = async (
identifier: string,
deps: PluginResolverDeps,
@@ -54,11 +72,7 @@ export const resolvePluginIdentifier = async (
// enabled and connected β€” a disabled or disconnected row contributes no tools.
const connectors = await deps.connectorModel.resolveAll(options.agentId);
const connector = connectors.find((c) => c.identifier === identifier);
- if (connector) {
- return connector.isEnabled && connector.status === 'connected'
- ? { source: 'connector', status: 'loadable' }
- : { status: 'not-connected' };
- }
+ if (connector) return connectorResolution(connector);
const installed = await deps.pluginModel.findById(identifier);
if (installed) {
@@ -79,6 +93,68 @@ export const resolvePluginIdentifier = async (
return { status: 'unknown', suggestions };
};
+const NEEDS_USER_INSTALL: Record<
+ MarketplaceInstallBlocker,
+ { content: (identifier: string) => string; message: string; type: string }
+> = {
+ 'config': {
+ content: (id) =>
+ `Marketplace MCP "${id}" needs settings only the user can provide (such as an API key), so it cannot be installed from here. Ask the user to install it from the marketplace and fill in its settings, then enable it. Nothing was changed.`,
+ message: 'Plugin needs configuration',
+ type: 'PluginNeedsConfig',
+ },
+ 'conflict': {
+ content: (id) =>
+ `A connector with the identifier "${id}" already exists and is not a finished install of this marketplace MCP. Ask the user to remove it (or finish its install) in Settings β†’ Connectors first. Nothing was changed.`,
+ message: 'Connector identifier already in use',
+ type: 'PluginIdentifierConflict',
+ },
+ 'forbidden': {
+ content: (id) =>
+ `Only workspace owners and admins can add connectors in this workspace, so "${id}" was not installed. Ask a workspace admin to install it. Nothing was changed.`,
+ message: 'Not allowed to add workspace connectors',
+ type: 'PluginInstallForbidden',
+ },
+ 'in-progress': {
+ content: (id) =>
+ `Marketplace MCP "${id}" is already being installed: an install started in the last few minutes has not finished. Try installPlugin again in a few minutes. Nothing was changed.`,
+ message: 'Plugin install already in progress',
+ type: 'PluginInstallInProgress',
+ },
+ 'local-only': {
+ content: (id) =>
+ `Marketplace MCP "${id}" has no remote endpoint: it runs as a local (stdio) process, which only the LobeHub desktop app can start. Ask the user to install it from the marketplace in the desktop app. Nothing was changed.`,
+ message: 'Plugin runs only as a local process',
+ type: 'PluginNeedsDesktop',
+ },
+ 'private-network': {
+ content: (id) =>
+ `Marketplace MCP "${id}" is served only at a localhost or private-network address, which this server would have to reach through the user's own machine, so it cannot be installed from here. Ask the user to install it from the marketplace in the LobeHub desktop app. Nothing was changed.`,
+ message: 'Plugin endpoint is on a private network',
+ type: 'PluginNeedsDesktop',
+ },
+ 'no-tools': {
+ content: (id) =>
+ `Marketplace MCP "${id}" lists no tools, so installing it would not make any tool available. Nothing was changed.`,
+ message: 'Plugin has no loadable tools',
+ type: 'PluginHasNoTools',
+ },
+ 'oauth': {
+ content: (id) =>
+ `Marketplace MCP "${id}" signs in with OAuth, which the user has to authorize in their browser. Ask the user to install it from the marketplace and complete the sign-in, then enable it. Nothing was changed.`,
+ message: 'Plugin needs OAuth authorization',
+ type: 'PluginNeedsAuthorization',
+ },
+};
+
+const needsUserInstallResult = (
+ identifier: string,
+ { blocker }: { blocker: MarketplaceInstallBlocker },
+): ToolExecutionResult => {
+ const { content, message, type } = NEEDS_USER_INSTALL[blocker];
+ return { content: content(identifier), error: { message, type }, success: false };
+};
+
/** The failure returned instead of pinning an id that would load no tools. */
export const unresolvablePluginResult = (
identifier: string,
@@ -92,6 +168,9 @@ export const unresolvablePluginResult = (
};
}
+ if (resolution.status === 'needs-user-install')
+ return needsUserInstallResult(identifier, resolution);
+
if (resolution.status === 'not-connected') {
return {
content: `"${identifier}" is an integration that is not connected (or is disabled), so it provides no tools yet. Ask the user to connect it in Settings β†’ Connectors, then enable it. Nothing was changed.`,
@@ -113,56 +192,107 @@ export const unresolvablePluginResult = (
};
export interface MarketPluginDeps extends PluginResolverDeps {
- discoverService: { getMcpManifest: (params: { identifier: string }) => Promise<unknown> };
- pluginModel: PluginResolverDeps['pluginModel'] & Pick<PluginModel, 'create' | 'update'>;
+ connectorModel: Pick<ConnectorModel, 'queryAvailableForAgent' | 'resolveAll'>;
+ discoverService: {
+ /** The MCP's market detail, which says whether the market hosts it (`haveCloudEndpoint`). */
+ getMcpDetail: (params: { identifier: string }) => Promise<unknown>;
+ getMcpManifest: (params: { identifier: string }) => Promise<unknown>;
+ };
+ /** Stores a marketplace MCP as a connector (`installMarketplaceMcpConnector`). */
+ installMarketplaceConnector: (
+ identifier: string,
+ manifest: MarketMcpManifest,
+ options?: MarketplaceInstallOptions,
+ ) => Promise<MarketplaceInstallOutcome>;
}
/**
* Resolve a plugin id for `installPlugin`. A `market` install is satisfied by
- * the marketplace plugin itself: an installed row with APIs, or a manifest
- * fetched now β€” a same-named builtin, catalog id or connector does not count
- * as that install. Only when the marketplace has nothing does it fall back to
- * the source-agnostic resolution. A row is written only when the fetched
- * manifest lists its APIs, and a custom plugin's own manifest is never
- * overwritten.
+ * the marketplace MCP itself: a legacy installed plugin row with APIs, a
+ * finished marketplace connector install, or one made now β€” a same-named
+ * builtin or catalog id does not count as that install. Only when the
+ * marketplace has nothing does it fall back to the source-agnostic resolution.
*
- * `installedNow` is true when this call created or filled the row: such a tool
- * was not in the current run's tool pool, so it loads from the next run.
+ * An install made now lands in `user_connectors`, as the web install does; no
+ * `user_installed_plugins` row is written, while rows written before stay
+ * readable. `installedNow` is true when this call installed it: such a tool was
+ * not in the current run's tool pool, so it loads from the next run.
*/
export const resolveOrInstallMarketPlugin = async (
identifier: string,
deps: MarketPluginDeps,
options: { agentId?: string; source?: string } = {},
): Promise<{ installedNow: boolean; resolution: PluginResolution }> => {
- if (options.source !== 'market')
- return {
- installedNow: false,
- resolution: await resolvePluginIdentifier(identifier, deps, options),
- };
+ const resolveExisting = async () => ({
+ installedNow: false,
+ resolution: await resolvePluginIdentifier(identifier, deps, options),
+ });
+
+ if (options.source !== 'market') return resolveExisting();
const existing = await deps.pluginModel.findById(identifier);
if (existing && hasLoadableApis(existing.manifest))
return { installedNow: false, resolution: { source: 'installed', status: 'loadable' } };
if (existing?.manifest) return { installedNow: false, resolution: { status: 'no-tools' } };
+ // The agent's own row of the identifier comes first in its runs, so a base
+ // install would never serve it: answer as its runs will, installing nothing.
+ // In its own conversation, so does its owner's private or personal row (a
+ // private agent's configuration scope), which a run without that topic does
+ // not resolve: answer as that row, rather than add a shared one it shadows.
+ if (options.agentId) {
+ const [runnable, configurable] = await Promise.all([
+ deps.connectorModel.resolveAll(options.agentId),
+ deps.connectorModel.queryAvailableForAgent(options.agentId),
+ ]);
+ const run = runnable.find((c) => c.identifier === identifier);
+ if (run?.agentId === options.agentId) return resolveExisting();
+ const own = configurable.find((c) => c.identifier === identifier);
+ if (own && own.id !== run?.id)
+ return { installedNow: false, resolution: connectorResolution(own) };
+ }
+
let manifest: unknown;
try {
manifest = await deps.discoverService.getMcpManifest({ identifier });
} catch {
// Not a marketplace plugin (or the market is unreachable).
}
+ if (!manifest || typeof manifest !== 'object') return resolveExisting();
- if (hasLoadableApis(manifest)) {
- if (existing) await deps.pluginModel.update(identifier, { manifest: manifest as any });
- else await deps.pluginModel.create({ identifier, manifest: manifest as any, type: 'plugin' });
-
- return { installedNow: true, resolution: { source: 'installed', status: 'loadable' } };
+ const outcome = await deps.installMarketplaceConnector(
+ identifier,
+ manifest as MarketMcpManifest,
+ {
+ // Whether the market hosts a stdio server is on its detail, not its
+ // manifest, and the web install reads it there too: without it a hosted
+ // server would be refused as one only the desktop app can run. A detail it
+ // cannot read fails the install, as it fails the web's, rather than reading
+ // as "not hosted"; the installer asks only when it decides the deployment.
+ readHostedEndpoint: async () =>
+ (
+ (await deps.discoverService.getMcpDetail({ identifier })) as
+ { haveCloudEndpoint?: unknown } | undefined
+ )?.haveCloudEndpoint,
+ },
+ );
+ switch (outcome.status) {
+ case 'installed': {
+ // Resolve as the agent's runs will (an agent row added meanwhile comes first)
+ const { resolution } = await resolveExisting();
+ return { installedNow: true, resolution };
+ }
+ case 'exists': {
+ // Enabled and connected, or not: the connector answers like any other
+ return resolveExisting();
+ }
+ case 'blocked': {
+ return {
+ installedNow: false,
+ resolution: { blocker: outcome.blocker, status: 'needs-user-install' },
+ };
+ }
}
-
- return {
- installedNow: false,
- resolution: await resolvePluginIdentifier(identifier, deps, options),
- };
};
export const NEXT_RUN_NOTE =
diff --git a/packages/builtin-tool-agent-builder/src/manifest.ts b/packages/builtin-tool-agent-builder/src/manifest.ts
index 47f209a1ecc..1550e2b1a70 100644
--- a/packages/builtin-tool-agent-builder/src/manifest.ts
+++ b/packages/builtin-tool-agent-builder/src/manifest.ts
@@ -56,6 +56,8 @@ export const AgentBuilderManifest: BuiltinToolManifest = {
{
description:
'Install a plugin for the agent. This tool ALWAYS REQUIRES user approval before installation, even in auto-run mode. For MCP marketplace plugins, it will install and enable the plugin. For Composio tools and LobehubSkill providers that need OAuth, it will initiate the connection flow and wait for user to complete authorization.',
+ // An install adds a third-party endpoint the agent's later runs call
+ humanIntervention: 'always',
name: AgentBuilderApiName.installPlugin,
parameters: {
properties: {
diff --git a/packages/builtin-tool-agent-management/src/manifest.ts b/packages/builtin-tool-agent-management/src/manifest.ts
index 5f7902875ff..ef098ad7cf0 100644
--- a/packages/builtin-tool-agent-management/src/manifest.ts
+++ b/packages/builtin-tool-agent-management/src/manifest.ts
@@ -194,7 +194,9 @@ export const AgentManagementManifest: BuiltinToolManifest = {
},
{
description:
- "Install a plugin/tool for an agent. Use 'official' source for builtin tools, Composio integrations, and LobehubSkill providers. Use 'market' source for MCP marketplace plugins.",
+ "Install a plugin/tool for an agent. This tool ALWAYS REQUIRES user approval before installation, even in auto-run mode. Use 'official' source for builtin tools, Composio integrations, and LobehubSkill providers. Use 'market' source for MCP marketplace plugins.",
+ // An install adds a third-party endpoint the agent's later runs call
+ humanIntervention: 'always',
name: AgentManagementApiName.installPlugin,
parameters: {
properties: {
diff --git a/packages/const/src/plugin.test.ts b/packages/const/src/plugin.test.ts
index dbc2ecd5176..d3c8429e99e 100644
--- a/packages/const/src/plugin.test.ts
+++ b/packages/const/src/plugin.test.ts
@@ -6,6 +6,8 @@ import {
humanInterventionMayResolveTo,
isMarketplaceInstallRunnable,
keepsDesktopStdioExecution,
+ marketplaceToolIntervention,
+ marketplaceToolPoliciesOf,
mayRequireMandatoryApproval,
withMandatoryApprovalMark,
} from './plugin';
@@ -202,3 +204,40 @@ describe('withMandatoryApprovalMark', () => {
expect(hasMandatoryApproval(null)).toBe(false);
});
});
+
+describe('marketplace tool policies', () => {
+ it('reads the per-tool market policies a connector stores', () => {
+ expect(
+ marketplaceToolPoliciesOf({ marketplaceToolPolicies: { search: null, send: 'required' } }),
+ ).toEqual(
+ new Map<string, unknown>([
+ ['search', null],
+ ['send', 'required'],
+ ]),
+ );
+ // An empty record is a record: the market declared no tool
+ expect(marketplaceToolPoliciesOf({ marketplaceToolPolicies: {} })).toEqual(new Map());
+ expect(marketplaceToolPoliciesOf({ marketplaceToolPolicies: ['search'] })).toBeUndefined();
+ expect(marketplaceToolPoliciesOf({ marketplaceToolPolicies: 'search' })).toBeUndefined();
+ expect(marketplaceToolPoliciesOf({})).toBeUndefined();
+ expect(marketplaceToolPoliciesOf(null)).toBeUndefined();
+ });
+
+ it('takes a tool its stored policy, or always when the market does not declare it', () => {
+ const policies = new Map<string, unknown>([
+ ['search', null],
+ ['send', 'required'],
+ ['delete', 'always'],
+ ]);
+
+ // The stored policy wins over whatever the listing (or a client) says
+ expect(marketplaceToolIntervention(policies, 'send', undefined)).toBe('required');
+ expect(marketplaceToolIntervention(policies, 'delete', 'never')).toBe('always');
+ expect(marketplaceToolIntervention(policies, 'search', 'always')).toBeUndefined();
+ expect(marketplaceToolIntervention(policies, 'exfiltrate', 'never')).toBe('always');
+ expect(marketplaceToolIntervention(new Map(), 'search', undefined)).toBe('always');
+ // A connector without stored policies (any install but an agent's HTTP one)
+ expect(marketplaceToolIntervention(undefined, 'anything', 'required')).toBe('required');
+ expect(marketplaceToolIntervention(undefined, 'anything', undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/const/src/plugin.ts b/packages/const/src/plugin.ts
index 3b32c5f98d8..2d5d5bb04cd 100644
--- a/packages/const/src/plugin.ts
+++ b/packages/const/src/plugin.ts
@@ -65,6 +65,46 @@ export const isMarketplaceInstallCompleted = (metadata: unknown): boolean =>
typeof metadata === 'object' &&
(metadata as Record<string, unknown>)[MARKETPLACE_INSTALL_COMPLETED_KEY] === true;
+/**
+ * `user_connectors.metadata` key holding, on a marketplace MCP an agent
+ * installed from an HTTP listing, the approval the market manifest gives each
+ * tool it lists: tool name β†’ its `humanIntervention` (`null` for none). What
+ * gets synced is what the server itself lists, at the install or any later
+ * sync, so each sync takes a tool's approval from here
+ * ({@link marketplaceToolIntervention}): a declared tool the server only starts
+ * listing later keeps the manifest's policy, and a tool the manifest does not
+ * declare (added later, or renamed), which nobody vouched for, gets `always`.
+ */
+export const MARKETPLACE_TOOL_POLICIES_KEY = 'marketplaceToolPolicies';
+
+/** The per-tool market policies a connector stores, or `undefined` when it stores none. */
+export const marketplaceToolPoliciesOf = (
+ metadata: unknown,
+): ReadonlyMap<string, unknown> | undefined => {
+ const policies =
+ metadata && typeof metadata === 'object'
+ ? (metadata as Record<string, unknown>)[MARKETPLACE_TOOL_POLICIES_KEY]
+ : undefined;
+ return policies && typeof policies === 'object' && !Array.isArray(policies)
+ ? new Map(Object.entries(policies))
+ : undefined;
+};
+
+/**
+ * The `humanIntervention` a tool the server lists is synced with. When the
+ * connector stores market policies, they decide: the tool's own (`null` β†’ none),
+ * or `always` for a tool they do not declare, whatever the listing says.
+ * Otherwise it is the one given (a manifest's, if any).
+ */
+export const marketplaceToolIntervention = (
+ marketPolicies: ReadonlyMap<string, unknown> | undefined,
+ toolName: string,
+ humanIntervention: unknown,
+): unknown => {
+ if (!marketPolicies) return humanIntervention;
+ return marketPolicies.has(toolName) ? (marketPolicies.get(toolName) ?? undefined) : 'always';
+};
+
/**
* `user_connectors.metadata` key a custom MCP installed from a protocol link
* sets. Those installs used to be custom plugins, whose stdio calls ran on the
diff --git a/packages/database/src/models/__tests__/connector.coverage.test.ts b/packages/database/src/models/__tests__/connector.coverage.test.ts
index 21664d6a313..1304075e804 100644
--- a/packages/database/src/models/__tests__/connector.coverage.test.ts
+++ b/packages/database/src/models/__tests__/connector.coverage.test.ts
@@ -28,6 +28,18 @@ const cleanup = async () => {
const base = { name: 'Connector', sourceType: 'builtin', status: 'connected' } as const;
+/** A base row written directly, as writers from before the identifier lock could duplicate one. */
+const insertBaseRow = async (fields: {
+ identifier: string;
+ metadata?: Record<string, unknown>;
+}) => {
+ const [row] = await serverDB
+ .insert(userConnectors)
+ .values({ ...base, ...fields, userId })
+ .returning();
+ return row;
+};
+
describe('ConnectorModel coverage edges', () => {
beforeEach(async () => {
await cleanup();
@@ -43,8 +55,8 @@ describe('ConnectorModel coverage edges', () => {
it('prefers the base row mounted by the agent over a free base row', async () => {
const model = new ConnectorModel(serverDB, userId);
const free = await model.create({ ...base, identifier: 'linear' });
- const mounted = await model.create({
- ...base,
+ // `create` refuses a held base identifier: seed the duplicate as an older writer left it
+ const mounted = await insertBaseRow({
identifier: 'linear',
metadata: { mountedByAgentId: agentId },
});
@@ -61,7 +73,7 @@ describe('ConnectorModel coverage edges', () => {
it('keeps one row per identifier when duplicates share the same priority', async () => {
const model = new ConnectorModel(serverDB, userId);
const first = await model.create({ ...base, identifier: 'notion' });
- const second = await model.create({ ...base, identifier: 'notion' });
+ const second = await insertBaseRow({ identifier: 'notion' });
const resolved = await model.resolveAll();
@@ -70,6 +82,26 @@ describe('ConnectorModel coverage edges', () => {
});
});
+ describe('queryBaseHolders', () => {
+ it('reads every base row of the scope holding the identifier, oldest first', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const first = await model.create({ ...base, identifier: 'linear' });
+ const mounted = await insertBaseRow({
+ identifier: 'linear',
+ metadata: { mountedByAgentId: agentId },
+ });
+ // Neither an agent's own row nor another identifier holds the base one
+ await model.create({ ...base, agentId, identifier: 'linear' });
+ await model.create({ ...base, identifier: 'notion' });
+
+ expect((await model.queryBaseHolders('linear')).map((row) => row.id)).toEqual([
+ first.id,
+ mounted.id,
+ ]);
+ expect(await model.queryBaseHolders('slack')).toEqual([]);
+ });
+ });
+
describe('empty identifier lists', () => {
it('returns [] without querying', async () => {
const model = new ConnectorModel(serverDB, userId);
diff --git a/packages/database/src/models/__tests__/connector.test.ts b/packages/database/src/models/__tests__/connector.test.ts
index 997da548ffb..0a4c41b0d3b 100644
--- a/packages/database/src/models/__tests__/connector.test.ts
+++ b/packages/database/src/models/__tests__/connector.test.ts
@@ -3,9 +3,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import type { ConnectorCredentials } from '../../schemas';
-import { agentEvalDatasets, agents, userConnectors, users, workspaces } from '../../schemas';
+import {
+ agentEvalDatasets,
+ agents,
+ userConnectors,
+ userConnectorTools,
+ users,
+ workspaces,
+} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
-import { ConnectorModel } from '../connector';
+import { ConnectorIdentifierHeldError, ConnectorModel } from '../connector';
import { EvalConnectorUpdateError } from '../connectorEval';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -343,6 +350,238 @@ describe('ConnectorModel', () => {
expect(callGateKeeper.encrypt).toHaveBeenCalledOnce();
expect(result.credentials).toBe(`call:${JSON.stringify(apikeyCredentials)}`);
});
+
+ it('creates a base row once while another writer claims its identifier', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const input = createBuiltinConnectorInput('fetch-mcp', 'Fetch');
+ const fetchRows = () =>
+ serverDB.select().from(userConnectors).where(eq(userConnectors.identifier, 'fetch-mcp'));
+
+ // An OpenAPI create racing an Agent Builder install's claim
+ const [created, claimed] = await Promise.allSettled([
+ model.create(input),
+ model.createUnlessIdentifierHeld(input),
+ ]);
+
+ expect(await fetchRows()).toHaveLength(1);
+ if (created.status === 'rejected')
+ expect(created.reason).toBeInstanceOf(ConnectorIdentifierHeldError);
+ else expect(claimed).toEqual({ status: 'fulfilled', value: { holder: created.value } });
+ await expect(model.create(input)).rejects.toThrow(ConnectorIdentifierHeldError);
+ // An agent's own row does not take the base identifier
+ await serverDB.insert(agents).values({ id: 'fetch-agent', userId });
+ await model.create({ ...input, agentId: 'fetch-agent' });
+ expect(await fetchRows()).toHaveLength(2);
+ });
+ });
+
+ describe('createUnlessIdentifierHeld', () => {
+ const marketplaceInput = {
+ identifier: 'fetch-mcp',
+ name: 'Fetch',
+ sourceType: 'marketplace',
+ status: 'disconnected',
+ };
+ const fetchRows = () =>
+ serverDB.select().from(userConnectors).where(eq(userConnectors.identifier, 'fetch-mcp'));
+
+ it('creates a base connector when no base row of the scope holds the identifier', async () => {
+ // Another scope's row and an agent's own row do not hold the base identifier
+ await new ConnectorModel(serverDB, userId).create(marketplaceInput);
+ await serverDB.insert(agents).values({ id: 'held-agent', userId, workspaceId });
+ await new ConnectorModel(serverDB, userId, workspaceId).create({
+ ...marketplaceInput,
+ agentId: 'held-agent',
+ });
+
+ const result = await new ConnectorModel(
+ serverDB,
+ userId,
+ workspaceId,
+ ).createUnlessIdentifierHeld(marketplaceInput);
+
+ expect(result).toEqual({
+ created: expect.objectContaining({ agentId: null, identifier: 'fetch-mcp', workspaceId }),
+ });
+ expect(await fetchRows()).toHaveLength(3);
+ });
+
+ it('returns the holding row and writes nothing when it may not be replaced', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const holder = await model.create(marketplaceInput);
+ const canReplace = vi.fn(() => false);
+
+ expect(
+ await model.createUnlessIdentifierHeld(
+ { ...marketplaceInput, name: 'Other' },
+ { canReplace },
+ ),
+ ).toEqual({ holder: expect.objectContaining({ id: holder.id, name: 'Fetch' }) });
+ expect(canReplace).toHaveBeenCalledWith(expect.objectContaining({ id: holder.id }));
+ expect(await fetchRows()).toEqual([expect.objectContaining({ id: holder.id })]);
+ });
+
+ it('replaces a holding row it may replace, with its tools', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const holder = await model.create(marketplaceInput);
+ await serverDB.insert(userConnectorTools).values({
+ crudType: 'read',
+ permission: 'auto',
+ toolName: 'stale',
+ userConnectorId: holder.id,
+ userId,
+ });
+
+ const result = await model.createUnlessIdentifierHeld(
+ { ...marketplaceInput, name: 'Fetch again' },
+ { canReplace: () => true },
+ );
+
+ expect(result).toEqual({ created: expect.objectContaining({ name: 'Fetch again' }) });
+ expect(await fetchRows()).toEqual([
+ expect.objectContaining({ id: 'created' in result ? result.created.id : undefined }),
+ ]);
+ expect(await serverDB.select().from(userConnectorTools)).toEqual([]);
+ });
+
+ it('replaces nothing while any of duplicate base holders may not go', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ // Rows a writer from before the identifier lock could leave side by side
+ const [stale, live] = await serverDB
+ .insert(userConnectors)
+ .values(
+ [true, false].map((stale) => ({ ...marketplaceInput, metadata: { stale }, userId })),
+ )
+ .returning();
+
+ expect(
+ await model.createUnlessIdentifierHeld(
+ { ...marketplaceInput, name: 'Fetch again' },
+ { canReplace: (row) => row.metadata?.stale === true },
+ ),
+ ).toEqual({ holder: expect.objectContaining({ id: live.id }) });
+ expect((await fetchRows()).map((row) => row.id).sort()).toEqual([live.id, stale.id].sort());
+ });
+
+ it('judges a holder a re-add is rewriting only once the re-add has landed', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const holder = await model.create({ ...marketplaceInput, metadata: { stale: true } });
+
+ // A re-add (the web install's `update`) holds the row while it rewrites it
+ let land!: () => void;
+ const landing = new Promise<void>((resolve) => (land = resolve));
+ let locked!: () => void;
+ const rowLocked = new Promise<void>((resolve) => (locked = resolve));
+ const reAdd = serverDB.transaction(async (tx) => {
+ await tx
+ .select()
+ .from(userConnectors)
+ .where(eq(userConnectors.id, holder.id))
+ .for('update');
+ locked();
+ await landing;
+ await tx
+ .update(userConnectors)
+ .set({ metadata: { readded: true } })
+ .where(eq(userConnectors.id, holder.id));
+ });
+ await rowLocked;
+
+ // Only the stale row may be replaced, not the one the re-add rewrote
+ const claim = model.createUnlessIdentifierHeld(
+ { ...marketplaceInput, name: 'Fetch again' },
+ { canReplace: (row) => row.metadata?.stale === true },
+ );
+ // The claim reaches the row before the re-add lands
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ land();
+ await reAdd;
+
+ expect(await claim).toEqual({ holder: expect.objectContaining({ id: holder.id }) });
+ expect(await fetchRows()).toEqual([
+ expect.objectContaining({ id: holder.id, metadata: { readded: true } }),
+ ]);
+ });
+
+ it('creates the connector once for concurrent calls', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+
+ const results = await Promise.all([
+ model.createUnlessIdentifierHeld(marketplaceInput),
+ model.createUnlessIdentifierHeld(marketplaceInput),
+ ]);
+
+ expect(results.filter((result) => 'created' in result)).toHaveLength(1);
+ expect(await fetchRows()).toHaveLength(1);
+ });
+ });
+
+ describe('moveToBaseUnlessIdentifierHeld', () => {
+ const agentInput = {
+ agentId: 'move-agent',
+ identifier: 'fetch-mcp',
+ name: 'Fetch',
+ sourceType: 'marketplace',
+ status: 'connected',
+ } as const;
+ const baseRows = async () =>
+ (await serverDB.select().from(userConnectors)).filter((row) => row.agentId === null);
+
+ beforeEach(async () => {
+ await serverDB.insert(agents).values({ id: 'move-agent', userId });
+ });
+
+ it('moves an agent connector into the base scope when no base row holds the identifier', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const agentRow = await model.create(agentInput);
+
+ expect(await model.moveToBaseUnlessIdentifierHeld(agentRow.id, 'fetch-mcp')).toEqual({
+ moved: true,
+ });
+ expect(await baseRows()).toEqual([expect.objectContaining({ id: agentRow.id })]);
+ });
+
+ it('reports a connector another unbind already moved as moved, not as a holder', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const agentRow = await model.create(agentInput);
+
+ // Both calls read the row as the agent's before either moved it (a retry,
+ // or two unbinds at once): the second finds the row itself in the base scope
+ const results = await Promise.all([
+ model.moveToBaseUnlessIdentifierHeld(agentRow.id, 'fetch-mcp'),
+ model.moveToBaseUnlessIdentifierHeld(agentRow.id, 'fetch-mcp'),
+ ]);
+ expect(await model.moveToBaseUnlessIdentifierHeld(agentRow.id, 'fetch-mcp')).toEqual({
+ moved: true,
+ });
+
+ expect(results).toEqual([{ moved: true }, { moved: true }]);
+ expect(await baseRows()).toEqual([expect.objectContaining({ id: agentRow.id })]);
+ });
+
+ it('returns the holding base row and leaves the agent connector bound', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const holder = await model.create({ ...agentInput, agentId: null });
+ const agentRow = await model.create(agentInput);
+
+ expect(await model.moveToBaseUnlessIdentifierHeld(agentRow.id, 'fetch-mcp')).toEqual({
+ holder: expect.objectContaining({ id: holder.id }),
+ });
+ expect(await model.findById(agentRow.id)).toMatchObject({ agentId: 'move-agent' });
+ });
+
+ it('never leaves two base rows when a create of the identifier runs at the same time', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const agentRow = await model.create(agentInput);
+ const { agentId: _agentId, ...baseInput } = agentInput;
+
+ await Promise.all([
+ model.moveToBaseUnlessIdentifierHeld(agentRow.id, 'fetch-mcp'),
+ model.createUnlessIdentifierHeld(baseInput),
+ ]);
+
+ expect(await baseRows()).toHaveLength(1);
+ });
});
describe('query', () => {
@@ -723,7 +962,7 @@ describe('ConnectorModel', () => {
const created = await otherModel.create(createBuiltinConnectorInput('linear', 'Linear'));
const model = new ConnectorModel(serverDB, userId);
- await model.update(created.id, { name: 'Hacked' });
+ await expect(model.update(created.id, { name: 'Hacked' })).resolves.toBe(false);
const [row] = await serverDB
.select()
@@ -731,6 +970,19 @@ describe('ConnectorModel', () => {
.where(eq(userConnectors.id, created.id));
expect(row.name).toBe('Linear');
});
+
+ it('reports a row a claim replaced after it was read as not updated', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const read = await model.create(createBuiltinConnectorInput('linear', 'Linear'));
+ const claim = await model.createUnlessIdentifierHeld(
+ createBuiltinConnectorInput('linear', 'Linear'),
+ { canReplace: () => true },
+ );
+ if (!('created' in claim)) throw new Error('the claim should replace the row it read');
+
+ await expect(model.update(read.id, { name: 'Re-added' })).resolves.toBe(false);
+ await expect(model.update(claim.created.id, { name: 'Re-added' })).resolves.toBe(true);
+ });
});
describe('updateStatus', () => {
@@ -845,4 +1097,90 @@ describe('ConnectorModel', () => {
expect(await otherModel.findById(created.id)).not.toBeNull();
});
});
+
+ describe('updateMetadataIfContains', () => {
+ const tag = { installAttempt: 'attempt-1' };
+
+ it('replaces the metadata while it still has the tag', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const created = await model.create({
+ ...createBuiltinConnectorInput('linear', 'Linear'),
+ metadata: { avatar: 'a.png', ...tag },
+ });
+
+ expect(await model.updateMetadataIfContains(created.id, tag, { avatar: 'done.png' })).toBe(
+ true,
+ );
+ expect((await model.findById(created.id))?.metadata).toEqual({ avatar: 'done.png' });
+ });
+
+ it('keeps metadata rewritten since', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const created = await model.create({
+ ...createBuiltinConnectorInput('linear', 'Linear'),
+ metadata: tag,
+ });
+ await model.update(created.id, { metadata: { avatar: 'readded.png' } });
+
+ expect(await model.updateMetadataIfContains(created.id, tag, { avatar: 'done.png' })).toBe(
+ false,
+ );
+ expect((await model.findById(created.id))?.metadata).toEqual({ avatar: 'readded.png' });
+ });
+
+ it("does not update another user's row", async () => {
+ const otherModel = new ConnectorModel(serverDB, otherUserId);
+ const created = await otherModel.create({
+ ...createBuiltinConnectorInput('linear', 'Linear'),
+ metadata: tag,
+ });
+
+ expect(
+ await new ConnectorModel(serverDB, userId).updateMetadataIfContains(created.id, tag, {}),
+ ).toBe(false);
+ expect((await otherModel.findById(created.id))?.metadata).toEqual(tag);
+ });
+ });
+
+ describe('deleteIfMetadataContains', () => {
+ const tag = { installAttempt: 'attempt-1' };
+
+ it('deletes the row while its metadata still has the tag', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const created = await model.create({
+ ...createBuiltinConnectorInput('linear', 'Linear'),
+ metadata: { avatar: 'a.png', ...tag },
+ });
+
+ expect(await model.deleteIfMetadataContains(created.id, tag)).toBe(true);
+ expect(await model.findById(created.id)).toBeNull();
+ });
+
+ it('keeps a row whose metadata was rewritten since', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const created = await model.create({
+ ...createBuiltinConnectorInput('linear', 'Linear'),
+ metadata: tag,
+ });
+ await model.update(created.id, { metadata: { avatar: 'readded.png' } });
+
+ expect(await model.deleteIfMetadataContains(created.id, tag)).toBe(false);
+ expect(await model.findById(created.id)).toMatchObject({
+ metadata: { avatar: 'readded.png' },
+ });
+ });
+
+ it("does not delete another user's row", async () => {
+ const otherModel = new ConnectorModel(serverDB, otherUserId);
+ const created = await otherModel.create({
+ ...createBuiltinConnectorInput('linear', 'Linear'),
+ metadata: tag,
+ });
+
+ expect(
+ await new ConnectorModel(serverDB, userId).deleteIfMetadataContains(created.id, tag),
+ ).toBe(false);
+ expect(await otherModel.findById(created.id)).not.toBeNull();
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/connectorIdentifierClaim.test.ts b/packages/database/src/models/__tests__/connectorIdentifierClaim.test.ts
new file mode 100644
index 00000000000..554d2e125ec
--- /dev/null
+++ b/packages/database/src/models/__tests__/connectorIdentifierClaim.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import { baseIdentifierLockKey } from '../connectorIdentifierClaim';
+
+describe('baseIdentifierLockKey', () => {
+ it('gives every spelling of one workspace the same lock', () => {
+ const key = baseIdentifierLockKey({ userId: 'u1', workspaceId: 'ws-1' }, 'notion');
+
+ expect(baseIdentifierLockKey({ userId: 'u1', workspaceId: ' ws-1 ' }, 'notion')).toBe(key);
+ expect(baseIdentifierLockKey({ userId: 'u2', workspaceId: 'ws-1\n' }, 'notion')).toBe(key);
+ });
+
+ it('locks a blank workspace id as the personal scope it writes to', () => {
+ const personal = baseIdentifierLockKey({ userId: 'u1' }, 'notion');
+
+ expect(baseIdentifierLockKey({ userId: 'u1', workspaceId: '' }, 'notion')).toBe(personal);
+ expect(baseIdentifierLockKey({ userId: 'u1', workspaceId: ' ' }, 'notion')).toBe(personal);
+ expect(baseIdentifierLockKey({ userId: 'u2' }, 'notion')).not.toBe(personal);
+ });
+
+ it('keeps identifiers and scopes apart', () => {
+ const key = baseIdentifierLockKey({ userId: 'u1', workspaceId: 'ws-1' }, 'notion');
+
+ expect(baseIdentifierLockKey({ userId: 'u1', workspaceId: 'ws-1' }, 'linear')).not.toBe(key);
+ expect(baseIdentifierLockKey({ userId: 'u1', workspaceId: 'ws-2' }, 'notion')).not.toBe(key);
+ expect(baseIdentifierLockKey({ userId: 'u1' }, 'notion')).not.toBe(key);
+ });
+});
diff --git a/packages/database/src/models/__tests__/connectorVisibility.test.ts b/packages/database/src/models/__tests__/connectorVisibility.test.ts
index d4c9d5dd7c8..98394871c1e 100644
--- a/packages/database/src/models/__tests__/connectorVisibility.test.ts
+++ b/packages/database/src/models/__tests__/connectorVisibility.test.ts
@@ -15,7 +15,7 @@ import {
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { CHANNEL_TOPIC_TRIGGER } from '../../utils/topicVisibility';
-import { ConnectorModel } from '../connector';
+import { ConnectorIdentifierHeldError, ConnectorModel } from '../connector';
import { ConnectorToolModel } from '../connectorTool';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -305,7 +305,7 @@ describe('connector visibility β€” agent configuration', () => {
const model = new ConnectorModel(serverDB, owner, workspaceId);
expect(await model.queryAvailableForAgent(privateAgent)).toEqual([
- { identifier: 'notion', isEnabled: false, status: 'connected' },
+ { id: privateRow.id, identifier: 'notion', isEnabled: false, status: 'connected' },
]);
});
});
@@ -389,6 +389,60 @@ describe('connector visibility β€” write paths', () => {
expect(await model.findScopedByIdentifier('slack', undefined, undefined, 'private')).toBeNull();
});
+ it('claims a base identifier within one visibility', async () => {
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+ const input = {
+ identifier: 'notion',
+ mcpConnectionType: 'http' as const,
+ mcpServerUrl: 'https://notion.example.com/mcp',
+ name: 'Notion',
+ sourceType: 'custom' as const,
+ status: 'connected' as const,
+ };
+ const mine = await insertConnector({ identifier: 'notion', visibility: 'private' });
+
+ // The caller's private row does not hold the shared identifier.
+ const shared = await model.create(input);
+ expect(shared.visibility).toBe('public');
+ expect((await model.queryBaseHolders('notion')).map((row) => row.id)).toEqual([shared.id]);
+ expect((await model.queryBaseHolders('notion', 'private')).map((row) => row.id)).toEqual([
+ mine.id,
+ ]);
+
+ // Within one visibility the identifier stays held.
+ await expect(model.create(input)).rejects.toThrow(ConnectorIdentifierHeldError);
+ await expect(model.create({ ...input, visibility: 'private' })).rejects.toThrow(
+ ConnectorIdentifierHeldError,
+ );
+
+ // A teammate's private row holds nothing for the caller.
+ await insertConnector({ identifier: 'slack', userId: mate, visibility: 'private' });
+ const myPrivateSlack = await model.create({
+ ...input,
+ identifier: 'slack',
+ visibility: 'private',
+ });
+ expect(myPrivateSlack.visibility).toBe('private');
+ });
+
+ it('moves an agent connector into the base scope within its own visibility', async () => {
+ const model = new ConnectorModel(serverDB, owner, workspaceId);
+ const myPrivate = await insertConnector({ identifier: 'notion', visibility: 'private' });
+
+ const sharedAgentRow = await insertConnector({ agentId: workspaceAgent, identifier: 'notion' });
+ expect(await model.moveToBaseUnlessIdentifierHeld(sharedAgentRow.id, 'notion')).toEqual({
+ moved: true,
+ });
+
+ const privateAgentRow = await insertConnector({
+ agentId: privateAgent,
+ identifier: 'notion',
+ visibility: 'private',
+ });
+ const blocked = await model.moveToBaseUnlessIdentifierHeld(privateAgentRow.id, 'notion');
+ expect('holder' in blocked && blocked.holder.id).toBe(myPrivate.id);
+ });
+
it('targets the row holding the Composio account a write names', async () => {
const composio = (connectedAccountId: string) => ({ composio: { connectedAccountId } });
const shared = await insertConnector({
diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.ts
index e1e0f3ad30b..3c08baf1f85 100644
--- a/packages/database/src/models/connector.ts
+++ b/packages/database/src/models/connector.ts
@@ -6,14 +6,23 @@ import pMap from 'p-map';
import type { ConnectorCredentials, NewUserConnector, UserConnectorItem } from '../schemas';
import { agentEvalDatasets, ConnectorStatus, userConnectors, userConnectorTools } from '../schemas';
-import type { LobeChatDatabase } from '../type';
+import type { LobeChatDatabase, Transaction } from '../type';
import {
buildWorkspacePayload,
buildWorkspaceWhere,
normalizeWorkspaceId,
} from '../utils/workspace';
import { EvalConnectorUpdateError, normalizeEvalConnectorPatch } from './connectorEval';
+import {
+ type BaseIdentifierScope,
+ claimBaseIdentifier,
+ ConnectorIdentifierHeldError,
+ moveToBaseUnlessIdentifierHeld,
+ queryBaseHolders,
+ sameBaseVisibility,
+} from './connectorIdentifierClaim';
import { ConnectorLinkModel, isConnectorOAuthAccounts } from './connectorLink';
+import { deleteIfMetadataContains, updateMetadataIfContains } from './connectorMetadataGuard';
import {
connectorAccessScope,
connectorAgentConfigScope,
@@ -21,6 +30,7 @@ import {
type ConnectorRunTarget,
} from './connectorScope';
+export { ConnectorIdentifierHeldError } from './connectorIdentifierClaim';
export type { ConnectorRunTarget } from './connectorScope';
/**
@@ -304,65 +314,126 @@ export class ConnectorModel {
return this;
};
+ /**
+ * Create a connector. An agent's own row is inserted as is. A base row
+ * (`agent_id IS NULL`) is claimed like {@link createUnlessIdentifierHeld}, under
+ * the identifier lock, and throws {@link ConnectorIdentifierHeldError} when a
+ * base row of the scope already holds the identifier: no caller can add a
+ * second base row for an identifier between another writer's lookup and insert.
+ */
create = async (
params: CreateConnectorParams,
gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<UserConnectorItem> => {
+ if (params.agentId)
+ return this.db.transaction((tx) => this.insertInTransaction(tx, params, gateKeeper));
+
+ const claim = await this.createUnlessIdentifierHeld(params, { gateKeeper });
+ if ('holder' in claim) throw new ConnectorIdentifierHeldError(params.identifier);
+ return claim.created;
+ };
+
+ /**
+ * Create a base connector (`agent_id IS NULL`) unless a row in this scope
+ * already holds its identifier in its visibility. The lookup and the insert
+ * are one step, serialized on the identifier lock every base-row writer takes
+ * ({@link claimBaseIdentifier}). `canReplace` may let the holding rows go:
+ * they are deleted, with their tools, in that step; one that may not go
+ * keeps the identifier and is returned.
+ */
+ createUnlessIdentifierHeld = async (
+ params: Omit<CreateConnectorParams, 'agentId'>,
+ options: {
+ canReplace?: (holder: UserConnectorItem) => boolean;
+ gateKeeper?: GateKeeper;
+ } = {},
+ ): Promise<{ created: UserConnectorItem } | { holder: UserConnectorItem }> => {
+ const { canReplace, gateKeeper = this.gateKeeper } = options;
+
return this.db.transaction(async (tx) => {
- if (!this.evaluationDatasetId && params.metadata?.agentEval) {
- throw new EvalConnectorUpdateError(
- 'Use the Dataset connection API for evaluation connections',
- );
- }
- if (this.evaluationDatasetId) {
- const [dataset] = await tx
- .select({ id: agentEvalDatasets.id })
- .from(agentEvalDatasets)
- .where(
- and(
- eq(agentEvalDatasets.id, this.evaluationDatasetId),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- agentEvalDatasets,
- ),
+ const holder = await claimBaseIdentifier(tx, this.baseIdentifierScope(), params, canReplace);
+ if (holder) return { holder };
+ return {
+ created: await this.insertInTransaction(tx, { ...params, agentId: null }, gateKeeper),
+ };
+ });
+ };
+
+ /** See {@link moveToBaseUnlessIdentifierHeld}. */
+ moveToBaseUnlessIdentifierHeld = async (id: string, identifier: string) =>
+ moveToBaseUnlessIdentifierHeld(this.db, this.baseIdentifierScope(), id, identifier);
+
+ /** See {@link queryBaseHolders}. */
+ queryBaseHolders = async (
+ identifier: string,
+ visibility?: ConnectorVisibility,
+ ): Promise<UserConnectorItem[]> =>
+ queryBaseHolders(this.db, this.baseIdentifierScope(), identifier, visibility);
+
+ private baseIdentifierScope = (): BaseIdentifierScope => ({
+ ownership: this.ownership,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+
+ private insertInTransaction = async (
+ tx: Transaction,
+ params: CreateConnectorParams,
+ gateKeeper: GateKeeper | undefined,
+ ): Promise<UserConnectorItem> => {
+ if (!this.evaluationDatasetId && params.metadata?.agentEval) {
+ throw new EvalConnectorUpdateError(
+ 'Use the Dataset connection API for evaluation connections',
+ );
+ }
+ if (this.evaluationDatasetId) {
+ const [dataset] = await tx
+ .select({ id: agentEvalDatasets.id })
+ .from(agentEvalDatasets)
+ .where(
+ and(
+ eq(agentEvalDatasets.id, this.evaluationDatasetId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ agentEvalDatasets,
),
- )
- .for('share');
- if (!dataset) throw new EvalConnectorUpdateError('Dataset not found');
- if (params.credentials && !gateKeeper)
- throw new EvalConnectorUpdateError('Secure connection storage is unavailable');
- if (params.agentId || params.metadata?.mountedByAgentId)
- throw new EvalConnectorUpdateError(
- 'Evaluation connections cannot be assigned to a normal Agent',
- );
- const marker = params.metadata?.agentEval;
- params = {
- ...params,
- metadata: {
- ...params.metadata,
- agentEval: {
- ...(marker && typeof marker === 'object' && !Array.isArray(marker) ? marker : {}),
- datasetId: this.evaluationDatasetId,
- },
- },
- };
- }
- const credentials = params.credentials
- ? await encryptCredentials(params.credentials, gateKeeper)
- : null;
-
- const [result] = await tx
- .insert(userConnectors)
- .values(
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- { ...params, credentials },
),
)
- .returning();
+ .for('share');
+ if (!dataset) throw new EvalConnectorUpdateError('Dataset not found');
+ if (params.credentials && !gateKeeper)
+ throw new EvalConnectorUpdateError('Secure connection storage is unavailable');
+ if (params.agentId || params.metadata?.mountedByAgentId)
+ throw new EvalConnectorUpdateError(
+ 'Evaluation connections cannot be assigned to a normal Agent',
+ );
+ const marker = params.metadata?.agentEval;
+ params = {
+ ...params,
+ metadata: {
+ ...params.metadata,
+ agentEval: {
+ ...(marker && typeof marker === 'object' && !Array.isArray(marker) ? marker : {}),
+ datasetId: this.evaluationDatasetId,
+ },
+ },
+ };
+ }
+ const credentials = params.credentials
+ ? await encryptCredentials(params.credentials, gateKeeper)
+ : null;
- return result;
- });
+ const [result] = await tx
+ .insert(userConnectors)
+ .values(
+ buildWorkspacePayload(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { ...params, credentials },
+ ),
+ )
+ .returning();
+
+ return result;
};
/**
@@ -417,6 +488,17 @@ export class ConnectorModel {
await this.db.delete(userConnectors).where(and(eq(userConnectors.id, id), this.ownership()));
};
+ /** See {@link deleteIfMetadataContains}. */
+ deleteIfMetadataContains = async (id: string, match: Record<string, unknown>) =>
+ deleteIfMetadataContains(this.db, this.ownership, id, match);
+
+ /** See {@link updateMetadataIfContains}. */
+ updateMetadataIfContains = async (
+ id: string,
+ match: Record<string, unknown>,
+ metadata: NonNullable<DecryptedConnector['metadata']>,
+ ) => updateMetadataIfContains(this.db, this.ownership, id, match, metadata);
+
query = async (
gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<DecryptedConnector[]> => {
@@ -572,7 +654,7 @@ export class ConnectorModel {
*/
queryAvailableForAgent = async (
agentId?: string,
- ): Promise<Pick<UserConnectorItem, 'identifier' | 'isEnabled' | 'status'>[]> => {
+ ): Promise<Pick<UserConnectorItem, 'id' | 'identifier' | 'isEnabled' | 'status'>[]> => {
const base = this.evaluationDatasetId
? this.ownership()
: connectorAgentConfigScope(
@@ -586,7 +668,8 @@ export class ConnectorModel {
.where(this.agentNarrowing(base, agentId))
.orderBy(...this.resolutionOrder());
- return this.pickByPriority(rows, agentId).map(({ identifier, isEnabled, status }) => ({
+ return this.pickByPriority(rows, agentId).map(({ id, identifier, isEnabled, status }) => ({
+ id,
identifier,
isEnabled,
status,
@@ -611,12 +694,6 @@ export class ConnectorModel {
gateKeeper: GateKeeper | undefined = this.gateKeeper,
visibility: ConnectorVisibility = 'public',
): Promise<DecryptedConnector | null> => {
- const sameVisibility =
- !agentId && normalizeWorkspaceId(this.workspaceId)
- ? visibility === 'private'
- ? and(eq(userConnectors.visibility, 'private'), eq(userConnectors.userId, this.userId))
- : eq(userConnectors.visibility, 'public')
- : undefined;
const [row] = await this.db
.select()
.from(userConnectors)
@@ -625,7 +702,7 @@ export class ConnectorModel {
this.ownership(),
eq(userConnectors.identifier, identifier),
agentId ? eq(userConnectors.agentId, agentId) : isNull(userConnectors.agentId),
- sameVisibility,
+ agentId ? undefined : sameBaseVisibility(this.baseIdentifierScope(), visibility),
),
)
.limit(1);
@@ -893,19 +970,24 @@ export class ConnectorModel {
return row ?? null;
};
+ /**
+ * Returns whether the row was there to update: one deleted after the caller
+ * read it (a claim that replaced it, see {@link createUnlessIdentifierHeld})
+ * is not, and its writer must look again for what holds it now.
+ */
update = async (
id: string,
patch: UpdateConnectorParams,
gateKeeper: GateKeeper | undefined = this.gateKeeper,
- ): Promise<void> => {
- await this.db.transaction(async (tx) => {
+ ): Promise<boolean> =>
+ this.db.transaction(async (tx) => {
const [current] = await tx
.select()
.from(userConnectors)
.where(and(eq(userConnectors.id, id), this.ownership()))
.limit(1)
.for('update');
- if (!current) return;
+ if (!current) return false;
const normalized = await normalizeEvalConnectorPatch(
current,
patch,
@@ -955,8 +1037,8 @@ export class ConnectorModel {
updatedAt: new Date(),
})
.where(and(eq(userConnectors.id, id), this.ownership()));
+ return true;
});
- };
updateStatus = async (id: string, status: ConnectorStatus): Promise<void> => {
await this.db
diff --git a/packages/database/src/models/connectorIdentifierClaim.ts b/packages/database/src/models/connectorIdentifierClaim.ts
new file mode 100644
index 00000000000..9b1cbf95508
--- /dev/null
+++ b/packages/database/src/models/connectorIdentifierClaim.ts
@@ -0,0 +1,196 @@
+import type { ConnectorVisibility } from '@lobechat/types';
+import type { SQL } from 'drizzle-orm';
+import { and, asc, eq, inArray, isNull, sql } from 'drizzle-orm';
+
+import type { UserConnectorItem } from '../schemas';
+import { userConnectors } from '../schemas';
+import type { LobeChatDatabase, Transaction } from '../type';
+import { normalizeWorkspaceId } from '../utils/workspace';
+
+/**
+ * The connector scope a base-row claim runs in: the {@link ConnectorModel}'s
+ * user, workspace and row filter.
+ */
+export interface BaseIdentifierScope {
+ ownership: () => SQL | undefined;
+ userId: string;
+ workspaceId?: string;
+}
+
+/** {@link ConnectorModel.create} of a base connector whose identifier a base row of the scope holds. */
+export class ConnectorIdentifierHeldError extends Error {
+ constructor(identifier: string) {
+ super(`A connector with identifier "${identifier}" already exists`);
+ this.name = 'ConnectorIdentifierHeldError';
+ }
+}
+
+/**
+ * In a workspace, the base rows of one visibility: the shared rows (default),
+ * or the caller's own private rows. A base row holds its identifier within its
+ * visibility only, so a member's private connector never blocks (or rewrites)
+ * the shared one of the same identifier, nor the shared one a private one. A
+ * personal scope has one visibility.
+ */
+export const sameBaseVisibility = (
+ scope: BaseIdentifierScope,
+ visibility: ConnectorVisibility = 'public',
+) =>
+ normalizeWorkspaceId(scope.workspaceId)
+ ? visibility === 'private'
+ ? and(eq(userConnectors.visibility, 'private'), eq(userConnectors.userId, scope.userId))
+ : eq(userConnectors.visibility, 'public')
+ : undefined;
+
+/**
+ * The advisory-lock key of `identifier`'s base rows in this scope. It names the
+ * scope the rows are written to, so the workspace id is normalized as
+ * `buildWorkspacePayload` stores it: a padded id is its trimmed workspace, and
+ * a blank one is the user's personal scope.
+ */
+export const baseIdentifierLockKey = (
+ scope: Pick<BaseIdentifierScope, 'userId' | 'workspaceId'>,
+ identifier: string,
+) => {
+ const workspaceId = normalizeWorkspaceId(scope.workspaceId);
+ const scopeKey = workspaceId ? `workspace:${workspaceId}` : `user:${scope.userId}`;
+ return `user_connectors:${scopeKey}:${identifier}`;
+};
+
+/**
+ * Hold this scope's base-row lock on `identifier` until `tx` ends. A writer
+ * that adds a base row (a create, a move out of an agent) takes it before
+ * looking for a holder, so no two of them both find the identifier free. One
+ * lock covers every visibility of the identifier.
+ */
+const lockBaseIdentifier = async (
+ tx: Transaction,
+ scope: BaseIdentifierScope,
+ identifier: string,
+) => {
+ await tx.execute(
+ sql`SELECT pg_advisory_xact_lock(hashtext(${baseIdentifierLockKey(scope, identifier)}))`,
+ );
+};
+
+const baseHolderFilter = (
+ scope: BaseIdentifierScope,
+ identifier: string,
+ visibility?: ConnectorVisibility,
+) =>
+ and(
+ scope.ownership(),
+ eq(userConnectors.identifier, identifier),
+ isNull(userConnectors.agentId),
+ sameBaseVisibility(scope, visibility),
+ );
+
+/**
+ * The base rows of this scope holding `identifier` in `visibility`, oldest
+ * first, locked until `tx` ends: the caller judges and may delete them as
+ * read, so a rewrite of one ({@link ConnectorModel.update}, a re-add) either
+ * lands first, and is what gets judged, or waits for the caller.
+ */
+const findBaseHolders = async (
+ tx: Transaction,
+ scope: BaseIdentifierScope,
+ identifier: string,
+ visibility?: ConnectorVisibility,
+): Promise<UserConnectorItem[]> =>
+ tx
+ .select()
+ .from(userConnectors)
+ .where(baseHolderFilter(scope, identifier, visibility))
+ .orderBy(asc(userConnectors.createdAt))
+ .for('update');
+
+/**
+ * The base rows of this scope holding `identifier` in `visibility`, oldest
+ * first, read without the lock: rows written before it may duplicate the
+ * identifier, so a caller judging the holder before (or after) a claim judges
+ * every one of them.
+ */
+export const queryBaseHolders = async (
+ db: LobeChatDatabase,
+ scope: BaseIdentifierScope,
+ identifier: string,
+ visibility?: ConnectorVisibility,
+): Promise<UserConnectorItem[]> =>
+ db
+ .select()
+ .from(userConnectors)
+ .where(baseHolderFilter(scope, identifier, visibility))
+ .orderBy(asc(userConnectors.createdAt));
+
+/**
+ * Claim `identifier` for a new base row inside `tx`, under the identifier lock
+ * every base-row writer takes: the identifier indexes are not unique, so two
+ * concurrent callers would otherwise both find it free and both insert.
+ * `canReplace` may let the holding rows go: they are deleted, with their tools,
+ * in that step. Every holder is judged (rows written before the lock may
+ * duplicate the identifier), and the first one that may not go is returned:
+ * it keeps the identifier, and the caller inserts nothing.
+ */
+export const claimBaseIdentifier = async (
+ tx: Transaction,
+ scope: BaseIdentifierScope,
+ row: { identifier: string; visibility?: ConnectorVisibility },
+ canReplace?: (holder: UserConnectorItem) => boolean,
+): Promise<UserConnectorItem | undefined> => {
+ await lockBaseIdentifier(tx, scope, row.identifier);
+
+ const holders = await findBaseHolders(tx, scope, row.identifier, row.visibility);
+ const kept = holders.find((holder) => !canReplace?.(holder));
+ if (kept) return kept;
+ if (holders.length > 0) {
+ await tx.delete(userConnectors).where(
+ and(
+ inArray(
+ userConnectors.id,
+ holders.map((holder) => holder.id),
+ ),
+ scope.ownership(),
+ ),
+ );
+ }
+ return undefined;
+};
+
+/**
+ * Move an agent's connector into the base scope (`agent_id = NULL`) unless a
+ * base row in this scope already holds its identifier: the lookup and the
+ * move are one step, under the lock {@link claimBaseIdentifier} takes. The
+ * holder is looked for in the connector's own visibility, which the move keeps.
+ * A connector already moved (by a retry, or an unbind running at the same
+ * time) is reported as moved, not as holding its own identifier.
+ */
+export const moveToBaseUnlessIdentifierHeld = async (
+ db: LobeChatDatabase,
+ scope: BaseIdentifierScope,
+ id: string,
+ identifier: string,
+): Promise<{ holder: UserConnectorItem } | { moved: true }> =>
+ db.transaction(async (tx) => {
+ await lockBaseIdentifier(tx, scope, identifier);
+
+ const [moving] = await tx
+ .select({ visibility: userConnectors.visibility })
+ .from(userConnectors)
+ .where(and(eq(userConnectors.id, id), scope.ownership()))
+ .limit(1);
+ const holders = await findBaseHolders(tx, scope, identifier, moving?.visibility);
+ if (holders.some((holder) => holder.id === id)) return { moved: true as const };
+ if (holders.length > 0) return { holder: holders[0] };
+
+ await tx
+ .update(userConnectors)
+ .set({ agentId: null, updatedAt: new Date() })
+ .where(
+ and(
+ eq(userConnectors.id, id),
+ eq(userConnectors.identifier, identifier),
+ scope.ownership(),
+ ),
+ );
+ return { moved: true as const };
+ });
diff --git a/packages/database/src/models/connectorMetadataGuard.ts b/packages/database/src/models/connectorMetadataGuard.ts
new file mode 100644
index 00000000000..98845f2de1f
--- /dev/null
+++ b/packages/database/src/models/connectorMetadataGuard.ts
@@ -0,0 +1,62 @@
+import type { SQL } from 'drizzle-orm';
+import { and, eq, sql } from 'drizzle-orm';
+
+import type { ConnectorMetadata } from '../schemas';
+import { userConnectors } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { withoutEvalConnectorMarker } from './connectorEval';
+
+/** The {@link ConnectorModel}'s row filter: its user, workspace and access scope. */
+type ConnectorOwnership = () => SQL | undefined;
+
+const metadataContains = (match: Record<string, unknown>) =>
+ sql`${userConnectors.metadata} @> ${JSON.stringify(match)}::jsonb`;
+
+/**
+ * Delete the row, with its tools, only while its metadata still contains
+ * `match`: a writer that tagged the row removes it only if no one has
+ * rewritten it since (a re-add replaces the metadata). Returns whether it did.
+ */
+export const deleteIfMetadataContains = async (
+ db: LobeChatDatabase,
+ ownership: ConnectorOwnership,
+ id: string,
+ match: Record<string, unknown>,
+): Promise<boolean> => {
+ const deleted = await db
+ .delete(userConnectors)
+ .where(and(eq(userConnectors.id, id), ownership(), metadataContains(match)))
+ .returning({ id: userConnectors.id });
+ return deleted.length > 0;
+};
+
+/**
+ * Replace the row's metadata only while it still contains `match`, as
+ * {@link deleteIfMetadataContains} deletes: a writer that tagged the row
+ * finishes it only if no one has re-added it since, whose writer owns it now.
+ * An evaluation connection is left alone (its provenance goes through
+ * {@link ConnectorModel.update}). In a transaction, a write that lands holds
+ * the row's lock until it ends, so the writer's other writes to the row land
+ * with it, before any {@link ConnectorModel.update}. Returns whether it did.
+ */
+export const updateMetadataIfContains = async (
+ db: LobeChatDatabase,
+ ownership: ConnectorOwnership,
+ id: string,
+ match: Record<string, unknown>,
+ metadata: ConnectorMetadata,
+): Promise<boolean> => {
+ const updated = await db
+ .update(userConnectors)
+ .set({ metadata: withoutEvalConnectorMarker(metadata), updatedAt: new Date() })
+ .where(
+ and(
+ eq(userConnectors.id, id),
+ ownership(),
+ metadataContains(match),
+ sql`NOT COALESCE(jsonb_exists(${userConnectors.metadata}, 'agentEval'), false)`,
+ ),
+ )
+ .returning({ id: userConnectors.id });
+ return updated.length > 0;
+};
diff --git a/packages/openapi/src/services/mcp-server.service.test.ts b/packages/openapi/src/services/mcp-server.service.test.ts
index de9d166170f..1415e470667 100644
--- a/packages/openapi/src/services/mcp-server.service.test.ts
+++ b/packages/openapi/src/services/mcp-server.service.test.ts
@@ -5,11 +5,13 @@ import type { LobeChatDatabase } from '@/database/type';
import { McpServerService } from './mcp-server.service';
-const { connectorInstances, hasAnyPermissionMock, syncConnectorToolsByIdMock } = vi.hoisted(() => ({
- connectorInstances: [] as any[],
- hasAnyPermissionMock: vi.fn(),
- syncConnectorToolsByIdMock: vi.fn(),
-}));
+const { claimMock, connectorInstances, hasAnyPermissionMock, syncConnectorToolsByIdMock } =
+ vi.hoisted(() => ({
+ claimMock: vi.fn(),
+ connectorInstances: [] as any[],
+ hasAnyPermissionMock: vi.fn(),
+ syncConnectorToolsByIdMock: vi.fn(),
+ }));
vi.mock('@/const/rbac', () => ({ ALL_SCOPE: 'all' }));
vi.mock('@lobechat/database', () => ({
@@ -48,6 +50,8 @@ vi.mock('@/database/models/connectorTool', () => ({
}));
vi.mock('@/database/models/connector', () => ({
ConnectorModel: class {
+ create = vi.fn().mockResolvedValue({ id: 'mcp-1' });
+ createUnlessIdentifierHeld = claimMock;
delete = vi.fn();
findById = vi.fn().mockResolvedValue({ id: 'mcp-1', metadata: {} });
findPublicById = vi.fn().mockResolvedValue({
@@ -59,6 +63,8 @@ vi.mock('@/database/models/connector', () => ({
// The row was created by a different workspace member.
userId: 'other-member',
});
+ // A lookup made before a concurrent writer added the identifier
+ queryPublic = vi.fn().mockResolvedValue([]);
update = vi.fn();
constructor() {
connectorInstances.push(this);
@@ -143,3 +149,33 @@ describe('McpServerService row-level manage checks', () => {
},
);
});
+
+describe('McpServerService.createServer', () => {
+ const request = { identifier: 'fetch-mcp', name: 'Fetch', serverUrl: 'https://example.com/mcp' };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ connectorInstances.length = 0;
+ claimMock.mockResolvedValue({ created: { id: 'mcp-1' } });
+ });
+
+ it('claims the identifier under the identifier lock and creates the server', async () => {
+ await expect(
+ new McpServerService({} as LobeChatDatabase, OWNER, WORKSPACE).createServer(request),
+ ).resolves.toMatchObject({ id: 'mcp-1', serverUrl: 'https://example.com/mcp' });
+
+ expect(claimMock.mock.calls).toEqual([[expect.objectContaining({ identifier: 'fetch-mcp' })]]);
+ });
+
+ it('reports an identifier another writer holds as a conflict instead of adding a row', async () => {
+ const service = new McpServerService({} as LobeChatDatabase, OWNER, WORKSPACE);
+ // An Agent Builder install claimed the identifier after any earlier lookup
+ claimMock.mockResolvedValue({ holder: { id: 'installed' } });
+
+ await expect(service.createServer(request)).rejects.toMatchObject({
+ message: 'MCP server identifier already exists',
+ name: 'ConflictError',
+ });
+ expect(connectorInstances.every((it) => it.create.mock.calls.length === 0)).toBe(true);
+ });
+});
diff --git a/packages/openapi/src/services/mcp-server.service.ts b/packages/openapi/src/services/mcp-server.service.ts
index 29069ee49e6..223ac3070e3 100644
--- a/packages/openapi/src/services/mcp-server.service.ts
+++ b/packages/openapi/src/services/mcp-server.service.ts
@@ -99,13 +99,11 @@ export class McpServerService extends BaseService {
async createServer(request: CreateMcpServerRequest): Promise<McpServerResponse> {
const model = await this.getCredentialConnectorModel();
- const existing = (await this.connectorModel.queryPublic()).find(
- (connector) => connector.identifier === request.identifier,
- );
- if (existing) throw this.createConflictError('MCP server identifier already exists');
-
- const created = await model.create({
- agentId: null,
+ // The lookup and the insert are one claim under the identifier lock every
+ // base-row writer takes (an Agent Builder install among them): a lookup
+ // before an unlocked insert would let a concurrent writer add the same
+ // identifier in between, leaving two rows for runtime resolution to choose from.
+ const claim = await model.createUnlessIdentifierHeld({
credentials: request.credentials ? JSON.stringify(request.credentials) : null,
identifier: request.identifier,
isEnabled: request.isEnabled ?? true,
@@ -118,8 +116,9 @@ export class McpServerService extends BaseService {
status: ConnectorStatus.disconnected,
tokenExpiresAt: null,
});
+ if ('holder' in claim) throw this.createConflictError('MCP server identifier already exists');
- const publicRecord = await this.connectorModel.findPublicById(created.id);
+ const publicRecord = await this.connectorModel.findPublicById(claim.created.id);
if (!publicRecord) throw this.createCommonError('Failed to read the created MCP server');
return this.projectServer(publicRecord);
}
diff --git a/src/libs/mcp/cloudManifest.test.ts b/src/libs/mcp/cloudManifest.test.ts
new file mode 100644
index 00000000000..14980f23568
--- /dev/null
+++ b/src/libs/mcp/cloudManifest.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildCloudMcpManifest, cloudManifestTools } from './cloudManifest';
+
+describe('buildCloudMcpManifest', () => {
+ it('keeps the approval an MCP tools-format manifest asks for', () => {
+ const manifest = buildCloudMcpManifest({
+ data: {
+ tools: [
+ { description: 'Search', inputSchema: { type: 'object' }, name: 'search' },
+ { humanIntervention: 'required', name: 'send' },
+ { humanIntervention: 'always', name: 'delete' },
+ ],
+ },
+ plugin: { identifier: 'remote-mcp' },
+ });
+
+ expect(
+ cloudManifestTools(manifest).map(({ humanIntervention, toolName }) => ({
+ humanIntervention,
+ toolName,
+ })),
+ ).toEqual([
+ { humanIntervention: undefined, toolName: 'search' },
+ { humanIntervention: 'required', toolName: 'send' },
+ { humanIntervention: 'always', toolName: 'delete' },
+ ]);
+ expect(manifest.api[0]).toEqual({
+ description: 'Search',
+ name: 'search',
+ parameters: { type: 'object' },
+ });
+ });
+
+ it('takes the tools list when the api list beside it is empty', () => {
+ const manifest = buildCloudMcpManifest({
+ data: { api: [], tools: [{ humanIntervention: 'always', name: 'delete' }] },
+ plugin: { identifier: 'remote-mcp' },
+ });
+
+ expect(manifest.api).toEqual([
+ { description: '', humanIntervention: 'always', name: 'delete', parameters: {} },
+ ]);
+ });
+});
diff --git a/src/store/tool/slices/mcpStore/cloudManifest.ts b/src/libs/mcp/cloudManifest.ts
similarity index 84%
rename from src/store/tool/slices/mcpStore/cloudManifest.ts
rename to src/libs/mcp/cloudManifest.ts
index c5183d1e9f6..2877fe28f36 100644
--- a/src/store/tool/slices/mcpStore/cloudManifest.ts
+++ b/src/libs/mcp/cloudManifest.ts
@@ -1,7 +1,7 @@
import type { ToolManifest } from '@lobechat/types';
import debug from 'debug';
-const log = debug('lobe-mcp:store:cloudManifest');
+const log = debug('lobe-mcp:cloudManifest');
/**
* Build manifest for cloud MCP connection from market data
@@ -23,14 +23,19 @@ export const buildCloudMcpManifest = (params: {
// LobeChat: { name, description, parameters }
let apiArray: any[] = [];
- if (lobeChatApi) {
+ // An empty `api` next to a populated `tools` list is no tool list of its own
+ if (Array.isArray(lobeChatApi) && lobeChatApi.length > 0) {
// Already in LobeChat format, use directly
apiArray = lobeChatApi;
log('[Cloud MCP] Using existing LobeChat API format');
} else if (mcpTools && Array.isArray(mcpTools)) {
- // Convert MCP tools format to LobeChat api format
+ // Convert MCP tools format to LobeChat api format. The approval a tool
+ // asks for carries over, as it does from the LobeChat format.
apiArray = mcpTools.map((tool: any) => ({
description: tool.description || '',
+ ...(tool.humanIntervention === undefined
+ ? {}
+ : { humanIntervention: tool.humanIntervention }),
name: tool.name,
parameters: tool.inputSchema || {},
}));
diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.ts
index c7d79cd8eff..36ca859cd02 100644
--- a/src/store/tool/slices/connector/action.ts
+++ b/src/store/tool/slices/connector/action.ts
@@ -8,6 +8,7 @@ import type { SWRResponse } from 'swr';
import type { ConnectorToolPermission } from '@/database/schemas';
import { runsOnAnotherDevice } from '@/helpers/mcpDeviceBinding';
+import { buildCloudMcpManifest, cloudManifestTools } from '@/libs/mcp/cloudManifest';
import { resolveLocalConnectorHttpParams } from '@/libs/mcp/localConnector';
import {
cacheScope,
@@ -24,7 +25,6 @@ import type { StoreSetter } from '@/store/types';
import { ConnectorOAuthError, waitForConnectorOAuth } from '@/utils/connectorOAuth';
import type { ToolStore } from '../../store';
-import { buildCloudMcpManifest, cloudManifestTools } from '../mcpStore/cloudManifest';
import {
agentBoundConnectorsEntity,
agentBoundConnectorsResource,
diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.ts
index 48c722fed82..bd5095b7171 100644
--- a/src/store/tool/slices/mcpStore/action.ts
+++ b/src/store/tool/slices/mcpStore/action.ts
@@ -7,6 +7,7 @@ import { omit } from 'es-toolkit/compat';
import { produce } from 'immer';
import { gt, valid } from 'semver';
+import { buildCloudMcpManifest } from '@/libs/mcp/cloudManifest';
import { type MCPErrorData } from '@/libs/mcp/types';
import { parseStdioErrorMessage } from '@/libs/mcp/types';
import { renderMcpArgs, renderMcpUrlTemplate } from '@/libs/mcp/urlTemplate';
@@ -40,7 +41,6 @@ import {
restoreConnector,
snapshotReplacedConnector,
} from '../connector/replaceConnector';
-import { buildCloudMcpManifest } from './cloudManifest';
import { type MCPPluginListData, type MCPStoreState } from './initialState';
import { installMarketplaceConnector } from './installMarketplaceConnector';
import { installOAuthPlugin } from './installOAuthPlugin';
diff --git a/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts b/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts
index c038b322817..87cd713d789 100644
--- a/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts
+++ b/src/store/tool/slices/mcpStore/installMarketplaceConnector.ts
@@ -2,6 +2,7 @@ import { MARKETPLACE_INSTALL_COMPLETED_KEY } from '@lobechat/const';
import type { ToolManifest } from '@lobechat/types';
import debug from 'debug';
+import { cloudManifestTools } from '@/libs/mcp/cloudManifest';
import { lambdaClient } from '@/libs/trpc/client';
import {
type ConnectorSnapshot,
@@ -11,8 +12,6 @@ import {
import { connectorSelectors } from '@/store/tool/slices/connector/selectors';
import type { ToolStore } from '@/store/tool/store';
-import { cloudManifestTools } from './cloudManifest';
-
const log = debug('lobe-mcp:store:installMarketplaceConnector');
type CreateConnectorPayload = Parameters<ToolStore['createConnector']>[0];