Skip to content
Saimul Islam

mcp-guardrails: MCP security for servers that let AI agents change data

AI agent guardrails for MCP servers: dry run and confirm, signed preview tokens, optimistic concurrency, revision undo and errors that teach the agent.

Install
npm install mcp-guardrails
# for the official SDK integration:
npm install @modelcontextprotocol/sdk zod

Overview

An agent with write tools behaves like a fast, confident new hire. It retries calls that already succeeded, guesses field names, edits a record it read ten minutes ago, and runs a delete on the first try because nothing asked it to look first. The official MCP SDKs give you tool annotations, which are hints, but no dry-run and confirm flow, no preview tokens, no version checks and no undo.

mcp-guardrails is that layer for MCP security, extracted from production servers. You define each tool once with a kind of read, write or destructive, and the package sets the MCP annotations and enforces the guard. It works with the official MCP TypeScript SDK through an optional entry point, and the same guardrails protect the MCP servers of Sitessa and the Bundlewise CRM.

The core has no runtime dependencies and uses WebCrypto, so it runs on Node 20+ and on edge runtimes such as Cloudflare Workers.

Examples

A delete tool that needs a dry run and a preview token
import { z } from 'zod';
import { createPreviewTokens, deleteIfUnchanged, notFound } from 'mcp-guardrails';
import { defineTool } from 'mcp-guardrails/sdk';

const tokens = createPreviewTokens({ secret: process.env.MCP_PREVIEW_SECRET! }); // 32+ bytes

const notesDelete = defineTool({
  name: 'notes_delete',
  kind: 'destructive', // with tokens: dryRun → previewToken → confirm
  idempotent: true,
  description: "Delete a note. Needs a dry run and the user's confirmation.",
  input: { id: z.string() },
  version: true, // adds a required expectedVersion argument
  tokens,
  actor,
  async plan({ id }) {
    const note = await notes.get(id);
    if (!note) throw notFound('note', id);
    return { deletes: { id, title: note.value.title, version: note.version } };
  },
  async run({ id }, extra, guard) {
    const deleted = await deleteIfUnchanged(notes, { id, expectedVersion: guard.expectedVersion });
    return { deleted: id, revisionId: deleted.revisionId };
  },
});
What the agent sees: a delete without confirmation is refused
→ notes_delete { "id": "n1", "expectedVersion": 1 }
← isError: { "error": { "code": "confirmation_required",
    "message": "notes_delete needs confirm: true. Call notes_delete with dryRun: true first, show the user the plan, then call it again with the same arguments plus previewToken and confirm: true." } }
A stale version is refused with the current one
→ notes_update { "id": "n3", "expectedVersion": 4, "patch": { "title": "New" } }
← isError: { "error": { "code": "version_conflict", "currentVersion": 6, "expectedVersion": 4,
    "message": "note \"n3\" was changed since you read it (current version 6, you sent 4). Read it again, redo your change on the current data, and pass the new version." } }

Features

01One definition per tool
kind: 'read' | 'write' | 'destructive' sets the MCP annotations and the guard, so the hints and the enforcement cannot drift apart.
02Dry run, then confirm
Destructive tools return a plan first and only act on confirm: true. The error for a missing confirmation tells the agent what to call next.
03Signed preview tokens
The confirm call must carry an HMAC-SHA-256 token bound to the same action, resource, actor and arguments. Tokens expire after 15 minutes by default.
04Optimistic concurrency
An expectedVersion argument is checked with an atomic compare-and-set, and a conflict error carries the current version so the agent can read again and retry.
05Revisions with undo
A snapshot is saved before each change, history is capped at 30 per resource, secret fields are redacted on output, and revisions_list and revisions_restore give the agent an undo.
06Errors that teach
Unknown fields and invalid options come back with the valid ones and a did-you-mean, and every refusal says what to do next.
07Generated instructions
instructions() writes the rules for the agent from the tools you defined, so the text always matches what the server enforces.

Limits

  • The in-memory stores are references. They lose everything on restart and work within one process, so implement VersionedStore and RevisionStore on your database for production.
  • Tokens are only as safe as the secret. Use at least 32 random bytes, keep it out of the repository, and rotate it by passing [newSecret, oldSecret].
  • Tokens are not single-use. A token can confirm the same call more than once until it expires, so make the action idempotent or refuse repeats.
  • Token claims are signed, not encrypted. The arguments are stored only as a hash.
  • Version checks need an atomic write. The guarantee comes from your compareAndSet being atomic.
  • Snapshots are stored unredacted so restore works. Encrypt secrets at rest in your RevisionStore.
  • Annotations are hints. Clients may ignore destructiveHint; the guard is what refuses the call.

Frequently asked questions

How do I secure an MCP server that can change or delete data?

Define each tool with mcp-guardrails. Mark deletes as kind: 'destructive' with preview tokens so they need a dry run and a signed token, add expectedVersion so stale edits are refused, and record revisions so a change can be undone. The agent gets an error that says what to do next.

What are guardrails for an AI agent that uses tools?

Checks that run on the server, outside the model, so they hold even when the agent guesses wrong. Here that means a dry run before a destructive call, a signed token tied to the previewed arguments, a version check on every update, and an undo log.

Does it work with the MCP TypeScript SDK?

Yes, through mcp-guardrails/sdk, which wraps registerTool for McpServer. It needs @modelcontextprotocol/sdk 1.32 or later and zod 4 as optional peer dependencies. The core package needs neither.

How does it keep a human in the loop for an agent?

A destructive tool refuses to act on the first call and returns a plan and a previewToken. The agent is told to show the plan to the user and call again with the same arguments, the token and confirm: true. The server enforces the two steps; showing the plan to a person is up to your client.

  • Documents

    safe-html-pdf

    Print HTML to PDF with Playwright and headless Chromium, with JavaScript and the network turned off, hard limits, and a layout lint for overflow and broken images.

  • Localization

    translation-facts

    Translation quality assurance for the facts in a string: check that numbers, prices, percentages, URLs, emails and {placeholders} survive translation.

See all 9 open-source packages

Author

Built by Saimul Islam

Saimul Islam is a Forward Deployed Engineer and Solutions Architect. Several of these packages run in production on DeveloperLook, the Bundlewise CRM and Sitessa.