TrolyPage

An autonomous Marketing & Sales operating system for businesses that want AI-powered omni-channel growth.

Contact Info

Follow Us

13 min read

Stopping Duplicate Orders When LLMs Retry: How idempotency_key and Operation Receipts Protect MCP Writes

TrolyPage

Dec 02, 2026
13 views
Isometric 3D illustration of a glowing receipt crystal locked inside a frosted glass socket deflecting duplicate ghost cubes on a clean editorial background.

When an LLM client drops a Streamable HTTP connection or retries after a 504 timeout, unkeyed Model Context Protocol writes execute twice and create duplicate orders, posts, or webhooks. Supplying a persistent idempotency_key per business intent lets server-side receipt tables lock execution before mutations run, returning cached replays, 409 argument conflicts, or safe executing_or_unknown recovery states.

Editorial disclosure: Published by TrolyPage, whose 330-tool MCP Gateway (expanded from its 291-tool baseline) and source-level McpOperationReceipts architecture are examined in this engineering guide alongside Model Context Protocol specifications, Stripe idempotency semantics, IETF RFC standards, and Redis atomic locking.

Why LLM Transport Retries Turn Timeouts Into Duplicate Orders

Modern AI agents run across unstable network boundaries. Under the Model Context Protocol (MCP) Streamable HTTP transport, long-running tool calls traverse mobile networks, proxies, IDE extensions, and edge timeouts. When a gateway drops an HTTP stream at 30 seconds while the origin server is committing an order or calling a shipping carrier, the client sees a socket reset or HTTP 504—not the committed row.

Compounding the problem, the MCP Server Tools specification separates JSON-RPC protocol errors from tool execution errors (isError: true) and warns that clients must treat tool annotations as untrusted unless talking to trusted servers. When Cursor, Claude, or an agent using OpenAI remote MCP connectors hits a dropped stream, its default reflex is to re-invoke the tool.

If the client omits an idempotency token—or generates a fresh UUID inside its retry loop—the server cannot distinguish a network retry from a new purchase. In commerce and marketing automation, that ambiguity creates duplicate pending orders, double social drafts, repeated outbound webhooks, and broken inventory counts.

Architectural Tradeoff: Unkeyed Retries vs. Client Flags vs. Durable Operation Receipts

Engineering teams generally choose among three architectures to guard mutating MCP tools. Picking the wrong layer transfers cleanup cost directly onto support staff and billing reconciliation.

Dimension Option A: Unkeyed or Fresh-UUID-Per-Retry Option B: Client-Side In-Memory Retry Flags Option C: Server-Side McpOperationReceipts + Read-Verify + Redis Webhook Guard
Idempotency Scope None; each HTTP POST starts an independent execution. Volatile client RAM (single IDE session or Node/Python worker). Relational unique key (manychat_account_id, user_id, tool, request_key) + SHA-256 arguments_hash.
Quantitative Thresholds 0% duplicate protection on 504/socket drops; 100% collision risk after mid-flight timeouts. 0s persistence across Cursor/VS Code restarts or pod recycling; fails under multi-agent concurrency. varchar(128) key (max:128 to 190 per tool), 64-hex SHA-256 digest, 300s default (60s min) approval dedup window, 65,536-byte (64 KiB) approval payload cap.
Root Technical & Economic Mechanism Stateless RPC handlers run blindly; zero upfront storage, high manual order-cleanup labor. In-memory Set blocks same-process retries, but crashes erase state before responses return. Atomic insertOrIgnore() persists status = 'executing' before side effects, pairing Stripe-style parameter matching with Redis SET NX EX downstream locks.
Exact Failure Cost When Choosing Wrong Duplicate orders, double shipments, and wasted AI token quotas (TrolyPage Lite starts at $8/mo for 250 MAU / 4M tokens, Scale at $104/mo; ghost writes burn quota and operator review hours). Silent split-brain: IDE restart mid-timeout causes the next session to send an untracked retry, creating orphaned duplicate orders. Requires clients to reuse idempotency_key per intent and run read-verify (list-bookings / get-booking on 409 executing_or_unknown, or list-orders / get-order for order reconciliation) before minting a new key.

Like Stripe's idempotent request model, reliable replay protection cannot live solely in caller RAM. It requires an atomic server-side claim recorded before any external mutation executes.

Inside TrolyPage's 330-Tool MCP Gateway and McpOperationReceipts Engine

According to the live TrolyPage MCP Gateway catalog and /mcp/status (checked 2026-12-02), workspaces expose 330 tools across 12 servers (118 read tools and 212 write tools, 14 resources, and 12 prompts): one unified server (/mcp/troly, 330 tools) alongside scoped servers support (19 tools), commerce (40), analytics (16), social (55), marketing (38), knowledge (14), workspace (30), agents (54), assets (13), automation (61), plus the editorial blog server. Reconciling earlier snapshots: this expands on the prior 291-tool / 11-domain-server baseline (notably growing automation from 21 to 61 tools and adjusting social to 55), while TrolyPage's pricing page still displays legacy copy listing 86 tools across 7 business servers.

