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.

fix(mcp): handle the "updatedBy" in insert-vs-update discriminator (#1602)

Brad Barbin3552b1c01c6b
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index dbcb5ed3b6..caabf75004 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -218,14 +218,32 @@ exports into the same module namespace), and writes `apps/erp/app/routes/api+/mc
genuine `delete*`) → `["companyId"]`. A DESTRUCTIVE-classified `upsert*` still
inserts rows, so it keeps its `createdBy` — the label is only a caller hint.
-- **`_operation`** (`usesCreatedByDiscriminator`): the ~96 tools whose service picks
- insert-vs-update with `if ("createdBy" in …)` get a **required**
- `_operation: "create" | "update"` in their schema — the schema is the only marker,
- there is no parallel metadata flag. The dispatch (`api+/v1+/lib/dispatch.server.ts`)
- strips `_operation` from the args (top level *and* the `{ args: {...} }` wrapper) before building the payload, then
- suppresses the `createdBy` stamp when it is `"update"` — otherwise every MCP edit would
- take the insert branch. Missing/invalid `_operation` on such a tool is rejected before
+- **`_operation`** (`usesOperationDiscriminator`): a tool whose service picks
+ insert-vs-update by testing for an audit field on the payload gets a **required**
+ `_operation: "create" | "update"` in its schema — the schema is the only marker,
+ there is no parallel metadata flag. **BOTH discriminator directions count**:
+ `if ("createdBy" in …)` (create-branch first, e.g. `upsertQuoteOperation`) AND
+ `if ("updatedBy" in …)` (update-branch first, e.g. `upsertQuoteMaterial`,
+ `upsertJobMaterial`, `upsertJob`, `upsertProductionQuantity`, `upsertPartner`,
+ `upsertPeriodCloseTaskDefinition`). The generator only matched `"createdBy" in`
+ until it was broadened — so the inverted ones shipped WITHOUT `_operation`, and
+ since `enrichWithAuthContext` always stamped `updatedBy`, their `"updatedBy" in`
+ test was always true: every create was forced down the UPDATE branch, matched
+ zero rows for a fresh id, and returned **PGRST116** — a silent no-op the customer
+ hit trying to add quote/job materials over the connector. (A few — `upsertJobOperation`,
+ `upsertContractor`, `upsertGaugeCalibrationRecord` — got `_operation` anyway from
+ a secondary `"createdBy" in` in the body, but were broken the same way until the
+ dispatch fix below, because their PRIMARY branch is `"updatedBy" in`.)
+ The dispatch (`api+/v1+/lib/dispatch.server.ts`) strips `_operation` from the args
+ (top level *and* the `{ args: {...} }` wrapper) before building the payload, then
+ stamps audit fields **symmetrically**: on `"create"` it stamps `createdBy` and
+ **suppresses `updatedBy`**; on `"update"` it stamps `updatedBy` and **suppresses
+ `createdBy`** — so either convention lands on the branch the caller asked for, and
+ the create path matches the create-variant service type / UI insert (createdBy, no
+ updatedBy). With no `_operation` (operation `undefined`) both audit fields are
+ stamped, as before. Missing/invalid `_operation` on such a tool is rejected before
the service is called; `call_tool.arguments` is `z.any()`, so the dispatch is the gate.
+ Pinned by `dispatch-parity.test.ts` (cases o/p/q) and `mcp-tool-metadata.test.ts`.
## The 15 modules (current `tool-metadata.json`)
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 26b56bfbc6..7a3b901e24 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -141,7 +141,7 @@
{"name":"accounting_upsertFixedAssetUsageLog","classification":"WRITE","paramCount":1,"schema":"12272e046f40","response":"3797626bd17e","injectAuth":"companyId+createdBy","permission":"accounting:create+update"},
{"name":"accounting_upsertJournalEntryLine","classification":"WRITE","paramCount":6,"schema":"ca2ee4db3127","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
{"name":"accounting_upsertPaymentTerm","classification":"WRITE","paramCount":6,"schema":"893974263c78","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
- {"name":"accounting_upsertPeriodCloseTaskDefinition","classification":"WRITE","paramCount":9,"schema":"5b9d3a16980b","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
+ {"name":"accounting_upsertPeriodCloseTaskDefinition","classification":"WRITE","paramCount":9,"schema":"22eb270aa01a","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
{"name":"accounting_upsertReportPin","classification":"WRITE","paramCount":2,"schema":"28ab82d5033e","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
{"name":"accounting_upsertReportView","classification":"WRITE","paramCount":1,"schema":"d91fde891b7f","response":"b8ded59f5c56","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create+update"},
{"name":"documents_deleteDocument","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"documents:delete"},
@@ -201,7 +201,7 @@
{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view"},
- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"dc7546a2e5ad","injectAuth":"companyId","permission":"inventory:view"},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"a4238ea3fb56","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"cc66c1b66f31","injectAuth":"companyId","permission":"inventory:view"},
{"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view"},
@@ -392,7 +392,7 @@
{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view"},
- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"dc7546a2e5ad","injectAuth":"companyId","permission":"parts:view"},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"a4238ea3fb56","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view"},
{"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view"},
@@ -579,7 +579,7 @@
{"name":"people_getEmployeeSummary","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"afd28b3efe9e","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getHoliday","classification":"READ","paramCount":1,"schema":"9189cc10f756","response":"8d2b62b6a13b","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getHolidays","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"1fedcd5adb59","injectAuth":"companyId","permission":"people:view"},
- {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7dd467066555","injectAuth":"companyId","permission":"people:view"},
+ {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"6752ec5720d7","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getOpenClockEntry","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getPeople","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"5483e69d7515","injectAuth":"companyId","permission":"people:view"},
{"name":"people_getRecentTimecards","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view"},
@@ -767,11 +767,11 @@
{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create"},
{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update"},
{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update"},
- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"dc7546a2e5ad","injectAuth":"companyId","permission":"production:update"},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"a4238ea3fb56","injectAuth":"companyId","permission":"production:update"},
{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update"},
{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update"},
{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update"},
- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"133d83f1706f","injectAuth":"companyId","permission":"production:update"},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"ba6a256056b4","injectAuth":"companyId","permission":"production:update"},
{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update"},
{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update"},
{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy","permission":"production:update"},
@@ -826,8 +826,8 @@
{"name":"production_upsertDemandProjections","classification":"DESTRUCTIVE","paramCount":1,"schema":"52be92b5f4a5","response":"57a0b3d217fb","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"production_upsertFailureMode","classification":"WRITE","paramCount":2,"schema":"df56b99ec46e","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"production_upsertInspectionDocument","classification":"WRITE","paramCount":7,"schema":"bb8780ca9841","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
- {"name":"production_upsertJob","classification":"WRITE","paramCount":2,"schema":"71fdb759384a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
- {"name":"production_upsertJobMaterial","classification":"WRITE","paramCount":15,"schema":"a8485ce0c973","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
+ {"name":"production_upsertJob","classification":"WRITE","paramCount":2,"schema":"73f73c34c970","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
+ {"name":"production_upsertJobMaterial","classification":"WRITE","paramCount":15,"schema":"5fa6ff98a6ca","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"production_upsertJobMaterialMakeMethod","classification":"WRITE","paramCount":5,"schema":"d603e9c57b46","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"production_upsertJobMethod","classification":"WRITE","paramCount":2,"schema":"170fba7b05c6","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"production_upsertJobOperation","classification":"WRITE","paramCount":24,"schema":"17d8a3d4ceaf","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
@@ -849,7 +849,7 @@
{"name":"production_upsertProcedureParameter","classification":"WRITE","paramCount":4,"schema":"d58a41fa9f2f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"production_upsertProcedureStep","classification":"WRITE","paramCount":10,"schema":"e0352a783337","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"production_upsertProductionEvent","classification":"WRITE","paramCount":8,"schema":"487f567809f9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
- {"name":"production_upsertProductionQuantity","classification":"WRITE","paramCount":6,"schema":"6ea5f7475d17","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
+ {"name":"production_upsertProductionQuantity","classification":"WRITE","paramCount":6,"schema":"bab2dacfa3a7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"production_upsertScrapReason","classification":"WRITE","paramCount":2,"schema":"df56b99ec46e","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update"},
{"name":"purchasing_closePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
{"name":"purchasing_convertSupplierQuoteToOrder","classification":"WRITE","paramCount":2,"schema":"03ce7e291c3c","response":"5cb338fa12e6","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
@@ -1132,7 +1132,7 @@
{"name":"resources_upsertMaintenanceDispatchWorkCenter","classification":"WRITE","paramCount":3,"schema":"d5b48775f398","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update"},
{"name":"resources_upsertMaintenanceSchedule","classification":"WRITE","paramCount":20,"schema":"89ff27d11274","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update"},
{"name":"resources_upsertMaintenanceScheduleItem","classification":"WRITE","paramCount":5,"schema":"00e2e6d24e50","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update"},
- {"name":"resources_upsertPartner","classification":"WRITE","paramCount":3,"schema":"dc6bf062f805","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update"},
+ {"name":"resources_upsertPartner","classification":"WRITE","paramCount":3,"schema":"aed2ed95d96a","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update"},
{"name":"resources_upsertProcess","classification":"DESTRUCTIVE","paramCount":15,"schema":"0bfaafc2ede1","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update"},
{"name":"resources_upsertTraining","classification":"WRITE","paramCount":4,"schema":"be53f09f9856","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update"},
{"name":"resources_upsertTrainingAssignment","classification":"WRITE","paramCount":3,"schema":"9f8996544bb7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update"},
@@ -1303,7 +1303,7 @@
{"name":"sales_upsertQuoteLineAdditionalCharges","classification":"WRITE","paramCount":2,"schema":"483aa73b0c32","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update"},
{"name":"sales_upsertQuoteLineMethod","classification":"WRITE","paramCount":5,"schema":"5f94e8a4cbf6","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update"},
{"name":"sales_upsertQuoteLinePrices","classification":"DESTRUCTIVE","paramCount":3,"schema":"25f3f3e7401f","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update"},
- {"name":"sales_upsertQuoteMaterial","classification":"WRITE","paramCount":14,"schema":"7f9d99db0c39","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update"},
+ {"name":"sales_upsertQuoteMaterial","classification":"WRITE","paramCount":14,"schema":"b2d9edf099a6","response":"af9af3838934","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update"},
{"name":"sales_upsertQuoteMaterialMakeMethod","classification":"WRITE","paramCount":4,"schema":"06f97e90fc79","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update"},
{"name":"sales_upsertQuoteOperation","classification":"WRITE","paramCount":24,"schema":"603cab4aa2b7","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update"},
{"name":"sales_upsertQuoteOperationParameter","classification":"WRITE","paramCount":4,"schema":"8288299a333f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update"},
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
index a171a601f5..d12574dabf 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
@@ -13,6 +13,7 @@ const spies = vi.hoisted(() => ({
getAccountLedger: vi.fn(),
getTrialBalance: vi.fn(),
upsertAccount: vi.fn(),
+ upsertJobMaterial: vi.fn(),
upsertQuoteLinePrices: vi.fn(),
generateInventoryCountLines: vi.fn(),
upsertNotificationPreference: vi.fn(),
@@ -44,7 +45,8 @@ vi.mock("~/modules/items/items.service", () => ({}));
vi.mock("~/modules/people/people.service", () => ({}));
vi.mock("~/modules/production/production.mcp.server", () => ({}));
vi.mock("~/modules/production/production.service", () => ({
- insertJob: spies.insertJob
+ insertJob: spies.insertJob,
+ upsertJobMaterial: spies.upsertJobMaterial
}));
vi.mock("~/modules/purchasing/purchasing.service", () => ({
insertPurchaseOrder: spies.insertPurchaseOrder
@@ -124,6 +126,7 @@ const allSpies = [
spies.getAccountLedger,
spies.getTrialBalance,
spies.upsertAccount,
+ spies.upsertJobMaterial,
spies.upsertQuoteLinePrices,
spies.generateInventoryCountLines,
spies.upsertNotificationPreference,
@@ -172,7 +175,7 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
]);
});
- it("b. _operation create at top level: stripped, createdBy/updatedBy/companyId stamped", async () => {
+ it("b. _operation create at top level: stripped, createdBy + companyId stamped, updatedBy NOT stamped (matches the create-variant service type / UI insert path)", async () => {
const r = await runDispatch(
"accounting_upsertAccount",
spies.upsertAccount,
@@ -188,11 +191,12 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
name: "Cash",
number: "1000",
createdBy: "u1",
- updatedBy: "u1",
companyId: "c1"
}
]
]);
+ const [, payload] = r.calls[0] as [unknown, Record<string, unknown>];
+ expect("updatedBy" in payload).toBe(false);
});
it("c. _operation update nested in the payload: stripped, createdBy suppressed", async () => {
@@ -385,7 +389,6 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
name: "Cash",
number: "1000",
createdBy: "u1",
- updatedBy: "u1",
companyId: "c1"
}
]
@@ -409,6 +412,62 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
count: 7
});
});
+
+ // The inverted discriminator: upsertJobMaterial branches on `if ("updatedBy" in
+ // jobMaterial)` (update-branch first), the mirror image of upsertAccount. A stamped
+ // updatedBy would force its UPDATE branch, which matches zero rows for a fresh id and
+ // returns PGRST116 — the create silently no-ops. The generator now gives these tools a
+ // required `_operation` too, and the dispatch suppresses updatedBy on create so the
+ // service falls through to its insert branch.
+ it('o. inverted `"updatedBy" in` discriminator, create: updatedBy suppressed, createdBy + companyId stamped, so the service inserts', async () => {
+ const r = await runDispatch(
+ "production_upsertJobMaterial",
+ spies.upsertJobMaterial,
+ {
+ _operation: "create",
+ jobId: "j1",
+ itemId: "i1",
+ methodType: "Pull from Inventory",
+ quantity: 2
+ }
+ );
+ const [, payload] = r.calls[0] as [unknown, Record<string, unknown>];
+ expect("updatedBy" in payload).toBe(false);
+ expect(payload).toMatchObject({
+ createdBy: "u1",
+ companyId: "c1",
+ jobId: "j1",
+ itemId: "i1"
+ });
+ });
+
+ it('p. inverted `"updatedBy" in` discriminator, update: updatedBy + companyId stamped, createdBy suppressed', async () => {
+ const r = await runDispatch(
+ "production_upsertJobMaterial",
+ spies.upsertJobMaterial,
+ { _operation: "update", id: "jm1", quantity: 3 }
+ );
+ const [, payload] = r.calls[0] as [unknown, Record<string, unknown>];
+ expect("createdBy" in payload).toBe(false);
+ expect(payload).toMatchObject({
+ updatedBy: "u1",
+ companyId: "c1",
+ id: "jm1"
+ });
+ });
+
+ it("q. an inverted-discriminator tool requires _operation, same as the createdBy convention", async () => {
+ const r = await runDispatch(
+ "production_upsertJobMaterial",
+ spies.upsertJobMaterial,
+ { jobId: "j1", itemId: "i1" }
+ );
+ expect(r.calls).toEqual([]);
+ expect(r.dispatchError).toBeInstanceOf(ORPCError);
+ expect((r.dispatchError as ORPCError<string, unknown>).message).toBe(
+ 'production_upsertJobMaterial requires _operation to be "create" (insert a new record) or "update" (modify an existing one).'
+ );
+ });
});
// The exact ids the workflow engine's create actions dispatch
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
index 27e26d535d..31a60b88a6 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch.server.ts
@@ -59,7 +59,8 @@ export function enrichWithAuthContext(
...(value as Record<string, unknown>)
};
- // A caller-supplied createdBy would send the service down its insert branch.
+ // A caller-supplied createdBy would send a `"createdBy" in` service down its
+ // insert branch.
if (operation === "update") {
delete enriched.createdBy;
} else if (fields.includes("createdBy")) {
@@ -68,7 +69,15 @@ export function enrichWithAuthContext(
// the same reason, and the two shapes must not disagree.
enriched.createdBy = context.userId;
}
- if (fields.includes("updatedBy")) {
+ // Symmetric to createdBy: a stamped updatedBy sends a service that
+ // discriminates on `"updatedBy" in` (update-branch first — upsertJobMaterial,
+ // upsertQuoteMaterial, …) down its UPDATE branch, which matches zero rows for a
+ // new id and returns PGRST116, so the record never inserts. Suppress it on an
+ // explicit create so the row inserts. With no _operation (operation undefined)
+ // both audit fields are stamped, exactly as before.
+ if (operation === "create") {
+ delete enriched.updatedBy;
+ } else if (fields.includes("updatedBy")) {
enriched.updatedBy = context.userId;
}
if (fields.includes("companyId")) {
diff --git a/apps/erp/test/mcp-tool-metadata.test.ts b/apps/erp/test/mcp-tool-metadata.test.ts
index 92f304c467..da17c7081a 100644
--- a/apps/erp/test/mcp-tool-metadata.test.ts
+++ b/apps/erp/test/mcp-tool-metadata.test.ts
@@ -160,4 +160,29 @@ describe("mcp tool-metadata generator", () => {
expect(Object.keys(ability?.properties ?? {})).toContain("name");
expect(ability?.required).toBeUndefined();
});
+
+ // Insert-vs-update discriminator, BOTH directions, gets a required `_operation`.
+ // upsertQuoteMaterial / upsertJobMaterial branch on `if ("updatedBy" in …)` — the
+ // generator used to detect only the `"createdBy" in` convention, so these tools
+ // shipped without `_operation`, the dispatch always stamped updatedBy, and every
+ // create was forced down the UPDATE branch (0 rows → PGRST116, silent no-op).
+ it("gives an `_operation` flag to `\"updatedBy\" in` upserts, not only `\"createdBy\" in` ones", () => {
+ const requiresOperation = (name: string) => {
+ const t = get(name);
+ expect(props(t)._operation, `${name} should expose _operation`).toMatchObject({
+ enum: ["create", "update"]
+ });
+ expect(t.schema.required ?? [], `${name} should require _operation`).toContain(
+ "_operation"
+ );
+ };
+ // Inverted (`"updatedBy" in`) — the ones that were broken.
+ requiresOperation("sales_upsertQuoteMaterial");
+ requiresOperation("production_upsertJobMaterial");
+ requiresOperation("production_upsertJob");
+ requiresOperation("production_upsertProductionQuantity");
+ requiresOperation("resources_upsertPartner");
+ // Standard (`"createdBy" in`) control — unchanged, still carries the flag.
+ requiresOperation("sales_upsertQuoteOperation");
+ });
});
diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.ts
index 11d74d76ac..daaa84fde1 100644
--- a/scripts/lib/service-metadata.ts
+++ b/scripts/lib/service-metadata.ts
@@ -1163,14 +1163,23 @@ function permissionActionsFor(
return ["update"];
}
-// Services that pick insert-vs-update this way are the only ones MCP can't infer.
-function usesCreatedByDiscriminator(
+// Services that pick insert-vs-update by testing for an audit field on the
+// payload are the only ones MCP can't infer, so they need the `_operation` flag.
+// BOTH directions count: `"createdBy" in` (create-branch first, e.g.
+// upsertQuoteOperation) and `"updatedBy" in` (update-branch first, e.g.
+// upsertQuoteMaterial / upsertJobMaterial). The dispatch stamps createdBy on
+// create and updatedBy on update and suppresses the other, so either convention
+// lands on the branch the caller asked for.
+function usesOperationDiscriminator(
content: string,
funcName: string
): boolean {
const body = extractFunctionBody(content, funcName);
if (body === null) return false;
- return stripComments(body).includes('"createdBy" in');
+ const stripped = stripComments(body);
+ return (
+ stripped.includes('"createdBy" in') || stripped.includes('"updatedBy" in')
+ );
}
// The `:` guard keeps `https://` intact.
@@ -1487,7 +1496,7 @@ export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {
});
if (
injectAuth.includes("createdBy") &&
- usesCreatedByDiscriminator(content, func.name)
+ usesOperationDiscriminator(content, func.name)
) {
addOperationArg(schema);
}