UNPKG

@agentpaid/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.

141 lines (140 loc) 5.06 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MCPClient = void 0; const node_fs_1 = __importDefault(require("node:fs")); const node_path_1 = __importDefault(require("node:path")); const config_js_1 = require("./config.js"); const logging_js_1 = require("./logging.js"); const session_js_1 = require("./session.js"); class MCPClient { config = {}; sessions = {}; activeSessions = []; constructor(config) { if (config) { if (typeof config === 'string') { this.config = (0, config_js_1.loadConfigFile)(config); } else { this.config = config; } } } static fromDict(cfg) { return new MCPClient(cfg); } static fromConfigFile(path) { return new MCPClient((0, config_js_1.loadConfigFile)(path)); } addServer(name, serverConfig) { this.config.mcpServers = this.config.mcpServers || {}; this.config.mcpServers[name] = serverConfig; } removeServer(name) { if (this.config.mcpServers?.[name]) { delete this.config.mcpServers[name]; this.activeSessions = this.activeSessions.filter(n => n !== name); } } getServerNames() { return Object.keys(this.config.mcpServers ?? {}); } getServerConfig(name) { return this.config.mcpServers?.[name]; } getConfig() { return this.config ?? {}; } saveConfig(filepath) { const dir = node_path_1.default.dirname(filepath); if (!node_fs_1.default.existsSync(dir)) { node_fs_1.default.mkdirSync(dir, { recursive: true }); } node_fs_1.default.writeFileSync(filepath, JSON.stringify(this.config, null, 2), 'utf-8'); } async createSession(serverName, autoInitialize = true) { const servers = this.config.mcpServers ?? {}; if (Object.keys(servers).length === 0) { logging_js_1.logger.warn('No MCP servers defined in config'); } if (!servers[serverName]) { throw new Error(`Server '${serverName}' not found in config`); } const connector = (0, config_js_1.createConnectorFromConfig)(servers[serverName]); const session = new session_js_1.MCPSession(connector); if (autoInitialize) { await session.initialize(); } this.sessions[serverName] = session; if (!this.activeSessions.includes(serverName)) { this.activeSessions.push(serverName); } return session; } async createAllSessions(autoInitialize = true) { const servers = this.config.mcpServers ?? {}; if (Object.keys(servers).length === 0) { logging_js_1.logger.warn('No MCP servers defined in config'); } for (const name of Object.keys(servers)) { await this.createSession(name, autoInitialize); } return this.sessions; } getSession(serverName) { const session = this.sessions[serverName]; // if (!session) { // throw new Error(`No session exists for server '${serverName}'`) // } if (!session) { return null; } return session; } getAllActiveSessions() { return Object.fromEntries(this.activeSessions.map(n => [n, this.sessions[n]])); } async closeSession(serverName) { const session = this.sessions[serverName]; if (!session) { logging_js_1.logger.warn(`No session exists for server ${serverName}, nothing to close`); return; } try { logging_js_1.logger.debug(`Closing session for server ${serverName}`); await session.disconnect(); } catch (e) { logging_js_1.logger.error(`Error closing session for server '${serverName}': ${e}`); } finally { delete this.sessions[serverName]; this.activeSessions = this.activeSessions.filter(n => n !== serverName); } } async closeAllSessions() { const serverNames = Object.keys(this.sessions); const errors = []; for (const serverName of serverNames) { try { logging_js_1.logger.debug(`Closing session for server ${serverName}`); await this.closeSession(serverName); } catch (e) { const errorMsg = `Failed to close session for server '${serverName}': ${e}`; logging_js_1.logger.error(errorMsg); errors.push(errorMsg); } } if (errors.length) { logging_js_1.logger.error(`Encountered ${errors.length} errors while closing sessions`); } else { logging_js_1.logger.debug('All sessions closed successfully'); } } } exports.MCPClient = MCPClient;