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.

24.1 KB
Raw Blame
import { spawn } from 'node:child_process';

import { BRANDING_NAME } from '@lobechat/business-const';
import type { McpUiToolMeta } from '@lobechat/const/mcpApp';
import {
  getMcpToolVisibility,
  isMcpToolVisibleTo,
  resolveMcpUiToolMeta,
} from '@lobechat/const/mcpApp';
import { toRecord } from '@lobechat/utils/object';
import {
  Client,
  InsufficientScopeError,
  SdkError,
  SdkErrorCode,
  SdkHttpError,
  StreamableHTTPClientTransport,
  UnauthorizedError,
} from '@modelcontextprotocol/client';
import { type Progress, type Transport } from '@modelcontextprotocol/client';
import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import debug from 'debug';

import { getEventsCapability } from './events/capability';
import { createMcpEventError } from './events/errors';
import { nameHeaderFetch } from './events/nameHeaderFetch';
import type {
  McpEventType,
  McpSubscribeEventParams,
  McpUnsubscribeEventParams,
} from './events/schema';
import {
  MCP_EVENTS_EXTENSION_ID,
  McpListEventsResultSchema,
  McpSubscribeEventParamsSchema,
  McpSubscribeEventResultSchema,
  McpUnsubscribeEventParamsSchema,
  McpUnsubscribeEventResultSchema,
} from './events/schema';
import { getToolUiResourceUri, isToolVisibleToApp, MCP_APPS_CLIENT_CAPABILITIES } from './mcpApp';
import { createMCPSSRFBlockedError, isMCPSSRFBlockedError, mcpSsrfSafeFetch } from './ssrf';
import {
  type MCPClientParams,
  type MCPError,
  type McpPrompt,
  type McpResource,
  type McpTool,
  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
// Parse MCP_TOOL_TIMEOUT, only use if it's a valid positive number, otherwise fallback to default 60000
const MCP_TOOL_TIMEOUT = (() => {
  const val = Number(process.env.MCP_TOOL_TIMEOUT);
  return Number.isFinite(val) && val > 0 ? val : 60_000;
})();
// How long a failed tool listing counts as "no views" before the next result lists again
const UI_RESOURCE_LIST_RETRY_MS = 60_000;

/**
 * A request the SSRF policy refused is a configuration error, never a transient
 * or empty result: surface it as the structured `SSRF_BLOCKED` error.
 */
const throwIfSSRFBlocked = (e: unknown) => {
  if (isMCPSSRFBlockedError(e)) throw createMCPSSRFBlockedError(e);
};

/**
 * Pre-check stdio command to capture detailed error information
 */
async function preCheckStdioCommand(params: {
  args: string[];
  command: string;
  env?: Record<string, string>;
}): Promise<{
  error?: MCPError;
  success: boolean;
}> {
  return new Promise((resolve) => {
    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, ...)
    // into the spawned MCP subprocess. Match the main StdioClientTransport below,
    // which only exposes the safe default environment plus user-configured vars.
    // The cast is required because this repo augments NodeJS.ProcessEnv with
    // required app keys that a restricted env intentionally omits.
    const env = {
      ...getDefaultEnvironment(),
      ...params.env,
    } as NodeJS.ProcessEnv;

    const child = spawn(params.command, params.args, {
      env,
      stdio: ['pipe', 'pipe', 'pipe'],
    });

    let stderr = '';
    let resolved = false;

    // Set timeout (5 seconds)
    const timeout = setTimeout(() => {
      if (!resolved) {
        resolved = true;
        child.kill('SIGTERM');
        resolve({
          error: createMCPError('INITIALIZATION_TIMEOUT', 'MCP service initialization timeout', {
            errorLog: stderr || 'No stderr output',
            params: {
              args: params.args,
              command: params.command,
            },
            step: 'precheck_timeout',
          }),
          success: false,
        });
      }
    }, 5000);

    child.stdout?.resume();

    // Collect stderr - this is the critical part
    child.stderr?.on('data', (data) => {
      stderr += data.toString();
      log('Captured stdio stderr output');
    });

    child.on('error', (error) => {
      if (!resolved) {
        resolved = true;
        clearTimeout(timeout);
        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,
            params: {
              args: params.args,
              command: params.command,
            },
            step: 'process_spawn',
          }),
          success: false,
        });
      }
    });

    child.on('exit', (code, signal) => {
      if (!resolved) {
        resolved = true;
        clearTimeout(timeout);

        if (code === 0) {
          log('MCP pre-check completed successfully');
          resolve({ success: true });
        } else {
          console.error('MCP pre-check process exited:', {
            exitCode: code,
            signal,
          });
          resolve({
            error: createMCPError('CONNECTION_FAILED', 'MCP service startup failed', {
              errorLog: stderr,
              params: {
                args: params.args,
                command: params.command,
              },
              process: {
                exitCode: code || undefined,
                signal: signal || undefined,
              },
              step: 'process_exit',
            }),
            success: false,
          });
        }
      }
    });

    // Send a simple JSON-RPC initialization message to test the connection
    try {
      const initMessage =
        JSON.stringify({
          id: 1,
          jsonrpc: '2.0',
          method: 'initialize',
          params: {
            clientInfo: { name: 'lobe-mcp-precheck', version: '1.0.0' },
            protocolVersion: '2024-11-05',
          },
        }) + '\n';

      child.stdin?.write(initMessage);
      child.stdin?.end();
    } catch (writeError) {
      console.error('Failed to write MCP pre-check request:', getMCPErrorLogMetadata(writeError));
    }
  });
}

