Metadata-Version: 2.5
Name: toolfix
Version: 0.1.0
Summary: OpenAI-compatible proxy that repairs broken tool calls from local models (Ollama, vLLM, LM Studio, llama.cpp) so coding agents stop stalling.
Project-URL: Homepage, https://github.com/boscofoulsham/toolfix
Project-URL: Repository, https://github.com/boscofoulsham/toolfix
Project-URL: Issues, https://github.com/boscofoulsham/toolfix/issues
Project-URL: Changelog, https://github.com/boscofoulsham/toolfix/blob/main/CHANGELOG.md
Author: Bosco Foulsham
License-Expression: MIT
License-File: LICENSE
Keywords: coding-agent,function-calling,llama.cpp,llm,lm-studio,ollama,openai,proxy,qwen,tool-calling,vllm
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: markdown-it-py>=3.0
Requires-Dist: uvicorn>=0.30
Description-Content-Type: text/markdown

# toolfix

A small OpenAI-compatible proxy that sits between your coding agent and a local model server (Ollama, vLLM, LM Studio, llama.cpp) and repairs broken tool calls, so the agent stops stalling.

## Why

I kept pointing tool-using agents at local open-weight models and watching them stall: the model had clearly decided to call a tool, but the call came back as text in `content` (Hermes JSON, Qwen3-Coder XML, `[TOOL_CALLS]`, bare JSON), wrapped in `<think>`, slightly malformed, or not at all. Server-side parsers fix this per model and per release, and they lag behind new models. toolfix fixes it once, in front of any OpenAI-compatible server, and leaves everything else alone.

Some of the reports that made me build it:

