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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(mcp): surface edge-function errors and accept the documented call shape
Raul7bfa5cacf2f3
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.mdindex 2c685f78f6..70fb61b989 100644--- a/.claude/rules/mcp-tools-reference.md+++ b/.claude/rules/mcp-tools-reference.md@@ -235,12 +235,19 @@ dispatcher (`apps/erp/app/routes/api+/inngest.ts`). There is no separatearg array: `client`/`userId`/`companyId`/`companyGroupId` come from `ctx`; aservice whose param is `db` is handed `getDatabaseClient()`; payload params arestamped with auth fields via `enrichWithAuthContext` (now in- `dispatch.server.ts`). 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+ `dispatch.server.ts`) — including `userId` when the payload itself declares one+ (the edge-function wrappers), which the manifest marks via `injectAuth` and the+ generator derives from the signature. Without it the service runs with no acting+ 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 isunwrapped; a flat schema means the body already IS the args object. A flat body- is still accepted either way. A param the schema declares as a **scalar** is- passed `undefined` when no key matches rather than being handed the whole+ 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 wholepayload object — that fallback made `deleteApiKey` run `.eq("id", {...})` andreturn `200 null`. Reading a key by the param's own name is likewise gated(`addressesWholeParam`): a service whose sole payload param is a destructureddiff --git a/apps/erp/app/routes/api+/mcp+/lib/instructions.ts b/apps/erp/app/routes/api+/mcp+/lib/instructions.tsindex b61bf87025..8f5e1ac826 100644--- a/apps/erp/app/routes/api+/mcp+/lib/instructions.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/instructions.ts@@ -32,10 +32,11 @@ search_tools({ query: "customer" })describe_tool({ name: "sales_getCustomers" })describe_tool({ names: ["sales_getCustomers", "sales_upsertCustomer"] })-// Step 3: Call the tool (arguments must be a JSON object, not a string)+// Step 3: Call the tool. The parameters go straight in "arguments" — the ones+// describe_tool lists, nothing wrapped around them.call_tool({name: "sales_getCustomers",- arguments: { args: { limit: 10 } }+ arguments: { limit: 10 }})SEARCH EXAMPLES:@@ -46,6 +47,8 @@ search_tools({ classification: "READ" }) // Find read-only toolsKEY PATTERNS:- companyId/userId are auto-filled- call_tool.arguments is always a JSON object (never a stringified JSON blob)+- Pass parameters flat in "arguments"; a legacy { args: {…} } envelope is still+ accepted, but describe_tool shows the shape to send- Responses: { data, error?, count? }- Results omit null fields — an absent field means null- List reads default to ${MCP_DEFAULT_LIMIT} rows; pass limit/offset to pagediff --git a/apps/erp/app/routes/api+/v1+/lib/call.server.ts b/apps/erp/app/routes/api+/v1+/lib/call.server.tsindex 081557ba99..62dce03b50 100644--- a/apps/erp/app/routes/api+/v1+/lib/call.server.ts+++ b/apps/erp/app/routes/api+/v1+/lib/call.server.ts@@ -5,6 +5,7 @@// the legacy executeFunction callers expect.import { call, ORPCError } from "@orpc/server";+import { getEdgeFunctionErrorMessage } from "~/utils/error";import { isMcpBlockedTool } from "../../mcp+/lib/mcp-blocked-tools";import type { AuthedContext } from "./base.server";import {@@ -23,6 +24,45 @@ export type CallResult =| { success: true; data: unknown; count?: number }| { success: false; error: string; errorKind: "database" | "execution" };+/**+ * The edge function's own message, for a `functions.invoke()` failure only. Null+ * for every other Supabase error — a PostgREST error carries a `message` too, and+ * reading it here would rewrite error text the parity tests pin byte for byte.+ */+async function edgeFunctionMessage(error: unknown): Promise<string | null> {+ const candidate = error as { name?: unknown; context?: unknown };+ if (candidate?.name !== "FunctionsHttpError" || !candidate.context)+ return null;+ const message = await getEdgeFunctionErrorMessage(error, "");+ 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,@@ -59,15 +99,16 @@ export async function callOperation(};}+ const callArgs = unwrapArgsEnvelope(+ meta,+ args as Record<string, unknown> | undefined+ );+try {// The handler shapes the HTTP body (bare single results, `{ results, count }`// lists); unshapeHttpBody reverses it so MCP/agent/workflow callers keep// DispatchResult semantics.- const body = await call(- procedure,- (args as Record<string, unknown> | undefined) ?? {},- { context }- );+ const body = await call(procedure, callArgs ?? {}, { context });const result = unshapeHttpBody(meta, body);return {success: true,@@ -80,11 +121,16 @@ export async function callOperation(? (err.data as { supabase?: unknown } | undefined)?.supabase: undefined;if (supabase) {- // A Supabase failure keeps MCP's exact `Database error:` text, raw error- // JSON included — the errorKind lets the formatter skip its `Error: ` prefix.+ // An edge-function failure carries its real message in an unread Response on+ // `context`, which JSON.stringify empties — every failure from "the process is+ // not batchable" to a missing field reached the caller as the same+ // `{"name":"FunctionsHttpError","context":{}}`. Unwrap it with the helper the+ // routes already use; anything else keeps the byte-exact legacy text, which+ // the dispatch parity tests assert.+ const edgeMessage = await edgeFunctionMessage(supabase);return {success: false,- error: `Database error: ${JSON.stringify(supabase)}`,+ error: `Database error: ${edgeMessage ?? JSON.stringify(supabase)}`,errorKind: "database"};}