// Write tools. Every write goes through approveThenRun():
//
// 1. PREVIEW dry-run in the ERP (simulate). Business errors stop here, nothing written.
// 2. ASK modern client with elicitation → MCP multi round-trip: return
// resultType "input_required" with a confirmation form for the USER and a
// signed requestState. Other clients → a preview + signed approval token.
// 3. VERIFY on the retry: signature, user, tool, exact arguments, expiry, single use,
// and that the ERP still says what the user saw (re-simulate).
// 4. EXECUTE claim the idempotency key, call the ERP once, commit.
// 5. RECONCILE if the response is lost, look the order up by its reference instead of
// guessing. A retry with the same idempotencyKey never creates a duplicate.
import { digest } from "../approval.ts";
import { BapiError, SoapFault } from "../soap/client.ts";
import { guard, ok, toolError, type ToolContext, type ToolDef, type ToolResult } from "./types.ts";
const CONFIRM_KEY = "confirm_write";
interface WritePlan {
tool: string;
args: Record<string, unknown>;
ctx: ToolContext;
/** Dry run. `fingerprint` captures what the user is shown (e.g. the total). */
preview(): Promise<{ summary: string; fingerprint: string; details: unknown; errors: string[] }>;
/** The real write. Must not be retried blindly. */
execute(reference: string): Promise<Record<string, unknown>>;
/** After a lost response: did the write happen? */
reconcile?(reference: string): Promise<Record<string, unknown> | undefined>;
reference: string;
}
/** The arguments the approval is bound to: everything except the approval token itself. */
const bound = (args: Record<string, unknown>) => {
const { approvalToken: _ignored, ...rest } = args;
return rest;
};
async function approveThenRun(plan: WritePlan): Promise<ToolResult> {
const { ctx, tool, args } = plan;
const who = ctx.principal.user;
const key = String(args.idempotencyKey);
const argsHash = digest(bound(args));
const audit = (outcome: string, detail?: unknown) => ctx.store.audit({ principal: who, client: ctx.clientName, tool, argsHash, outcome, detail });
// Already done (or in flight) under this key? Answer from the store; never write twice.
const prior = ctx.store.check(who, key, argsHash);
if (prior.state === "conflict") return toolError("This idempotencyKey was already used with different arguments. Use a new key for a new request.", { code: "idempotency_conflict" });
if (prior.state === "replay") { audit("replayed"); return ok({ ...(prior.result as object), replayed: true }, "Already done earlier with this idempotencyKey; returning the original result."); }
if (prior.state === "pending") {
const found = plan.reconcile ? await plan.reconcile(prior.reference) : undefined;
if (found) { ctx.store.complete(who, key, found); audit("reconciled", found); return ok({ ...found, reconciled: true }); }
return toolError("An identical request is still being processed. Wait a few seconds, then retry with the same idempotencyKey.", { code: "in_progress", retryAfterSeconds: 5 });
}
const responses = ctx.inputResponses?.[CONFIRM_KEY];
const token = ctx.requestState ?? (args.approvalToken as string | undefined);
// ── first call: preview and ask ──
if (!token) {
const p = await plan.preview();
if (p.errors.length) { audit("rejected_in_preview", p.errors); return toolError(`The ERP would reject this: ${p.errors.join("; ")}`, { code: "erp_rejected", preview: p.details }); }
const { token: approval } = ctx.approvals.issue(who, tool, bound(args), p.fingerprint);
audit("approval_requested", { fingerprint: p.fingerprint });
if (ctx.canElicit) {
return {
resultType: "input_required",
inputRequests: {
[CONFIRM_KEY]: {
method: "elicitation/create",
params: {
mode: "form",
message: `${p.summary}\n\nThis writes to the ERP (system of record).`,
requestedSchema: {
type: "object",
properties: { confirm: { type: "boolean", title: "Yes, write this to the ERP", default: false } },
required: ["confirm"],
},
},
},
},
requestState: approval,
};
}
if (ctx.config.legacyWrites === "deny") {
return toolError("This client cannot ask the user for confirmation (no elicitation support), and writes require it. Ask an administrator to enable a supported client.", { code: "approval_unsupported" });
}
return ok({
status: "approval_required",
summary: p.summary,
preview: p.details,
approvalToken: approval,
expiresInSeconds: Math.round(ctx.config.approvalTtlMs / 1000),
instructions: "Show the summary to the user and ask them to confirm. ONLY if they explicitly say yes, call this tool again with exactly the same arguments plus approvalToken.",
}, "Nothing was written yet. The user must confirm first.");
}
// ── retry: the user answered ──
const claims = ctx.approvals.verify(token, who, tool, bound(args));
if (ctx.requestState) {
if (!responses) return toolError("Missing the user's answer to the confirmation form.", { code: "approval_missing" });
if (responses.action !== "accept" || responses.content?.confirm !== true) {
audit("declined_by_user");
return ok({ status: "cancelled", reason: responses.action === "accept" ? "user did not tick confirm" : `user chose ${responses.action}` }, "The user did not approve. Nothing was written.");
}
}
// What the user approved must still be true: re-run the dry run and compare.
ctx.progress(1, 3, "Re-checking with the ERP");
const now = await plan.preview();
if (now.errors.length) { audit("rejected_after_approval", now.errors); return toolError(`The ERP now rejects this: ${now.errors.join("; ")}`, { code: "erp_rejected" }); }
if (now.fingerprint !== claims.f) {
audit("changed_since_approval", { approved: claims.f, now: now.fingerprint });
return toolError(`The ERP's answer changed since the user approved it (${claims.f} → ${now.fingerprint}). Ask the user again.`, { code: "approval_stale" });
}
if (!ctx.store.redeem(claims.n, claims.e)) return toolError("This approval was already used. Each approval works once.", { code: "approval_replayed" });
if (!ctx.store.begin(who, key, argsHash, plan.reference)) return toolError("An identical request is already in progress.", { code: "in_progress", retryAfterSeconds: 5 });
ctx.progress(2, 3, "Writing to the ERP");
try {
const result = await plan.execute(plan.reference);
ctx.store.complete(who, key, result);
audit("written", result);
ctx.progress(3, 3, "Committed");
return ok(result);
} catch (e) {
if (e instanceof SoapFault && e.uncertain && plan.reconcile) {
// The ERP may have done it and the answer got lost. Look, don't guess.
const found = await plan.reconcile(plan.reference).catch(() => undefined);
if (found) { ctx.store.complete(who, key, found); audit("reconciled", found); return ok({ ...found, reconciled: true }); }
}
if (e instanceof SoapFault && e.uncertain) {
// Unknown outcome and no way to check: keep the key claimed so a blind retry can't duplicate.
audit("outcome_unknown", e.message);
return toolError("The ERP did not confirm the write and its outcome is unknown. Do NOT create it again; ask the user to check in the ERP.", { code: "outcome_unknown" });
}
ctx.store.release(who, key); // definitely not written: the key can be retried
audit("failed", (e as Error).message);
throw e;
}
}
const idempotencyKey = {
type: "string", minLength: 8, maxLength: 64, pattern: "^[A-Za-z0-9_-]+$",
description: "A unique ID you generate for this write (e.g. a UUID). Reuse it ONLY when retrying the same request: the ERP will not do it twice.",
};
const approvalToken = { type: "string", maxLength: 2048, description: "Only when a previous call returned status approval_required AND the user explicitly confirmed." };
export const writeTools: ToolDef[] = [
{
name: "erp_create_sales_order",
title: "Create sales order",
description: "Create a sales order in the ERP. The ERP checks prices, stock and credit first; then the USER must confirm before anything is written. Always pass a fresh idempotencyKey.",
requiredScope: "erp:write",
annotations: { title: "Create sales order", readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
inputSchema: {
type: "object",
properties: {
customerId: { type: "string", pattern: "^[A-Za-z0-9]{1,10}$" },
lines: {
type: "array", minItems: 1, maxItems: 20,
items: {
type: "object",
properties: {
materialId: { type: "string", pattern: "^[A-Za-z0-9-]{1,18}$" },
quantity: { type: "integer", minimum: 1, maximum: 10000 },
},
required: ["materialId", "quantity"],
additionalProperties: false,
},
},
requestedDelivery: { type: "string", format: "date", pattern: "^\\d{4}-\\d{2}-\\d{2}$" },
customerReference: { type: "string", maxLength: 35, pattern: "^[A-Za-z0-9 ._/-]*$", description: "The customer's PO number, if any." },
idempotencyKey,
approvalToken,
},
required: ["customerId", "lines", "requestedDelivery", "idempotencyKey"],
additionalProperties: false,
},
outputSchema: {
type: "object",
properties: {
status: { type: "string", enum: ["approval_required", "created", "cancelled"] },
orderId: { type: "string" }, netValue: { type: "string" }, currency: { type: "string" },
summary: { type: "string" }, approvalToken: { type: "string" }, replayed: { type: "boolean" }, reconciled: { type: "boolean" },
},
required: ["status"],
},
handler: (a, ctx) => guard(async () => {
const plant = ctx.config.erp.defaultPlant;
if (a.requestedDelivery < new Date().toISOString().slice(0, 10)) return toolError("requestedDelivery is in the past.", { code: "invalid_date" });
// Our reference doubles as the reconciliation key: it is stored ON the ERP document.
const reference = a.customerReference || `MCP-${a.idempotencyKey}`.slice(0, 35);
return approveThenRun({
tool: "erp_create_sales_order", args: a, ctx, reference,
preview: async () => {
const s = await ctx.erp.simulateOrder(a.customerId, a.lines, a.requestedDelivery, plant, ctx.signal);
const lines = s.items.map((i) => ` ${i.quantity} × ${i.description} (${i.materialId}) = ${i.netValue} ${s.currency}${i.available ? "" : " ⚠ not enough stock"}`).join("\n");
return {
summary: `Create a sales order for customer ${a.customerId}, delivery ${a.requestedDelivery}:\n${lines}\nTotal ${s.netValue} ${s.currency}${s.warnings.length ? `\nWarnings: ${s.warnings.join("; ")}` : ""}`,
fingerprint: `${s.netValue} ${s.currency}`,
details: s,
errors: s.errors,
};
},
execute: async (ref) => {
const r = await ctx.erp.createOrder(a.customerId, a.lines, a.requestedDelivery, ref, plant, ctx.signal);
const order = await ctx.erp.findOrderByReference(a.customerId, ref, ctx.signal);
return { status: "created", orderId: r.orderId, netValue: order?.netValue ?? "", currency: order?.currency ?? "", customerReference: ref };
},
reconcile: async (ref) => {
const o = await ctx.erp.findOrderByReference(a.customerId, ref, ctx.signal);
return o ? { status: "created", orderId: o.orderId, netValue: o.netValue, currency: o.currency, customerReference: ref } : undefined;
},
});
}),
},
{
name: "erp_change_delivery_date",
title: "Change delivery date",
description: "Move the requested delivery date of an OPEN sales order. The user must confirm. Fails if someone else is editing the order in the ERP.",
requiredScope: "erp:write",
annotations: { title: "Change delivery date", readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
inputSchema: {
type: "object",
properties: {
customerId: { type: "string", pattern: "^[A-Za-z0-9]{1,10}$", description: "Owner of the order (used to look it up)." },
orderId: { type: "string", pattern: "^\\d{1,10}$" },
requestedDelivery: { type: "string", format: "date", pattern: "^\\d{4}-\\d{2}-\\d{2}$" },
idempotencyKey,
approvalToken,
},
required: ["customerId", "orderId", "requestedDelivery", "idempotencyKey"],
additionalProperties: false,
},
outputSchema: {
type: "object",
properties: { status: { type: "string" }, orderId: { type: "string" }, requestedDelivery: { type: "string" }, summary: { type: "string" }, approvalToken: { type: "string" } },
required: ["status"],
},
handler: (a, ctx) => guard(async () => {
if (a.requestedDelivery < new Date().toISOString().slice(0, 10)) return toolError("requestedDelivery is in the past.", { code: "invalid_date" });
return approveThenRun({
tool: "erp_change_delivery_date", args: a, ctx, reference: `order:${a.orderId}`,
preview: async () => {
const order = (await ctx.erp.listOrders(a.customerId, undefined, undefined, ctx.signal)).find((o) => o.orderId === String(Number(a.orderId)));
if (!order) return { summary: "", fingerprint: "", details: null, errors: [`Order ${a.orderId} not found for customer ${a.customerId}`] };
if (order.status !== "Open") return { summary: "", fingerprint: "", details: order, errors: [`Order ${a.orderId} is ${order.status} and cannot be changed`] };
// Don't ask a human to approve something the ERP will refuse: test-run it first (locks!).
try {
await ctx.erp.changeDeliveryDate(a.orderId, a.requestedDelivery, ctx.signal, { simulate: true });
} catch (e) {
if (e instanceof BapiError) return { summary: "", fingerprint: "", details: order, errors: e.messages.filter((m) => m.type === "E").map((m) => m.message) };
throw e;
}
return {
summary: `Change the delivery date of order ${order.orderId} (${order.netValue} ${order.currency}) from ${order.requestedDelivery ?? "none"} to ${a.requestedDelivery}.`,
fingerprint: `${order.orderId}:${order.requestedDelivery}`,
details: order,
errors: [],
};
},
execute: async () => ({ status: "changed", ...(await ctx.erp.changeDeliveryDate(a.orderId, a.requestedDelivery, ctx.signal)) }),
});
}),
},
];