Skip to content
Dev ResourcesTested on a Mac, November 23, 2026

Make Your MCP Write Tools Safe to Call Twice With Idempotency Keys

A write tool on your MCP server can run twice for one intended action: a client retry, a resend after a timeout, or a hosted API replaying an approved call, as one developer reported to OpenAI this month. Add an idempotency key, keep the first result for 24 hours, return it on a repeat, and reject a reused key with different arguments. Built and run with the MCP TypeScript SDK v2, with the real output.

One action · one write · however many calls arrive
A key in the arguments, a store with a TTL, and the first result returned again.
MCPModel Context ProtocolIdempotencyAI AgentsTypeScriptNode.jsOpenAIResponses APITutorial
Cost
$0
Time
~30 min
Steps
6
Stack
MCP TypeScript SDK 2.4 · Node.js 24 · zod 4
What you'll get
  • ✓A two-call test that shows a duplicate write on a plain MCP tool
  • ✓An idempotency_key argument, and the description that tells the model how to use it
  • ✓A store that returns the first call's result to every repeat, for 24 hours
  • ✓A rejection for the same key with different arguments
  • ✓One write when two identical calls arrive at the same moment
  • ✓Where the key should come from when a model writes the call
Share

Once your product has an MCP server, an agent can do more than read. It can publish a post, create an order, send an invite. Every one of those calls can arrive twice for one action the user meant once: an SDK retries after a timeout, a person resends a request that seemed to hang, a model calls again because it never saw the first result. The tool runs both times, because nothing in MCP says it should not.

On November 16, 2026, a developer reported on the OpenAI community forum that the Responses API ran one approved MCP write twice. In their repro (openai Node SDK 7.43.0, SDK retries off, a run on November 15), the approval-resumption response continued with a hosted programmatic read, and their test server logged write, read, write. Both write items carried the same approval_request_id and the same arguments, and the model's final answer said it had called the write once. OpenAI Support replied on November 19 that it had shipped a fix for the extra write after a programmatic read. The same reply says that if the first request times out on your side, the write may already have gone through, and sending the request again can run it a second time, even with the same approval ID.

So a duplicate can come from the platform, from your client, or from a person, and the platform will not always catch it. The one place that sees every call is your server. This guide is the follow-up to Ship an MCP Server With Your Product: it takes one write tool, shows the duplicate, then makes the tool safe to call twice.

What was run for this guide, and what was not
Run on a Mac on November 23, 2026, with Node.js 24.13.0, @modelcontextprotocol/server and @modelcontextprotocol/client 2.4.0, and zod 4.6.7: a stdio MCP server with one write tool, before and after the fix, driven by a small client script. The code and output below are copied from that run. Not run: the Responses API repro. There was no OpenAI API key on this machine, so I did not try it and cannot say whether the duplicate, or OpenAI's fix, shows up for you. Also not run: a real model writing the key (the test client passes keys by hand), a Redis or database store, and the HTTP transport.
Step 1 of 6
5 min

Watch the duplicate happen

At a glance
SDK
@modelcontextprotocol/server 2.4.0
Transport
stdio
Result
2 posts for 1 action

Run on a Mac for this guide

The MCP TypeScript SDK is on version 2 now. The single @modelcontextprotocol/sdk package that the earlier guide used is the v1 line, which its README says will get bug fixes and security updates for at least six months after v2 shipped on July 27, 2026. v2 splits into @modelcontextprotocol/server and @modelcontextprotocol/client, and takes a schema object, such as a zod object, as a tool's input schema. Node.js 24 runs .ts files directly, so there is no build step here.

Terminal
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/[email protected] @modelcontextprotocol/[email protected] zod

A changelog server with one write tool. Each call appends a post to a file:

