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): tolerate prototype keys in desktop MCP IPC and parse pasted stdio commands (#18617)

Innei2a3b27a76dfd
diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.ts
index b574e3ee8f0..002aa9aedb4 100644
--- a/apps/desktop/src/main/controllers/McpCtr.ts
+++ b/apps/desktop/src/main/controllers/McpCtr.ts
@@ -3,7 +3,11 @@ import { createHash, randomUUID } from 'node:crypto';
import path from 'node:path';
import { promisify } from 'node:util';
-import superjson from 'superjson';
+import {
+ deserializeMcpIpcPayload,
+ type McpIpcPayload,
+ serializeMcpIpcPayload,
+} from '@lobechat/utils/mcpIpcPayload';
import FileService from '@/services/fileSrv';
import { createLogger } from '@/utils/logger';
@@ -106,24 +110,11 @@ export interface CallToolInput {
toolName: string;
}
-interface SuperJSONSerialized<T = unknown> {
- json: T;
- meta?: any;
-}
-
-const isSuperJSONSerialized = (value: unknown): value is SuperJSONSerialized => {
- if (!value || typeof value !== 'object') return false;
- return 'json' in value;
-};
+type SuperJSONSerialized<T = unknown> = McpIpcPayload<T>;
-const deserializePayload = <T>(payload: unknown): T => {
- // Keep backward compatibility for older renderer builds that might not serialize yet
- if (isSuperJSONSerialized(payload)) return superjson.deserialize(payload as any) as T;
- return payload as T;
-};
+const deserializePayload = deserializeMcpIpcPayload;
-const serializePayload = <T>(payload: T): SuperJSONSerialized =>
- superjson.serialize(payload) as any;
+const serializePayload = serializeMcpIpcPayload;
const safeParseToRecord = (value: unknown): Record<string, unknown> => {
if (value && typeof value === 'object' && !Array.isArray(value))
diff --git a/packages/utils/package.json b/packages/utils/package.json
index 99900fa6572..9dbf06ae4ec 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -35,6 +35,7 @@
"remark": "^15.0.1",
"remark-gfm": "^4.0.1",
"remark-html": "^16.0.1",
+ "superjson": "^2.2.6",
"tokenx": "^1.3.0",
"ua-parser-js": "^1.0.41",
"uuid": "^14.0.1",
diff --git a/packages/utils/src/mcpIpcPayload.test.ts b/packages/utils/src/mcpIpcPayload.test.ts
new file mode 100644
index 00000000000..4b98731f411
--- /dev/null
+++ b/packages/utils/src/mcpIpcPayload.test.ts
@@ -0,0 +1,49 @@
+import superjson from 'superjson';
+import { describe, expect, it } from 'vitest';
+
+import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from './mcpIpcPayload';
+
+describe('mcpIpcPayload', () => {
+ it('round-trips schemas containing prototype/constructor keys', () => {
+ const manifest = {
+ api: [
+ {
+ name: 'set_function_prototype',
+ parameters: {
+ properties: {
+ constructor: { type: 'string' },
+ prototype: { type: 'string' },
+ },
+ type: 'object',
+ },
+ },
+ ],
+ identifier: 'idalib-mcp',
+ };
+
+ expect(() => superjson.serialize(manifest)).toThrow(/prototype/);
+
+ const envelope = serializeMcpIpcPayload(manifest);
+ expect(deserializeMcpIpcPayload(envelope)).toEqual(manifest);
+ });
+
+ it('strips undefined values like superjson json output', () => {
+ const envelope = serializeMcpIpcPayload({ a: 1, b: undefined });
+ expect(envelope.json).toEqual({ a: 1 });
+ });
+
+ it('deserializes legacy superjson envelopes with meta', () => {
+ const date = new Date('2026-01-01T00:00:00.000Z');
+ const legacy = superjson.serialize({ createdAt: date, name: 'x' });
+ expect(legacy.meta).toBeTruthy();
+
+ const result = deserializeMcpIpcPayload<{ createdAt: Date; name: string }>(legacy);
+ expect(result.createdAt).toEqual(date);
+ expect(result.name).toBe('x');
+ });
+
+ it('passes through non-envelope payloads', () => {
+ expect(deserializeMcpIpcPayload({ command: 'uv' })).toEqual({ command: 'uv' });
+ expect(deserializeMcpIpcPayload(undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/utils/src/mcpIpcPayload.ts b/packages/utils/src/mcpIpcPayload.ts
new file mode 100644
index 00000000000..e3527bb6638
--- /dev/null
+++ b/packages/utils/src/mcpIpcPayload.ts
@@ -0,0 +1,18 @@
+import superjson from 'superjson';
+
+export interface McpIpcPayload<T = unknown> {
+ json: T;
+ meta?: unknown;
+}
+
+export const serializeMcpIpcPayload = <T>(payload: T): McpIpcPayload<T> => ({
+ json: JSON.parse(JSON.stringify(payload ?? null)) as T,
+});
+
+export const deserializeMcpIpcPayload = <T>(payload: unknown): T => {
+ if (!payload || typeof payload !== 'object' || !('json' in payload)) return payload as T;
+ const envelope = payload as McpIpcPayload<T>;
+ // Older builds superjson-serialize this envelope; `meta` only exists there.
+ if (envelope.meta) return superjson.deserialize(envelope as never) as T;
+ return envelope.json;
+};
diff --git a/src/components/MCPStdioCommandInput/index.tsx b/src/components/MCPStdioCommandInput/index.tsx
index b04a4f8f090..12181b46c44 100644
--- a/src/components/MCPStdioCommandInput/index.tsx
+++ b/src/components/MCPStdioCommandInput/index.tsx
@@ -11,6 +11,8 @@ import { AutoComplete, type AutoCompleteProps } from '@lobehub/ui/base-ui';
import { type FC } from 'react';
import { memo } from 'react';
+import { parseCommandInput } from './parseCommandInput';
+
// Define preset command options
const STDIO_COMMAND_OPTIONS: {
// Assuming icon is a React function component
@@ -30,19 +32,36 @@ const STDIO_COMMAND_OPTIONS: {
{ color: '#2496ED', icon: SiDocker, value: 'docker' },
];
-const MCPStdioCommandInput = memo<AutoCompleteProps>((props) => (
- <AutoComplete
- options={STDIO_COMMAND_OPTIONS.map(({ value, icon: Icon, color }) => ({
- label: (
- <Flexbox horizontal align={'center'} gap={8}>
- {Icon && <Icon color={color} size={16} />}
- {value}
- </Flexbox>
- ),
- value,
- }))}
- {...props}
- />
-));
+interface MCPStdioCommandInputProps extends AutoCompleteProps {
+ onParsedArgs?: (args: string[]) => void;
+}
+
+const MCPStdioCommandInput = memo<MCPStdioCommandInputProps>(({ onParsedArgs, ...props }) => {
+ const handleBlur = () => {
+ if (typeof props.value !== 'string') return;
+ const parsed = parseCommandInput(props.value);
+ if (!parsed) return;
+
+ props.onChange?.(parsed.command);
+ if (parsed.args.length > 0) onParsedArgs?.(parsed.args);
+ };
+
+ return (
+ <div style={{ display: 'contents' }} onBlur={handleBlur}>
+ <AutoComplete
+ options={STDIO_COMMAND_OPTIONS.map(({ value, icon: Icon, color }) => ({
+ label: (
+ <Flexbox horizontal align={'center'} gap={8}>
+ {Icon && <Icon color={color} size={16} />}
+ {value}
+ </Flexbox>
+ ),
+ value,
+ }))}
+ {...props}
+ />
+ </div>
+ );
+});
export default MCPStdioCommandInput;
diff --git a/src/components/MCPStdioCommandInput/parseCommandInput.test.ts b/src/components/MCPStdioCommandInput/parseCommandInput.test.ts
new file mode 100644
index 00000000000..68f0132e5a5
--- /dev/null
+++ b/src/components/MCPStdioCommandInput/parseCommandInput.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseCommandInput } from './parseCommandInput';
+
+describe('parseCommandInput', () => {
+ it('splits a pasted command line into command and args', () => {
+ expect(parseCommandInput('uv run idalib-mcp --stdio')).toEqual({
+ args: ['run', 'idalib-mcp', '--stdio'],
+ command: 'uv',
+ });
+ });
+
+ it('returns null for a bare command', () => {
+ expect(parseCommandInput('npx')).toBeNull();
+ expect(parseCommandInput(' npx ')).toBeNull();
+ expect(parseCommandInput('')).toBeNull();
+ });
+
+ it('keeps quoted segments as single args', () => {
+ expect(parseCommandInput('node "my server.js" --name \'a b\'')).toEqual({
+ args: ['my server.js', '--name', 'a b'],
+ command: 'node',
+ });
+ });
+});
diff --git a/src/components/MCPStdioCommandInput/parseCommandInput.ts b/src/components/MCPStdioCommandInput/parseCommandInput.ts
new file mode 100644
index 00000000000..4ee367acb44
--- /dev/null
+++ b/src/components/MCPStdioCommandInput/parseCommandInput.ts
@@ -0,0 +1,19 @@
+export interface ParsedCommandInput {
+ args: string[];
+ command: string;
+}
+
+const tokenize = (input: string): string[] =>
+ (input.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((token) =>
+ /^(["']).*\1$/.test(token) ? token.slice(1, -1) : token,
+ );
+
+export const parseCommandInput = (raw: string): ParsedCommandInput | null => {
+ const trimmed = raw.trim();
+ if (!trimmed || !/\s/.test(trimmed)) return null;
+
+ const [command, ...args] = tokenize(trimmed);
+ if (!command) return null;
+
+ return { args, command };
+};
diff --git a/src/features/MCP/MCPSettings/index.tsx b/src/features/MCP/MCPSettings/index.tsx
index 7aa5a005ea1..6dfa071a45e 100644
--- a/src/features/MCP/MCPSettings/index.tsx
+++ b/src/features/MCP/MCPSettings/index.tsx
@@ -321,7 +321,16 @@ const Settings = ({
name={'command'}
rules={[{ message: t('settings.rules.commandRequired'), required: true }]}
>
- <MCPStdioCommandInput placeholder="npx, uv, python..." />
+ <MCPStdioCommandInput
+ placeholder="npx, uv, python..."
+ onParsedArgs={(args) => {
+ const existing: string[] = connectionForm.getFieldValue('args') ?? [];
+ connectionForm.setFieldValue('args', [
+ ...args,
+ ...existing.filter(Boolean),
+ ]);
+ }}
+ />
</AForm.Item>
<AForm.Item
diff --git a/src/features/PluginDevModal/MCPManifestForm/index.tsx b/src/features/PluginDevModal/MCPManifestForm/index.tsx
index 01bdd885511..66dae8e639f 100644
--- a/src/features/PluginDevModal/MCPManifestForm/index.tsx
+++ b/src/features/PluginDevModal/MCPManifestForm/index.tsx
@@ -340,7 +340,13 @@ const MCPManifestForm = ({
rules={[{ message: t('dev.mcp.command.required'), required: true }]}
tag={'command'}
>
- <MCPStdioCommandInput placeholder={t('dev.mcp.command.placeholder')} />
+ <MCPStdioCommandInput
+ placeholder={t('dev.mcp.command.placeholder')}
+ onParsedArgs={(args) => {
+ const existing: string[] = form.getFieldValue(STDIO_ARGS) ?? [];
+ form.setFieldValue(STDIO_ARGS, [...args, ...existing.filter(Boolean)]);
+ }}
+ />
</FormItem>
<FormItem
desc={t('dev.mcp.args.desc')}
diff --git a/src/services/mcp.ts b/src/services/mcp.ts
index 427ccaa2633..2bbf1e6bb11 100644
--- a/src/services/mcp.ts
+++ b/src/services/mcp.ts
@@ -5,9 +5,9 @@ import {
type CustomPluginMetadata,
} from '@lobechat/types';
import { isLocalOrPrivateUrl, safeParseJSON } from '@lobechat/utils';
+import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utils/mcpIpcPayload';
import { type PluginManifest } from '@lobehub/market-sdk';
import { type CallReportRequest } from '@lobehub/market-types';
-import superjson from 'superjson';
import { type MCPToolCallResult } from '@/libs/mcp';
import { toolsClient } from '@/libs/trpc/client';
@@ -124,7 +124,7 @@ class MCPService {
const data = {
// For desktop IPC, always pass a record/object for tool "arguments"
- // (IPC layer will superjson serialize the whole payload).
+ // (IPC layer serializes the whole payload into a JSON envelope).
args: isDesktop && isStdio ? (safeParseJSON(args) ?? {}) : args,
env: connection?.type === 'stdio' ? params.env : (pluginSettings ?? connection?.env),
meta,
@@ -158,9 +158,9 @@ class MCPService {
} else if (isDesktop && isStdio) {
// For desktop and stdio, use IPC (main process)
// Note: IPC doesn't support AbortSignal yet
- const serialized = superjson.serialize(data);
+ const serialized = serializeMcpIpcPayload(data);
const serializedResult = await ensureElectronIpc().mcp.callTool(serialized as any);
- result = superjson.deserialize(serializedResult as any) as any;
+ result = deserializeMcpIpcPayload(serializedResult) as any;
} else {
// For other types, use the toolsClient
result = await toolsClient.mcp.callTool.mutate(data, { signal });
@@ -237,11 +237,11 @@ class MCPService {
// This avoids accessing user local services through remote server in production
if (isDesktop && isLocalOrPrivateUrl(params.url)) {
// Note: IPC doesn't support AbortSignal yet
- const serialized = superjson.serialize(params);
+ const serialized = serializeMcpIpcPayload(params);
const serializedResult = await ensureElectronIpc().mcp.getStreamableMcpServerManifest(
serialized as any,
);
- return superjson.deserialize(serializedResult as any) as any;
+ return deserializeMcpIpcPayload(serializedResult) as any;
}
// Otherwise use toolsClient (via server relay)
@@ -260,11 +260,11 @@ class MCPService {
) {
void _signal;
// Note: IPC doesn't support AbortSignal yet
- const serialized = superjson.serialize({ ...stdioParams, metadata });
+ const serialized = serializeMcpIpcPayload({ ...stdioParams, metadata });
const serializedResult = await ensureElectronIpc().mcp.getStdioMcpServerManifest(
serialized as any,
);
- return superjson.deserialize(serializedResult as any) as any;
+ return deserializeMcpIpcPayload(serializedResult) as any;
}
/**
@@ -280,13 +280,13 @@ class MCPService {
void _signal;
// Pass all deployment options to main process for checking
// Note: IPC doesn't support AbortSignal yet
- const serialized = superjson.serialize({
+ const serialized = serializeMcpIpcPayload({
deploymentOptions: manifest.deploymentOptions as any,
});
const serializedResult = await ensureElectronIpc().mcp.validMcpServerInstallable(
serialized as any,
);
- return superjson.deserialize(serializedResult as any) as any;
+ return deserializeMcpIpcPayload(serializedResult) as any;
}
}