← Back to Writing
NOV 28, 2026  ·  9 MIN READ  ·  SERIES: PRODUCTION MCP & ZERO-ZOMBIE AGENTS

Idempotency Key Scoping for Production MCP Servers: Why (tenant_id, token_id, tool_name, client_key) Beats Per-Token Alone

In production Model Context Protocol (MCP) deployments, agent runtimes and orchestrators (n8n, Temporal, Cursor, or Claude Desktop) retry mutating tools/call requests whenever a Streamable HTTP proxy times out or a worker reconnects. Without idempotency enforcement on write tools, a single transient socket reset can issue duplicate invoices, double-decrement inventory, or dispatch duplicate CRM webhooks.

Yet the most common first implementation — scoping the idempotency store solely by (token_id, client_key) — quietly breaks under real multi-tool agent pipelines and multi-tenant deployments in two nasty ways: cross-tool workflow UUID collisions and silent parameter-mutation replays.

1. The Cross-Tool Workflow UUID Collision Trap

Consider an order-fulfillment agent that forwards its orchestrator's correlation UUID — say client_key = "run_9f3c2a1b" — across sequential steps in a single run. Step 1 invokes create_draft_order, which caches its JSON envelope under (token_42, "run_9f3c2a1b"). Three hundred milliseconds later, Step 2 invokes reserve_inventory using the exact same workflow UUID.

If the unique key omits tool_name (and tenant_id to anchor tenant isolation independently of rotated PATs or service tokens), the MCP server mistakes Step 2 for a retry of Step 1 and replays create_draft_order's cached payload — never executing reserve_inventory at all. Worse, the LLM sees a clean success envelope and advances to fulfillment against unlocked stock.

2. The 4-Tuple Primary Key & SHA-256 Canonicalized Args Hash (409 Conflict)

Every mutating MCP tool must scope its idempotency ledger by the full 4-tuple: (tenant_id, token_id, tool_name, client_key). At the same time, before claiming the key, the server canonicalizes the JSON tool arguments (recursive key sorting, deterministic compact serialization, integer minor units) and computes a SHA-256 digest stored as args_sha256:

3. Atomic Claim via INSERT ... ON CONFLICT DO NOTHING in Postgres & SQLite WAL

Just like payment webhook storms, a naive SELECT-then-INSERT collapses when two concurrent retries hit inside 1 millisecond. Instead, make the database's composite primary key inside PostgreSQL or SQLite WAL mode the single atomic arbiter, paired with an indexed bounded 24-hour TTL (expires_at):

sql // mcp_idempotency_schema.sql (Postgres & SQLite WAL compatible)
CREATE TABLE IF NOT EXISTS mcp_idempotency_records (
  tenant_id     TEXT NOT NULL,
  token_id      TEXT NOT NULL,
  tool_name     TEXT NOT NULL,
  client_key    TEXT NOT NULL,
  args_sha256   TEXT NOT NULL,
  status        TEXT NOT NULL CHECK (status IN ('in_progress', 'completed', 'failed')),
  response_json TEXT,
  created_at    INTEGER NOT NULL,
  expires_at    INTEGER NOT NULL,
  PRIMARY KEY (tenant_id, token_id, tool_name, client_key)
);

CREATE INDEX IF NOT EXISTS idx_mcp_idem_expires_at
  ON mcp_idempotency_records (expires_at);
python // atomic_mcp_idempotency.py
import hashlib
import json
import sqlite3
import time
from typing import Any, Callable

TTL_SECONDS = 24 * 60 * 60  # Bounded 24h replay retention


def canonical_args_sha256(args: dict[str, Any]) -> str:
    canonical = json.dumps(args, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def run_idempotent_mcp_tool(
    conn: sqlite3.Connection,
    *,
    tenant_id: str,
    token_id: str,
    tool_name: str,
    client_key: str,
    args: dict[str, Any],
    execute_fn: Callable[[dict[str, Any]], dict[str, Any]],
) -> tuple[int, dict[str, Any]]:
    now = int(time.time())
    expires_at = now + TTL_SECONDS
    digest = canonical_args_sha256(args)

    with conn:
        # Opportunistically purge expired row for this exact 4-tuple before atomic claim
        conn.execute(
            """
            DELETE FROM mcp_idempotency_records
             WHERE tenant_id = ? AND token_id = ? AND tool_name = ?
               AND client_key = ? AND expires_at <= ?
            """,
            (tenant_id, token_id, tool_name, client_key, now),
        )
        cur = conn.execute(
            """
            INSERT INTO mcp_idempotency_records (
              tenant_id, token_id, tool_name, client_key,
              args_sha256, status, response_json, created_at, expires_at
            ) VALUES (?, ?, ?, ?, ?, 'in_progress', NULL, ?, ?)
            ON CONFLICT(tenant_id, token_id, tool_name, client_key) DO NOTHING
            """,
            (tenant_id, token_id, tool_name, client_key, digest, now, expires_at),
        )
        claimed = cur.rowcount == 1

    if not claimed:
        row = conn.execute(
            """
            SELECT args_sha256, status, response_json
              FROM mcp_idempotency_records
             WHERE tenant_id = ? AND token_id = ? AND tool_name = ? AND client_key = ?
            """,
            (tenant_id, token_id, tool_name, client_key),
        ).fetchone()
        if row is None:
            return 409, {"error": "IDEMPOTENCY_RACE_RETRY"}
        stored_digest, status, response_json = row
        if stored_digest != digest:
            return 409, {
                "error": "IDEMPOTENCY_PAYLOAD_MISMATCH",
                "message": "Idempotency key already bound to different canonicalized arguments.",
            }
        if status == "completed" and response_json is not None:
            return 200, {"replayed": True, "result": json.loads(response_json)}
        return 409, {"error": "IDEMPOTENCY_IN_FLIGHT", "retry_after_seconds": 2}

    try:
        result = execute_fn(args)
    except Exception:
        with conn:
            conn.execute(
                """
                DELETE FROM mcp_idempotency_records
                 WHERE tenant_id = ? AND token_id = ? AND tool_name = ?
                   AND client_key = ? AND status = 'in_progress'
                """,
                (tenant_id, token_id, tool_name, client_key),
            )
        raise

    with conn:
        conn.execute(
            """
            UPDATE mcp_idempotency_records
               SET status = 'completed', response_json = ?, expires_at = ?
             WHERE tenant_id = ? AND token_id = ? AND tool_name = ? AND client_key = ?
            """,
            (json.dumps(result, separators=(",", ":")), int(time.time()) + TTL_SECONDS,
             tenant_id, token_id, tool_name, client_key),
        )
    return 200, {"replayed": False, "result": result}

4. Bounded 24h TTL Hygiene & Failure-Mode Boundaries

An idempotency table must never grow without bound. Indexing expires_at lets an hourly bounded sweep delete expired 24-hour entries in single-digit milliseconds without stalling active readers or writers under SQLite WAL or PostgreSQL MVCC. Two final production guardrails lock the design down:

INSTANT TOOLKITS & CUSTOM MCP ENGINEERING (100% ASYNC)

Ship Faster with Instant Gumroad Kits ($19–$29) or a Custom MCP Sprint?

Download production-ready Docker/FastAPI and n8n workflow kits immediately on Gumroad, or book a bounded 48h starter ($65, 0%-fee Contra escrow) or Custom MCP Server shipped asynchronously via GPG-signed GitHub PRs.