diff --git a/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpServerSession.java b/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpServerSession.java index 8f86138f0..b063b2313 100644 --- a/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpServerSession.java +++ b/mcp-core/src/main/java/io/modelcontextprotocol/spec/McpServerSession.java @@ -287,8 +287,12 @@ private Mono handleIncomingRequest(McpSchema.JSONRPCR resultMono = this.initRequestHandler.handle(initializeRequest); } else { - // TODO handle errors for communication to this session without - // initialization happening first + if (this.state.get() != STATE_INITIALIZED) { + logger.warn("Rejecting uninitialized request method: {}", request.method()); + return Mono.just(McpSchema.JSONRPCResponse.error(request.id(), + new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INVALID_REQUEST, + "Session is not initialized. Cannot process method: " + request.method(), null))); + } var handler = this.requestHandlers.get(request.method()); if (handler == null) { MethodNotFoundError error = getMethodNotFoundError(request.method()); @@ -327,6 +331,12 @@ private Mono handleIncomingNotification(McpSchema.JSONRPCNotification noti exchangeSink.tryEmitValue(new McpAsyncServerExchange(this.id, this, clientCapabilities.get(), clientInfo.get(), transportContext, this.jsonSchemaValidator)); } + else if (this.state.get() != STATE_INITIALIZED) { + logger.warn("Rejecting uninitialized notification method: {}", notification.method()); + return Mono + .error(new McpError(new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INVALID_REQUEST, + "Session is not initialized. Cannot process method: " + notification.method(), null))); + } var handler = notificationHandlers.get(notification.method()); if (handler == null) {