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.

✨ feat(mcp): bind a stdio / intranet MCP server to one device (#23067)

Bryanc68faea0ce1b
diff --git a/apps/server/src/routers/lambda/__tests__/connector.update.test.ts b/apps/server/src/routers/lambda/__tests__/connector.update.test.ts
index 4eaa26ee616..368e1cf776c 100644
--- a/apps/server/src/routers/lambda/__tests__/connector.update.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/connector.update.test.ts
@@ -9,6 +9,12 @@ vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+const findPersonalByDeviceId = vi.hoisted(() => vi.fn());
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn(function DeviceModel() {
+ return { findPersonalByDeviceId, findWorkspaceDeviceById: vi.fn() };
+ }),
+}));
vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
}));
@@ -85,4 +91,22 @@ describe('connectorRouter.update', () => {
expect(connectorModelMock.update.mock.calls[0][1]).not.toHaveProperty('status');
});
+
+ it("binds one of the caller's own devices, and refuses any other", async () => {
+ findPersonalByDeviceId.mockImplementation(async (id: string) =>
+ id === 'my-laptop' ? { deviceId: id } : undefined,
+ );
+
+ await update({ metadata: { boundDeviceId: 'my-laptop' } });
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ CONNECTOR_ID,
+ expect.objectContaining({ metadata: { boundDeviceId: 'my-laptop' } }),
+ );
+
+ connectorModelMock.update.mockClear();
+ await expect(update({ metadata: { boundDeviceId: 'not-mine' } })).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.test.ts b/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.test.ts
new file mode 100644
index 00000000000..6f3273bcd36
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.test.ts
@@ -0,0 +1,128 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ assertBoundDeviceOperable,
+ assertConnectorDeviceBindingAllowed,
+} from './connectorDeviceBinding';
+
+const findWorkspaceDeviceById = vi.hoisted(() => vi.fn());
+const findPersonalByDeviceId = vi.hoisted(() => vi.fn());
+const DeviceModel = vi.hoisted(() =>
+ vi.fn(function DeviceModel() {
+ return { findPersonalByDeviceId, findWorkspaceDeviceById };
+ }),
+);
+vi.mock('@/database/models/device', () => ({ DeviceModel }));
+
+const serverDB = {} as never;
+const personal = { serverDB, userId: 'u1' };
+const workspace = { serverDB, userId: 'u1', workspaceId: 'ws1' };
+
+describe('assertConnectorDeviceBindingAllowed', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('allows a personal connector to bind one of the caller’s personal devices', async () => {
+ findPersonalByDeviceId.mockResolvedValue({ deviceId: 'laptop' });
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(personal, { boundDeviceId: 'laptop' }),
+ ).resolves.toBeUndefined();
+ expect(DeviceModel).toHaveBeenCalledWith(serverDB, 'u1');
+ expect(findPersonalByDeviceId).toHaveBeenCalledWith('laptop');
+ });
+
+ it('refuses a personal connector a device that is not the caller’s', async () => {
+ findPersonalByDeviceId.mockResolvedValue(undefined);
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(personal, { boundDeviceId: 'someone-else' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('allows a workspace connector to bind a public device of its workspace', async () => {
+ findWorkspaceDeviceById.mockResolvedValue({ deviceId: 'ws-nas', visibility: 'public' });
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, { boundDeviceId: 'ws-nas' }),
+ ).resolves.toBeUndefined();
+ expect(DeviceModel).toHaveBeenCalledWith(serverDB, 'u1', 'ws1');
+ });
+
+ // Only the member who enrolled a private device can reach it, while every
+ // member's runs use a workspace connector
+ it('refuses a workspace connector a private device, even the caller’s own', async () => {
+ findWorkspaceDeviceById.mockResolvedValue({ deviceId: 'my-private', visibility: 'private' });
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, { boundDeviceId: 'my-private' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('refuses a workspace connector a device outside the workspace', async () => {
+ findWorkspaceDeviceById.mockResolvedValue(undefined);
+
+ await expect(
+ assertConnectorDeviceBindingAllowed(workspace, { boundDeviceId: 'personal-laptop' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('skips writes without a binding, and a binding the write keeps unchanged', async () => {
+ await assertConnectorDeviceBindingAllowed(workspace, { description: 'x' });
+ await assertConnectorDeviceBindingAllowed(workspace, undefined);
+ await assertConnectorDeviceBindingAllowed(
+ workspace,
+ { boundDeviceId: 'unshared-since' },
+ { boundDeviceId: 'unshared-since' },
+ );
+
+ expect(DeviceModel).not.toHaveBeenCalled();
+ });
+
+ it('refuses a malformed binding', async () => {
+ await expect(
+ assertConnectorDeviceBindingAllowed(personal, { boundDeviceId: 42 }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+});
+
+describe('assertBoundDeviceOperable', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ const publicDevice = { deviceId: 'ws-nas', userId: 'enroller', visibility: 'public' };
+
+ it('lets a member run an MCP server on a public workspace device', async () => {
+ findWorkspaceDeviceById.mockResolvedValue(publicDevice);
+
+ await expect(
+ assertBoundDeviceOperable({ ...workspace, workspaceRole: 'member' }, 'ws-nas'),
+ ).resolves.toBeUndefined();
+ });
+
+ // A connection test starts the stdio command on that machine
+ it('refuses a workspace viewer, even on a public device', async () => {
+ findWorkspaceDeviceById.mockResolvedValue(publicDevice);
+
+ await expect(
+ assertBoundDeviceOperable({ ...workspace, workspaceRole: 'viewer' }, 'ws-nas'),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it("refuses another member's private device", async () => {
+ findWorkspaceDeviceById.mockResolvedValue({ ...publicDevice, visibility: 'private' });
+
+ await expect(
+ assertBoundDeviceOperable({ ...workspace, workspaceRole: 'member' }, 'ws-nas'),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('needs no check without a binding or for a personal binding', async () => {
+ await assertBoundDeviceOperable({ ...workspace, workspaceRole: 'viewer' }, undefined);
+ await assertBoundDeviceOperable(personal, 'my-laptop');
+
+ expect(DeviceModel).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.ts b/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.ts
new file mode 100644
index 00000000000..c1b7d0a4860
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/connectorDeviceBinding.ts
@@ -0,0 +1,90 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { TRPCError } from '@trpc/server';
+
+import type { WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { DeviceModel } from '@/database/models/device';
+
+import { canOperateWorkspaceDevice } from '../deviceWorkspaceGuard';
+
+interface DeviceBindingCtx {
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+ workspaceRole?: WorkspaceRole;
+}
+
+/**
+ * Whether a connector write may bind the connector to the device its metadata
+ * names (`metadata.boundDeviceId`). A binding pins every call to that device,
+ * so it must be one the connector's every runner can reach:
+ *
+ * - personal connector (no `workspaceId`): one of the caller's personal
+ * devices — its runs only ever reach the owner's own pool;
+ * - workspace connector: a PUBLIC device of that workspace. A private
+ * enrollment resolves only for the member who enrolled it, so other
+ * members' runs could never reach it.
+ *
+ * A binding the write keeps unchanged is not checked again: the device may
+ * have been unshared since, and an unrelated edit must not fail on it (its
+ * calls already fail with the reason).
+ *
+ * Throws `BAD_REQUEST` for a binding outside those devices.
+ */
+export const assertConnectorDeviceBindingAllowed = async (
+ ctx: DeviceBindingCtx,
+ metadata: Record<string, unknown> | null | undefined,
+ previousMetadata?: Record<string, unknown> | null,
+): Promise<void> => {
+ const deviceId = metadata?.boundDeviceId;
+ if (deviceId === undefined || deviceId === previousMetadata?.boundDeviceId) return;
+ if (typeof deviceId !== 'string' || !deviceId) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid bound device' });
+ }
+
+ const allowed = ctx.workspaceId
+ ? (
+ await new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId).findWorkspaceDeviceById(
+ deviceId,
+ )
+ )?.visibility === 'public'
+ : !!(await new DeviceModel(ctx.serverDB, ctx.userId).findPersonalByDeviceId(deviceId));
+
+ if (!allowed) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: ctx.workspaceId
+ ? 'A workspace MCP server can only be bound to a shared (public) device of this workspace.'
+ : 'An MCP server can only be bound to one of your own devices.',
+ });
+ }
+};
+
+/**
+ * Whether the caller may run an MCP server on a bound device right now (a
+ * connection test starts its stdio command or reaches its network there). In
+ * a workspace that is operating the machine, so the device guard's rule
+ * applies: any member on a public device, never a viewer, and a private one
+ * only for its enroller or an owner. A personal binding only ever reaches the
+ * caller's own devices (the gateway pool is per user), so it needs no check.
+ *
+ * Throws `NOT_FOUND` for a device outside the workspace, `FORBIDDEN` otherwise.
+ */
+export const assertBoundDeviceOperable = async (
+ ctx: DeviceBindingCtx,
+ deviceId: string | undefined,
+): Promise<void> => {
+ if (!deviceId || !ctx.workspaceId) return;
+
+ const row = await new DeviceModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).findWorkspaceDeviceById(deviceId);
+ if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });
+ if (!canOperateWorkspaceDevice(ctx.workspaceRole, ctx.userId, row)) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'You cannot run an MCP server on this workspace device.',
+ });
+ }
+};
diff --git a/apps/server/src/routers/lambda/connector.syncTools.test.ts b/apps/server/src/routers/lambda/connector.syncTools.test.ts
index 117ac6d2db0..60b78f2e9eb 100644
--- a/apps/server/src/routers/lambda/connector.syncTools.test.ts
+++ b/apps/server/src/routers/lambda/connector.syncTools.test.ts
@@ -6,6 +6,7 @@ import superjson from 'superjson';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ConnectorModel } from '@/database/models/connector';
+import { McpBoundDeviceUnavailableError } from '@/server/services/mcp/deviceTunnel';
import { connectorRouter } from './connector';
@@ -118,6 +119,14 @@ describe('connectorRouter.syncTools', () => {
});
});
+ it('reports a bound device that cannot list the tools as a precondition, naming it', async () => {
+ sync.mockRejectedValue(new McpBoundDeviceUnavailableError('nas', 'offline', 'devbox-b'));
+ await expect(caller().syncTools({ id })).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ message: expect.stringContaining('"devbox-b", which is offline'),
+ });
+ });
+
it('still wraps unexpected upstream failures', async () => {
sync.mockRejectedValue(new Error('connection reset'));
await expect(caller().syncTools({ id })).rejects.toMatchObject({
diff --git a/apps/server/src/routers/lambda/connector/agentScope.ts b/apps/server/src/routers/lambda/connector/agentScope.ts
new file mode 100644
index 00000000000..b33ca89fbc5
--- /dev/null
+++ b/apps/server/src/routers/lambda/connector/agentScope.ts
@@ -0,0 +1,177 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { AgentModel } from '@/database/models/agent';
+import { router } from '@/libs/trpc/lambda';
+
+import { assertConnectorCredentialsManageable } from '../_helpers/connectorManagePolicy';
+import { connectorWriteProcedure } from './procedures';
+
+/**
+ * Moving a connector in and out of an agent's scope: bind / unbind (transfer
+ * the row), copy (an independent agent-owned clone) and mount / unmount (a
+ * reference lock on a user-owned row). Every write here re-routes a
+ * connector's credentials, so each is creator/owner only.
+ */
+export const connectorAgentScopeRouter = router({
+ /**
+ * Bind an existing connector to an agent (transfer it into the agent scope).
+ * The connector then resolves only for that agent's runs and shadows the
+ * user's base connector of the same identifier (Agent > Workspace/Personal).
+ *
+ * Guards: the caller must be able to edit the agent; the agent must not
+ * already have a connector for this identifier (one per identifier per agent).
+ */
+ bindAgent: connectorWriteProcedure
+ .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))
+ .mutation(async ({ input, ctx }) => {
+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+ if (!(await agentModel.existsOwnedById(input.agentId))) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });
+ }
+
+ const connector = await ctx.connectorModel.findById(input.connectorId);
+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ // Rebinding routes the connector's credentials to the agent — creator/owner only.
+ await assertConnectorCredentialsManageable(ctx, connector);
+
+ const existingAgentRow = await ctx.connectorModel.findScopedByIdentifier(
+ connector.identifier,
+ input.agentId,
+ );
+ if (existingAgentRow && existingAgentRow.id !== connector.id) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `Agent already has a "${connector.identifier}" connector`,
+ });
+ }
+
+ await ctx.connectorModel.update(input.connectorId, { agentId: input.agentId });
+ return { id: input.connectorId };
+ }),
+
+ /**
+ * Unbind a connector from its agent, returning it to the personal/workspace
+ * scope. Rejected when a base connector of the same identifier already exists,
+ * to keep the base scope single-per-identifier — the caller should delete the
+ * agent connector instead of demoting it into a collision.
+ */
+ unbindAgent: connectorWriteProcedure
+ .input(z.object({ connectorId: z.string().uuid() }))
+ .mutation(async ({ input, ctx }) => {
+ const connector = await ctx.connectorModel.findById(input.connectorId);
+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ 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) {
+ 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 };
+ }),
+
+ /**
+ * "Copy user tool": clone a user connector into an independent agent-owned
+ * row (own credentials, separately editable). Server-side because the
+ * credentials ciphertext never reaches the client (see ConnectorModel).
+ */
+ copyToAgent: connectorWriteProcedure
+ .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))
+ .mutation(async ({ input, ctx }) => {
+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+ if (!(await agentModel.existsOwnedById(input.agentId))) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });
+ }
+
+ const source = await ctx.connectorModel.findById(input.connectorId);
+ if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ // Cloning duplicates the source's encrypted credentials into a row the
+ // agent owner controls — creator/owner only.
+ await assertConnectorCredentialsManageable(ctx, source);
+
+ const existing = await ctx.connectorModel.findScopedByIdentifier(
+ source.identifier,
+ input.agentId,
+ );
+ if (existing) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `Agent already has a "${source.identifier}" connector`,
+ });
+ }
+
+ const created = await ctx.connectorModel.copyToAgent(input.connectorId, input.agentId);
+ if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ return { id: created.id };
+ }),
+
+ /**
+ * "Mount user tool" (Linked): reference-lock a user connector onto this agent.
+ * The row stays user-owned (keeps syncing with the user's edits) but resolves
+ * for this agent and is locked so no other agent can mount the same one.
+ */
+ mountToAgent: connectorWriteProcedure
+ .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))
+ .mutation(async ({ input, ctx }) => {
+ const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+ if (!(await agentModel.existsOwnedById(input.agentId))) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });
+ }
+
+ const connector = await ctx.connectorModel.findById(input.connectorId);
+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ // Mounting routes the source's credentials to the agent and locks the
+ // row (metadata.mountedByAgentId) — creator/owner only.
+ await assertConnectorCredentialsManageable(ctx, connector);
+ if (connector.agentId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Only a user connector can be mounted (this one is already agent-owned)',
+ });
+ }
+
+ const lockedBy = connector.metadata?.mountedByAgentId;
+ if (lockedBy && lockedBy !== input.agentId) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'Connector is already mounted by another agent',
+ });
+ }
+
+ const existing = await ctx.connectorModel.findScopedByIdentifier(
+ connector.identifier,
+ input.agentId,
+ );
+ if (existing) {
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `Agent already has a "${connector.identifier}" connector`,
+ });
+ }
+
+ await ctx.connectorModel.update(input.connectorId, {
+ metadata: { ...connector.metadata, mountedByAgentId: input.agentId },
+ });
+ return { id: input.connectorId };
+ }),
+
+ /** Unmount a connector from its agent (clears the reference lock). */
+ unmountFromAgent: connectorWriteProcedure
+ .input(z.object({ connectorId: z.string().uuid() }))
+ .mutation(async ({ input, ctx }) => {
+ const connector = await ctx.connectorModel.findById(input.connectorId);
+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ // Clearing the mount lock mutates the source row — creator/owner only.
+ await assertConnectorCredentialsManageable(ctx, connector);
+
+ const { mountedByAgentId: _drop, ...restMeta } = connector.metadata ?? {};
+ await ctx.connectorModel.update(input.connectorId, { metadata: restMeta });
+ return { id: input.connectorId };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector/index.ts
similarity index 79%
rename from apps/server/src/routers/lambda/connector.ts
rename to apps/server/src/routers/lambda/connector/index.ts
index 2a3e7a127bd..e9a62377475 100644
--- a/apps/server/src/routers/lambda/connector.ts
+++ b/apps/server/src/routers/lambda/connector/index.ts
@@ -1,7 +1,9 @@
+import { builtinTools } from '@lobechat/builtin-tools';
import { getComposioAppByIdentifier, hasCallableMcpEndpoint } from '@lobechat/const';
import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';
-import { GetStreamableMcpServerManifestInputSchema, upsertPluginMode } from '@lobechat/types';
+import { upsertPluginMode } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
+import pMap from 'p-map';
import { z } from 'zod';
import {
@@ -9,13 +11,10 @@ import {
wsCompatProcedure,
} from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentModel } from '@/database/models/agent';
-import { ConnectorModel } from '@/database/models/connector';
import {
EvalConnectorUpdateError,
withoutEvalConnectorMarker,
} from '@/database/models/connectorEval';
-import { ConnectorToolModel } from '@/database/models/connectorTool';
-import { PluginModel } from '@/database/models/plugin';
import { WorkspaceModel } from '@/database/models/workspace';
import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';
import type { OIDCConfig } from '@/database/schemas';
@@ -27,9 +26,8 @@ import {
} from '@/database/schemas';
import { getComposioClient } from '@/libs/composio';
import { getMCPConnectionErrorType, inferCrudType } from '@/libs/mcp/utils';
-import { router } from '@/libs/trpc/lambda';
+import { mergeRouters, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import {
callConnectorToolById,
ConnectorToolCallError,
@@ -52,44 +50,41 @@ import {
pruneMissingAutoConnectorTools,
syncConnectorToolsById,
} from '@/server/services/connector/sync';
-import { getDeviceMcpManifest } from '@/server/services/mcp/deviceManifest';
+import {
+ DeviceMcpManifestInputSchema,
+ getDeviceMcpManifest,
+} from '@/server/services/mcp/deviceManifest';
+import {
+ McpBoundDeviceUnavailableError,
+ McpDeviceUnavailableError,
+} from '@/server/services/mcp/deviceTunnel';
import {
resolveConnectorAuthorizerId,
resolveUserDisplayMap,
withTrustedLinkedByUserId,
} from '@/server/utils/connectorAttribution';
-import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
-import { toClientToolSyncInputs } from './_helpers/clientToolSyncInputs';
-import { withRequestConnectorCallers } from './_helpers/connectorCallContext';
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import { toClientToolSyncInputs } from '../_helpers/clientToolSyncInputs';
+import { withRequestConnectorCallers } from '../_helpers/connectorCallContext';
+import {
+ assertBoundDeviceOperable,
+ assertConnectorDeviceBindingAllowed,
+} from '../_helpers/connectorDeviceBinding';
import {
assertConnectorCredentialsManageable,
assertConnectorMaintainable,
canManageWorkspaceConnectors,
getConnectorMemberManage,
isWorkspaceConnectorAdmin,
-} from './_helpers/connectorManagePolicy';
-import { resolveDefaultPermission } from './_helpers/connectorToolPermission';
-import { upsertConnectorEntry } from './_helpers/upsertConnectorEntry';
-
-const connectorProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
- // Credentials (OAuth tokens) are encrypted at rest — give the model a gatekeeper.
- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
- const wsId = ctx.workspaceId ?? undefined;
- return opts.next({
- ctx: {
- agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
- connectorModel: new ConnectorModel(ctx.serverDB, ctx.userId, wsId, gateKeeper),
- connectorToolModel: new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId),
- pluginModel: new PluginModel(ctx.serverDB, ctx.userId, wsId),
- },
- });
-});
+} from '../_helpers/connectorManagePolicy';
+import { resolveDefaultPermission } from '../_helpers/connectorToolPermission';
+import { upsertConnectorEntry } from '../_helpers/upsertConnectorEntry';
+import { connectorAgentScopeRouter } from './agentScope';
+import { connectorProcedure, connectorWriteProcedure } from './procedures';
-// Writes: workspace mode requires at least the member role, gating viewers
-// out (read-only role) while personal mode passes through unrestricted.
-const connectorWriteProcedure = connectorProcedure.use(requireWorkspaceRoleWhenScoped('member'));
+/** Per-connector DB reads and writes a request runs at once, however many rows it covers. */
+const DB_CONCURRENCY = 5;
const oidcConfigSchema = z.object({
authorizationEndpoint: z.string().optional(),
@@ -151,7 +146,7 @@ const createConnectorSchema = z.object({
]),
});
-export const connectorRouter = router({
+const connectorCoreRouter = router({
// ── Queries ──────────────────────────────────────────────────────────────
list: connectorProcedure.query(async ({ ctx }) => {
@@ -165,8 +160,9 @@ export const connectorRouter = router({
connectors.map((c) => resolveConnectorAuthorizerId(c)),
);
- const toolsByConnector = await Promise.all(
- connectors.map(async (c) => {
+ const toolsByConnector = await pMap(
+ connectors,
+ async (c) => {
const tools = await ctx.connectorToolModel.queryByConnector(c.id);
// Never ship decrypted OAuth tokens or the client secret to the browser.
const { credentials: _credentials, oidcConfig, ...rest } = c;
@@ -179,7 +175,8 @@ export const connectorRouter = router({
oidcConfig: safeOidcConfig,
tools,
};
- }),
+ },
+ { concurrency: DB_CONCURRENCY },
);
return toolsByConnector;
@@ -202,8 +199,9 @@ export const connectorRouter = router({
connectors.map((c) => resolveConnectorAuthorizerId(c)),
);
- return Promise.all(
- connectors.map(async (c) => {
+ return pMap(
+ connectors,
+ async (c) => {
const tools = await ctx.connectorToolModel.queryByConnector(c.id);
const { credentials: _credentials, oidcConfig, ...rest } = c;
const safeOidcConfig = oidcConfig
@@ -217,7 +215,8 @@ export const connectorRouter = router({
oidcConfig: safeOidcConfig,
tools,
};
- }),
+ },
+ { concurrency: DB_CONCURRENCY },
);
}),
@@ -249,25 +248,23 @@ export const connectorRouter = router({
const agentMetas = agentIds.length > 0 ? await agentModel.getAgentAvatarsByIds(agentIds) : [];
const agentMetaById = new Map(agentMetas.map((m) => [m.id, m]));
- return Promise.all(
- connectors
- .filter((c) => !!c.agentId && agentMetaById.has(c.agentId))
- .map(async (c) => {
- const tools = await ctx.connectorToolModel.queryByConnector(c.id);
- const { credentials: _credentials, oidcConfig, ...rest } = c;
- const safeOidcConfig = oidcConfig
- ? { ...oidcConfig, clientSecret: undefined }
- : oidcConfig;
- const meta = agentMetaById.get(c.agentId!);
- return {
- ...rest,
- agentAvatar: meta?.avatar ?? null,
- agentName: meta?.name ?? null,
- agentTitle: meta?.title ?? null,
- oidcConfig: safeOidcConfig,
- tools,
- };
- }),
+ return pMap(
+ connectors.filter((c) => !!c.agentId && agentMetaById.has(c.agentId)),
+ async (c) => {
+ const tools = await ctx.connectorToolModel.queryByConnector(c.id);
+ const { credentials: _credentials, oidcConfig, ...rest } = c;
+ const safeOidcConfig = oidcConfig ? { ...oidcConfig, clientSecret: undefined } : oidcConfig;
+ const meta = agentMetaById.get(c.agentId!);
+ return {
+ ...rest,
+ agentAvatar: meta?.avatar ?? null,
+ agentName: meta?.name ?? null,
+ agentTitle: meta?.title ?? null,
+ oidcConfig: safeOidcConfig,
+ tools,
+ };
+ },
+ { concurrency: DB_CONCURRENCY },
);
}),
@@ -310,16 +307,25 @@ export const connectorRouter = router({
.mutation(({ ctx, input }) => getConnectorLocalCallToken(ctx, input.id)),
/**
- * Test an HTTP MCP server the user set to connect through their device: its
- * manifest, read on their own desktop app. A mutation so the credentials
- * travel in the body, not the URL.
+ * Test an MCP server that runs on the user's device (an HTTP server set to
+ * connect through it, or one bound to a device): its manifest, read on the
+ * device its calls will run on. A mutation so the credentials travel in the
+ * body, not the URL.
*/
getDeviceMcpManifest: wsCompatProcedure
.use(serverDatabase)
- .input(GetStreamableMcpServerManifestInputSchema)
- .mutation(({ ctx, input }) =>
- getDeviceMcpManifest({ connection: input, serverDB: ctx.serverDB, userId: ctx.userId }),
- ),
+ // Starts the server on a device: read-only viewers never operate one
+ .use(requireWorkspaceRoleWhenScoped('member'))
+ .input(DeviceMcpManifestInputSchema)
+ .mutation(async ({ ctx, input }) => {
+ await assertBoundDeviceOperable(ctx, input.boundDeviceId);
+ return getDeviceMcpManifest({
+ connection: input,
+ serverDB: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ }),
/**
* The exact redirect URI the server will send to the OAuth/DCR endpoints.
@@ -435,6 +441,7 @@ export const connectorRouter = router({
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,
@@ -460,167 +467,6 @@ export const connectorRouter = router({
return { id: created.id, isNew: true };
}),
- /**
- * Bind an existing connector to an agent (transfer it into the agent scope).
- * The connector then resolves only for that agent's runs and shadows the
- * user's base connector of the same identifier (Agent > Workspace/Personal).
- *
- * Guards: the caller must be able to edit the agent; the agent must not
- * already have a connector for this identifier (one per identifier per agent).
- */
- bindAgent: connectorWriteProcedure
- .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))
- .mutation(async ({ input, ctx }) => {
- const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
- if (!(await agentModel.existsOwnedById(input.agentId))) {
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });
- }
-
- const connector = await ctx.connectorModel.findById(input.connectorId);
- if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
- // Rebinding routes the connector's credentials to the agent — creator/owner only.
- await assertConnectorCredentialsManageable(ctx, connector);
-
- const existingAgentRow = await ctx.connectorModel.findScopedByIdentifier(
- connector.identifier,
- input.agentId,
- );
- if (existingAgentRow && existingAgentRow.id !== connector.id) {
- throw new TRPCError({
- code: 'CONFLICT',
- message: `Agent already has a "${connector.identifier}" connector`,
- });
- }
-
- await ctx.connectorModel.update(input.connectorId, { agentId: input.agentId });
- return { id: input.connectorId };
- }),
-
- /**
- * Unbind a connector from its agent, returning it to the personal/workspace
- * scope. Rejected when a base connector of the same identifier already exists,
- * to keep the base scope single-per-identifier — the caller should delete the
- * agent connector instead of demoting it into a collision.
- */
- unbindAgent: connectorWriteProcedure
- .input(z.object({ connectorId: z.string().uuid() }))
- .mutation(async ({ input, ctx }) => {
- const connector = await ctx.connectorModel.findById(input.connectorId);
- if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
- 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) {
- 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 };
- }),
-
- /**
- * "Copy user tool": clone a user connector into an independent agent-owned
- * row (own credentials, separately editable). Server-side because the
- * credentials ciphertext never reaches the client (see ConnectorModel).
- */
- copyToAgent: connectorWriteProcedure
- .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))
- .mutation(async ({ input, ctx }) => {
- const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
- if (!(await agentModel.existsOwnedById(input.agentId))) {
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });
- }
-
- const source = await ctx.connectorModel.findById(input.connectorId);
- if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
- // Cloning duplicates the source's encrypted credentials into a row the
- // agent owner controls — creator/owner only.
- await assertConnectorCredentialsManageable(ctx, source);
-
- const existing = await ctx.connectorModel.findScopedByIdentifier(
- source.identifier,
- input.agentId,
- );
- if (existing) {
- throw new TRPCError({
- code: 'CONFLICT',
- message: `Agent already has a "${source.identifier}" connector`,
- });
- }
-
- const created = await ctx.connectorModel.copyToAgent(input.connectorId, input.agentId);
- if (!created) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
- return { id: created.id };
- }),
-
- /**
- * "Mount user tool" (Linked): reference-lock a user connector onto this agent.
- * The row stays user-owned (keeps syncing with the user's edits) but resolves
- * for this agent and is locked so no other agent can mount the same one.
- */
- mountToAgent: connectorWriteProcedure
- .input(z.object({ agentId: z.string(), connectorId: z.string().uuid() }))
- .mutation(async ({ input, ctx }) => {
- const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
- if (!(await agentModel.existsOwnedById(input.agentId))) {
- throw new TRPCError({ code: 'FORBIDDEN', message: 'Agent not found or not editable' });
- }
-
- const connector = await ctx.connectorModel.findById(input.connectorId);
- if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
- // Mounting routes the source's credentials to the agent and locks the
- // row (metadata.mountedByAgentId) — creator/owner only.
- await assertConnectorCredentialsManageable(ctx, connector);
- if (connector.agentId) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Only a user connector can be mounted (this one is already agent-owned)',
- });
- }
-
- const lockedBy = connector.metadata?.mountedByAgentId;
- if (lockedBy && lockedBy !== input.agentId) {
- throw new TRPCError({
- code: 'CONFLICT',
- message: 'Connector is already mounted by another agent',
- });
- }
-
- const existing = await ctx.connectorModel.findScopedByIdentifier(
- connector.identifier,
- input.agentId,
- );
- if (existing) {
- throw new TRPCError({
- code: 'CONFLICT',
- message: `Agent already has a "${connector.identifier}" connector`,
- });
- }
-
- await ctx.connectorModel.update(input.connectorId, {
- metadata: { ...connector.metadata, mountedByAgentId: input.agentId },
- });
- return { id: input.connectorId };
- }),
-
- /** Unmount a connector from its agent (clears the reference lock). */
- unmountFromAgent: connectorWriteProcedure
- .input(z.object({ connectorId: z.string().uuid() }))
- .mutation(async ({ input, ctx }) => {
- const connector = await ctx.connectorModel.findById(input.connectorId);
- if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
- // Clearing the mount lock mutates the source row — creator/owner only.
- await assertConnectorCredentialsManageable(ctx, connector);
-
- const { mountedByAgentId: _drop, ...restMeta } = connector.metadata ?? {};
- await ctx.connectorModel.update(input.connectorId, { metadata: restMeta });
- return { id: input.connectorId };
- }),
-
/**
* Begin the OAuth authorization-code flow for a custom MCP connector.
*
@@ -752,6 +598,7 @@ export const connectorRouter = router({
// A patch may keep the stored credentials while repointing the server
// URL, which would send them elsewhere — creator/owner only.
await assertConnectorCredentialsManageable(ctx, target);
+ await assertConnectorDeviceBindingAllowed(ctx, input.patch.metadata, target.metadata);
const { credentials, ...patch } = input.patch;
// Preserve the server-owned `composio.linkedByUserId` from the stored row
@@ -858,6 +705,13 @@ export const connectorRouter = router({
} catch (err: any) {
// Keep actionable rejections and their structured reason for the client.
if (err instanceof TRPCError) throw err;
+ // No device can list it now (the bound one offline or gone, none
+ // online): a precondition the user fixes, with the reason as written
+ if (
+ err instanceof McpBoundDeviceUnavailableError ||
+ err instanceof McpDeviceUnavailableError
+ )
+ throw new TRPCError({ cause: err, code: 'PRECONDITION_FAILED', message: err.message });
throw new TRPCError({
cause: err,
code: 'INTERNAL_SERVER_ERROR',
@@ -940,10 +794,10 @@ export const connectorRouter = router({
await assertConnectorMaintainable(ctx, target);
const tools = await ctx.connectorToolModel.queryByConnector(input.id);
- await Promise.all(
- tools.map((t) =>
- ctx.connectorToolModel.updatePermission(t.id, ConnectorToolPermission.auto),
- ),
+ await pMap(
+ tools,
+ (t) => ctx.connectorToolModel.updatePermission(t.id, ConnectorToolPermission.auto),
+ { concurrency: DB_CONCURRENCY },
);
return { toolCount: tools.length };
}),
@@ -1081,7 +935,6 @@ export const connectorRouter = router({
syncBuiltinTool: connectorProcedure
.input(z.object({ identifier: z.string().min(1) }))
.mutation(async ({ input, ctx }) => {
- const { builtinTools } = await import('@lobechat/builtin-tools');
const tool = builtinTools.find((t) => t.identifier === input.identifier);
if (!tool) {
@@ -1196,3 +1049,5 @@ export const connectorRouter = router({
return { connectorId, toolCount: syncInputs.length };
}),
});
+
+export const connectorRouter = mergeRouters(connectorCoreRouter, connectorAgentScopeRouter);
diff --git a/apps/server/src/routers/lambda/connector/procedures.ts b/apps/server/src/routers/lambda/connector/procedures.ts
new file mode 100644
index 00000000000..7682a7619b3
--- /dev/null
+++ b/apps/server/src/routers/lambda/connector/procedures.ts
@@ -0,0 +1,31 @@
+import {
+ requireWorkspaceRoleWhenScoped,
+ wsCompatProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentModel } from '@/database/models/agent';
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { PluginModel } from '@/database/models/plugin';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+
+export const connectorProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ // Credentials (OAuth tokens) are encrypted at rest — give the model a gatekeeper.
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const wsId = ctx.workspaceId ?? undefined;
+ return opts.next({
+ ctx: {
+ agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
+ connectorModel: new ConnectorModel(ctx.serverDB, ctx.userId, wsId, gateKeeper),
+ connectorToolModel: new ConnectorToolModel(ctx.serverDB, ctx.userId, wsId),
+ pluginModel: new PluginModel(ctx.serverDB, ctx.userId, wsId),
+ },
+ });
+});
+
+// Writes: workspace mode requires at least the member role, gating viewers
+// out (read-only role) while personal mode passes through unrestricted.
+export const connectorWriteProcedure = connectorProcedure.use(
+ requireWorkspaceRoleWhenScoped('member'),
+);
diff --git a/apps/server/src/services/connector/exec.boundDevice.test.ts b/apps/server/src/services/connector/exec.boundDevice.test.ts
new file mode 100644
index 00000000000..ea8497e9496
--- /dev/null
+++ b/apps/server/src/services/connector/exec.boundDevice.test.ts
@@ -0,0 +1,163 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorToolPermission } from '@/database/schemas';
+import { deviceGateway } from '@/server/services/deviceGateway';
+import { mcpService } from '@/server/services/mcp';
+import {
+ McpBoundDeviceUnavailableError,
+ resolveBoundMcpDevice,
+} from '@/server/services/mcp/deviceTunnel';
+
+import { callConnectorToolById } from './exec';
+
+vi.mock('@/server/services/mcp', () => ({ mcpService: { callTool: vi.fn() } }));
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { executeMcpCall: vi.fn(), isConfigured: true },
+}));
+vi.mock('@/server/services/mcp/deviceTunnel', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ resolveBoundMcpDevice: vi.fn(),
+}));
+vi.mock('@/server/services/mcp/featureGate', () => ({
+ isMcpAppsEnabled: vi.fn().mockResolvedValue(false),
+}));
+vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (c) => c) }));
+vi.mock('./refresh', () => ({
+ buildLastSyncedAtMap: vi.fn(() => new Map()),
+ scheduleStaleConnectorToolsRefresh: vi.fn(),
+}));
+
+const serverDB = {} as never;
+const stdioConnector = (metadata: Record<string, unknown> | null, workspaceId?: string) =>
+ ({
+ credentials: null,
+ id: 'c1',
+ identifier: 'local-tool',
+ isEnabled: true,
+ mcpConnectionType: 'stdio',
+ mcpServerUrl: null,
+ mcpStdioConfig: { args: ['serve'], command: 'my-mcp', env: { TOKEN: 'secret' } },
+ metadata,
+ name: 'Local tool',
+ oidcConfig: null,
+ workspaceId: workspaceId ?? null,
+ }) as any;
+
+const makeCtx = (connector: any) =>
+ ({
+ agentModel: { existsById: vi.fn().mockResolvedValue(true) },
+ connectorModel: { queryByIdentifiers: vi.fn().mockResolvedValue([connector]) },
+ connectorToolModel: {
+ queryByConnector: vi
+ .fn()
+ .mockResolvedValue([{ permission: ConnectorToolPermission.auto, toolName: 'do_thing' }]),
+ },
+ serverDB,
+ userId: 'u1',
+ }) as any;
+
+const call = (connector: any, over: Record<string, unknown> = {}) =>
+ callConnectorToolById(
+ { args: '{"q":1}', identifier: 'local-tool', toolName: 'do_thing', ...over },
+ makeCtx(connector),
+ );
+
+describe('callConnectorToolById — connector bound to a device', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(resolveBoundMcpDevice).mockResolvedValue({
+ clientKinds: ['desktop'],
+ deviceId: 'ws-nas',
+ workspaceId: 'ws1',
+ });
+ vi.mocked(deviceGateway.executeMcpCall).mockResolvedValue({
+ content: 'done',
+ state: { content: [{ text: 'done', type: 'text' }], mcpApp: { resourceUri: 'ui://x' } },
+ success: true,
+ } as never);
+ });
+
+ it('runs the tool on the bound device, without the view a device result offers', async () => {
+ await expect(call(stdioConnector({ boundDeviceId: 'ws-nas' }, 'ws1'))).resolves.toEqual({
+ content: 'done',
+ state: { content: [{ text: 'done', type: 'text' }] },
+ success: true,
+ });
+
+ expect(resolveBoundMcpDevice).toHaveBeenCalledWith({
+ binding: { deviceId: 'ws-nas', workspaceId: 'ws1' },
+ identifier: 'local-tool',
+ serverDB,
+ userId: 'u1',
+ });
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith({
+ apiName: 'do_thing',
+ arguments: '{"q":1}',
+ clientKinds: ['desktop'],
+ deviceId: 'ws-nas',
+ identifier: 'local-tool',
+ params: {
+ args: ['serve'],
+ command: 'my-mcp',
+ env: { TOKEN: 'secret' },
+ name: 'local-tool',
+ type: 'stdio',
+ },
+ userId: 'u1',
+ workspaceId: 'ws1',
+ });
+ expect(mcpService.callTool).not.toHaveBeenCalled();
+ });
+
+ it("keeps a failure's error marker and details from the device", async () => {
+ vi.mocked(deviceGateway.executeMcpCall).mockResolvedValue({
+ content: 'Device call timed out',
+ error: 'TIMEOUT',
+ success: false,
+ } as never);
+
+ await expect(call(stdioConnector({ boundDeviceId: 'ws-nas' }))).resolves.toEqual({
+ content: 'Device call timed out',
+ error: { code: 'MCP_DEVICE_EXECUTION_ERROR', message: 'TIMEOUT' },
+ state: undefined,
+ success: false,
+ });
+
+ const errorData = { code: 'DEVICE_NOT_FOUND', deviceId: 'ws-nas', retryable: true };
+ vi.mocked(deviceGateway.executeMcpCall).mockResolvedValue({
+ content: 'gone',
+ errorData,
+ success: false,
+ } as never);
+
+ await expect(call(stdioConnector({ boundDeviceId: 'ws-nas' }))).resolves.toMatchObject({
+ error: errorData,
+ success: false,
+ });
+ });
+
+ it('fails as a precondition with the reason when the bound device is offline', async () => {
+ vi.mocked(resolveBoundMcpDevice).mockRejectedValue(
+ new McpBoundDeviceUnavailableError('local-tool', 'offline', 'Office NAS'),
+ );
+
+ await expect(call(stdioConnector({ boundDeviceId: 'ws-nas' }))).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ message: expect.stringContaining('"Office NAS", which is offline'),
+ });
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ });
+
+ it('still refuses an unbound device-only connector, which the server cannot reach', async () => {
+ await expect(call(stdioConnector(null))).rejects.toHaveProperty('code', 'BAD_REQUEST');
+ expect(resolveBoundMcpDevice).not.toHaveBeenCalled();
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ });
+
+ it("refuses a view's call: a device result offers no view to call back into", async () => {
+ await expect(
+ call(stdioConnector({ boundDeviceId: 'ws-nas' }), { fromEntrypoint: true }),
+ ).rejects.toHaveProperty('code', 'BAD_REQUEST');
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/connector/exec.ts b/apps/server/src/services/connector/exec.ts
index e3c930e7e32..93ad77863ef 100644
--- a/apps/server/src/services/connector/exec.ts
+++ b/apps/server/src/services/connector/exec.ts
@@ -1,7 +1,13 @@
import { hasCallableMcpEndpoint, isMarketplaceInstallRunnable } from '@lobechat/const';
import { getMcpServerFingerprint, isSyncedMcpToolVisibleTo } from '@lobechat/const/mcpApp';
+import type { LobeChatDatabase } from '@lobechat/database';
import { getDisabledPluginIds } from '@lobechat/types';
-import { connectorMcpEndpoint, shouldConnectViaDevice } from '@lobechat/utils/mcpEndpoint';
+import {
+ connectorDeviceBinding,
+ connectorMcpEndpoint,
+ type McpDeviceBinding,
+ shouldConnectViaDevice,
+} from '@lobechat/utils/mcpEndpoint';
import type { AgentModel } from '@/database/models/agent';
import type { DecryptedConnector } from '@/database/models/connector';
@@ -12,13 +18,23 @@ import type { FileService } from '@/server/services/file';
import { mcpService } from '@/server/services/mcp';
import { callCloudMcpTool, type CloudMcpCaller } from '@/server/services/mcp/cloudTool';
import { processContentBlocks } from '@/server/services/mcp/contentProcessor';
+import {
+ McpBoundDeviceUnavailableError,
+ resolveBoundMcpDevice,
+ toGatewayMcpParams,
+} from '@/server/services/mcp/deviceTunnel';
import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';
import { buildLastSyncedAtMap, scheduleStaleConnectorToolsRefresh } from './refresh';
import { buildConnectorMcpParams, type ConnectorToolSyncContext } from './sync';
import { ensureFreshConnectorToken } from './tokens';
-export type ConnectorToolCallErrorCode = 'NOT_FOUND' | 'FORBIDDEN' | 'BAD_REQUEST';
+export type ConnectorToolCallErrorCode =
+ | 'NOT_FOUND'
+ | 'FORBIDDEN'
+ | 'BAD_REQUEST'
+ /** The device a bound connector runs on can't run it now (offline, gone, too old). */
+ | 'PRECONDITION_FAILED';
/** Typed error so the tRPC layer can map to the right code and tests can assert. */
export class ConnectorToolCallError extends Error {
@@ -74,6 +90,11 @@ export interface ConnectorExecContext extends ConnectorToolSyncContext {
* user turned telemetry off.
*/
resolveToolCallReporter?: () => Promise<ConnectorToolCallReporter | undefined>;
+ /**
+ * Finds the device a connector bound to one runs on. `undefined`: such a
+ * connector's call fails instead of reaching the device.
+ */
+ serverDB?: LobeChatDatabase;
/** `userId` decides the caller's `mcp_apps` flag. */
userId?: string | null;
}
@@ -245,6 +266,13 @@ export const callConnectorToolById = async (
deviceGatewayConfigured: deviceGateway.isConfigured,
})
) {
+ // A connector bound to a device runs there: the caller's client may be on
+ // another machine (the web, or a desktop that isn't the bound one). A view's
+ // call is refused: a device's result offers no view to call back into.
+ const binding = connectorDeviceBinding(connector);
+ if (binding && deviceGateway.isConfigured && !params.fromApp && !params.fromEntrypoint) {
+ return runConnectorToolOnBoundDevice(connector, binding, { ...params, mcpApps }, ctx);
+ }
throw new ConnectorToolCallError(
'BAD_REQUEST',
`Connector '${connector.name}' connects through your own device (stdio, a local-network address, or set to "Connect via device"), so the server can't call it directly. ` +
@@ -347,6 +375,69 @@ const runConnectorTool = async (
});
};
+/**
+ * Run a bound connector's tool on its device through the device gateway, with
+ * the credentials its agent-run calls send (`buildConnectorMcpParams`, token
+ * fields only). Never moves to another device: when the bound one can't run
+ * it, the call fails with the reason.
+ */
+const runConnectorToolOnBoundDevice = async (
+ connector: DecryptedConnector,
+ binding: McpDeviceBinding,
+ params: { args?: string; mcpApps: boolean; toolName: string },
+ ctx: ConnectorExecContext,
+): Promise<unknown> => {
+ if (!ctx.serverDB || !ctx.userId) {
+ throw new ConnectorToolCallError(
+ 'BAD_REQUEST',
+ `Connector '${connector.name}' runs on a bound device, which this call can't reach.`,
+ );
+ }
+
+ let target: Awaited<ReturnType<typeof resolveBoundMcpDevice>>;
+ try {
+ target = await resolveBoundMcpDevice({
+ binding,
+ identifier: connector.identifier,
+ serverDB: ctx.serverDB,
+ userId: ctx.userId,
+ });
+ } catch (error) {
+ if (error instanceof McpBoundDeviceUnavailableError) {
+ throw new ConnectorToolCallError('PRECONDITION_FAILED', error.message);
+ }
+ throw error;
+ }
+
+ const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);
+ const result = await deviceGateway.executeMcpCall({
+ apiName: params.toolName,
+ arguments: params.args ?? '{}',
+ clientKinds: target.clientKinds,
+ deviceId: target.deviceId,
+ identifier: connector.identifier,
+ params: toGatewayMcpParams(buildConnectorMcpParams(fresh)),
+ userId: ctx.userId,
+ workspaceId: target.workspaceId,
+ });
+
+ // A view is read from the client that opens the conversation, so a device's
+ // result offers none (as agent runs drop it).
+ const { mcpApp: _deviceView, ...state } = (result.state as Record<string, unknown>) ?? {};
+ return {
+ content: result.content,
+ // A failure keeps its marker and structured details, as agent runs do
+ ...(!result.success && {
+ error: result.errorData ?? {
+ code: 'MCP_DEVICE_EXECUTION_ERROR',
+ message: result.error || result.content,
+ },
+ }),
+ state: result.state ? state : undefined,
+ success: result.success,
+ };
+};
+
/**
* Read an MCP Apps `ui://` resource from a connector's server, so the chat can
* render a connector tool result's interactive view. Same connector checks as
diff --git a/apps/server/src/services/connector/sync.test.ts b/apps/server/src/services/connector/sync.test.ts
index b0f1079f1b6..5386cf4dc60 100644
--- a/apps/server/src/services/connector/sync.test.ts
+++ b/apps/server/src/services/connector/sync.test.ts
@@ -4,6 +4,7 @@ import type { DecryptedConnector } from '@/database/models/connector';
import type { ConnectorCredentials } from '@/database/schemas';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
import { mcpService } from '@/server/services/mcp';
+import { listMcpToolsOnDevice } from '@/server/services/mcp/deviceTunnel';
import {
buildConnectorMcpParams,
@@ -12,6 +13,9 @@ import {
} 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() }));
const mcpAppsEnabled = vi.hoisted(() => vi.fn().mockResolvedValue(false));
vi.mock('@/server/services/mcp/featureGate', () => ({ isMcpAppsEnabled: mcpAppsEnabled }));
vi.mock('./tokens', () => ({ ensureFreshConnectorToken: async (connector: unknown) => connector }));
@@ -202,6 +206,92 @@ describe('buildConnectorMcpParams', () => {
});
});
+describe('a connector bound to a device', () => {
+ const stdioConnector = (metadata: Record<string, unknown> | null, workspaceId?: string) =>
+ ({
+ credentials: null,
+ id: 'c1',
+ identifier: 'local-conn',
+ isEnabled: true,
+ mcpConnectionType: 'stdio',
+ mcpServerUrl: null,
+ mcpStdioConfig: { args: ['serve'], command: 'my-mcp' },
+ metadata,
+ name: 'Local Connector',
+ oidcConfig: null,
+ userId: 'creator',
+ workspaceId: workspaceId ?? null,
+ }) as any;
+
+ it('carries the binding, in its workspace, into the params agent runs use', () => {
+ const connector = stdioConnector({ boundDeviceId: 'ws-nas' }, 'ws1');
+ const [manifest] = buildConnectorManifests(
+ [connector],
+ [{ toolName: 'do_thing', userConnectorId: 'c1' } as any],
+ );
+
+ expect(buildConnectorMcpParams(connector)).toMatchObject({
+ boundDevice: { deviceId: 'ws-nas', workspaceId: 'ws1' },
+ });
+ expect(buildConnectorMcpParams(connector)).toEqual((manifest as any).mcpParams);
+ });
+
+ it('ignores a binding left on a server the server reaches itself', () => {
+ expect(
+ buildConnectorMcpParams(httpConnector(null, { boundDeviceId: 'nas' })),
+ ).not.toHaveProperty('boundDevice');
+ });
+
+ it("lets any member refresh a workspace connector's tools on its bound device", async () => {
+ gateway.isConfigured = true;
+ vi.mocked(listMcpToolsOnDevice).mockResolvedValue([
+ { description: 'Do', inputSchema: { type: 'object' }, name: 'do_thing' },
+ ]);
+ try {
+ const result = await syncConnectorToolsById('c1', {
+ connectorModel: {
+ findById: async () => stdioConnector({ boundDeviceId: 'ws-nas' }, 'ws1'),
+ updateStatus: vi.fn(),
+ } as any,
+ connectorToolModel: { upsertMany: vi.fn() } as any,
+ serverDB: {} as any,
+ userId: 'another-member',
+ });
+
+ expect(result).toEqual({ toolCount: 1 });
+ expect(listMcpToolsOnDevice).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ boundDevice: { deviceId: 'ws-nas', workspaceId: 'ws1' },
+ }),
+ userId: 'another-member',
+ }),
+ );
+ } finally {
+ gateway.isConfigured = false;
+ }
+ });
+
+ it("still keeps an unbound workspace connector's device refresh to its creator", async () => {
+ gateway.isConfigured = true;
+ try {
+ await expect(
+ syncConnectorToolsById('c1', {
+ connectorModel: {
+ findById: async () => stdioConnector(null, 'ws1'),
+ updateStatus: vi.fn(),
+ } as any,
+ connectorToolModel: { upsertMany: vi.fn() } as any,
+ serverDB: {} as any,
+ userId: 'another-member',
+ }),
+ ).rejects.toThrow(/only the member who set it up/);
+ } finally {
+ gateway.isConfigured = false;
+ }
+ });
+});
+
describe('syncConnectorToolsById', () => {
it("syncs view-only tools too, recording each tool's MCP Apps visibility", async () => {
vi.mocked(mcpService.listRawTools).mockResolvedValue([
diff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.ts
index aada7017dde..d622afe4296 100644
--- a/apps/server/src/services/connector/sync.ts
+++ b/apps/server/src/services/connector/sync.ts
@@ -6,6 +6,7 @@ import {
import { type LobeChatDatabase } from '@lobechat/database';
import {
connectorConnectVia,
+ connectorDeviceBinding,
connectorMcpEndpoint,
shouldConnectViaDevice,
} from '@lobechat/utils/mcpEndpoint';
@@ -22,7 +23,7 @@ import type { AuthConfig, McpTool } from '@/libs/mcp';
import { inferCrudType } from '@/libs/mcp/utils';
import { deviceGateway } from '@/server/services/deviceGateway';
import { mcpService } from '@/server/services/mcp';
-import { listMcpToolsOnPersonalDevice } from '@/server/services/mcp/deviceTunnel';
+import { listMcpToolsOnDevice } from '@/server/services/mcp/deviceTunnel';
import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';
import { ensureFreshConnectorToken } from './tokens';
@@ -43,10 +44,13 @@ export interface ConnectorToolSyncContext {
export const buildConnectorMcpParams = (
connector: DecryptedConnector,
): Parameters<typeof mcpService.listRawTools>[0] => {
+ // Only set when bound, as `buildConnectorManifests` does
+ const boundDevice = connectorDeviceBinding(connector);
if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) {
if (!connector.mcpStdioConfig) throw new Error('Missing stdio config');
return {
args: connector.mcpStdioConfig.args ?? [],
+ ...(boundDevice && { boundDevice }),
command: connector.mcpStdioConfig.command,
env: connector.mcpStdioConfig.env,
name: connector.identifier,
@@ -63,6 +67,7 @@ export const buildConnectorMcpParams = (
const mergedHeaders = headers || customHeaders ? { ...headers, ...customHeaders } : undefined;
return {
auth,
+ ...(boundDevice && { boundDevice }),
// Only set when chosen, as `buildConnectorManifests` does
...(connectorConnectVia(connector.metadata) === 'device' && { connectVia: 'device' as const }),
headers: mergedHeaders,
@@ -133,14 +138,16 @@ export const pruneMissingAutoConnectorTools = async (
/**
* A connector this server must not connect to itself (stdio, local network, or
- * set to connect through the device) is listed on the user's desktop through
- * the device gateway; `undefined` for any other, which the server lists itself.
- * Without a gateway (self-hosted) every connector keeps the in-process listing,
- * as agent runs keep the in-process call.
+ * set to connect through the device) is listed on a device through the device
+ * gateway: the device it is bound to, else the caller's newest capable one.
+ * `undefined` for any other, which the server lists itself. Without a gateway
+ * (self-hosted) every connector keeps the in-process listing, as agent runs
+ * keep the in-process call.
*
- * Only the caller's own connector is tunneled to the caller's device: a
- * workspace connector another member set up carries that member's credentials,
- * which must not reach a machine they never approved.
+ * An unbound connector is only tunneled to the caller's device when it is the
+ * caller's own: a workspace connector another member set up carries that
+ * member's credentials, which must not reach a machine they never approved. A
+ * bound one always reaches the device its tool calls run on, whoever refreshes.
*/
const listOnDevice = async (
connector: DecryptedConnector,
@@ -156,13 +163,13 @@ const listOnDevice = async (
)
return undefined;
- if (connector.userId !== ctx.userId) {
+ if (!mcpParams.boundDevice && connector.userId !== ctx.userId) {
throw new Error(
`Connector '${connector.name}' connects through a device, and only the member who set it up can refresh its tools from their desktop app.`,
);
}
- return listMcpToolsOnPersonalDevice({
+ return listMcpToolsOnDevice({
mcpApps,
params: mcpParams,
serverDB: ctx.serverDB,
diff --git a/apps/server/src/services/mcp/deviceManifest.test.ts b/apps/server/src/services/mcp/deviceManifest.test.ts
index 16d83c6f3ef..f78a021be0d 100644
--- a/apps/server/src/services/mcp/deviceManifest.test.ts
+++ b/apps/server/src/services/mcp/deviceManifest.test.ts
@@ -2,7 +2,11 @@ import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getDeviceMcpManifest } from './deviceManifest';
-import { listMcpToolsOnPersonalDevice, McpDeviceUnavailableError } from './deviceTunnel';
+import {
+ listMcpToolsOnDevice,
+ McpBoundDeviceUnavailableError,
+ McpDeviceUnavailableError,
+} from './deviceTunnel';
const gateway = vi.hoisted(() => ({ isConfigured: true }));
@@ -21,7 +25,7 @@ vi.mock('@/server/services/mcp', () => ({
}));
vi.mock('./deviceTunnel', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
- listMcpToolsOnPersonalDevice: vi.fn(),
+ listMcpToolsOnDevice: vi.fn(),
}));
const serverDB = {} as never;
@@ -40,14 +44,14 @@ describe('getDeviceMcpManifest', () => {
it("lists the tools on the user's desktop app and maps them into a manifest", async () => {
const { mcpService } = await import('@/server/services/mcp');
- vi.mocked(listMcpToolsOnPersonalDevice).mockResolvedValue(tools as never);
+ vi.mocked(listMcpToolsOnDevice).mockResolvedValue(tools as never);
await expect(getDeviceMcpManifest({ connection, serverDB, userId: 'u1' })).resolves.toEqual({
api: tools,
identifier: 'nas',
});
- expect(listMcpToolsOnPersonalDevice).toHaveBeenCalledWith({
+ expect(listMcpToolsOnDevice).toHaveBeenCalledWith({
mcpApps: true,
params: {
auth: connection.auth,
@@ -74,11 +78,11 @@ describe('getDeviceMcpManifest', () => {
expect.objectContaining({ name: 'nas', url: connection.url }),
{ mcpApps: true },
);
- expect(listMcpToolsOnPersonalDevice).not.toHaveBeenCalled();
+ expect(listMcpToolsOnDevice).not.toHaveBeenCalled();
});
it('fails as a precondition, with what to do, when no desktop app is online', async () => {
- vi.mocked(listMcpToolsOnPersonalDevice).mockRejectedValue(new McpDeviceUnavailableError('nas'));
+ vi.mocked(listMcpToolsOnDevice).mockRejectedValue(new McpDeviceUnavailableError('nas'));
const error = await getDeviceMcpManifest({ connection, serverDB, userId: 'u1' }).catch(
(e) => e,
@@ -91,7 +95,7 @@ describe('getDeviceMcpManifest', () => {
it("passes a connection's own TRPC error through with its data", async () => {
const authError = new TRPCError({ code: 'UNAUTHORIZED', message: 'Reconnect this MCP' });
- vi.mocked(listMcpToolsOnPersonalDevice).mockRejectedValue(authError);
+ vi.mocked(listMcpToolsOnDevice).mockRejectedValue(authError);
await expect(getDeviceMcpManifest({ connection, serverDB, userId: 'u1' })).rejects.toBe(
authError,
@@ -99,10 +103,74 @@ describe('getDeviceMcpManifest', () => {
});
it('reports a failed listing on the device as a bad request', async () => {
- vi.mocked(listMcpToolsOnPersonalDevice).mockRejectedValue(new Error('ECONNREFUSED'));
+ vi.mocked(listMcpToolsOnDevice).mockRejectedValue(new Error('ECONNREFUSED'));
await expect(
getDeviceMcpManifest({ connection, serverDB, userId: 'u1' }),
).rejects.toMatchObject({ code: 'BAD_REQUEST', message: 'ECONNREFUSED' });
});
+
+ it("lists on the bound device of the caller's workspace", async () => {
+ vi.mocked(listMcpToolsOnDevice).mockResolvedValue(tools as never);
+
+ await getDeviceMcpManifest({
+ connection: { ...connection, boundDeviceId: 'nas-box' },
+ serverDB,
+ userId: 'u1',
+ workspaceId: 'ws1',
+ });
+
+ expect(listMcpToolsOnDevice).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: expect.objectContaining({
+ boundDevice: { deviceId: 'nas-box', workspaceId: 'ws1' },
+ type: 'http',
+ }),
+ }),
+ );
+ });
+
+ it('starts a stdio server on its bound device', async () => {
+ vi.mocked(listMcpToolsOnDevice).mockResolvedValue(tools as never);
+
+ await expect(
+ getDeviceMcpManifest({
+ connection: {
+ args: ['serve'],
+ boundDeviceId: 'build-box',
+ command: 'my-mcp',
+ identifier: 'local-tool',
+ type: 'stdio',
+ },
+ serverDB,
+ userId: 'u1',
+ }),
+ ).resolves.toMatchObject({ identifier: 'local-tool' });
+
+ expect(listMcpToolsOnDevice).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: {
+ args: ['serve'],
+ boundDevice: { deviceId: 'build-box' },
+ command: 'my-mcp',
+ name: 'local-tool',
+ type: 'stdio',
+ },
+ }),
+ );
+ });
+
+ it('fails as a precondition when the bound device is offline', async () => {
+ vi.mocked(listMcpToolsOnDevice).mockRejectedValue(
+ new McpBoundDeviceUnavailableError('nas', 'offline', 'Office NAS'),
+ );
+
+ await expect(
+ getDeviceMcpManifest({
+ connection: { ...connection, boundDeviceId: 'nas-box' },
+ serverDB,
+ userId: 'u1',
+ }),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ });
});
diff --git a/apps/server/src/services/mcp/deviceManifest.ts b/apps/server/src/services/mcp/deviceManifest.ts
index 5c0401e1bf4..6606c64e193 100644
--- a/apps/server/src/services/mcp/deviceManifest.ts
+++ b/apps/server/src/services/mcp/deviceManifest.ts
@@ -1,48 +1,99 @@
import { type LobeChatDatabase } from '@lobechat/database';
-import { type GetStreamableMcpServerManifestInputSchema } from '@lobechat/types';
+import { GetStreamableMcpServerManifestInputSchema } from '@lobechat/types';
+import type { McpDeviceBinding } from '@lobechat/utils/mcpEndpoint';
import { TRPCError } from '@trpc/server';
-import type { z } from 'zod';
+import { z } from 'zod';
+import type { HttpMCPClientParams, StdioMCPParams } from '@/libs/mcp/types';
import { deviceGateway } from '@/server/services/deviceGateway';
import { mcpService } from '@/server/services/mcp';
import {
- listMcpToolsOnPersonalDevice,
+ listMcpToolsOnDevice,
+ McpBoundDeviceUnavailableError,
McpDeviceUnavailableError,
} from '@/server/services/mcp/deviceTunnel';
import { isMcpAppsEnabled } from '@/server/services/mcp/featureGate';
/**
- * The manifest of an HTTP MCP server the user set to connect through their
- * device: its tools are listed on the user's own desktop app, then mapped the
- * way the server relay's `getStreamableMcpServerManifest` maps a listing it ran
- * itself. Without a device gateway (self-hosted) the server connects itself.
+ * A connection test that must run on the user's device: an HTTP server set to
+ * connect through the device, or a stdio server bound to a device other than
+ * the desktop testing it. `boundDeviceId`: the device the server is bound to,
+ * in the caller's current scope (personal, or the active workspace).
+ */
+export const DeviceMcpManifestInputSchema = z.union([
+ z.object({
+ args: z.array(z.string()).default([]),
+ boundDeviceId: z.string().min(1).optional(),
+ command: z.string().min(1),
+ env: z.record(z.string(), z.string()).optional(),
+ identifier: z.string(),
+ metadata: GetStreamableMcpServerManifestInputSchema.shape.metadata,
+ type: z.literal('stdio'),
+ }),
+ GetStreamableMcpServerManifestInputSchema.extend({
+ boundDeviceId: z.string().min(1).optional(),
+ }),
+]);
+
+export type DeviceMcpManifestInput = z.infer<typeof DeviceMcpManifestInputSchema>;
+
+const toDeviceMcpParams = (
+ connection: DeviceMcpManifestInput,
+ boundDevice: McpDeviceBinding | undefined,
+): HttpMCPClientParams | StdioMCPParams =>
+ 'command' in connection
+ ? {
+ args: connection.args,
+ ...(boundDevice && { boundDevice }),
+ command: connection.command,
+ ...(connection.env && { env: connection.env }),
+ name: connection.identifier,
+ type: 'stdio',
+ }
+ : {
+ ...(connection.auth && { auth: connection.auth }),
+ ...(boundDevice && { boundDevice }),
+ connectVia: 'device',
+ ...(connection.headers && { headers: connection.headers }),
+ name: connection.identifier,
+ type: 'http',
+ url: connection.url,
+ };
+
+/**
+ * The manifest of an MCP server that runs on the user's device: its tools are
+ * listed on the device its calls will run on (the bound one, else the user's
+ * newest capable desktop app), then mapped the way the server relay's
+ * `getStreamableMcpServerManifest` maps a listing it ran itself. Without a
+ * device gateway (self-hosted) the server connects to an HTTP server itself.
*
- * Fails with `PRECONDITION_FAILED` when no desktop app of the user's is online,
- * and with the connection's own error when the listing fails.
+ * Fails with `PRECONDITION_FAILED` when no device can run it (the bound device
+ * offline, gone, or too old; no desktop app of the user's online), and with the
+ * connection's own error when the listing fails.
*/
export const getDeviceMcpManifest = async ({
connection,
serverDB,
userId,
+ workspaceId,
}: {
- connection: z.infer<typeof GetStreamableMcpServerManifestInputSchema>;
+ connection: DeviceMcpManifestInput;
serverDB: LobeChatDatabase;
userId: string;
+ /** The caller's scope: a binding names a device of this workspace, or a personal one. */
+ workspaceId?: string;
}) => {
const mcpApps = await isMcpAppsEnabled(userId);
- const params = {
- ...(connection.auth && { auth: connection.auth }),
- connectVia: 'device' as const,
- ...(connection.headers && { headers: connection.headers }),
- name: connection.identifier,
- type: 'http' as const,
- url: connection.url,
- };
+ const boundDevice = connection.boundDeviceId
+ ? { deviceId: connection.boundDeviceId, ...(workspaceId && { workspaceId }) }
+ : undefined;
+ const params = toDeviceMcpParams(connection, boundDevice);
try {
- const rawTools = deviceGateway.isConfigured
- ? await listMcpToolsOnPersonalDevice({ mcpApps, params, serverDB, userId })
- : await mcpService.listRawTools(params, { mcpApps });
+ const rawTools =
+ deviceGateway.isConfigured || params.type === 'stdio'
+ ? await listMcpToolsOnDevice({ mcpApps, params, serverDB, userId })
+ : await mcpService.listRawTools(params, { mcpApps });
return mcpService.buildStreamableMcpManifest(
connection.identifier,
@@ -56,7 +107,11 @@ export const getDeviceMcpManifest = async ({
if (error instanceof TRPCError) throw error;
throw new TRPCError({
cause: error,
- code: error instanceof McpDeviceUnavailableError ? 'PRECONDITION_FAILED' : 'BAD_REQUEST',
+ code:
+ error instanceof McpDeviceUnavailableError ||
+ error instanceof McpBoundDeviceUnavailableError
+ ? 'PRECONDITION_FAILED'
+ : 'BAD_REQUEST',
message: error instanceof Error ? error.message : String(error),
});
}
diff --git a/apps/server/src/services/mcp/deviceTunnel.test.ts b/apps/server/src/services/mcp/deviceTunnel.test.ts
index c8a6797fbca..53372a4781b 100644
--- a/apps/server/src/services/mcp/deviceTunnel.test.ts
+++ b/apps/server/src/services/mcp/deviceTunnel.test.ts
@@ -1,9 +1,15 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
-import { listMcpToolsOnPersonalDevice, McpDeviceUnavailableError } from './deviceTunnel';
+import {
+ listMcpToolsOnDevice,
+ McpBoundDeviceUnavailableError,
+ McpDeviceUnavailableError,
+ resolveBoundMcpDevice,
+} from './deviceTunnel';
vi.mock('@/server/services/deviceGateway', () => ({
deviceGateway: {
@@ -16,6 +22,9 @@ vi.mock('@/server/services/deviceGateway', () => ({
vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
getScopedOnlineDevices: vi.fn(),
}));
+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),
+}));
const serverDB = {} as never;
const params = {
@@ -25,10 +34,15 @@ const params = {
url: 'https://nas.tail1234.ts.net/mcp',
};
const tools = [{ inputSchema: { type: 'object' }, name: 'list_files' }];
-const device = (deviceId: string, channels: string[], online = true) =>
- ({ channels: channels.map((channel) => ({ channel })), deviceId, online }) as never;
+const device = (deviceId: string, channels: string[], online = true, friendlyName?: string) =>
+ ({
+ channels: channels.map((channel) => ({ channel })),
+ deviceId,
+ friendlyName,
+ online,
+ }) as never;
-describe('listMcpToolsOnPersonalDevice', () => {
+describe('listMcpToolsOnDevice', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(deviceGateway.listMcpTools).mockResolvedValue(tools as never);
@@ -41,7 +55,7 @@ describe('listMcpToolsOnPersonalDevice', () => {
]);
await expect(
- listMcpToolsOnPersonalDevice({ mcpApps: true, params, serverDB, userId: 'u1' }),
+ listMcpToolsOnDevice({ mcpApps: true, params, serverDB, userId: 'u1' }),
).resolves.toEqual(tools);
expect(deviceGateway.listMcpTools).toHaveBeenCalledWith({
@@ -67,7 +81,7 @@ describe('listMcpToolsOnPersonalDevice', () => {
systemInfo: { supportedToolCallTypes: ['mcp'] },
} as never);
- await listMcpToolsOnPersonalDevice({ params, serverDB, userId: 'u1' });
+ await listMcpToolsOnDevice({ params, serverDB, userId: 'u1' });
expect(deviceGateway.listMcpTools).toHaveBeenCalledWith(
expect.objectContaining({ clientKinds: ['cli'], deviceId: 'devbox' }),
@@ -84,17 +98,147 @@ describe('listMcpToolsOnPersonalDevice', () => {
systemInfo: {},
} as never);
- await expect(
- listMcpToolsOnPersonalDevice({ params, serverDB, userId: 'u1' }),
- ).rejects.toBeInstanceOf(McpDeviceUnavailableError);
+ await expect(listMcpToolsOnDevice({ params, serverDB, userId: 'u1' })).rejects.toBeInstanceOf(
+ McpDeviceUnavailableError,
+ );
expect(deviceGateway.listMcpTools).not.toHaveBeenCalled();
});
it('tells the user to open the desktop app or run `lh connect` when no device can list it', async () => {
vi.mocked(getScopedOnlineDevices).mockResolvedValue([]);
- await expect(listMcpToolsOnPersonalDevice({ params, serverDB, userId: 'u1' })).rejects.toThrow(
+ await expect(listMcpToolsOnDevice({ params, serverDB, userId: 'u1' })).rejects.toThrow(
/desktop app or run `lh connect`/,
);
});
});
+
+describe('resolveBoundMcpDevice', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(resolveDeviceDispatchAuthorizationFailure).mockResolvedValue(undefined);
+ });
+
+ it('resolves the bound device in its pool, even when a newer device is online', async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ device('newest', ['desktop']),
+ device('nas-box', ['desktop']),
+ ]);
+
+ await expect(
+ resolveBoundMcpDevice({
+ binding: { deviceId: 'nas-box', workspaceId: 'ws1' },
+ identifier: 'nas',
+ serverDB,
+ userId: 'u1',
+ }),
+ ).resolves.toEqual({ clientKinds: ['desktop'], deviceId: 'nas-box', workspaceId: 'ws1' });
+ // Looked up in the workspace pool the binding names
+ expect(getScopedOnlineDevices).toHaveBeenCalledWith(serverDB, 'u1', 'ws1');
+ });
+
+ it('fails as offline, naming the device, instead of falling back to another one', async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ device('laptop', ['desktop']),
+ device('nas-box', ['desktop'], false, 'Office NAS'),
+ ]);
+
+ const error = await resolveBoundMcpDevice({
+ binding: { deviceId: 'nas-box' },
+ identifier: 'nas',
+ serverDB,
+ userId: 'u1',
+ }).catch((e) => e);
+
+ expect(error).toBeInstanceOf(McpBoundDeviceUnavailableError);
+ expect(error.reason).toBe('offline');
+ expect(error.message).toContain('"Office NAS", which is offline');
+ });
+
+ it('fails as not found when the device is gone or no longer visible', async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([device('laptop', ['desktop'])]);
+
+ await expect(
+ resolveBoundMcpDevice({
+ binding: { deviceId: 'gone' },
+ identifier: 'nas',
+ serverDB,
+ userId: 'u1',
+ }),
+ ).rejects.toMatchObject({ reason: 'not_found' });
+ });
+
+ it('fails as not found when the workspace registry no longer authorizes the device', async () => {
+ vi.mocked(resolveDeviceDispatchAuthorizationFailure).mockResolvedValue({
+ code: 'DEVICE_NOT_FOUND',
+ } as never);
+
+ await expect(
+ resolveBoundMcpDevice({
+ binding: { deviceId: 'nas-box', workspaceId: 'ws1' },
+ identifier: 'nas',
+ serverDB,
+ userId: 'u1',
+ }),
+ ).rejects.toMatchObject({ reason: 'not_found' });
+ expect(getScopedOnlineDevices).not.toHaveBeenCalled();
+ });
+
+ it('fails as unsupported when the device only has an `lh connect` that predates MCP', async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([device('old-cli', ['cli'])]);
+ vi.mocked(deviceGateway.readDeviceSystemInfo).mockResolvedValue({
+ ok: true,
+ systemInfo: {},
+ } as never);
+
+ await expect(
+ resolveBoundMcpDevice({
+ binding: { deviceId: 'old-cli' },
+ identifier: 'nas',
+ serverDB,
+ userId: 'u1',
+ }),
+ ).rejects.toMatchObject({ reason: 'unsupported' });
+ });
+});
+
+describe('listMcpToolsOnDevice with a bound device', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(resolveDeviceDispatchAuthorizationFailure).mockResolvedValue(undefined);
+ vi.mocked(deviceGateway.listMcpTools).mockResolvedValue(tools as never);
+ });
+
+ it('lists on the bound workspace device, addressed under its workspace', async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ device('newest', ['desktop']),
+ device('nas-box', ['desktop']),
+ ]);
+
+ await listMcpToolsOnDevice({
+ params: { ...params, boundDevice: { deviceId: 'nas-box', workspaceId: 'ws1' } },
+ serverDB,
+ userId: 'u1',
+ });
+
+ expect(deviceGateway.listMcpTools).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'nas-box', workspaceId: 'ws1' }),
+ );
+ });
+
+ it('fails with the bound reason when the bound device is offline', async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ device('laptop', ['desktop']),
+ device('nas-box', ['desktop'], false),
+ ]);
+
+ await expect(
+ listMcpToolsOnDevice({
+ params: { ...params, boundDevice: { deviceId: 'nas-box' } },
+ serverDB,
+ userId: 'u1',
+ }),
+ ).rejects.toMatchObject({ reason: 'offline' });
+ expect(deviceGateway.listMcpTools).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/mcp/deviceTunnel.ts b/apps/server/src/services/mcp/deviceTunnel.ts
index d68b8cbae73..a59a1e9f428 100644
--- a/apps/server/src/services/mcp/deviceTunnel.ts
+++ b/apps/server/src/services/mcp/deviceTunnel.ts
@@ -2,6 +2,7 @@ import { BRANDING_NAME } from '@lobechat/business-const';
import { type LobeChatDatabase } from '@lobechat/database';
import type { GatewayMcpParams } from '@lobechat/device-gateway-client';
import type { DeviceClient } from '@lobechat/types';
+import type { McpDeviceBinding } from '@lobechat/utils/mcpEndpoint';
import debug from 'debug';
import type { HttpMCPClientParams, McpTool, StdioMCPParams } from '@/libs/mcp/types';
@@ -10,6 +11,7 @@ import {
clientKindFromChannels,
resolveMcpClientKinds,
} from '@/server/services/deviceGateway/deviceChannels';
+import { resolveDeviceDispatchAuthorizationFailure } from '@/server/services/deviceGateway/dispatchAuthorization';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
const log = debug('lobe-server:mcp:device-tunnel');
@@ -33,6 +35,51 @@ export class McpDeviceUnavailableError extends Error {
}
}
+/** Code of the error an MCP server bound to a device fails with when that device can't run it. */
+export const MCP_BOUND_DEVICE_UNAVAILABLE = 'MCP_BOUND_DEVICE_UNAVAILABLE';
+
+/**
+ * Why the device an MCP server is bound to can't run it:
+ * - `not_found`: removed, unshared, or no longer visible to the caller;
+ * - `offline`: registered but not connected;
+ * - `unsupported`: connected only through an `lh connect` that predates MCP.
+ */
+export type McpBoundDeviceUnavailableReason = 'not_found' | 'offline' | 'unsupported';
+
+/**
+ * What a user reads when the device an MCP server is bound to can't run it. A
+ * bound server never moves to another device, so each reason names the fix.
+ */
+export const mcpBoundDeviceUnavailableMessage = (
+ identifier: string,
+ reason: McpBoundDeviceUnavailableReason,
+ deviceName?: string,
+) => {
+ const device = deviceName ? `"${deviceName}"` : 'its device';
+ switch (reason) {
+ case 'offline': {
+ return `MCP server '${identifier}' is bound to ${device}, which is offline. Open the ${BRANDING_NAME} desktop app or run \`lh connect\` on that computer, then try again. A bound MCP server never runs on another device.`;
+ }
+ case 'unsupported': {
+ return `MCP server '${identifier}' is bound to ${device}, which is online but can't run MCP servers: its \`lh connect\` is too old. Update the CLI or open the ${BRANDING_NAME} desktop app on that computer, then try again.`;
+ }
+ default: {
+ return `MCP server '${identifier}' is bound to a device that is no longer available (it was removed or is no longer shared with you). Edit the MCP server to choose another device, or let it pick one automatically.`;
+ }
+ }
+};
+
+export class McpBoundDeviceUnavailableError extends Error {
+ readonly code = MCP_BOUND_DEVICE_UNAVAILABLE;
+ readonly reason: McpBoundDeviceUnavailableReason;
+
+ constructor(identifier: string, reason: McpBoundDeviceUnavailableReason, deviceName?: string) {
+ super(mcpBoundDeviceUnavailableMessage(identifier, reason, deviceName));
+ this.name = 'McpBoundDeviceUnavailableError';
+ this.reason = reason;
+ }
+}
+
/**
* The connection params a device needs to reach an MCP server. Credentials for
* HTTP are narrowed to the token fields: the full `AuthConfig` also carries
@@ -67,6 +114,8 @@ export const toGatewayMcpParams = (
export interface McpDeviceTarget {
clientKinds: DeviceClient[];
deviceId: string;
+ /** The device's pool: a workspace device is addressed under its workspace. */
+ workspaceId?: string;
}
/**
@@ -108,16 +157,67 @@ export const findPersonalMcpDevice = async (
}
};
+/**
+ * The device an MCP server is bound to, when it can run the server now. Bound
+ * servers never fall back to another device, so every way that device can't
+ * run it throws {@link McpBoundDeviceUnavailableError} with its reason.
+ *
+ * The lookup is scoped to the binding's pool through the scoped device helper
+ * (not the raw gateway pool), so device visibility applies: a workspace device
+ * that was unshared, or another member's private one, reads as `not_found`.
+ * A workspace device is also rechecked against the registry the way every
+ * workspace dispatch is (`resolveDeviceDispatchAuthorizationFailure`).
+ */
+export const resolveBoundMcpDevice = async ({
+ binding,
+ identifier,
+ serverDB,
+ userId,
+}: {
+ binding: McpDeviceBinding;
+ identifier: string;
+ serverDB: LobeChatDatabase;
+ userId: string;
+}): Promise<McpDeviceTarget> => {
+ const { deviceId, workspaceId } = binding;
+
+ if (await resolveDeviceDispatchAuthorizationFailure(serverDB, userId, deviceId, workspaceId)) {
+ throw new McpBoundDeviceUnavailableError(identifier, 'not_found');
+ }
+
+ const devices = await getScopedOnlineDevices(serverDB, userId, workspaceId);
+ const device = devices.find((item) => item.deviceId === deviceId);
+ if (!device) throw new McpBoundDeviceUnavailableError(identifier, 'not_found');
+
+ const deviceName = device.friendlyName || device.hostname || undefined;
+ if (!device.online) throw new McpBoundDeviceUnavailableError(identifier, 'offline', deviceName);
+
+ // Unlabelled channels (an older gateway) keep the desktop routing, as an
+ // active run device does: the user chose this device explicitly.
+ const clientKinds = await resolveMcpClientKinds(
+ userId,
+ deviceId,
+ workspaceId,
+ clientKindFromChannels(device.channels),
+ );
+ if (!clientKinds) throw new McpBoundDeviceUnavailableError(identifier, 'unsupported', deviceName);
+
+ return { clientKinds, deviceId, workspaceId };
+};
+
/**
* List an MCP server's tools on the user's own device, for a server this
* deployment must not connect to itself (`shouldConnectViaDevice`): an
* install, a tool refresh or a connection test the user started. It runs on
- * the device and client a tool call would, so both reach the server alike.
+ * the device and client a tool call would, so both reach the server alike: the
+ * bound device when the server has one (`params.boundDevice`), else the user's
+ * newest capable personal device.
*
- * Throws {@link McpDeviceUnavailableError} when no device of theirs can run
- * it, and the device's own reason when the listing fails there.
+ * Throws {@link McpBoundDeviceUnavailableError} when the bound device can't run
+ * it, {@link McpDeviceUnavailableError} when no device of theirs can, and the
+ * device's own reason when the listing fails there.
*/
-export const listMcpToolsOnPersonalDevice = async ({
+export const listMcpToolsOnDevice = async ({
mcpApps,
params,
serverDB,
@@ -130,7 +230,14 @@ export const listMcpToolsOnPersonalDevice = async ({
}): Promise<McpTool[]> => {
if (!serverDB || !userId) throw new McpDeviceUnavailableError(params.name);
- const device = await findPersonalMcpDevice(serverDB, userId);
+ const device = params.boundDevice
+ ? await resolveBoundMcpDevice({
+ binding: params.boundDevice,
+ identifier: params.name,
+ serverDB,
+ userId,
+ })
+ : await findPersonalMcpDevice(serverDB, userId);
if (!device) throw new McpDeviceUnavailableError(params.name);
log('listing tools of %s (%s) on device %s', params.name, params.type, device.deviceId);
@@ -141,5 +248,6 @@ export const listMcpToolsOnPersonalDevice = async ({
mcpApps,
params: toGatewayMcpParams(params),
userId,
+ workspaceId: device.workspaceId,
});
};
diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.ts
index afad212f0f7..76e6ca4bc4c 100644
--- a/apps/server/src/services/mcp/index.ts
+++ b/apps/server/src/services/mcp/index.ts
@@ -535,7 +535,7 @@ export class MCPService {
*/
buildStreamableMcpManifest(
identifier: string,
- mcpParams: HttpMCPClientParams,
+ mcpParams: HttpMCPClientParams | StdioMCPParams,
rawTools: McpTool[],
metadata?: CustomPluginMetadata,
{ mcpApps = false }: { mcpApps?: boolean } = {},
diff --git a/apps/server/src/services/toolExecution/__tests__/boundDeviceMcp.test.ts b/apps/server/src/services/toolExecution/__tests__/boundDeviceMcp.test.ts
new file mode 100644
index 00000000000..56ce415ddcc
--- /dev/null
+++ b/apps/server/src/services/toolExecution/__tests__/boundDeviceMcp.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { deviceGateway } from '@/server/services/deviceGateway';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
+
+import { ToolExecutionService } from '../index';
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ executeMcpCall: vi.fn(),
+ isConfigured: true,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ readDeviceSystemInfo: vi.fn().mockResolvedValue({ ok: true, systemInfo: {} }),
+ },
+}));
+vi.mock('@/server/services/mcp/featureGate', () => ({
+ isMcpAppsEnabled: vi.fn().mockResolvedValue(false),
+}));
+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
+ getScopedOnlineDevices: vi.fn().mockResolvedValue([]),
+}));
+
+/** A device-only MCP server bound to one device runs there and nowhere else. */
+describe('ToolExecutionService — MCP bound to a device', () => {
+ const makeService = () =>
+ new ToolExecutionService({
+ builtinToolsExecutor: { execute: vi.fn() } as any,
+ mcpService: { callTool: vi.fn() } as any,
+ });
+
+ const mcpPayload = {
+ apiName: 'do_thing',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'my-mcp',
+ type: 'mcp',
+ } as any;
+
+ const contextWith = (mcpParams: Record<string, unknown>, over: Record<string, unknown> = {}) =>
+ ({
+ serverDB: {},
+ toolManifestMap: { 'my-mcp': { mcpParams } },
+ userId: 'user-1',
+ ...over,
+ }) as any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(deviceGateway.executeMcpCall).mockResolvedValue({
+ content: 'ok',
+ success: true,
+ } as any);
+ });
+
+ const stdio = { args: [], command: 'npx', name: 'my-mcp', type: 'stdio' };
+
+ it("tunnels to the bound device, not the run's device or a newer one", async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ { channels: [{ channel: 'desktop' }], deviceId: 'newest', online: true },
+ { channels: [{ channel: 'desktop' }], deviceId: 'nas-box', online: true },
+ ] as any);
+ const service = makeService();
+
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { ...stdio, boundDevice: { deviceId: 'nas-box' } },
+ { activeDeviceId: 'run-device' },
+ ),
+ );
+
+ expect(result.success).toBe(true);
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'nas-box', workspaceId: undefined }),
+ undefined,
+ );
+ });
+
+ it("addresses the bound workspace device under the connector's workspace in a run with no device", async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ { channels: [{ channel: 'desktop' }], deviceId: 'ws-nas', online: true },
+ ] as any);
+ const service = makeService();
+
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith(
+ { ...stdio, boundDevice: { deviceId: 'ws-nas', workspaceId: 'ws-1' } },
+ { workspaceId: 'ws-1' },
+ ),
+ );
+
+ expect(result.success).toBe(true);
+ expect(getScopedOnlineDevices).toHaveBeenCalledWith({}, 'user-1', 'ws-1');
+ expect(deviceGateway.executeMcpCall).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceId: 'ws-nas', workspaceId: 'ws-1' }),
+ undefined,
+ );
+ });
+
+ it('fails with the reason instead of falling back when the bound device is offline', async () => {
+ vi.mocked(getScopedOnlineDevices).mockResolvedValue([
+ { channels: [{ channel: 'desktop' }], deviceId: 'laptop', online: true },
+ { deviceId: 'nas-box', friendlyName: 'Office NAS', online: false },
+ ] as any);
+ const service = makeService();
+
+ const result = await service.executeTool(
+ mcpPayload,
+ contextWith({ ...stdio, boundDevice: { deviceId: 'nas-box' } }, { activeDeviceId: 'laptop' }),
+ );
+
+ expect(deviceGateway.executeMcpCall).not.toHaveBeenCalled();
+ expect(result.success).toBe(false);
+ expect((result.error as any)?.code).toBe('MCP_BOUND_DEVICE_UNAVAILABLE');
+ expect(result.content).toContain('"Office NAS", which is offline');
+ });
+});
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index e2cd874419c..82afddcc4dd 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -20,8 +20,12 @@ import { type MCPService } from '../mcp';
import { callCloudMcpTool, runtimeCloudMcpCaller } from '../mcp/cloudTool';
import {
findPersonalMcpDevice,
+ MCP_BOUND_DEVICE_UNAVAILABLE,
MCP_DEVICE_UNAVAILABLE,
+ McpBoundDeviceUnavailableError,
+ mcpBoundDeviceUnavailableMessage,
mcpDeviceUnavailableMessage,
+ resolveBoundMcpDevice,
toGatewayMcpParams,
} from '../mcp/deviceTunnel';
import { type BuiltinToolsExecutor } from './builtin';
@@ -349,6 +353,22 @@ export class ToolExecutionService {
};
}
+ // A server bound to a device runs there and nowhere else: when that
+ // device can't run it, the call fails with the reason instead of
+ // moving to the run's device or another of the user's.
+ if (mcpParams.boundDevice) {
+ const bound = await this.resolveBoundMcpTunnelTarget(context, mcpParams);
+ if ('error' in bound) {
+ log('Bound MCP %s:%s cannot run on its device — %s', identifier, apiName, bound.error);
+ return {
+ content: bound.error,
+ error: { code: MCP_BOUND_DEVICE_UNAVAILABLE, message: bound.error },
+ success: false,
+ };
+ }
+ return await this.executeMcpViaDevice(payload, context, mcpParams, bound);
+ }
+
const tunnelTarget = context.userId
? await this.resolveMcpTunnelTarget(context)
: undefined;
@@ -415,6 +435,33 @@ export class ToolExecutionService {
}
}
+ /**
+ * The device a bound MCP server's call tunnels to: always the bound one, in
+ * the pool the binding names (the connector's workspace, or its owner's
+ * personal devices), never the run's. `error` explains why it can't run there.
+ */
+ private async resolveBoundMcpTunnelTarget(
+ context: ToolExecutionContext,
+ mcpParams: StdioMCPParams | HttpMCPClientParams,
+ ): Promise<McpTunnelTarget | { error: string }> {
+ const binding = mcpParams.boundDevice!;
+ if (!context.userId || !context.serverDB) {
+ return { error: mcpBoundDeviceUnavailableMessage(mcpParams.name, 'not_found') };
+ }
+ try {
+ const target = await resolveBoundMcpDevice({
+ binding,
+ identifier: mcpParams.name,
+ serverDB: context.serverDB,
+ userId: context.userId,
+ });
+ return { ...target, workspaceId: binding.workspaceId };
+ } catch (error) {
+ if (error instanceof McpBoundDeviceUnavailableError) return { error: error.message };
+ throw error;
+ }
+ }
+
/**
* Resolve which device a device-only MCP call should tunnel to.
*
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 3def57cac06..65556e6e6b3 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -767,6 +767,13 @@
"dev.mcp.auth.token.placeholder": "sk-xxxxx",
"dev.mcp.auth.token.required": "Enter auth token",
"dev.mcp.avatar.label": "Skill icon",
+ "dev.mcp.boundDevice.auto": "Auto",
+ "dev.mcp.boundDevice.autoDesc": "Runs on the conversation's device, or your most recently active online device",
+ "dev.mcp.boundDevice.desc": "Pin this MCP server to one device. When that device is offline, calls fail instead of moving to another device.",
+ "dev.mcp.boundDevice.empty": "No device yet. Open the LobeHub desktop app or run `lh connect` on a computer first.",
+ "dev.mcp.boundDevice.emptyWorkspace": "No shared device in this workspace yet",
+ "dev.mcp.boundDevice.label": "Run on device",
+ "dev.mcp.boundDevice.unavailable": "Bound device is no longer available",
"dev.mcp.command.desc": "Executable or script to start MCP STDIO server",
"dev.mcp.command.label": "Command",
"dev.mcp.command.placeholder": "e.g. npx / uv / docker",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 7cccc870a2b..7e93d5e2fea 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -767,6 +767,13 @@
"dev.mcp.auth.token.placeholder": "sk-xxxxx",
"dev.mcp.auth.token.required": "请输入认证令牌",
"dev.mcp.avatar.label": "技能图标",
+ "dev.mcp.boundDevice.auto": "自动选择",
+ "dev.mcp.boundDevice.autoDesc": "在对话所用的设备上运行,没有时选择你最近活跃的在线设备",
+ "dev.mcp.boundDevice.desc": "把这个 MCP 服务固定在一台设备上运行。该设备离线时调用会直接失败,不会换到其他设备。",
+ "dev.mcp.boundDevice.empty": "还没有设备。请先在电脑上打开 LobeHub 桌面端或运行 `lh connect`。",
+ "dev.mcp.boundDevice.emptyWorkspace": "这个工作区还没有共享设备",
+ "dev.mcp.boundDevice.label": "运行设备",
+ "dev.mcp.boundDevice.unavailable": "绑定的设备已不可用",
"dev.mcp.command.desc": "用于启动 MCP STDIO Server 的可执行文件或脚本",
"dev.mcp.command.label": "命令",
"dev.mcp.command.placeholder": "例如:npx / uv / docker 等",
diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.ts
index eac0d1fb798..0ddb7cffc8f 100644
--- a/packages/database/src/schemas/connector.ts
+++ b/packages/database/src/schemas/connector.ts
@@ -142,6 +142,15 @@ export interface ComposioConnectorMetadata {
export interface ConnectorMetadata {
[key: string]: unknown;
avatar?: string;
+ /**
+ * Stdio / device-routed HTTP only: the device this connector always runs on,
+ * through the device gateway. Absent means the device is picked automatically
+ * (the run's device, else the newest capable personal one). A personal
+ * connector binds one of its owner's personal devices, a workspace connector
+ * a public device of its workspace. Never falls back: an offline bound device
+ * fails the call (`connectorDeviceBinding` in `@lobechat/utils/mcpEndpoint`).
+ */
+ boundDeviceId?: string;
composio?: ComposioConnectorMetadata;
/**
* HTTP only: `device` reaches the MCP server from the user's device through
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 3aaf617f9fa..5da688c106b 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -796,6 +796,16 @@ export default {
'dev.mcp.auth.token.placeholder': 'sk-xxxxx',
'dev.mcp.auth.token.required': 'Enter auth token',
'dev.mcp.avatar.label': 'Skill icon',
+ 'dev.mcp.boundDevice.auto': 'Auto',
+ 'dev.mcp.boundDevice.autoDesc':
+ "Runs on the conversation's device, or your most recently active online device",
+ 'dev.mcp.boundDevice.desc':
+ 'Pin this MCP server to one device. When that device is offline, calls fail instead of moving to another device.',
+ 'dev.mcp.boundDevice.empty':
+ 'No device yet. Open the LobeHub desktop app or run `lh connect` on a computer first.',
+ 'dev.mcp.boundDevice.emptyWorkspace': 'No shared device in this workspace yet',
+ 'dev.mcp.boundDevice.label': 'Run on device',
+ 'dev.mcp.boundDevice.unavailable': 'Bound device is no longer available',
'dev.mcp.command.desc': 'Executable or script to start MCP STDIO server',
'dev.mcp.command.label': 'Command',
'dev.mcp.command.placeholder': 'e.g. npx / uv / docker',
diff --git a/packages/types/src/plugins/mcp.ts b/packages/types/src/plugins/mcp.ts
index 67867008635..46a55e8918c 100644
--- a/packages/types/src/plugins/mcp.ts
+++ b/packages/types/src/plugins/mcp.ts
@@ -218,6 +218,11 @@ export interface McpConnection {
token?: string;
type: 'none' | 'bearer' | 'oauth2';
};
+ /**
+ * The device a server that runs on the user's device (stdio, or HTTP reached
+ * from the device) is pinned to. Absent: the device is picked automatically.
+ */
+ boundDeviceId?: string;
// STDIO connection parameters
command?: string;
/** HTTP only: `device` reaches the server from the user's device (`McpConnectVia`). */
diff --git a/packages/types/src/tool/plugin.ts b/packages/types/src/tool/plugin.ts
index dc5624ad530..be6a4ed0111 100644
--- a/packages/types/src/tool/plugin.ts
+++ b/packages/types/src/tool/plugin.ts
@@ -71,6 +71,11 @@ export interface CustomPluginParams {
headers?: Record<string, string>;
/** HTTP only: where the server is reached from. Absent means `auto`. */
connectVia?: McpConnectVia;
+ /**
+ * Connectors only: the device a server that runs on the user's device is
+ * pinned to (`metadata.boundDeviceId`). Absent: picked automatically.
+ */
+ boundDeviceId?: string;
};
useProxy?: boolean;
}
diff --git a/packages/utils/src/mcpEndpoint.test.ts b/packages/utils/src/mcpEndpoint.test.ts
index b999c809a28..24a1da500b1 100644
--- a/packages/utils/src/mcpEndpoint.test.ts
+++ b/packages/utils/src/mcpEndpoint.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
connectorConnectVia,
+ connectorDeviceBinding,
connectorMcpEndpoint,
isDeviceOnlyMcpEndpoint,
shouldConnectViaDevice,
@@ -123,3 +124,51 @@ describe('connectorMcpEndpoint', () => {
expect(connectorConnectVia({ connectVia: 'device' })).toBe('device');
});
});
+
+describe('connectorDeviceBinding', () => {
+ const stdio = { mcpConnectionType: 'stdio', mcpServerUrl: null };
+
+ it('is the bound device of a personal connector', () => {
+ expect(connectorDeviceBinding({ ...stdio, metadata: { boundDeviceId: 'laptop' } })).toEqual({
+ deviceId: 'laptop',
+ });
+ });
+
+ it("names the workspace pool of a workspace connector's device", () => {
+ expect(
+ connectorDeviceBinding({ ...stdio, metadata: { boundDeviceId: 'nas' }, workspaceId: 'ws1' }),
+ ).toEqual({ deviceId: 'nas', workspaceId: 'ws1' });
+ });
+
+ it('binds an HTTP server only when it runs on the device', () => {
+ const bound = { boundDeviceId: 'nas' };
+ expect(
+ connectorDeviceBinding({
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'http://192.168.1.10:8000/mcp',
+ metadata: bound,
+ }),
+ ).toEqual({ deviceId: 'nas' });
+ expect(
+ connectorDeviceBinding({
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://nas.tail1234.ts.net/mcp',
+ metadata: { ...bound, connectVia: 'device' },
+ }),
+ ).toEqual({ deviceId: 'nas' });
+ // A server the cloud reaches itself ignores a binding left on it
+ expect(
+ connectorDeviceBinding({
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com',
+ metadata: bound,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('is unbound without a usable device id', () => {
+ expect(connectorDeviceBinding({ ...stdio, metadata: null })).toBeUndefined();
+ expect(connectorDeviceBinding({ ...stdio, metadata: { boundDeviceId: '' } })).toBeUndefined();
+ expect(connectorDeviceBinding({ ...stdio, metadata: { boundDeviceId: 1 } })).toBeUndefined();
+ });
+});
diff --git a/packages/utils/src/mcpEndpoint.ts b/packages/utils/src/mcpEndpoint.ts
index 955a78af3e8..d3c2dec9ed3 100644
--- a/packages/utils/src/mcpEndpoint.ts
+++ b/packages/utils/src/mcpEndpoint.ts
@@ -68,3 +68,31 @@ export const connectorMcpEndpoint = (connector: {
export const connectorConnectVia = (
metadata: { connectVia?: unknown } | null | undefined,
): McpConnectVia => (metadata?.connectVia === 'device' ? 'device' : 'auto');
+
+/**
+ * The device a device-only MCP server is pinned to. `workspaceId` is the pool
+ * the device lives in: a workspace connector binds a device of its workspace,
+ * a personal one a device of its owner (no `workspaceId`).
+ */
+export interface McpDeviceBinding {
+ deviceId: string;
+ workspaceId?: string;
+}
+
+/**
+ * The device a connector is bound to (`metadata.boundDeviceId`), or `undefined`
+ * when it picks a device automatically. Only a server that runs on the user's
+ * device ({@link isDeviceOnlyMcpEndpoint}) can be bound: a binding left on one
+ * the server reaches itself is ignored, as the editor hides it there.
+ */
+export const connectorDeviceBinding = (connector: {
+ mcpConnectionType?: string | null;
+ mcpServerUrl?: string | null;
+ metadata?: { boundDeviceId?: unknown; connectVia?: unknown } | null;
+ workspaceId?: string | null;
+}): McpDeviceBinding | undefined => {
+ const deviceId = connector.metadata?.boundDeviceId;
+ if (typeof deviceId !== 'string' || !deviceId) return undefined;
+ if (!isDeviceOnlyMcpEndpoint(connectorMcpEndpoint(connector))) return undefined;
+ return connector.workspaceId ? { deviceId, workspaceId: connector.workspaceId } : { deviceId };
+};
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsx
index d00ebb1ba97..602eb3c2b4e 100644
--- a/src/features/Connectors/CustomConnectorModal/index.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.tsx
@@ -1,5 +1,5 @@
import { type LobeToolCustomPlugin, type McpConnectVia } from '@lobechat/types';
-import { connectorConnectVia } from '@lobechat/utils/mcpEndpoint';
+import { connectorConnectVia, connectorDeviceBinding } from '@lobechat/utils/mcpEndpoint';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import type { ConnectorCredentials, OIDCConfig } from '@/database/schemas';
@@ -189,6 +189,11 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
token: authType === 'bearer' ? (credentials as { token: string })?.token : undefined,
type: authType === 'header' ? 'none' : authType,
},
+ boundDeviceId: connectorDeviceBinding({
+ mcpConnectionType: connector.mcpConnectionType,
+ mcpServerUrl: connector.mcpServerUrl,
+ metadata,
+ })?.deviceId,
command: mcpStdioConfig?.command,
connectVia: connectorConnectVia(metadata),
env: mcpStdioConfig?.env,
@@ -250,6 +255,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
const mcp = (value.customParams?.mcp ?? {}) as {
args?: string[];
auth?: { clientId?: string; clientSecret?: string; token?: string; type?: string };
+ boundDeviceId?: string;
command?: string;
connectVia?: McpConnectVia;
env?: Record<string, string>;
@@ -261,6 +267,8 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
// Only `device` is stored; stdio always runs on the device anyway
const connectViaDevice = mcp.type !== 'stdio' && mcp.connectVia === 'device';
const isHttp = mcp.type !== 'stdio';
+ // Only kept for a server that runs on the device (the form prunes it otherwise)
+ const boundDeviceId = mcp.boundDeviceId || undefined;
const authType = mcp.auth?.type;
// ── Edit mode ─────────────────────────────────────────────────────────
@@ -299,6 +307,8 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
else delete nextMetadata.customHeaders;
if (connectViaDevice) nextMetadata.connectVia = 'device';
else delete nextMetadata.connectVia;
+ if (boundDeviceId) nextMetadata.boundDeviceId = boundDeviceId;
+ else delete nextMetadata.boundDeviceId;
patch.metadata = nextMetadata;
}
@@ -352,8 +362,13 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
command: (mcp.command ?? '').trim(),
env: cleanRecord(mcp.env),
},
- // The OAuth create keeps the choice too; the other path rebuilds metadata below
- ...(connectViaDevice && { metadata: { connectVia: 'device' as const } }),
+ // The OAuth create keeps the choices too; the other path rebuilds metadata below
+ ...((connectViaDevice || boundDeviceId) && {
+ metadata: {
+ ...(boundDeviceId && { boundDeviceId }),
+ ...(connectViaDevice && { connectVia: 'device' as const }),
+ },
+ }),
name: identifier,
sourceType: ConnectorSourceType.custom,
};
@@ -414,6 +429,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
// server already has, and the rollback below must never delete a
// connector the user already had.
const metadata = {
+ ...(boundDeviceId && { boundDeviceId }),
...(headers && { customHeaders: headers }),
...(connectViaDevice && { connectVia: 'device' as const }),
};
@@ -448,6 +464,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
return (
<DevModal
+ enableDeviceBinding
enableOAuth
mode={isEditMode || isMigrationMode ? 'edit' : 'create'}
open={open}
diff --git a/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.tsx b/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.tsx
new file mode 100644
index 00000000000..38574a3e224
--- /dev/null
+++ b/src/features/PluginDevModal/MCPManifestForm/BoundDeviceSelect.tsx
@@ -0,0 +1,179 @@
+import type { DeviceListItem } from '@lobechat/types';
+import type { SelectOptions } from '@lobehub/ui';
+import { Select } from '@lobehub/ui';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import AsyncError from '@/components/AsyncError';
+import {
+ ExecutionTargetLabel,
+ executionTargetSelectClassNames,
+ groupExecutionTargetDevices,
+} from '@/features/ExecutionTargetPicker';
+import { useDeviceList } from '@/store/device';
+
+const AUTO = 'auto';
+const STATUS_PREFIX = 'status:';
+
+/**
+ * The devices an MCP server of the current scope may be bound to: the user's
+ * personal devices for a personal server, the workspace's public devices for a
+ * workspace one (a private enrollment only resolves for the member who
+ * enrolled it, while every member's runs use the server). The server checks
+ * the same rule on save (`assertConnectorDeviceBindingAllowed`).
+ */
+export const bindableMcpDevices = (
+ devices: DeviceListItem[] | undefined,
+ workspaceScoped: boolean,
+): DeviceListItem[] => {
+ const groups = groupExecutionTargetDevices(devices);
+ return workspaceScoped ? groups.publicWorkspace : groups.personal;
+};
+
+interface BoundDeviceSelectProps {
+ onChange?: (value: string | undefined) => void;
+ /** The bound device id; `undefined` picks a device automatically. */
+ value?: string;
+}
+
+/**
+ * Pick the device an MCP server that runs on the user's device always runs on,
+ * or leave it automatic. A bound device that is no longer listed (removed,
+ * unshared) stays selected as unavailable, so the user sees why its calls fail
+ * instead of the binding silently reading as automatic.
+ */
+const BoundDeviceSelect = memo<BoundDeviceSelectProps>(({ onChange, value }) => {
+ const { t } = useTranslation(['plugin', 'chat']);
+ const workspaceScoped = !!useActiveWorkspaceId();
+ const { data, error, isConfirmed, isLoading, mutate } = useDeviceList();
+ const devices = useMemo(() => bindableMcpDevices(data, workspaceScoped), [data, workspaceScoped]);
+ const deviceName = (device: DeviceListItem) =>
+ device.friendlyName || device.hostname || device.deviceId;
+
+ const renderAuto = useCallback(
+ (compact = false) => (
+ <ExecutionTargetLabel
+ compact={compact}
+ description={t('dev.mcp.boundDevice.autoDesc')}
+ label={t('dev.mcp.boundDevice.auto')}
+ offlineLabel={t('chat:heteroAgent.executionTarget.offline')}
+ onlineLabel={t('chat:heteroAgent.executionTarget.online')}
+ target={'auto'}
+ unknownLabel={t('chat:heteroAgent.executionTarget.presenceChecking')}
+ />
+ ),
+ [t],
+ );
+
+ const renderDevice = useCallback(
+ (device: DeviceListItem, compact = false) => (
+ <ExecutionTargetLabel
+ compact={compact}
+ description=""
+ device={device}
+ label={device.friendlyName || device.hostname || device.deviceId}
+ offlineLabel={t('chat:heteroAgent.executionTarget.offline')}
+ onlineLabel={t('chat:heteroAgent.executionTarget.online')}
+ target={'device'}
+ unknownLabel={t('chat:heteroAgent.executionTarget.presenceChecking')}
+ />
+ ),
+ [t],
+ );
+
+ const isMissing = !!value && isConfirmed && !devices.some((d) => d.deviceId === value);
+
+ const options = useMemo<SelectOptions<string>>(() => {
+ // Until the server confirms the list, the stored copy may hold devices
+ // since removed or unshared: show its rows, but only pick from the
+ // confirmed list.
+ const deviceOptions =
+ isLoading || (!isConfirmed && devices.length === 0)
+ ? [
+ {
+ disabled: true,
+ label: t('chat:heteroAgent.executionTarget.loading'),
+ value: `${STATUS_PREFIX}loading`,
+ },
+ ]
+ : devices.length > 0
+ ? devices.map((device) => ({
+ disabled: !isConfirmed,
+ label: renderDevice(device),
+ title: deviceName(device),
+ value: device.deviceId,
+ }))
+ : [
+ {
+ disabled: true,
+ label: workspaceScoped
+ ? t('dev.mcp.boundDevice.emptyWorkspace')
+ : t('dev.mcp.boundDevice.empty'),
+ value: `${STATUS_PREFIX}empty`,
+ },
+ ];
+
+ return [
+ { label: renderAuto(), title: t('dev.mcp.boundDevice.auto'), value: AUTO },
+ ...(isMissing
+ ? [
+ {
+ disabled: true,
+ label: t('dev.mcp.boundDevice.unavailable'),
+ title: t('dev.mcp.boundDevice.unavailable'),
+ value: value!,
+ },
+ ]
+ : []),
+ ...(error
+ ? []
+ : [
+ {
+ label: workspaceScoped
+ ? t('chat:heteroAgent.executionTarget.workspaceGroup')
+ : t('chat:heteroAgent.executionTarget.personalGroup'),
+ options: deviceOptions,
+ },
+ ]),
+ ];
+ }, [
+ devices,
+ error,
+ isConfirmed,
+ isLoading,
+ isMissing,
+ renderAuto,
+ renderDevice,
+ t,
+ value,
+ workspaceScoped,
+ ]);
+
+ return (
+ <>
+ <Select
+ classNames={executionTargetSelectClassNames}
+ optionRender={(option) => option.label}
+ options={options}
+ popupMatchSelectWidth={true}
+ style={{ width: '100%' }}
+ value={value ?? AUTO}
+ labelRender={(option) => {
+ if (option.value === AUTO) return renderAuto(true);
+ const device = devices.find((item) => item.deviceId === option.value);
+ return device ? renderDevice(device, true) : option.label;
+ }}
+ onChange={(next) => {
+ if (typeof next !== 'string' || next.startsWith(STATUS_PREFIX)) return;
+ onChange?.(next === AUTO ? undefined : next);
+ }}
+ />
+ {error ? <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} /> : null}
+ </>
+ );
+});
+
+BoundDeviceSelect.displayName = 'BoundDeviceSelect';
+
+export default BoundDeviceSelect;
diff --git a/src/features/PluginDevModal/MCPManifestForm/index.tsx b/src/features/PluginDevModal/MCPManifestForm/index.tsx
index eeea272ca8b..f1d2f921a36 100644
--- a/src/features/PluginDevModal/MCPManifestForm/index.tsx
+++ b/src/features/PluginDevModal/MCPManifestForm/index.tsx
@@ -1,4 +1,5 @@
import { type LobeToolCustomPlugin, type McpConnectVia } from '@lobechat/types';
+import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';
import { Alert, Button, Divider, Flexbox, Input, InputPassword, RadioGroup } from '@lobehub/ui';
import { type FieldPath, Form, type FormInstance, useWatch } from '@lobehub/ui/form';
import isEqual from 'fast-deep-equal';
@@ -14,6 +15,7 @@ import { mcpStoreSelectors, pluginSelectors } from '@/store/tool/selectors';
import { type McpConnectionParams, type MCPErrorInfoMetadata } from '@/types/plugins';
import ArgsInput from './ArgsInput';
+import BoundDeviceSelect from './BoundDeviceSelect';
import CollapsibleSection from './CollapsibleSection';
import MCPTypeSelect from './MCPTypeSelect';
import QuickImportSection from './QuickImportSection';
@@ -24,6 +26,12 @@ interface MCPManifestFormProps {
* OAuth flow is backed by the connector subsystem, so it must NOT show up for
* the plain custom-plugin DevModal callers (editing plugins, agent tools, …).
*/
+ /**
+ * Let a server that runs on the user's device be bound to one device. Only
+ * the custom-connector entry sets this: the binding is stored on the
+ * connector (`metadata.boundDeviceId`), which plain custom plugins don't have.
+ */
+ enableDeviceBinding?: boolean;
enableOAuth?: boolean;
form: FormInstance<LobeToolCustomPlugin>;
isEditMode?: boolean;
@@ -37,6 +45,7 @@ interface MCPManifestFormProps {
const HTTP_URL_KEY = 'customParams.mcp.url';
const CONNECT_VIA = 'customParams.mcp.connectVia';
+const BOUND_DEVICE = 'customParams.mcp.boundDeviceId';
const STDIO_COMMAND = 'customParams.mcp.command';
const STDIO_ARGS = 'customParams.mcp.args';
const STDIO_ENV = 'customParams.mcp.env';
@@ -71,6 +80,7 @@ const ConnectViaRadio = ({
const MCPManifestForm = ({
form,
isEditMode,
+ enableDeviceBinding,
enableOAuth,
onAuthorizeOAuth,
}: MCPManifestFormProps) => {
@@ -78,6 +88,12 @@ const MCPManifestForm = ({
const mcpType = useWatch(form, MCP_TYPE);
const authType = useWatch(form, AUTH_TYPE);
const connectVia = useWatch(form, CONNECT_VIA);
+ const httpUrl = useWatch(form, HTTP_URL_KEY);
+ // Only a server that runs on the user's device can be bound to one
+ const showDeviceBinding =
+ enableDeviceBinding &&
+ (mcpType === 'stdio' ||
+ (mcpType === 'http' && isDeviceOnlyMcpEndpoint({ connectVia, type: 'http', url: httpUrl })));
// For OAuth servers there is no token to test with — "testing" the connection
// means running the authorize flow instead.
const isOAuth = enableOAuth && mcpType === 'http' && authType === 'oauth2';
@@ -376,6 +392,15 @@ const MCPManifestForm = ({
</Form.Field>
</>
)}
+ {showDeviceBinding && (
+ <Form.Field
+ desc={t('dev.mcp.boundDevice.desc')}
+ label={t('dev.mcp.boundDevice.label')}
+ name={BOUND_DEVICE}
+ >
+ <BoundDeviceSelect />
+ </Form.Field>
+ )}
<Form.Field label={t('dev.mcp.testConnectionTip')} layout={'horizontal'}>
<Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>
<Button
diff --git a/src/features/PluginDevModal/index.tsx b/src/features/PluginDevModal/index.tsx
index 40c71793b42..59a70d72a13 100644
--- a/src/features/PluginDevModal/index.tsx
+++ b/src/features/PluginDevModal/index.tsx
@@ -18,6 +18,8 @@ const INITIAL_VALUES = {
} as LobeToolCustomPlugin;
interface DevModalProps {
+ /** Let a device-run server be bound to one device (connectors only, see MCPManifestForm). */
+ enableDeviceBinding?: boolean;
/** Enable the connector-backed OAuth auth type in the MCP form (see MCPManifestForm). */
enableOAuth?: boolean;
mode?: 'edit' | 'create';
@@ -41,6 +43,7 @@ const DevModal = memo<DevModalProps>(
onSave,
onOpenChange,
onDelete,
+ enableDeviceBinding,
enableOAuth,
}) => {
const isEditMode = mode === 'edit';
@@ -208,6 +211,7 @@ const DevModal = memo<DevModalProps>(
>
<Flexbox flex={3} gap={16} padding={24} style={{ overflowY: 'auto' }}>
<MCPManifestForm
+ enableDeviceBinding={enableDeviceBinding}
enableOAuth={enableOAuth}
form={form}
isEditMode={isEditMode}
diff --git a/src/features/PluginDevModal/pruneHiddenFields.test.ts b/src/features/PluginDevModal/pruneHiddenFields.test.ts
index 7695f06ffa4..90f82d2da5d 100644
--- a/src/features/PluginDevModal/pruneHiddenFields.test.ts
+++ b/src/features/PluginDevModal/pruneHiddenFields.test.ts
@@ -92,4 +92,25 @@ describe('pruneHiddenFields', () => {
expect(pruneHiddenFields(cloud)).toBe(cloud);
expect(pruneHiddenFields(legacy)).toBe(legacy);
});
+
+ it('keeps a device binding only for a server that runs on the device', () => {
+ const stdio = pruneHiddenFields(plugin({ ...stale, boundDeviceId: 'nas', type: 'stdio' }))
+ .customParams!.mcp!;
+ expect(stdio.boundDeviceId).toBe('nas');
+
+ const lan = pruneHiddenFields(
+ plugin({ ...stale, boundDeviceId: 'nas', type: 'http', url: 'http://192.168.1.10/mcp' }),
+ ).customParams!.mcp!;
+ expect(lan.boundDeviceId).toBe('nas');
+
+ const viaDevice = pruneHiddenFields(
+ plugin({ ...stale, boundDeviceId: 'nas', connectVia: 'device', type: 'http' }),
+ ).customParams!.mcp!;
+ expect(viaDevice.boundDeviceId).toBe('nas');
+
+ // Switched to a public server the cloud reaches itself
+ const publicHttp = pruneHiddenFields(plugin({ ...stale, boundDeviceId: 'nas', type: 'http' }))
+ .customParams!.mcp!;
+ expect(publicHttp).not.toHaveProperty('boundDeviceId');
+ });
});
diff --git a/src/features/PluginDevModal/pruneHiddenFields.ts b/src/features/PluginDevModal/pruneHiddenFields.ts
index af18d8ed884..8bd57c024a8 100644
--- a/src/features/PluginDevModal/pruneHiddenFields.ts
+++ b/src/features/PluginDevModal/pruneHiddenFields.ts
@@ -1,4 +1,5 @@
import { type LobeToolCustomPlugin } from '@lobechat/types';
+import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';
// The form keeps values of unmounted conditional fields, so switching transport or auth type
// would otherwise persist the abandoned branch (e.g. a bearer token after choosing "none").
@@ -6,12 +7,12 @@ export const pruneHiddenFields = (values: LobeToolCustomPlugin): LobeToolCustomP
const mcp = values.customParams?.mcp;
if (!mcp || (mcp.type !== 'http' && mcp.type !== 'stdio')) return values;
- const { args, auth, command, connectVia, env, headers, url, ...rest } = mcp;
+ const { args, auth, boundDeviceId, command, connectVia, env, headers, url, ...rest } = mcp;
let nextMcp: typeof mcp;
if (mcp.type === 'stdio') {
// Stdio always runs on the device: there is no connection to choose
- nextMcp = { ...rest, args, command, env };
+ nextMcp = { ...rest, args, ...(boundDeviceId && { boundDeviceId }), command, env };
} else {
let nextAuth = auth;
if (auth) {
@@ -22,7 +23,17 @@ export const pruneHiddenFields = (values: LobeToolCustomPlugin): LobeToolCustomP
...(auth.type === 'oauth2' && { accessToken, clientId, clientSecret }),
};
}
- nextMcp = { ...rest, auth: nextAuth, connectVia, headers, url };
+ // A device binding only applies to a server reached from the device
+ const keepsBinding =
+ !!boundDeviceId && isDeviceOnlyMcpEndpoint({ connectVia, type: 'http', url });
+ nextMcp = {
+ ...rest,
+ auth: nextAuth,
+ ...(keepsBinding && { boundDeviceId }),
+ connectVia,
+ headers,
+ url,
+ };
}
return { ...values, customParams: { ...values.customParams, mcp: nextMcp } };
diff --git a/src/helpers/mcpDeviceBinding.ts b/src/helpers/mcpDeviceBinding.ts
new file mode 100644
index 00000000000..2bf33741d34
--- /dev/null
+++ b/src/helpers/mcpDeviceBinding.ts
@@ -0,0 +1,18 @@
+import { isDesktop } from '@lobechat/const';
+
+import { getElectronStoreState } from '@/store/electron';
+
+/**
+ * Whether an MCP server bound to `boundDeviceId` must run on a device other
+ * than this client: always on the web, and on a desktop that isn't the bound
+ * device. Such a server's calls, tool listings and connection tests go through
+ * the server, which tunnels them to the bound device; this desktop's own
+ * process never runs them. Unbound servers (`undefined`) keep their routing.
+ *
+ * Compared with this desktop's personal device id: a workspace device bound on
+ * this same machine has its own id, and reaches this desktop through the
+ * gateway's workspace channel, so it is still correct (one round trip longer).
+ */
+export const runsOnAnotherDevice = (boundDeviceId: string | null | undefined): boolean =>
+ !!boundDeviceId &&
+ !(isDesktop && getElectronStoreState().gatewayDeviceInfo?.deviceId === boundDeviceId);
diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.ts
index ac90a602e08..f0c539b3452 100644
--- a/src/libs/mcp/buildConnectorManifests.ts
+++ b/src/libs/mcp/buildConnectorManifests.ts
@@ -1,6 +1,6 @@
import { buildConnectorManifest } from '@lobechat/mecha';
import type { ToolManifest } from '@lobechat/types';
-import { connectorConnectVia } from '@lobechat/utils/mcpEndpoint';
+import { connectorConnectVia, connectorDeviceBinding } from '@lobechat/utils/mcpEndpoint';
import type { DecryptedConnector } from '@/database/models/connector';
import type { UserConnectorToolItem } from '@/database/schemas';
@@ -55,9 +55,13 @@ export function buildConnectorManifests(
}
function buildMcpParams(connector: DecryptedConnector) {
+ // Only set when bound, so an unbound connector keeps the params it always
+ // had. Must match `buildConnectorMcpParams`.
+ const boundDevice = connectorDeviceBinding(connector);
if (connector.mcpConnectionType === 'stdio') {
return {
args: connector.mcpStdioConfig?.args ?? [],
+ ...(boundDevice && { boundDevice }),
command: connector.mcpStdioConfig?.command ?? '',
env: connector.mcpStdioConfig?.env,
name: connector.identifier,
@@ -86,6 +90,7 @@ function buildMcpParams(connector: DecryptedConnector) {
return {
auth,
+ ...(boundDevice && { boundDevice }),
// Only set when chosen, so `auto` keeps the params (and the MCP session
// cached by them) it always had. Must match `buildConnectorMcpParams`.
...(connectorConnectVia(connector.metadata) === 'device' && { connectVia: 'device' as const }),
diff --git a/src/libs/mcp/types.ts b/src/libs/mcp/types.ts
index 753b6efb034..78e9bf4a7aa 100644
--- a/src/libs/mcp/types.ts
+++ b/src/libs/mcp/types.ts
@@ -1,4 +1,5 @@
import type { MCPErrorType } from '@lobechat/types';
+import type { McpDeviceBinding } from '@lobechat/utils/mcpEndpoint';
interface InputSchema {
[k: string]: unknown;
@@ -135,6 +136,13 @@ export interface AuthConfig {
export interface HttpMCPClientParams {
auth?: AuthConfig;
+ /**
+ * The device this server is pinned to (`connectorDeviceBinding`): a server
+ * with a device gateway tunnels every call there, and fails when it is
+ * offline. Routing only, never read by the MCP client itself. Absent: the
+ * device is picked automatically.
+ */
+ boundDevice?: McpDeviceBinding;
/**
* `device`: the user chose to reach this server from their device; a server
* with a device gateway tunnels it there (`shouldConnectViaDevice`). Never
@@ -149,6 +157,8 @@ export interface HttpMCPClientParams {
export interface StdioMCPParams {
args: string[];
+ /** The device this server is pinned to, as on {@link HttpMCPClientParams}. */
+ boundDevice?: McpDeviceBinding;
command: string;
env?: Record<string, string>;
name: string;
diff --git a/src/services/mcp.boundDevice.test.ts b/src/services/mcp.boundDevice.test.ts
new file mode 100644
index 00000000000..5b267603e9a
--- /dev/null
+++ b/src/services/mcp.boundDevice.test.ts
@@ -0,0 +1,234 @@
+import { type ChatToolPayload } from '@lobechat/types';
+import superjson from 'superjson';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { mcpService } from './mcp';
+
+// A server bound to a device runs on that device only: this desktop runs it
+// over IPC when it IS that device, any other client (the web, another desktop)
+// leaves it to the server, which tunnels it there.
+
+const mockElectronIpc = {
+ mcp: {
+ callTool: vi.fn(),
+ getStdioMcpServerManifest: vi.fn(),
+ getStreamableMcpServerManifest: vi.fn(),
+ },
+};
+
+const environment = vi.hoisted(() => ({ deviceId: 'this-desktop', isDesktop: true }));
+
+vi.mock('@/store/electron', () => ({
+ getElectronStoreState: () => ({ gatewayDeviceInfo: { deviceId: environment.deviceId } }),
+}));
+
+vi.mock('@/store/serverConfig/store', () => ({
+ getServerConfigStoreState: () => ({
+ featureFlags: { enableMcpApps: false },
+ serverConfig: { deviceGatewayConfigured: true },
+ }),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ CURRENT_VERSION: '1.0.0',
+ get isDesktop() {
+ return environment.isDesktop;
+ },
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ connector: {
+ callTool: { mutate: vi.fn() },
+ getDeviceMcpManifest: { mutate: vi.fn() },
+ getForEdit: { query: vi.fn() },
+ getLocalCallToken: { mutate: vi.fn() },
+ },
+ },
+ toolsClient: {
+ mcp: {
+ callTool: { mutate: vi.fn() },
+ getStreamableMcpServerManifest: { query: vi.fn() },
+ },
+ },
+}));
+
+vi.mock('@/utils/electron/ipc', () => ({ ensureElectronIpc: () => mockElectronIpc }));
+
+vi.mock('./discover', () => ({
+ discoverService: {
+ reportPluginCall: vi.fn().mockResolvedValue(undefined),
+ safeInjectMPToken: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+const mockGetToolStoreState = vi.fn();
+vi.mock('@/store/tool/store', () => ({ getToolStoreState: () => mockGetToolStoreState() }));
+vi.mock('@/store/tool/selectors', () => ({
+ pluginSelectors: {
+ getCustomPluginById: () => () => undefined,
+ getInstalledPluginById: () => () => undefined,
+ },
+}));
+
+const LAN_URL = 'http://192.168.1.10:8000/mcp';
+const payload = {
+ apiName: 'list_files',
+ arguments: '{}',
+ id: 'call-1',
+ identifier: 'nas',
+ type: 'mcp',
+} as unknown as ChatToolPayload;
+
+// A LAN server: unbound, a desktop runs its calls here over IPC
+const lanConnector = (boundDeviceId?: string) => ({
+ id: 'nas-id',
+ identifier: 'nas',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: LAN_URL,
+ metadata: boundDeviceId ? { boundDeviceId } : null,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ environment.isDesktop = true;
+ environment.deviceId = 'this-desktop';
+ mockElectronIpc.mcp.callTool.mockResolvedValue(
+ superjson.serialize({ content: 'ok', success: true }),
+ );
+ mockElectronIpc.mcp.getStdioMcpServerManifest.mockResolvedValue(
+ superjson.serialize({ api: [], identifier: 'nas' }),
+ );
+});
+
+describe('a connector bound to a device', () => {
+ it('leaves a call to the server when the bound device is another machine', async () => {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ mockGetToolStoreState.mockReturnValue({ connectors: [lanConnector('office-nas')] });
+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue({
+ content: 'ok',
+ success: true,
+ } as never);
+
+ await mcpService.invokeMcpToolCall(payload, {});
+
+ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ identifier: 'nas', toolName: 'list_files' }),
+ expect.anything(),
+ );
+ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();
+ });
+
+ it('runs a call here over IPC when this desktop is the bound device', async () => {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ mockGetToolStoreState.mockReturnValue({ connectors: [lanConnector('this-desktop')] });
+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({
+ ...lanConnector('this-desktop'),
+ credentials: null,
+ tools: [{ permission: 'auto', toolName: 'list_files' }],
+ } as never);
+
+ await mcpService.invokeMcpToolCall(payload, {});
+
+ expect(mockElectronIpc.mcp.callTool).toHaveBeenCalledOnce();
+ expect(lambdaClient.connector.callTool.mutate).not.toHaveBeenCalled();
+ });
+});
+
+describe('a connector rebound since this client loaded it', () => {
+ it('leaves the call to the server when the fresh binding names another device', async () => {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ // The stored projection is still unbound, so the call looks local
+ mockGetToolStoreState.mockReturnValue({ connectors: [lanConnector()] });
+ vi.mocked(lambdaClient.connector.getForEdit.query).mockResolvedValue({
+ ...lanConnector('office-nas'),
+ credentials: null,
+ tools: [{ permission: 'auto', toolName: 'list_files' }],
+ } as never);
+ vi.mocked(lambdaClient.connector.callTool.mutate).mockResolvedValue({
+ content: 'ok',
+ success: true,
+ } as never);
+
+ await mcpService.invokeMcpToolCall(payload, {});
+
+ expect(lambdaClient.connector.callTool.mutate).toHaveBeenCalledOnce();
+ expect(mockElectronIpc.mcp.callTool).not.toHaveBeenCalled();
+ });
+});
+
+describe('testing a server bound to a device', () => {
+ it('starts a stdio server bound to another machine there, through the server', async () => {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ vi.mocked(lambdaClient.connector.getDeviceMcpManifest.mutate).mockResolvedValue({
+ api: [],
+ identifier: 'nas',
+ } as never);
+
+ await mcpService.getStdioMcpServerManifest({
+ args: ['serve'],
+ boundDeviceId: 'office-nas',
+ command: 'my-mcp',
+ name: 'nas',
+ });
+
+ expect(lambdaClient.connector.getDeviceMcpManifest.mutate).toHaveBeenCalledWith(
+ {
+ args: ['serve'],
+ boundDeviceId: 'office-nas',
+ command: 'my-mcp',
+ env: undefined,
+ identifier: 'nas',
+ metadata: undefined,
+ type: 'stdio',
+ },
+ expect.anything(),
+ );
+ expect(mockElectronIpc.mcp.getStdioMcpServerManifest).not.toHaveBeenCalled();
+ });
+
+ it('starts a stdio server bound to this desktop here, without the binding', async () => {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+
+ await mcpService.getStdioMcpServerManifest({
+ args: ['serve'],
+ boundDeviceId: 'this-desktop',
+ command: 'my-mcp',
+ name: 'nas',
+ });
+
+ const sent = superjson.deserialize(
+ mockElectronIpc.mcp.getStdioMcpServerManifest.mock.calls[0][0],
+ ) as Record<string, unknown>;
+ expect(sent).toMatchObject({ command: 'my-mcp', name: 'nas' });
+ expect(sent).not.toHaveProperty('boundDeviceId');
+ expect(lambdaClient.connector.getDeviceMcpManifest.mutate).not.toHaveBeenCalled();
+ });
+
+ it('reads a LAN server bound to a device through the server on the web', async () => {
+ const { lambdaClient, toolsClient } = await import('@/libs/trpc/client');
+ environment.isDesktop = false;
+ vi.mocked(lambdaClient.connector.getDeviceMcpManifest.mutate).mockResolvedValue({
+ api: [],
+ identifier: 'nas',
+ mcpParams: { connectVia: 'device', name: 'nas', type: 'http', url: LAN_URL },
+ } as never);
+
+ const manifest = await mcpService.getStreamableMcpServerManifest({
+ auth: { type: 'none' },
+ boundDeviceId: 'office-nas',
+ identifier: 'nas',
+ url: LAN_URL,
+ });
+
+ expect(lambdaClient.connector.getDeviceMcpManifest.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ boundDeviceId: 'office-nas', identifier: 'nas', url: LAN_URL }),
+ expect.anything(),
+ );
+ // An `auto` server keeps the params its calls send
+ expect(manifest.mcpParams).not.toHaveProperty('connectVia');
+ expect(toolsClient.mcp.getStreamableMcpServerManifest.query).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/services/mcp.ts b/src/services/mcp.ts
index fd71cc07be4..8f92fc0294a 100644
--- a/src/services/mcp.ts
+++ b/src/services/mcp.ts
@@ -17,6 +17,7 @@ import {
} from '@lobechat/types';
import { safeParseJSON } from '@lobechat/utils';
import {
+ connectorDeviceBinding,
connectorMcpEndpoint,
isDeviceOnlyMcpEndpoint,
type McpConnectVia,
@@ -28,6 +29,7 @@ import { type CallReportRequest } from '@lobehub/market-types';
import { type ReadResourceResult } from '@modelcontextprotocol/client';
import { omit } from 'es-toolkit/compat';
+import { runsOnAnotherDevice } from '@/helpers/mcpDeviceBinding';
import { type MCPToolCallResult } from '@/libs/mcp';
import { resolveLocalConnectorHttpParams } from '@/libs/mcp/localConnector';
import { renderMcpArgs, renderMcpUrlTemplate } from '@/libs/mcp/urlTemplate';
@@ -308,9 +310,11 @@ class MCPService {
connector?.mcpConnectionType !== 'stdio' &&
!!connector?.mcpServerUrl &&
isDeviceOnlyMcpEndpoint(connectorMcpEndpoint(connector));
+ // A connector bound to another device runs there, through the server
const runsHere =
connector &&
isDesktop &&
+ !runsOnAnotherDevice(connectorDeviceBinding(connector)?.deviceId) &&
((connector.mcpConnectionType === 'stdio' &&
(fromMcpApp ||
fromEntrypoint ||
@@ -320,10 +324,17 @@ class MCPService {
(isDeviceHttp && (fromMcpApp ? !!onThisDevice : true)));
// A view's calls run where its result was produced
if (fromMcpApp && !!runsHere !== !!onThisDevice) throw new Error(VIEW_SITE_MISMATCH);
- if (runsHere) {
- // Persisted connector projections omit env secrets and may be stale.
- // This protected read retains the connector's credential ownership gate.
- const detail = await lambdaClient.connector.getForEdit.query({ id: connector.id });
+ // Persisted connector projections omit env secrets and may be stale.
+ // This protected read retains the connector's credential ownership gate,
+ // and carries the current binding: a connector rebound to another device
+ // since this projection loaded runs there, through the server.
+ const detail = runsHere
+ ? await lambdaClient.connector.getForEdit.query({ id: connector.id })
+ : undefined;
+ const reboundElsewhere =
+ !!detail && runsOnAnotherDevice(connectorDeviceBinding(detail)?.deviceId);
+ if (reboundElsewhere && fromMcpApp) throw new Error(VIEW_SITE_MISMATCH);
+ if (connector && detail && !reboundElsewhere) {
if (!detail.isEnabled) throw new Error('Connector is disabled');
const tool = detail.tools.find((item) => item.toolName === apiName);
if (!tool || tool.permission === 'disabled') {
@@ -794,6 +805,11 @@ class MCPService {
token?: string;
type: 'none' | 'bearer' | 'oauth2';
};
+ /**
+ * The device a server reached from the user's device is pinned to: it is
+ * read there, through the server, unless that device is this desktop.
+ */
+ boundDeviceId?: string;
/** `device`: reach the server from the user's device, whatever its address. */
connectVia?: McpConnectVia;
headers?: Record<string, string>;
@@ -803,7 +819,22 @@ class MCPService {
},
signal?: AbortSignal,
) {
- const { connectVia, ...connection } = params;
+ const { boundDeviceId, connectVia, ...connection } = params;
+
+ if (
+ runsOnAnotherDevice(boundDeviceId) &&
+ isDeviceOnlyMcpEndpoint({ connectVia, type: 'http', url: params.url })
+ ) {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ const manifest = (await lambdaClient.connector.getDeviceMcpManifest.mutate(
+ { ...connection, boundDeviceId },
+ { signal },
+ )) as any;
+ // An `auto` server keeps the params its calls send (no `connectVia`)
+ return connectVia === 'device' || !manifest?.mcpParams
+ ? manifest
+ : { ...manifest, mcpParams: omit(manifest.mcpParams, 'connectVia') };
+ }
// A server only this machine reaches (a localhost / LAN address, or one set
// to connect through the device) is read from the desktop over IPC (main
@@ -863,6 +894,11 @@ class MCPService {
async getStdioMcpServerManifest(
stdioParams: {
args?: string[];
+ /**
+ * The device the server is pinned to: it is started there, through the
+ * server, unless that device is this desktop.
+ */
+ boundDeviceId?: string;
command: string;
env?: Record<string, string>;
name: string;
@@ -870,10 +906,26 @@ class MCPService {
metadata?: CustomPluginMetadata,
_signal?: AbortSignal,
) {
+ const { boundDeviceId, ...localParams } = stdioParams;
+ if (runsOnAnotherDevice(boundDeviceId)) {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ return lambdaClient.connector.getDeviceMcpManifest.mutate(
+ {
+ args: localParams.args ?? [],
+ boundDeviceId,
+ command: localParams.command,
+ env: localParams.env,
+ identifier: localParams.name,
+ metadata,
+ type: 'stdio',
+ },
+ { signal: _signal },
+ ) as any;
+ }
void _signal;
// Note: IPC doesn't support AbortSignal yet
// With MCP Apps on, the tools only views call are listed and kept too
- const serialized = serializeMcpIpcPayload({ ...stdioParams, mcpApps: isMcpAppsOn(), metadata });
+ const serialized = serializeMcpIpcPayload({ ...localParams, mcpApps: isMcpAppsOn(), metadata });
const serializedResult = await ensureElectronIpc().mcp.getStdioMcpServerManifest(
serialized as any,
);
diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.ts
index 7d50f9e8699..f748f211e49 100644
--- a/src/store/tool/slices/connector/action.ts
+++ b/src/store/tool/slices/connector/action.ts
@@ -1,8 +1,13 @@
import { isDesktop } from '@lobechat/const';
-import { connectorMcpEndpoint, isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';
+import {
+ connectorDeviceBinding,
+ connectorMcpEndpoint,
+ isDeviceOnlyMcpEndpoint,
+} from '@lobechat/utils/mcpEndpoint';
import type { SWRResponse } from 'swr';
import type { ConnectorToolPermission } from '@/database/schemas';
+import { runsOnAnotherDevice } from '@/helpers/mcpDeviceBinding';
import { resolveLocalConnectorHttpParams } from '@/libs/mcp/localConnector';
import {
cacheScope,
@@ -542,6 +547,8 @@ export class ConnectorActionImpl {
const isLocalHttp =
!!detail.mcpServerUrl && isDeviceOnlyMcpEndpoint(connectorMcpEndpoint(detail));
if (!isStdio && !isLocalHttp) return false;
+ // Bound to another device: the server lists it there, where its calls run
+ if (runsOnAnotherDevice(connectorDeviceBinding(detail)?.deviceId)) return false;
// The full tool list, not a manifest: a manifest leaves out view-only
// tools, yet a view's call must find its tool synced.
diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.ts
index 2f30f9e998c..48c722fed82 100644
--- a/src/store/tool/slices/mcpStore/action.ts
+++ b/src/store/tool/slices/mcpStore/action.ts
@@ -882,7 +882,9 @@ export class PluginMCPStoreActionImpl {
manifest = await mcpService.getStreamableMcpServerManifest(
{
auth: connection.auth,
- // Tested from where its calls will run: the device, when chosen
+ // Tested from where its calls will run: the bound device, or the
+ // device when chosen
+ boundDeviceId: connection.boundDeviceId,
connectVia: connection.connectVia,
headers: connection.headers,
identifier,
@@ -899,6 +901,7 @@ export class PluginMCPStoreActionImpl {
manifest = await mcpService.getStdioMcpServerManifest(
{
args: connection.args,
+ boundDeviceId: connection.boundDeviceId,
command: connection.command,
env: connection.env,
name: identifier,