UNPKG

mcp-use

Version:

A utility library for integrating Model Context Protocol (MCP) with LangChain, Zod, and related tools. Provides helpers for schema conversion, event streaming, and SDK usage.

50 lines (49 loc) 1.95 kB
import process from 'node:process'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { logger } from '../logging.js'; import { StdioConnectionManager } from '../task_managers/stdio.js'; import { BaseConnector } from './base.js'; export class StdioConnector extends BaseConnector { command; args; env; errlog; clientInfo; constructor({ command = 'npx', args = [], env, errlog = process.stderr, ...rest } = {}) { super(rest); this.command = command; this.args = args; this.env = env; this.errlog = errlog; this.clientInfo = rest.clientInfo ?? { name: 'stdio-connector', version: '1.0.0' }; } /** Establish connection to the MCP implementation. */ async connect() { if (this.connected) { logger.debug('Already connected to MCP implementation'); return; } logger.debug(`Connecting to MCP implementation via stdio: ${this.command}`); try { // 1. Build server parameters for the transport const serverParams = { command: this.command, args: this.args, env: this.env, }; // 2. Start the connection manager -> returns a live transport this.connectionManager = new StdioConnectionManager(serverParams, this.errlog); const transport = await this.connectionManager.start(); // 3. Create & connect the MCP client this.client = new Client(this.clientInfo, this.opts.clientOptions); await this.client.connect(transport); this.connected = true; logger.debug(`Successfully connected to MCP implementation: ${this.command}`); } catch (err) { logger.error(`Failed to connect to MCP implementation: ${err}`); await this.cleanupResources(); throw err; } } }