server-naive.ts
// server-naive.ts: one write tool, no protection against a repeated call.
import { appendFileSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { McpServer } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

const POSTS = process.env.POSTS_FILE ?? "posts.jsonl";

const server = new McpServer({ name: "changelog", version: "1.0.0" });

server.registerTool(
    "create_post",
    {
        description: "Publish a changelog post.",
        inputSchema: z.object({ title: z.string(), body: z.string() }),
        annotations: { readOnlyHint: false, idempotentHint: false },
    },
    async ({ title, body }) => {
        const post = { id: randomUUID().slice(0, 8), title, body, at: new Date().toISOString() };
        appendFileSync(POSTS, JSON.stringify(post) + "\n"); // the side effect
        return { content: [{ type: "text", text: `Published post ${post.id}` }] };
    },
);

await server.connect(new StdioServerTransport());

The test client starts a server over stdio, calls create_post the way duplicates arrive, and counts the lines in posts.jsonl after each call. It drives every run in this guide:

demo.ts
// demo.ts: start a server over stdio, call create_post the way a duplicate
// would arrive, and count what landed in posts.jsonl.
import { readFileSync, rmSync } from "node:fs";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";

const [serverFile, ttl] = process.argv.slice(2);
rmSync("posts.jsonl", { force: true });

const client = new Client({ name: "demo", version: "1.0.0" });
await client.connect(
    new StdioClientTransport({
        command: "node",
        args: [serverFile],
        env: { ...process.env, IDEMPOTENCY_TTL_MS: ttl ?? "86400000" } as Record<string, string>,
    }),
);

const text = (r: any) => `${r.isError ? "ERROR " : ""}${r.content[0].text}`;
const posts = () => readFileSync("posts.jsonl", "utf8").trim().split("\n").length;
const call = (args: Record<string, string>) => client.callTool({ name: "create_post", arguments: args });
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

const post = { title: "v1.4 is out", body: "Dark mode and CSV export." };

if (serverFile === "server-naive.ts") {
    console.log("call 1:", text(await call(post)));
    console.log("call 2:", text(await call(post)));
    console.log("posts written:", posts());
} else {
    console.log("-- same key, same arguments, one after the other");
    console.log("call 1:", text(await call({ idempotency_key: "k-7f3a9c21", ...post })));
    console.log("call 2:", text(await call({ idempotency_key: "k-7f3a9c21", ...post })));
    console.log("posts written:", posts());

    console.log("-- same key, different arguments");
    console.log("call 3:", text(await call({ idempotency_key: "k-7f3a9c21", ...post, title: "v1.5 is out" })));
    console.log("posts written:", posts());

    console.log("-- same key twice at the same moment (first call still in flight)");
    const [a, b] = await Promise.all([
        call({ idempotency_key: "k-0b5e44d8", ...post }),
        call({ idempotency_key: "k-0b5e44d8", ...post }),
    ]);
    console.log("call 4:", text(a));
    console.log("call 5:", text(b));
    console.log("posts written:", posts());

    console.log("-- no key at all");
    console.log("call 6:", text(await call(post)));
    console.log("posts written:", posts());

    if (ttl) {
        console.log(`-- same key again after the TTL (${ttl} ms) has passed`);
        await sleep(Number(ttl) + 200);
        console.log("call 7:", text(await call({ idempotency_key: "k-7f3a9c21", ...post })));
        console.log("posts written:", posts());
    }
}

await client.close();

Two calls with the same arguments:

Terminal
$ node demo.ts server-naive.ts
call 1: Published post da15ed0f
call 2: Published post cf72204e
posts written: 2

$ cat posts.jsonl
{"id":"da15ed0f","title":"v1.4 is out","body":"Dark mode and CSV export.","at":"2026-11-23T15:50:02.015Z"}
{"id":"cf72204e","title":"v1.4 is out","body":"Dark mode and CSV export.","at":"2026-11-23T15:50:02.017Z"}

Two posts with different ids, two milliseconds apart. The tool cannot tell a repeat from a second post the user really wants, because nothing in the call says which it is.

Step 2 of 6
5 min

Add an idempotency_key argument

At a glance
Where
In the tool's arguments
Required
Yes
Annotation
idempotentHint: true

Run on a Mac for this guide

The fix needs one value that is the same on every copy of a call and different for each action the user means. Put it in the arguments, because nothing else in a tools/call request identifies the action. In the OpenAI report, all three calls (write, read, write) arrived with JSON-RPC id 0, and the two writes had identical arguments. A key in those arguments would have come back with the second write.

server.ts (excerpt)
inputSchema: z.object({
    idempotency_key: z
        .string()
        .min(8)
        .max(128)
        .describe(
            "A new random value, such as a UUID, for each post you intend to publish. " +
                "If you call this tool again for the same post, after an error or a timeout, " +
                "send the same key. A key already used for different content is rejected.",
        ),
    title: z.string(),
    body: z.string(),
}),
annotations: { readOnlyHint: false, idempotentHint: true },

The description is the only instruction the model gets, so it says three things: a new value per post, the same value when retrying that post, and what happens if a key is reused. This is the definition a client receives from tools/list, printed by a short client:

list-tools.ts
// list-tools.ts: print the tool definition a client (and the model) receives.
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";

const client = new Client({ name: "list", version: "1.0.0" });
await client.connect(new StdioClientTransport({ command: "node", args: ["server.ts"] }));
const { tools } = await client.listTools();
console.log(JSON.stringify(tools[0], null, 2));
await client.close();
Terminal
$ node list-tools.ts
{
  "name": "create_post",
  "description": "Publish a changelog post.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "idempotency_key": {
        "type": "string",
        "minLength": 8,
        "maxLength": 128,
        "description": "A new random value, such as a UUID, for each post you intend to publish. If you call this tool again for the same post, after an error or a timeout, send the same key. A key already used for different content is rejected."
      },
      "title": {
        "type": "string"
      },
      "body": {
        "type": "string"
      }
    },
    "required": [
      "idempotency_key",
      "title",
      "body"
    ],
    "$schema": "https://json-schema.org/draft/2020-12/schema"
  },
  "annotations": {
    "readOnlyHint": false,
    "idempotentHint": true
  }
}

