Skip to main content
Back to Community & Earn Hub
Q&A Questionmcp +150 pt Bounty

Streaming Tool Calls Over WebSockets: How to handle partial JSON argument chunks and client-side tool cancellation cleanly?

@maya_lin3 days ago 1633 views

In our real-time agent workspace, we stream OpenAI/Anthropic tool_use delta chunks directly over a FastAPI WebSocket so users see live arguments (e.g. SQL queries or file diffs) as they generate.

Two production headaches keep biting us:

  1. Partial JSON Parsing: Sending raw arguments delta strings to the frontend causes noisy JSON.parse errors when we try to render structured previews before the stream finishes.
  2. Mid-Flight Cancellation: When a user clicks Cancel while an MCP tool call is already executing on the server, our WebSocket closes or ignores the frame—but the background asyncio tool task keeps mutating state!

How do production agent backends structure WebSocket framing and cooperative cancellation for streaming tool calls?

1 Answers

Community Answers

@noah_goldstein Accepted Answer3 days ago

Treat WebSocket tool streaming as a stateful turn protocol with explicit tool_call_id correlation, buffered partial-JSON parsing, and asyncio.Task cancellation registries.


1. Server-Side Partial JSON + Typed Event Envelope

Never push raw unframed token strings to UI widgets. Buffer argument deltas per tool_call_id on the server (or use a streaming partial-JSON parser like jiter / partial-json-parser on the client) and emit typed envelopes:

  • tool_delta: { "call_id": "tc_1", "name": "run_sql", "partial_args": {...} }
  • tool_executing: { "call_id": "tc_1" }
  • tool_cancelled: { "call_id": "tc_1", "reason": "user_abort" }

2. Cooperative asyncio.Task Cancellation Registry

Track active tool tasks per session_id / call_id and pass a cancellation asyncio.Event (or anyio.CancelScope) into your MCP client call:

python
active_tasks: dict[str, asyncio.Task] = {}

async def ws_loop(ws: WebSocket, session_id: str):
    async for msg in ws.iter_json():
        if msg["type"] == "cancel_turn":
            task = active_tasks.pop(session_id, None)
            if task and not task.done():
                task.cancel()
                await ws.send_json({"type": "turn_cancelled", "session_id": session_id})

Inside the tool runner, catch asyncio.CancelledError, send an MCP notifications/cancelled frame to the downstream MCP server, roll back any uncommitted DB transaction, and re-raise cleanly.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.