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(production): stop server-only module leak breaking the ERP deploy build (#1478)

Brad Barbinda4890794bde
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index f23ce87c3e..7278de946b 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -77,8 +77,11 @@ registered individually:
`tool-metadata.json` is **generated**, never hand-edited. Run
`npx tsx scripts/generate-mcp.ts`; it parses every `apps/erp/app/modules/*/*.service.ts`
-(falling back to the `.ee`-licensed `<module>.ee.service.ts` — e.g. `accounting`)
-and writes `apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json`
+(falling back to the `.ee`-licensed `<module>.ee.service.ts` — e.g. `accounting`),
+plus an optional server-only companion `<module>.mcp.server.ts` when present (for MCP
+functions that must import `*.server` modules — see the gotcha below — e.g.
+`production.mcp.server.ts`; `direct-executor.ts` merges its exports into the same module
+namespace), and writes `apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json`
(`{ generated, totalTools, modules, tools }`). Each tool entry:
`{ name, module, classification, description, paramCount, serviceParams, injectAuth, schema }`.
@@ -129,3 +132,13 @@ and writes `apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json`
*different*, still-current concept — don't conflate them.
- To block a tool from MCP, add its `<module>_<func>` name to
`MCP_BLOCKED_TOOL_NAMES` and regenerate metadata.
+- **A `{module}.service.ts` must not import a `*.server` module** (`@carbon/auth/users.server`,
+ `@carbon/ee/storage-rules.server`, an app `*.server.ts`, …) — even via `await import(...)`.
+ The module barrel (`~/modules/{module}`) re-exports the service, and client components
+ value-import that barrel for validators/enums, so the service is in the **client** bundle;
+ React Router's `react-router:dot-server` plugin then fails the build with *"Server-only
+ module referenced by client"*. Put such MCP write functions in a server-only companion
+ `{module}.mcp.server.ts` instead (never re-exported by the barrel). The generator parses it
+ and `direct-executor.ts` spreads its exports into the module namespace, so the tool names and
+ metadata are identical to a service-file function. Precedent: `production.mcp.server.ts`
+ holds `issueMaterial` / `completeJob`.
diff --git a/apps/erp/app/modules/production/production.mcp.server.ts b/apps/erp/app/modules/production/production.mcp.server.ts
new file mode 100644
index 0000000000..676e2b1926
--- /dev/null
+++ b/apps/erp/app/modules/production/production.mcp.server.ts
@@ -0,0 +1,183 @@
+import { hasPermission } from "@carbon/auth";
+import { getUserClaims } from "@carbon/auth/users.server";
+import type { Database } from "@carbon/database";
+import {
+ evaluateLinesForSurface,
+ isBlocked
+} from "@carbon/ee/storage-rules.server";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { triggerJobSchedule } from "./production.service";
+
+// MCP-exposed production writes that depend on server-only modules
+// (`@carbon/auth/users.server`, `@carbon/ee/storage-rules.server`). These CANNOT
+// live in `production.service.ts`: that file is re-exported by the
+// `~/modules/production` barrel, which client components value-import, so it is
+// part of the client bundle and React Router's dot-server plugin rejects any
+// `.server` reference reachable from it. This module is server-only (never
+// re-exported by the barrel) and is pulled into the MCP tool set by
+// `scripts/generate-mcp.ts` + `direct-executor.ts`, which run server-side only.
+//
+// The MCP executor injects companyId/userId from the OAuth token but performs no
+// per-tool permission check, and some of these writes reach privileged paths (a
+// SECURITY DEFINER RPC, an Inngest trigger) that bypass RLS — so the ERP route's
+// permission gate is re-applied inline via `hasPermission` on the caller's claims.
+
+/**
+ * Issue material to a job operation, enforcing work-center material-issue rules first.
+ * Wraps the `issue` edge function (type "partToOperation").
+ *
+ * The work-center rule check fails closed: a failed or empty operation lookup throws rather
+ * than silently skipping the rule and letting the edge function run unchecked.
+ */
+export async function issueMaterial(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ userId: string,
+ args: {
+ operationId: string;
+ itemId: string;
+ quantity: number;
+ materialId?: string;
+ jobOperationStepId?: string;
+ adjustmentType?: string;
+ acknowledged?: boolean;
+ }
+) {
+ const { data: jobOp, error: jobOpError } = await client
+ .from("jobOperation")
+ .select("workCenterId")
+ .eq("id", args.operationId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ // Fail closed: a failed or empty lookup must not silently skip the work-center
+ // material-issue rule and let the `issue` edge function run unchecked.
+ if (jobOpError || !jobOp) {
+ throw new Error(`Job operation ${args.operationId} was not found.`);
+ }
+ const workCenterId = jobOp.workCenterId;
+ if (workCenterId) {
+ const ruleEval = await evaluateLinesForSurface({
+ client,
+ companyId,
+ userId,
+ targetType: "workCenter",
+ surface: "materialIssue",
+ lines: [
+ {
+ lineId: args.operationId,
+ itemId: args.itemId,
+ workCenterId,
+ operation: {
+ id: args.operationId,
+ itemId: args.itemId,
+ quantity: args.quantity,
+ workInstructionId: null
+ },
+ quantity: args.quantity
+ }
+ ]
+ });
+ if (
+ ruleEval.violations.length > 0 &&
+ isBlocked(ruleEval.violations, args.acknowledged ?? false)
+ ) {
+ throw new Error(
+ `Material issue blocked by a work-center rule: ${ruleEval.violations
+ .map((v) => v.message)
+ .join("; ")}`
+ );
+ }
+ }
+
+ return client.functions.invoke("issue", {
+ body: {
+ id: args.operationId,
+ type: "partToOperation",
+ itemId: args.itemId,
+ materialId: args.materialId,
+ jobOperationStepId: args.jobOperationStepId,
+ quantity: args.quantity,
+ adjustmentType: args.adjustmentType,
+ companyId,
+ userId
+ }
+ });
+}
+
+/**
+ * Complete a job to inventory (finished goods, backflush, cost rollup). Wraps the
+ * `complete_job_to_inventory` RPC — the same entry point the ERP job-complete route uses.
+ *
+ * The RPC is SECURITY DEFINER (bypasses RLS) and the MCP endpoint does not enforce per-tool
+ * claims, so the ERP route's `{ update: "production" }` gate is re-applied here to prevent an
+ * unprivileged MCP caller from completing jobs.
+ */
+export async function completeJob(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ userId: string,
+ args: {
+ jobId: string;
+ quantity: number;
+ storageUnitId?: string;
+ locationId?: string;
+ }
+) {
+ const claims = await getUserClaims(userId, companyId);
+ if (!hasPermission(claims?.permissions, "production", "update", companyId)) {
+ throw new Error(
+ "You do not have permission to complete jobs to inventory (production update)."
+ );
+ }
+ return client.rpc("complete_job_to_inventory", {
+ p_job_id: args.jobId,
+ p_quantity_complete: args.quantity,
+ p_storage_unit_id: args.storageUnitId ?? undefined,
+ p_location_id: args.locationId ?? undefined,
+ p_company_id: companyId,
+ p_user_id: userId
+ });
+}
+
+/**
+ * Schedule or reschedule a job's operations. Routes through `triggerJobSchedule` (the Inngest
+ * scheduling path) rather than invoking the `schedule` edge function directly, so the MCP entry
+ * point uses the same validated dispatch the rest of the app does. Invalid `mode`/`direction`
+ * strings are rejected up front rather than only at the edge function.
+ *
+ * `triggerJobSchedule` fires an Inngest event with no gate of its own — every ERP route that
+ * calls it does `requirePermissions({ update: "production" })` first — so the same
+ * `production` update gate is re-applied here (the MCP executor performs no per-tool check).
+ * `client` is unused (the work is an Inngest event) but MUST stay named `client` and first —
+ * the MCP executor injects it positionally by that exact name; renaming breaks the tool.
+ */
+export async function scheduleJob(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ userId: string,
+ args: {
+ jobId: string;
+ mode?: "initial" | "reschedule";
+ direction?: "backward" | "forward";
+ }
+) {
+ const claims = await getUserClaims(userId, companyId);
+ if (!hasPermission(claims?.permissions, "production", "update", companyId)) {
+ throw new Error(
+ "You do not have permission to schedule jobs (production update)."
+ );
+ }
+ const mode = args.mode ?? "reschedule";
+ const direction = args.direction ?? "backward";
+ if (mode !== "initial" && mode !== "reschedule") {
+ throw new Error(
+ `Invalid schedule mode "${mode}". Expected "initial" or "reschedule".`
+ );
+ }
+ if (direction !== "backward" && direction !== "forward") {
+ throw new Error(
+ `Invalid schedule direction "${direction}". Expected "backward" or "forward".`
+ );
+ }
+ return triggerJobSchedule(args.jobId, companyId, userId, mode, direction);
+}
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 8520ef3721..242c38cb06 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1,11 +1,6 @@
-import { getUserClaims } from "@carbon/auth/users.server";
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
-import {
- evaluateLinesForSurface,
- isBlocked
-} from "@carbon/ee/storage-rules.server";
import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
import type { JobSource } from "@carbon/lib/telemetry";
import { asJobSource, trackWorkEvent } from "@carbon/lib/telemetry";
@@ -7733,157 +7728,9 @@ export async function saveInspectionDocumentAtomic(
// MCP executor), not from caller-supplied (falsifiable) fields. Exposed automatically by
// scripts/generate-mcp.ts as production_issueMaterial / _completeJob / _scheduleJob.
-/**
- * Issue material to a job operation. Wraps the `issue` edge function (partToOperation) — the same
- * transactional entry point the MES material-issue screen uses (inventory draw-down + WIP posting).
- * Issuing requires only an authenticated company user (matching the MES route), so no extra
- * permission gate is applied here.
- *
- * Mirrors the MES screen's work-center blocking-rule pre-check: if the operation's work center has
- * a `materialIssue` rule that blocks (any error-severity violation, or any violation when not
- * acknowledged), the issue is refused rather than performed. Pass `acknowledged: true` to override
- * non-error (warning) violations, as the MES screen's acknowledge step does.
- */
-export async function issueMaterial(
- client: SupabaseClient<Database>,
- companyId: string,
- userId: string,
- args: {
- operationId: string;
- itemId: string;
- quantity: number;
- materialId?: string;
- jobOperationStepId?: string;
- adjustmentType?: string;
- acknowledged?: boolean;
- }
-) {
- const { data: jobOp, error: jobOpError } = await client
- .from("jobOperation")
- .select("workCenterId")
- .eq("id", args.operationId)
- .eq("companyId", companyId)
- .maybeSingle();
- // Fail closed: a failed or empty lookup must not silently skip the work-center
- // material-issue rule and let the `issue` edge function run unchecked.
- if (jobOpError || !jobOp) {
- throw new Error(`Job operation ${args.operationId} was not found.`);
- }
- const workCenterId = jobOp.workCenterId;
- if (workCenterId) {
- const ruleEval = await evaluateLinesForSurface({
- client,
- companyId,
- userId,
- targetType: "workCenter",
- surface: "materialIssue",
- lines: [
- {
- lineId: args.operationId,
- itemId: args.itemId,
- workCenterId,
- operation: {
- id: args.operationId,
- itemId: args.itemId,
- quantity: args.quantity,
- workInstructionId: null
- },
- quantity: args.quantity
- }
- ]
- });
- if (
- ruleEval.violations.length > 0 &&
- isBlocked(ruleEval.violations, args.acknowledged ?? false)
- ) {
- throw new Error(
- `Material issue blocked by a work-center rule: ${ruleEval.violations
- .map((v) => v.message)
- .join("; ")}`
- );
- }
- }
-
- return client.functions.invoke("issue", {
- body: {
- id: args.operationId,
- type: "partToOperation",
- itemId: args.itemId,
- materialId: args.materialId,
- jobOperationStepId: args.jobOperationStepId,
- quantity: args.quantity,
- adjustmentType: args.adjustmentType,
- companyId,
- userId
- }
- });
-}
-
-/**
- * Complete a job to inventory (finished goods, backflush, cost rollup). Wraps the
- * `complete_job_to_inventory` RPC — the same entry point the ERP job-complete route uses.
- *
- * The RPC is SECURITY DEFINER (bypasses RLS) and the MCP endpoint does not enforce per-tool
- * claims, so the ERP route's `{ update: "production" }` gate is re-applied here to prevent an
- * unprivileged MCP caller from completing jobs.
- */
-export async function completeJob(
- client: SupabaseClient<Database>,
- companyId: string,
- userId: string,
- args: {
- jobId: string;
- quantity: number;
- storageUnitId?: string;
- locationId?: string;
- }
-) {
- const claims = await getUserClaims(userId, companyId);
- if (!claims?.permissions?.production?.update?.includes(companyId)) {
- throw new Error(
- "You do not have permission to complete jobs to inventory (production update)."
- );
- }
- return client.rpc("complete_job_to_inventory", {
- p_job_id: args.jobId,
- p_quantity_complete: args.quantity,
- p_storage_unit_id: args.storageUnitId ?? undefined,
- p_location_id: args.locationId ?? undefined,
- p_company_id: companyId,
- p_user_id: userId
- });
-}
-
-/**
- * Schedule or reschedule a job's operations. Routes through `triggerJobSchedule` (the Inngest
- * scheduling path) rather than invoking the `schedule` edge function directly, so the MCP entry
- * point uses the same validated dispatch the rest of the app does. Invalid `mode`/`direction`
- * strings are rejected here rather than only at the edge function.
- */
-export async function scheduleJob(
- client: SupabaseClient<Database>,
- companyId: string,
- userId: string,
- args: {
- jobId: string;
- mode?: "initial" | "reschedule";
- direction?: "backward" | "forward";
- }
-) {
- const mode = args.mode ?? "reschedule";
- const direction = args.direction ?? "backward";
- if (mode !== "initial" && mode !== "reschedule") {
- throw new Error(
- `Invalid schedule mode "${mode}". Expected "initial" or "reschedule".`
- );
- }
- if (direction !== "backward" && direction !== "forward") {
- throw new Error(
- `Invalid schedule direction "${direction}". Expected "backward" or "forward".`
- );
- }
- return triggerJobSchedule(args.jobId, companyId, userId, mode, direction);
-}
+// `issueMaterial`, `completeJob`, and `scheduleJob` moved to `production.mcp.server.ts`: they
+// depend on server-only modules (`@carbon/ee/storage-rules.server`, `@carbon/auth/users.server`)
+// that cannot be referenced from this file, which is client-reachable via the module barrel.
/**
* Complete a job operation by reporting produced quantity (non-tracked items). Re-orchestrates the
diff --git a/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts b/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts
index 03c0ce7120..f3475f8cc0 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/direct-executor.ts
@@ -10,6 +10,7 @@ import * as inventoryFunctions from "~/modules/inventory/inventory.service";
import * as invoicingFunctions from "~/modules/invoicing/invoicing.service";
import * as itemsFunctions from "~/modules/items/items.service";
import * as peopleFunctions from "~/modules/people/people.service";
+import * as productionMcpFunctions from "~/modules/production/production.mcp.server";
import * as productionFunctions from "~/modules/production/production.service";
import * as purchasingFunctions from "~/modules/purchasing/purchasing.service";
import * as qualityFunctions from "~/modules/quality/quality.service";
@@ -34,7 +35,7 @@ const functionRegistry = {
invoicing: invoicingFunctions,
items: itemsFunctions,
people: peopleFunctions,
- production: productionFunctions,
+ production: { ...productionFunctions, ...productionMcpFunctions },
purchasing: purchasingFunctions,
quality: qualityFunctions,
resources: resourcesFunctions,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts
index 967a97fe2e..cc4f786547 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/mcp-blocked-tools.ts
@@ -11,7 +11,12 @@ export const MCP_BLOCKED_TOOL_NAMES: readonly string[] = [
// Their args require a userId the MCP executor cannot inject (AuthField has
// no such payload field), so direct calls would only ever fail validation.
"production_returnPickedRemaindersForOperation",
- "production_returnPickedRemaindersForJob"
+ "production_returnPickedRemaindersForJob",
+ // Ungated scheduling primitive: it fires the `schedule-job` Inngest event with
+ // no permission check of its own (every ERP route gates on `production` update
+ // before calling it). `production_scheduleJob` is the intended MCP entry point —
+ // it re-applies that gate — so the raw trigger must not be reachable via MCP.
+ "production_triggerJobSchedule"
];
export function isMcpBlockedTool(name: string): boolean {
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index b1218ea49c..2ea9fce239 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-08-25T14:49:54.249Z",
- "totalTools": 1448,
+ "generated": "2026-08-25T18:57:30.955Z",
+ "totalTools": 1447,
"modules": 15,
"tools": [
{
@@ -23337,38 +23337,6 @@
]
}
},
- {
- "name": "production_triggerJobSchedule",
- "module": "production",
- "classification": "WRITE",
- "description": "trigger job schedule",
- "paramCount": 3,
- "serviceParams": [
- "jobId",
- "companyId",
- "userId",
- "mode",
- "direction"
- ],
- "injectAuth": [
- "companyId"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "jobId": {
- "type": "string"
- },
- "mode": {},
- "direction": {}
- },
- "required": [
- "jobId",
- "mode",
- "direction"
- ]
- }
- },
{
"name": "production_getAssemblyInstruction",
"module": "production",
@@ -25269,6 +25237,37 @@
]
}
},
+ {
+ "name": "production_completeOperation",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "complete operation",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "userId",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "operationId": {
+ "type": "string"
+ },
+ "quantity": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "operationId",
+ "quantity"
+ ]
+ }
+ },
{
"name": "production_issueMaterial",
"module": "production",
@@ -25394,37 +25393,6 @@
]
}
},
- {
- "name": "production_completeOperation",
- "module": "production",
- "classification": "WRITE",
- "description": "complete operation",
- "paramCount": 2,
- "serviceParams": [
- "client",
- "companyId",
- "userId",
- "args"
- ],
- "injectAuth": [
- "companyId"
- ],
- "schema": {
- "type": "object",
- "properties": {
- "operationId": {
- "type": "string"
- },
- "quantity": {
- "type": "number"
- }
- },
- "required": [
- "operationId",
- "quantity"
- ]
- }
- },
{
"name": "purchasing_closePurchaseOrder",
"module": "purchasing",
diff --git a/packages/auth/src/services/users.ts b/packages/auth/src/services/users.ts
index 454b4feb29..c8d1e542b7 100644
--- a/packages/auth/src/services/users.ts
+++ b/packages/auth/src/services/users.ts
@@ -18,6 +18,21 @@ export function getPermissionCacheKey(userId: string) {
return `permissions:${userId}`;
}
+/**
+ * Does a resolved claims permission set grant `<module>_<action>` for the company?
+ * Honors the `"0"` all-companies wildcard, matching `requirePermissions`. `permissions`
+ * is the `permissions` field from `makePermissionsFromClaims` / `getUserClaims`.
+ */
+export function hasPermission(
+ permissions: Record<string, Permission> | null | undefined,
+ module: string,
+ action: keyof Permission,
+ companyId: string
+): boolean {
+ const scoped = permissions?.[module]?.[action];
+ return scoped?.some((c) => c === companyId || c === "0") ?? false;
+}
+
export async function getCompanies(
client: SupabaseClient<Database>,
userId: string
diff --git a/scripts/generate-mcp.ts b/scripts/generate-mcp.ts
index 936021ee80..cad6ec26b6 100644
--- a/scripts/generate-mcp.ts
+++ b/scripts/generate-mcp.ts
@@ -651,10 +651,20 @@ export function generateToolMetadata(): void {
serviceFile = eeServiceFile;
}
- const content = fs.readFileSync(serviceFile, "utf-8");
+ let content = fs.readFileSync(serviceFile, "utf-8");
const modelsContent = loadModelsContent(mod);
const functions = parseExportedFunctions(content);
+ // A module may expose MCP tools from a server-only companion file
+ // (`{mod}.mcp.server.ts`) when those functions must import `*.server`
+ // modules and therefore cannot live in the client-reachable service file.
+ const mcpServerFile = path.join(MODULES_DIR, mod, `${mod}.mcp.server.ts`);
+ if (fs.existsSync(mcpServerFile)) {
+ const mcpServerContent = fs.readFileSync(mcpServerFile, "utf-8");
+ content = `${content}\n${mcpServerContent}`;
+ functions.push(...parseExportedFunctions(mcpServerContent));
+ }
+
let toolCount = 0;
for (const func of functions) {