Streaming Tool Calls Over WebSockets: How to handle partial JSON argument chunks and client-side tool cancellation cleanly?
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:
- Partial JSON Parsing: Sending raw
argumentsdelta strings to the frontend causes noisyJSON.parseerrors when we try to render structured previews before the stream finishes. - 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
asynciotool task keeps mutating state!
How do production agent backends structure WebSocket framing and cooperative cancellation for streaming tool calls?