Contents · 10 sections↓
- 01How do you handle long-running tasks in an MCP server?
- 02How background jobs work in an MCP server
- 03What MCP 2026-07-28 changes for long-running work
- 04What you need
- 05Build a report server with background jobs, step by step
- 06Progress and cancellation on a normal tool call
- 07Fire-and-forget work with BackgroundTasks
- 08Honest limits
- 09Frequently asked questions
- 10Where to go next
Some tools are slow. A quarterly report, a full export or a site crawl can take minutes, and an MCP tool call that takes minutes holds up the agent, the user waiting on it, and sooner or later a client timeout. The fix is the same one web backends use: start the work in the background, hand back a job ID straight away, and let the caller check on it. In this guide you'll build an MCP server in Python whose slow report runs as a background job with progress, retries and cancellation, then put a real agent in front of it. You'll also see what progress notifications, cancellation, timeouts and fire-and-forget tasks do on a normal tool call, what the MCP 2026-07-28 revision changes for long-running work, and where the limits are. Every snippet ran with the MCP SDK 2.3.0 and gpt-5-mini for the agents, and every output is what it printed.
How do you handle long-running tasks in an MCP server?
Don't do the slow work inside the tool call. Register it as a job on a queue, so the agent submits it, gets a job ID back in milliseconds, and checks its status or fetches its result whenever it likes. With Promptise Foundry, that's MCPQueue and the @queue.job() decorator:
import asyncio
from promptise.mcp.server import MCPQueue, MCPServer
server = MCPServer("reports")
queue = MCPQueue(server, max_workers=2)
@queue.job(name="generate_report", timeout=120)
async def generate_report(region: str, quarter: str) -> dict:
"""Build the quarterly sales report for one region."""
await asyncio.sleep(8) # the slow part: queries, joins, rendering
return {"region": region, "quarter": quarter, "url": f"https://reports.example.com/{region}-{quarter}.pdf"}
if __name__ == "__main__":
server.run(transport="http", host="127.0.0.1", port=8185)Passing the server to MCPQueue adds five tools to it and starts the workers when the server starts. Submitting the eight-second report returns at once:
['queue_submit', 'queue_status', 'queue_result', 'queue_cancel', 'queue_list']
0.02s {"job_id": "a9b7ae5c5e8ca083", "status": "pending", "job_type": "generate_report"}The rest of this guide builds this out with progress, retries, cancellation and an agent that uses it.
[02]
How background jobs work in an MCP server
The tool call only puts the job on a queue. A pool of workers inside the server process picks jobs up and runs them, and every later call reads the job's record:
Rendering diagram…
These are the five tools the queue adds. Pass tool_prefix="jobs" to MCPQueue and they become jobs_submit, jobs_status and so on.
Tool | What it does |
|---|---|
queue_submit | Queues a job by job_type with an args dict and an optional priority, and returns its job_id |
queue_status | Returns the status, progress from 0.0 to 1.0, the latest progress message and the attempt count |
queue_result | Returns the result once the job is finished, or the current status while it's still running |
queue_cancel | Cancels a pending or running job |
queue_list | Lists jobs, optionally filtered by status |
A job is pending until a worker takes it, then running, and ends as completed, failed, timeout or cancelled.
These are ordinary MCP tools, so they work for every client and every protocol revision, and the model can read them like any other tool result.
[03]
What MCP 2026-07-28 changes for long-running work
The 2026-07-28 revision of the MCP specification makes every request stand alone. Five of its changes touch slow work:
Progress only reaches an open call. A tool still reports with notifications/progress tied to the progress token of its request. On HTTP these notifications now travel only on that request's own response stream (progress). Once the call has returned, there's nowhere to send progress, which is why a job keeps its progress in its record instead.
Cancelling means closing the stream. On Streamable HTTP, closing a request's response stream is the cancellation signal, and no notifications/cancelled message is sent. On stdio the client still sends notifications/cancelled (cancellation).
No resumable streams. Last-Event-ID is not supported, so a request whose stream breaks is lost and the client sends it again as a new request. For a ten-minute tool call, one dropped connection restarts the work. A job ID survives it.
No sessions, no server-to-client requests. A tool that keeps job IDs in per-session state has nowhere to keep them, and a question to the user becomes an input round: the call ends with an InputRequiredResult, and the client sends the call again with the answer. Step 7 shows what that means for a tool that queues work.
Tasks are an extension. The 2025-11-25 revision had an experimental tasks feature in the core spec. In 2026-07-28 it moved to the official Tasks extension, io.modelcontextprotocol/tasks. A server that supports it may answer a tools/call with a task handle (resultType: "task", a taskId, ttlMs and pollIntervalMs), and the client polls tasks/get, answers questions with tasks/update and cancels with tasks/cancel. Statuses are working, input_required, completed, failed and cancelled, and the server must create the task durably before it answers.
Promptise Foundry (as of 1.10.0) implements the Tasks extension on neither side. Its queue is a set of tools on top of MCP, so it works with clients that know nothing about tasks, and the model decides when to check. Promptise agents connect with the initialize handshake. MCPClient(protocol="auto") uses 2026-07-28 when a server offers it, and both work with everything in this guide.
[04]
What you need
Python 3.10 or newer.
Promptise Foundry 1.7.0 or later from PyPI. The server and the queue need nothing else.
An API key for a model provider for the agent steps. This guide uses OpenAI's gpt-5-mini; other providers work by changing the model string.
pip install "promptise>=1.7.0"
export OPENAI_API_KEY="sk-..."[05]
Build a report server with background jobs, step by step
The server makes quarterly sales reports, which take a while, and exports invoices to an accounting system that sometimes fails. The complete file, report_server.py, is in Step 4.
Turn the slow function into a job
A job is an ordinary async function. Two extra parameters are filled in by the queue, based on their type annotation: a ProgressReporter that writes progress into the job's record, and a CancellationToken that tells the job when someone has cancelled it.
@queue.job(name="generate_report", timeout=120)
async def generate_report(
region: str,
quarter: str,
progress: ProgressReporter,
cancel: CancellationToken,
) -> dict:
"""Build the quarterly sales report for one region."""
data = SALES[region.lower()]
for done, step in enumerate(STEPS):
cancel.check() # stop here if someone called queue_cancel
await progress.report(done, total=len(STEPS), message=step)
await asyncio.sleep(2) # the slow part: queries, joins, rendering
return {
"region": region,
"quarter": quarter,
"net_revenue": data["revenue"] - data["refunds"],
"orders": data["orders"],
"url": f"https://reports.example.com/{region.lower()}-{quarter.lower()}.pdf",
}progress.report(done, total=4, message=...) stores done / total as a fraction, so status shows 0.25, not 25.
cancel.check() raises when the job has been cancelled. Call it between steps, at points where stopping is safe.
timeout=120 is the ceiling for one attempt. The default is 300 seconds, set by default_timeout on MCPQueue.
max_workers=2 on the queue means at most two jobs run at the same time. The rest wait as pending.
Watch a job from a client
Before an agent gets involved, check the queue with a plain MCP client. Start the server with python report_server.py, then run this. It connects with protocol="auto", so it uses the 2026-07-28 revision:
import asyncio
import json
import time
from promptise.mcp.client import MCPClient
def show(result) -> dict:
return json.loads(result.content[0].text)
async def main():
async with MCPClient(url="http://127.0.0.1:8183/mcp", protocol="auto") as client:
print("Protocol:", client.protocol_version)
print("Tools:", [t.name for t in await client.list_tools()])
start = time.perf_counter()
job = show(await client.call_tool(
"queue_submit",
{"job_type": "generate_report", "args": {"region": "EMEA", "quarter": "Q3"}},
))
print(f"{time.perf_counter() - start:.2f}s submit ->", job)
while True:
await asyncio.sleep(1.5)
status = show(await client.call_tool("queue_status", {"job_id": job["job_id"]}))
print(f"{time.perf_counter() - start:.2f}s status ->", status)
if status["status"] not in ("pending", "running"):
break
result = show(await client.call_tool("queue_result", {"job_id": job["job_id"]}))
print(f"{time.perf_counter() - start:.2f}s result ->", json.dumps(result, indent=2))
asyncio.run(main())Protocol: 2026-07-28
Tools: ['queue_submit', 'queue_status', 'queue_result', 'queue_cancel', 'queue_list', 'wait_for_job']
0.06s submit -> {'job_id': '53b673f5436664db', 'status': 'pending', 'job_type': 'generate_report'}
1.57s status -> {'job_id': '53b673f5436664db', 'job_type': 'generate_report', 'status': 'running', 'priority': 'normal', 'progress': 0.0, 'attempts': 1, 'progress_message': 'Loading orders'}
3.08s status -> {'job_id': '53b673f5436664db', 'job_type': 'generate_report', 'status': 'running', 'priority': 'normal', 'progress': 0.25, 'attempts': 1, 'progress_message': 'Matching refunds'}
4.60s status -> {'job_id': '53b673f5436664db', 'job_type': 'generate_report', 'status': 'running', 'priority': 'normal', 'progress': 0.5, 'attempts': 1, 'progress_message': 'Computing totals'}
6.11s status -> {'job_id': '53b673f5436664db', 'job_type': 'generate_report', 'status': 'running', 'priority': 'normal', 'progress': 0.75, 'attempts': 1, 'progress_message': 'Rendering the PDF'}
7.64s status -> {'job_id': '53b673f5436664db', 'job_type': 'generate_report', 'status': 'running', 'priority': 'normal', 'progress': 0.75, 'attempts': 1, 'progress_message': 'Rendering the PDF'}
9.15s status -> {'job_id': '53b673f5436664db', 'job_type': 'generate_report', 'status': 'completed', 'priority': 'normal', 'progress': 1.0, 'attempts': 1, 'progress_message': 'Rendering the PDF'}
9.15s result -> {
"job_id": "53b673f5436664db",
"job_type": "generate_report",
"status": "completed",
"priority": "normal",
"progress": 1.0,
"attempts": 1,
"progress_message": "Rendering the PDF",
"result": {
"region": "EMEA",
"quarter": "Q3",
"net_revenue": 402450.0,
"orders": 1840,
"url": "https://reports.example.com/emea-q3.pdf"
}
}The submit took six hundredths of a second, the status moved from step to step, and the result arrived about nine seconds later. Each of those calls was a request of its own, with no session in between: the job lives on the server, and the job ID is all the client needs. wait_for_job in the tool list is a small tool you'll add in Step 4.
Let an agent submit the job and come back later
The model sees the five queue tools. queue_submit's description lists every registered job type with its docstring and the JSON Schema of its arguments, and job_type only accepts those names. What the tools can't say is how you want the agent to handle slow work, so put that in its instructions:
import asyncio
from promptise import build_agent
from promptise.config import HTTPServerSpec
INSTRUCTIONS = """You are a reporting assistant. Reports are slow, so they run as background jobs.
Job types on the reports server:
- generate_report: args {"region": "EMEA" or "Americas", "quarter": "Q1" to "Q4"}
To produce a report, submit it with queue_submit and check it with queue_status.
When the status is completed, fetch it with queue_result. Don't wait for a
slow job: tell the user the job ID and the progress message, and check again
when they ask.
Answer in short, plain sentences."""
async def main():
agent = await build_agent(
model="openai:gpt-5-mini",
servers={"reports": HTTPServerSpec(url="http://127.0.0.1:8183/mcp")},
instructions=INSTRUCTIONS,
trace_tools=True,
)
try:
messages = [{"role": "user", "content": "I need the Q3 sales report for EMEA."}]
result = await agent.ainvoke({"messages": messages})
print(">>>", result["messages"][-1].content)
await asyncio.sleep(10) # the user does something else for a while
messages = result["messages"] + [{"role": "user", "content": "Is it ready?"}]
result = await agent.ainvoke({"messages": messages})
print(">>>", result["messages"][-1].content)
finally:
await agent.shutdown()
asyncio.run(main())→ Invoking tool: queue_submit with {'job_type': 'generate_report', 'args': {'region': 'EMEA', 'quarter': 'Q3'}}
✔ Tool result from queue_submit: {"job_id": "01d2e6289d43b992", "status": "pending", "job_type": "generate_report"}
>>> I submitted the report job. Job ID: 01d2e6289d43b992. Current status: pending. Check back for progress or results.
→ Invoking tool: queue_status with {'job_id': '01d2e6289d43b992'}
✔ Tool result from queue_status: {"job_id": "01d2e6289d43b992", "job_type": "generate_report", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 1, "progress_message": "Rendering the PDF"}
→ Invoking tool: queue_result with {'job_id': '01d2e6289d43b992'}
✔ Tool result from queue_result: {"job_id": "01d2e6289d43b992", "job_type": "generate_report", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 1, "progress_message": "Rendering the PDF", "result": {"region": "EMEA", "quarter": "Q3", "net_revenue": 402450.0, "orders": 1840, "url": "https://reports.example.com/emea-q3.pdf"}}
>>> The report is ready. Job ID: 01d2e6289d43b992. Progress: Rendering the PDF (completed). Download: https://reports.example.com/emea-q3.pdf.This is the point of a queue. The first turn ended as soon as the job was queued, so the user got an answer instead of a spinner. The job kept running between turns, and the second turn found it completed and fetched the link. The job ID lives in the conversation history, which is why passing result["messages"] into the next turn matters. The model still makes its own choices, so expect some turns to ask before fetching the result.
Let the agent wait without polling
Sometimes the user does want to wait. With only the queue tools, an agent waits by calling queue_status again and again, and each check costs a model round trip. With instructions to keep checking until the job finished, and no other tool to wait with, this is how a run went:
→ Invoking tool: queue_submit with {'job_type': 'generate_report', 'args': {'region': 'EMEA', 'quarter': 'Q3'}}
✔ Tool result from queue_submit: {"job_id": "9024ed104ef9dfcc", "status": "pending", "job_type": "generate_report"}
→ Invoking tool: queue_status with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_status: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "running", "priority": "normal", "progress": 0.0, "attempts": 1, "progress_message": "Loading orders"}
→ Invoking tool: queue_status with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_status: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "running", "priority": "normal", "progress": 0.25, "attempts": 1, "progress_message": "Matching refunds"}
→ Invoking tool: queue_status with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_status: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "running", "priority": "normal", "progress": 0.25, "attempts": 1, "progress_message": "Matching refunds"}
→ Invoking tool: queue_status with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_status: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "running", "priority": "normal", "progress": 0.5, "attempts": 1, "progress_message": "Computing totals"}
→ Invoking tool: queue_status with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_status: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "running", "priority": "normal", "progress": 0.5, "attempts": 1, "progress_message": "Computing totals"}
→ Invoking tool: queue_status with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_status: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "running", "priority": "normal", "progress": 0.75, "attempts": 1, "progress_message": "Rendering the PDF"}
→ Invoking tool: queue_status with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_status: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 1, "progress_message": "Rendering the PDF"}
→ Invoking tool: queue_status with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_status: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 1, "progress_message": "Rendering the PDF"}
→ Invoking tool: queue_result with {'job_id': '9024ed104ef9dfcc'}
✔ Tool result from queue_result: {"job_id": "9024ed104ef9dfcc", "job_type": "generate_report", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 1, "progress_message": "Rendering the PDF", "result": {"region": "EMEA", "quarter": "Q3", "net_revenue": 402450.0, "orders": 1840, "url": "https://reports.example.com/emea-q3.pdf"}}
>>> The Q3 EMEA sales report is ready.
Net revenue: 402,450. Orders: 1,840.
Download the PDF: https://reports.example.com/emea-q3.pdf.
Would you like a breakdown or key insights from the report?
(20.1s)Eight status checks, each one a model round trip, and the agent checked once more after the status said completed before it fetched the result. The turn took 20 seconds for an eight-second job. Every check reached the server: its log shows a POST /mcp request for each of the ten tool calls, plus three for the connection handshake. It works, but the model sets the pace, not the job, and every check costs a model call.
A better way is one tool that waits on the server side and returns when the job finishes or the time is up. It uses the queue's own status() method, so it reads the same record as queue_status. Here it is in the complete server:
import asyncio
import time
from typing import Annotated
from pydantic import Field
from promptise.mcp.server import CancellationToken, MCPQueue, MCPServer, ProgressReporter
server = MCPServer("reports")
queue = MCPQueue(server, max_workers=2)
# A stand-in for your warehouse and your accounting system.
SALES = {
"emea": {"orders": 1840, "revenue": 412_300.0, "refunds": 9_850.0},
"americas": {"orders": 2310, "revenue": 598_120.0, "refunds": 14_200.0},
}
STEPS = ["Loading orders", "Matching refunds", "Computing totals", "Rendering the PDF"]
export_attempts: dict[str, int] = {}
@queue.job(name="generate_report", timeout=120)
async def generate_report(
region: str,
quarter: str,
progress: ProgressReporter,
cancel: CancellationToken,
) -> dict:
"""Build the quarterly sales report for one region."""
data = SALES[region.lower()]
for done, step in enumerate(STEPS):
cancel.check() # stop here if someone called queue_cancel
await progress.report(done, total=len(STEPS), message=step)
await asyncio.sleep(2) # the slow part: queries, joins, rendering
return {
"region": region,
"quarter": quarter,
"net_revenue": data["revenue"] - data["refunds"],
"orders": data["orders"],
"url": f"https://reports.example.com/{region.lower()}-{quarter.lower()}.pdf",
}
@queue.job(name="export_invoices", timeout=60, max_retries=2, backoff_base=2.0)
async def export_invoices(month: str) -> dict:
"""Send one month of invoices to the accounting system."""
export_attempts[month] = export_attempts.get(month, 0) + 1
await asyncio.sleep(1)
if export_attempts[month] == 1:
raise ConnectionError("accounting API answered 503 Service Unavailable")
return {"month": month, "invoices": 214, "file": f"invoices-{month}.csv"}
@server.tool()
async def wait_for_job(
job_id: str,
seconds: Annotated[int, Field(ge=1, le=25, description="How long to wait at most.")] = 20,
) -> dict:
"""Wait for a background job to finish, then return its status.
Use this instead of calling queue_status again and again. It returns as soon as
the job is completed, failed, cancelled or timed out, or when the time is up.
"""
deadline = time.monotonic() + seconds
while True:
status = await queue.status(job_id)
if status["status"] not in ("pending", "running") or time.monotonic() >= deadline:
return status
await asyncio.sleep(0.5)
if __name__ == "__main__":
server.run(transport="http", host="127.0.0.1", port=8183)The 25-second cap keeps each call well inside client timeouts; if the job needs longer, the agent simply calls it again. The agent's instructions now list both job types and say: "When the user wants to wait for the result, call wait_for_job instead of polling queue_status". Asked for two things at once, it ran them side by side:
→ Invoking tool: queue_submit with {'job_type': 'export_invoices', 'args': {'month': '2026-09'}}
→ Invoking tool: queue_submit with {'job_type': 'generate_report', 'args': {'region': 'Americas', 'quarter': 'Q3'}}
✔ Tool result from queue_submit: {"job_id": "5f75ed6003bb9424", "status": "pending", "job_type": "export_invoices"}
✔ Tool result from queue_submit: {"job_id": "b49b8c416d395414", "status": "pending", "job_type": "generate_report"}
→ Invoking tool: wait_for_job with {'job_id': '5f75ed6003bb9424', 'seconds': 25}
→ Invoking tool: wait_for_job with {'job_id': 'b49b8c416d395414', 'seconds': 25}
✔ Tool result from wait_for_job: {"job_id": "5f75ed6003bb9424", "job_type": "export_invoices", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 2}
✔ Tool result from wait_for_job: {"job_id": "b49b8c416d395414", "job_type": "generate_report", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 1, "progress_message": "Rendering the PDF"}
→ Invoking tool: queue_result with {'job_id': '5f75ed6003bb9424'}
✔ Tool result from queue_result: {"job_id": "5f75ed6003bb9424", "job_type": "export_invoices", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 2, "result": {"month": "2026-09", "invoices": 214, "file": "invoices-2026-09.csv"}}
→ Invoking tool: queue_result with {'job_id': 'b49b8c416d395414'}
✔ Tool result from queue_result: {"job_id": "b49b8c416d395414", "job_type": "generate_report", "status": "completed", "priority": "normal", "progress": 1.0, "attempts": 1, "progress_message": "Rendering the PDF", "result": {"region": "Americas", "quarter": "Q3", "net_revenue": 583920.0, "orders": 2310, "url": "https://reports.example.com/americas-q3.pdf"}}
>>> Both jobs finished.
The September 2026 invoices export completed. 214 invoices exported. File: invoices-2026-09.csv.
The Americas Q3 report completed. Net revenue: 583,920. Orders: 2,310. Report URL: https://reports.example.com/americas-q3.pdf.
Do you want me to download the files or send them somewhere?
(18.9s)The model asked to wait 25 seconds, the most le=25 allows: the limit is part of the schema the model sees. A client that asks for more anyway gets a VALIDATION_ERROR, Invalid input: seconds: Input should be less than or equal to 25, so each call stays well inside client timeouts. One wait per job was enough, and the export's retry happened without the agent having to do anything: the export came back with "attempts": 2.
Keep the instructions and the tools in agreement. With the polling instructions from earlier ("Keep checking with queue_status until the job is completed") and wait_for_job on the server, the agent called queue_status five times before it switched to wait_for_job: the instructions won over the tool's description. And nothing in the tools makes the model fetch every result. If a result must not be dropped, check the job list yourself after the turn rather than relying on the model to.
Retry jobs that fail
export_invoices fails on its first attempt with a ConnectionError, the kind of transient error worth retrying. max_retries=2 allows two more attempts, and backoff_base=2.0 sets the wait between them: backoff_base * 2 ** (attempt - 1), so 2 seconds, then 4. A small client that prints each change of status shows the whole cycle:
0.0s {'job_id': '58dc83a8c0b1af7f', 'job_type': 'export_invoices', 'status': 'running', 'priority': 'normal', 'progress': 0.0, 'attempts': 1}
1.2s {'job_id': '58dc83a8c0b1af7f', 'job_type': 'export_invoices', 'status': 'pending', 'priority': 'normal', 'progress': 0.0, 'attempts': 1, 'error': 'Attempt 1 failed: accounting API answered 503 Service Unavailable. Retrying in 2.0s.'}
3.2s {'job_id': '58dc83a8c0b1af7f', 'job_type': 'export_invoices', 'status': 'running', 'priority': 'normal', 'progress': 0.0, 'attempts': 2, 'error': 'Attempt 1 failed: accounting API answered 503 Service Unavailable. Retrying in 2.0s.'}
4.2s {'job_id': '58dc83a8c0b1af7f', 'job_type': 'export_invoices', 'status': 'completed', 'priority': 'normal', 'progress': 1.0, 'attempts': 2}
result: {'month': '2026-09', 'invoices': 214, 'file': 'invoices-2026-09.csv'}What to notice:
Between attempts the job is
pendingagain, with the failure in error. Once a retry succeeds, error is cleared, and attempts shows how many tries it took.Timeouts aren't retried. A job that runs past its timeout ends as timeout with
Job timed out after 1sin error, on the first attempt.The worker is free during the backoff. A failed attempt schedules its retry and hands the worker back at once. With max_workers=1, a second job submitted half a second after the first one failed was done 0.7 seconds after the first was submitted, while the first was still waiting out its four-second backoff.
Wrong arguments never become a job. queue_submit checks args against the job function's signature, so a job submitted without its quarter argument was refused at once, with nothing queued and nothing retried. The error names the field and shows the schema to use:
{
"error": {
"code": "INVALID_JOB_ARGUMENTS",
"message": "Invalid arguments for job type 'needs_args': quarter: Field required",
"retryable": false,
"suggestion": "Pass `args` matching this schema: {\"additionalProperties\":false,\"properties\":{\"quarter\":{\"type\":\"string\"},\"region\":{\"type\":\"string\"}},\"required\":[\"region\",\"quarter\"],\"type\":\"object\"}",
"details": {
"field_errors": {
"quarter": "Field required"
}
}
}
}Cancel a job
queue_cancel marks the job as cancelled, sets its CancellationToken and cancels the job's task right away. Whatever the job returns afterwards is discarded:
import asyncio
import json
from promptise.mcp.client import MCPClient
def show(result) -> dict:
return json.loads(result.content[0].text)
async def main():
async with MCPClient(url="http://127.0.0.1:8183/mcp") as client:
job = show(await client.call_tool(
"queue_submit", {"job_type": "generate_report", "args": {"region": "Americas", "quarter": "Q3"}}
))
await asyncio.sleep(3)
print("before:", show(await client.call_tool("queue_status", {"job_id": job["job_id"]})))
print("cancel:", show(await client.call_tool("queue_cancel", {"job_id": job["job_id"]})))
await asyncio.sleep(10) # long after the job would have finished
print("later: ", show(await client.call_tool("queue_result", {"job_id": job["job_id"]})))
asyncio.run(main())before: {'job_id': '7cebaf7017038317', 'job_type': 'generate_report', 'status': 'running', 'priority': 'normal', 'progress': 0.25, 'attempts': 1, 'progress_message': 'Matching refunds'}
cancel: {'job_id': '7cebaf7017038317', 'status': 'cancelled'}
later: {'job_id': '7cebaf7017038317', 'job_type': 'generate_report', 'status': 'cancelled', 'priority': 'normal', 'progress': 0.25, 'attempts': 1, 'progress_message': 'Matching refunds'}The job was in its second step and stopped there, so it never reached "Computing totals", and ten seconds later it's still cancelled with no result.
Ask the user before you queue the work
Some jobs shouldn't start without a yes, like sending a month of invoices to the accounting system. A tool can ask with Elicitor and queue the job itself with queue.submit(). The order of those two lines matters on 2026-07-28, because there the question is an input round: the tool call ends with the question, the client sends the call again with the answer, and the tool runs again from the start. These two tools differ only in the order:
@server.tool()
async def export_month_unsafe(month: str, elicit: Elicitor = Depends(Elicitor)) -> dict:
"""Queue the export, then ask. On 2026-07-28 the first line runs once per round."""
job = await queue.submit("export_invoices", {"month": month})
answer = await elicit.ask(f"Send the {month} invoices to the accounting system?", schema=CONFIRM)
if not answer or not answer.get("confirm"):
await queue.cancel(job["job_id"])
return {"submitted": False}
return job
@server.tool()
async def export_month(month: str, elicit: Elicitor = Depends(Elicitor)) -> dict:
"""Ask first, then queue the export: the job is submitted once, after the answer."""
answer = await elicit.ask(f"Send the {month} invoices to the accounting system?", schema=CONFIRM)
if not answer or not answer.get("confirm"):
return {"submitted": False, "reason": elicit.last_failure or "not confirmed"}
return await queue.submit("export_invoices", {"month": month})A client that answers yes called each tool once with the handshake and once with protocol="auto", and counted the jobs in queue_list before and after each call. A third tool kept the job ID in SessionState:
--- 2025-11-25
asked: Send the 2026-09 invoices to the accounting system?
export_month_unsafe: {'job_id': '6eea918fb6f2fa74', 'status': 'pending', 'job_type': 'export_invoices'}, jobs queued: 1
asked: Send the 2026-09 invoices to the accounting system?
export_month: {'job_id': '0068fd86495992d6', 'status': 'pending', 'job_type': 'export_invoices'}, jobs queued: 1
remember_job: {'jobs': ['0068fd86495992d6']}
--- 2026-07-28
asked: Send the 2026-09 invoices to the accounting system?
export_month_unsafe: {'job_id': '61d3bba1cbc160dd', 'status': 'pending', 'job_type': 'export_invoices'}, jobs queued: 2
asked: Send the 2026-09 invoices to the accounting system?
export_month: {'job_id': 'a1c9fbaa29126662', 'status': 'pending', 'job_type': 'export_invoices'}, jobs queued: 1
remember_job: SESSION_REQUIREDOn the handshake, ask() waits for the answer inside the call, so both tools queued one job. On 2026-07-28, export_month_unsafe queued a job in the round that asked and another in the round that got the answer, and nothing cancelled the first: the invoices would go out twice. Put every side effect after the answer, as export_month does. And keep job IDs where 2026-07-28 clients can reach them: in the tool's result, or in your own store keyed by the caller, not in SessionState, which answers SESSION_REQUIRED when there is no session.
[06]
Progress and cancellation on a normal tool call
Not everything needs a queue. A tool that takes ten or twenty seconds can stay a normal tool and still tell the client how it's doing. ProgressReporter and CancellationToken work there too, injected with Depends:
@server.tool()
async def crawl_site(pages: int, progress: ProgressReporter = Depends(ProgressReporter)) -> dict:
"""Crawl a number of pages and report progress as it goes."""
for page in range(1, pages + 1):
await asyncio.sleep(0.5)
await progress.report(page, total=pages, message=f"Crawled page {page} of {pages}")
return {"pages": pages}Here, report() sends MCP progress notifications to the client while the call is still running. A client only receives them if it asked for them by sending a progress token with the call. The official MCP Python SDK's Client (from mcp import Client, new in SDK 2.x, and on 2026-07-28 by default) does that when you pass a progress_callback:
async def on_progress(progress, total, message):
print(f" progress {progress}/{total}: {message}")
async with Client(URL) as client:
print("official client, with progress_callback:")
r = await client.call_tool("crawl_site", {"pages": 3}, progress_callback=on_progress)
print(" result:", r.content[0].text)official client, with progress_callback:
progress 1.0/3.0: Crawled page 1 of 3
progress 2.0/3.0: Crawled page 2 of 3
progress 3.0/3.0: Crawled page 3 of 3
result: {"pages": 3}
Promptise MCPClient, without progress_callback:
result: {"pages": 3}
Promptise MCPClient, with progress_callback:
progress 1.0/3.0: Crawled page 1 of 3
progress 2.0/3.0: Crawled page 2 of 3
progress 3.0/3.0: Crawled page 3 of 3
result: {"pages": 3}
Promptise MCPClient, protocol=2026-07-28, with progress_callback:
progress 1.0/3.0: Crawled page 1 of 3
progress 2.0/3.0: Crawled page 2 of 3
progress 3.0/3.0: Crawled page 3 of 3
result: {"pages": 3}Promptise's own MCP client asks for progress when you pass progress_callback= to call_tool, with the handshake and with protocol="auto", and sends no progress token without one, so the server then sends nothing. An agent gets the same with build_agent(on_tool_progress=...), and trace_tools=True prints each notification:
import asyncio
from promptise import build_agent
from promptise.config import HTTPServerSpec
async def on_tool_progress(tool_name, progress, total, message):
print(f" [{tool_name}] {progress:.0f}/{total:.0f} {message}")
async def main():
agent = await build_agent(
model="openai:gpt-5-mini",
servers={"direct": HTTPServerSpec(url="http://127.0.0.1:8184/mcp")},
instructions="Use your tools. Answer in one plain sentence.",
on_tool_progress=on_tool_progress,
trace_tools=True,
)
try:
result = await agent.ainvoke({"messages": [{"role": "user", "content": "Crawl 3 pages."}]})
print(">>>", result["messages"][-1].content)
finally:
await agent.shutdown()
asyncio.run(main())→ Invoking tool: crawl_site with {'pages': 3}
… crawl_site progress 1/3: Crawled page 1 of 3
[crawl_site] 1/3 Crawled page 1 of 3
… crawl_site progress 2/3: Crawled page 2 of 3
[crawl_site] 2/3 Crawled page 2 of 3
… crawl_site progress 3/3: Crawled page 3 of 3
[crawl_site] 3/3 Crawled page 3 of 3
✔ Tool result from crawl_site: {"pages": 3}
>>> I crawled 3 pages.The model never sees progress notifications; they're for a person watching. All it got was the tool's result, {"pages": 3}, so "I crawled 3 pages" is the model's reading of a bare number: nothing in the result says the crawl finished, or that every page worked. Make a result say what happened, for example {"pages_crawled": 3, "status": "done"}. If the agent needs to know how far along something is, use a queue job, whose progress the agent can read with queue_status.
Cancelling a normal tool call works much like cancelling a job. When the client cancels, Promptise sets the tool's CancellationToken and gives the handler cancel_grace_period (5 seconds by default, set on MCPServer) to stop on its own before its task is cancelled. A handshake client cancels with a notifications/cancelled message; a 2026-07-28 client over HTTP closes the response stream. A tool that waited on its token logged this when the official client (2026-07-28) and then Promptise's MCPClient (handshake) cancelled it:
22:56:26 watch_feed: token set, token.is_cancelled=True
22:56:28 watch_feed: token set, token.is_cancelled=TrueSo cancel.wait() and cancel.check() work on a normal tool with both kinds of client. Still put cleanup that must run in a try/finally: a handler that ignores the token is cancelled once the grace period is over.
When a normal tool call times out
@server.tool(timeout=...) caps a normal call. This tool needs five seconds and is allowed two:
@server.tool(timeout=2)
async def sync_inventory(warehouse: str) -> dict:
"""Push one warehouse's stock counts to the shop."""
await asyncio.sleep(5) # longer than its 2-second limit
return {"warehouse": warehouse, "synced": True}sync_inventory: {
"error": {
"code": "TIMEOUT",
"message": "Tool 'sync_inventory' did not finish within 2s, so its outcome is unknown.",
"retryable": false,
"suggestion": "Whether the call took effect is unknown: it may have completed before it was stopped. Check whether it did (for example by looking the result up) before calling the tool again; do not simply retry it.",
"details": {
"outcome": "unknown",
"timeout_seconds": 2
}
}
}A timed-out call may already have done its work, so the error tells the model not to simply call the tool again. It says retryable: true only for a tool marked read_only_hint=True or idempotent_hint=True. That's one more reason to move work you can't afford to repeat into a job, whose status the model can check instead of guessing.
[07]
Fire-and-forget work with BackgroundTasks
BackgroundTasks is for small jobs after a tool has done its real work, such as sending a receipt or writing an analytics event. You add callables during the tool call, and they run after the response has gone out:
async def send_receipt(order_id: str) -> None:
await asyncio.sleep(3) # a slow email API
print(f"{time.strftime('%X')} receipt sent for {order_id}", flush=True)
@server.tool()
async def place_order(order_id: str, bg: BackgroundTasks = Depends(BackgroundTasks)) -> dict:
"""Place an order and email the receipt afterwards."""
bg.add(send_receipt, order_id)
print(f"{time.strftime('%X')} handler returned for {order_id}", flush=True)
return {"order_id": order_id, "status": "placed"}Errors in background tasks are logged and never reach the caller. Here's the timing over HTTP. The server printed:
22:56:25 handler returned for A-1001
22:56:28 receipt sent for A-1001And the client calling place_order printed:
22:56:25 place_order answered after 0.03s: {"order_id": "A-1001", "status": "placed"}The caller got its answer at once, and the receipt went out three seconds later. On a graceful shutdown the server waits for background tasks that are still running. Under TestClient they run before call_tool returns, so a test can check their effects. They have no ID, status or retries, so make anything slow or likely to fail a queue job.
Here's how to choose:
The work takes | Use | The agent sees |
|---|---|---|
A few seconds | A normal tool | The result |
Up to a minute or so | A normal tool with ProgressReporter | The result; a client UI can show progress |
Minutes, or it may fail and need retries | An MCPQueue job | A job ID now, status and result later |
Short follow-up work | BackgroundTasks | The result at once; the tasks run after it |
[08]
Honest limits
These are true of Promptise Foundry 1.10.0. Each one was checked in a run or in the source.
Jobs live in memory. The only backend that ships is InMemoryQueueBackend. When the server restarts, every job and result is gone: asked about a job submitted before the restart, the server answered JOB_NOT_FOUND. There's no persistence and no Redis backend. You can write your own against the QueueBackend protocol, seven async methods from enqueue to count, but nothing re-runs jobs that were running when a process died.
One queue per process. With two replicas, a job submitted to one is JOB_NOT_FOUND on the other. Sticky sessions keep a handshake client on one replica, but 2026-07-28 clients have no session to stick to, so route them by a key of your own, such as the API key, or run one replica. A shared backend alone doesn't fix cancellation, because the cancellation signal is held in the memory of the process running the job.
Job ownership needs authentication. On a server with require_auth=True, or with MCPQueue(auth=True), each caller sees and cancels only its own jobs: in a test with two API keys, the second caller's queue_list was empty, and the first caller's job answered it JOB_NOT_FOUND. A caller with the admin role sees every job of its own tenant. Without authentication, all callers share one anonymous owner, so don't expose the queue tools that way on a shared server.
Results expire. Finished jobs are removed after result_ttl, one hour by default, checked every cleanup_interval of 60 seconds.
No MCP Tasks. Foundry doesn't implement the io.modelcontextprotocol/tasks extension, as a server or as a client, so a client that expects task handles gets ordinary tool results.
Testing needs a manual start. TestClient doesn't run startup hooks, so queue workers don't start and submitted jobs stay pending. Call await queue.start() in your test and await queue.stop() after it. call_tool returns MCP content, so read the job with json.loads(resp[0].text).
[09]
Frequently asked questions
How do I fix an MCP tool timeout?
Stop making the client wait for the whole job. Turn the slow tool into a queue job, so the call that starts it returns a job ID at once and nothing long-running is left to time out. Through Promptise's MCP client, plain tool calls that took 45 seconds and 330 seconds both came back fine, so when you do hit a timeout, check the client you use, any proxy in between, and TimeoutMiddleware or timeout= on the server. Whatever the limit, a job ID sidesteps it, and it also survives a dropped connection, which on MCP 2026-07-28 loses a plain call.
How do MCP progress notifications work?
The client sends a progress token with a tool call, and the server sends notifications/progress messages tied to that token while the call runs, each with a number, an optional total and a message. On the 2026-07-28 revision they travel only on the response stream of that call. In Promptise, ProgressReporter.report() sends them, and does nothing when the client didn't ask; Promptise's client asks when you pass progress_callback= (or on_tool_progress= to build_agent). They show in client UIs; the model doesn't see them. The MCP specification has the details.
Does MCP have a built-in way to run long tasks?
Yes, as an extension. The 2025-11-25 revision added experimental tasks to the core protocol, and in 2026-07-28 they became the official Tasks extension: a server may answer a tool call with a task ID, and the client polls tasks/get, answers questions with tasks/update and cancels with tasks/cancel. Both sides have to support the extension. Promptise Foundry (as of 1.10.0) doesn't implement it; its MCPQueue offers the same pattern as ordinary tools that every client can call.
What's the difference between BackgroundTasks and an MCP job queue?
BackgroundTasks runs small follow-up work after one tool call has answered, with no ID, status or retries. MCPQueue runs jobs on separate workers, gives each a job ID, and adds progress, retries, timeouts and cancellation. Use the queue for anything that takes noticeable time.
Can the MCP job queue use Redis?
Not out of the box in Promptise 1.10.0. MCPQueue takes any object that implements the QueueBackend protocol through its backend argument, so you can write a Redis or Postgres backend yourself. The Queue & Background Jobs page shows the methods to implement.
Should the agent wait for a background job?
Usually not. The value of a job is that the conversation can move on, as in Step 3. When the user does want to wait, give the agent a tool that waits on the server side, like wait_for_job in Step 4, instead of letting it poll, and say so in its instructions.
[10]
Where to go next
Queue & Background Jobs: every MCPQueue option, priorities, backends and health checks.
Resilience Patterns: BackgroundTasks, ProgressReporter, CancellationToken and the circuit breaker.
Production Features: caching, rate limits, timeouts and the order to add middleware in.
Deployment: running an MCP server over HTTP in production.
MCP client: MCPClient, progress callbacks and protocol="auto".
MCP Transports: stdio vs Streamable HTTP vs SSE: sessions, the 2026-07-28 revision and replicas.
How to Connect MCP Servers to Your AI Agent in Python: the agent and client basics this guide builds on.
OpenAPI to MCP: Turn Any REST API into an MCP Server: generate a server from an existing API, then add jobs for its slow endpoints.
Idempotent Tool Calls: Make AI Agent Retries Safe: keep a retried or timed-out job submission from starting the work twice.
MCP 2026-07-28 Migration: Make Your MCP Server Stateless: what changes for servers and clients on the 2026-07-28 revision.
Long-Running AI Tasks: Write a Brief That Lasts Hours: the same problem from the user's side, for tasks an assistant runs for hours.