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): redact sensitive log metadata (#21423)

YuTengjing9cc0cfbba4b8
diff --git a/apps/server/src/services/mcp/contentProcessor.test.ts b/apps/server/src/services/mcp/contentProcessor.test.ts
index d078ddc8aa2..47a39229940 100644
--- a/apps/server/src/services/mcp/contentProcessor.test.ts
+++ b/apps/server/src/services/mcp/contentProcessor.test.ts
@@ -1,9 +1,15 @@
+import { inspect } from 'node:util';
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type ToolCallContent } from '@/libs/mcp';
import { contentBlocksToString, processContentBlocks } from './contentProcessor';
+const debugLog = vi.hoisted(() => vi.fn());
+
+vi.mock('debug', () => ({ default: () => debugLog }));
+
describe('contentProcessor', () => {
describe('contentBlocksToString', () => {
it('should return empty string for null input', () => {
@@ -172,6 +178,34 @@ describe('contentProcessor', () => {
);
});
+ it('should not log resource or uploaded URL credentials', async () => {
+ mockFileService.uploadBase64.mockResolvedValue({
+ url: 'https://storage.example/proxy-path-secret?signature=proxy-query-secret',
+ fileId: 'file-secret-log-test',
+ key: 'mcp/images/2025-01-01/secret.png',
+ });
+
+ const blocks: ToolCallContent[] = [
+ {
+ type: 'resource',
+ resource: {
+ blob: 'resourceImageBase64==',
+ mimeType: 'image/png',
+ uri: 'https://remote.example/resource-path-secret?token=resource-query-secret',
+ },
+ },
+ ];
+
+ await processContentBlocks(blocks, mockFileService);
+
+ const logOutput = inspect(debugLog.mock.calls, { depth: null });
+ expect(logOutput).toContain("mediaType: 'image'");
+ expect(logOutput).not.toContain('resource-path-secret');
+ expect(logOutput).not.toContain('resource-query-secret');
+ expect(logOutput).not.toContain('proxy-path-secret');
+ expect(logOutput).not.toContain('proxy-query-secret');
+ });
+
it('should convert resource audio blobs to uploaded audio content', async () => {
mockFileService.uploadBase64.mockResolvedValue({
url: 'https://example.com/f/resource-audio',
diff --git a/apps/server/src/services/mcp/contentProcessor.ts b/apps/server/src/services/mcp/contentProcessor.ts
index fed74d77d53..da4ae006746 100644
--- a/apps/server/src/services/mcp/contentProcessor.ts
+++ b/apps/server/src/services/mcp/contentProcessor.ts
@@ -99,7 +99,7 @@ export const processContentBlocks = async (
today,
});
- log(`Image uploaded, proxy URL: ${url}`);
+ log('MCP media uploaded: %O', { mediaType: 'image' });
return { ...block, data: url, mimeType };
}
@@ -115,7 +115,7 @@ export const processContentBlocks = async (
today,
});
- log(`Audio uploaded, proxy URL: ${url}`);
+ log('MCP media uploaded: %O', { mediaType: 'audio' });
return { ...block, data: url, mimeType };
}
@@ -137,7 +137,7 @@ export const processContentBlocks = async (
today,
});
- log(`Resource ${mediaType} uploaded (${resource.uri}), proxy URL: ${url}`);
+ log('MCP media uploaded: %O', { mediaType });
// Convert to native media content so downstream renderers/model adapters handle it visually.
const metadata = resourceBlock._meta ? { _meta: resourceBlock._meta } : {};
diff --git a/apps/server/src/services/mcp/deps/MCPSystemDepsCheckService.test.ts b/apps/server/src/services/mcp/deps/MCPSystemDepsCheckService.test.ts
index 784c3628b88..9e0be428bbf 100644
--- a/apps/server/src/services/mcp/deps/MCPSystemDepsCheckService.test.ts
+++ b/apps/server/src/services/mcp/deps/MCPSystemDepsCheckService.test.ts
@@ -6,8 +6,9 @@ import { mcpSystemDepsCheckService } from './MCPSystemDepsCheckService';
import { type InstallationChecker } from './types';
// Hoist the mock to ensure it's available in the factory
-const { mockExecPromise } = vi.hoisted(() => {
+const { debugLog, mockExecPromise } = vi.hoisted(() => {
return {
+ debugLog: vi.fn(),
mockExecPromise: vi.fn(),
};
});
@@ -15,6 +16,8 @@ const { mockExecPromise } = vi.hoisted(() => {
// Mock node:child_process
vi.mock('node:child_process');
+vi.mock('debug', () => ({ default: () => debugLog }));
+
// Mock node:util to return our hoisted mock when promisify is called
vi.mock('node:util', () => ({
default: {
@@ -227,6 +230,26 @@ describe('MCPSystemDepsCheckService', () => {
expect(result.error).toBe('command not found');
});
+ it('should not log check commands or execution error messages', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const mockDependency: SystemDependency = {
+ name: 'private-tool',
+ checkCommand: 'private-tool --token command-secret-marker',
+ };
+
+ mockExecPromise.mockRejectedValue(new Error('execution-error-secret-marker'));
+
+ await mcpSystemDepsCheckService.checkSystemDependency(mockDependency);
+
+ const logOutput = JSON.stringify([debugLog.mock.calls, consoleError.mock.calls]);
+ expect(logOutput).toContain('private-tool');
+ expect(logOutput).toContain('Error');
+ expect(logOutput).not.toContain('command-secret-marker');
+ expect(logOutput).not.toContain('execution-error-secret-marker');
+
+ consoleError.mockRestore();
+ });
+
it('should handle unknown error types', async () => {
const mockDependency: SystemDependency = {
name: 'tool',
@@ -422,6 +445,33 @@ describe('MCPSystemDepsCheckService', () => {
expect(result.configSchema).toBeDefined();
});
+ it('should not log deployment configuration schema values', async () => {
+ const mockOption: DeploymentOption = {
+ installationMethod: 'npm',
+ installationDetails: { packageName: 'test-package' },
+ connection: {
+ args: ['index.js'],
+ command: 'node',
+ configSchema: {
+ properties: {
+ apiKey: {
+ description: 'config-schema-secret-marker',
+ required: true,
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ },
+ } as any;
+
+ await mcpSystemDepsCheckService.checkDeployOption(mockOption);
+
+ const logOutput = JSON.stringify(debugLog.mock.calls);
+ expect(logOutput).toContain('needsConfig');
+ expect(logOutput).not.toContain('config-schema-secret-marker');
+ });
+
it('should detect configuration requirements from property-level required flag', async () => {
const mockOption: DeploymentOption = {
installationMethod: 'npm',
diff --git a/apps/server/src/services/mcp/deps/MCPSystemDepsCheckService.ts b/apps/server/src/services/mcp/deps/MCPSystemDepsCheckService.ts
index 31895b2d28a..60c790b5654 100644
--- a/apps/server/src/services/mcp/deps/MCPSystemDepsCheckService.ts
+++ b/apps/server/src/services/mcp/deps/MCPSystemDepsCheckService.ts
@@ -4,6 +4,7 @@ import { promisify } from 'node:util';
import { type DeploymentOption, type SystemDependency } from '@lobehub/market-sdk';
import debug from 'debug';
+import { getMCPErrorLogMetadata } from '@/libs/mcp/utils';
import { type SystemDependencyCheckResult } from '@/types/plugins';
import { type InstallationChecker } from './types';
@@ -62,7 +63,7 @@ class MCPSystemDepsCheckService {
try {
// If check command not provided, use generic command
const checkCommand = dependency.checkCommand || `${dependency.name} --version`;
- log(`Checking system dependency: ${dependency.name}, command: ${checkCommand}`);
+ log('Checking MCP system dependency: %s', dependency.name);
const { stdout, stderr } = await execPromise(checkCommand);
if (stderr && !stdout) {
@@ -130,9 +131,11 @@ class MCPSystemDepsCheckService {
}
}
- log(
- `System dependency check result: ${dependency.name}, installed: ${true}, meets requirement: ${meetRequirement}, version: ${version}`,
- );
+ log('MCP system dependency check completed: %O', {
+ installed: true,
+ meetRequirement,
+ name: dependency.name,
+ });
return {
installInstructions: getCurrentPlatformInstructions(
(dependency as any).installInstructions,
@@ -144,7 +147,10 @@ class MCPSystemDepsCheckService {
version,
};
} catch (error) {
- log(`System dependency check error: ${dependency.name}, ${error}`);
+ console.error('MCP system dependency check failed:', {
+ dependency: dependency.name,
+ error: getMCPErrorLogMetadata(error),
+ });
return {
error: error instanceof Error ? error.message : 'Unknown error',
installInstructions: getCurrentPlatformInstructions(
@@ -206,10 +212,7 @@ class MCPSystemDepsCheckService {
Object.values(configSchema.properties).some((prop: any) => prop.required === true))),
);
- log(
- `Configuration check result: needsConfig=${needsConfig}, required=${configSchema?.required}, configSchema=%O`,
- configSchema,
- );
+ log('MCP deployment configuration check completed: %O', { needsConfig });
// Create connection info
const connection = option.connection.url
diff --git a/apps/server/src/services/mcp/index.test.ts b/apps/server/src/services/mcp/index.test.ts
index a2ca4bed187..9842a382104 100644
--- a/apps/server/src/services/mcp/index.test.ts
+++ b/apps/server/src/services/mcp/index.test.ts
@@ -1,13 +1,16 @@
+import { inspect } from 'node:util';
+
import type * as LobeConst from '@lobechat/const';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { TRPCError } from '@trpc/server';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { MCPClient } from '@/libs/mcp';
+import { MCPClient, type MCPClientParams } from '@/libs/mcp';
import { MCPService } from './index';
const environment = vi.hoisted(() => ({ isDesktop: false }));
+const debugLog = vi.hoisted(() => vi.fn());
vi.mock('@lobechat/const', async (importOriginal) => ({
...(await importOriginal<typeof LobeConst>()),
@@ -16,9 +19,61 @@ vi.mock('@lobechat/const', async (importOriginal) => ({
},
}));
+vi.mock('debug', () => ({ default: () => debugLog }));
+
// Mock 依赖
vi.mock('@/libs/mcp');
+const sensitiveHttpParams = {
+ auth: {
+ accessToken: 'oauth-access-token-secret',
+ clientSecret: 'oauth-client-secret',
+ refreshToken: 'oauth-refresh-token-secret',
+ token: 'bearer-token-secret',
+ type: 'oauth2' as const,
+ },
+ headers: {
+ 'Authorization': 'Bearer authorization-header-secret',
+ 'Cookie': 'session=cookie-header-secret',
+ 'X-Api-Key': 'custom-header-secret',
+ },
+ metadata: {
+ nested: {
+ auth: { token: 'nested-auth-secret' },
+ env: { PRIVATE_KEY: 'nested-env-secret' },
+ headers: { Cookie: 'nested-cookie-secret' },
+ },
+ },
+ name: 'remote-connector',
+ type: 'http' as const,
+ url: 'https://url-user:[email protected]/path-token-secret?api_key=url-query-secret#fragment-secret',
+} as unknown as MCPClientParams;
+
+const sensitiveValues = [
+ 'oauth-access-token-secret',
+ 'oauth-client-secret',
+ 'oauth-refresh-token-secret',
+ 'bearer-token-secret',
+ 'authorization-header-secret',
+ 'cookie-header-secret',
+ 'custom-header-secret',
+ 'nested-auth-secret',
+ 'nested-env-secret',
+ 'nested-cookie-secret',
+ 'url-user',
+ 'url-password',
+ 'path-token-secret',
+ 'url-query-secret',
+ 'fragment-secret',
+ 'remote-generated-secret',
+];
+
+const expectLogsToBeRedacted = (logOutput: string) => {
+ for (const sensitiveValue of sensitiveValues) {
+ expect(logOutput).not.toContain(sensitiveValue);
+ }
+};
+
describe('MCPService stdio authorization', () => {
const stdioParams = {
args: ['serve'],
@@ -77,6 +132,114 @@ describe('MCPService stdio authorization', () => {
});
});
+describe('MCPService log redaction', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ environment.isDesktop = false;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ {
+ invoke: (service: MCPService) => service.listTools(sensitiveHttpParams),
+ operationName: 'listing tools',
+ },
+ {
+ invoke: (service: MCPService) => service.listResources(sensitiveHttpParams),
+ operationName: 'listing resources',
+ },
+ {
+ invoke: (service: MCPService) => service.listPrompts(sensitiveHttpParams),
+ operationName: 'listing prompts',
+ },
+ {
+ invoke: (service: MCPService) =>
+ service.callTool({
+ argsStr: '{}',
+ clientParams: sensitiveHttpParams,
+ toolName: 'read_records',
+ }),
+ operationName: 'calling tool "read_records"',
+ },
+ ])('redacts credentials when $operationName fails', async ({ invoke, operationName }) => {
+ const service = new MCPService();
+ const failure = new Error('Connection failed with remote-generated-secret');
+ const mockClient = {
+ callTool: vi.fn().mockRejectedValue(failure),
+ listPrompts: vi.fn().mockRejectedValue(failure),
+ listResources: vi.fn().mockRejectedValue(failure),
+ listTools: vi.fn().mockRejectedValue(failure),
+ };
+ vi.spyOn(service as any, 'getClient').mockResolvedValue(mockClient);
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(invoke(service)).rejects.toThrow(TRPCError);
+
+ const logOutput = inspect([debugLog.mock.calls, consoleError.mock.calls], { depth: null });
+ expectLogsToBeRedacted(logOutput);
+ expect(logOutput).toContain(operationName);
+ expect(logOutput).toContain('attempt');
+ expect(logOutput).toContain('https://mcp.example.com');
+ expect(logOutput).toContain("type: 'http'");
+ });
+
+ it('redacts credentials from client initialization failures', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(MCPClient.prototype.initialize).mockRejectedValueOnce(
+ new Error('Initialization failed with remote-generated-secret'),
+ );
+
+ await expect(new MCPService().listRawTools(sensitiveHttpParams)).rejects.toThrow(TRPCError);
+
+ const logOutput = inspect([debugLog.mock.calls, consoleError.mock.calls], { depth: null });
+ expectLogsToBeRedacted(logOutput);
+ expect(logOutput).toContain('https://mcp.example.com');
+ expect(logOutput).toContain("name: 'Error'");
+ });
+
+ it('redacts stdio environment variables from rejected server operations', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(
+ new MCPService().listRawTools({
+ args: ['serve'],
+ command: 'local-mcp',
+ env: { PRIVATE_KEY: 'stdio-env-secret' },
+ name: 'local-connector',
+ type: 'stdio',
+ }),
+ ).rejects.toThrow(TRPCError);
+
+ const logOutput = inspect([debugLog.mock.calls, consoleError.mock.calls], { depth: null });
+ expect(logOutput).not.toContain('stdio-env-secret');
+ expect(logOutput).toContain("type: 'stdio'");
+ });
+
+ it('does not log tool argument or result values', async () => {
+ const service = new MCPService();
+ const mockClient = {
+ callTool: vi.fn().mockResolvedValue({
+ content: [{ text: 'tool-result-secret', type: 'text' }],
+ }),
+ };
+ vi.spyOn(service as any, 'getClient').mockResolvedValue(mockClient);
+
+ await service.callTool({
+ argsStr: JSON.stringify({ apiKey: 'tool-argument-secret' }),
+ clientParams: sensitiveHttpParams,
+ toolName: 'read_records',
+ });
+
+ const logOutput = inspect(debugLog.mock.calls, { depth: null });
+ expect(logOutput).not.toContain('tool-argument-secret');
+ expect(logOutput).not.toContain('tool-result-secret');
+ expectLogsToBeRedacted(logOutput);
+ });
+});
+
describe('MCPService', () => {
let mcpService: any;
let mockClient: any;
diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.ts
index 03b61b02b41..82a9165a223 100644
--- a/apps/server/src/services/mcp/index.ts
+++ b/apps/server/src/services/mcp/index.ts
@@ -21,6 +21,7 @@ import {
type StdioMCPParams,
} from '@/libs/mcp';
import { MCPClient } from '@/libs/mcp';
+import { getMCPErrorLogMetadata, getMCPLogOrigin } from '@/libs/mcp/utils';
import { type ProcessContentBlocksFn } from './contentProcessor';
import { contentBlocksToString } from './contentProcessor';
@@ -28,6 +29,11 @@ import { mcpSystemDepsCheckService } from './deps';
const log = debug('lobe-mcp:service');
+interface MCPConnectionLogMetadata {
+ origin?: string;
+ type: MCPClientParams['type'];
+}
+
/**
* MCP Tool call raw result type
*/
@@ -82,11 +88,15 @@ export class MCPService {
return { content, state, success: true };
}
- private sanitizeForLogging = <T extends Record<string, any>>(obj: T): Omit<T, 'env'> => {
- if (!obj) return obj;
+ /**
+ * Keep MCP logs allowlist-only so future connection fields cannot silently expose credentials.
+ */
+ private getConnectionLogMetadata = (params: MCPClientParams): MCPConnectionLogMetadata => {
+ if (params.type === 'http') {
+ return { origin: getMCPLogOrigin(params.url), type: params.type };
+ }
- const { env: _, ...rest } = obj;
- return rest as Omit<T, 'env'>;
+ return { type: params.type };
};
/**
@@ -104,13 +114,14 @@ export class MCPService {
operationName: string,
operation: (client: MCPClient) => Promise<T>,
): Promise<T> {
- const loggableParams = this.sanitizeForLogging(params);
+ const connection = this.getConnectionLogMetadata(params);
return retry(
async (bail, attemptNumber) => {
// Skip cache on retry attempts to drop the stale (dead) session
const skipCache = attemptNumber > 1;
- log(`${operationName} for params: %O (attempt ${attemptNumber})`, loggableParams);
+ const operationLog = { attempt: attemptNumber, connection, operation: operationName };
+ log('MCP operation attempt: %O', operationLog);
try {
// Keep getClient inside the guarded block: a client initialization
@@ -122,7 +133,10 @@ export class MCPService {
} catch (error) {
// Only retry for NoValidSessionId errors
if ((error as Error).message !== 'NoValidSessionId') {
- console.error(`Error ${operationName} for params %O:`, loggableParams, error);
+ console.error('MCP operation failed:', {
+ ...operationLog,
+ error: getMCPErrorLogMetadata(error),
+ });
bail(
error instanceof TRPCError
? error
@@ -203,7 +217,7 @@ export class MCPService {
const args = safeParseJSON(argsStr);
return this.withSessionRetry(clientParams, `calling tool "${toolName}"`, async (client) => {
- log(`Calling tool "${toolName}" with args: %O`, args);
+ log('Calling MCP tool: %s', toolName);
try {
// Delegate the call to the MCPClient instance
@@ -215,7 +229,13 @@ export class MCPService {
processContentBlocksFn,
);
- log(`Tool "${toolName}" called successfully, result: %O`, processedResult.state);
+ log('MCP tool call completed: %O', {
+ contentBlockCount: Array.isArray(processedResult.state.content)
+ ? processedResult.state.content.length
+ : 0,
+ isError: processedResult.state.isError === true,
+ toolName,
+ });
return processedResult;
} catch (error) {
@@ -260,6 +280,7 @@ export class MCPService {
return this.clients.get(key)!;
}
+ const connection = this.getConnectionLogMetadata(params);
log(`No cached client found, Initializing new client.`);
try {
const client = new MCPClient(params);
@@ -269,10 +290,11 @@ export class MCPService {
},
}); // Initialization logic should be within MCPClient
this.clients.set(key, client);
- log(`New client initialized and cached for key: ${key.slice(0, 20)}`);
+ log('New MCP client initialized and cached: %O', connection);
return client;
} catch (error) {
- console.error(`Failed to initialize MCP client:`, error);
+ const errorLog = getMCPErrorLogMetadata(error);
+ console.error('Failed to initialize MCP client:', { connection, error: errorLog });
// Preserve complete error information, especially detailed stderr output
const errorMessage = error instanceof Error ? error.message : String(error);
@@ -287,9 +309,8 @@ export class MCPService {
// Log detailed error information for debugging
log('Detailed initialization error: %O', {
- error: errorMessage,
- params: this.sanitizeForLogging(params),
- stack: error instanceof Error ? error.stack : undefined,
+ connection,
+ error: errorLog,
});
throw new TRPCError({
@@ -407,10 +428,10 @@ export class MCPService {
deploymentOptions: DeploymentOption[];
}): Promise<CheckMcpInstallResult> {
try {
- const loggableInput = {
- deploymentOptions: input.deploymentOptions.map((o) => this.sanitizeForLogging(o)),
- };
- log('Checking MCP plugin installation status: %O', loggableInput);
+ log(
+ 'Checking MCP plugin installation status for %d option(s)',
+ input.deploymentOptions.length,
+ );
const results = [];
// Check each deployment option
@@ -427,7 +448,12 @@ export class MCPService {
// Return the recommended result, or the first installable result, or the first result
const bestResult = recommendedResult || firstInstallableResult || results[0];
- log('Check completed, best result: %O', bestResult);
+ log('MCP plugin installation check completed: %O', {
+ allDependenciesMet: bestResult?.allDependenciesMet === true,
+ hasResult: Boolean(bestResult),
+ isRecommended: bestResult?.isRecommended === true,
+ needsConfig: bestResult?.needsConfig === true,
+ });
// Construct return result, ensure configuration check information is included
const checkResult: CheckMcpInstallResult = {
@@ -441,12 +467,12 @@ export class MCPService {
if (bestResult?.needsConfig) {
checkResult.needsConfig = true;
checkResult.configSchema = bestResult.configSchema;
- log('Configuration required for best deployment option: %O', bestResult.configSchema);
+ log('Configuration is required for the selected MCP deployment option');
}
return checkResult;
} catch (error) {
- log('Check failed: %O', error);
+ log('MCP plugin installation check failed: %O', getMCPErrorLogMetadata(error));
return {
error:
error instanceof Error
diff --git a/src/libs/mcp/__tests__/index.test.ts b/src/libs/mcp/__tests__/index.test.ts
index 85120321ee1..3e00127fac4 100644
--- a/src/libs/mcp/__tests__/index.test.ts
+++ b/src/libs/mcp/__tests__/index.test.ts
@@ -1,10 +1,15 @@
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
+import { inspect } from 'node:util';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MCPClient } from '../index';
+const debugLog = vi.hoisted(() => vi.fn());
+
+vi.mock('debug', () => ({ default: () => debugLog }));
+
const require = createRequire(import.meta.url);
const mcpHelloWorldRoot = dirname(require.resolve('mcp-hello-world/package.json'));
/** Local stdio entry (see mcp-hello-world `bin`); avoids `npx` so npm never reads this repo's overrides. */
@@ -242,4 +247,131 @@ describe('MCPClient', () => {
await expect(client.listPrompts()).rejects.toThrow('NoValidSessionId');
});
});
+
+ describe('Log redaction', () => {
+ const remoteErrorSecret = 'remote-generated-secret';
+ const remoteErrorCodeSecret = 'remote-error-code-secret';
+ const remoteErrorNameSecret = 'remote-error-name-secret';
+ const sensitiveConnection = {
+ auth: {
+ accessToken: 'oauth-access-token-secret',
+ refreshToken: 'oauth-refresh-token-secret',
+ type: 'oauth2' as const,
+ },
+ headers: {
+ Authorization: 'Bearer authorization-header-secret',
+ Cookie: 'session=cookie-header-secret',
+ },
+ name: 'HTTP Test Connection',
+ type: 'http' as const,
+ url: 'https://url-user:[email protected]/path-token-secret?api_key=query-token-secret#fragment-token-secret',
+ };
+ const sensitiveValues = [
+ remoteErrorSecret,
+ remoteErrorCodeSecret,
+ remoteErrorNameSecret,
+ 'oauth-access-token-secret',
+ 'oauth-refresh-token-secret',
+ 'authorization-header-secret',
+ 'cookie-header-secret',
+ 'url-user',
+ 'url-password',
+ 'path-token-secret',
+ 'query-token-secret',
+ 'fragment-token-secret',
+ ];
+
+ const buildClient = (mcp: Record<string, unknown>) => {
+ const client = new MCPClient(sensitiveConnection);
+ (client as any).mcp = mcp;
+ return client;
+ };
+
+ const expectLogsToBeRedacted = (consoleError: ReturnType<typeof vi.spyOn>) => {
+ const logOutput = inspect([debugLog.mock.calls, consoleError.mock.calls], { depth: null });
+ for (const sensitiveValue of sensitiveValues) {
+ expect(logOutput).not.toContain(sensitiveValue);
+ }
+ expect(logOutput).toContain('https://example.com');
+ return logOutput;
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('redacts connection and remote error details during initialization', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const remoteError = Object.assign(new Error(remoteErrorSecret), {
+ code: remoteErrorCodeSecret,
+ name: remoteErrorNameSecret,
+ });
+ const client = buildClient({
+ connect: vi.fn().mockRejectedValue(remoteError),
+ });
+
+ await expect(client.initialize()).rejects.toThrow(remoteErrorSecret);
+
+ const logOutput = expectLogsToBeRedacted(consoleError);
+ expect(logOutput).toContain("name: 'Error'");
+ });
+
+ it.each([
+ {
+ invoke: (client: MCPClient) => client.listTools(),
+ method: 'listTools',
+ },
+ {
+ invoke: (client: MCPClient) => client.listResources(),
+ method: 'listResources',
+ },
+ {
+ invoke: (client: MCPClient) => client.listPrompts(),
+ method: 'listPrompts',
+ },
+ ])('redacts remote errors from $method logs', async ({ invoke, method }) => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const client = buildClient({
+ [method]: vi.fn().mockRejectedValue(new Error(remoteErrorSecret)),
+ });
+
+ await expect(invoke(client)).resolves.toEqual([]);
+
+ expectLogsToBeRedacted(consoleError);
+ });
+
+ it('does not log tool argument or result values', async () => {
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const client = buildClient({
+ callTool: vi.fn().mockResolvedValue({
+ content: [{ text: 'tool-result-secret', type: 'text' }],
+ }),
+ });
+
+ await client.callTool('read_records', { apiKey: 'tool-argument-secret' });
+
+ const logOutput = expectLogsToBeRedacted(consoleError);
+ expect(logOutput).not.toContain('tool-argument-secret');
+ expect(logOutput).not.toContain('tool-result-secret');
+ });
+
+ it('does not log stdio args or environment values', () => {
+ new MCPClient({
+ args: ['--token', 'stdio-argument-secret'],
+ command: 'local-mcp',
+ env: { PRIVATE_KEY: 'stdio-env-secret' },
+ name: 'Stdio Test Connection',
+ type: 'stdio',
+ });
+
+ const logOutput = inspect(debugLog.mock.calls, { depth: null });
+ expect(logOutput).not.toContain('stdio-argument-secret');
+ expect(logOutput).not.toContain('stdio-env-secret');
+ expect(logOutput).toContain('stdio transport');
+ });
+ });
});
diff --git a/src/libs/mcp/client.ts b/src/libs/mcp/client.ts
index 6a61c09cd19..ddba45babed 100644
--- a/src/libs/mcp/client.ts
+++ b/src/libs/mcp/client.ts
@@ -19,6 +19,7 @@ import {
type ToolCallResult,
} from './types';
import { createMCPError } from './types';
+import { getMCPErrorLogMetadata, getMCPLogOrigin } from './utils';
const log = debug('lobe-mcp:client');
// MCP tool call timeout (milliseconds), configurable via the environment variable MCP_TOOL_TIMEOUT, default is 60000
@@ -40,7 +41,7 @@ async function preCheckStdioCommand(params: {
success: boolean;
}> {
return new Promise((resolve) => {
- log('Pre-checking stdio command: %s with args: %O', params.command, params.args);
+ log('Pre-checking stdio command');
// Do NOT spread the full process.env here: it would leak server-side secrets
// (DATABASE_URL, KEY_VAULTS_SECRET, provider API keys, OAuth/JWT secrets, ...)
@@ -58,7 +59,6 @@ async function preCheckStdioCommand(params: {
stdio: ['pipe', 'pipe', 'pipe'],
});
- let stdout = '';
let stderr = '';
let resolved = false;
@@ -81,22 +81,19 @@ async function preCheckStdioCommand(params: {
}
}, 5000);
- // Collect stdout
- child.stdout?.on('data', (data) => {
- stdout += data.toString();
- });
+ child.stdout?.resume();
// Collect stderr - this is the critical part
child.stderr?.on('data', (data) => {
stderr += data.toString();
- log('Captured stderr: %s', data.toString());
+ log('Captured stdio stderr output');
});
child.on('error', (error) => {
if (!resolved) {
resolved = true;
clearTimeout(timeout);
- log('Process spawn error: %O', error);
+ console.error('MCP pre-check process spawn failed:', getMCPErrorLogMetadata(error));
resolve({
error: createMCPError('PROCESS_SPAWN_ERROR', 'Failed to start MCP service process', {
originalError: error.message,
@@ -117,10 +114,13 @@ async function preCheckStdioCommand(params: {
clearTimeout(timeout);
if (code === 0) {
- log('Pre-check successful, stdout: %s', stdout);
+ log('MCP pre-check completed successfully');
resolve({ success: true });
} else {
- log('Pre-check failed with code: %d, stderr: %s', code, stderr);
+ console.error('MCP pre-check process exited:', {
+ exitCode: code,
+ signal,
+ });
resolve({
error: createMCPError('CONNECTION_FAILED', 'MCP service startup failed', {
errorLog: stderr,
@@ -156,7 +156,7 @@ async function preCheckStdioCommand(params: {
child.stdin?.write(initMessage);
child.stdin?.end();
} catch (writeError) {
- log('Failed to write to stdin: %O', writeError);
+ console.error('Failed to write MCP pre-check request:', getMCPErrorLogMetadata(writeError));
}
});
}
@@ -172,7 +172,10 @@ export class MCPClient {
switch (params.type) {
case 'http': {
- log('Using HTTP transport with url: %s', params.url);
+ log('Using HTTP transport: %O', {
+ origin: getMCPLogOrigin(params.url),
+ type: params.type,
+ });
// Build headers, including custom headers and authentication information
const headers: Record<string, string> = { ...params.headers };
@@ -207,13 +210,13 @@ export class MCPClient {
requestInit: { headers },
});
- log('HTTP transport created with headers: %O', Object.keys(headers));
+ log('HTTP transport created with %d header(s)', Object.keys(headers).length);
break;
}
case 'stdio': {
- log('Using Stdio transport with command: %s , args: %O', params.command, params.args);
+ log('Using stdio transport');
this.transport = new StdioClientTransport({
args: params.args,
@@ -234,7 +237,7 @@ export class MCPClient {
params: { type: (params as any).type },
},
);
- log('Error creating client: %O', err);
+ console.error('Failed to create MCP client:', getMCPErrorLogMetadata(err));
throw err;
}
}
@@ -247,7 +250,7 @@ export class MCPClient {
await this.mcp.connect(this.transport, { onprogress: options.onProgress });
log('MCP connection initialized.');
} catch (e) {
- log('MCP connection failed:', e);
+ console.error('MCP connection failed:', getMCPErrorLogMetadata(e));
if (this.params.type === 'http') {
// StreamableHTTPError carries the status in code, not necessarily in its message.
@@ -268,7 +271,10 @@ export class MCPClient {
});
if (!preCheckResult.success && preCheckResult.error) {
- log('Detailed error captured: %O', preCheckResult.error);
+ console.error(
+ 'MCP stdio pre-check failed:',
+ getMCPErrorLogMetadata(preCheckResult.error),
+ );
throw preCheckResult.error;
}
}
@@ -335,10 +341,10 @@ export class MCPClient {
try {
log('Listing tools...');
const { tools } = await this.mcp.listTools();
- log('Listed tools: %O', tools);
+ log('Listed %d MCP tool(s)', tools.length);
return tools as McpTool[];
} catch (e) {
- console.error('Listed tools error: %O', e);
+ console.error('Failed to list MCP tools:', getMCPErrorLogMetadata(e));
if (MCPClient.isNoValidSessionError(e)) {
throw new Error('NoValidSessionId', { cause: e });
@@ -352,10 +358,10 @@ export class MCPClient {
try {
log('Listing resources...');
const { resources } = await this.mcp.listResources();
- log('Listed resources: %O', resources);
+ log('Listed %d MCP resource(s)', resources.length);
return resources as McpResource[];
} catch (e) {
- log('Listed resources: %O', e);
+ console.error('Failed to list MCP resources:', getMCPErrorLogMetadata(e));
if (MCPClient.isNoValidSessionError(e)) {
throw new Error('NoValidSessionId', { cause: e });
@@ -369,10 +375,10 @@ export class MCPClient {
try {
log('Listing prompts...');
const { prompts } = await this.mcp.listPrompts();
- log('Listed prompts: %O', prompts);
+ log('Listed %d MCP prompt(s)', prompts.length);
return prompts as McpPrompt[];
} catch (e) {
- log('Listed prompts: %O', e);
+ console.error('Failed to list MCP prompts:', getMCPErrorLogMetadata(e));
if (MCPClient.isNoValidSessionError(e)) {
throw new Error('NoValidSessionId', { cause: e });
@@ -383,8 +389,7 @@ export class MCPClient {
}
async listManifests() {
- const capabilities = this.mcp.getServerCapabilities();
- log('get capabilities: %O', capabilities);
+ log('Reading MCP server capabilities');
const [tools, prompts, resources] = await Promise.all([
this.listTools(),
@@ -400,18 +405,26 @@ export class MCPClient {
version: this.mcp.getServerVersion()?.version?.replace('v', ''),
};
- log('Listed Manifest: %O', manifest);
+ log('Listed MCP manifest: %O', {
+ promptCount: prompts.length,
+ resourceCount: resources.length,
+ toolCount: tools.length,
+ });
return manifest;
}
async callTool(toolName: string, args: any): Promise<ToolCallResult> {
- log('Calling tool: %s with args: %O, timeout: %O', toolName, args, MCP_TOOL_TIMEOUT);
+ log('Calling MCP tool: %O', { timeout: MCP_TOOL_TIMEOUT, toolName });
try {
const result = await this.mcp.callTool({ arguments: args, name: toolName }, undefined, {
timeout: MCP_TOOL_TIMEOUT,
});
- log('Tool call result: %O', result);
+ log('MCP tool call completed: %O', {
+ contentBlockCount: Array.isArray(result.content) ? result.content.length : 0,
+ isError: result.isError === true,
+ toolName,
+ });
return result as ToolCallResult;
} catch (e) {
// The server rejects the request before executing the tool, so retrying
diff --git a/src/libs/mcp/utils.ts b/src/libs/mcp/utils.ts
index a03286d201a..1a59b15e483 100644
--- a/src/libs/mcp/utils.ts
+++ b/src/libs/mcp/utils.ts
@@ -1,3 +1,5 @@
+import { isRecord } from '@lobechat/utils/object';
+
import type { ToolCRUDType } from '@/database/schemas';
// Prefix-based matching (anchored at ^) handles camelCase names like getReactions, listPins.
@@ -7,6 +9,36 @@ const UPDATE_PREFIX = /^(?:update|edit|modify|patch|set|change|rename|move)/;
const READ_PREFIX =
/^(?:get|list|read|fetch|search|find|check|describe|show|view|extract|query|count)/;
+export interface MCPErrorLogMetadata {
+ code?: number;
+ name: string;
+}
+
+/**
+ * Error messages and objects are untrusted remote data, so MCP logs only keep fixed metadata.
+ */
+export const getMCPErrorLogMetadata = (error: unknown): MCPErrorLogMetadata => {
+ const errorRecord = isRecord(error) ? error : undefined;
+ const rawCode = errorRecord?.code;
+ const code = typeof rawCode === 'number' ? rawCode : undefined;
+
+ return {
+ code,
+ name: error instanceof Error ? 'Error' : typeof error,
+ };
+};
+
+/**
+ * URL paths can contain session keys or signed values, so logs retain the origin only.
+ */
+export const getMCPLogOrigin = (endpoint: string): string | undefined => {
+ try {
+ return new URL(endpoint).origin;
+ } catch {
+ return undefined;
+ }
+};
+
/**
* Infer the CRUD operation type from an MCP tool name.
*