- [ollama/ollama#14493](https://github.com/ollama/ollama/issues/14493): Qwen 3.5 27B tool calling "completely non-functional"; calls arrive as `<tool_call><function=...>` text.
- [vllm-project/vllm#39056](https://github.com/vllm-project/vllm/issues/39056): vLLM loses Qwen3.5 tool calls when the XML is emitted inside `<think>`.
- [QwenLM/Qwen3-Coder#475](https://github.com/QwenLM/Qwen3-Coder/issues/475): Qwen3-Coder 30B drops the opening `<tool_call>` tag, so the server never sees a call.

## Real output

`toolfix parse` repairs a saved response offline. This is the Qwen3-Coder XML example shipped in `examples/`, run with the installed CLI (verbatim):

```text
$ toolfix parse examples/qwen3-coder-response.json --tools examples/tools.json
status:  repaired (2 tool calls)
format:  qwen3_coder_xml

before (message.content, finish_reason=stop):
  <think>
  The test for the invoice total is failing. I should read the test before touching the code.
  </think>
  I'll read the failing test first, then run it on its own.

  <tool_call>
  <function=read_file>
  <parameter=path>
  tests/test_invoice.py
  </parameter>
  <parameter=max_lines>
  80
  </parameter>
  </function>
  </tool_call>
  <tool_call>
  <function=run_command>
  <parameter=command>
  pytest tests/test_invoice.py -q
  </parameter>
  <parameter=timeout_seconds>
  120
  </parameter>
  </function>
  </tool_call>

after (finish_reason=tool_calls):
  content: "I'll read the failing test first, then run it on its own."
  tool_calls[0]: read_file {"path": "tests/test_invoice.py", "max_lines": 80}
  tool_calls[1]: run_command {"command": "pytest tests/test_invoice.py -q", "timeout_seconds": 120}
```

Note `max_lines` and `timeout_seconds` became integers because the tool schema says so, the reasoning was stripped, and the prose was kept.

`examples/demo.py` runs the real proxy (`toolfix serve`) between a plain HTTP client and a fake model server that answers in Qwen3-Coder XML. Output of one run (verbatim; the call id, ports and timing differ per run):

```text
$ python examples/demo.py
x-toolfix: repaired  x-toolfix-format: qwen3_coder_xml
{
  "index": 0,
  "message": {
    "role": "assistant",
    "content": "I'll read the failing test first.",
    "tool_calls": [
      {
        "id": "call_21uqq2chYXLSdMf5CNitwXah",
        "type": "function",
        "function": {
          "name": "read_file",
          "arguments": "{\"path\": \"tests/test_invoice.py\", \"max_lines\": 80}"
        }
      }
    ]
  },
  "finish_reason": "tool_calls"
}

proxy log (stderr):
toolfix 0.1.0 listening on http://127.0.0.1:47203/v1 -> http://127.0.0.1:47250 (retries=1, strip-think=on)
toolfix: 200 POST /v1/chat/completions model=qwen3-coder-xml stream=no repaired format=qwen3_coder_xml calls=1 retries=0 238ms
```

## Quickstart

You need [uv](https://docs.astral.sh/uv/) (or pip) and Python 3.10 or newer.

```sh
# 1. start the proxy in front of your model server (Ollama here)
uvx toolfix serve --upstream http://localhost:11434

# 2. point your agent's OpenAI-compatible base URL at the proxy
#    http://127.0.0.1:4000/v1   (any API key; it is passed through untouched)
```

Check whether your model needs it at all (sends one canned tool-calling request straight to the model server and shows raw vs repaired):

```sh
uvx toolfix test --upstream http://localhost:11434 --model qwen3-coder:30b
```

> **Try it before it's published.** toolfix is not on PyPI yet, so `uvx toolfix` will not find it. From a checkout of this repository:
>
> ```sh
> uv build
> uvx --from ./dist/toolfix-0.1.0-py3-none-any.whl toolfix parse examples/qwen3-coder-response.json --tools examples/tools.json
> uvx --from ./dist/toolfix-0.1.0-py3-none-any.whl toolfix serve --upstream http://localhost:11434
> ```
>
> or `pip install ./dist/toolfix-0.1.0-py3-none-any.whl` into any virtualenv and run `toolfix ...`.

## Usage

### `toolfix serve`

```text
toolfix serve --upstream URL [--host 127.0.0.1] [--port 4000] [--retries 1]
              [--no-strip-think] [--reasoning leading|lone-close]
              [--strict-schema] [--log-content] [--timeout 600]
              [--keepalive 10] [--quiet]
```

| Flag | Default | What it does |
| --- | --- | --- |
| `--upstream URL` | required | Model server base URL. `http://host:port` and `http://host:port/v1` both work. |
| `--host` | `127.0.0.1` | Address to listen on. Anything other than localhost exposes your model server; toolfix has no auth of its own. |
| `--port` | `4000` | Port to listen on (`0` picks a free one and prints it). |
| `--retries N` | `1` | Resend the identical request up to N times when the reply is empty (no content and no tool call). |
| `--no-strip-think` | off | Keep `<think>...</think>` reasoning in `content`. By default a leading reasoning block is removed when the request has tools. |
| `--reasoning MODE` | `leading` | What counts as reasoning. `leading`: a complete `<think>...</think>` that starts the reply. `lone-close`: also leading text that ends in a lone `</think>`, for DeepSeek-R1-style templates that put `<think>` in the prompt. |
| `--strict-schema` | off | If a recovered call's arguments fail the tool's JSON schema (missing required key, wrong type), leave the response untouched instead. |
| `--log-content` | off | Also log model output before and after repair, plus repair notes. Off by default: toolfix never logs content otherwise. |
| `--timeout SECONDS` | `600` | Upstream read timeout. Timeouts become HTTP 504, unreachable upstreams 502. Not applied to streaming tool requests while keep-alives are on (see below). |
| `--keepalive SECONDS` | `10` | While a streaming request with tools is being buffered, send an SSE comment (`: keep-alive`) this often so the agent does not time out. `0` turns it off. |
| `--quiet` | off | No per-request log lines. |

Every request goes to the upstream with its method, path, query, body and headers (including `Authorization` and `Cookie`), minus `Host` and hop-by-hop headers. toolfix adds no headers of its own and keeps no cookies between requests. Only `POST .../chat/completions` requests that define `tools` (or legacy `functions`) and do not set `tool_choice: "none"` are inspected; for those it asks the upstream for an uncompressed JSON reply (`Accept: application/json`, `Accept-Encoding: identity`). Their body goes upstream as the client sent it, byte for byte, except that a streaming request has its `"stream"` value set to `false` and its `"stream_options"` removed (toolfix needs the whole reply); nothing else in it is re-encoded. Everything else, including chat requests without tools, streams through byte for byte. When nothing needed repairing, a non-streaming reply is also passed back byte for byte. If the client disconnects (for example you press Stop in the agent), toolfix closes the upstream request, so the model server stops generating.

One line per request goes to stderr:

```text
toolfix: 200 POST /v1/chat/completions model=qwen3-coder-xml stream=no repaired format=qwen3_coder_xml calls=1 retries=0 90ms
```

Inspected responses carry headers (unless a keep-alive was already sent, see Limits): `x-toolfix` (`repaired`, `normalised`, `unparsed`, `think-stripped`, `unchanged`, or `skipped` when the upstream body is not a completion), `x-toolfix-format` and `x-toolfix-retries`. `GET /toolfix/stats` returns counters as JSON (requests, repaired, normalised, unparsed, retries, upstream errors, replies and request bodies handled in a worker process, repairs per format, uptime).

### `toolfix parse`

```text
toolfix parse FILE --tools TOOLS.json [--json] [--no-strip-think] [--reasoning MODE]
              [--strict-schema] [--finish-reason stop] [-o OUT.json [--force]]
```

Repairs a saved response offline and prints before/after. `FILE` can be a full `chat.completion` JSON, a single message object, or a text file with the raw model output (anything else, including JSON such as a Llama bare-JSON reply, is taken as raw output). Files are read as bytes, so CRLF line endings reach the parser as the model wrote them. `TOOLS.json` is a list of tools or a whole request body with `tools`/`functions`. `--json` prints the machine-readable result. `-o` also writes the repaired response; it refuses to overwrite an existing file unless you add `--force`. Nothing is sent anywhere.

### `toolfix test`

```text
toolfix test --upstream URL --model NAME [--api-key KEY] [--timeout 300] [--json]
```

Sends one canned request (a `read_file` / `list_dir` tool pair and "open src/app.py") straight to the model server, then prints the raw reply, what toolfix would turn it into, and a verdict: `native`, `normalised`, `repaired`, `unparsed` or `no tool call`. The key can also come from `TOOLFIX_API_KEY`.

### Exit codes

| Code | Meaning |
| --- | --- |
| 0 | Success. `parse`: repaired or nothing to repair. `test`: the model produced a usable tool call. `serve`: stopped with Ctrl-C. |
| 1 | Unexpected internal error (please report it). |
| 2 | Usage or input error: bad flags, unreadable file, port in use, bad `--upstream`, `-o` target exists. |
| 3 | `parse`/`test`: a tool call was found but could not be repaired safely; `test`: no tool call at all. |
| 4 | `test`: the model server could not be reached or returned an error. |

There is no colour output, so nothing changes when stdout is not a terminal; `NO_COLOR` is respected trivially.

## Configuration

Model server URLs (their usual defaults):

| Server | `--upstream` |
| --- | --- |
| Ollama | `http://localhost:11434` |
| vLLM | `http://localhost:8000` |
| LM Studio | `http://localhost:1234` |
| llama.cpp `llama-server` | `http://localhost:8080` |

Agents: use the agent's **OpenAI-compatible** provider and set its base URL to `http://127.0.0.1:4000/v1`. Providers that speak Ollama's native `/api/chat` API bypass toolfix's repair (they pass straight through).

- **Cline**: Settings, API Provider "OpenAI Compatible", Base URL `http://127.0.0.1:4000/v1`, any API key, Model ID as your server names it ([Cline docs](https://docs.cline.bot/provider-config/openai-compatible)).
- **opencode**: in `opencode.json`, a provider using `"npm": "@ai-sdk/openai-compatible"` with `"options": {"baseURL": "http://127.0.0.1:4000/v1"}` ([opencode docs](https://opencode.ai/docs/en/providers/)).
- **Anything built on an OpenAI SDK**: set the base URL (for example `OpenAI(base_url="http://127.0.0.1:4000/v1")`).

There is no config file and no environment variable for `serve`; everything is a flag.

### Formats it repairs

A call is only accepted when its name matches a tool in the request (exactly, or ignoring case and `-`/`_`), and its arguments parse to a JSON object. Each format's source is cited next to its parser in `src/toolfix/formats.py`.

toolfix would rather miss a call than run an example, because tools can be destructive (`run_command`). So it is deliberately conservative:

- Markup inside code is never a call. Code is found with a CommonMark parser (markdown-it-py): fenced and indented code blocks, including ones nested in lists and block quotes, and code spans (also across line breaks). The one exception is a fenced JSON call that is the entire reply.
- Markup indented by 4 or more columns is never a call either. Real calls start at column 0 or after prose on their line; indented markup is an example, even where CommonMark would call it a list paragraph.
- A marker-based call must start the reply or a line, or follow a sentence end (`.`, `:`, `!`, `?`). Only whitespace or end-of-turn tokens may follow it. So `Qwen emits <tool_call>...</tool_call> and vLLM parses it` stays text.
- Whole-reply JSON (`bare_json`, `fenced_json`, `pythonic`) must have exactly the call shape. OpenAI tool definitions (`{"type": "function", "function": ...}`), objects with a `description`, and arguments that are a JSON Schema (`{"type": "object", "properties": ...}`) are never calls. If the request sets `response_format` to JSON, whole-reply JSON is never converted.
- A cut-off reply never becomes a call. When `finish_reason` is `length` (or `max_tokens` or `content_filter`), nothing in `content` or the reasoning field is converted, even a complete call (it may be an example at the end of cut-off reasoning), and native tool calls in such a reply are not completed either. If toolfix finds call markup where a call could be (by the rules in this list, complete or not), the reply comes back exactly as the server sent it, marked `unparsed`, and keeps its `finish_reason`. A cut-off reply that is only reasoning (a leading reasoning block with nothing after it, or only the reasoning field) comes back the same way, as sent and `unparsed` and without a retry, if that reasoning holds the opening marker of any format (`<tool_call>`, `<function=`, `[TOOL_CALLS]`, `<|python_tag|>`, `<｜tool▁call▁begin｜>`, `to=functions.`, `<|tool_call>`, `<start_function_call>`) anywhere, even mid-sentence. Markup elsewhere in a cut-off reply (mid-sentence or in code, next to visible prose) is ordinary text, and the reply is handled like any other. With `stop`, a call only counts when the format's own closing structure is there: `</tool_call>`, `</function>`, `<｜tool▁call▁end｜>`, `<tool_call|>`, `<|call|>`, a closing fence, or, for formats that have no closing marker (Mistral, bare JSON, `<|python_tag|>`) or where the marker is missing, JSON that is complete and balanced. So `<tool_call>{"name": "list_dir"` or `<tool_call><function=run_command><parameter=command>rm -rf build` (no closing tags) is `unparsed`. Empty arguments become `{}` only when the format closed the call (`{"name": "list_dir"}`, `NAME<｜tool▁sep｜><｜tool▁call▁end｜>`, `call:list_dir{}`); arguments that never arrived are never invented.
- In Qwen3-Coder XML a value ends at its `</parameter>`. If `<parameter=` text comes before that `</parameter>` (a value that mentions the format, or a missing `</parameter>`), the call is refused (`unparsed`) whatever the tool's schema says, so an argument name is never taken from inside a value. A repeated parameter name, a name a closed schema does not declare, or stray text between parameters is refused too, instead of letting a later value override an earlier one. A last value without `</parameter>` is accepted only when `</function>` and `</tool_call>` both follow it (either alone could be text inside a value that was cut off). A write is never redirected to another path.
- Tool calls are parsed on the raw reply first. Only then is a leading reasoning block removed from the prose that is left. By default that is a complete `<think>...</think>` starting the reply, which is what vLLM's qwen3 reasoning parser (v0.11.0) requires; Gemma 4's `<|channel>thought...<channel|>`, gpt-oss's analysis channel and Magistral's `[THINK]...[/THINK]` (mistral-common's `begin_think`/`end_think` tokens) count the same way. The text after the block is then parsed as a reply of its own, so a call that starts right after `</think>` (or `<channel|>`, or `[/THINK]`) on the same line is found, as in Google's documented Gemma 4 thinking and function-calling output. A lone `</think>` is only treated as the end of reasoning with `--reasoning lone-close`, matching vLLM's deepseek_r1 parser for templates that put `<think>` in the prompt. Even then it is ignored if JSON, code or call markup comes before it. `<think>` text in code, prose or tool arguments is left alone.

**Minimal edits.** The only change toolfix makes to `content` is deleting exact spans of the original text:

- a leading reasoning block, plus the line breaks right after it (after gpt-oss's analysis channel this includes the `<|start|>assistant<|channel|>final<|message|>` header of the answer that follows it, as in the [harmony guide](https://developers.openai.com/cookbook/articles/openai-harmony)'s raw output; a trailing `<|return|>` stays);
- the recovered call markup, with the whitespace that joins it to the prose before it and the end-of-turn tokens (`<|im_end|>`, `<|eom_id|>`, `</s>` and so on) right next to it.

Everything else stays byte-identical: blank lines, trailing spaces, indentation, form feeds, tokens inside inline code. Argument values are taken verbatim from the reply, after the format's own unescaping. That includes numbers: `1.50`, `1E5` and `12345678901234567890.123` reach the agent with the digits the model wrote, not re-printed through a float (in the pythonic format, a Python-only spelling such as `1_000` or `0x10` becomes the plain number). Numbers elsewhere in a reply that toolfix re-serialises keep their digits too. `tests/test_corpus.py` checks this as a property on every corpus reply. It asserts that the output equals the input with exactly the reported spans removed, that the removed spans hold only call markup, whitespace and end-of-turn tokens, and that every string argument is text the reply contains.

Measured on five labelled corpora of invented replies. The three from the independent reviewers (`tests/corpus_reviewer.py`, `tests/corpus_reviewer3.py` and `tests/corpus_reviewer4.py`) are copied as written. The table below is generated by `tests/test_corpus.py`, and a test fails if this README disagrees with it:

524 labelled replies: 79 + 30 of mine, 105 from the round-2 reviewer, 144 from the round-3 reviewer and 166 from the round-4 reviewer.

| Set | Replies | Result |
| --- | --- | --- |
| Ordinary replies, and replies that explain or show calls, formats or tool definitions | 251 | 0 converted; 0 changed beyond removing a leading reasoning block |
| Genuine calls written as text, every format | 242 | 242 recovered with exactly the expected arguments; the remaining prose is exact in all 217 cases that specify it |
| Calls that must not be repaired (cut off, unknown tool, Qwen XML values containing parameter markup) | 18 | 18 left untouched |
| Documented limits (see Limits) | 13 | 10 converted, 3 left alone, as documented |

All of these replies were written from the documented formats (by me or by the reviewer), not captured from real models. Treat the recall figure as "the documented formats work", not as a measure on real model traffic.

| `x-toolfix-format` | Looks like | Models | Source |
| --- | --- | --- | --- |
| `hermes` | `<tool_call>{"name": ..., "arguments": {...}}</tool_call>` | Qwen2.5, Qwen3, QwQ, Hermes | vLLM `hermes` parser and template; [Qwen function calling docs](https://qwen.readthedocs.io/en/latest/framework/function_call.html) |
| `qwen3_coder_xml` | `<tool_call><function=NAME><parameter=KEY>value</parameter></function></tool_call>`, also without the opening tag | Qwen3-Coder, Qwen3.5 | vLLM `qwen3_xml`/`qwen3_coder` parser ([tool calling docs](https://docs.vllm.ai/en/stable/features/tool_calling.html)) |
| `mistral` | `[TOOL_CALLS][{...}]`, `[TOOL_CALLS]NAME[CALL_ID]id[ARGS]{...}`, `[TOOL_CALLS]NAME[ARGS]{...}` | Mistral 7B v0.3, Mistral Small 3.2, Ministral 3, Magistral | `mistral-common` instruct tokenisers (before v11, v11, v13 and later) |
| `bare_json` | whole reply is `{"name": ..., "parameters": {...}}` (or a list, or `;`-separated) | Llama 3.1, 3.2, 4 and others | [Llama 3.1 prompt format](https://dev.meta.ai/llama/docs/model-cards-and-prompt-formats/llama3_1) |
| `llama_json` | `<|python_tag|>{"name": ..., "parameters": {...}}` | Llama 3.x | same |
| `llama_function_tag` | `<function=NAME>{"arg": "value"}</function>` | Llama 3.1 custom tools | [Llama 3.1 prompt format](https://dev.meta.ai/llama/docs/model-cards-and-prompt-formats/llama3_1) |
| `pythonic` | whole reply is `[read_file(path='a.py')]` (parsed with `ast`, never evaluated) | Llama 3.2 1B/3B, Llama 4, ToolACE | [vLLM tool calling docs](https://docs.vllm.ai/en/stable/features/tool_calling.html) |
| `deepseek` | `<｜tool▁calls▁begin｜><｜tool▁call▁begin｜>...<｜tool▁sep｜>...` (V3/R1 and V3.1 layouts) | DeepSeek-V3-0324, R1-0528, V3.1 | vLLM `deepseek_v3`/`deepseek_v31` parsers and V3.1 template |
| `harmony` | `<|channel|>commentary to=functions.NAME <|constrain|>json<|message|>{...}<|call|>` | gpt-oss | [OpenAI harmony guide](https://developers.openai.com/cookbook/articles/openai-harmony) |
| `gemma` | `<|tool_call>call:NAME{key:<|"|>value<|"|>}<tool_call|>`, optionally followed by `<|tool_response>`; also ending `<turn|>`; FunctionGemma's `<start_function_call>` form | Gemma 4, FunctionGemma | [Gemma 4 prompt formatting](https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4) (format, `<|tool_response>`); the `<turn|>` ending from vLLM's [`gemma4_utils.py`](https://github.com/vllm-project/vllm/blob/main/vllm/tool_parsers/gemma4_utils.py) |
| `fenced_json` | a ```` ```json ```` or ```` ```tool_call ```` block holding `{"name": ..., "arguments": ...}`, when that block is the whole reply | models prompted with tools but no native format | no official source: a heuristic |

A suffix `@reasoning` (for example `hermes@reasoning`) means the call was found inside `<think>` or the `reasoning_content`/`reasoning` field, with nothing else in the reply ([vllm-project/vllm#39056](https://github.com/vllm-project/vllm/issues/39056)). Only the tagged formats are trusted there.

It also normalises tool calls the server did parse: `arguments` sent as an object instead of a string, invalid JSON in `arguments`, double-encoded arguments, missing `id`/`type`, a tool name in the wrong case, and `finish_reason: "stop"` next to tool calls.

Argument repairs: trailing commas, single quotes, `True`/`False`/`None`, unquoted keys, raw newlines in strings, unknown escapes, and a missing final `}`/`]`. The last one is only made inside a call whose closing marker is present (for example `</tool_call>`, `<tool_call|>`, `<｜tool▁call▁end｜>` or a closing fence), when the JSON stops right after a complete string, object, array or literal (never after a number, which might have been cut short), and never when the reply was cut off. Then obvious type slips are fixed from the tool schema: a string written exactly as a JSON number becomes that number, digits kept (`"3"` to `3`, `"1.50"` to `1.50`; `"1_000"`, `"+5"`, `"007"`, `"0x10"`, `"NaN"` and non-ASCII digits such as `"٣"` stay strings); `"true"`/`"false"` become booleans; a JSON string becomes an object or array; a float becomes an integer only when the number written is whole (`1.0` or `1E2`, not `12345678901234567890.5`). If anything would need a guess, the response is left as the server sent it (byte for byte when not streaming) and marked `x-toolfix: unparsed`. The same happens if repairing fails for any other reason, for example a worker running out of memory: the reply is passed on unchanged, marked `unparsed`, and the log line shows `error=MemoryError` (or whatever was raised). toolfix never turns a reply it could not handle into an error of its own. In that case a streaming client gets the reply as ordinary chunks, or, if it could not even be decoded, as one `data:` event holding the server's JSON. Deep nesting is not such a failure: a reply nested deeper than Python's own JSON parser allows (about 1,000 levels on Python 3.10 and 3.11) is decoded and repaired normally on every Python version.

## How it works

1. The proxy (a small ASGI app on uvicorn, upstream calls through httpx) forwards every request.
2. For chat completions with tools, it reads the whole upstream reply (if the client asked for a stream, it asks the upstream for a non-streaming reply instead).
3. A pure-function parser looks for tool calls in `content`, outside the leading reasoning block and outside code, applying the rules above, and cuts them out, keeping any prose.
4. It builds `message.tool_calls` (ids `call_<24 random chars>`, `type: "function"`, arguments as a JSON string) and sets `finish_reason: "tool_calls"`.
5. If the reply was empty, it retries. Then it returns JSON (byte for byte when nothing changed), or replays the result as a valid SSE stream (role delta, content, tool call deltas with index/id/name/arguments, finish chunk, usage chunk when `stream_options.include_usage` is set, `data: [DONE]`).

Dependencies:
- `httpx`: the async upstream client, with streaming and timeouts.
- `uvicorn`: the HTTP server.
- `markdown-it-py`: a CommonMark parser, so that code blocks in lists, block quotes and every other CommonMark form are recognised as the spec defines them, which a hand-written approximation got wrong.

No framework, no telemetry, no network calls other than to your `--upstream`. Decoding a request, and decoding, repairing and re-encoding a reply, is CPU work, so it never runs on the event loop: bodies of 256 KiB or more go to a pool of 2 worker processes (started with `serve`), smaller ones to a thread. A process is used because a thread would still hold Python's GIL during long C calls (decoding a 30 MB body), which stalls every other request. For the same reason large bodies travel to and from the workers as raw bytes, never inside a pickle, and are sent to the model server in 256 KiB pieces (with a `Content-Length`, not chunked). With the pool, other requests stay under 300 ms while a 12 MB write is repaired or a 20 MB request body is decoded (`tests/test_round4.py` and `tests/test_round5.py` measure this through the real `toolfix serve`, best of three runs). If worker processes cannot be started, toolfix logs that once, handles large bodies in a thread, and does not try again for 60 s; if a worker dies, that body is handled in a thread. Every parser is linear in the length of the reply (no regular expression in it can backtrack more than linearly). On the machine I built it on (2 CPUs, shared with other work), a 1 MB reply of any of the 22 pathological shapes in `tests/test_round4.py` takes at most about 0.2 s, and up to about 0.3 s while the machine is busy. The slow case is a reply made almost entirely of code-fence lines, at about 1.4 to 1.6 s per MB (that is markdown-it-py's CommonMark parse; still linear, and done in a worker process). A reply with more than 1,000 call markers of one format is left unrepaired without parsing each one.

## Limits

- **Not tested against live models by me.** Every format was implemented from the documentation and parser sources cited above and tested with fixtures and a fake model server. If your model emits something toolfix misses or gets wrong, please open an issue with the raw response (`toolfix serve --log-content`, or `toolfix test --json`).
- **Streaming with tools is buffered.** When tools are present and the client asks for a stream, no tokens are sent until the model has finished; the stream is then replayed in one go, so long generations feel slower. Every `--keepalive` seconds an SSE comment is sent so agents do not time out; most SSE clients (the OpenAI SDKs included) ignore comments, but a hand-written parser might not (`--keepalive 0` turns them off). Once a keep-alive has gone out the status is already 200, so an upstream error arrives as a `data: {"error": ...}` event and the `x-toolfix*` headers are missing. With keep-alives on, streaming tool requests have no read timeout (they end when the model finishes or the client disconnects). Requests without tools stream normally.
- **False positives are still possible, and tools can be destructive.** The rules above block examples in code blocks, indented markup, quoted markup, tool definitions and cut-off replies (see the corpus table: no ordinary or explanatory reply is converted). What the rules still convert, by design, because it looks exactly like a real call (each shape below is pinned by a test, `tests/test_round4.py`):
  - any unfenced call markup for one of your tools that is not inside code, is indented by fewer than 4 columns, starts the reply or a line or follows `.`, `:`, `!` or `?` (or `。`, `：`, `！`, `？`), and ends the reply (only whitespace or end-of-turn tokens after it). So an example right after "like this:", a `1. ` list item, a line after a heading (`## Example`), a list item's continuation line (`- Example:` then an indented call), a lazy block-quote line (`> Example:` then a call), or a footnote (`[^1]: ` then a call) is converted when it is the last thing in the reply;
  - a whole reply that is exactly `{"name": <one of your tools>, "arguments": {...}}` (or a list of them, or `[tool(arg=...)]`), because that is Llama's documented call format (set `response_format` to JSON when you want JSON back);
  - a whole reply that is one ```` ```json ```` or ```` ```tool_call ```` fence holding exactly such an object, when the fence's info string is only the language (```` ```json title=x.json ```` is a file being shown and is left alone);
  - a reply that is only reasoning, whose reasoning ends with a complete call in one of the tagged formats (placed as in the first item, and not inside code), with nothing after the reasoning and `finish_reason: stop`. The reasoning can be a `<think>` block, closed or not, Gemma 4's thought channel, Magistral's `[THINK]` block, gpt-oss's analysis channel, or the `reasoning_content`/`reasoning` field when `content` is empty. This is how vLLM loses calls emitted inside reasoning ([vllm-project/vllm#39056](https://github.com/vllm-project/vllm/issues/39056)), so it is converted (`x-toolfix-format` ends in `@reasoning`), even though an example at the end of reasoning looks the same. With `finish_reason: length` it is never converted (see above).
  If your agent exposes a shell or file-deleting tool, keep its own confirmation step on.
- **Being conservative costs some real calls.** A call that is followed by more prose, starts mid-sentence, or sits inside code (fenced, indented, in a list or block quote, or a code span) or is indented by 4 or more columns is left as text (unchanged, not guessed). So is a complete call in a reply cut off by `max_tokens`, a call whose closing tag is missing and whose JSON is not complete and balanced, a call with one `}` too many (even inside `</tool_call>`), a Qwen3-Coder XML call whose value mentions `<parameter=`, arguments nested more than 10,000 levels deep, a pythonic call with a value that has no JSON form (a set, bytes, a complex number), and any reply with more than 1,000 call markers of one format. A whole reply that is one ```` ```xml ```` (or plain ```` ``` ````) fence holding Hermes or XML call markup is left as text too, because markup inside code is never a call and only a fenced JSON call counts as a whole reply; some Qwen2.5-Coder quantisations answer this way. With `--reasoning lone-close`, a `</think>` with plain prose before it and no `<think>` is treated as the end of reasoning; that is the price of handling DeepSeek-R1 templates, so it is opt-in.
- **Line endings.** CRLF and CR count as one line break for each format's own trimming rule (for example the newline after `<parameter=...>`). Line breaks inside a value are kept exactly. Prose left around a call keeps its CRLF.
- **Format edge cases.** A Qwen3-Coder XML value that contains `<parameter=` text (for example a file that documents the format) is left unrepaired, whatever the schema. A value that contains `</parameter>` followed by anything other than whitespace and a new parameter is left unrepaired too; 3 genuine calls in the reviewers' corpora are affected. One shape cannot be detected, by toolfix or by vLLM: a value containing `</parameter>`, a line break and then a complete `<parameter=NAME>...` for a name the tool accepts and that has not been used yet looks exactly like two parameters, so the value is cut there. A value that contains `</function>` directly followed by `</tool_call>` is cut there. Gemma 4 booleans, arrays and nested objects are not documented by Google; they are parsed with the same lenient JSON reader, unconfirmed. Harmony is only recognised with its special tokens. The DeepSeek layouts come from vLLM's parsers and template, not DeepSeek's own documentation. DeepSeek V3.2/V4, Kimi K2, GLM and Granite formats are not supported.
- **Server-side failures can't be repaired.** If the model server's own parser consumes the raw text and drops the call (for example [ollama/ollama#15315](https://github.com/ollama/ollama/issues/15315), where Ollama logs a parse error, drops the Gemma 4 call and the request can hang), the text never reaches toolfix, so there is nothing to repair. Any error the server does return is passed through.
- **Only `/chat/completions` is inspected.** The Responses API, `/v1/completions` and Ollama's native `/api/chat` pass through untouched. Aider mostly edits through text formats rather than tool calls, so it gains little.
- Calls recovered from the Mistral format get 9-character alphanumeric ids instead of `call_...`, because Mistral chat templates reject other ids.
- With the legacy `functions` API only one call can be returned; a reply with several calls is left unchanged.
- Retries resend the identical request, also when the model spent its whole `max_tokens` on reasoning (`finish_reason: length` with no answer), which doubles the wait and often ends the same way; at temperature 0 the same empty reply may come back. Use `--retries 0` to turn retries off. After a retry, `usage` is the sum over all attempts, so it reflects the compute actually used.
- A reply that was repaired, retried or re-emitted as a stream is re-serialised JSON (same values, and numbers keep their digits; spacing and string escaping may differ); only unchanged non-streaming replies are byte-identical.
- Removing `<think>` from `content` hides reasoning from agents that show it; use `--no-strip-think`. The separate `reasoning_content`/`reasoning` field is left as is, apart from a tool call cut out of it.
- Counters in `/toolfix/stats` live in memory and reset on restart.
- `toolfix serve` starts 2 worker processes for large bodies, using about 35 to 45 MB of memory each, next to about 33 MB for the proxy itself (measured on Linux with Python 3.13). While a large reply is handled, memory rises to several times its size: for a 30 MB reply the proxy peaked at about 160 MB and the worker handling it used about 270 MB. Afterwards it goes back down: a worker that handled a body of 4 MiB or more is replaced by a fresh one, and on Linux with glibc the proxy hands freed memory back to the system (after a 30 MB reply: proxy 39 to 45 MB, workers 36 MB). Elsewhere the proxy may keep more. If the client disconnects while its reply is being repaired in a worker, the upstream request is cancelled and that worker is stopped and replaced at once. A large body handled in a thread (worker processes unavailable) is finished in the background.
- Developed and tested on Linux with Python 3.10 to 3.13. It is pure Python and should work on macOS and Windows, but I have not run it there.

## Contributing

```sh
uv sync                     # Python 3.10+; installs the dev tools (pytest, ruff, openai)
uv run pytest --cov=toolfix # unit tests, fuzzing, and end-to-end tests through the real proxy
uv run ruff check . && uv run ruff format --check .
```

`tests/fake_upstream.py` is a stdlib-only fake model server with one scenario per format (`python tests/fake_upstream.py --port 47250` runs it by hand). To add a format: add a parser with its source cited in `src/toolfix/formats.py`, a scenario to the fake upstream, and true-positive, malformed and false-positive tests. The end-to-end tests use ports 47200 to 47299 on 127.0.0.1.

## License

MIT. See [LICENSE](LICENSE).
