mcp-guardrails 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +340 -2
- package/dist/concurrency.d.ts +104 -0
- package/dist/concurrency.js +136 -0
- package/dist/define.d.ts +117 -0
- package/dist/define.js +213 -0
- package/dist/encoding.d.ts +15 -0
- package/dist/encoding.js +89 -0
- package/dist/errors.d.ts +34 -0
- package/dist/errors.js +104 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +18 -0
- package/dist/instructions.d.ts +36 -0
- package/dist/instructions.js +56 -0
- package/dist/merge-patch.d.ts +6 -0
- package/dist/merge-patch.js +29 -0
- package/dist/result.d.ts +31 -0
- package/dist/result.js +48 -0
- package/dist/revisions.d.ts +119 -0
- package/dist/revisions.js +166 -0
- package/dist/sdk.d.ts +88 -0
- package/dist/sdk.js +144 -0
- package/dist/tokens.d.ts +62 -0
- package/dist/tokens.js +107 -0
- package/package.json +84 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
Initial release.
|
|
6
|
+
|
|
7
|
+
- `defineTool`: MCP annotations from `kind` (read, write, destructive) plus a guard for dry runs, confirmation, preview tokens and expected versions.
|
|
8
|
+
- `createPreviewTokens`: HMAC-SHA-256 preview tokens over WebCrypto, bound to action, resource, actor and payload hash, with expiry, key rotation and distinct errors for tampering, expiry, mismatch and stale state.
|
|
9
|
+
- Optimistic concurrency: `checkVersion`, `updateIfUnchanged` and `deleteIfUnchanged` over a storage-agnostic compare-and-set interface, with a conflict error that carries the current version.
|
|
10
|
+
- `createRevisionLog`: snapshots before each change, capped history, secret-field redaction, scopes and restore.
|
|
11
|
+
- `jsonMergePatch` (RFC 7396), agent-facing errors that list the valid options, and `instructions()` for the server-instructions text.
|
|
12
|
+
- `mcp-guardrails/sdk`: `defineTool`, `registerTools` and `revisionTools` for the official TypeScript SDK.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Saimul Islam
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,341 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mcp-guardrails
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Safety rails for MCP servers that let AI agents change data.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/mcp-guardrails)
|
|
6
|
+
[](https://www.npmjs.com/package/mcp-guardrails)
|
|
7
|
+
[](https://www.npmjs.com/package/mcp-guardrails)
|
|
8
|
+
|
|
9
|
+
The same guardrails protect the MCP servers of [Sitessa](https://sitessa.com) and the [Bundlewise CRM](https://crm.bundlewise.app).
|
|
10
|
+
|
|
11
|
+
## The problem
|
|
12
|
+
|
|
13
|
+
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. Every server ends up writing those itself.
|
|
14
|
+
|
|
15
|
+
mcp-guardrails is that layer, extracted from production servers:
|
|
16
|
+
|
|
17
|
+
- **One definition per tool.** `kind: 'read' | 'write' | 'destructive'` sets the MCP annotations and the guard.
|
|
18
|
+
- **Dry run, then confirm.** Destructive tools return a plan first and only act on `confirm: true`.
|
|
19
|
+
- **Signed preview tokens.** The confirm call must carry an HMAC token bound to the same action, resource, actor and arguments. Tokens expire.
|
|
20
|
+
- **Optimistic concurrency.** `expectedVersion` checks with an atomic compare-and-set, and a conflict error that carries the current version.
|
|
21
|
+
- **Revisions with undo.** A snapshot before each change, capped history, secret fields redacted, restore.
|
|
22
|
+
- **Errors that teach.** Unknown fields and invalid options come back with the valid ones, and every refusal says what to do next.
|
|
23
|
+
- **Instructions text.** `instructions()` writes the rules for the agent from the tools you defined.
|
|
24
|
+
|
|
25
|
+
The core has no runtime dependencies and uses WebCrypto, so it runs on Node 20+ and on edge runtimes such as Cloudflare Workers. Results use the MCP shape, so it fits any server. An optional `mcp-guardrails/sdk` entry point wires it into the official TypeScript SDK.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
npm install mcp-guardrails
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
For the official SDK integration, also install its peer dependencies:
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
npm install @modelcontextprotocol/sdk zod
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`mcp-guardrails/sdk` needs `@modelcontextprotocol/sdk` 1.32 or later and zod 4. The core (`mcp-guardrails`) needs neither.
|
|
40
|
+
|
|
41
|
+
## A complete server
|
|
42
|
+
|
|
43
|
+
A notes server with every guardrail on: a read tool, a versioned merge-patch update, a delete that needs a preview token, and undo through the revision log.
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
47
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
48
|
+
import { z } from 'zod';
|
|
49
|
+
import {
|
|
50
|
+
assertKnownFields,
|
|
51
|
+
assertOption,
|
|
52
|
+
createMemoryStore,
|
|
53
|
+
createPreviewTokens,
|
|
54
|
+
createRevisionLog,
|
|
55
|
+
deleteIfUnchanged,
|
|
56
|
+
instructions,
|
|
57
|
+
jsonMergePatch,
|
|
58
|
+
notFound,
|
|
59
|
+
updateIfUnchanged,
|
|
60
|
+
} from 'mcp-guardrails';
|
|
61
|
+
import { defineTool, registerTools, revisionTools } from 'mcp-guardrails/sdk';
|
|
62
|
+
import type { ToolExtra } from 'mcp-guardrails/sdk';
|
|
63
|
+
|
|
64
|
+
type Note = { title: string; body: string; status: 'draft' | 'published' };
|
|
65
|
+
const NOTE_FIELDS = ['title', 'body', 'status'];
|
|
66
|
+
const STATUSES = ['draft', 'published'] as const;
|
|
67
|
+
|
|
68
|
+
const notes = createMemoryStore<Note>({ n1: { title: 'Hello', body: 'First note', status: 'draft' } });
|
|
69
|
+
const revisions = createRevisionLog();
|
|
70
|
+
const tokens = createPreviewTokens({ secret: process.env.MCP_PREVIEW_SECRET! }); // 32+ bytes
|
|
71
|
+
// Who is calling: your user (and tenant) id from the auth info. Over stdio there is one local user.
|
|
72
|
+
const actor = (extra: ToolExtra) => String(extra.authInfo?.extra?.userId ?? 'local');
|
|
73
|
+
|
|
74
|
+
const notesGet = defineTool({
|
|
75
|
+
name: 'notes_get',
|
|
76
|
+
kind: 'read',
|
|
77
|
+
description: 'Get a note with its version.',
|
|
78
|
+
input: { id: z.string() },
|
|
79
|
+
async run({ id }) {
|
|
80
|
+
const note = await notes.get(id);
|
|
81
|
+
if (!note) throw notFound('note', id);
|
|
82
|
+
return { id, version: note.version, note: note.value };
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
const notesUpdate = defineTool({
|
|
87
|
+
name: 'notes_update',
|
|
88
|
+
kind: 'write',
|
|
89
|
+
description: 'Change a note with a JSON Merge Patch of its fields (title, body, status).',
|
|
90
|
+
input: { id: z.string(), patch: z.record(z.string(), z.unknown()) },
|
|
91
|
+
version: true, // adds a required expectedVersion argument
|
|
92
|
+
async run({ id, patch }, extra, guard) {
|
|
93
|
+
assertKnownFields(patch, NOTE_FIELDS, 'patch');
|
|
94
|
+
if (patch.status !== undefined) assertOption('status', patch.status, STATUSES);
|
|
95
|
+
const saved = await updateIfUnchanged(notes, {
|
|
96
|
+
id,
|
|
97
|
+
expectedVersion: guard.expectedVersion,
|
|
98
|
+
update: (note) => jsonMergePatch<Note>(note, patch),
|
|
99
|
+
revision: { log: revisions, resourceType: 'note', actor: actor(extra) },
|
|
100
|
+
});
|
|
101
|
+
return { id, version: saved.version, note: saved.value };
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const notesDelete = defineTool({
|
|
106
|
+
name: 'notes_delete',
|
|
107
|
+
kind: 'destructive', // with tokens: dryRun → previewToken → confirm
|
|
108
|
+
idempotent: true,
|
|
109
|
+
description: "Delete a note. Needs a dry run and the user's confirmation.",
|
|
110
|
+
input: { id: z.string() },
|
|
111
|
+
version: true,
|
|
112
|
+
tokens,
|
|
113
|
+
actor,
|
|
114
|
+
async plan({ id }) {
|
|
115
|
+
const note = await notes.get(id);
|
|
116
|
+
if (!note) throw notFound('note', id);
|
|
117
|
+
return { deletes: { id, title: note.value.title, version: note.version } };
|
|
118
|
+
},
|
|
119
|
+
async run({ id }, extra, guard) {
|
|
120
|
+
const deleted = await deleteIfUnchanged(notes, {
|
|
121
|
+
id,
|
|
122
|
+
expectedVersion: guard.expectedVersion,
|
|
123
|
+
revision: { log: revisions, resourceType: 'note', actor: actor(extra) },
|
|
124
|
+
});
|
|
125
|
+
return { deleted: id, revisionId: deleted.revisionId };
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
const undo = revisionTools({ log: revisions, stores: { note: notes }, actor });
|
|
130
|
+
const tools = [notesGet, notesUpdate, notesDelete, undo.list, undo.restore];
|
|
131
|
+
|
|
132
|
+
const server = new McpServer(
|
|
133
|
+
{ name: 'notes', version: '1.0.0' },
|
|
134
|
+
{
|
|
135
|
+
instructions: instructions({
|
|
136
|
+
intro: 'Notes: read, change and delete notes.',
|
|
137
|
+
tools,
|
|
138
|
+
mergePatch: true,
|
|
139
|
+
revisions: true,
|
|
140
|
+
}),
|
|
141
|
+
},
|
|
142
|
+
);
|
|
143
|
+
registerTools(server, tools);
|
|
144
|
+
await server.connect(new StdioServerTransport());
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
The same server is in [`examples/notes-server.ts`](examples/notes-server.ts), and the end-to-end test drives it with an SDK client.
|
|
148
|
+
|
|
149
|
+
### What the agent sees
|
|
150
|
+
|
|
151
|
+
`tools/list` shows the annotations and the guard arguments. `notes_delete` gets `readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false`, and its input schema becomes `{ id, dryRun?, confirm?, previewToken?, expectedVersion }` with `additionalProperties: false`. Each guard argument carries a description that tells the agent how to use it.
|
|
152
|
+
|
|
153
|
+
A typical call sequence:
|
|
154
|
+
|
|
155
|
+
```jsonc
|
|
156
|
+
// 1. Read first, to get the version.
|
|
157
|
+
→ notes_get { "id": "n1" }
|
|
158
|
+
← { "id": "n1", "version": 1, "note": { "title": "Hello", "body": "First note", "status": "draft" } }
|
|
159
|
+
|
|
160
|
+
// 2. A delete without confirmation is refused, with the next step.
|
|
161
|
+
→ notes_delete { "id": "n1", "expectedVersion": 1 }
|
|
162
|
+
← isError: { "error": { "code": "confirmation_required",
|
|
163
|
+
"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." } }
|
|
164
|
+
|
|
165
|
+
// 3. The dry run returns the plan and a token. Nothing changes.
|
|
166
|
+
→ notes_delete { "id": "n1", "expectedVersion": 1, "dryRun": true }
|
|
167
|
+
← { "dryRun": true, "plan": { "deletes": { "id": "n1", "title": "Hello", "version": 1 } },
|
|
168
|
+
"previewToken": "eyJ2IjoxLC…", "expiresAt": "2026-01-01T12:15:00.000Z",
|
|
169
|
+
"next": "Show the user this plan. To apply it, call notes_delete again with the same arguments plus this previewToken and confirm: true (valid until 2026-01-01T12:15:00.000Z)." }
|
|
170
|
+
|
|
171
|
+
// 4. After the user agrees: same arguments, the token, confirm.
|
|
172
|
+
→ notes_delete { "id": "n1", "expectedVersion": 1, "previewToken": "eyJ2IjoxLC…", "confirm": true }
|
|
173
|
+
← { "deleted": "n1", "revisionId": "4c0d…" }
|
|
174
|
+
|
|
175
|
+
// The token only works for what was previewed:
|
|
176
|
+
→ notes_delete { "id": "n2", "expectedVersion": 1, "previewToken": "eyJ2IjoxLC…", "confirm": true }
|
|
177
|
+
← isError: { "error": { "code": "preview_mismatch", "mismatch": ["resource", "payload"],
|
|
178
|
+
"message": "The previewToken was issued for a different resource, payload. Confirm with exactly the arguments you previewed, or preview the new ones first." } }
|
|
179
|
+
|
|
180
|
+
// A stale version is refused with the current one.
|
|
181
|
+
→ notes_update { "id": "n3", "expectedVersion": 4, "patch": { "title": "New" } }
|
|
182
|
+
← isError: { "error": { "code": "version_conflict", "currentVersion": 6, "expectedVersion": 4,
|
|
183
|
+
"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." } }
|
|
184
|
+
|
|
185
|
+
// A guessed field name comes back with the real ones.
|
|
186
|
+
→ notes_update { "id": "n3", "expectedVersion": 6, "patch": { "titel": "New" } }
|
|
187
|
+
← isError: { "error": { "code": "unknown_field", "fields": ["titel"], "knownFields": ["title", "body", "status"],
|
|
188
|
+
"didYouMean": { "titel": "title" }, "message": "Unknown field in patch: \"titel\". Known fields: …" } }
|
|
189
|
+
|
|
190
|
+
// Undo: list revisions, preview the restore, confirm it.
|
|
191
|
+
→ revisions_list { "resourceId": "n1" }
|
|
192
|
+
← { "revisions": [{ "id": "4c0d…", "resourceType": "note", "resourceId": "n1", "operation": "delete", … }] }
|
|
193
|
+
→ revisions_restore { "revisionId": "4c0d…", "dryRun": true }
|
|
194
|
+
→ revisions_restore { "revisionId": "4c0d…", "confirm": true }
|
|
195
|
+
← { "restoredFrom": "4c0d…", "revisionId": "9a1e…", "resourceType": "note", "resourceId": "n1", "version": 7, "deleted": false }
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## API reference
|
|
199
|
+
|
|
200
|
+
### Core: `mcp-guardrails`
|
|
201
|
+
|
|
202
|
+
| Export | What it does |
|
|
203
|
+
| --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
204
|
+
| `defineTool(definition)` | A `GuardedTool`: annotations from `kind`, the guard's arguments, and `call(args, ctx)` that enforces them and returns an MCP result. |
|
|
205
|
+
| `annotationsFor(kind, options?)` | The MCP annotations for a kind, without the rest. |
|
|
206
|
+
| `createPreviewTokens({ secret, ttlMs?, now? })` | `{ issue(binding), verify(token, binding), ttlMs }`. HMAC-SHA-256 over WebCrypto. Default lifetime 15 minutes. |
|
|
207
|
+
| `checkVersion(current, expected, options?)` | Fast-fail version check: `version_required`, `version_conflict`. |
|
|
208
|
+
| `updateIfUnchanged(store, options)` / `deleteIfUnchanged(store, opt)` | Read, check `expectedVersion`, write with compare-and-set, optionally record a revision. Returns `{ value, version, previous, revisionId }`. |
|
|
209
|
+
| `sameVersion(a, b)` | Version equality; timestamps compare by instant. |
|
|
210
|
+
| `versionConflict(current, expected, resource?)` | The `version_conflict` error, for your own write paths. |
|
|
211
|
+
| `createMemoryStore(initial?)` | A reference `VersionedStore` in memory. |
|
|
212
|
+
| `createRevisionLog(options?)` | `{ record, list, get, restore, redact }`. Capped history (30 per resource), redaction on output. |
|
|
213
|
+
| `createMemoryRevisionStore()` | The reference `RevisionStore` in memory. |
|
|
214
|
+
| `jsonMergePatch(target, patch)` | RFC 7396 JSON Merge Patch. Inputs are not modified. |
|
|
215
|
+
| `invalidOption(field, value, options)` / `assertOption(...)` | `invalid_option` with the valid values and a "did you mean". |
|
|
216
|
+
| `unknownField(fields, known, where?)` / `assertKnownFields(...)` | `unknown_field` with the known fields and suggestions. |
|
|
217
|
+
| `confirmationRequired(tool, next?)`, `notFound(resource, id)` | The other common refusals. |
|
|
218
|
+
| `GuardrailError`, `isGuardrailError(error)` | An error with a `code`, an agent-facing `message` and `details`. Throw it from any handler. |
|
|
219
|
+
| `toolResult(data)`, `toolError(error, options?)` | Build MCP results by hand. Unexpected errors become `internal_error` without their message. |
|
|
220
|
+
| `instructions(options)` | The server-instructions text. See [Conventions](#conventions). |
|
|
221
|
+
|
|
222
|
+
#### `defineTool` options
|
|
223
|
+
|
|
224
|
+
| Option | Default | Meaning |
|
|
225
|
+
| ------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
|
|
226
|
+
| `name`, `description` | | Required. |
|
|
227
|
+
| `kind` | | `read`, `write` or `destructive`. |
|
|
228
|
+
| `title` | | Display name, also in the annotations. |
|
|
229
|
+
| `idempotent`, `openWorld` | `false` | The matching hints. |
|
|
230
|
+
| `confirm` | `preview` for destructive with `tokens`, `flag` for other destructive, else `none` | `flag`: `confirm: true` required, `dryRun` returns the plan. `preview`: also a valid `previewToken` from the dry run. |
|
|
231
|
+
| `tokens` | | From `createPreviewTokens`. Required for `preview`. |
|
|
232
|
+
| `actor(ctx)` | | The caller's id the token is bound to. Required for `preview`. |
|
|
233
|
+
| `resource(args)` | `args.id` | The resource the token is bound to. |
|
|
234
|
+
| `bind(args)` | all arguments except `dryRun`, `confirm`, `previewToken` | The payload whose hash the token carries. |
|
|
235
|
+
| `fingerprint(args, ctx)` | | State the plan depends on (a count, a version). A change gives `preview_stale`. |
|
|
236
|
+
| `previewTool` | | A separate tool issues the token through `tool.preview(args, ctx)`; this tool then has no `dryRun`. |
|
|
237
|
+
| `version` | | `true` or `{ field?: 'expectedVersion', required?: true }`. The value reaches `run` as `guard.expectedVersion`. |
|
|
238
|
+
| `fields` | | Known argument names; others get `unknown_field`. The SDK helpers enforce this through the schema instead. |
|
|
239
|
+
| `plan(args, ctx, guard)` | the tool, resource and arguments | The dry-run result. Must not change anything. |
|
|
240
|
+
| `run(args, ctx, guard)` | | Does the work and returns plain data (sent as JSON text and `structuredContent`). |
|
|
241
|
+
| `onError(error, tool)` | `console.error`, then `internal_error` | Map your own errors to a `GuardrailError` the agent may see. |
|
|
242
|
+
|
|
243
|
+
`guard` is `{ tool, expectedVersion?, confirmed, preview? }`, where `preview` holds the verified token claims.
|
|
244
|
+
|
|
245
|
+
#### Interfaces you implement
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
interface VersionedStore<T> {
|
|
249
|
+
get(id: string): Promise<{ value: T; version: string | number } | undefined>;
|
|
250
|
+
// Atomic: write `next` only while the stored version equals `expected`, bump the version in the same write.
|
|
251
|
+
// null means absent on both sides: expected null creates, next null deletes.
|
|
252
|
+
compareAndSet(
|
|
253
|
+
id: string,
|
|
254
|
+
expected: Version | null,
|
|
255
|
+
next: T | null,
|
|
256
|
+
): Promise<{ ok: true; version: Version | null } | { ok: false }>;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
interface RevisionStore {
|
|
260
|
+
add(revision: Revision): Promise<void>;
|
|
261
|
+
get(id: string): Promise<Revision | undefined>;
|
|
262
|
+
list(query: { resourceType?; resourceId?; scope?; limit: number }): Promise<Revision[]>; // newest first
|
|
263
|
+
prune(resource: { resourceType; resourceId; scope? }, keep: number): Promise<void>;
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
On a SQL database, `compareAndSet` is `UPDATE … SET …, version = version + 1 WHERE id = ? AND version = ?` and checking the affected row count. On MongoDB it is `findOneAndUpdate({ _id, updatedAt: expected }, …)`.
|
|
268
|
+
|
|
269
|
+
#### Revision log options
|
|
270
|
+
|
|
271
|
+
| Option | Default | Meaning |
|
|
272
|
+
| ------------------ | ------------------------- | ----------------------------------------------------------------------------- |
|
|
273
|
+
| `store` | in memory | A `RevisionStore`. |
|
|
274
|
+
| `maxPerResource` | `30` | History kept per resource. |
|
|
275
|
+
| `redact` | `DEFAULT_REDACTED_FIELDS` | Field names (or patterns) shown as `"[redacted]"` by `get` and restore plans. |
|
|
276
|
+
| `defaultListLimit` | `20` | Page size of `list`. |
|
|
277
|
+
| `maxListLimit` | `100` | Largest page. |
|
|
278
|
+
|
|
279
|
+
Revisions take an optional `scope` (for example the tenant id). Pass the caller's scope to `list`, `get` and `restore` and they only see that scope.
|
|
280
|
+
|
|
281
|
+
### Official SDK: `mcp-guardrails/sdk`
|
|
282
|
+
|
|
283
|
+
| Export | What it does |
|
|
284
|
+
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
|
285
|
+
| `defineTool(definition)` | The core `defineTool` plus `input` (a zod shape that types `run`) and optional `output`. The context is the SDK's `extra`. |
|
|
286
|
+
| `registerTools(server, tools)` | Registers those tools on an `McpServer` with `registerTool`. |
|
|
287
|
+
| `revisionTools({ log, stores, ... })` | `revisions_list` and `revisions_restore` for a revision log. Options: `scope(extra)`, `actor(extra)`, `tokens`, `names`. |
|
|
288
|
+
| `toolConfig(tool, { input, output })` | The `registerTool` config: description, annotations, and the input schema with the guard's arguments, as a strict zod object. |
|
|
289
|
+
| `toolHandler(tool)` | The `registerTool` callback. |
|
|
290
|
+
| `inputSchema(tool, input)` | The strict input schema alone. |
|
|
291
|
+
|
|
292
|
+
Define tools before creating the server, so `instructions({ tools })` can describe them: the SDK takes instructions in the `McpServer` constructor.
|
|
293
|
+
|
|
294
|
+
## Conventions
|
|
295
|
+
|
|
296
|
+
These are the rules agents learn, and what enforces them:
|
|
297
|
+
|
|
298
|
+
| Rule | Enforced by |
|
|
299
|
+
| ------------------------------------------------------------------------- | --------------------------------------------------------- |
|
|
300
|
+
| Call `*_get` before `*_update`; pass `expectedVersion` from the response. | `version: true`, `updateIfUnchanged` |
|
|
301
|
+
| Deletes and bulk operations: `dryRun: true` first, then `confirm: true`. | `confirm: 'flag'` |
|
|
302
|
+
| Call the preview first, then pass `previewToken` + `confirm: true`. | `confirm: 'preview'`, `tokens` |
|
|
303
|
+
| Unknown fields are rejected with the valid options. | strict input schemas, `assertKnownFields`, `assertOption` |
|
|
304
|
+
| Updates take a JSON Merge Patch; pass `expectedVersion`. | `jsonMergePatch` |
|
|
305
|
+
| `revisions_list` → `revisions_restore` to undo. | `createRevisionLog`, `revisionTools` |
|
|
306
|
+
|
|
307
|
+
`instructions()` writes them from the tools you pass, so the text always matches what the server enforces. The version field name, the tools that need a dry run or a preview token, and the token lifetime come from the tool definitions; `mergePatch` and `revisions` are switched on by you. For the server above it returns:
|
|
308
|
+
|
|
309
|
+
```text
|
|
310
|
+
Notes: read, change and delete notes.
|
|
311
|
+
|
|
312
|
+
Rules:
|
|
313
|
+
- Call *_get before an update and pass expectedVersion from that response. If the data changed in the meantime the update is refused with version_conflict and the current version: read again and redo the change.
|
|
314
|
+
- Updates take a JSON Merge Patch: send only the fields that change; nested objects merge; lists replace (send the whole list); null clears a field.
|
|
315
|
+
- Deletes and bulk operations (revisions_restore): call with dryRun: true first, show the user the plan, then call again with confirm: true once they agree.
|
|
316
|
+
- notes_delete: call with dryRun: true first, show the user the plan, then call again with the same arguments plus previewToken and confirm: true.
|
|
317
|
+
- Tokens expire after 15 minutes and only work for the arguments that were previewed; preview again after any change.
|
|
318
|
+
- Never invent fields or values: unknown fields and options are rejected with the valid options.
|
|
319
|
+
- Every change saves a revision: revisions_list → revisions_restore to undo.
|
|
320
|
+
- A refused call returns an error that names the problem and how to fix it. Follow the message; never repeat a refused call unchanged.
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
Options: `intro`, `tools`, `readTool` (default `*_get`), `version` (a field name, or `false`), `confirm`, `preview`, `unknownFields`, `mergePatch`, `revisions` (`true` or `{ list, restore }`), `errors`, and `rules` for your own lines. Without `tools`, the flags alone decide which rules are written.
|
|
324
|
+
|
|
325
|
+
Error codes: `invalid_arguments`, `invalid_option`, `unknown_field`, `confirmation_required`, `preview_required`, `preview_invalid`, `preview_expired`, `preview_mismatch`, `preview_stale`, `version_required`, `version_conflict`, `not_found`, `internal_error`. Your handlers can throw `GuardrailError` with codes of their own.
|
|
326
|
+
|
|
327
|
+
## Limits
|
|
328
|
+
|
|
329
|
+
- **The in-memory stores are references.** `createMemoryStore` and `createMemoryRevisionStore` lose everything on restart and only work within one process. Implement `VersionedStore` and `RevisionStore` on your database for production.
|
|
330
|
+
- **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]`. Anyone with the secret can mint tokens.
|
|
331
|
+
- **Tokens are not single-use.** A token can confirm the same call more than once until it expires. Make the action idempotent, or store `guard.preview.id` until `expiresAt` and refuse repeats.
|
|
332
|
+
- **Token claims are signed, not encrypted.** The action, resource and actor are readable by whoever holds the token; the arguments are only stored as a hash.
|
|
333
|
+
- **The actor binding is yours to get right.** `actor` must return an id the client can't choose, such as the user from verified auth info, with the tenant if you have one.
|
|
334
|
+
- **Version checks need an atomic write.** `checkVersion` alone only fails fast. The guarantee comes from your `compareAndSet` being atomic.
|
|
335
|
+
- **Snapshots are stored unredacted.** Redaction applies to what agents see; restore needs the real values. Encrypt secrets at rest in your `RevisionStore`.
|
|
336
|
+
- **Annotations are hints.** Clients may ignore `destructiveHint`. The guard is what actually refuses the call.
|
|
337
|
+
- **Output schemas and dry runs don't mix.** A tool with a dry run returns two shapes, so the SDK helpers refuse an `output` schema on it.
|
|
338
|
+
|
|
339
|
+
## License
|
|
340
|
+
|
|
341
|
+
MIT © Saimul Islam
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { GuardrailError } from './errors.ts';
|
|
2
|
+
import type { RevisionLog } from './revisions.ts';
|
|
3
|
+
/** A resource version: a counter, an etag, or an `updatedAt` timestamp as an ISO string. */
|
|
4
|
+
export type Version = string | number;
|
|
5
|
+
/** A stored value with its version. */
|
|
6
|
+
export interface Versioned<T> {
|
|
7
|
+
value: T;
|
|
8
|
+
version: Version;
|
|
9
|
+
}
|
|
10
|
+
/** Outcome of a compare-and-set: the new version (`null` after a delete), or `ok: false` when it moved on. */
|
|
11
|
+
export type CompareAndSetResult = {
|
|
12
|
+
ok: true;
|
|
13
|
+
version: Version | null;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* The one storage interface for versioned writes. `compareAndSet` must be atomic: write `next` only while
|
|
19
|
+
* the stored version still equals `expected`, and bump the version in the same write.
|
|
20
|
+
* `null` means "absent" on both sides: `expected: null` creates, `next: null` deletes.
|
|
21
|
+
*/
|
|
22
|
+
export interface VersionedStore<T> {
|
|
23
|
+
get(id: string): Promise<Versioned<T> | undefined>;
|
|
24
|
+
compareAndSet(id: string, expected: Version | null, next: T | null): Promise<CompareAndSetResult>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* True when two versions are the same. Timestamps compare by instant, so `2025-01-02T03:04:05Z` equals
|
|
28
|
+
* `2025-01-02T03:04:05.000Z`; numbers and their decimal strings are equal too.
|
|
29
|
+
*/
|
|
30
|
+
export declare function sameVersion(a: Version | null | undefined, b: Version | null | undefined): boolean;
|
|
31
|
+
/** Options for `checkVersion`. */
|
|
32
|
+
export interface CheckVersionOptions {
|
|
33
|
+
/** Refuse a missing expected version with `version_required`. Default true. */
|
|
34
|
+
required?: boolean;
|
|
35
|
+
/** The argument name the agent sends, for messages. Default `expectedVersion`. */
|
|
36
|
+
field?: string;
|
|
37
|
+
/** What is being changed, for messages, for example `note "n1"`. */
|
|
38
|
+
resource?: string;
|
|
39
|
+
}
|
|
40
|
+
/** `version_conflict`: the resource moved on. Carries the current version so the agent can re-read. */
|
|
41
|
+
export declare function versionConflict(currentVersion: Version | null, expectedVersion: unknown, resource?: string): GuardrailError;
|
|
42
|
+
/**
|
|
43
|
+
* Fast-fail check of `expected` against the version just read. Throws `version_required` or
|
|
44
|
+
* `version_conflict`. Not a lock on its own: pair it with `compareAndSet` (or `updateIfUnchanged`).
|
|
45
|
+
*/
|
|
46
|
+
export declare function checkVersion(current: Version | null | undefined, expected: unknown, options?: CheckVersionOptions): void;
|
|
47
|
+
/** Records a revision of the previous value after a successful write. */
|
|
48
|
+
export interface RevisionTarget {
|
|
49
|
+
log: RevisionLog;
|
|
50
|
+
/** The resource type the revision is filed under, for example `note`. */
|
|
51
|
+
resourceType: string;
|
|
52
|
+
actor?: string;
|
|
53
|
+
/** Partition, for example the tenant id. Lists and restores only see revisions of their own scope. */
|
|
54
|
+
scope?: string;
|
|
55
|
+
summary?: string;
|
|
56
|
+
}
|
|
57
|
+
/** Options for `updateIfUnchanged`. */
|
|
58
|
+
export interface UpdateOptions<T> {
|
|
59
|
+
id: string;
|
|
60
|
+
/** The version the agent read. */
|
|
61
|
+
expectedVersion: unknown;
|
|
62
|
+
/** Computes the new value from the current one. Must not have side effects: it may run before a conflict. */
|
|
63
|
+
update: (current: T) => T | Promise<T>;
|
|
64
|
+
/** Refuse calls without `expectedVersion`. Default true. */
|
|
65
|
+
required?: boolean;
|
|
66
|
+
/** Names the resource in messages. Default `` `${resourceType ?? 'resource'} "${id}"` ``. */
|
|
67
|
+
label?: string;
|
|
68
|
+
/** Snapshot the previous value into this revision log once the write succeeds. */
|
|
69
|
+
revision?: RevisionTarget;
|
|
70
|
+
}
|
|
71
|
+
/** Options for `deleteIfUnchanged`. */
|
|
72
|
+
export type DeleteOptions<T> = Omit<UpdateOptions<T>, 'update'>;
|
|
73
|
+
/** What a versioned write returns. */
|
|
74
|
+
export interface WriteResult<T> {
|
|
75
|
+
/** The stored value after the write; `null` after a delete. */
|
|
76
|
+
value: T | null;
|
|
77
|
+
/** The new version; `null` after a delete. */
|
|
78
|
+
version: Version | null;
|
|
79
|
+
/** The value before the write. */
|
|
80
|
+
previous: T;
|
|
81
|
+
previousVersion: Version;
|
|
82
|
+
/** Id of the revision saved for the previous value, when `revision` was set. */
|
|
83
|
+
revisionId?: string;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Optimistic-locked update: reads the current value, checks `expectedVersion`, and writes the update with
|
|
87
|
+
* an atomic compare-and-set. When another writer got in between, nothing is written and the call fails
|
|
88
|
+
* with `version_conflict` carrying the current version.
|
|
89
|
+
*/
|
|
90
|
+
export declare function updateIfUnchanged<T>(store: VersionedStore<T>, options: UpdateOptions<T>): Promise<WriteResult<T>>;
|
|
91
|
+
/** Optimistic-locked delete, with the same checks as `updateIfUnchanged`. */
|
|
92
|
+
export declare function deleteIfUnchanged<T>(store: VersionedStore<T>, options: DeleteOptions<T>): Promise<WriteResult<T>>;
|
|
93
|
+
/** An in-memory `VersionedStore` with a `seed` method and a synchronous `snapshot` for tests. */
|
|
94
|
+
export interface MemoryStore<T> extends VersionedStore<T> {
|
|
95
|
+
/** Writes without a version check (setup and tests). Returns the new version. */
|
|
96
|
+
seed(id: string, value: T): number;
|
|
97
|
+
/** All current values by id. */
|
|
98
|
+
snapshot(): Record<string, Versioned<T>>;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* A reference `VersionedStore` kept in memory. Versions are integers from one counter shared by every
|
|
102
|
+
* id, so a deleted and recreated record never reuses an old version. Values are cloned in and out.
|
|
103
|
+
*/
|
|
104
|
+
export declare function createMemoryStore<T>(initial?: Record<string, T>): MemoryStore<T>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { GuardrailError, notFound } from "./errors.js";
|
|
2
|
+
const TIMESTAMP = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
|
|
3
|
+
function normalize(version) {
|
|
4
|
+
if (typeof version === 'string') {
|
|
5
|
+
const text = version.trim();
|
|
6
|
+
if (TIMESTAMP.test(text)) {
|
|
7
|
+
const time = Date.parse(text.includes('T') ? text : text.replace(' ', 'T'));
|
|
8
|
+
if (!Number.isNaN(time))
|
|
9
|
+
return new Date(time).toISOString();
|
|
10
|
+
}
|
|
11
|
+
return text;
|
|
12
|
+
}
|
|
13
|
+
return version;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* True when two versions are the same. Timestamps compare by instant, so `2025-01-02T03:04:05Z` equals
|
|
17
|
+
* `2025-01-02T03:04:05.000Z`; numbers and their decimal strings are equal too.
|
|
18
|
+
*/
|
|
19
|
+
export function sameVersion(a, b) {
|
|
20
|
+
if (a === null || a === undefined || b === null || b === undefined)
|
|
21
|
+
return a == b;
|
|
22
|
+
return String(normalize(a)) === String(normalize(b));
|
|
23
|
+
}
|
|
24
|
+
/** `version_conflict`: the resource moved on. Carries the current version so the agent can re-read. */
|
|
25
|
+
export function versionConflict(currentVersion, expectedVersion, resource) {
|
|
26
|
+
const what = resource ?? 'The resource';
|
|
27
|
+
return new GuardrailError('version_conflict', `${what} was changed since you read it (current version ${JSON.stringify(currentVersion)}, you sent ${JSON.stringify(expectedVersion)}). ` +
|
|
28
|
+
'Read it again, redo your change on the current data, and pass the new version.', { currentVersion, expectedVersion, ...(resource ? { resource } : {}) });
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Fast-fail check of `expected` against the version just read. Throws `version_required` or
|
|
32
|
+
* `version_conflict`. Not a lock on its own: pair it with `compareAndSet` (or `updateIfUnchanged`).
|
|
33
|
+
*/
|
|
34
|
+
export function checkVersion(current, expected, options = {}) {
|
|
35
|
+
const field = options.field ?? 'expectedVersion';
|
|
36
|
+
if (expected === undefined || expected === null || expected === '') {
|
|
37
|
+
if (options.required ?? true) {
|
|
38
|
+
throw new GuardrailError('version_required', `${field} is required: pass the version from your latest read so a change made in the meantime is not overwritten.`, { field });
|
|
39
|
+
}
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (typeof expected !== 'string' && typeof expected !== 'number') {
|
|
43
|
+
throw new GuardrailError('invalid_arguments', `${field} must be a string or a number, the version from your latest read.`, {
|
|
44
|
+
field,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if (!sameVersion(current, expected))
|
|
48
|
+
throw versionConflict(current ?? null, expected, options.resource);
|
|
49
|
+
}
|
|
50
|
+
async function writeIfUnchanged(store, options) {
|
|
51
|
+
const label = options.label ?? `${options.revision?.resourceType ?? 'resource'} ${JSON.stringify(options.id)}`;
|
|
52
|
+
const current = await store.get(options.id);
|
|
53
|
+
if (!current)
|
|
54
|
+
throw notFound(options.revision?.resourceType ?? 'resource', options.id);
|
|
55
|
+
checkVersion(current.version, options.expectedVersion, { required: options.required, resource: label });
|
|
56
|
+
const next = options.update ? await options.update(current.value) : null;
|
|
57
|
+
const result = await store.compareAndSet(options.id, current.version, next);
|
|
58
|
+
if (!result.ok) {
|
|
59
|
+
const latest = await store.get(options.id);
|
|
60
|
+
if (!latest)
|
|
61
|
+
throw notFound(options.revision?.resourceType ?? 'resource', options.id);
|
|
62
|
+
throw versionConflict(latest.version, options.expectedVersion ?? current.version, label);
|
|
63
|
+
}
|
|
64
|
+
let revisionId;
|
|
65
|
+
if (options.revision) {
|
|
66
|
+
const { log, ...target } = options.revision;
|
|
67
|
+
const saved = await log.record({
|
|
68
|
+
...target,
|
|
69
|
+
resourceId: options.id,
|
|
70
|
+
operation: next === null ? 'delete' : 'update',
|
|
71
|
+
snapshot: current.value,
|
|
72
|
+
version: current.version,
|
|
73
|
+
});
|
|
74
|
+
revisionId = saved.id;
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
value: next,
|
|
78
|
+
version: result.version,
|
|
79
|
+
previous: current.value,
|
|
80
|
+
previousVersion: current.version,
|
|
81
|
+
revisionId,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Optimistic-locked update: reads the current value, checks `expectedVersion`, and writes the update with
|
|
86
|
+
* an atomic compare-and-set. When another writer got in between, nothing is written and the call fails
|
|
87
|
+
* with `version_conflict` carrying the current version.
|
|
88
|
+
*/
|
|
89
|
+
export function updateIfUnchanged(store, options) {
|
|
90
|
+
return writeIfUnchanged(store, options);
|
|
91
|
+
}
|
|
92
|
+
/** Optimistic-locked delete, with the same checks as `updateIfUnchanged`. */
|
|
93
|
+
export function deleteIfUnchanged(store, options) {
|
|
94
|
+
return writeIfUnchanged(store, { ...options, update: undefined });
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* A reference `VersionedStore` kept in memory. Versions are integers from one counter shared by every
|
|
98
|
+
* id, so a deleted and recreated record never reuses an old version. Values are cloned in and out.
|
|
99
|
+
*/
|
|
100
|
+
export function createMemoryStore(initial = {}) {
|
|
101
|
+
const rows = new Map();
|
|
102
|
+
let counter = 0;
|
|
103
|
+
const store = {
|
|
104
|
+
async get(id) {
|
|
105
|
+
const row = rows.get(id);
|
|
106
|
+
return row ? { value: structuredClone(row.value), version: row.version } : undefined;
|
|
107
|
+
},
|
|
108
|
+
async compareAndSet(id, expected, next) {
|
|
109
|
+
const row = rows.get(id);
|
|
110
|
+
const matches = row ? expected !== null && sameVersion(row.version, expected) : expected === null;
|
|
111
|
+
if (!matches)
|
|
112
|
+
return { ok: false };
|
|
113
|
+
if (next === null) {
|
|
114
|
+
rows.delete(id);
|
|
115
|
+
return { ok: true, version: null };
|
|
116
|
+
}
|
|
117
|
+
const version = ++counter;
|
|
118
|
+
rows.set(id, { value: structuredClone(next), version });
|
|
119
|
+
return { ok: true, version };
|
|
120
|
+
},
|
|
121
|
+
seed(id, value) {
|
|
122
|
+
const version = ++counter;
|
|
123
|
+
rows.set(id, { value: structuredClone(value), version });
|
|
124
|
+
return version;
|
|
125
|
+
},
|
|
126
|
+
snapshot() {
|
|
127
|
+
const out = {};
|
|
128
|
+
for (const [id, row] of rows)
|
|
129
|
+
out[id] = { value: structuredClone(row.value), version: row.version };
|
|
130
|
+
return out;
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
for (const [id, value] of Object.entries(initial))
|
|
134
|
+
store.seed(id, value);
|
|
135
|
+
return store;
|
|
136
|
+
}
|