Step 4 of 7
Build an MCP client with Tasks support
Declare support, call the tool and poll for its result.
Your MCP server can now return a task, so the next job is to write an MCP client that can work with one. The client has to declare that it knows how to handle tasks, and then tell a task handle apart from an ordinary result. Keep the MCP server running in terminal A.
1. Write the tool caller
Replace scripts/tasks-client.ts with:
import { connect } from '../src/connection.ts';
import { sampleInput } from '../src/config.ts';
import { watchTask } from '../src/watch-task.ts';
import { z } from 'zod';
const capabilities = {
extensions: { 'io.modelcontextprotocol/tasks': {} },
};
const connection = await connect(process.argv[2], capabilities);
try {
const response = await connection.callTool(sampleInput);
let result;
if (response.resultType === 'task') {
console.log(`Task ID: ${response.taskId}`);
result = await watchTask(connection, response.taskId);
} else {
result = response;
}
if (result) {
const output = z
.object({
content: z.array(
z.object({ type: z.literal('text'), text: z.string() }),
),
isError: z.boolean().optional(),
})
.parse(result);
for (const item of output.content) {
if (item.type === 'text') console.log(item.text);
}
if (output.isError) process.exitCode = 1;
}
} finally {
await connection.close();
}The capabilities object tells the server that this client supports Tasks.
The supplied connect() helper attaches it to every request.
The resultType check matters because the server can answer with either a task
handle or an ordinary result. Both paths end with a tool result, which the
client validates before printing it.
connect(), callTool() and watchTask() are helpers from this project, not
SDK functions. For a larger application, see the official
Tasks client API.
2. Follow the task to its result
Replace src/watch-task.ts with:
import { setTimeout as delay } from 'node:timers/promises';
import { CallToolResultV2Schema } from '@modelcontextprotocol/ext-tasks/core/v2';
import type { Connection } from './connection.ts';
export async function watchTask(
connection: Connection,
taskId: string,
log = console.log,
) {
const deadline = Date.now() + 120_000;
let previous = '';
while (Date.now() < deadline) {
const task = await connection.getTask(taskId);
const message = `${task.status}: ${task.statusMessage ?? ''}`;
if (message !== previous) log(message);
previous = message;
if (task.status === 'completed')
return CallToolResultV2Schema.parse(task.result);
if (task.status === 'cancelled') return undefined;
if (task.status === 'failed') throw new Error(task.error.message);
if (task.status === 'input_required')
throw new Error(
'This example does not handle requests for additional input.',
);
await delay(Math.max(100, task.pollIntervalMs ?? 500));
}
throw new Error(
'Stopped waiting after two minutes; the server may still be working. Run the watch command again.',
);
}On each pass, the loop calls tasks/get through connection.getTask() with the
same ID, and it handles each status like this:
| Status | What watchTask() does |
|---|---|
working | Logs a changed message, waits pollIntervalMs (at least 100 ms), checks again. |
completed | Returns task.result, validated as a tool result. |
failed | Throws the JSON-RPC error message. |
cancelled | Returns undefined, so the caller prints nothing. |
input_required | Throws, because this image tool never asks for input. |
The two-minute deadline stops this MCP client from waiting forever, but it does
not cancel the image processing. And because this image tool never asks for
input, the example simply reports input_required as unsupported. A
general-purpose MCP client would handle those requests and send its answers with
tasks/update.
In this version of the extension, tasks/get includes the final result, so
there is no separate tasks/result request. The
task polling
section of the specification describes this.
3. Run your MCP client
In terminal B:
pnpm run tasks-client
pnpm run verify --outputThe start and end of the output should look like this. Your task ID and folder will differ, and polling may skip some of the intermediate counts:
Task ID: <task-id>
working: Starting the image batch.
working: Created 2 of 18 thumbnails.
...
completed: All thumbnails are ready.
Created 18 thumbnails.
Output: <your-project>/output/<batch-id>
Verified 18 WebP files against manifest.json.Open the output folder and look at one of the WebP files. manifest.json lists
each file's name, width, height and size. The result only points to local files
that your MCP server and MCP client both have access to. It does not transfer the
image files over MCP.
If the connection is refused, check that terminal A is still running. If you
started the server on another port, pass its URL, for example
pnpm run tasks-client http://127.0.0.1:3002/mcp. A TODO error means that one
of this step's files has not been saved yet. If an input image is missing,
regenerate the fixtures.
Checkpoint: your own MCP client declares Tasks support, receives a task ID, checks the task's state, and retrieves a result that describes eighteen verified images. The progress lines are messages stored on the task, so don't read them as a measure of how fast the images are processed.
Step 4
Ready to continue?
Mark this step complete when you have finished the checks above.
Checking saved progress…