export interface MCPClientOptions {
  /**
   * Advertise MCP Apps (SEP-1865) during `initialize`, so servers expose their
   * interactive views. Off: the client announces itself as it did before MCP
   * Apps, and servers answer as they would any other client.
   */
  mcpApps?: boolean;
  /** Advertise SEP-3415 and enable webhook subscription requests. */
  mcpEvents?: boolean;
}

export class MCPClient {
  private mcp: Client;
  private transport: Transport;
  private params: MCPClientParams;
  private mcpEvents: boolean;
  private rawDiscoverCapabilities?: unknown;
  /** tool name → `ui://` resource URI, filled from the last successful `listTools` */
  private uiResourceUris?: Map<string, string>;
  private readonly mcpApps: boolean;
  private toolUiMeta?: Map<string, McpUiToolMeta>;
  /**
   * The tools a view may call (`_meta.ui.visibility` with "app", or unset), from
   * the same listing. An allow-list: a name the listing didn't name is refused.
   */
  private appVisibleTools?: Set<string>;
  /** Tools only views may call (`_meta.ui.visibility` without "model"), from the same listing */
  private modelHiddenTools?: Set<string>;
  /** When the last `getToolUiResourceUri` listing failed, while no listing has succeeded */
  private uiResourceListFailedAt?: number;

