↓ Skip to main content

Beyond Basic MCP: Eliminating 'Double-Echo' Token Bloat and Debugging Local Ollama Endpoints

Author
David Watson
Terraforming enterprise clouds by day, terraforming worlds by night. With an unhealthy urge to over-engineer both.

In my previous post, I shared how I connected a desktop gaming PC (ollama-pc) and a headless Mac mini (ollama-mac) over my home LAN using the Model Context Protocol (MCP) to offload GDScript maths, shaders, and unit tests from metered frontier cloud models.

On paper, the architecture was a triumph. In practice, after running a full weekend of intensive ticket-driven development on my Godot 4 project, I discovered that how an agent communicates with local models matters just as much as where those models run.

While debugging stalls, timeouts, and a surprisingly stubborn cloud token burn rate, I uncovered three subtle failure modes in local LLM tooling—and built a lightweight CLI pattern that cut my remaining cloud transcript bloat by over 90%.


1. The Core Problem: The Hidden Economics of Agentic Loops
#

Frontier cloud models excel at multi-file system design, cross-repository reasoning, and interactive problem solving. However, inside an autonomous agentic loop (such as Antigravity or Claude Code), token consumption compounds exponentially across three hidden traps:

  1. Context Accumulation: Every turn appends to the conversation transcript. A 2,000-token tool response generated on Turn 3 is re-read and billed as input tokens on Turn 4, Turn 5, Turn 6, and Turn 20.
  2. The “Double-Echo” Anti-Pattern: When a cloud orchestrator uses a standard MCP model-to-model tool call to generate code:
    • The agent calls ollama_generate to draft a 150-line test suite (~2,000 tokens).
    • The MCP server returns those 2,000 tokens into the cloud agent’s context history.
    • The cloud agent immediately calls write_file("tests/test_feature.gd", code)—echoing the exact same 2,000 tokens a second time in its tool arguments.
    • The Result: The exact same 2,000 lines of code now exist twice in the cloud transcript (once as tool output, once as tool input). On every subsequent step of the task, that 4,000-token block is repeatedly re-sent and billed as cloud input tokens.
  3. Sub-Agent Token Burn: Running a two-axis code review at the end of a ticket (Standards Review + Specification Review) typically spawns two cloud research sub-agents. Each sub-agent reads the diff, repository rules, and calling scripts, burning 15,000 to 30,000 cloud tokens per ticket just to verify tab indentation, static typing, and acceptance criteria.

2. The Evolved Hardware & Model Lineup
#

After stress-testing my local endpoints against real Godot 4.x GDScript tasks and automated diff reviews, I standardised both LAN nodes on Google’s quantised Gemma 4 instruction-tuned models:

EndpointHardwareActive ModelContext WindowRole
ollama-pcRTX 4070 Ti (12GB VRAM)gemma4-it-qat-32k:latest (12B)32kTier 1 (Fastest): Code generation, unit tests, two-axis code reviews, maths recipes
ollama-macMac mini M6 (24GB Unified)gemma4:12b-it-qat (12B)64kTier 2 (Medium): Large diffs (>500 lines), multi-file logs, larger test suites

Why did I move ollama-pc away from qwen3.5-32k? That brings me directly to the debugging journey.


3. The Debugging Journey: Three Subtle Roadblocks
#

Getting local models to cooperate reliably with an automated agentic harness required diagnosing three non-obvious failure modes across samplers, MCP adapters, and Ollama’s streaming API.

A. The Infinite <think> Loop and Presence Penalty
#

  • Symptom: MCP calls to ollama-pc consistently timed out after 3 minutes (context deadline exceeded).
  • Root Cause: My initial qwen3.5-32k Modelfile had presence_penalty: 1.5 configured to discourage repetitive code boilerplate. However, for models that use internal chain-of-thought (<think> blocks), penalising token repetition mid-thought breaks the sampler’s reasoning loop. The model spiralled into runaway self-correction inside its <think> block until it hit the 3-minute client timeout.
  • Fix: Switched ollama-pc to gemma4-it-qat-32k:latest with zero presence penalty, dropping generation latency to a rock-solid 6–12 seconds.