The MCP schema defines idempotentHint as: if true, calling the tool repeatedly with the same arguments will have no additional effect on its environment. With the key in the arguments, that is now true, so the hint changes from false to true.

The annotation is a hint, not the fix
The SDK's own types say clients should never make tool use decisions based on annotations from untrusted servers. Setting idempotentHint: true on a tool that writes twice changes nothing about the second write. The store in step 3 is what makes it true.
Step 3 of 6
8 min

Keep the first result and return it again

At a glance
Store
In-memory Map
Default TTL
24 hours
On a repeat
The first result, unchanged

Run on a Mac for this guide

The whole server. The handler looks the key up before it writes. If it has seen the key, it returns what the first call returned and writes nothing. If not, it writes and saves the result under the key:

server.ts
// server.ts: the same write tool, safe to call twice.
import { appendFileSync } from "node:fs";
import { createHash, randomUUID } from "node:crypto";
import { McpServer } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

const POSTS = process.env.POSTS_FILE ?? "posts.jsonl";
const TTL_MS = Number(process.env.IDEMPOTENCY_TTL_MS ?? 24 * 60 * 60 * 1000); // 24 hours

type Result = { content: { type: "text"; text: string }[]; isError?: boolean };
type Entry = {
    fingerprint: string; // hash of the arguments that define the action
    expiresAt: number;
    pending?: Promise<Result>; // set while the first call is still running
    result?: Result; // set once it finished
};
const store = new Map<string, Entry>();

function fingerprint(title: string, body: string) {
    return createHash("sha256").update(JSON.stringify([title, body])).digest("hex");
}

function log(line: string) {
    process.stderr.write(`[server] ${line}\n`);
}

async function publish(title: string, body: string): Promise<Result> {
    await new Promise((r) => setTimeout(r, 300)); // stands in for a slow API call
    const post = { id: randomUUID().slice(0, 8), title, body, at: new Date().toISOString() };
    appendFileSync(POSTS, JSON.stringify(post) + "\n"); // the side effect
    return { content: [{ type: "text", text: `Published post ${post.id}` }] };
}

const server = new McpServer({ name: "changelog", version: "1.1.0" });

