@ratifia/mcp 0.4.1 → 0.8.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.
Files changed (3) hide show
  1. package/README.md +63 -1
  2. package/dist/index.js +457 -125
  3. package/package.json +7 -6
package/README.md CHANGED
@@ -44,6 +44,12 @@ Point separate registrations at different environments by giving each its own `R
44
44
  Clone, then `npm install && npm run build` (rebuild after source changes). Use
45
45
  `npx tsx src/index.ts` instead of the built file to skip the build step while iterating.
46
46
 
47
+ `npm run validate` checks the built server against the MCP protocol using the
48
+ [Inspector CLI](https://modelcontextprotocol.io/docs/tools/inspector/cli) — the
49
+ handshake, the advertised tool surface and schemas, and a full create → await →
50
+ resolve cycle — driven against a stub API, so it needs no key and creates no
51
+ real decisions. CI runs it on every push.
52
+
47
53
  ## Configuration (env)
48
54
 
49
55
  | Var | Required | Default | Purpose |
@@ -52,7 +58,7 @@ Clone, then `npm install && npm run build` (rebuild after source changes). Use
52
58
  | `RATIFIA_API_URL` | | `https://api.ratifia.com` | Ratifia API base. |
53
59
  | `RATIFIA_APP_URL` | | `https://app.ratifia.com` | Dashboard base for decision links. |
54
60
  | `RATIFIA_APPROVER_EMAIL` | | — | Who the decision is assigned to / notified. |
55
- | `RATIFIA_POLICY` | | — | Named policy whose route decides **how** you're notified (e.g. to your phone). |
61
+ | `RATIFIA_POLICY` | | — | Named policy deciding **who** reviews and the quorum they need. It must exist in your org: an unknown name is a tool error, and the `gate` hook denies. |
56
62
 
57
63
  Routing (email / SMS / escalation) is decided **inside Ratifia** by your org's policy — this server is a thin request/verdict bridge.
58
64
 
@@ -65,6 +71,29 @@ Routing (email / SMS / escalation) is decided **inside Ratifia** by your org's p
65
71
  | `await_decision` | Block until the verdict lands (or a max wait elapses). |
66
72
  | `list_pending_decisions` | The agent's inbox — what's outstanding. |
67
73
  | `cancel_decision` | Withdraw a decision the agent no longer needs. |
74
+ | `attach_evidence` | Attach immutable material the decision is judged **on** (a Slack thread, an email). |
75
+
76
+ ### Waiting for a verdict
77
+
78
+ `await_decision` blocks for `max_wait_seconds` (default **90**, max **110**) and
79
+ returns the moment the human answers. If they haven't yet, it comes back
80
+ `pending` with `timed_out: true` — **that's normal, just call it again.**
81
+
82
+ The 110s ceiling is deliberate: agent harnesses background a tool call that runs
83
+ much past ~120s, so a longer block doesn't reach the agent sooner, it just lands
84
+ late. While waiting, the server polls Ratifia every 1s for the first 15s (most
85
+ decisions land there), then eases to 3s and 5s.
86
+
87
+ Transient failures — network blips, 429s, 5xx — are retried internally. One that
88
+ still surfaces comes back as data rather than an exception:
89
+
90
+ ```json
91
+ { "error": "unreachable", "message": "...", "retryable": true }
92
+ ```
93
+
94
+ On `retryable: true` the call is worth repeating; the decision is still open and
95
+ the human has already been notified, so **retry rather than requesting a second
96
+ decision.**
68
97
 
69
98
  ## Decision shapes
70
99
 
