|
| 1 | +/* |
| 2 | + * Copyright 2024-2026 the original author or authors. |
| 3 | + */ |
| 4 | + |
| 5 | +package io.modelcontextprotocol.experimental.tasks; |
| 6 | + |
| 7 | +import java.time.Duration; |
| 8 | +import java.util.function.BiFunction; |
| 9 | + |
| 10 | +import io.modelcontextprotocol.spec.McpError; |
| 11 | +import io.modelcontextprotocol.spec.McpSchema; |
| 12 | +import io.modelcontextprotocol.spec.McpSchema.ErrorCodes; |
| 13 | +import io.modelcontextprotocol.spec.McpSchema.Notification; |
| 14 | +import io.modelcontextprotocol.spec.McpSchema.Request; |
| 15 | +import io.modelcontextprotocol.spec.McpSchema.Result; |
| 16 | +import org.slf4j.Logger; |
| 17 | +import org.slf4j.LoggerFactory; |
| 18 | +import reactor.core.publisher.Mono; |
| 19 | + |
| 20 | +/** |
| 21 | + * Shared base class for task handler implementations on both client and server sides. |
| 22 | + * |
| 23 | + * <p> |
| 24 | + * This class encapsulates the common task lifecycle logic that is identical between |
| 25 | + * {@code ServerTaskToolHandler} and {@code ClientTaskHandler}: |
| 26 | + * <ul> |
| 27 | + * <li>TaskManager creation (DefaultTaskManager vs NullTaskManager) and binding</li> |
| 28 | + * <li>Handler registration via {@link TaskHandlerRegistry}</li> |
| 29 | + * <li>Custom task handler invocation with validation and error handling</li> |
| 30 | + * <li>Task store session validation</li> |
| 31 | + * <li>Close and graceful close lifecycle</li> |
| 32 | + * <li>Accessor methods for TaskStore and TaskManager</li> |
| 33 | + * </ul> |
| 34 | + * |
| 35 | + * <p> |
| 36 | + * Subclasses must implement the transport-specific methods {@link #request} and |
| 37 | + * {@link #notification} which differ between client (delegates to session) and server |
| 38 | + * (broadcasts to all clients or errors). |
| 39 | + * |
| 40 | + * <p> |
| 41 | + * The {@link #findAndInvokeCustomHandler} method is an overridable hook that defaults to |
| 42 | + * returning empty. The server overrides this to look up tool-specific custom handlers by |
| 43 | + * tool name from the originating request. |
| 44 | + * |
| 45 | + * <p> |
| 46 | + * This is an experimental API that may change in future releases. |
| 47 | + * |
| 48 | + * @param <S> the task store payload type (e.g., ServerTaskPayloadResult or |
| 49 | + * ClientTaskPayloadResult) |
| 50 | + * @see TaskManagerHost |
| 51 | + * @see TaskManager |
| 52 | + */ |
| 53 | +abstract class AbstractTaskHandler<S extends Result> implements TaskManagerHost { |
| 54 | + |
| 55 | + private static final Logger logger = LoggerFactory.getLogger(AbstractTaskHandler.class); |
| 56 | + |
| 57 | + /** |
| 58 | + * Task store for managing long-running tasks. May be null if tasks are not |
| 59 | + * configured. |
| 60 | + */ |
| 61 | + protected final TaskStore<S> taskStore; |
| 62 | + |
| 63 | + /** |
| 64 | + * Task manager for task orchestration. Handles task lifecycle operations, message |
| 65 | + * queuing, and handler registration. |
| 66 | + */ |
| 67 | + protected final TaskManager taskManager; |
| 68 | + |
| 69 | + /** |
| 70 | + * Registry for task handlers registered by TaskManager during bind(). These are |
| 71 | + * adapted to the appropriate handler type by subclasses. |
| 72 | + */ |
| 73 | + protected final TaskHandlerRegistry taskHandlerRegistry = new TaskHandlerRegistry(); |
| 74 | + |
| 75 | + /** |
| 76 | + * Creates a new AbstractTaskHandler. |
| 77 | + * @param taskStore the task store for managing task state, or null if tasks are not |
| 78 | + * configured |
| 79 | + * @param taskOptions the task manager options, or null if tasks are not configured |
| 80 | + */ |
| 81 | + protected AbstractTaskHandler(TaskStore<S> taskStore, TaskManagerOptions taskOptions) { |
| 82 | + this.taskStore = taskStore; |
| 83 | + |
| 84 | + // Initialize TaskManager based on whether TaskOptions are configured |
| 85 | + if (taskOptions != null && taskStore != null) { |
| 86 | + this.taskManager = new DefaultTaskManager(taskOptions); |
| 87 | + } |
| 88 | + else { |
| 89 | + this.taskManager = NullTaskManager.getInstance(); |
| 90 | + } |
| 91 | + |
| 92 | + // Bind the TaskManager to this handler so it can register handlers and send |
| 93 | + // requests |
| 94 | + this.taskManager.bind(this); |
| 95 | + } |
| 96 | + |
| 97 | + // -------------------------- |
| 98 | + // TaskManagerHost Implementation |
| 99 | + // -------------------------- |
| 100 | + |
| 101 | + @Override |
| 102 | + public void registerHandler(String method, TaskRequestHandler handler) { |
| 103 | + this.taskHandlerRegistry.registerHandler(method, handler); |
| 104 | + } |
| 105 | + |
| 106 | + @Override |
| 107 | + public <T extends Result> Mono<T> invokeCustomTaskHandler(String taskId, String method, Request request, |
| 108 | + TaskHandlerContext context, Class<T> resultType) { |
| 109 | + if (this.taskStore == null) { |
| 110 | + return Mono.empty(); |
| 111 | + } |
| 112 | + return getTaskWithSessionValidation(taskId, context.sessionId()) |
| 113 | + .flatMap(storeResult -> findAndInvokeCustomHandler(storeResult, method, request, context, resultType)) |
| 114 | + .onErrorResume(e -> { |
| 115 | + logger.debug("invokeCustomTaskHandler: task lookup failed for taskId={}, returning empty", taskId, e); |
| 116 | + return Mono.empty(); |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + /** |
| 121 | + * Overridable hook for subclass-specific custom handler lookup. The server overrides |
| 122 | + * this to look up tool-specific custom handlers by tool name from the originating |
| 123 | + * request. The client inherits the default which returns empty. |
| 124 | + * @param <T> the result type |
| 125 | + * @param storeResult the task store result containing the task and originating |
| 126 | + * request |
| 127 | + * @param method the request method (e.g., METHOD_TASKS_GET or METHOD_TASKS_RESULT) |
| 128 | + * @param request the original request object |
| 129 | + * @param context the handler context with session information |
| 130 | + * @param resultType the expected result type class |
| 131 | + * @return a Mono emitting the handler result, or empty if no custom handler found |
| 132 | + */ |
| 133 | + protected <T extends Result> Mono<T> findAndInvokeCustomHandler(GetTaskFromStoreResult storeResult, String method, |
| 134 | + Request request, TaskHandlerContext context, Class<T> resultType) { |
| 135 | + return Mono.empty(); |
| 136 | + } |
| 137 | + |
| 138 | + // -------------------------- |
| 139 | + // Session Validation |
| 140 | + // -------------------------- |
| 141 | + |
| 142 | + /** |
| 143 | + * Validates that a task exists and is accessible for the given session. |
| 144 | + * @param taskId the task identifier |
| 145 | + * @param sessionId the session ID for validation |
| 146 | + * @return a Mono emitting the task store result, or error if not found |
| 147 | + */ |
| 148 | + protected Mono<GetTaskFromStoreResult> getTaskWithSessionValidation(String taskId, String sessionId) { |
| 149 | + return this.taskStore.getTask(taskId, sessionId) |
| 150 | + .switchIfEmpty(Mono.error(McpError.builder(ErrorCodes.INVALID_PARAMS) |
| 151 | + .message("Task not found (may have expired after TTL)") |
| 152 | + .data("Task ID: " + taskId) |
| 153 | + .build())); |
| 154 | + } |
| 155 | + |
| 156 | + // -------------------------- |
| 157 | + // Handler Context Factory |
| 158 | + // -------------------------- |
| 159 | + |
| 160 | + /** |
| 161 | + * Creates a {@link TaskHandlerContext} that provides session identification and |
| 162 | + * message routing capabilities to task request handlers. |
| 163 | + * |
| 164 | + * <p> |
| 165 | + * Both client and server need to create context objects when adapting |
| 166 | + * {@link TaskRequestHandler} instances to their respective request handler types. |
| 167 | + * This factory centralizes that creation to avoid duplicating the anonymous class |
| 168 | + * implementation. |
| 169 | + * @param sessionId the session ID for the requesting client, or null if not |
| 170 | + * applicable (e.g., client-side handlers) |
| 171 | + * @param requestSender sends a request to the remote party; accepts the method name |
| 172 | + * and params, returns a Mono of the result |
| 173 | + * @param notificationSender sends a notification to the remote party; accepts the |
| 174 | + * method name and notification object |
| 175 | + * @return a new TaskHandlerContext backed by the provided functions |
| 176 | + */ |
| 177 | + protected static TaskHandlerContext createTaskHandlerContext(String sessionId, |
| 178 | + BiFunction<String, Object, Mono<? extends Result>> requestSender, |
| 179 | + BiFunction<String, Notification, Mono<Void>> notificationSender) { |
| 180 | + return new TaskHandlerContext() { |
| 181 | + @Override |
| 182 | + public String sessionId() { |
| 183 | + return sessionId; |
| 184 | + } |
| 185 | + |
| 186 | + @Override |
| 187 | + @SuppressWarnings("unchecked") |
| 188 | + public <R extends Result> Mono<R> sendRequest(String reqMethod, Object reqParams, Class<R> resultType) { |
| 189 | + return (Mono<R>) requestSender.apply(reqMethod, reqParams); |
| 190 | + } |
| 191 | + |
| 192 | + @Override |
| 193 | + public Mono<Void> sendNotification(String notifMethod, Notification notification) { |
| 194 | + return notificationSender.apply(notifMethod, notification); |
| 195 | + } |
| 196 | + }; |
| 197 | + } |
| 198 | + |
| 199 | + // -------------------------- |
| 200 | + // Lifecycle |
| 201 | + // -------------------------- |
| 202 | + |
| 203 | + /** |
| 204 | + * Cleanup on immediate close. Shuts down the TaskManager and TaskStore. |
| 205 | + */ |
| 206 | + public void close() { |
| 207 | + this.taskManager.onClose(); |
| 208 | + if (this.taskStore != null) { |
| 209 | + this.taskStore.shutdown().block(Duration.ofSeconds(TaskDefaults.TASK_STORE_SHUTDOWN_TIMEOUT_SECONDS)); |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + /** |
| 214 | + * Cleanup on graceful close. |
| 215 | + * @return a Mono that completes when cleanup is done |
| 216 | + */ |
| 217 | + public Mono<Void> closeGracefully() { |
| 218 | + this.taskManager.onClose(); |
| 219 | + return this.taskStore != null ? this.taskStore.shutdown() : Mono.empty(); |
| 220 | + } |
| 221 | + |
| 222 | + // -------------------------- |
| 223 | + // Accessors |
| 224 | + // -------------------------- |
| 225 | + |
| 226 | + /** |
| 227 | + * Get the task store used for managing long-running tasks. |
| 228 | + * @return the task store, or null if tasks are not configured |
| 229 | + */ |
| 230 | + public TaskStore<S> getTaskStore() { |
| 231 | + return this.taskStore; |
| 232 | + } |
| 233 | + |
| 234 | + /** |
| 235 | + * Returns the task manager for task orchestration operations. |
| 236 | + * @return the task manager (never null; returns NullTaskManager if task support is |
| 237 | + * not configured) |
| 238 | + */ |
| 239 | + public TaskManager taskManager() { |
| 240 | + return this.taskManager; |
| 241 | + } |
| 242 | + |
| 243 | +} |
0 commit comments