Teams comparing REST and MCP should also note that TrolyPage's Public Developer REST API is still in progress and not yet publicly open (an internal v1 API exists in the codebase; production integrations rely on Outbound/Inbound Webhooks, Zapier Webhooks, and the 330-tool MCP Gateway). When connecting Claude, ChatGPT, or Cursor for catalog and order reconciliation via MCP or Facebook and Instagram inbox automation, write safety rests on McpOperationReceipts, OrderCreationService, and McpPolicyGuard.

Three-column architecture diagram showing TrolyPage McpOperationReceipts flow: incoming MCP write with request_key and canonical SHA-256 arguments_hash, atomic insertOrIgnore executing claim on mcp_operation_receipts, and three-way replay resolution (replayed true, 409 Conflict, and 409 executing_or_unknown).
How TrolyPage McpOperationReceipts claims an executing receipt before running mutations and routes retries across three deterministic outcomes.

1. Canonical Recursive JSON Hashing (arguments_hash)

LLM callers often reorder JSON object keys between retries. In App\Services\Mcp\McpOperationReceipts, arguments pass through a recursive canonical() normalizer before hashing: associative arrays sort via ksort() at every depth, while list arrays retain index order because sequence matters for array items. The normalized JSON string is hashed with SHA-256 into a 64-character arguments_hash.

2. Claim-Before-Side-Effect Locking on mcp_operation_receipts

Before running protected writes—including create-booking, upload-asset, import-asset, propose-fact, AutomationTool workflows, and IntegrationConfigurationTool actions via ControllerTool and FileUploadTool—McpOperationReceipts::run() constructs the four-column tuple (manychat_account_id, user_id, tool, request_key) and runs an atomic insertOrIgnore() into mcp_operation_receipts under unique index mcp_operation_identity. This persists status = 'executing' and result = NULL before the closure mutates bookings, assets, facts, or automation definitions.

If insertOrIgnore() claims 1 row, the worker executes the tool and updates status to 'completed' or 'failed' with the serialized result JSON. If the insert returns 0 because the identity exists, execution halts and routes into the three-way replay resolver.

3. Dedicated Order Intent Protection in create-order

Commerce order creation uses its own dedicated guard rather than McpOperationReceipts. In CreateOrderTool (create-order), idempotency_key is required (max:128), hashed with SHA-256, and passed into OrderCreationService::createAiOrder(), which compares an order-agnostic cart fingerprint (product_id, variant_id, and summed quantity). Exact retries return ToolResult::success with data.idempotent_reuse: true and the existing order_id, whereas altered carts return ToolResult::failure (status: 422) with errors.code: "idempotency_conflict"—rather than 409 executing_or_unknown. Every MCP-created order lands in pending_review inside Orders for human confirmation.

The 3-Outcome Receipt Recovery Matrix for Agent Runtimes

When a retry matches an existing mcp_operation_receipts row, McpOperationReceipts::replayResult() checks constant-time hash_equals() against arguments_hash and inspects whether result !== null, yielding three deterministic branches.

Receipt State in mcp_operation_receipts Server Response & Status Root Meaning Required Agent Recovery Action
Hash matches + result !== null Cached JSON payload + "replayed": true First call completed cleanly, but the HTTP/SSE response dropped in transit. Consume the cached result; keep the same idempotency_key.
Hash mismatch (!hash_equals()) ok: false, HTTP 409 Same request_key reused with changed schedule, payload, or subscriber parameters. Abort retry; mint a new idempotency_key only if the user intentionally changed the request.
Hash matches + result === null ok: false, HTTP 409, status: ["executing_or_unknown"] + operation_id Prior worker is still running or crashed mid-mutation without writing a final result. Never auto-retry with a new key. Read-verify via list-bookings / get-booking, list-assets, get-knowledge, list-automation-run, or get-integration-configuration first.

Branch three—409 executing_or_unknown—prevents the classic retry storm after worker OOM crashes: instead of blindly minting a new UUID, the agent inspects authoritative server state before deciding whether a new intent is warranted.

Dark-mode execution trace comparing an unkeyed LLM retry creating two duplicate bookings after a 504 timeout against a keyed McpOperationReceipts run returning 409 executing_or_unknown and verifying via list-bookings and get-booking, paired with callouts on recursive key sorting, 300s approval windows, and Redis SET NX EX webhook deduplication.
Unkeyed LLM retry storm creating duplicate bookings versus keyed McpOperationReceipts lock recovery paired with 300s approval windows and Redis webhook deduplication.

