Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tasks.ts

199 lines6.3 KB

1import { isCallToolResult } from '@modelcontextprotocol/server'
2import type { Task } from '@modelcontextprotocol/server'
3import type { TaskStore } from './stores'
4​
5const toolFailedMessage = 'The tool failed.'
6​
7/**
8 * One task in the store.
9 * It is the spec 2025-11-25 `Task` that `tasks/get` returns, plus the
10 * fields that never leave the server: the owner and the tool result.
11 */
12type StoredTask = Task & {
13 status: 'working' | 'completed' | 'failed'
14 /** The auth subject that started the task. Absent without auth. */
15 owner?: string
16 /** The tool output. Present when `status` is `completed`. */
17 result?: unknown
19​
20type StartTaskOptions = {
21 /** Task store. Use `inMemoryTaskStore()` or another {@link TaskStore}. */
22 store: TaskStore
23 /**
24 * Keeps the process alive until the tool run settles.
25 * The promise resolves after the store saves the tool result,
26 * or the tool error.
27 */
28 waitUntil?: (promise: Promise<unknown>) => void
29 /** The auth subject that starts the task. Only this subject can read it. */
30 owner?: string
32​
33/**
34 * Starts a tool run and returns a task id before the run finishes.
35 *
36 * `run` is the tool function. This function calls `run` in this process.
37 * The caller passes `inMemoryTaskStore()` or another TaskStore
38 * on `options.store`.
39 * When you pass `options.waitUntil`, this function calls it
40 * with the in-flight promise.
41 * That promise settles after the store saves the tool result or the tool error.
42 * If the store rejects the first save, this function rejects.
43 * A tool error does not reject this function.
44 * The store records the error on the task as `statusMessage`.
45 *
46 * @param run - Tool function. It returns the tool result.
47 * @param options - `store` is required. `waitUntil` is optional.
48 *
49 * @example
50 * ```ts
51 * const store = inMemoryTaskStore()
52 * const handle = await startTask(() => Promise.resolve({ text: 'done' }), {
53 * store,
54 * })
55 * ```
56 */
57export async function startTask(
58 run: () => Promise<unknown>,
59 options: StartTaskOptions,
60) {
61 const taskId = crypto.randomUUID()
62 const now = new Date().toISOString()
63 const working: StoredTask = {
64 taskId,
65 status: 'working',
66 ttl: null,
67 createdAt: now,
68 lastUpdatedAt: now,
69 ...(options.owner === undefined ? {} : { owner: options.owner }),
70 }
71 await options.store.set(taskId, working)
72​
73 // A tool can throw before it returns a promise. `.then(run)` turns that
74 // throw into a rejection, so the store records it.
75 const inflight = Promise.resolve()
76 .then(run)
77 .then(
78 (result) =>
79 options.store.set(taskId, {
80 ...working,
81 status: 'completed',
82 lastUpdatedAt: new Date().toISOString(),
83 result,
84 }),
85 (error: unknown) =>
86 options.store.set(taskId, {
87 ...working,
88 status: 'failed',
89 lastUpdatedAt: new Date().toISOString(),
90 statusMessage: errorMessage(error),
91 }),
92 )
93 const waitUntil = options.waitUntil
94 if (waitUntil !== undefined) {
95 waitUntil(inflight)
96 } else {
97 // A failed save leaves the task `working`. Say so on stderr.
98 void inflight.catch((error: unknown) => {
99 console.error(`Task ${taskId} could not save its result:`, error)
100 })
101 }
102​
103 return { taskId }
105​
106/**
107 * Returns the task record for a poll, or `null` when the id is absent.
108 * The result is also `null` when `owner` is not the caller that
109 * started the task.
110 *
111 * `task` is the spec 2025-11-25 `Task` that `tasks/get` returns.
112 * `record` also has the tool result and the owner.
113 *
114 * @param taskId - Id from `startTask`.
115 * @param store - Same store that `startTask` received.
116 * @param owner - The auth subject of the caller. Absent without auth.
117 *
118 * @example
119 * ```ts
120 * const polled = await getTask(handle.taskId, store)
121 * ```
122 */
123export async function getTask(
124 taskId: string,
125 store: TaskStore,
126 owner?: string,
127) {
128 const value = await store.get(taskId)
129 if (!isStoredTask(value)) return null
130 if (value.owner !== owner) return null
131 return { record: value, task: taskView(value) }
133​
134function taskView(record: StoredTask) {
135 const task = {
136 taskId: record.taskId,
137 status: record.status,
138 ttl: record.ttl,
139 createdAt: record.createdAt,
140 lastUpdatedAt: record.lastUpdatedAt,
141 ...(record.statusMessage === undefined
142 ? {}
143 : { statusMessage: record.statusMessage }),
144 } satisfies Task
145 return task
147​
148/**
149 * Turns a tool output into an MCP `CallToolResult`.
150 * A string becomes one text block. Any other value becomes a JSON text block.
151 * An object also becomes `structuredContent`. With `structured`, every
152 * value does, so the result matches an advertised output schema.
153 */
154export function toCallToolResult(output: unknown, structured = false) {
155 // A tool that builds its own MCP result keeps it: its content blocks,
156 // its structuredContent, and its isError flag.
157 if (isCallToolResult(output)) return output
158 // JSON.stringify(undefined) is undefined. A text block needs a string.
159 const text =
160 typeof output === 'string' ? output : (JSON.stringify(output) ?? '')
161 const content = [{ type: 'text' as const, text }]
162 if (structured || isRecord(output)) {
163 return { content, structuredContent: output }
164 }
165 return { content }
167​
168function errorMessage(error: unknown) {
169 if (error instanceof Error && error.message.length > 0) return error.message
170 if (typeof error === 'string' && error.length > 0) return error
171 return toolFailedMessage
173​
174function isStoredTask(value: unknown): value is StoredTask {
175 if (!isRecord(value)) return false
176 const taskIdMissing =
177 typeof value.taskId !== 'string' || value.taskId.length === 0
178 if (taskIdMissing) return false
179 if (typeof value.createdAt !== 'string') return false
180 if (typeof value.lastUpdatedAt !== 'string') return false
181 if (value.ttl !== null) return false
182 if (value.owner !== undefined && typeof value.owner !== 'string') return false
183 const messageInvalid =
184 value.statusMessage !== undefined && typeof value.statusMessage !== 'string'
185 if (messageInvalid) return false
186 switch (value.status) {
187 case 'working':
188 case 'failed':
189 return true
190 case 'completed':
191 return 'result' in value
192 default:
193 return false
194 }
196​
197function isRecord(value: unknown): value is Record<string, unknown> {
198 return typeof value === 'object' && value !== null && !Array.isArray(value)