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) • 2.08 kB
JavaScript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { logger } from '../logging.js';
import { SseConnectionManager } from '../task_managers/sse.js';
import { BaseConnector } from './base.js';
export class HttpConnector extends BaseConnector {
baseUrl;
headers;
timeout;
sseReadTimeout;
clientInfo;
constructor(baseUrl, opts = {}) {
super(opts);
this.baseUrl = baseUrl.replace(/\/$/, '');
this.headers = { ...(opts.headers ?? {}) };
if (opts.authToken) {
this.headers.Authorization = `Bearer ${opts.authToken}`;
}
this.timeout = opts.timeout ?? 5;
this.sseReadTimeout = opts.sseReadTimeout ?? 60 * 5;
this.clientInfo = opts.clientInfo ?? { name: 'http-connector', version: '1.0.0' };
}
/** Establish connection to the MCP implementation via SSE. */
async connect() {
if (this.connected) {
logger.debug('Already connected to MCP implementation');
return;
}
logger.debug(`Connecting to MCP implementation via HTTP/SSE: ${this.baseUrl}`);
try {
// Build the SSE URL (root of server endpoint)
const sseUrl = this.baseUrl;
// Create and start the connection manager -> returns an SSE transport
this.connectionManager = new SseConnectionManager(sseUrl, {
requestInit: {
headers: this.headers,
},
});
const transport = await this.connectionManager.start();
// Create and connect the 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 via HTTP/SSE: ${this.baseUrl}`);
}
catch (err) {
logger.error(`Failed to connect to MCP implementation via HTTP/SSE: ${err}`);
await this.cleanupResources();
throw err;
}
}
}