How Approval Modes, Least-Privilege Scopes, and Secret Redaction Layer Around Writes

Idempotency protects against duplicate retries; workspace governance controls who can write and which mutations require human sign-off. TrolyPage enforces these gates server-side in McpPolicyGuard, McpPolicy, McpCredentialPermissions, and McpSecretFieldGuard.

Governance Control strict Mode hybrid Mode (Fail-Closed Pattern) auto Mode
Read-Only Tools Run immediately Run immediately Run immediately
Low-Risk / Draft Writes (HYBRID_DIRECT_TOOLS: inbox messages/tags/notes, propose-fact, unscheduled create-social-post, inactive agent edits is_active = false, draft integration configs, create-order into pending_review) Queued as McpActionRequest Run immediately Run immediately
High-Risk / Live Writes (scheduled posts, active agent edits, publish-social-post, submit-broadcast, create-shipment, publish-automation-workflow, enable-integration-configuration, replay-integration-delivery) Queued as McpActionRequest Fail-closed into McpActionRequest approval queue Run immediately (admin/owner required)
Mandatory Guardrails (All Modes) Tenant binding; mcp:read PATs blocked from writes; admin/owner role check; plan entitlement enforcement (HTTP 402); queued approvals capped at 65,536 bytes (64 KiB) and deduplicated over a 300s default (60s min) bucket via lockForUpdate().

Authentication and payload scrubbing add defense-in-depth:

  • Sanctum PAT Scopes: McpCredentialPermissions rejects all writes when a token holds mcp:read without mcp:write, and restricts domain servers when mcp:module:<module> abilities are present.
  • OAuth 2.1 Resource Binding (IETF RFC 8707): Passport tokens bind mcp_resource to the consented endpoint—so a /mcp/analytics token cannot invoke /mcp/commerce or /mcp/agents.
  • Secret Redaction & Rate Limits: McpSecretFieldGuard and RedactsSecrets mask credentials and query tokens as [redacted]. Live production limits verified on /mcp and /mcp/status cap workspaces at 360 requests/min and actors at 180 requests/min (120 req/min on public endpoints; the 30 / 60 values in config/mcp.php are only local .env fallbacks). On HTTP 429, honor Retry-After with backoff.

Operational Asset: TypeScript MCP Intent Wrapper and HMAC + Redis Webhook Bridge

Because TrolyPage does not provide native two-way admin sync for Shopify, WooCommerce, BigCommerce, HubSpot, or Salesforce, engineering teams bridge external ERPs using scoped MCP endpoints plus outbound webhooks. First, isolate read-only analytics tokens from commerce write endpoints in your MCP client config:

{
  "mcpServers": {
    "trolypage-analytics-readonly": {
      "url": "https://trolypage.com/mcp/analytics",
      "headers": { "Authorization": "Bearer ${TROLYPAGE_MCP_READ_TOKEN}" }
    },
    "trolypage-commerce-ops": {
      "url": "https://trolypage.com/mcp/commerce",
      "headers": { "Authorization": "Bearer ${TROLYPAGE_MCP_WRITE_TOKEN}" }
    }
  }
}

Next, deploy this TypeScript wrapper and webhook receiver. It matches each tool's real TrolyPage contract: invokeIdempotentBooking handles McpOperationReceipts (replayed: true and 409 executing_or_unknown read-verify via list-bookings), invokeIdempotentOrder handles OrderCreationService::createAiOrder() (idempotent_reuse, idempotency_conflict, and list-orders reconciliation using supported filters status, approval_status, date_from, date_to, and limit), and the Express endpoint enforces RFC 2104 HMAC-SHA256 verification on X-Webhook-Signature plus atomic Redis SET NX EX deduplication:

import crypto from "node:crypto";
import express from "express";
import Redis from "ioredis";

type CallMcpTool = (tool: string, args: Record<string, unknown>) => Promise<any>;

// 1. McpOperationReceipts wrapper (create-booking, upload-asset, import-asset, propose-fact, AutomationTool)
export async function invokeIdempotentBooking(
  callMcpTool: CallMcpTool,
  intentId: string,
  bookingArgs: { subscriber_id: string; scheduled_at: string; duration_minutes?: number }
) {
  const payload = { ...bookingArgs, idempotency_key: `bkg:${intentId}` };
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const res = await callMcpTool("create-booking", payload);
      if (res?.status === 409) {
        if (res?.errors?.status?.includes("executing_or_unknown")) {
          const check = await callMcpTool("list-bookings", { status: "pending", limit: 10 });
          return { recovered: true, operation_id: res?.errors?.operation_id?.[0], bookings: check };
        }
        throw new Error(`Argument conflict (409): ${res.message}`);
      }
      return res; // { ok: true, data: { result, replayed } }
    } catch (err: any) {
      if (attempt === 3 || err?.status === 409 || err?.status === 422) throw err;
      await new Promise((r) => setTimeout(r, 400 * 2 ** (attempt - 1)));
    }
  }
}

