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.

🐛 fix(mcp): pass install config to Market MCP servers that ignored it (#22763)

Mocha22b95ecd0d7f
diff --git a/src/libs/mcp/urlTemplate.test.ts b/src/libs/mcp/urlTemplate.test.ts
index 4f2048aacda..28fd5b26f6b 100644
--- a/src/libs/mcp/urlTemplate.test.ts
+++ b/src/libs/mcp/urlTemplate.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { renderMcpUrlTemplate } from './urlTemplate';
+import { renderMcpArgs, renderMcpUrlTemplate } from './urlTemplate';
describe('renderMcpUrlTemplate', () => {
it('fills placeholders with URL-encoded config values and reports the keys it used', () => {
@@ -39,4 +39,27 @@ describe('renderMcpUrlTemplate', () => {
usedKeys: [],
});
});
+
+ it('fills the `{{config.KEY}}` placeholders Market listings use', () => {
+ expect(
+ renderMcpUrlTemplate('https://x.dev/mcp?key={{config.API_KEY}}', { API_KEY: 'k 1' }),
+ ).toEqual({ url: 'https://x.dev/mcp?key=k%201', usedKeys: ['API_KEY'] });
+ });
+});
+
+describe('renderMcpArgs', () => {
+ it('fills placeholders in stdio args with the raw config values', () => {
+ expect(
+ renderMcpArgs(['-y', 'pkg', 'API_KEY={{config.API_KEY}}', '--team={{team}}'], {
+ API_KEY: 'a&b c',
+ team: 'core',
+ }),
+ ).toEqual(['-y', 'pkg', 'API_KEY=a&b c', '--team=core']);
+ });
+
+ it('leaves args without a value or without config untouched', () => {
+ expect(renderMcpArgs(['--key={{config.KEY}}'], { KEY: '' })).toEqual(['--key={{config.KEY}}']);
+ expect(renderMcpArgs(['--key={{config.KEY}}'])).toEqual(['--key={{config.KEY}}']);
+ expect(renderMcpArgs(undefined, { KEY: 'v' })).toBeUndefined();
+ });
});
diff --git a/src/libs/mcp/urlTemplate.ts b/src/libs/mcp/urlTemplate.ts
index 5f434062da4..d034597fd93 100644
--- a/src/libs/mcp/urlTemplate.ts
+++ b/src/libs/mcp/urlTemplate.ts
@@ -1,8 +1,24 @@
-const PLACEHOLDER = /\{\{\s*([\w.-]+)\s*\}\}/g;
+// `{{config.KEY}}` is the form Market listings use (crawler-generated args, registry remote URLs);
+// `{{KEY}}` is accepted too
+const PLACEHOLDER = /\{\{\s*(?:config\.)?([\w.-]+)\s*\}\}/g;
+
+const fillPlaceholders = (
+ template: string,
+ values: Record<string, unknown>,
+ encode: (value: string) => string,
+ usedKeys: string[] = [],
+) =>
+ template.replaceAll(PLACEHOLDER, (placeholder, key: string) => {
+ const value = values[key];
+ if (value === undefined || value === null || value === '') return placeholder;
+
+ if (!usedKeys.includes(key)) usedKeys.push(key);
+ return encode(String(value));
+ });
/**
- * Fill `{{KEY}}` placeholders in an HTTP MCP URL with the user's config values,
- * for servers that read credentials from the URL (e.g. `?apikey={{API_KEY}}`)
+ * Fill config placeholders in an HTTP MCP URL with the user's config values,
+ * for servers that read credentials from the URL (e.g. `?apikey={{config.API_KEY}}`)
* rather than from headers. Values are URL-encoded. A placeholder without a
* value is left as is.
*
@@ -12,13 +28,15 @@ export const renderMcpUrlTemplate = (url: string, values?: Record<string, unknow
const usedKeys: string[] = [];
if (!values) return { url, usedKeys };
- const rendered = url.replaceAll(PLACEHOLDER, (placeholder, key: string) => {
- const value = values[key];
- if (value === undefined || value === null || value === '') return placeholder;
+ return { url: fillPlaceholders(url, values, encodeURIComponent, usedKeys), usedKeys };
+};
- if (!usedKeys.includes(key)) usedKeys.push(key);
- return encodeURIComponent(String(value));
- });
+/**
+ * Fill config placeholders in stdio args (e.g. `API_KEY={{config.API_KEY}}`) with the
+ * raw config values. The config is still passed as env too.
+ */
+export const renderMcpArgs = (args?: string[], values?: Record<string, unknown>) => {
+ if (!args || !values) return args;
- return { url: rendered, usedKeys };
+ return args.map((arg) => fillPlaceholders(arg, values, (value) => value));
};
diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.ts
index 465c49bc15d..ce089a1ad09 100644
--- a/src/services/mcp.test.ts
+++ b/src/services/mcp.test.ts
@@ -441,6 +441,38 @@ describe('MCPService', () => {
expect(toolsClient.mcp.callTool.mutate).toHaveBeenCalled();
});
+ it('fills config placeholders in stdio args from the current settings', async () => {
+ const { toolsClient } = await import('@/libs/trpc/client');
+
+ mockPluginSelectors.getInstalledPluginById.mockReturnValue(() => ({
+ customParams: {
+ mcp: { args: ['-y', 'pkg', 'API_KEY={{config.API_KEY}}'], command: 'npx', type: 'stdio' },
+ },
+ manifest: { meta: { title: 'Stdio Plugin' }, version: '1.0.0' },
+ settings: { API_KEY: 'rotated' },
+ }));
+ vi.mocked(toolsClient.mcp.callTool.mutate).mockResolvedValue('ok' as never);
+
+ await mcpService.invokeMcpToolCall(
+ {
+ apiName: 'run',
+ arguments: '{}',
+ id: 'c2',
+ identifier: 'stdio-plugin',
+ type: 'standalone',
+ },
+ {},
+ );
+
+ expect(vi.mocked(toolsClient.mcp.callTool.mutate).mock.calls[0][0].params).toEqual({
+ args: ['-y', 'pkg', 'API_KEY=rotated'],
+ command: 'npx',
+ env: { API_KEY: 'rotated' },
+ name: 'stdio-plugin',
+ type: 'stdio',
+ });
+ });
+
it('should return undefined when plugin is not found', async () => {
mockPluginSelectors.getInstalledPluginById.mockReturnValue(() => null);
mockPluginSelectors.getCustomPluginById.mockReturnValue(() => null);
diff --git a/src/services/mcp.ts b/src/services/mcp.ts
index 19ee0d31791..5eb7478ba92 100644
--- a/src/services/mcp.ts
+++ b/src/services/mcp.ts
@@ -18,7 +18,7 @@ import { type ReadResourceResult } from '@modelcontextprotocol/client';
import { omit } from 'es-toolkit/compat';
import { type MCPToolCallResult } from '@/libs/mcp';
-import { renderMcpUrlTemplate } from '@/libs/mcp/urlTemplate';
+import { renderMcpArgs, renderMcpUrlTemplate } from '@/libs/mcp/urlTemplate';
import { getMCPConnectionErrorType } from '@/libs/mcp/utils';
import { toolsClient } from '@/libs/trpc/client';
import { serverConfigSelectors } from '@/store/serverConfig/selectors';
@@ -158,6 +158,8 @@ const buildPluginMcpParams = (
}
if (connection?.type === 'stdio') {
+ // Match the install that produced `manifest.mcpParams`: args get the settings they ask for
+ if (connection.args) params.args = renderMcpArgs(connection.args, pluginSettings);
params.env = {
...connection?.env,
...pluginSettings,
diff --git a/src/store/tool/slices/mcpStore/action.hostedConfig.test.ts b/src/store/tool/slices/mcpStore/action.hostedConfig.test.ts
new file mode 100644
index 00000000000..917aac6d221
--- /dev/null
+++ b/src/store/tool/slices/mcpStore/action.hostedConfig.test.ts
@@ -0,0 +1,168 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ReplicaModule from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import { mcpService } from '@/services/mcp';
+import { pluginService } from '@/services/plugin';
+import type { ToolStore } from '@/store/tool/store';
+
+import { createMCPPluginStoreSlice } from './action';
+
+const environment = vi.hoisted(() => ({ isDesktop: true }));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ get isDesktop() {
+ return environment.isDesktop;
+ },
+}));
+vi.mock('@/libs/replica', async (original) => ({
+ ...(await original<typeof ReplicaModule>()),
+ createReplicaSlice: () => ({}),
+}));
+vi.mock('./projection', () => ({ MCP_PLUGIN_LIST_KEY: 'all', mcpPluginListResource: {} }));
+vi.mock('@/store/tool/selectors', () => ({
+ mcpStoreSelectors: {
+ getPluginById: () => () => ({
+ haveCloudEndpoint: true,
+ identifier: 'hosted-mcp',
+ manifestUrl: 'manifest',
+ }),
+ },
+}));
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getMCPPluginManifest: vi.fn(),
+ reportMcpEvent: vi.fn(),
+ reportMcpInstallResult: vi.fn(),
+ },
+}));
+vi.mock('@/services/mcp', () => ({
+ mcpService: { checkInstallation: vi.fn(), getStdioMcpServerManifest: vi.fn() },
+}));
+vi.mock('@/services/plugin', () => ({ pluginService: { installPlugin: vi.fn() } }));
+vi.mock('@/utils/sleep', () => ({ sleep: async () => {} }));
+
+const HOSTED_URL = 'https://runtime.example.com/runtimes/hosted-mcp/invocations';
+// Market's crawler writes config placeholders into args for the client to fill
+const stdioConnection = {
+ args: ['-y', 'hosted-mcp', 'API_KEY={{config.API_KEY}}'],
+ command: 'npx',
+ type: 'stdio',
+};
+
+// The shape Market serves for a hosted plugin: its runtime URL as the recommended
+// `none` option (callable only through the cloud gateway), plus the package itself
+const manifestData = (required = ['API_KEY']) => ({
+ name: 'Hosted MCP',
+ version: '1.0.0',
+ deploymentOptions: [
+ {
+ connection: { type: 'http', url: HOSTED_URL },
+ installationMethod: 'none',
+ isRecommended: true,
+ },
+ {
+ connection: {
+ ...stdioConnection,
+ configSchema: { properties: { API_KEY: { type: 'string' } }, required, type: 'object' },
+ },
+ installationMethod: 'npm',
+ isRecommended: true,
+ },
+ ],
+});
+
+let state: ToolStore;
+let actions: ReturnType<typeof createMCPPluginStoreSlice>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ environment.isDesktop = true;
+ state = {
+ mcpInstallAbortControllers: {},
+ mcpInstallProgress: {},
+ refreshPlugins: vi.fn().mockResolvedValue(undefined),
+ updateInstallLoadingState: vi.fn(),
+ updateMCPInstallProgress: (id: string, progress: unknown) => {
+ state.mcpInstallProgress = { ...state.mcpInstallProgress, [id]: progress as never };
+ },
+ } as unknown as ToolStore;
+ actions = createMCPPluginStoreSlice(
+ (update) => {
+ state = { ...state, ...(typeof update === 'function' ? update(state) : update) };
+ },
+ () => state,
+ );
+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(manifestData() as never);
+ vi.mocked(mcpService.checkInstallation).mockResolvedValue({
+ allDependenciesMet: true,
+ connection: stdioConnection,
+ needsConfig: false,
+ success: true,
+ } as never);
+ vi.mocked(mcpService.getStdioMcpServerManifest).mockResolvedValue({
+ api: [],
+ identifier: 'hosted-mcp',
+ meta: { title: 'Hosted MCP' },
+ } as never);
+ vi.mocked(pluginService.installPlugin).mockResolvedValue(undefined);
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe('hosted MCP plugins that need user config', () => {
+ it('should run the package locally on desktop so the config reaches the server', async () => {
+ await actions.installMCPPlugin('hosted-mcp', { config: { API_KEY: 'user-key' } });
+
+ // Only the package options are checked: the hosted runtime URL is not callable directly
+ expect(mcpService.checkInstallation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ deploymentOptions: [expect.objectContaining({ installationMethod: 'npm' })],
+ }),
+ expect.any(AbortSignal),
+ );
+ expect(mcpService.getStdioMcpServerManifest).toHaveBeenCalledWith(
+ expect.objectContaining({
+ args: ['-y', 'hosted-mcp', 'API_KEY=user-key'],
+ command: 'npx',
+ env: { API_KEY: 'user-key' },
+ }),
+ expect.anything(),
+ expect.any(AbortSignal),
+ );
+ expect(pluginService.installPlugin).toHaveBeenCalledWith(
+ expect.objectContaining({
+ // The stored connection keeps the template; the key stays in settings
+ customParams: {
+ mcp: expect.objectContaining({ args: stdioConnection.args, type: 'stdio' }),
+ },
+ }),
+ );
+ });
+
+ it('should keep the cloud connection on desktop when no config is required', async () => {
+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(manifestData([]) as never);
+
+ await actions.installMCPPlugin('hosted-mcp');
+
+ expect(mcpService.checkInstallation).not.toHaveBeenCalled();
+ expect(pluginService.installPlugin).toHaveBeenCalledWith(
+ expect.objectContaining({
+ customParams: { mcp: expect.objectContaining({ type: 'cloud' }) },
+ }),
+ );
+ });
+
+ it('should keep the cloud connection on web, where packages cannot run', async () => {
+ environment.isDesktop = false;
+
+ await actions.installMCPPlugin('hosted-mcp', { config: { API_KEY: 'user-key' } });
+
+ expect(mcpService.checkInstallation).not.toHaveBeenCalled();
+ expect(pluginService.installPlugin).toHaveBeenCalledWith(
+ expect.objectContaining({
+ customParams: { mcp: expect.objectContaining({ type: 'cloud' }) },
+ }),
+ );
+ });
+});
diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.ts
index 0aaae422730..53f578e161a 100644
--- a/src/store/tool/slices/mcpStore/action.ts
+++ b/src/store/tool/slices/mcpStore/action.ts
@@ -9,7 +9,7 @@ import { gt, valid } from 'semver';
import { type MCPErrorData } from '@/libs/mcp/types';
import { parseStdioErrorMessage } from '@/libs/mcp/types';
-import { renderMcpUrlTemplate } from '@/libs/mcp/urlTemplate';
+import { renderMcpArgs, renderMcpUrlTemplate } from '@/libs/mcp/urlTemplate';
import {
createReplicaSlice,
type ReplicaLens,
@@ -363,7 +363,15 @@ export class PluginMCPStoreActionImpl {
// Web: endpoint only (stdio not supported)
const shouldUseHttpDeployment = !!httpOption;
- if (hasCloudEndpoint) {
+ // The cloud gateway sends a hosted runtime only the tool call, never the user's config.
+ // On desktop, a hosted plugin that needs config runs its package locally instead, where
+ // the config is passed as env.
+ const runHostedPackageLocally =
+ isDesktop &&
+ !!hasCloudEndpoint &&
+ doesConfigSchemaRequireInput(stdioOption?.connection?.configSchema);
+
+ if (hasCloudEndpoint && !runHostedPackageLocally) {
// Use cloudEndPoint, create cloud type connection
log('Using cloudEndPoint for stdio plugin: %s', haveCloudEndpoint);
@@ -395,7 +403,7 @@ export class PluginMCPStoreActionImpl {
updateInstallLoadingState(identifier, undefined);
return false;
}
- } else if (shouldUseHttpDeployment && httpOption) {
+ } else if (shouldUseHttpDeployment && httpOption && !runHostedPackageLocally) {
// HTTP type: skip system dependency check, use URL directly
log('HTTP MCP detected, skipping system dependency check');
@@ -438,7 +446,17 @@ export class PluginMCPStoreActionImpl {
return;
}
- result = await mcpService.checkInstallation(data, abortController.signal);
+ // A hosted plugin's `none` option is its runtime URL, not callable directly: check
+ // only the package options
+ result = await mcpService.checkInstallation(
+ runHostedPackageLocally
+ ? {
+ ...data,
+ deploymentOptions: deploymentOptions.filter((option) => !option?.connection?.url),
+ }
+ : data,
+ abortController.signal,
+ );
if (!result.success) {
updateMCPInstallProgress(identifier, undefined);
@@ -546,7 +564,8 @@ export class PluginMCPStoreActionImpl {
if (connection?.type === 'stdio') {
manifest = await mcpService.getStdioMcpServerManifest(
{
- args: connection.args,
+ // Config placeholders in args are filled here; the stored connection keeps them
+ args: renderMcpArgs(connection.args, normalizedConfig),
command: connection.command!,
env: mergedStdioEnv,
name: identifier, // Pass config as environment variables (in resume mode)