🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(mcp): fill Market HTTP MCP URL placeholders from install config (#22745)
Mochaf94b8f3ecb22
diff --git a/src/libs/mcp/urlTemplate.test.ts b/src/libs/mcp/urlTemplate.test.tsnew file mode 100644index 00000000000..4f2048aacda--- /dev/null+++ b/src/libs/mcp/urlTemplate.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';++import { renderMcpUrlTemplate } from './urlTemplate';++describe('renderMcpUrlTemplate', () => {+ it('fills placeholders with URL-encoded config values and reports the keys it used', () => {+ expect(+ renderMcpUrlTemplate('https://api.example.com/mcp?apikey={{API_KEY}}®ion={{ region }}', {+ API_KEY: 'a&b=c d',+ region: 'eu',+ X_TRACE: 'kept',+ }),+ ).toEqual({+ url: 'https://api.example.com/mcp?apikey=a%26b%3Dc%20d®ion=eu',+ usedKeys: ['API_KEY', 'region'],+ });+ });++ it('fills path segments too', () => {+ expect(+ renderMcpUrlTemplate('https://{{host}}.example.com/{{team}}/mcp', { team: 'a/b' }),+ ).toEqual({+ url: 'https://{{host}}.example.com/a%2Fb/mcp',+ usedKeys: ['team'],+ });+ });++ it('leaves placeholders without a value and URLs without placeholders untouched', () => {+ expect(renderMcpUrlTemplate('https://x.dev/mcp?k={{KEY}}', { KEY: '' })).toEqual({+ url: 'https://x.dev/mcp?k={{KEY}}',+ usedKeys: [],+ });+ expect(renderMcpUrlTemplate('https://x.dev/mcp', { KEY: 'v' })).toEqual({+ url: 'https://x.dev/mcp',+ usedKeys: [],+ });+ expect(renderMcpUrlTemplate('https://x.dev/mcp?k={{KEY}}')).toEqual({+ url: 'https://x.dev/mcp?k={{KEY}}',+ usedKeys: [],+ });+ });+});diff --git a/src/libs/mcp/urlTemplate.ts b/src/libs/mcp/urlTemplate.tsnew file mode 100644index 00000000000..5f434062da4--- /dev/null+++ b/src/libs/mcp/urlTemplate.ts@@ -0,0 +1,24 @@+const PLACEHOLDER = /\{\{\s*([\w.-]+)\s*\}\}/g;++/**+ * 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}}`)+ * rather than from headers. Values are URL-encoded. A placeholder without a+ * value is left as is.+ *+ * Returns the keys the URL used, so callers send only the rest as headers.+ */+export const renderMcpUrlTemplate = (url: string, values?: Record<string, unknown>) => {+ 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;++ if (!usedKeys.includes(key)) usedKeys.push(key);+ return encodeURIComponent(String(value));+ });++ return { url: rendered, usedKeys };+};diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.tsindex d9bcb4345e8..465c49bc15d 100644--- a/src/services/mcp.test.ts+++ b/src/services/mcp.test.ts@@ -328,6 +328,41 @@ describe('MCPService', () => {expect(discoverService.reportPluginCall).not.toHaveBeenCalled();});+ it('fills config placeholders in an HTTP plugin URL instead of sending them as headers', async () => {+ const { toolsClient } = await import('@/libs/trpc/client');++ mockPluginSelectors.getInstalledPluginById.mockReturnValue(() => ({+ customParams: {+ mcp: {+ headers: { 'X-Client': 'lobehub' },+ type: 'http',+ url: 'https://quotes.example.com/mcp?apikey={{API_KEY}}',+ },+ },+ manifest: { meta: { title: 'Quote MCP' }, version: '1.0.0' },+ settings: { API_KEY: 'rotated key', X_REGION: 'eu' },+ }));+ vi.mocked(toolsClient.mcp.callTool.mutate).mockResolvedValue('ok' as never);++ await mcpService.invokeMcpToolCall(+ {+ apiName: 'quote',+ arguments: '{}',+ id: 'c1',+ identifier: 'quote-mcp',+ type: 'standalone',+ },+ {},+ );++ expect(vi.mocked(toolsClient.mcp.callTool.mutate).mock.calls[0][0].params).toEqual({+ headers: { 'X-Client': 'lobehub', 'X_REGION': 'eu' },+ name: 'quote-mcp',+ type: 'http',+ url: 'https://quotes.example.com/mcp?apikey=rotated%20key',+ });+ });+it('should invoke tool call with custom plugin', async () => {const { toolsClient } = await import('@/libs/trpc/client');diff --git a/src/services/mcp.ts b/src/services/mcp.tsindex 0ffd72919d5..19ee0d31791 100644--- a/src/services/mcp.ts+++ b/src/services/mcp.ts@@ -15,8 +15,10 @@ import { toRecord } from '@lobechat/utils/object';import { type PluginManifest } from '@lobehub/market-sdk';import { type CallReportRequest } from '@lobehub/market-types';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 { getMCPConnectionErrorType } from '@/libs/mcp/utils';import { toolsClient } from '@/libs/trpc/client';import { serverConfigSelectors } from '@/store/serverConfig/selectors';@@ -142,7 +144,14 @@ const buildPluginMcpParams = (} as any;if (connection?.type === 'http') {- const headers = { ...connection.headers, ...pluginSettings };+ // Settings the URL asks for (`{{KEY}}`) go into the URL, matching the install+ // that produced `manifest.mcpParams`; the rest are headers+ const rendered = renderMcpUrlTemplate(connection.url ?? '', pluginSettings);+ if (connection.url) params.url = rendered.url;+ const headers = {+ ...connection.headers,+ ...(pluginSettings && omit(pluginSettings, rendered.usedKeys)),+ };// Left out when empty, as the runtime's manifest params leave it: MCP// sessions are cached by these params, so `{}` would open a second oneif (Object.keys(headers).length > 0) params.headers = headers;diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.tsindex a7260820fa4..0aaae422730 100644--- a/src/store/tool/slices/mcpStore/action.ts+++ b/src/store/tool/slices/mcpStore/action.ts@@ -3,11 +3,13 @@ import { type ToolManifest } from '@lobechat/types';import { type PluginItem } from '@lobehub/market-sdk';import { type TRPCClientError } from '@trpc/client';import debug from 'debug';+import { omit } from 'es-toolkit/compat';import { produce } from 'immer';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 {createReplicaSlice,type ReplicaLens,@@ -482,16 +484,23 @@ export class PluginMCPStoreActionImpl {}let mergedHttpHeaders: Record<string, string> | undefined;+ let httpUrl: string | undefined;let mergedStdioEnv: Record<string, string> | undefined;let mergedCloudHeaders: Record<string, string> | undefined;if (connection?.type === 'http') {const baseHeaders = toNonEmptyStringRecord(connection.headers);+ // Config values the URL asks for (`{{KEY}}`) go into the URL; the rest are headers+ const rendered = renderMcpUrlTemplate(connection.url ?? '', normalizedConfig);+ httpUrl = rendered.url;+ const headerConfig = toNonEmptyStringRecord(+ normalizedConfig && omit(normalizedConfig, rendered.usedKeys),+ );- if (baseHeaders || normalizedConfig) {+ if (baseHeaders || headerConfig) {mergedHttpHeaders = {...baseHeaders,- ...normalizedConfig,+ ...headerConfig,};}}@@ -586,7 +595,7 @@ export class PluginMCPStoreActionImpl {avatar: plugin.icon,description: plugin.description,},- url: connection.url!,+ url: httpUrl!,},abortController.signal,);diff --git a/src/store/tool/slices/mcpStore/action.urlTemplate.test.ts b/src/store/tool/slices/mcpStore/action.urlTemplate.test.tsnew file mode 100644index 00000000000..b4e25946e66--- /dev/null+++ b/src/store/tool/slices/mcpStore/action.urlTemplate.test.ts@@ -0,0 +1,120 @@+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';++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: () => () => ({ identifier: 'quote-mcp', manifestUrl: 'manifest' }),+ },+}));+vi.mock('@/services/discover', () => ({+ discoverService: {+ getMCPPluginManifest: vi.fn(),+ reportMcpEvent: vi.fn(),+ reportMcpInstallResult: vi.fn(),+ },+}));+vi.mock('@/services/mcp', () => ({ mcpService: { getStreamableMcpServerManifest: vi.fn() } }));+vi.mock('@/services/plugin', () => ({ pluginService: { installPlugin: vi.fn() } }));+vi.mock('@/utils/sleep', () => ({ sleep: async () => {} }));++const TEMPLATE_URL = 'https://quotes.example.com/mcp?apikey={{API_KEY}}';++const manifestData = {+ name: 'Quote MCP',+ version: '1.0.0',+ deploymentOptions: [+ {+ connection: {+ configSchema: {+ properties: { API_KEY: { type: 'string' }, X_REGION: { type: 'string' } },+ required: ['API_KEY'],+ type: 'object',+ },+ headers: { 'X-Client': 'lobehub' },+ type: 'http',+ url: TEMPLATE_URL,+ },+ },+ ],+};++let state: ToolStore;+let actions: ReturnType<typeof createMCPPluginStoreSlice>;++beforeEach(() => {+ vi.clearAllMocks();+ 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(+ structuredClone(manifestData) as never,+ );+ vi.mocked(mcpService.getStreamableMcpServerManifest).mockResolvedValue({+ api: [],+ identifier: 'quote-mcp',+ meta: { title: 'Quote MCP' },+ } as never);+ vi.mocked(pluginService.installPlugin).mockResolvedValue(undefined);+});+afterEach(() => vi.restoreAllMocks());++describe('marketplace HTTP MCP with config placeholders in the URL', () => {+ it('sends the config values the URL uses in the URL, and the rest as headers', async () => {+ await actions.installMCPPlugin('quote-mcp', {+ config: { API_KEY: 'k&1', X_REGION: 'eu' },+ resume: false,+ });++ expect(mcpService.getStreamableMcpServerManifest).toHaveBeenCalledWith(+ expect.objectContaining({+ headers: { 'X-Client': 'lobehub', 'X_REGION': 'eu' },+ url: 'https://quotes.example.com/mcp?apikey=k%261',+ }),+ expect.any(AbortSignal),+ );+ });++ it('stores the template URL so the key stays in settings, not in the saved connection', async () => {+ await actions.installMCPPlugin('quote-mcp', {+ config: { API_KEY: 'k&1', X_REGION: 'eu' },+ resume: false,+ });++ expect(pluginService.installPlugin).toHaveBeenCalledWith(+ expect.objectContaining({+ customParams: {+ mcp: expect.objectContaining({+ headers: { 'X-Client': 'lobehub', 'X_REGION': 'eu' },+ type: 'http',+ url: TEMPLATE_URL,+ }),+ },+ settings: { API_KEY: 'k&1', X_REGION: 'eu' },+ }),+ );+ });+});