server.registerTool(
    "create_post",
    {
        description: "Publish a changelog post.",
        inputSchema: z.object({
            idempotency_key: z
                .string()
                .min(8)
                .max(128)
                .describe(
                    "A new random value, such as a UUID, for each post you intend to publish. " +
                        "If you call this tool again for the same post, after an error or a timeout, " +
                        "send the same key. A key already used for different content is rejected.",
                ),
            title: z.string(),
            body: z.string(),
        }),
        annotations: { readOnlyHint: false, idempotentHint: true },
    },
    async ({ idempotency_key, title, body }) => {
        const now = Date.now();
        for (const [k, e] of store) if (e.expiresAt <= now) store.delete(k); // drop expired keys

        // Scope keys to the caller. Over stdio there is one; over HTTP use the
        // authenticated user or tenant id so two users can never share a key.
        const key = `local:${idempotency_key}`;
        const fp = fingerprint(title, body);
        const seen = store.get(key);

        if (seen) {
            if (seen.fingerprint !== fp) {
                log(`rejected ${idempotency_key}: same key, different arguments`);
                return {
                    isError: true,
                    content: [
                        {
                            type: "text",
                            text: "This idempotency_key was already used for a different post. Use a new key for a new post.",
                        },
                    ],
                };
            }
            log(`replayed ${idempotency_key} (${seen.result ? "finished" : "still in flight"})`);
            return seen.result ?? (await seen.pending!);
        }

        log(`executing ${idempotency_key}`);
        const pending = publish(title, body);
        store.set(key, { fingerprint: fp, expiresAt: now + TTL_MS, pending });
        try {
            const result = await pending;
            store.set(key, { fingerprint: fp, expiresAt: now + TTL_MS, result });
            return result;
        } catch (err) {
            store.delete(key); // the write failed, so let a retry run it again
            throw err;
        }
    },
);

await server.connect(new StdioServerTransport());

The publish function waits 300 ms to stand in for a slow API call, which step 5 needs. The run below uses node demo.ts server.ts 2000, which sets the TTL to two seconds so step 6 can show a key expiring. Same key, same arguments, one call after the other:

Terminal
$ node demo.ts server.ts 2000
-- same key, same arguments, one after the other
[server] executing k-7f3a9c21
call 1: Published post 0cf72f07
[server] replayed k-7f3a9c21 (finished)
call 2: Published post 0cf72f07
posts written: 1

One post. The second call got back the first call's text, post id included, so whoever made the second call sees the same outcome as the first and has no reason to try again.

Scope the key to the caller
Over stdio there is one user, so the code prefixes every key with local:. On a remote server, prefix it with the authenticated user or workspace id. Otherwise two users who happen to send the same key would get each other's results.
Step 4 of 6
3 min

Reject a reused key with different arguments

At a glance
Compare
SHA-256 of title and body
Answer
isError: true
Missing key
Rejected by the schema

Run on a Mac for this guide

A key alone is not enough. If a model reuses a key for a different post, a plain lookup would return the old post and silently drop the new one. So the store keeps a fingerprint of the arguments that define the action, and a repeat must match it:

Terminal
-- same key, different arguments
[server] rejected k-7f3a9c21: same key, different arguments
call 3: ERROR This idempotency_key was already used for a different post. Use a new key for a new post.
posts written: 1
...
-- no key at all
call 6: ERROR Input validation error: Invalid arguments for tool create_post: idempotency_key: Invalid input: expected string, received undefined
posts written: 2

The mismatch comes back as a tool result with isError: true, not a protocol error. The MCP spec says tool execution errors carry feedback a model can use to correct itself, and this text tells it exactly what to change. Stripe's API does the same comparison: it checks incoming parameters against the original request and errors if they differ.