@@ -121,6 +150,39 @@ request_decision(
121
150
  `tool_args` is optional (some tools take none); it's ignored unless `tool_name`
122
151
  is set.
123
152
 
153
+ ### Evidence — what the decision was made *on*
154
+
155
+ A decision often rests on something outside the ask: the Slack thread where a
156
+ customer complained, the email that set the terms, the policy clause that
157
+ permits it. Attach that material and it becomes part of the decision's record.
158
+
159
+ ```
160
+ request_decision(
161
+ title: "Approve refund?",
162
+ question: "This exceeds the $5,000 auto-approve floor.",
163
+ evidence: [{
164
+ kind: "slack_thread",
165
+ title: "#support — refund thread",
166
+ source_url: "https://acme.slack.com/archives/C123/p1700000000",
167
+ body: "ana: customer is furious\nbo: refund is within policy"
168
+ }]
169
+ )
170
+ ```
171
+
172
+ Found something after you asked? `attach_evidence(decision_id, ...)` appends it.
173
+
174
+ Three properties worth knowing, because they shape how you should use it:
175
+
176
+ - **Send the text, not just a link.** The stored snapshot (and its sha256) is
177
+ what the audit trail keeps. A permalink can be edited or deleted after the
178
+ fact; the snapshot can't.
179
+ - **Sealed at the verdict.** Evidence can only be attached while the decision is
180
+ pending — so attach *before* you `await_decision`. Afterwards you get
181
+ `http_409` with `retryable: false`. That's the point: the record shows exactly
182
+ what the reviewer could see.
183
+ - **Re-attaching is free.** Identical content dedupes on its hash, so a retry
184
+ never produces a second panel for the reviewer.
185
+
124
186
  ## How it works
125
187
 
126
188
  1. The agent calls `request_decision` before a consequential/irreversible step (deploy, delete, spend, send externally), an ambiguous call it shouldn't guess, or to get a human to pick/refine something.
package/dist/index.js CHANGED
@@ -12,6 +12,8 @@
12
12
  * so the agent doesn't have to poll in a loop.
13
13
  * - list_pending_decisions : the agent's own inbox — what's outstanding.
14
14
  * - cancel_decision : withdraw a decision the agent no longer needs.
15
+ * - attach_evidence : append immutable material the decision is judged ON
16
+ * (a Slack thread, an email). Sealed at the verdict.
15
17
  *
16
18
  * Routing (HOW a human is reached — email/SMS/phone/escalation) is decided
17
19
  * INSIDE Ratifia by the org's policy/route, never by this client. The MCP is a
@@ -23,11 +25,12 @@
23
25
  * RATIFIA_API_KEY org-scoped worker API key (required)
24
26
  * RATIFIA_APP_URL dashboard base for the decision link (default https://app.ratifia.com)
25
27
  * RATIFIA_APPROVER_EMAIL who the decision is assigned to / notified
26
- * RATIFIA_POLICY optional: policy name whose route decides HOW you're notified
28
+ * RATIFIA_POLICY optional: policy name deciding who reviews (must exist in the org)
27
29
  * (e.g. a route to your phone)
28
30
  */
29
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
30
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
31
+ import { McpServer } from '@modelcontextprotocol/server';
32
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
33
+ import { randomUUID } from 'node:crypto';
31
34
  import { z } from 'zod';
32
35
  const API_URL = (process.env.RATIFIA_API_URL ?? 'https://api.ratifia.com').replace(/\/+$/, '');
33
36
  const API_KEY = process.env.RATIFIA_API_KEY;
@@ -38,21 +41,118 @@ if (!API_KEY) {
38
41
  console.error('RATIFIA_API_KEY is required');
39
42
  process.exit(1);
40
43
  }
44
+ /** Per-request ceiling. Node's fetch defaults run to ~300s, long enough to
45
+ * outlive a whole await_decision budget and strand the caller on a dead
46
+ * connection well past the deadline it was promised. */
47
+ const REQUEST_TIMEOUT_MS = 15_000;
48
+ /** An API failure that knows whether trying again is worth anything. */
49
+ class ApiError extends Error {
50
+ /** null = no response at all (network, DNS, or our own timeout). */
51
+ status;
52
+ /** The API's machine-readable `error` code, when it sent one (e.g. `unknown_policy`). */
53
+ code;
54
+ constructor(message, status, code = null) {
55
+ super(message);
56
+ this.status = status;
57
+ this.code = code;
58
+ }
59
+ get retryable() {
60
+ if (this.status === null)
61
+ return true;
62
+ if (this.status === 408 || this.status === 429)
63
+ return true;
64
+ return this.status >= 500;
65
+ }
66
+ }
67
+ function errorCode(body) {
68
+ try {
69
+ const code = JSON.parse(body).error;
70
+ return typeof code === 'string' ? code : null;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ /** FN-255: RATIFIA_POLICY names a policy the org doesn't have. A misconfiguration, not an outage. */
77
+ const isUnknownPolicy = (err) => err instanceof ApiError && err.code === 'unknown_policy';
78
+ const unknownPolicyMessage = () => `RATIFIA_POLICY "${POLICY}" does not exist in this Ratifia org. Create the policy in the Ratifia dashboard (Policies) or fix RATIFIA_POLICY in this MCP server's config. No decision was created: do not proceed with the action.`;
79
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
80
+ /** `idempotencyKey` makes a retried write safe to collapse server-side; mint it
81
+ * once per tool invocation so two independent asks never share one. */
41
82
  async function api(path, init) {
42
- const res = await fetch(`${API_URL}${path}`, {
43
- ...init,
44
- headers: {
45
- 'Content-Type': 'application/json',
46
- Authorization: `Bearer ${API_KEY}`,
47
- ...(init?.headers ?? {}),
48
- },
49
- });
50
- const text = await res.text();
51
- if (!res.ok)
52
- throw new Error(`Ratifia ${path} → ${res.status}: ${text.slice(0, 300)}`);
53
- return (text ? JSON.parse(text) : {});
83
+ const { idempotencyKey, ...rest } = init ?? {};
84
+ try {
85
+ const res = await fetch(`${API_URL}${path}`, {
86
+ ...rest,
87
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
88
+ headers: {
89
+ 'Content-Type': 'application/json',
90
+ Authorization: `Bearer ${API_KEY}`,
91
+ ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
92
+ ...(rest.headers ?? {}),
93
+ },
94
+ });
95
+ const text = await res.text();
96
+ if (!res.ok)
97
+ throw new ApiError(`Ratifia ${path} → ${res.status}: ${text.slice(0, 300)}`, res.status, errorCode(text));
98
+ return (text ? JSON.parse(text) : {});
99
+ }
100
+ catch (err) {
101
+ if (err instanceof ApiError)
102
+ throw err;
103
+ const msg = err instanceof Error ? err.message : String(err);
104
+ throw new ApiError(`Ratifia ${path} → unreachable: ${msg}`, null);
105
+ }
106
+ }
107
+ /** Retry transient failures with backoff. One blip used to abort an entire
108
+ * wait, which reads to the agent as "this step failed" — the expensive
109
+ * outcome, since it may then re-ask a human who was already notified. */
110
+ async function apiRetry(fn, attempts = 3) {
111
+ for (let i = 0;; i++) {
112
+ try {
113
+ return await fn();
114
+ }
115
+ catch (err) {
116
+ if (!(err instanceof ApiError) || !err.retryable || i >= attempts - 1)
117
+ throw err;
118
+ await sleep(500 * 2 ** i); // 500ms, then 1s
119
+ }
120
+ }
54
121
  }
55
122
  const getDecision = (id) => api(`/v1/worker/decisions/${encodeURIComponent(id)}`, { method: 'GET' });
123
+ /** Evidence lives on the dual-auth decisions route, not /worker — an API key
124
+ * authenticates there exactly as a dashboard session does. */
125
+ const attachEvidence = (decisionId, e) => api(`/v1/decisions/${encodeURIComponent(decisionId)}/evidence`, {
126
+ method: 'POST',
127
+ body: JSON.stringify({
128
+ kind: e.kind,
129
+ ...(e.title ? { title: e.title } : {}),
130
+ ...(e.source_system ? { sourceSystem: e.source_system } : {}),
131
+ ...(e.source_url ? { sourceUrl: e.source_url } : {}),
132
+ ...(e.body ? { body: e.body } : {}),
133
+ ...(e.captured_at ? { capturedAt: e.captured_at } : {}),
134
+ }),
135
+ });
136
+ /** Poll fast while the human is plausibly still at the keyboard, then back off.
137
+ * Most decisions land in the first few seconds, and a flat interval made every
138
+ * one of those wait out the full tick before the agent could move. */
139
+ const pollIntervalMs = (elapsedMs) => elapsedMs < 15_000 ? 1_000 : elapsedMs < 60_000 ? 3_000 : 5_000;
140
+ /** Poll until the decision leaves PENDING or the budget runs out (returns it
141
+ * still PENDING in that case). Transient API failures are retried, not fatal. */
142
+ async function waitForDecision(decisionId, budgetMs) {
143
+ const start = Date.now();
144
+ let d = await apiRetry(() => getDecision(decisionId));
145
+ for (;;) {
146
+ if (d.status !== 'PENDING')
147
+ return d;
148
+ const elapsed = Date.now() - start;
149
+ const wait = pollIntervalMs(elapsed);
150
+ if (elapsed + wait > budgetMs)
151
+ return d;
152
+ await sleep(wait);
153
+ d = await apiRetry(() => getDecision(decisionId));
154
+ }
155
+ }
56
156
  /** Agent-facing shape for a decision's current state. */
57
157
  const formatDecision = (d) => ({
58
158
  decision_id: d.id,
@@ -74,6 +174,33 @@ const formatDecision = (d) => ({
74
174
  const asToolResult = (payload) => ({
75
175
  content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
76
176
  });
177
+ /** Report an API failure as a structured result rather than an MCP exception,
178
+ * so the agent can retry on `retryable` instead of treating the step as lost
179
+ * and abandoning a decision a human may already be looking at. */
180
+ const asToolError = (err) => isUnknownPolicy(err)
181
+ ? asToolResult({ error: 'unknown_policy', policy: POLICY, message: unknownPolicyMessage(), retryable: false })
182
+ : asToolResult({
183
+ error: err instanceof ApiError && err.status ? `http_${err.status}` : 'unreachable',
184
+ message: err instanceof Error ? err.message : String(err),
185
+ retryable: err instanceof ApiError ? err.retryable : true,
186
+ });
187
+ /** FN-239: one piece of evidence, shared by request_decision and attach_evidence. */
188
+ const evidenceItemSchema = z.object({
189
+ kind: z
190
+ .enum(['slack_thread', 'email', 'document', 'link', 'note'])
191
+ .describe("What this material is. 'slack_thread' / 'email' for a captured conversation, 'document' for a doc or policy excerpt, 'link' for a bare reference with no text, 'note' for your own written rationale."),
192
+ title: z.string().optional().describe('Short reviewer-facing label, e.g. "#incidents — refund thread".'),
193
+ source_system: z.string().optional().describe('Where it came from, e.g. "slack", "email", "notion".'),
194
+ source_url: z.string().optional().describe('Deep link back to the original, for provenance.'),
195
+ body: z
196
+ .string()
197
+ .optional()
198
+ .describe('The actual text, captured. Send the content, not just a link — a link can be edited or deleted after the decision, and the stored snapshot is what the audit trail keeps. Required unless kind is "link".'),
199
+ captured_at: z
200
+ .string()
201
+ .optional()
202
+ .describe('ISO timestamp of when the material was originally written, if it predates now.'),
203
+ });
77
204
  function buildResponseSpec(responseType, options, allowMultiple) {
78
205
  if (!responseType || responseType === 'approval')
79
206
  return undefined;
@@ -97,7 +224,118 @@ function buildResponseSpec(responseType, options, allowMultiple) {
97
224
  max: allowMultiple ? specOptions.length : 1,
98
225
  };
99
226
  }
100
- const server = new McpServer({ name: 'ratifia', version: '0.4.1' }, {
227
+ // ─── Gate mode (Claude Code PreToolUse hook) ─────────────────────────────────
228
+ /** Read the hook payload from stdin (Claude Code pipes the PreToolUse JSON). */
229
+ function readStdin() {
230
+ return new Promise((resolve) => {
231
+ if (process.stdin.isTTY)
232
+ return resolve('');
233
+ let data = '';
234
+ process.stdin.setEncoding('utf8');
235
+ process.stdin.on('data', (c) => (data += c));
236
+ process.stdin.on('end', () => resolve(data));
237
+ setTimeout(() => resolve(data), 3000); // don't hang if the stream never ends
238
+ });
239
+ }
240
+ /** Emit Claude Code's PreToolUse permission decision (allow | deny) as JSON. */
241
+ function gateDecision(decision, reason) {
242
+ process.stdout.write(JSON.stringify({
243
+ hookSpecificOutput: {
244
+ hookEventName: 'PreToolUse',
245
+ permissionDecision: decision,
246
+ permissionDecisionReason: reason,
247
+ },
248
+ }));
249
+ }
250
+ /**
251
+ * `ratifia-mcp gate` — a Claude Code **PreToolUse hook**. Opens a Ratifia
252
+ * decision for the tool call (rendered as a `tool_call` context panel), blocks
253
+ * until a human answers, and returns allow/deny to the harness. The "list of
254
+ * tools" that trigger this is the hook's matcher in settings.json; narrow it
255
+ * further with RATIFIA_GATED_TOOLS. Fail-CLOSED (deny) on error/timeout unless
256
+ * RATIFIA_GATE_FAIL_OPEN=1 — a gate that fails open is no gate.
257
+ */
258
+ async function runGate() {
259
+ const failOpen = process.env.RATIFIA_GATE_FAIL_OPEN === '1';
260
+ let payload = {};
261
+ try {
262
+ payload = JSON.parse((await readStdin()) || '{}');
263
+ }
264
+ catch {
265
+ /* proceed with an empty payload */
266
+ }
267
+ const toolName = String(payload.tool_name ?? 'unknown_tool');
268
+ const toolInput = payload.tool_input ?? {};
269
+ // Optional allow-list: if set, only gate these tools; pass the rest through.
270
+ const gated = (process.env.RATIFIA_GATED_TOOLS ?? '')
271
+ .split(',')
272
+ .map((s) => s.trim())
273
+ .filter(Boolean);
274
+ if (gated.length > 0 && !gated.includes(toolName)) {
275
+ return gateDecision('allow', `not a gated tool: ${toolName}`);
276
+ }
277
+ // How long to block waiting for a human. Keep the settings.json hook `timeout`
278
+ // a little higher than this; on timeout we fail-closed (deny) by default.
279
+ const budgetMs = Math.max(10, Number(process.env.RATIFIA_GATE_TIMEOUT_SEC ?? 240)) * 1000;
280
+ let decisionId;
281
+ try {
282
+ // One id per hook invocation: retries below collapse into this decision,
283
+ // while a genuinely separate tool call mints its own and gates separately.
284
+ const externalRunId = `gate-${randomUUID()}`;
285
+ const res = await apiRetry(() => api('/v1/worker/decisions', {
286
+ method: 'POST',
287
+ idempotencyKey: externalRunId,
288
+ body: JSON.stringify({
289
+ engine: 'mcp',
290
+ externalRunId,
291
+ stepRef: `tool:${toolName}`.slice(0, 80),
292
+ workflowRef: 'ratifia-gate',
293
+ ...(APPROVER_EMAIL ? { assigneeEmail: APPROVER_EMAIL } : {}),
294
+ ...(POLICY ? { policy: POLICY } : {}),
295
+ required: true,
296
+ context: {
297
+ prompt: `An agent wants to run the tool "${toolName}". Approve?`,
298
+ blocks: [{ kind: 'tool_call', title: 'Tool call', tool: toolName, args: toolInput }],
299
+ },
300
+ }),
301
+ }));
302
+ // Policy gate resolved "no approval needed" → let it run.
303
+ if (res.approvalNeeded === false || !res.decisionId) {
304
+ return gateDecision('allow', 'no approval required by policy');
305
+ }
306
+ decisionId = res.decisionId;
307
+ }
308
+ catch (err) {
309
+ // A bad RATIFIA_POLICY denies even with fail-open: fail-open is for Ratifia
310
+ // being unreachable, and letting a misconfigured gate wave every tool call
311
+ // through is exactly the outage it exists to prevent.
312
+ if (isUnknownPolicy(err))
313
+ return gateDecision('deny', unknownPolicyMessage());
314
+ const msg = err instanceof Error ? err.message : String(err);
315
+ return gateDecision(failOpen ? 'allow' : 'deny', `ratifia gate unreachable: ${msg}`);
316
+ }
317
+ // Block until the human answers (or the budget elapses → fail-closed).
318
+ try {
319
+ const d = await waitForDecision(decisionId, budgetMs);
320
+ if (d.status === 'APPROVED')
321
+ return gateDecision('allow', d.note ?? 'approved by reviewer');
322
+ if (d.status === 'REJECTED')
323
+ return gateDecision('deny', d.note ?? 'rejected by reviewer');
324
+ if (d.status !== 'PENDING')
325
+ return gateDecision('deny', `decision ${d.status.toLowerCase()}`);
326
+ return gateDecision(failOpen ? 'allow' : 'deny', 'timed out waiting for approval');
327
+ }
328
+ catch (err) {
329
+ const msg = err instanceof Error ? err.message : String(err);
330
+ return gateDecision(failOpen ? 'allow' : 'deny', `ratifia gate error: ${msg}`);
331
+ }
332
+ }
333
+ // Dispatch: `ratifia-mcp gate` runs the hook; otherwise start the MCP server.
334
+ if (process.argv[2] === 'gate') {
335
+ await runGate();
336
+ process.exit(0);
337
+ }
338
+ const server = new McpServer({ name: 'ratifia', version: '0.7.0' }, {
101
339
  instructions: [
102
340
  'Ratifia lets you request a HUMAN decision or input mid-task (human-in-the-loop) and resume once it is answered.',
103
341
  '',
@@ -109,54 +347,63 @@ const server = new McpServer({ name: 'ratifia', version: '0.4.1' }, {
109
347
  '3. Wait for the verdict: prefer await_decision (it blocks until answered) over polling check_decision in a loop. Either way, "approved"/"rejected" comes with a note — the note is the human\'s actual answer/input, so read and follow it. If you asked for a choice/typed value (response_type select/text), the answer is in response_value (selected option ids — map them back via response_spec.options — or text), not just the note.',
110
348
  '4. Do NOT perform the gated action until it resolves approved. On rejected or expired, do not proceed — adapt or ask again.',
111
349
  'Refining content: to have a human review/edit a draft (e.g. an email you want to send), pass proposed_output.content. They can refine it (in the dashboard or by replying in the Slack thread); once approved, use output.content as the final text — it may differ from what you sent.',
350
+ 'Evidence: if your ask rests on material the human should see — a Slack conversation, an email, a policy excerpt — attach it (the `evidence` array on request_decision, or attach_evidence afterwards). Send the text, not just a link: the snapshot is what the audit trail keeps, and a link can change. Evidence can only be attached while the decision is pending; once it resolves the set is sealed, so attach before you await.',
112
351
  'Prefer one well-scoped decision with rich context over many small ones.',
113
352
  ].join('\n'),
114
353
  });
115
- server.tool('request_decision', 'Ask the human for a decision or input before proceeding (human-in-the-loop). Creates a Ratifia decision, notifies them (even away from keyboard), and returns a decision_id to await/poll. Use whenever you need approval, a choice, or input you should not assume. Set response_type to shape the answer: "approval" (yes/no, default), "select" (pick from options you provide), or "text" (a typed value) — for select/text the answer comes back in response_value. To have a human refine a draft (e.g. an email), pass proposed_output — the approved/edited text comes back in output.content. If this decision gates a specific tool/function call, pass tool_name (and tool_args) so the reviewer sees a structured "Tool call" panel of exactly what you would run.', {
116
- title: z.string().describe('Short title, e.g. "Deploy API to prod?"'),
117
- question: z.string().describe('Exactly what you need the human to decide or provide.'),
118
- context: z
119
- .string()
120
- .optional()
121
- .describe('Details to help them decide: options, tradeoffs, a diff, the command you would run.'),
122
- timeout_minutes: z
123
- .number()
124
- .int()
125
- .positive()
126
- .optional()
127
- .describe('Auto-expire (and reject) if unanswered after N minutes. Omit to wait indefinitely.'),
128
- response_type: z
129
- .enum(['approval', 'select', 'text'])
130
- .optional()
131
- .describe("What kind of answer you need. 'approval' (default) = yes/no gate. 'select' = the human picks from `options`. 'text' = the human types a value. For select/text, read the answer from `response_value` (not just `note`)."),
132
- options: z
133
- .array(z.object({
134
- label: z.string().describe('What the human sees for this choice.'),
135
- description: z.string().optional().describe('Optional one-line clarification of the choice.'),
136
- }))
137
- .min(2)
138
- .optional()
139
- .describe("The choices for a 'select' decision (at least 2). Required when response_type is 'select'."),
140
- allow_multiple: z
141
- .boolean()
142
- .optional()
143
- .describe("For 'select': allow picking more than one option (default single-choice)."),
144
- proposed_output: z
145
- .object({
146
- title: z.string().optional().describe('Short label for the artifact, e.g. "Email body".'),
147
- content: z.string().describe('The draft the human can edit before approving (e.g. the email text).'),
148
- })
149
- .optional()
150
- .describe('A draft artifact the human can refine before approving — e.g. an email you propose to send. They can edit it (in the dashboard or by replying in the Slack thread); on approval the final text comes back in `output.content`. Use this when you want a human to review/refine content, not just say yes/no.'),
151
- tool_name: z
152
- .string()
153
- .optional()
154
- .describe('The tool/function this decision gates, e.g. "issue_refund" or "delete_database". Shown to the reviewer as a structured "Tool call" panel — the concrete action you would take if approved.'),
155
- tool_args: z
156
- .record(z.unknown())
157
- .optional()
158
- .describe('The arguments you would call `tool_name` with, as an object, e.g. { "amount_cents": 600000, "currency": "USD" }. Displayed next to the tool name. Ignored unless `tool_name` is set.'),
159
- }, async ({ title, question, context, timeout_minutes, response_type, options, allow_multiple, proposed_output, tool_name, tool_args }) => {
354
+ server.registerTool('request_decision', {
355
+ description: 'Ask the human for a decision or input before proceeding (human-in-the-loop). Creates a Ratifia decision, notifies them (even away from keyboard), and returns a decision_id to await/poll. Use whenever you need approval, a choice, or input you should not assume. Set response_type to shape the answer: "approval" (yes/no, default), "select" (pick from options you provide), or "text" (a typed value) — for select/text the answer comes back in response_value. To have a human refine a draft (e.g. an email), pass proposed_output — the approved/edited text comes back in output.content. If this decision gates a specific tool/function call, pass tool_name (and tool_args) so the reviewer sees a structured "Tool call" panel of exactly what you would run.',
356
+ inputSchema: {
357
+ title: z.string().describe('Short title, e.g. "Deploy API to prod?"'),
358
+ question: z.string().describe('Exactly what you need the human to decide or provide.'),
359
+ context: z
360
+ .string()
361
+ .optional()
362
+ .describe('Details to help them decide: options, tradeoffs, a diff, the command you would run.'),
363
+ timeout_minutes: z
364
+ .number()
365
+ .int()
366
+ .positive()
367
+ .optional()
368
+ .describe('Auto-expire (and reject) if unanswered after N minutes. Omit to wait indefinitely.'),
369
+ response_type: z
370
+ .enum(['approval', 'select', 'text'])
371
+ .optional()
372
+ .describe("What kind of answer you need. 'approval' (default) = yes/no gate. 'select' = the human picks from `options`. 'text' = the human types a value. For select/text, read the answer from `response_value` (not just `note`)."),
373
+ options: z
374
+ .array(z.object({
375
+ label: z.string().describe('What the human sees for this choice.'),
376
+ description: z.string().optional().describe('Optional one-line clarification of the choice.'),
377
+ }))
378
+ .min(2)
379
+ .optional()
380
+ .describe("The choices for a 'select' decision (at least 2). Required when response_type is 'select'."),
381
+ allow_multiple: z
382
+ .boolean()
383
+ .optional()
384
+ .describe("For 'select': allow picking more than one option (default single-choice)."),
385
+ proposed_output: z
386
+ .object({
387
+ title: z.string().optional().describe('Short label for the artifact, e.g. "Email body".'),
388
+ content: z.string().describe('The draft the human can edit before approving (e.g. the email text).'),
389
+ })
390
+ .optional()
391
+ .describe('A draft artifact the human can refine before approving — e.g. an email you propose to send. They can edit it (in the dashboard or by replying in the Slack thread); on approval the final text comes back in `output.content`. Use this when you want a human to review/refine content, not just say yes/no.'),
392
+ tool_name: z
393
+ .string()
394
+ .optional()
395
+ .describe('The tool/function this decision gates, e.g. "issue_refund" or "delete_database". Shown to the reviewer as a structured "Tool call" panel — the concrete action you would take if approved.'),
396
+ tool_args: z
397
+ .record(z.string(), z.unknown())
398
+ .optional()
399
+ .describe('The arguments you would call `tool_name` with, as an object, e.g. { "amount_cents": 600000, "currency": "USD" }. Displayed next to the tool name. Ignored unless `tool_name` is set.'),
400
+ evidence: z
401
+ .array(evidenceItemSchema)
402
+ .max(20)
403
+ .optional()
404
+ .describe('Material this decision should be made ON — the Slack thread, the email, the policy excerpt you are relying on. Stored immutably against the decision and sealed when it resolves, so the record shows what the human could see. Attach what you already have; use attach_evidence for anything you find afterwards.'),
405
+ },
406
+ }, async ({ title, question, context, timeout_minutes, response_type, options, allow_multiple, proposed_output, tool_name, tool_args, evidence }) => {
160
407
  if (response_type === 'select' && (!options || options.length < 2)) {
161
408
  return asToolResult({
162
409
  error: 'invalid_request',
@@ -164,7 +411,11 @@ server.tool('request_decision', 'Ask the human for a decision or input before pr
164
411
  });
165
412
  }
166
413
  const responseSpec = buildResponseSpec(response_type, options, allow_multiple);
167
- const externalRunId = `mcp-${Date.now()}-${Math.round(Math.random() * 1e6)}`;
414
+ // Minted once per tool invocation and reused as the Idempotency-Key: a
415
+ // retry of *this* call collapses server-side, while a second, independent
416
+ // request_decision — even with identical arguments — gets its own id and is
417
+ // correctly treated as a new ask.
418
+ const externalRunId = `mcp-${randomUUID()}`;
168
419
  // Structured context blocks (FN-83): a tool_call panel when the agent names
169
420
  // the tool it's gating, plus any free-text context. Order = display order.
170
421
  const contextBlocks = [];
@@ -174,29 +425,36 @@ server.tool('request_decision', 'Ask the human for a decision or input before pr
174
425
  if (context) {
175
426
  contextBlocks.push({ kind: 'text', title, text: context });
176
427
  }
177
- const res = await api('/v1/worker/decisions', {
178
- method: 'POST',
179
- body: JSON.stringify({
180
- // The agent is its own "engine" — it polls (check/await) for the
181
- // verdict rather than parking on an engine resume event.
182
- engine: 'mcp',
183
- externalRunId,
184
- stepRef: title.slice(0, 80),
185
- workflowRef: 'ratifia-mcp',
186
- ...(APPROVER_EMAIL ? { assigneeEmail: APPROVER_EMAIL } : {}),
187
- ...(POLICY ? { policy: POLICY } : {}),
188
- required: true,
189
- ...(timeout_minutes ? { timeoutSec: timeout_minutes * 60 } : {}),
190
- ...(responseSpec ? { responseSpec } : {}),
191
- ...(proposed_output
192
- ? { proposedOutput: { title: proposed_output.title, format: 'text', content: proposed_output.content } }
193
- : {}),
194
- context: {
195
- prompt: question,
196
- ...(contextBlocks.length ? { blocks: contextBlocks } : {}),
197
- },
198
- }),
199
- });
428
+ let res;
429
+ try {
430
+ res = await apiRetry(() => api('/v1/worker/decisions', {
431
+ method: 'POST',
432
+ idempotencyKey: externalRunId,
433
+ body: JSON.stringify({
434
+ // The agent is its own "engine" — it polls (check/await) for the
435
+ // verdict rather than parking on an engine resume event.
436
+ engine: 'mcp',
437
+ externalRunId,
438
+ stepRef: title.slice(0, 80),
439
+ workflowRef: 'ratifia-mcp',
440
+ ...(APPROVER_EMAIL ? { assigneeEmail: APPROVER_EMAIL } : {}),
441
+ ...(POLICY ? { policy: POLICY } : {}),
442
+ required: true,
443
+ ...(timeout_minutes ? { timeoutSec: timeout_minutes * 60 } : {}),
444
+ ...(responseSpec ? { responseSpec } : {}),
445
+ ...(proposed_output
446
+ ? { proposedOutput: { title: proposed_output.title, format: 'text', content: proposed_output.content } }
447
+ : {}),
448
+ context: {
449
+ prompt: question,
450
+ ...(contextBlocks.length ? { blocks: contextBlocks } : {}),
451
+ },
452
+ }),
453
+ }));
454
+ }
455
+ catch (err) {
456
+ return asToolError(err);
457
+ }
200
458
  // The policy gate can resolve "no approval needed" — no decision is created.
201
459
  // Tell the agent it may just proceed, rather than returning a bogus id/url.
202
460
  if (res.approvalNeeded === false || !res.decisionId) {
@@ -207,61 +465,135 @@ server.tool('request_decision', 'Ask the human for a decision or input before pr
207
465
  note: 'Ratifia policy did not require a human decision — you may proceed.',
208
466
  });
209
467
  }
468
+ // FN-239: evidence is attached after the decision exists — it hangs off the
469
+ // decision id, so there is nothing to attach to before this point. A failure
470
+ // here is reported, never thrown: the decision is open and the human has
471
+ // already been notified, so aborting would strand it and tempt a duplicate
472
+ // ask. The agent can retry the failed items with attach_evidence.
473
+ const evidenceErrors = [];
474
+ let evidenceAttached = 0;
475
+ for (const item of evidence ?? []) {
476
+ try {
477
+ await apiRetry(() => attachEvidence(res.decisionId, item));
478
+ evidenceAttached++;
479
+ }
480
+ catch (err) {
481
+ evidenceErrors.push(`${item.kind}: ${err instanceof Error ? err.message : String(err)}`);
482
+ }
483
+ }
210
484
  return asToolResult({
211
485
  approval_required: true,
212
486
  decision_id: res.decisionId,
213
487
  status: 'pending',
214
488
  url: `${APP_URL}/decisions/${res.decisionId}`,
489
+ ...(evidence?.length ? { evidence_attached: evidenceAttached } : {}),
490
+ ...(evidenceErrors.length
491
+ ? {
492
+ evidence_errors: evidenceErrors,
493
+ evidence_note: 'The decision was created and the human notified; only these evidence items failed. Retry them with attach_evidence — do NOT request a second decision.',
494
+ }
495
+ : {}),
215
496
  });
216
497
  });
217
- server.tool('check_decision', "Check a Ratifia decision's status ONCE (non-blocking). Returns 'pending' until the human acts, then 'approved'/'rejected' plus their note (their input/answer). Prefer await_decision if you just want to wait for the verdict.", {
218
- decision_id: z.string().describe('The decision_id returned by request_decision.'),
219
- }, async ({ decision_id }) => asToolResult(formatDecision(await getDecision(decision_id))));
220
- server.tool('await_decision', "Block until a Ratifia decision resolves (or max_wait_seconds elapses), so you don't have to poll in a loop. Returns as soon as the human acts ('approved'/'rejected' + their note), or status 'pending' with timed_out=true if still unanswered after the wait — just call await_decision again to keep waiting. Use this after request_decision to wait for the verdict.", {
221
- decision_id: z.string().describe('The decision_id returned by request_decision.'),
222
- max_wait_seconds: z
223
- .number()
224
- .int()
225
- .positive()
226
- .max(240)
227
- .optional()
228
- .describe('How long to block before returning (default 60, max 240). If still pending, call again to keep waiting.'),
498
+ server.registerTool('attach_evidence', {
499
+ description: "Attach material a decision should be judged ON — a Slack conversation, an email, a policy excerpt — to a decision you already opened. Use it when you find something relevant after asking, or when the human asks 'what did the customer actually say?'. Evidence is immutable and append-only, and can only be attached while the decision is still pending: once it resolves the set is sealed, so the record shows exactly what the reviewer could see. Send the text itself, not just a link.",
500
+ inputSchema: {
501
+ decision_id: z.string().describe('The decision_id returned by request_decision.'),
502
+ ...evidenceItemSchema.shape,
503
+ },
504
+ }, async ({ decision_id, ...item }) => {
505
+ try {
506
+ const res = await apiRetry(() => attachEvidence(decision_id, item));
507
+ return asToolResult({
508
+ decision_id,
509
+ evidence_id: res.evidence?.id ?? null,
510
+ // The API dedupes on content hash, so re-sending the same material is a
511
+ // no-op rather than a second panel for the reviewer.
512
+ deduplicated: Boolean(res.deduplicated),
513
+ status: 'attached',
514
+ });
515
+ }
516
+ catch (err) {
517
+ return asToolError(err);
518
+ }
519
+ });
520
+ server.registerTool('check_decision', {
521
+ description: "Check a Ratifia decision's status ONCE (non-blocking). Returns 'pending' until the human acts, then 'approved'/'rejected' plus their note (their input/answer). Prefer await_decision if you just want to wait for the verdict.",
522
+ inputSchema: {
523
+ decision_id: z.string().describe('The decision_id returned by request_decision.'),
524
+ },
525
+ }, async ({ decision_id }) => {
526
+ try {
527
+ return asToolResult(formatDecision(await apiRetry(() => getDecision(decision_id))));
528
+ }
529
+ catch (err) {
530
+ return asToolError(err);
531
+ }
532
+ });
533
+ server.registerTool('await_decision', {
534
+ description: "Block until a Ratifia decision resolves (or max_wait_seconds elapses), so you don't have to poll in a loop. Returns as soon as the human acts ('approved'/'rejected' + their note), or status 'pending' with timed_out=true if still unanswered after the wait — just call await_decision again to keep waiting (that is normal, not a failure). Transient API errors are retried internally; if one still surfaces it comes back as error + retryable rather than throwing, so call again rather than re-requesting the decision. Use this after request_decision to wait for the verdict.",
535
+ inputSchema: {
536
+ decision_id: z.string().describe('The decision_id returned by request_decision.'),
537
+ max_wait_seconds: z
538
+ .number()
539
+ .int()
540
+ .positive()
541
+ .max(110)
542
+ .optional()
543
+ .describe('How long to block before returning (default 90, max 110). Kept under the ~120s at which a harness backgrounds a tool call — a longer wait does not reach you sooner, it just lands late. If still pending, call again to keep waiting.'),
544
+ },
229
545
  }, async ({ decision_id, max_wait_seconds }) => {
230
- const budgetMs = (max_wait_seconds ?? 60) * 1000;
231
- const pollMs = 4000;
232
- const start = Date.now();
233
- let d = await getDecision(decision_id);
234
- while (d.status === 'PENDING' && Date.now() - start + pollMs <= budgetMs) {
235
- await new Promise((r) => setTimeout(r, pollMs));
236
- d = await getDecision(decision_id);
546
+ try {
547
+ const d = await waitForDecision(decision_id, (max_wait_seconds ?? 90) * 1000);
548
+ return asToolResult({
549
+ ...formatDecision(d),
550
+ ...(d.status === 'PENDING' ? { timed_out: true } : {}),
551
+ });
552
+ }
553
+ catch (err) {
554
+ return asToolError(err);
237
555
  }
238
- return asToolResult({
239
- ...formatDecision(d),
240
- ...(d.status === 'PENDING' ? { timed_out: true } : {}),
241
- });
242
556
  });
243
- server.tool('list_pending_decisions', 'List the decisions you have outstanding with Ratifia (default: still-pending), newest first. Use to reconcile after a restart, or to see what you are waiting on before deciding whether to keep waiting or cancel.', {
244
- status: z
245
- .enum(['PENDING', 'APPROVED', 'REJECTED', 'EXPIRED', 'CANCELLED'])
246
- .optional()
247
- .describe('Filter by status. Omit for PENDING (your outstanding asks).'),
248
- limit: z.number().int().positive().max(200).optional().describe('Max to return (default 50).'),
557
+ server.registerTool('list_pending_decisions', {
558
+ description: 'List the decisions you have outstanding with Ratifia (default: still-pending), newest first. Use to reconcile after a restart, or to see what you are waiting on before deciding whether to keep waiting or cancel.',
559
+ inputSchema: {
560
+ status: z
561
+ .enum(['PENDING', 'APPROVED', 'REJECTED', 'EXPIRED', 'CANCELLED'])
562
+ .optional()
563
+ .describe('Filter by status. Omit for PENDING (your outstanding asks).'),
564
+ limit: z.number().int().positive().max(200).optional().describe('Max to return (default 50).'),
565
+ },
249
566
  }, async ({ status, limit }) => {
250
567
  const qs = new URLSearchParams({ status: status ?? 'PENDING' });
251
568
  if (limit)
252
569
  qs.set('limit', String(limit));
253
- const res = await api(`/v1/worker/decisions?${qs.toString()}`, {
254
- method: 'GET',
255
- });
256
- return asToolResult({ count: res.decisions.length, decisions: res.decisions });
570
+ try {
571
+ const res = await apiRetry(() => api(`/v1/worker/decisions?${qs.toString()}`, { method: 'GET' }));
572
+ return asToolResult({ count: res.decisions.length, decisions: res.decisions });
573
+ }
574
+ catch (err) {
575
+ return asToolError(err);
576
+ }
577
+ });
578
+ server.registerTool('cancel_decision', {
579
+ description: 'Withdraw a decision you requested but no longer need (the task was aborted or the question became moot). Resolves it and stops notifying the human. Only PENDING decisions cancel; an already-answered one is returned unchanged (cancelled=false).',
580
+ inputSchema: {
581
+ decision_id: z.string().describe('The decision_id returned by request_decision.'),
582
+ note: z.string().optional().describe('Optional reason, recorded on the decision.'),
583
+ },
584
+ }, async ({ decision_id, note }) => {
585
+ // Cancel is naturally idempotent (only PENDING transitions), so a retry is
586
+ // safe without a key: a second one returns the already-resolved decision.
587
+ try {
588
+ return asToolResult(await apiRetry(() => api(`/v1/worker/decisions/${encodeURIComponent(decision_id)}/cancel`, {
589
+ method: 'POST',
590
+ body: JSON.stringify(note ? { note } : {}),
591
+ })));
592
+ }
593
+ catch (err) {
594
+ return asToolError(err);
595
+ }
257
596
  });
258
- server.tool('cancel_decision', 'Withdraw a decision you requested but no longer need (the task was aborted or the question became moot). Resolves it and stops notifying the human. Only PENDING decisions cancel; an already-answered one is returned unchanged (cancelled=false).', {
259
- decision_id: z.string().describe('The decision_id returned by request_decision.'),
260
- note: z.string().optional().describe('Optional reason, recorded on the decision.'),
261
- }, async ({ decision_id, note }) => asToolResult(await api(`/v1/worker/decisions/${encodeURIComponent(decision_id)}/cancel`, {
262
- method: 'POST',
263
- body: JSON.stringify(note ? { note } : {}),
264
- })));
265
597
  const transport = new StdioServerTransport();
266
598
  await server.connect(transport);
267
599
  console.error(`ratifia-mcp connected → ${API_URL}`);
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@ratifia/mcp",
3
- "version": "0.4.1",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
- "description": "Ratifia MCP server — let an AI agent request a human decision/approval (HITL) mid-task and resume once it's answered. The agent becomes a Ratifia 'engine'.",
5
+ "description": "Ratifia MCP server \u2014 let an AI agent request a human decision/approval (HITL) mid-task and resume once it's answered. The agent becomes a Ratifia 'engine'.",
6
6
  "keywords": [
7
7
  "mcp",
8
8
  "model-context-protocol",
@@ -29,7 +29,7 @@
29
29
  "dist"
30
30
  ],
31
31
  "engines": {
32
- "node": ">=18"
32
+ "node": ">=22"
33
33
  },
34
34
  "publishConfig": {
35
35
  "access": "public"
@@ -38,11 +38,12 @@
38
38
  "build": "tsc",
39
39
  "dev": "tsx src/index.ts",
40
40
  "start": "node dist/index.js",
41
- "prepare": "tsc"
41
+ "prepare": "tsc",
42
+ "validate": "node test/validate.mjs"
42
43
  },
43
44
  "dependencies": {
44
- "@modelcontextprotocol/sdk": "^1.12.0",
45
- "zod": "^3.23.0"
45
+ "@modelcontextprotocol/server": "^2.0.0",
46
+ "zod": "^4.4.3"
46
47
  },
47
48
  "devDependencies": {
48
49
  "@types/node": "^20.0.0",