Cancelling a tool call doesn't undo what the tool did: designing agent tools for dropped connections
When the connection drops in the middle of an MCP tool call, the tool may already have acted. What the spec says about cancellation, timeouts and progress, and how to build tools and agents that never do the same thing twice.
On 13 November 2026 the llama.cpp project published pre-release b12344, with a small change to llama-server: when the client disconnects or a timeout hits during an MCP tool call, the tool’s server is now told about the cancellation.
Pull request #32025 describes the problem before the change plainly: if the client disconnected mid-call, llama-server kept waiting until timeout_ms expired, nothing reached the MCP server so it kept working, and its result was then thrown away. After the change, llama-server sends a notifications/cancelled notification with the request id in both cases, as the protocol specification describes.
A good fix. But it raises a bigger question: if the tool already sent an email, created an order or changed a record before the cancellation arrived, who rolls that back? Nobody, unless you designed for it from the start.
What the specification says
The current version of the Model Context Protocol specification is 2026-07-28. Three mechanisms matter here.
Cancellation. The client sends a notifications/cancelled notification carrying the requestId of the request to cancel and an optional reason. How it is signalled depends on the transport: on Streamable HTTP, closing the response stream is enough, and the server must treat a client disconnect as cancellation of that request. On stdio there is no per-request stream, so the client must send the notification explicitly. According to its documentation, llama-server currently supports only the stdio transport for MCP servers.
Timeouts. The spec recommends that the sender set a timeout on every request and, if no response arrives in time, cancel it and stop waiting. It recommends that SDKs let you configure the timeout per request. Implementations may reset the timeout clock when a progress notification arrives, but should always enforce a hard maximum regardless.
Progress. The client puts a progressToken in the request’s _meta, and the server sends notifications/progress messages with progress, an optional total and an optional message. The progress value must increase with every notification.
The line that changes how you think
When a cancellation arrives, the server should stop processing, free resources and not send a response. But the spec allows it to ignore the cancellation if processing has already finished or the request cannot be cancelled. And it states outright that the notification may arrive after processing is done, possibly after the response was sent, and that both sides must handle that race.
In practice: cancellation is a request to stop the remaining work, not a rollback of the work already done. When the connection drops mid-call, there are three possibilities and the client cannot tell them apart:
- The tool hadn’t started anything.
- The tool did part of the work and stopped.
- The tool finished everything, and only the response was lost.
So the first rule is: a cancelled call has an “unknown” outcome, not a “failed” one. Treat it as a failure and you will retry right away, and in case three the action happens twice: two emails, two orders, a double refund.
If you write the tool
1. Accept an idempotency key. The idea is old and proven in payment APIs. Stripe’s documentation explains it this way: the client generates a unique key per operation, the server saves the status code and body of the first request made with that key, returns the saved response on every retry with the same key, and rejects the request if its parameters differ from the original. Stripe suggests V4 UUIDs, and its keys can be up to 255 characters. There is also an IETF draft for an Idempotency-Key header that suggests answering 409 to a concurrent request with the same key and 422 when a key is reused with a different payload; it is still a draft, not a standard.
The MCP spec defines no dedicated field for this in tools/call, so make it an explicit parameter in the tool’s inputSchema. If your tool calls an external service that accepts such keys, pass the same key along.
2. Split “prepare” from “commit” for risky actions. Instead of a single refund_order tool, write two: prepare_refund validates, computes and returns a draft id with a summary, then commit_refund executes that draft exactly once. Preparing is safe to repeat; committing is guarded by the draft id. This matches the spec’s non-normative guidance that a creation tool should return an explicit handle that later calls pass back, since the protocol keeps no state between calls.
3. Stop at safe points. When a cancellation reaches you, don’t cut work off in the middle of a write. Check for cancellation between steps, and make each step all-or-nothing. If you can’t stop safely, finish the step and record it.
4. Report progress on long jobs. Progress notifications tell the client that work is happening so it doesn’t give up early, and the message says how far you got, which is very useful when you later investigate a call that was cut off.
5. Describe your tool honestly in annotations. In the schema, idempotentHint defaults to false and destructiveHint defaults to true. Set them to match what the tool really does, knowing the spec treats them as hints that clients must not rely on when they come from untrusted servers.
If you build the agent
1. An explicit timeout per tool. In llama-server, timeout_ms is set per MCP server, with a default of 30000 (30 seconds). A search tool doesn’t need that long; a report generator may need more. Decide per tool, and keep a hard maximum even with progress notifications.
2. Record every action before it starts. One row per side-effecting call: key, tool, arguments, status, time. Without this log, after a power cut you won’t know what was halfway done.
3. Cancelled means “unknown”, and tell the model so. When a call is cancelled, don’t hand the model text that reads like a failure. Say plainly that the outcome is unknown and that it must not retry before checking.
4. Check state before retrying. Does the order exist in the shop? Did the email go out? Ask the tool or the external system using the same key. If you do retry, always use the same key, never a new one. That’s why the agent’s code, not the model, should generate the key: otherwise the model may invent a fresh key on every attempt.
5. Sweep for stuck actions. Any row still started long after it should have finished needs review, automatic or human.
Example: a status table with a key
This is an illustrative sketch in Python with SQLite that keeps the key and the status table in one place:
import hashlib, json, sqlite3, time
db = sqlite3.connect("actions.db", isolation_level=None) # autocommit
db.execute("""CREATE TABLE IF NOT EXISTS actions (
key TEXT PRIMARY KEY,
tool TEXT NOT NULL,
args_hash TEXT NOT NULL,
status TEXT NOT NULL, -- started | done | failed
result TEXT,
started_at REAL NOT NULL,
updated_at REAL NOT NULL
)""")
class DefinitelyFailed(Exception):
"""Raise only when you know the action left nothing behind."""
def run_once(key, tool, args, do_work):
args_hash = hashlib.sha256(json.dumps(args, sort_keys=True).encode()).hexdigest()
now = time.time()
try:
db.execute("INSERT INTO actions VALUES (?, ?, ?, 'started', NULL, ?, ?)",
(key, tool, args_hash, now, now))
except sqlite3.IntegrityError: # key seen before: never run twice
t, h, status, result = db.execute(
"SELECT tool, args_hash, status, result FROM actions WHERE key = ?",
(key,)).fetchone()
if (t, h) != (tool, args_hash):
raise ValueError("idempotency key reused with different arguments")
return {"status": status, "result": json.loads(result) if result else None}
try:
result = do_work(args, idempotency_key=key) # pass the key downstream too
except DefinitelyFailed as exc:
db.execute("UPDATE actions SET status = 'failed', result = ?, updated_at = ? WHERE key = ?",
(json.dumps(str(exc)), time.time(), key))
raise
# Any other error, crash or cancellation leaves the row 'started' = unknown outcome.
db.execute("UPDATE actions SET status = 'done', result = ?, updated_at = ? WHERE key = ?",
(json.dumps(result), time.time(), key))
return {"status": "done", "result": result}
# Half-finished actions to review:
# SELECT * FROM actions WHERE status = 'started' AND updated_at < strftime('%s','now') - 600;
Three things to notice. A retry with the same key never runs the action again; it returns what was saved, or reports that it is still started. A failure is recorded only when you are sure it left no trace; any other error or a cancellation leaves the row started, meaning “unknown”. And the last query gives you the list of actions that need someone to check them.
The takeaway
The llama.cpp change is the right step: the tool’s server now knows nobody is waiting for it any more. But cancellation only prevents future work; it doesn’t reverse what happened. Design your tools on the assumption that any call can be cut at any moment: a key per action, preparation separate from execution, a timeout per tool, progress for long jobs, and a status log you actually review. And when you don’t know what happened, say “I don’t know” and check, rather than retrying.
