|
| 1 | +import type { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js' |
| 2 | +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' |
| 3 | +import { logger } from '../logging.js' |
| 4 | +import { ConnectionManager } from './base.js' |
| 5 | + |
| 6 | +export class StreamableHttpConnectionManager extends ConnectionManager<StreamableHTTPClientTransport> { |
| 7 | + private readonly url: URL |
| 8 | + private readonly opts?: StreamableHTTPClientTransportOptions |
| 9 | + private _transport: StreamableHTTPClientTransport | null = null |
| 10 | + |
| 11 | + /** |
| 12 | + * Create a Streamable HTTP connection manager. |
| 13 | + * |
| 14 | + * @param url The HTTP endpoint URL. |
| 15 | + * @param opts Optional transport options (auth, headers, etc.). |
| 16 | + */ |
| 17 | + constructor(url: string | URL, opts?: StreamableHTTPClientTransportOptions) { |
| 18 | + super() |
| 19 | + this.url = typeof url === 'string' ? new URL(url) : url |
| 20 | + this.opts = opts |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Spawn a new `StreamableHTTPClientTransport` and return it. |
| 25 | + * The Client.connect() method will handle starting the transport. |
| 26 | + */ |
| 27 | + protected async establishConnection(): Promise<StreamableHTTPClientTransport> { |
| 28 | + this._transport = new StreamableHTTPClientTransport(this.url, this.opts) |
| 29 | + |
| 30 | + logger.debug(`${this.constructor.name} created successfully`) |
| 31 | + return this._transport |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Close the underlying transport and clean up resources. |
| 36 | + */ |
| 37 | + protected async closeConnection(_connection: StreamableHTTPClientTransport): Promise<void> { |
| 38 | + if (this._transport) { |
| 39 | + try { |
| 40 | + await this._transport.close() |
| 41 | + } |
| 42 | + catch (e) { |
| 43 | + logger.warn(`Error closing Streamable HTTP transport: ${e}`) |
| 44 | + } |
| 45 | + finally { |
| 46 | + this._transport = null |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Get the session ID from the transport if available. |
| 53 | + */ |
| 54 | + get sessionId(): string | undefined { |
| 55 | + return this._transport?.sessionId |
| 56 | + } |
| 57 | +} |
0 commit comments