// 2. OrderCreationService::createAiOrder() wrapper (idempotent_reuse / idempotency_conflict)
export async function invokeIdempotentOrder(
  callMcpTool: CallMcpTool,
  intentId: string,
  orderArgs: { subscriber_id: string; items: Array<{ product_id: number; quantity: number; variant_id?: number }> }
) {
  const payload = { ...orderArgs, idempotency_key: `ord:${intentId}` };
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const res = await callMcpTool("create-order", payload);
      if (res?.errors?.code === "idempotency_conflict") {
        throw new Error(`Order cart conflict on order #${res.errors.order_id}: ${res.message}`);
      }
      return res; // { ok: true, data: { order_id, approval_status, idempotent_reuse } }
    } catch (err: any) {
      if (err?.errors?.code === "idempotency_conflict" || err?.status === 422) throw err;
      if (attempt === 3) {
        // ListOrdersTool accepts status, approval_status, date_from, date_to, limit (not subscriber_id)
        const recent = await callMcpTool("list-orders", { approval_status: "pending_review", limit: 10 });
        throw Object.assign(new Error("Transport retries exhausted; reconcile with list-orders / get-order"), { cause: err, recent });
      }
      await new Promise((r) => setTimeout(r, 400 * 2 ** (attempt - 1)));
    }
  }
}

const app = express();
const redis = new Redis(process.env.REDIS_URL!);
const SECRET = process.env.TROLYPAGE_WEBHOOK_SECRET!;

app.post("/webhooks/trolypage", express.raw({ type: "application/json" }), async (req, res) => {
  const sig = req.header("X-Webhook-Signature") ?? "";
  const ts = req.header("X-Webhook-Timestamp") ?? "";
  const eventId = req.header("X-Webhook-Event-Id") ?? "";
  const body = req.body.toString("utf8");

  if (!sig.startsWith("sha256=") || !ts || !eventId) {
    return res.status(401).json({ error: "missing_webhook_headers" });
  }
  const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(`${ts}.${body}`).digest("hex");
  const a = Buffer.from(sig, "utf8"), b = Buffer.from(expected, "utf8");
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    return res.status(401).json({ error: "invalid_webhook_signature" });
  }

  const claimed = await redis.set(`wh:troly:${eventId}`, "1", "EX", 86400, "NX");
  if (claimed !== "OK") return res.status(200).json({ ok: true, deduplicated: true });

  try {
    await enqueueErpSyncJob(JSON.parse(body));
    return res.status(202).json({ ok: true, queued: true });
  } catch {
    await redis.del(`wh:troly:${eventId}`);
    return res.status(503).json({ error: "retry_downstream_queue" });
  }
});

Practical Implementation Boundaries Teams Should Verify Before Rollout

Before enabling autonomous MCP writes across TrolyPage's omnichannel inbox and commerce stack, teams should verify five operational realities:

  • Plan & Quota Economics: Self-serve tiers run from Lite ($8/mo) and Starter ($16/mo) to Pro ($32/mo) and Scale ($104/mo), with add-ons at $1/seat/mo and $2/Page/mo (1 Page using publishing plus messaging consumes 2 connections). Free is a one-time time-limited trial (10 auto-posts/mo without links), not a permanent free tier.
  • SSO & Identity Scope: Troly ecosystem SSO uses auth tokens, with no enterprise SAML/OIDC SSO for arbitrary identity providers. Enforce least privilege via scoped PATs or RFC 8707 OAuth 2.1 sessions alongside hybrid or strict approval modes.
  • Connectors & Channels: There is no native two-way Shopify, WooCommerce, BigCommerce, HubSpot, or Salesforce admin sync, and Slack supports outbound notifications only (no two-way inbox).
  • Knowledge Parsing: Embedded text layers in uploaded PDFs and documents are indexed, and vision models interpret attached images, but there is no OCR pipeline for scanned image-only PDFs.
  • Support & Docs Locale: Automated MCP tools run 24/7, while live vendor support operates during Vietnam business hours (UTC+7) and public reference documentation at docs.trolypage.com is currently in Vietnamese.

Combining canonical arguments_hash verification, pre-execution executing claims in mcp_operation_receipts (409 executing_or_unknown read-verify for bookings, assets, knowledge, and automation), create-order cart-fingerprinted idempotent_reuse / idempotency_conflict checks, and atomic Redis webhook locks prevents retry storms without sacrificing AI workflow speed.

Comments

Your comment will appear after review.

Sign in to comment

No comments to show.