@ratifia/mcp 0.12.0 → 0.13.1

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.
@@ -0,0 +1,22 @@
1
+ import { McpServer, type McpHttpHandler } from '@modelcontextprotocol/server';
2
+ import { type RatifiaConfig } from './client.js';
3
+ export { ApiError, createClient, type RatifiaConfig } from './client.js';
4
+ export interface ServerOptions {
5
+ version: string;
6
+ /** Hosted connector (FN-366): shorter waits, since remote clients time a tool call out sooner. */
7
+ hosted?: boolean;
8
+ }
9
+ /**
10
+ * The Ratifia MCP server: the same tools whether it runs over stdio
11
+ * (`npx @ratifia/mcp`) or hosted at the API's /mcp endpoint (FN-366). Build one
12
+ * per caller; it holds that caller's token.
13
+ */
14
+ export declare function createRatifiaServer(cfg: RatifiaConfig, opts: ServerOptions): McpServer;
15
+ /**
16
+ * FN-366: the hosted endpoint. A stateless Streamable HTTP handler that builds a
17
+ * fresh server per request from the caller's config — the host authenticates
18
+ * the request, then passes the config (token, default approver) in
19
+ * `authInfo.extra.ratifia`. A request without one is refused: the handler
20
+ * never reads credentials itself.
21
+ */
22
+ export declare function createRatifiaMcpHandler(opts: Omit<ServerOptions, 'hosted'>): McpHttpHandler;
package/dist/server.js ADDED
@@ -0,0 +1,400 @@
1
+ import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { z } from 'zod';
4
+ import { apiRetry, ApiError, createClient, isUnknownPolicy, label, trimUrl, unknownPolicyMessage, who, } from './client.js';
5
+ export { ApiError, createClient } from './client.js';
6
+ /** Agent-facing shape for a decision's current state. */
7
+ const formatDecision = (d) => ({
8
+ decision_id: d.id,
9
+ status: d.status, // PENDING | APPROVED | REJECTED | EXPIRED
10
+ verdict: d.decision, // approve | reject | null
11
+ note: d.note, // the human's free-text input/answer — read and follow it
12
+ // FN-181: for a select/text decision the real answer is here, not in `note`.
13
+ // `response_value.selected` holds the chosen option id(s); map them back to
14
+ // labels via `response_spec.options`. `response_value.text` holds a typed value.
15
+ ...(d.responseSpec ? { response_spec: d.responseSpec } : {}),
16
+ ...(d.responseValue ? { response_value: d.responseValue } : {}),
17
+ // FN-185: if you sent a proposed_output (e.g. a draft email), the human may
18
+ // have edited it in the Ratifia app (Slack can only approve or reject it).
19
+ // `output.content` is the effective final text to act on — use it over your
20
+ // original draft.
21
+ ...(d.output ? { output: d.output, refined: Boolean(d.refinedOutput) } : {}),
22
+ decided_by: d.decidedBy,
23
+ decided_at: d.decidedAt,
24
+ // FN-316: which version of the policy governed this decision, so an agent can
25
+ // cite it ("approved under refunds v3"). Stays put when the policy is edited.
26
+ policy_version: d.policyVersion ?? null,
27
+ policy_version_id: d.policyVersionId ?? null,
28
+ });
29
+ const asToolResult = (payload) => ({
30
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
31
+ });
32
+ /** Report an API failure as a structured result rather than an MCP exception,
33
+ * so the agent can retry on `retryable` instead of treating the step as lost
34
+ * and abandoning a decision a human may already be looking at. */
35
+ const asToolError = (err, policy) => isUnknownPolicy(err)
36
+ ? asToolResult({ error: 'unknown_policy', policy, message: unknownPolicyMessage(policy), retryable: false })
37
+ : asToolResult({
38
+ error: err instanceof ApiError && err.status ? `http_${err.status}` : 'unreachable',
39
+ message: err instanceof Error ? err.message : String(err),
40
+ retryable: err instanceof ApiError ? err.retryable : true,
41
+ });
42
+ /** FN-239: one piece of evidence, shared by request_decision and attach_evidence. */
43
+ const evidenceItemSchema = z.object({
44
+ kind: z
45
+ .enum(['slack_thread', 'email', 'document', 'link', 'note'])
46
+ .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."),
47
+ title: z.string().optional().describe('Short reviewer-facing label, e.g. "#incidents — refund thread".'),
48
+ source_system: z.string().optional().describe('Where it came from, e.g. "slack", "email", "notion".'),
49
+ source_url: z.string().optional().describe('Deep link back to the original, for provenance.'),
50
+ body: z
51
+ .string()
52
+ .optional()
53
+ .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".'),
54
+ captured_at: z
55
+ .string()
56
+ .optional()
57
+ .describe('ISO timestamp of when the material was originally written, if it predates now.'),
58
+ });
59
+ function buildResponseSpec(responseType, options, allowMultiple) {
60
+ if (!responseType || responseType === 'approval')
61
+ return undefined;
62
+ if (responseType === 'text')
63
+ return { type: 'text' };
64
+ // select
65
+ const seen = new Set();
66
+ const specOptions = (options ?? []).map((o, i) => {
67
+ // Cap at 40: option ids ride in a Discord button custom_id (100-char limit)
68
+ // alongside the 28-char decision id, so keep them short.
69
+ let id = (o.label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || `opt-${i}`).slice(0, 40);
70
+ while (seen.has(id))
71
+ id = `${id}-${i}`;
72
+ seen.add(id);
73
+ return { id, label: o.label, ...(o.description ? { description: o.description } : {}) };
74
+ });
75
+ return {
76
+ type: 'select',
77
+ options: specOptions,
78
+ min: 1,
79
+ max: allowMultiple ? specOptions.length : 1,
80
+ };
81
+ }
82
+ /**
83
+ * The Ratifia MCP server: the same tools whether it runs over stdio
84
+ * (`npx @ratifia/mcp`) or hosted at the API's /mcp endpoint (FN-366). Build one
85
+ * per caller; it holds that caller's token.
86
+ */
87
+ export function createRatifiaServer(cfg, opts) {
88
+ const { api, getDecision, attachEvidence, waitForDecision } = createClient(cfg);
89
+ const APP_URL = trimUrl(cfg.appUrl);
90
+ // A local harness backgrounds a tool call at ~120s; hosted clients give up
91
+ // sooner (ChatGPT at ~60s), so a hosted await returns well inside that.
92
+ const maxWait = opts.hosted ? 55 : 110;
93
+ const defaultWait = opts.hosted ? 45 : 90;
94
+ const server = new McpServer({ name: 'ratifia', version: opts.version }, {
95
+ instructions: [
96
+ 'Ratifia lets you request a HUMAN decision or input mid-task (human-in-the-loop) and resume once it is answered.',
97
+ '',
98
+ 'When to use request_decision: before a consequential or irreversible action (prod deploy, delete/drop, data migration, spending, sending something externally, credential rotation), or when a requirement is ambiguous and guessing wrong would be costly. Skip it for trivial, reversible, or clearly-authorized steps — that is just friction.',
99
+ '',
100
+ 'Workflow:',
101
+ '1. Call request_decision with a short title, a precise question, and enough context to decide (the command/diff/options + tradeoffs). Set timeout_minutes if it is time-sensitive.',
102
+ 'Filing: set `workflow` to the project or ongoing effort the decision belongs to (e.g. the repo name, "billing-refunds") so a human can see related decisions together in the dashboard, and reuse the exact same string every time. Put what is specific to this decision (the release, record, environment) in `step`, e.g. "deploy-v2.3-prod". Without them every decision lands in one "ratifia-mcp" bucket.',
103
+ '2. It returns a decision_id (+ url). The human is notified and may be away from their keyboard, so a verdict can take a while. (If the org policy auto-resolved that no approval was needed, it returns approval_required=false — just proceed.)',
104
+ '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.',
105
+ '4. Do NOT perform the gated action until it resolves approved. On rejected or expired, do not proceed — adapt or ask again.',
106
+ 'Refining content: to have a human review/edit a draft (e.g. an email you want to send), pass proposed_output.content. They can edit it in the Ratifia app (Slack can only approve or reject it); once approved, use output.content as the final text — it may differ from what you sent.',
107
+ '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.',
108
+ 'Prefer one well-scoped decision with rich context over many small ones.',
109
+ ].join('\n'),
110
+ });
111
+ server.registerTool('request_decision', {
112
+ 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.',
113
+ inputSchema: {
114
+ title: z.string().describe('Short title, e.g. "Deploy API to prod?"'),
115
+ question: z.string().describe('Exactly what you need the human to decide or provide.'),
116
+ context: z
117
+ .string()
118
+ .optional()
119
+ .describe('Details to help them decide: options, tradeoffs, a diff, the command you would run.'),
120
+ timeout_minutes: z
121
+ .number()
122
+ .int()
123
+ .positive()
124
+ .optional()
125
+ .describe("Auto-expire (and reject) if unanswered after N minutes. Omit to wait indefinitely. Ignored when a policy decides who answers: the policy's expiry applies."),
126
+ response_type: z
127
+ .enum(['approval', 'select', 'text'])
128
+ .optional()
129
+ .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`)."),
130
+ options: z
131
+ .array(z.object({
132
+ label: z.string().describe('What the human sees for this choice.'),
133
+ description: z.string().optional().describe('Optional one-line clarification of the choice.'),
134
+ }))
135
+ .min(2)
136
+ .optional()
137
+ .describe("The choices for a 'select' decision (at least 2). Required when response_type is 'select'."),
138
+ allow_multiple: z
139
+ .boolean()
140
+ .optional()
141
+ .describe("For 'select': allow picking more than one option (default single-choice)."),
142
+ proposed_output: z
143
+ .object({
144
+ title: z.string().optional().describe('Short label for the artifact, e.g. "Email body".'),
145
+ content: z.string().describe('The draft the human can edit before approving (e.g. the email text).'),
146
+ })
147
+ .optional()
148
+ .describe('A draft artifact the human can refine before approving — e.g. an email you propose to send. They can edit it in the Ratifia app (Slack can only approve or reject it); 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.'),
149
+ tool_name: z
150
+ .string()
151
+ .optional()
152
+ .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.'),
153
+ tool_args: z
154
+ .record(z.string(), z.unknown())
155
+ .optional()
156
+ .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.'),
157
+ approvers: z
158
+ .array(z.string().email())
159
+ .min(1)
160
+ .max(20)
161
+ .optional()
162
+ .describe('Who may answer: one or more email addresses of people in your Ratifia org. Omit to use the default (the signed-in user on a hosted connector, else RATIFIA_APPROVER_EMAIL). Do not combine with `policy`.'),
163
+ policy: z
164
+ .string()
165
+ .max(100)
166
+ .optional()
167
+ .describe('Instead of approvers: the key of a Ratifia policy that decides who answers, the quorum and the expiry. It must exist in the org. Do not combine with `approvers`.'),
168
+ workflow: z
169
+ .string()
170
+ .max(100)
171
+ .optional()
172
+ .describe('The project or ongoing effort this decision belongs to, e.g. the repo name or "billing-refunds" — the dashboard groups and filters by it, so reuse the exact same string for related decisions and keep ids/versions out of it. Omit to use the server default ("ratifia-mcp" unless configured).'),
173
+ step: z
174
+ .string()
175
+ .max(80)
176
+ .optional()
177
+ .describe('What is specific to this decision within the workflow, e.g. "deploy-v2.3-prod" or "refund-INV-1042". Omit to use the title.'),
178
+ evidence: z
179
+ .array(evidenceItemSchema)
180
+ .max(20)
181
+ .optional()
182
+ .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.'),
183
+ },
184
+ }, async ({ title, question, context, timeout_minutes, response_type, options, allow_multiple, proposed_output, tool_name, tool_args, approvers, policy, workflow, step, evidence }) => {
185
+ if (approvers?.length && policy) {
186
+ return asToolResult({
187
+ error: 'invalid_request',
188
+ message: 'Pass approvers or policy, not both: a policy decides who answers.',
189
+ });
190
+ }
191
+ // A call's own choice wins; otherwise the server's defaults.
192
+ const effectivePolicy = approvers?.length ? undefined : (policy ?? cfg.policy);
193
+ const whoBody = who(effectivePolicy, approvers ?? cfg.approvers);
194
+ if (response_type === 'select' && (!options || options.length < 2)) {
195
+ return asToolResult({
196
+ error: 'invalid_request',
197
+ message: "response_type 'select' requires at least 2 options.",
198
+ });
199
+ }
200
+ const responseSpec = buildResponseSpec(response_type, options, allow_multiple);
201
+ // Minted once per tool invocation and reused as the Idempotency-Key: a
202
+ // retry of *this* call collapses server-side, while a second, independent
203
+ // request_decision — even with identical arguments — gets its own id and is
204
+ // correctly treated as a new ask.
205
+ const externalRunId = `mcp-${randomUUID()}`;
206
+ // Structured context blocks (FN-83): a tool_call panel when the agent names
207
+ // the tool it's gating, plus any free-text context. Order = display order.
208
+ const contextBlocks = [];
209
+ if (tool_name) {
210
+ contextBlocks.push({ kind: 'tool_call', title: 'Tool call', tool: tool_name, args: tool_args ?? {} });
211
+ }
212
+ if (context) {
213
+ contextBlocks.push({ kind: 'text', title, text: context });
214
+ }
215
+ let res;
216
+ try {
217
+ res = await apiRetry(() => api('/v1/worker/decisions', {
218
+ method: 'POST',
219
+ idempotencyKey: externalRunId,
220
+ body: JSON.stringify({
221
+ // The agent is its own "engine" — it polls (check/await) for the
222
+ // verdict rather than parking on an engine resume event.
223
+ engine: 'mcp',
224
+ externalRunId,
225
+ stepRef: label(step, title, 80),
226
+ workflowRef: label(workflow, label(cfg.workflow, 'ratifia-mcp', 100), 100),
227
+ ...whoBody,
228
+ required: true,
229
+ // With a policy, the policy sets the expiry (a timeoutSec would be refused).
230
+ ...(timeout_minutes && !effectivePolicy ? { timeoutSec: timeout_minutes * 60 } : {}),
231
+ ...(responseSpec ? { responseSpec } : {}),
232
+ ...(proposed_output
233
+ ? { proposedOutput: { title: proposed_output.title, format: 'text', content: proposed_output.content } }
234
+ : {}),
235
+ context: {
236
+ prompt: question,
237
+ ...(contextBlocks.length ? { blocks: contextBlocks } : {}),
238
+ },
239
+ }),
240
+ }));
241
+ }
242
+ catch (err) {
243
+ return asToolError(err, effectivePolicy);
244
+ }
245
+ // The policy gate can resolve "no approval needed" — no decision is created.
246
+ // Tell the agent it may just proceed, rather than returning a bogus id/url.
247
+ if (res.approvalNeeded === false || !res.decisionId) {
248
+ return asToolResult({
249
+ approval_required: false,
250
+ status: 'not_required',
251
+ reason: res.reason ?? 'policy_gate_not_required',
252
+ note: 'Ratifia policy did not require a human decision — you may proceed.',
253
+ });
254
+ }
255
+ // FN-239: evidence is attached after the decision exists — it hangs off the
256
+ // decision id, so there is nothing to attach to before this point. A failure
257
+ // here is reported, never thrown: the decision is open and the human has
258
+ // already been notified, so aborting would strand it and tempt a duplicate
259
+ // ask. The agent can retry the failed items with attach_evidence.
260
+ const evidenceErrors = [];
261
+ let evidenceAttached = 0;
262
+ for (const item of evidence ?? []) {
263
+ try {
264
+ await apiRetry(() => attachEvidence(res.decisionId, item));
265
+ evidenceAttached++;
266
+ }
267
+ catch (err) {
268
+ evidenceErrors.push(`${item.kind}: ${err instanceof Error ? err.message : String(err)}`);
269
+ }
270
+ }
271
+ return asToolResult({
272
+ approval_required: true,
273
+ decision_id: res.decisionId,
274
+ status: 'pending',
275
+ url: `${APP_URL}/decisions/${res.decisionId}`,
276
+ ...(evidence?.length ? { evidence_attached: evidenceAttached } : {}),
277
+ ...(evidenceErrors.length
278
+ ? {
279
+ evidence_errors: evidenceErrors,
280
+ 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.',
281
+ }
282
+ : {}),
283
+ });
284
+ });
285
+ server.registerTool('attach_evidence', {
286
+ 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.",
287
+ inputSchema: {
288
+ decision_id: z.string().describe('The decision_id returned by request_decision.'),
289
+ ...evidenceItemSchema.shape,
290
+ },
291
+ }, async ({ decision_id, ...item }) => {
292
+ try {
293
+ const res = await apiRetry(() => attachEvidence(decision_id, item));
294
+ return asToolResult({
295
+ decision_id,
296
+ evidence_id: res.evidence?.id ?? null,
297
+ // The API dedupes on content hash, so re-sending the same material is a
298
+ // no-op rather than a second panel for the reviewer.
299
+ deduplicated: Boolean(res.deduplicated),
300
+ status: 'attached',
301
+ });
302
+ }
303
+ catch (err) {
304
+ return asToolError(err);
305
+ }
306
+ });
307
+ server.registerTool('check_decision', {
308
+ 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.",
309
+ inputSchema: {
310
+ decision_id: z.string().describe('The decision_id returned by request_decision.'),
311
+ },
312
+ }, async ({ decision_id }) => {
313
+ try {
314
+ return asToolResult(formatDecision(await apiRetry(() => getDecision(decision_id))));
315
+ }
316
+ catch (err) {
317
+ return asToolError(err);
318
+ }
319
+ });
320
+ server.registerTool('await_decision', {
321
+ 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.",
322
+ inputSchema: {
323
+ decision_id: z.string().describe('The decision_id returned by request_decision.'),
324
+ max_wait_seconds: z
325
+ .number()
326
+ .int()
327
+ .positive()
328
+ .max(maxWait)
329
+ .optional()
330
+ .describe(`How long to block before returning (default ${defaultWait}, max ${maxWait}). Kept under the point at which your client gives up on a tool call — a longer wait does not reach you sooner, it just lands late. If still pending, call again to keep waiting.`),
331
+ },
332
+ }, async ({ decision_id, max_wait_seconds }) => {
333
+ try {
334
+ const d = await waitForDecision(decision_id, (max_wait_seconds ?? defaultWait) * 1000);
335
+ return asToolResult({
336
+ ...formatDecision(d),
337
+ ...(d.status === 'PENDING' ? { timed_out: true } : {}),
338
+ });
339
+ }
340
+ catch (err) {
341
+ return asToolError(err);
342
+ }
343
+ });
344
+ server.registerTool('list_pending_decisions', {
345
+ 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.',
346
+ inputSchema: {
347
+ status: z
348
+ .enum(['PENDING', 'APPROVED', 'REJECTED', 'EXPIRED', 'CANCELLED'])
349
+ .optional()
350
+ .describe('Filter by status. Omit for PENDING (your outstanding asks).'),
351
+ limit: z.number().int().positive().max(200).optional().describe('Max to return (default 50).'),
352
+ },
353
+ }, async ({ status, limit }) => {
354
+ const qs = new URLSearchParams({ status: status ?? 'PENDING' });
355
+ if (limit)
356
+ qs.set('limit', String(limit));
357
+ try {
358
+ const res = await apiRetry(() => api(`/v1/worker/decisions?${qs.toString()}`, { method: 'GET' }));
359
+ return asToolResult({ count: res.decisions.length, decisions: res.decisions });
360
+ }
361
+ catch (err) {
362
+ return asToolError(err);
363
+ }
364
+ });
365
+ server.registerTool('cancel_decision', {
366
+ 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).',
367
+ inputSchema: {
368
+ decision_id: z.string().describe('The decision_id returned by request_decision.'),
369
+ note: z.string().optional().describe('Optional reason, recorded on the decision.'),
370
+ },
371
+ }, async ({ decision_id, note }) => {
372
+ // Cancel is naturally idempotent (only PENDING transitions), so a retry is
373
+ // safe without a key: a second one returns the already-resolved decision.
374
+ try {
375
+ return asToolResult(await apiRetry(() => api(`/v1/worker/decisions/${encodeURIComponent(decision_id)}/cancel`, {
376
+ method: 'POST',
377
+ body: JSON.stringify(note ? { note } : {}),
378
+ })));
379
+ }
380
+ catch (err) {
381
+ return asToolError(err);
382
+ }
383
+ });
384
+ return server;
385
+ }
386
+ /**
387
+ * FN-366: the hosted endpoint. A stateless Streamable HTTP handler that builds a
388
+ * fresh server per request from the caller's config — the host authenticates
389
+ * the request, then passes the config (token, default approver) in
390
+ * `authInfo.extra.ratifia`. A request without one is refused: the handler
391
+ * never reads credentials itself.
392
+ */
393
+ export function createRatifiaMcpHandler(opts) {
394
+ return createMcpHandler((ctx) => {
395
+ const cfg = ctx.authInfo?.extra?.ratifia;
396
+ if (!cfg?.token)
397
+ throw new Error('ratifia-mcp: no caller config on this request');
398
+ return createRatifiaServer(cfg, { ...opts, hosted: true });
399
+ });
400
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ratifia/mcp",
3
- "version": "0.12.0",
3
+ "version": "0.13.1",
4
4
  "type": "module",
5
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'.",
6
6
  "keywords": [
@@ -24,7 +24,7 @@
24
24
  "bin": {
25
25
  "ratifia-mcp": "dist/index.js"
26
26
  },
27
- "main": "./dist/index.js",
27
+ "main": "./dist/server.js",
28
28
  "files": [
29
29
  "dist"
30
30
  ],
@@ -49,5 +49,13 @@
49
49
  "@types/node": "^20.0.0",
50
50
  "tsx": "^4.19.0",
51
51
  "typescript": "^5.6.0"
52
+ },
53
+ "types": "./dist/server.d.ts",
54
+ "exports": {
55
+ ".": {
56
+ "types": "./dist/server.d.ts",
57
+ "default": "./dist/server.js"
58
+ },
59
+ "./package.json": "./package.json"
52
60
  }
53
61
  }