# Temporal & AI: Durable MCP Gateway with Code Mode

> Source: <https://dev.to/temporalio/temporal-ai-durable-mcp-gateway-with-code-mode-g02>
> Published: 2026-11-24 17:03:00+00:00

**Recommendation:** Route agent tool calls through a code-mode script that filters results before they hit context, and make each call a durable step so interrupted jobs resume; avoid write tools until calls are idempotent.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

When an agent calls MCP tools directly, every result lands in its context window. Ask it which of 30 Notion pages mention AI, and it reads all 30 pages into context to answer a yes or no question about each one. And when a long job of hundreds of tool calls dies partway through, from a rate limit, a dropped connection or a restarted MCP server, the agent starts over and pays for every call again.

In this episode of Temporal & AI, Maple Xu from Temporal's AI Foundations team builds an MCP gateway on Temporal that fixes both.

**Code mode:** the agent gets one tool, run_script, and writes a short Python script against the upstream tools. The script fetches, filters and returns only what the agent needs, so the page bodies never reach the model. In the video, 30 pages took 142K tokens with plain tool calls and 68K in code mode.

**Durable steps:** every tool call inside the script is a durable step. A failed call retries with backoff, up to 8 attempts.

**Same scan, two outcomes:** Maple interrupts a 300 page scan partway through. Without Temporal, every fetch is lost and the agent runs the script again from the start. With the gateway, the Workflow pauses, finished fetches stay in Event History, and the agent is still on the same tool call and doesn't notice.

One caveat from the repo: it isn't safe for write tools as is, since a tool call can run more than once.

🎥 Watch the episode: [https://youtu.be/emAjjoT_liY](https://youtu.be/emAjjoT_liY)

🧪 GitHub repo, run it yourself: [https://github.com/temporal-community/temporal-ai-mcp-gateway](https://github.com/temporal-community/temporal-ai-mcp-gateway)