B. The MCP JSON Grammar Sampler Deadlock
#

  • Symptom: Asking the MCP server for GDScript or Python code resulted in mysterious deadlocks or completely blank responses.
  • Root Cause: The official @modelcontextprotocol/server-ollama adapter had two issues: it attempted strict JSON schema validation and defaulted its format parameter to "json". Under the hood in llama.cpp, passing "format": "json" activates a strict context-free grammar sampler that only permits valid JSON tokens ({, ", :, etc.). When the prompt asks for a Godot script starting with extends Node, the grammar sampler rejects the code tokens, causing generation to stall or emit empty strings.
  • Fix: Switched the underlying MCP package from @modelcontextprotocol/server-ollama to ollama-mcp, and explicitly pass "format": "markdown" (or omit JSON formatting) on all code generation calls.

C. Updating the MCP Configuration (mcp_config.json)
#

To reflect the package switch and streamlined configuration, I updated my MCP config (~/.gemini/antigravity-cli/mcp_config.json). The updated setup replaces @modelcontextprotocol/server-ollama with ollama-mcp, stripping away the rigid JSON-enforcing environment variables while pointing directly at my dedicated hardware endpoints over the LAN:

{
  "mcpServers": {
    "ollama-pc": {
      "command": "npx",
      "args": ["-y", "ollama-mcp"],
      "env": {
        "OLLAMA_HOST": "http://<PC LOCAL IP>:11434"
      }
    },
    "ollama-mac": {
      "command": "npx",
      "args": ["-y", "ollama-mcp"],
      "env": {
        "OLLAMA_HOST": "http://<MAC LOCAL IP>:11434"
      }
    }
  }
}

This cleaner configuration avoids the grammar lockup traps of the older adapter and provides reliable tool calling for the orchestrator.

D. The Separate thinking Field in Ollama 0.40+
#

  • Symptom: Streaming code reviews from local models returned empty text despite running on the GPU for 20 seconds.
  • Root Cause: Modern reasoning models in Ollama 0.40+ emit internal reasoning tokens under a distinct "thinking" key in each streaming JSON chunk, while emitting "response": "" until the thinking phase finishes. When num_predict was set too low (for example, 1024), the model consumed its entire token allocation inside "thinking" before emitting a single character into "response".
  • Fix: Bumped num_predict to 4096 and updated my streaming client to handle full generation budgets properly.

4. The Solution: Two Architectural Changes That Save 90% of Tokens
#

Innovation 1: Direct-to-Disk Generation (Eliminating “Double-Echo”)
#

Instead of round-tripping generated code through the cloud agent’s context window via MCP, I created a lightweight repository CLI helper (bin/ollama-gen -o <path>) that queries the local Ollama endpoints directly, strips markdown code fences automatically, and writes the result straight to disk:

Traditional MCP Flow showing Double-Echo Context Bloat (4,000 tokens in cloud history)
Direct-to-Disk Flow showing Zero Context Bloat via bin/ollama-gen (12 tokens in cloud history)

99.7%

Transcript Reduction

Cloud transcript impact per file drops from 4,000+ tokens to just 12 confirmation tokens.

0

Cloud Review Tokens

Two-axis Standards & Spec code reviews run entirely on the local RTX 4070 Ti in ~15s.

6–12s

Generation Latency

Fast local inference with Gemma 4 QAT with zero presence-penalty timeouts.

By piping the local GPU’s output directly to the filesystem and returning only a single confirmation line to the cloud orchestrator, the cloud model never has to ingest or echo the raw boilerplate. If a test fails, the cloud agent inspects only the relevant lines rather than carrying every draft in its permanent conversation memory.

Innovation 2: Local Two-Axis Code Reviews
#

Before any ticket is closed, changes are reviewed along two axes: Standards (Godot 4 syntax, strict tabs, static typing, architectural boundaries, and domain glossary compliance) and Spec (comparing the git diff against the GitHub issue’s acceptance criteria).

  • The Old Way: Spawn two cloud research sub-agents (~15,000 to 30,000 cloud tokens per ticket).
  • The New Way: Run local CLI review commands directly on ollama-pc:
    bin/ollama-gen --review-standards
    bin/ollama-gen --review-spec <ticket_number>
    bin/ollama-gen automatically extracts the current git diff, pulls the issue specification via gh issue view, queries the RTX 4070 Ti over the LAN in ~15 seconds, and prints either concrete violations or CLEAN.
    • Cloud Tokens Used: 0.

5. Evolving the Agent Rules (~/.antigravity.md)
#

A tool is only useful if your coding agent actually remembers to use it. I updated my global agent instructions (~/.antigravity.md) with three strict mandates:

  1. Direct-to-Disk by Default: Instructs the agent to use bin/ollama-gen -o <path> whenever generating standalone files or test suites.
  2. Local-First Code Reviews: Replaces cloud review sub-agents with --review-standards and --review-spec.
  3. Pre-Filtered Test Logs: Prohibits dumping raw 500-line bin/test outputs into cloud context, requiring bin/test | grep -E ... instead.

The Complete ~/.antigravity.md Configuration
#

# Sub-Agent Delegation Rules (Hybrid Local/Cloud)

You have access to local LLM sub-agents via configured Ollama MCP servers (`ollama-pc`, `ollama-mac`) and the repo CLI helper `bin/ollama-gen`. To conserve cloud context, token limits, and quota, delegate tasks according to the following guidelines.

---

## High-Leverage Quota Optimization Workflows

### 1. Direct-to-Disk Code Generation (Eliminate "Double-Echo")
- **The Problem:** Calling an MCP tool (`ollama_generate`) returns the entire code snippet into the cloud conversation history, and then calling `write_file` echoes the exact same code a second time in tool arguments. That double-sized block is billed as input tokens on every subsequent turn.
- **The Solution:** Use `bin/ollama-gen -o <path>` to generate directly to disk:
  ```bash
  bin/ollama-gen -p "Write test suite for..." -o tests/test_new_feature.gd
  ```
  - **Result:** The cloud context only receives `Wrote 120 lines to tests/test_new_feature.gd (6.8s)`. Zero code bloat in cloud history.
  - Automatically strips markdown code fences so the file contains clean, ready-to-run code.

### 2. Local-First Code Reviews (Eliminate Cloud Review Sub-Agents)
- Instead of spawning two cloud `research` subagents per ticket for Standards and Spec reviews, run them locally via `bin/ollama-gen`:
  ```bash
  # Standards Review (checks git diff against Godot 4 & repo standards)
  bin/ollama-gen --review-standards

  # Spec Review (checks git diff against GitHub issue spec or text)
  bin/ollama-gen --review-spec <ticket_number_or_spec_text>
  ```
  - Reviews run on `ollama-pc` in ~10–25s and output concise, bulleted findings or `CLEAN`.
  - Saves 15,000–30,000 cloud tokens per ticket.

### 3. Pre-Filter Test Logs & Command Outputs
- Never dump raw 500-line `bin/test` progress into context. Filter output:
  ```bash
  bin/test | grep -E "(Running test suite|Results:|FAIL|ERROR|ALL TEST SUITES PASSED)"
  ```
- If an error trace is long, let `ollama-pc` isolate the root cause before ingesting.

---

## Division of Responsibilities

### Keep on Cloud (Yourself):
- Multi-file architectural planning, whole-project refactoring, and complex Godot scene/architecture debugging.
- Final code integration, validation, and executing final `edit_file` / `write_file` adjustments.
- Cross-file dependency analysis, tool orchestration, and direct user interaction.

### Handoff to Local Ollama Endpoints:
- Generating standalone functions, math recipes, shaders, or boilerplate GDScript / C# classes.
- Writing unit tests, mock data structures, or test fixtures (via `bin/ollama-gen -o <path>`).
- Two-axis code reviews (`--review-standards` and `--review-spec`).
- Summarizing long error logs, stack traces, or profiling captures.

---

## Available Endpoints & Active Models

| Endpoint / MCP Server | Active Model | Active Context Window | Relative Speed | Host & Hardware |
| :--- | :--- | :--- | :--- | :--- |
| **`ollama-pc`** | `gemma4-it-qat-32k:latest` (12B) | **32,768 tokens** (32k) | **Fastest** | `http://192.168.0.2:11434` (RTX 4070 Ti 12GB) |
| **`ollama-mac`** | `gemma4:12b-it-qat` (12B) | **65,536 tokens** (64k) | **Medium** | `http://192.168.0.173:11434` (Mac mini M6 24GB Unified RAM) |

---

## Endpoint Selection Strategy (Speed-First with Context Gating)

Select local endpoints strictly in speed order (`pc` > `mac`), based on context required:

1. **Tier 1 — `ollama-pc` (Primary / Default):**
   - **Criteria:** Context required is <= **32k tokens**.
   - **Use cases:** Rapid function generation, unit tests, code reviews, shader code, math helpers.
   - **CLI flag:** `-e pc` (default).

2. **Tier 2 — `ollama-mac` (Medium-Context Fallback):**
   - **Criteria:** Context required is > **32k tokens** and <= **64k tokens**.
   - **Use cases:** Larger diffs (>500 lines), multi-file logs, larger test suites.
   - **CLI flag:** `-e mac`.

3. **Tier 3 — Cloud Agent (Yourself):**
   - **Criteria:** Context exceeds 64k tokens, tasks requiring multi-file workspace tools, or cross-cutting architectural reasoning.

6. Key Takeaways
#

  1. Keep the Brain in the Cloud, the Muscle on Local Metal: Use frontier cloud models for system-level planning, architectural coordination, and complex scene integrations. Let local GPUs grind out unit tests, boilerplate syntax, and diff reviews.
  2. Never Echo Generated Code in Tool Calls: If an orchestrator requests code from a local sub-model, pipe it straight to disk. Writing directly to the filesystem and returning only a status line to the cloud agent prevents conversational history bloat.
  3. Watch Your Grammar and Presence Samplers: Beware of default "format": "json" constraints in MCP adapters when generating source code, and zero out presence penalties on reasoning models so their <think> blocks don’t spiral into timeouts.

Have you hit the “Double-Echo” token trap or wrestled with MCP grammar samplers in your own local LLM setup? Let me know in the comments below!