@@ -48,6 +48,7 @@ function printHelp(): void {
4848 console . log ( '\nAvailable commands:' ) ;
4949 console . log ( ' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)' ) ;
5050 console . log ( ' disconnect - Disconnect from server' ) ;
51+ console . log ( ' terminate-session - Terminate the current session' ) ;
5152 console . log ( ' reconnect - Reconnect to the server' ) ;
5253 console . log ( ' list-tools - List available tools' ) ;
5354 console . log ( ' call-tool <name> [args] - Call a tool with optional JSON arguments' ) ;
@@ -76,6 +77,10 @@ function commandLoop(): void {
7677 await disconnect ( ) ;
7778 break ;
7879
80+ case 'terminate-session' :
81+ await terminateSession ( ) ;
82+ break ;
83+
7984 case 'reconnect' :
8085 await reconnect ( ) ;
8186 break ;
@@ -249,6 +254,36 @@ async function disconnect(): Promise<void> {
249254 }
250255}
251256
257+ async function terminateSession ( ) : Promise < void > {
258+ if ( ! client || ! transport ) {
259+ console . log ( 'Not connected.' ) ;
260+ return ;
261+ }
262+
263+ try {
264+ console . log ( 'Terminating session with ID:' , transport . sessionId ) ;
265+ await transport . terminateSession ( ) ;
266+ console . log ( 'Session terminated successfully' ) ;
267+
268+ // Check if sessionId was cleared after termination
269+ if ( ! transport . sessionId ) {
270+ console . log ( 'Session ID has been cleared' ) ;
271+ sessionId = undefined ;
272+
273+ // Also close the transport and clear client objects
274+ await transport . close ( ) ;
275+ console . log ( 'Transport closed after session termination' ) ;
276+ client = null ;
277+ transport = null ;
278+ } else {
279+ console . log ( 'Server responded with 405 Method Not Allowed (session termination not supported)' ) ;
280+ console . log ( 'Session ID is still active:' , transport . sessionId ) ;
281+ }
282+ } catch ( error ) {
283+ console . error ( 'Error terminating session:' , error ) ;
284+ }
285+ }
286+
252287async function reconnect ( ) : Promise < void > {
253288 if ( client ) {
254289 await disconnect ( ) ;
@@ -411,13 +446,24 @@ async function listResources(): Promise<void> {
411446async function cleanup ( ) : Promise < void > {
412447 if ( client && transport ) {
413448 try {
449+ // First try to terminate the session gracefully
450+ if ( transport . sessionId ) {
451+ try {
452+ console . log ( 'Terminating session before exit...' ) ;
453+ await transport . terminateSession ( ) ;
454+ console . log ( 'Session terminated successfully' ) ;
455+ } catch ( error ) {
456+ console . error ( 'Error terminating session:' , error ) ;
457+ }
458+ }
459+
460+ // Then close the transport
414461 await transport . close ( ) ;
415462 } catch ( error ) {
416463 console . error ( 'Error closing transport:' , error ) ;
417464 }
418465 }
419466
420-
421467 process . stdin . setRawMode ( false ) ;
422468 readline . close ( ) ;
423469 console . log ( '\nGoodbye!' ) ;
0 commit comments