Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

docs(mcp): scope the flat-body rule, and pin the envelope unwrap in tests

Raul828c64567e2f
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index 70fb61b989..b938f848dd 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -241,15 +241,21 @@ dispatcher (`apps/erp/app/routes/api+/inngest.ts`). There is no separate
user; `apps/erp/test/mcp-tool-auth-injection.test.ts` guards the pairing.
A param literally named `args` is stamped too, and which wire shape it takes
is read off the operation's schema: a declared `args` object means the body
- wraps it (`{ args: {...} }`) and the inner object is
- unwrapped; a flat schema means the body already IS the args object. A flat body
- is still accepted either way, and so is the reverse — a lone `{ args: {...} }`
- envelope sent to a flat-schema operation is unwrapped in `callOperation` before
- validation, since the published instructions taught that shape. A param the
- schema declares as a **scalar** is passed `undefined` when no key matches
- rather than being handed the whole
- payload object — that fallback made `deleteApiKey` run `.eq("id", {...})` and
- return `200 null`. Reading a key by the param's own name is likewise gated
+ wraps it (`{ args: {...} }`) and the inner object is unwrapped; a flat schema
+ means the body already IS the args object. Both directions have a compatibility
+ path, and they are NOT symmetric:
+ - A wrapped schema also accepts the wrapper's contents sent flat, but only when
+ the wrapper is the schema's **sole required property** (`compileSoleWrapper`
+ in `packages/api/src/schema.ts`). An operation that requires `args` alongside
+ another property rejects a flat body at validation, before dispatch.
+ - A flat schema also accepts a lone `{ args: {...} }` envelope, unwrapped in
+ `callOperation` before validation because the published instructions taught
+ that shape.
+
+ A param the schema declares as a **scalar** is passed `undefined` when no key
+ matches rather than being handed the whole payload object — that fallback made
+ `deleteApiKey` run `.eq("id", {...})` and return `200 null`. Reading a key by
+ the param's own name is likewise gated
(`addressesWholeParam`): a service whose sole payload param is a destructured
object can share its name with one of that object's FIELDS —
`insertNote(client, note: { note, documentId, … })` — and reading `body.note`
diff --git a/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts b/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts
new file mode 100644
index 0000000000..c8bcc68b23
--- /dev/null
+++ b/apps/erp/app/routes/api+/v1+/lib/args-envelope.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+import { unwrapArgsEnvelope } from "./args-envelope";
+
+// The published MCP instructions taught `arguments: { args: {...} }`, which only
+// operations declaring an `args` object can take — for every other one the
+// envelope IS the payload, so each declared field arrived undefined and
+// validation rejected the call. The unwrap runs before validation, so it has to
+// be exact about which bodies it rewrites.
+//
+// Note the asymmetry (see .claude/rules/mcp-tools-reference.md): the opposite
+// compatibility path — a flat body sent to a WRAPPED schema — lives in
+// `jsonSchemaInput` and applies only when the wrapper is the sole required
+// property. Nothing here should widen that.
+
+const flatSchema = {
+ type: "object",
+ properties: {
+ jobOperationIds: { type: "array" },
+ locationId: { type: "string" }
+ }
+};
+const wrapperSchema = {
+ type: "object",
+ properties: { args: { type: "object" } }
+};
+
+describe("unwrapArgsEnvelope", () => {
+ it("unwraps a lone envelope for a flat-schema operation", () => {
+ expect(
+ unwrapArgsEnvelope(
+ { schema: flatSchema },
+ { args: { jobOperationIds: ["jo_1"], locationId: "loc_1" } }
+ )
+ ).toEqual({ jobOperationIds: ["jo_1"], locationId: "loc_1" });
+ });
+
+ it("leaves a flat body alone", () => {
+ const body = { jobOperationIds: ["jo_1"], locationId: "loc_1" };
+ expect(unwrapArgsEnvelope({ schema: flatSchema }, body)).toBe(body);
+ });
+
+ it("leaves the envelope in place when the operation declares args", () => {
+ const body = { args: { limit: 10 } };
+ expect(unwrapArgsEnvelope({ schema: wrapperSchema }, body)).toBe(body);
+ });
+
+ it("does not unwrap when args sits beside another key", () => {
+ // Sibling keys mean the caller addressed real parameters; the dispatcher's
+ // own `args` handling owns that shape.
+ const body = { args: { limit: 10 }, jobId: "job_1" };
+ expect(unwrapArgsEnvelope({ schema: flatSchema }, body)).toBe(body);
+ });
+
+ it("does not unwrap a non-object envelope", () => {
+ for (const value of [null, ["jo_1"], "jobId"]) {
+ const body = { args: value } as Record<string, unknown>;
+ expect(unwrapArgsEnvelope({ schema: flatSchema }, body)).toBe(body);
+ }
+ });
+
+ it("passes undefined through", () => {
+ expect(
+ unwrapArgsEnvelope({ schema: flatSchema }, undefined)
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts b/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts
new file mode 100644
index 0000000000..6e0ad92571
--- /dev/null
+++ b/apps/erp/app/routes/api+/v1+/lib/args-envelope.ts
@@ -0,0 +1,29 @@
+// Kept out of call.server.ts so it can be tested without loading the service
+// registry (and with it the lingui-macro modules), the same split as
+// validation-issues.ts.
+
+/**
+ * The published MCP instructions tell clients to send
+ * `arguments: { args: { … } }`, and clients have copied that shape, but only the
+ * operations that genuinely declare an `args` object want it — for every other
+ * one the envelope IS the payload, so each declared field arrives undefined and
+ * input validation rejects the call before the dispatcher ever unwraps it. Strip
+ * a lone envelope here, where the operation's own schema says whether it is one.
+ */
+export function unwrapArgsEnvelope(
+ meta: { schema?: unknown },
+ args?: Record<string, unknown>
+): Record<string, unknown> | undefined {
+ if (!args) return args;
+ const declaresArgs = Boolean(
+ (meta.schema as { properties?: Record<string, unknown> } | undefined)
+ ?.properties?.args
+ );
+ if (declaresArgs) return args;
+ const keys = Object.keys(args);
+ if (keys.length !== 1 || keys[0] !== "args") return args;
+ const envelope = args.args;
+ return envelope && typeof envelope === "object" && !Array.isArray(envelope)
+ ? (envelope as Record<string, unknown>)
+ : args;
+}
diff --git a/apps/erp/app/routes/api+/v1+/lib/call.server.ts b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
index 62dce03b50..8de8cf69f4 100644
--- a/apps/erp/app/routes/api+/v1+/lib/call.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/call.server.ts
@@ -7,6 +7,7 @@
import { call, ORPCError } from "@orpc/server";
import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { isMcpBlockedTool } from "../../mcp+/lib/mcp-blocked-tools";
+import { unwrapArgsEnvelope } from "./args-envelope";
import type { AuthedContext } from "./base.server";
import {
operationId,
@@ -37,32 +38,6 @@ async function edgeFunctionMessage(error: unknown): Promise<string | null> {
return message === "" ? null : message;
}
-/**
- * The published MCP instructions tell clients to send
- * `arguments: { args: { … } }`, and clients have copied that shape, but only the
- * operations that genuinely declare an `args` object want it — for every other
- * one the envelope IS the payload, so each declared field arrives undefined and
- * input validation rejects the call before the dispatcher ever unwraps it. Strip
- * a lone envelope here, where the operation's own schema says whether it is one.
- */
-function unwrapArgsEnvelope(
- meta: { schema?: unknown },
- args?: Record<string, unknown>
-): Record<string, unknown> | undefined {
- if (!args) return args;
- const declaresArgs = Boolean(
- (meta.schema as { properties?: Record<string, unknown> } | undefined)
- ?.properties?.args
- );
- if (declaresArgs) return args;
- const keys = Object.keys(args);
- if (keys.length !== 1 || keys[0] !== "args") return args;
- const envelope = args.args;
- return envelope && typeof envelope === "object" && !Array.isArray(envelope)
- ? (envelope as Record<string, unknown>)
- : args;
-}
-
export async function callOperation(
name: string,
context: AuthedContext,