Step 3 of 7
Build an MCP server with Tasks support
Register the image tool, return a task ID and serve task status.
In this step you will add task-backed execution to the create_thumbnails tool,
along with handlers for retrieving a task's status and cancelling it. The tool
will still return an ordinary result to any MCP client that does not declare
Tasks support. This is the MCP server's half of the exchange from step 1:
1. Register the image tool
Replace src/app.ts with this complete file:
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { thumbnailInput } from './config.ts';
import { createThumbnails, type BatchOptions } from './thumbnails.ts';
import { registerTaskHandlers } from './task-handlers.ts';
import { TaskWorker } from './task-worker.ts';
export function createApp(options: BatchOptions, worker?: TaskWorker) {
return createMcpHandler(
() => {
const server = new McpServer({
name: 'thumbnail-server',
version: '1.0.0',
});
server.registerTool(
'create_thumbnails',
{
description: 'Create WebP thumbnails from local sample images.',
inputSchema: thumbnailInput,
},
(input) => createThumbnails(input, options),
);
if (worker) registerTaskHandlers(server, worker);
return server;
},
{ legacy: 'reject' },
);
}The tool's normal execution path calls createThumbnails(). When a worker is
provided, registerTaskHandlers() adds the Tasks capability and the request
handlers. The supplied TaskWorker runs the batches and keeps their task state
outside the HTTP request, so the state survives after the request ends.
The supplied src/server.ts starts the HTTP endpoint. Its legacy: 'reject'
option keeps every request on the protocol revision that this guide uses.
2. Add the Tasks handlers
Replace src/task-handlers.ts with:
import type { McpServer } from '@modelcontextprotocol/server';
import { tasksExtension } from './config.ts';
import { createThumbnails } from './thumbnails.ts';
import type { TaskWorker } from './task-worker.ts';
import {
callSchema,
getSchema,
cancelSchema,
supportsTasks,
requireTasks,
} from './task-protocol.ts';
export function registerTaskHandlers(server: McpServer, worker: TaskWorker) {
const protocol = server.server;
protocol.registerCapabilities({ extensions: { [tasksExtension]: {} } });
protocol.setRequestHandler('tools/call', callSchema, (params, context) => {
return supportsTasks(context)
? worker.start(params.arguments)
: createThumbnails(params.arguments, worker.options);
});
protocol.setRequestHandler(
'tasks/get',
getSchema,
async (params, context) => {
requireTasks(context);
return {
resultType: 'complete' as const,
...(await worker.store.get(params.taskId)),
};
},
);
protocol.setRequestHandler(
'tasks/cancel',
cancelSchema,
async (params, context) => {
requireTasks(context);
await worker.store.cancel(params.taskId);
return { resultType: 'complete' as const };
},
);
}The extension adds four responsibilities to your server:
| Code | What it does |
|---|---|
registerCapabilities() | Advertises io.modelcontextprotocol/tasks in discovery. tasksExtension is defined in src/config.ts. |
tools/call handler | Checks this request's capabilities. Declaring clients get a task handle from worker.start(); others wait for the ordinary result. |
tasks/get handler | Returns the stored record. Once the task is completed, the record also holds the tool result. |
tasks/cancel handler | Records a request to stop and returns an empty acknowledgement. The worker checks it between images. |
Both tasks/* handlers call requireTasks() first, so a request that does not
declare the extension gets error -32021, as the specification requires.
The schemas and capability checks in task-protocol.ts are supplied project
code, built from the extension's official core/v2 exports. They validate the
messages so that your handlers don't have to carry that boilerplate. The base SDK
also exposes older task types, but this example uses the
versioned extension schemas.
3. Persist the task before returning its ID
Open the supplied src/task-worker.ts. Its start() method saves the task
before it schedules the batch:
async start(input: ThumbnailInput) {
const task = await this.store.create();
const job = new Promise<void>((resolve) => setImmediate(resolve)).then(() =>
this.run(task.taskId, input),
);
this.running.add(job);
void job.finally(() => this.running.delete(job)).catch(console.error);
return { resultType: 'task' as const, ...task };
}The server saves the task first and returns its handle second.
store.create() writes the record to .tasks/ first. Then setImmediate
schedules run() for after the current turn of the event loop, so the response
goes out with the saved record and resultType: 'task' while the batch starts
separately. Because the save has already finished by then, the MCP client can
look up the ID straight away. The running set keeps track of active jobs for
shutdown and for the tests.
The worker keeps running outside the HTTP request handler. After each output it
updates statusMessage, and when the batch ends it saves status: 'completed'
along with the result. This implementation keeps records for one hour and
suggests checking every 500 milliseconds. Both are example settings, not MCP
defaults.
4. Start the MCP server and check a task
In terminal A, run:
pnpm run server --demo-delay-ms 1000Expect:
MCP server: http://127.0.0.1:3001/mcp
Mode: MCP Tasks
Teaching delay: 1000 ms between outputs (not processing time).The delay adds a pause after each output so that you have time to watch the task. Sharp doesn't need it, so leave the flag out for normal processing. Keep terminal A running.
In terminal B, in the same folder, run the supplied probe:
pnpm run probeIt calls your tool with Tasks support and immediately checks the returned ID:
Task handle received: <task-id>
Task is readable: working
The server continues working after this probe exits.Your ID will differ. A completed status is also fine, because the images may
finish before the check. Look in output/ while terminal A is running: the
batch carries on after the probe exits. In the next step you will write your own
MCP client to follow it.
If something goes wrong, check these two cases:
- The probe prints an ordinary result instead of a task handle. Terminal A
is probably running in the wrong mode. Save both edited files, stop the
server, and start it again with
pnpm run server --demo-delay-ms 1000. Do not add--ordinary. - The server says port 3001 is already in use. Start it on another port with
pnpm run server --port 3002, then point the probe at that port:pnpm run probe http://127.0.0.1:3002/mcp.
Checkpoint: your MCP server returns a task ID that you can look up straight away, while the image work carries on in the background.
Step 3
Ready to continue?
Mark this step complete when you have finished the checks above.
Checking saved progress…