Call 6 left the key out. The SDK checked the arguments against the zod schema and rejected the call before the handler ran, so a tool with a required key cannot be called without one. (Call 6 ran after step 5's two calls, which is why its count reads 2. The "..." marks where those lines were cut.)

Fingerprint the action, not the whole request
Hash only the fields that define what gets written. Leave out the key itself, and anything a client may vary between copies of the same call, such as a timestamp or a trace id. Hashing a fixed array, [title, body], also avoids depending on the order of keys in an object.
Step 5 of 6
4 min

Handle a repeat that arrives mid-write

At a glance
Case
First call still running
Here
Await the same promise
Across servers
Reserve the key first

Run on a Mac for this guide

A retry after a timeout often lands while the first call is still running. If the store only records finished results, both calls miss the lookup and both write. That is why the handler saves the key before it writes, with the pending promise, and a repeat waits on that promise. Two identical calls sent at the same moment:

Terminal
-- same key twice at the same moment (first call still in flight)
[server] executing k-0b5e44d8
[server] replayed k-0b5e44d8 (still in flight)
call 4: Published post 5ea8bad1
call 5: Published post 5ea8bad1
posts written: 2

One post, and both calls got its id. The count went from 1 to 2 because this is a new key and a new post.

If the write throws, the handler deletes the key so a retry can run it again. That is right when the write failed before it changed anything. It is wrong when it failed after: a downstream API that timed out may have committed anyway. For those writes, pass your key on to the downstream API if it accepts one (Stripe does), or keep the key and check the downstream state before writing again.

More than one server process

Not run here


A promise only exists in one process. Once you run two instances, or restart on deploy, the Map is not enough. Reserve the key with an atomic write that fails if the key exists, such as Redis SET key value NX PX ttl or an insert into a table with a unique index on the key, and have the losing call return an isError result that says the post is still being published and to call again with the same key. Better still, store the key in the same table and transaction as the post, so a crash cannot leave a post without its key.
Step 6 of 6
5 min

Pick the TTL and the key's source

At a glance
TTL here
24 hours
Stripe
Keys removable after 24 hours
Best key source
The server

Run on a Mac for this guide

A key protects you only while the store remembers it. After the TTL, the same key is a new action. With the TTL set to two seconds for this run:

Terminal
-- same key again after the TTL (2000 ms) has passed
[server] executing k-7f3a9c21
call 7: Published post 17baff4a
posts written: 3

$ cat posts.jsonl
{"id":"0cf72f07","title":"v1.4 is out","body":"Dark mode and CSV export.","at":"2026-11-23T15:50:02.513Z"}
{"id":"5ea8bad1","title":"v1.4 is out","body":"Dark mode and CSV export.","at":"2026-11-23T15:50:02.825Z"}
{"id":"17baff4a","title":"v1.4 is out","body":"Dark mode and CSV export.","at":"2026-11-23T15:50:05.336Z"}

The TTL has to be longer than the longest gap between a call and a copy of it. SDK retries arrive within seconds. A person who resends after a timeout does it within minutes. A resend from a queue or a job that crashed overnight can take hours. Stripe's docs say its keys can be removed once they are at least 24 hours old, and 24 hours is the default in the code above. Storage is one small entry per write, so there is little reason to go shorter. The store keeps a hash of the arguments, not the arguments themselves, which matters if they hold personal data.

The harder question is who writes the key. In this guide's server, the model does, and that covers less than it seems:

Who writes the keyStopsDoes not stop
The model writes it (this guide's server)A replay or resend of the same call, because the arguments, key included, come back unchangedThe model deciding to call again and writing a new key. To the server, that is a new action
Your own code sets itEvery retry your code makes, if the key comes from something stable such as the tool call's idHosted MCP tools, where the platform sends the call and your code never touches the arguments
The server issues itBoth of the above: a draft tool returns an id, and the publish tool does nothing new for an id it already publishedNothing on duplicates. It costs a second tool and a second call

A model-written key still covers the case in the OpenAI report and the resend after a timeout: both repeat the approved call as it was, key included. For writes that cost money or notify people, let the server issue the id. A draft_post tool that returns a draft id, and a publish_post tool that takes it and returns the existing post if that draft is already published, does not depend on the model remembering anything. That two-tool version was not built for this guide.

Check on the client side too

The server stops the second write. The client can still notice that one happened, which is how you find out about the next platform bug. Two suggestions from replies in the OpenAI thread, not tested here:

  • Two mcp_call items with the same approval_request_id in one response mean the approved call was sent twice. Log it.
  • Count executions from your server's log, never from the model's final answer. In the report, the answer said "once" and the server saw two writes.

And when an approval-resumption request times out, do not resend it blindly. OpenAI's reply says the write may already have happened. With the key in place, a resend returns the first result instead of writing again.

Not run here

Not run here

  • The Responses API repro, before or after OpenAI's fix. No OpenAI API key was available, so no request was sent to OpenAI for this guide.
  • A real model calling create_post: whether models write a fresh key per post and reuse it on a retry, as the description asks, was not measured.
  • The Redis and unique-index stores in step 5, and the server-issued draft id in step 6.
  • The Streamable HTTP transport and per-user key scoping behind OAuth.

Sources

Disclaimer: Nick Launches is not affiliated with OpenAI, Stripe or the Model Context Protocol project. Tested on one Mac on November 23, 2026, with Node.js 24.13.0, @modelcontextprotocol/server and @modelcontextprotocol/client 2.4.0 and zod 4.6.7. The OpenAI behavior described here is from a public forum thread and OpenAI's replies in it, and was not reproduced for this guide.

Share

Get the weekly recap

New dev-resource guides, top launches, and what's worth a look. One email a week.