connection.ts
1 import { Client } from '@modelcontextprotocol/sdk/client/index.js' 2 import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js' 3 4 export const validLogLevels = ['trace', 'debug', 'info', 'warn', 'error'] as const 5 6 export type LogLevel = (typeof validLogLevels)[number] 7 8 export async function connect(client: Client, transport: Transport): Promise<void> { 9 try { 10 await client.connect(transport) 11 } catch (error) { 12 try { 13 await disconnect(transport) 14 } catch (_disconnectError) {} 15 throw new Error( 16 `Failed to connect to MCP server: ${error instanceof Error ? error.message : String(error)}` 17 ) 18 } 19 } 20 21 export async function disconnect(transport: Transport): Promise<void> { 22 try { 23 await transport.close() 24 } catch (error) { 25 throw new Error( 26 `Failed to disconnect from MCP server: ${error instanceof Error ? error.message : String(error)}` 27 ) 28 } 29 } 30 31 // Set logging level 32 export async function setLoggingLevel( 33 client: Client, 34 level: LogLevel 35 ): Promise<Record<string, unknown>> { 36 try { 37 const response = await client.setLoggingLevel(level as any) 38 return response 39 } catch (error) { 40 throw new Error( 41 `Failed to set logging level: ${error instanceof Error ? error.message : String(error)}` 42 ) 43 } 44 }