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.

52 lines (51 loc) 1.86 kB
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { logger } from '../logging.js'; import { ConnectionManager } from './base.js'; export class StdioConnectionManager extends ConnectionManager { serverParams; errlog; _transport = null; /** * Create a new stdio connection manager. * * @param serverParams Parameters for the stdio server process. * @param errlog Stream to which the server's stderr should be piped. * Defaults to `process.stderr`. */ constructor(serverParams, errlog = process.stderr) { super(); this.serverParams = serverParams; this.errlog = errlog; } /** * Establish the stdio connection by spawning the server process and starting * the SDK's transport. Returns the live `StdioClientTransport` instance. */ async establishConnection() { // Instantiate and start the transport this._transport = new StdioClientTransport(this.serverParams); // If stderr was piped, forward it to `errlog` for visibility if (this._transport.stderr && typeof this._transport.stderr.pipe === 'function') { this._transport.stderr.pipe(this.errlog); } logger.debug(`${this.constructor.name} connected successfully`); return this._transport; } /** * Close the stdio connection, making sure the transport cleans up the child * process and associated resources. */ async closeConnection(_connection) { if (this._transport) { try { await this._transport.close(); } catch (e) { logger.warn(`Error closing stdio transport: ${e}`); } finally { this._transport = null; } } } }