  constructor(
    params: MCPClientParams,
    { mcpApps = false, mcpEvents = false }: MCPClientOptions = {},
  ) {
    this.mcpApps = mcpApps;
    this.params = params;
    this.mcpEvents = mcpEvents;
    this.mcp = new Client(
      { name: 'lobehub-mcp-client', version: '1.0.0' },
      {
        ...(mcpApps || mcpEvents
          ? {
              capabilities: {
                extensions: {
                  ...(mcpApps ? MCP_APPS_CLIENT_CAPABILITIES.extensions : {}),
                  ...(mcpEvents ? { [MCP_EVENTS_EXTENSION_ID]: {} } : {}),
                },
              },
            }
          : {}),
        // Stdio stays legacy: auto would spawn a sibling probe process and can
        // wait the entire probe timeout on servers that ignore unknown requests.
        versionNegotiation: { mode: params.type === 'http' ? 'auto' : 'legacy' },
        // No elicitation/sampling/roots handlers are registered by this host.
        inputRequired: { autoFulfill: false },
      },
    );
    // A server whose tools changed (a view's visibility, its `ui://` resource)
    // voids what its last listing taught; the next lookup lists them again
    this.mcp.setNotificationHandler('notifications/tools/list_changed', () =>
      this.forgetToolListing(),
    );

    switch (params.type) {
      case 'http': {
        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 };

        // Handle authentication configuration
        if (params.auth) {
          switch (params.auth.type) {
            case 'bearer': {
              if (params.auth.token) {
                headers['Authorization'] = `Bearer ${params.auth.token}`;
                log('Added Bearer token authentication');
              }
              break;
            }
            case 'oauth2': {
              if (params.auth.accessToken) {
                headers['Authorization'] = `Bearer ${params.auth.accessToken}`;
                log('Added OAuth2 access token authentication');
              }
              break;
            }

            default: {
              // No authentication required
              break;
            }
          }
        }

        // Create StreamableHTTPClientTransport and pass headers. Every request
        // it makes (including redirects and OAuth) goes through the SSRF-safe
        // fetch: this client runs on the server, never on the user's device.
        // MCP Events wraps that same fetch to add the Mcp-Name header, so it never
        // trades the SSRF guard for the header.
        this.transport = new StreamableHTTPClientTransport(new URL(params.url), {
          fetch: mcpEvents
            ? nameHeaderFetch(mcpSsrfSafeFetch, (capabilities) => {
                this.rawDiscoverCapabilities = capabilities;
              })
            : mcpSsrfSafeFetch,
          requestInit: { headers },
        });

        log('HTTP transport created with %d header(s)', Object.keys(headers).length);

        break;
      }

      case 'stdio': {
        log('Using stdio transport');

        this.transport = new StdioClientTransport({
          args: params.args,
          command: params.command,
          env: {
            ...getDefaultEnvironment(),
            ...params.env,
          },
        });
        break;
      }

      default: {
        const err = createMCPError(
          'VALIDATION_ERROR',
          `Unsupported MCP connection type: ${(params as any).type}`,
          {
            params: { type: (params as any).type },
          },
        );
        console.error('Failed to create MCP client:', getMCPErrorLogMetadata(err));
        throw err;
      }
    }
  }

  async initialize(options: { onProgress?: (progress: Progress) => void } = {}) {
    log('Initializing MCP connection...');

    try {
      await this.mcp.connect(this.transport, { onprogress: options.onProgress });
      log('MCP connection initialized.');
    } catch (e) {
      console.error('MCP connection failed:', getMCPErrorLogMetadata(e));

      if (this.params.type === 'http') {
        throwIfSSRFBlocked(e);

        if (
          (SdkHttpError.isInstance(e) && (e.status === 401 || e.status === 403)) ||
          UnauthorizedError.isInstance(e) ||
          InsufficientScopeError.isInstance(e)
        )
          throw createMCPError(
            'AUTHORIZATION_ERROR',
            'MCP server authorization failed. Reconnect this MCP in your connector settings and try again.',
            { originalError: e.message },
          );

        if (SdkError.isInstance(e) && e.code === SdkErrorCode.RequestTimeout)
          throw createMCPError(
            'INITIALIZATION_TIMEOUT',
            'MCP server version negotiation timed out. Check the server connection and try again.',
          );

        if (SdkError.isInstance(e) && e.code === SdkErrorCode.EraNegotiationFailed)
          throw createMCPError(
            'CONNECTION_FAILED',
            `Could not negotiate the MCP server protocol: ${e.message}`,
          );

        throw e;
      }

      // For stdio connection failure, attempt to pre-check command to get detailed error information
      if (this.params.type === 'stdio') {
        log('Attempting to pre-check stdio command for detailed error information...');

        const preCheckResult = await preCheckStdioCommand({
          args: this.params.args,
          command: this.params.command,
          env: this.params.env,
        });

        if (!preCheckResult.success && preCheckResult.error) {
          console.error(
            'MCP stdio pre-check failed:',
            getMCPErrorLogMetadata(preCheckResult.error),
          );
          throw preCheckResult.error;
        }
      }

      // For other connection types or when pre-check doesn't provide more information
      if (SdkError.isInstance(e) && e.code === SdkErrorCode.ConnectionClosed) {
        throw createMCPError(
          'CONNECTION_FAILED',
          'Failed to connect to MCP server, please check your configuration',
          {
            originalError: (e as Error).message,
            params: {
              args: this.params.args,
              command: this.params.command,
              type: this.params.type,
            },
            step: 'mcp_connect',
          },
        );
      }

      // Wrap other unknown errors
      throw createMCPError('UNKNOWN_ERROR', (e as Error).message, {
        originalError: (e as Error).message,
        params: {
          args: this.params.args,
          command: this.params.command,
          type: this.params.type,
        },
        step: 'mcp_connect',
      });
    }
  }

  async disconnect() {
    await this.mcp.close();
    log('MCP connection disconnected.');
  }

  getProtocolEra() {
    return this.mcp.getProtocolEra();
  }

  getEventsCapability() {
    if (!this.mcpEvents) return { supported: false };
    return getEventsCapability(
      this.rawDiscoverCapabilities ?? this.mcp.getServerCapabilities(),
      this.getProtocolEra(),
    );
  }

  private assertEventsCapability() {
    if (!this.getEventsCapability().supported) {
      throw createMCPError(
        'VALIDATION_ERROR',
        'MCP Events Unsupported: this connection does not support events',
      );
    }
  }

  async listEvents(): Promise<McpEventType[]> {
    this.assertEventsCapability();
    const events: McpEventType[] = [];
    const cursors = new Set<string>();
    let cursor: string | undefined;
    try {
      do {
        const page = await this.mcp.request(
          { method: 'events/list', params: cursor ? { cursor } : {} },
          McpListEventsResultSchema,
          { timeout: MCP_TOOL_TIMEOUT },
        );
        events.push(...page.events);
        cursor = page.nextCursor;
        if (cursor) {
          if (cursors.has(cursor))
            throw createMCPError(
              'VALIDATION_ERROR',
              'MCP events/list returned a repeated pagination cursor',
            );
          cursors.add(cursor);
        }
      } while (cursor);
      return events;
    } catch (error) {
      if (this.isNoValidSessionError(error)) throw new Error('NoValidSessionId', { cause: error });
      throw createMcpEventError(error);
    }
  }

  async subscribeEvent(input: McpSubscribeEventParams) {
    this.assertEventsCapability();
    try {
      return await this.mcp.request(
        { method: 'events/subscribe', params: McpSubscribeEventParamsSchema.parse(input) },
        McpSubscribeEventResultSchema,
        { timeout: MCP_TOOL_TIMEOUT },
      );
    } catch (error) {
      if (this.isNoValidSessionError(error)) throw new Error('NoValidSessionId', { cause: error });
      throw createMcpEventError(error);
    }
  }

  async unsubscribeEvent(input: McpUnsubscribeEventParams) {
    this.assertEventsCapability();
    try {
      return await this.mcp.request(
        { method: 'events/unsubscribe', params: McpUnsubscribeEventParamsSchema.parse(input) },
        McpUnsubscribeEventResultSchema,
        { timeout: MCP_TOOL_TIMEOUT },
      );
    } catch (error) {
      if (this.isNoValidSessionError(error)) throw new Error('NoValidSessionId', { cause: error });
      throw createMcpEventError(error);
    }
  }

  /**
   * Detect the StreamableHTTP "session expired" error.
   *
   * Happens when the remote MCP server restarts: the cached client still sends
   * the old session id and the server rejects it with HTTP 404. The legacy
   * example-server message is also recognized. Callers (e.g. MCPService) surface this as a dedicated
   * `NoValidSessionId` error and retry with a freshly-initialized session.
   */
  private isNoValidSessionError(e: unknown): boolean {
    return (
      this.getProtocolEra() !== 'modern' &&
      ((SdkHttpError.isInstance(e) && e.status === 404) ||
        (e instanceof Error && e.message.includes('No valid session ID provided')))
    );
  }

  async listTools() {
    try {
      log('Listing tools...');
      const { tools } = await this.mcp.listTools();
      this.toolUiMeta = this.mcpApps
        ? new Map(tools.map((tool) => [tool.name, resolveMcpUiToolMeta(tool._meta)]))
        : undefined;
      this.uiResourceUris = new Map(
        tools.flatMap((tool) => {
          const uri = getToolUiResourceUri(tool, this.mcpApps);
          return uri ? [[tool.name, uri] as const] : [];
        }),
      );
      this.appVisibleTools = new Set(
        tools.filter((tool) => isToolVisibleToApp(tool, this.mcpApps)).map((tool) => tool.name),
      );
      this.modelHiddenTools = new Set(
        tools
          .filter(
            (tool) => !isMcpToolVisibleTo(getMcpToolVisibility(tool._meta, this.mcpApps), 'model'),
          )
          .map((tool) => tool.name),
      );
      log('Listed %d MCP tool(s)', tools.length);
      return (
        this.mcpApps
          ? tools.map((tool) => ({
              ...tool,
              icons: tool.icons ?? this.mcp.getServerVersion()?.icons,
            }))
          : tools
      ) as McpTool[];
    } catch (e) {
      console.error('Failed to list MCP tools:', getMCPErrorLogMetadata(e));
      throwIfSSRFBlocked(e);

      if (this.isNoValidSessionError(e)) {
        throw new Error('NoValidSessionId', { cause: e });
      }

      return [];
    }
  }

  async listResources() {
    try {
      log('Listing resources...');
      const { resources } = await this.mcp.listResources();
      log('Listed %d MCP resource(s)', resources.length);
      return resources as McpResource[];
    } catch (e) {
      console.error('Failed to list MCP resources:', getMCPErrorLogMetadata(e));
      throwIfSSRFBlocked(e);

      if (this.isNoValidSessionError(e)) {
        throw new Error('NoValidSessionId', { cause: e });
      }

      return [];
    }
  }

  async listPrompts() {
    try {
      log('Listing prompts...');
      const { prompts } = await this.mcp.listPrompts();
      log('Listed %d MCP prompt(s)', prompts.length);
      return prompts as McpPrompt[];
    } catch (e) {
      console.error('Failed to list MCP prompts:', getMCPErrorLogMetadata(e));
      throwIfSSRFBlocked(e);

      if (this.isNoValidSessionError(e)) {
        throw new Error('NoValidSessionId', { cause: e });
      }

      return [];
    }
  }

  async listManifests() {
    log('Reading MCP server capabilities');

    const [tools, prompts, resources] = await Promise.all([
      this.listTools(),
      this.listPrompts(),
      this.listResources(),
    ]);

    const manifest = {
      prompts: prompts.length === 0 ? undefined : prompts,
      resources: resources.length === 0 ? undefined : resources,
      title: this.mcp.getServerVersion()?.title,
      tools: tools.length === 0 ? undefined : tools,
      version: this.mcp.getServerVersion()?.version?.replace('v', ''),
    };

    log('Listed MCP manifest: %O', {
      promptCount: prompts.length,
      resourceCount: resources.length,
      toolCount: tools.length,
    });

    return manifest;
  }

  /**
   * The MCP Apps `ui://` resource a tool renders its result with, if any.
   * Lists tools once per client to learn it. A failed listing counts as "no
   * views" for `UI_RESOURCE_LIST_RETRY_MS` instead of being retried on every
   * call, then the next call lists again. On the server nothing else refreshes
   * the map: manifests are listed on a separate client without MCP Apps.
   */
  async getToolUiMeta(toolName: string) {
    if (!this.mcpApps) return undefined;
    await this.ensureToolUiListed();
    return this.toolUiMeta?.get(toolName);
  }

  async getToolUiResourceUri(toolName: string): Promise<string | undefined> {
    await this.ensureToolUiListed();

    return this.uiResourceUris?.get(toolName);
  }

  /**
   * Whether a view may call `toolName`: the listing named it, with a
   * `_meta.ui.visibility` that includes "app" or is unset. Unknown while the
   * tools can't be listed, which counts as no: a view's call is refused rather
   * than run unchecked.
   */
  async isToolCallableByApp(toolName: string): Promise<boolean> {
    await this.ensureToolUiListed();
    return !!this.appVisibleTools?.has(toolName);
  }

  /**
   * Whether the server keeps `toolName` from the model (`_meta.ui.visibility`
   * without "model"): only its views may call it. Unknown while the tools
   * can't be listed, which counts as no, so the model's calls keep running.
   */
  async isToolHiddenFromModel(toolName: string): Promise<boolean> {
    await this.ensureToolUiListed();

    return !!this.modelHiddenTools?.has(toolName);
  }

  private forgetToolListing() {
    this.uiResourceUris = undefined;
    this.toolUiMeta = undefined;
    this.appVisibleTools = undefined;
    this.modelHiddenTools = undefined;
    this.uiResourceListFailedAt = undefined;
  }

  /** List tools once per client for their MCP Apps metadata; see {@link getToolUiResourceUri}. */
  private async ensureToolUiListed() {
    const failedAt = this.uiResourceListFailedAt;
    if (
      !this.uiResourceUris &&
      (failedAt === undefined || Date.now() - failedAt >= UI_RESOURCE_LIST_RETRY_MS)
    ) {
      await this.listTools();
      this.uiResourceListFailedAt = this.uiResourceUris ? undefined : Date.now();
    }
  }

  async readResource(uri: string) {
    log('Reading resource: %s', uri);
    try {
      return await this.mcp.readResource({ uri });
    } catch (e) {
      throwIfSSRFBlocked(e);
      if (this.isNoValidSessionError(e)) {
        throw new Error('NoValidSessionId', { cause: e });
      }
      throw e;
    }
  }

  async callTool(toolName: string, args: any): Promise<ToolCallResult> {
    log('Calling MCP tool: %O', { timeout: MCP_TOOL_TIMEOUT, toolName });
    try {
      const result = await this.mcp.callTool(
        { arguments: args, name: toolName },
        {
          timeout: MCP_TOOL_TIMEOUT,
        },
      );
      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) {
      throwIfSSRFBlocked(e);
      // The server rejects the request before executing the tool, so retrying
      // with a fresh session is safe (no double side effects).
      if (this.isNoValidSessionError(e)) {
        throw new Error('NoValidSessionId', { cause: e });
      }
      if (
        SdkError.isInstance(e) &&
        e.code === SdkErrorCode.UnsupportedResultType &&
        toRecord(e.data)?.resultType === 'input_required'
      ) {
        return {
          content: [
            {
              type: 'text',
              text: `This MCP tool requires user input that ${BRANDING_NAME} does not support yet. Use a tool that does not require additional input.`,
            },
          ],
          isError: true,
        };
      }
      throw e;
    }
  }
}