interfaces.d.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /**
  2. * Experimental task interfaces for MCP SDK.
  3. * WARNING: These APIs are experimental and may change without notice.
  4. */
  5. import { Task, RequestId, Result, JSONRPCRequest, JSONRPCNotification, JSONRPCResultResponse, JSONRPCErrorResponse, ServerRequest, ServerNotification, CallToolResult, GetTaskResult, ToolExecution, Request } from '../../types.js';
  6. import { CreateTaskResult } from './types.js';
  7. import type { RequestHandlerExtra, RequestTaskStore } from '../../shared/protocol.js';
  8. import type { ZodRawShapeCompat, AnySchema, ShapeOutput } from '../../server/zod-compat.js';
  9. /**
  10. * Extended handler extra with task store for task creation.
  11. * @experimental
  12. */
  13. export interface CreateTaskRequestHandlerExtra extends RequestHandlerExtra<ServerRequest, ServerNotification> {
  14. taskStore: RequestTaskStore;
  15. }
  16. /**
  17. * Extended handler extra with task ID and store for task operations.
  18. * @experimental
  19. */
  20. export interface TaskRequestHandlerExtra extends RequestHandlerExtra<ServerRequest, ServerNotification> {
  21. taskId: string;
  22. taskStore: RequestTaskStore;
  23. }
  24. /**
  25. * Base callback type for tool handlers.
  26. * @experimental
  27. */
  28. export type BaseToolCallback<SendResultT extends Result, ExtraT extends RequestHandlerExtra<ServerRequest, ServerNotification>, Args extends undefined | ZodRawShapeCompat | AnySchema = undefined> = Args extends ZodRawShapeCompat ? (args: ShapeOutput<Args>, extra: ExtraT) => SendResultT | Promise<SendResultT> : Args extends AnySchema ? (args: unknown, extra: ExtraT) => SendResultT | Promise<SendResultT> : (extra: ExtraT) => SendResultT | Promise<SendResultT>;
  29. /**
  30. * Handler for creating a task.
  31. * @experimental
  32. */
  33. export type CreateTaskRequestHandler<SendResultT extends Result, Args extends undefined | ZodRawShapeCompat | AnySchema = undefined> = BaseToolCallback<SendResultT, CreateTaskRequestHandlerExtra, Args>;
  34. /**
  35. * Handler for task operations (get, getResult).
  36. * @experimental
  37. */
  38. export type TaskRequestHandler<SendResultT extends Result, Args extends undefined | ZodRawShapeCompat | AnySchema = undefined> = BaseToolCallback<SendResultT, TaskRequestHandlerExtra, Args>;
  39. /**
  40. * Interface for task-based tool handlers.
  41. * @experimental
  42. */
  43. export interface ToolTaskHandler<Args extends undefined | ZodRawShapeCompat | AnySchema = undefined> {
  44. createTask: CreateTaskRequestHandler<CreateTaskResult, Args>;
  45. getTask: TaskRequestHandler<GetTaskResult, Args>;
  46. getTaskResult: TaskRequestHandler<CallToolResult, Args>;
  47. }
  48. /**
  49. * Task-specific execution configuration.
  50. * taskSupport cannot be 'forbidden' for task-based tools.
  51. * @experimental
  52. */
  53. export type TaskToolExecution<TaskSupport = ToolExecution['taskSupport']> = Omit<ToolExecution, 'taskSupport'> & {
  54. taskSupport: TaskSupport extends 'forbidden' | undefined ? never : TaskSupport;
  55. };
  56. /**
  57. * Represents a message queued for side-channel delivery via tasks/result.
  58. *
  59. * This is a serializable data structure that can be stored in external systems.
  60. * All fields are JSON-serializable.
  61. */
  62. export type QueuedMessage = QueuedRequest | QueuedNotification | QueuedResponse | QueuedError;
  63. export interface BaseQueuedMessage {
  64. /** Type of message */
  65. type: string;
  66. /** When the message was queued (milliseconds since epoch) */
  67. timestamp: number;
  68. }
  69. export interface QueuedRequest extends BaseQueuedMessage {
  70. type: 'request';
  71. /** The actual JSONRPC request */
  72. message: JSONRPCRequest;
  73. }
  74. export interface QueuedNotification extends BaseQueuedMessage {
  75. type: 'notification';
  76. /** The actual JSONRPC notification */
  77. message: JSONRPCNotification;
  78. }
  79. export interface QueuedResponse extends BaseQueuedMessage {
  80. type: 'response';
  81. /** The actual JSONRPC response */
  82. message: JSONRPCResultResponse;
  83. }
  84. export interface QueuedError extends BaseQueuedMessage {
  85. type: 'error';
  86. /** The actual JSONRPC error */
  87. message: JSONRPCErrorResponse;
  88. }
  89. /**
  90. * Interface for managing per-task FIFO message queues.
  91. *
  92. * Similar to TaskStore, this allows pluggable queue implementations
  93. * (in-memory, Redis, other distributed queues, etc.).
  94. *
  95. * Each method accepts taskId and optional sessionId parameters to enable
  96. * a single queue instance to manage messages for multiple tasks, with
  97. * isolation based on task ID and session ID.
  98. *
  99. * All methods are async to support external storage implementations.
  100. * All data in QueuedMessage must be JSON-serializable.
  101. *
  102. * @experimental
  103. */
  104. export interface TaskMessageQueue {
  105. /**
  106. * Adds a message to the end of the queue for a specific task.
  107. * Atomically checks queue size and throws if maxSize would be exceeded.
  108. * @param taskId The task identifier
  109. * @param message The message to enqueue
  110. * @param sessionId Optional session ID for binding the operation to a specific session
  111. * @param maxSize Optional maximum queue size - if specified and queue is full, throws an error
  112. * @throws Error if maxSize is specified and would be exceeded
  113. */
  114. enqueue(taskId: string, message: QueuedMessage, sessionId?: string, maxSize?: number): Promise<void>;
  115. /**
  116. * Removes and returns the first message from the queue for a specific task.
  117. * @param taskId The task identifier
  118. * @param sessionId Optional session ID for binding the query to a specific session
  119. * @returns The first message, or undefined if the queue is empty
  120. */
  121. dequeue(taskId: string, sessionId?: string): Promise<QueuedMessage | undefined>;
  122. /**
  123. * Removes and returns all messages from the queue for a specific task.
  124. * Used when tasks are cancelled or failed to clean up pending messages.
  125. * @param taskId The task identifier
  126. * @param sessionId Optional session ID for binding the query to a specific session
  127. * @returns Array of all messages that were in the queue
  128. */
  129. dequeueAll(taskId: string, sessionId?: string): Promise<QueuedMessage[]>;
  130. }
  131. /**
  132. * Task creation options.
  133. * @experimental
  134. */
  135. export interface CreateTaskOptions {
  136. /**
  137. * Time in milliseconds to keep task results available after completion.
  138. * If null, the task has unlimited lifetime until manually cleaned up.
  139. */
  140. ttl?: number | null;
  141. /**
  142. * Time in milliseconds to wait between task status requests.
  143. */
  144. pollInterval?: number;
  145. /**
  146. * Additional context to pass to the task store.
  147. */
  148. context?: Record<string, unknown>;
  149. }
  150. /**
  151. * Interface for storing and retrieving task state and results.
  152. *
  153. * Similar to Transport, this allows pluggable task storage implementations
  154. * (in-memory, database, distributed cache, etc.).
  155. *
  156. * @experimental
  157. */
  158. export interface TaskStore {
  159. /**
  160. * Creates a new task with the given creation parameters and original request.
  161. * The implementation must generate a unique taskId and createdAt timestamp.
  162. *
  163. * TTL Management:
  164. * - The implementation receives the TTL suggested by the requestor via taskParams.ttl
  165. * - The implementation MAY override the requested TTL (e.g., to enforce limits)
  166. * - The actual TTL used MUST be returned in the Task object
  167. * - Null TTL indicates unlimited task lifetime (no automatic cleanup)
  168. * - Cleanup SHOULD occur automatically after TTL expires, regardless of task status
  169. *
  170. * @param taskParams - The task creation parameters from the request (ttl, pollInterval)
  171. * @param requestId - The JSON-RPC request ID
  172. * @param request - The original request that triggered task creation
  173. * @param sessionId - Optional session ID for binding the task to a specific session
  174. * @returns The created task object
  175. */
  176. createTask(taskParams: CreateTaskOptions, requestId: RequestId, request: Request, sessionId?: string): Promise<Task>;
  177. /**
  178. * Gets the current status of a task.
  179. *
  180. * @param taskId - The task identifier
  181. * @param sessionId - Optional session ID for binding the query to a specific session
  182. * @returns The task object, or null if it does not exist
  183. */
  184. getTask(taskId: string, sessionId?: string): Promise<Task | null>;
  185. /**
  186. * Stores the result of a task and sets its final status.
  187. *
  188. * @param taskId - The task identifier
  189. * @param status - The final status: 'completed' for success, 'failed' for errors
  190. * @param result - The result to store
  191. * @param sessionId - Optional session ID for binding the operation to a specific session
  192. */
  193. storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result, sessionId?: string): Promise<void>;
  194. /**
  195. * Retrieves the stored result of a task.
  196. *
  197. * @param taskId - The task identifier
  198. * @param sessionId - Optional session ID for binding the query to a specific session
  199. * @returns The stored result
  200. */
  201. getTaskResult(taskId: string, sessionId?: string): Promise<Result>;
  202. /**
  203. * Updates a task's status (e.g., to 'cancelled', 'failed', 'completed').
  204. *
  205. * @param taskId - The task identifier
  206. * @param status - The new status
  207. * @param statusMessage - Optional diagnostic message for failed tasks or other status information
  208. * @param sessionId - Optional session ID for binding the operation to a specific session
  209. */
  210. updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string, sessionId?: string): Promise<void>;
  211. /**
  212. * Lists tasks, optionally starting from a pagination cursor.
  213. *
  214. * @param cursor - Optional cursor for pagination
  215. * @param sessionId - Optional session ID for binding the query to a specific session
  216. * @returns An object containing the tasks array and an optional nextCursor
  217. */
  218. listTasks(cursor?: string, sessionId?: string): Promise<{
  219. tasks: Task[];
  220. nextCursor?: string;
  221. }>;
  222. }
  223. /**
  224. * Checks if a task status represents a terminal state.
  225. * Terminal states are those where the task has finished and will not change.
  226. *
  227. * @param status - The task status to check
  228. * @returns True if the status is terminal (completed, failed, or cancelled)
  229. * @experimental
  230. */
  231. export declare function isTerminal(status: Task['status']): boolean;
  232. //# sourceMappingURL=interfaces.d.ts.map