@@ -102,6 +102,7 @@ export class Server extends Protocol<ServerContext> {
102102 private _instructions ?: string ;
103103 private _jsonSchemaValidator : jsonSchemaValidator ;
104104 private _experimental ?: { tasks : ExperimentalServerTasks } ;
105+ private _initialized = false ;
105106
106107 /**
107108 * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification).
@@ -132,7 +133,13 @@ export class Server extends Protocol<ServerContext> {
132133 }
133134
134135 this . setRequestHandler ( 'initialize' , request => this . _oninitialize ( request ) ) ;
135- this . setNotificationHandler ( 'notifications/initialized' , ( ) => this . oninitialized ?.( ) ) ;
136+ this . setNotificationHandler ( 'notifications/initialized' , ( ) => {
137+ if ( ! this . _clientCapabilities ) {
138+ throw new ProtocolError ( ProtocolErrorCode . InvalidRequest , 'Server not initialized' ) ;
139+ }
140+ this . _initialized = true ;
141+ this . oninitialized ?.( ) ;
142+ } ) ;
136143
137144 if ( this . _capabilities . logging ) {
138145 this . _registerLoggingHandler ( ) ;
@@ -226,8 +233,15 @@ export class Server extends Protocol<ServerContext> {
226233 method : string ,
227234 handler : ( request : JSONRPCRequest , ctx : ServerContext ) => Promise < Result >
228235 ) : ( request : JSONRPCRequest , ctx : ServerContext ) => Promise < Result > {
236+ const lifecycleHandler : ( request : JSONRPCRequest , ctx : ServerContext ) => Promise < Result > = async ( request , ctx ) => {
237+ if ( ! ctx . http && ! this . _initialized && method !== 'initialize' && method !== 'ping' ) {
238+ throw new ProtocolError ( ProtocolErrorCode . InvalidRequest , 'Server not initialized' ) ;
239+ }
240+ return handler ( request , ctx ) ;
241+ } ;
242+
229243 if ( method !== 'tools/call' ) {
230- return handler ;
244+ return lifecycleHandler ;
231245 }
232246 return async ( request , ctx ) => {
233247 const validatedRequest = parseSchema ( CallToolRequestSchema , request ) ;
@@ -239,7 +253,7 @@ export class Server extends Protocol<ServerContext> {
239253
240254 const { params } = validatedRequest . data ;
241255
242- const result = await handler ( request , ctx ) ;
256+ const result = await lifecycleHandler ( request , ctx ) ;
243257
244258 // When task creation is requested, validate and return CreateTaskResult
245259 if ( params . task ) {
0 commit comments