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.

perf(mcp): cut response tokens — compact null-stripped results, default list limits, lean schemas

Sidwebworks4fc67789c5ae
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index caabf75004..8d924014a0 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -89,6 +89,32 @@ registered individually:
| `describe_tool` | Return the JSON-Schema + classification + description for one tool name. |
| `call_tool` | Execute any ERP tool: `{ name, arguments }`. `arguments` may arrive as a JSON string and is normalized to an object. |
+### Response formatting is token-lean BY CONTRACT (`lib/format-result.ts`)
+
+MCP text responses deliberately differ from the HTTP API's exact data — the
+HTTP/agent/workflow callers of `callOperation` are untouched:
+
+- `call_tool` results are COMPACT JSON with **null fields omitted** (an absent
+ field means null — stated in the server instructions) via `formatMcpResult`.
+ Top-level arrays are hard-capped at `MCP_MAX_ROWS` (100) with an explicit
+ "… N more rows omitted" marker — the backstop for the unpaginated `get*List`
+ (fetchAll) operations. A paginated read short of its total appends
+ `(showing R of C rows)` from the envelope's `count`.
+- `call_tool` INJECTS the pagination PAIR — `limit: MCP_DEFAULT_LIMIT` (25) AND
+ `offset: 0` — into a **list operation's** args for whichever of the two the
+ caller omits (`isListOperation` on the manifest entry; both the flat body and
+ the `{ args: {...} }` wrapper, and the argless call). The pair matters:
+ `setGenericQueryFilters` applies its `.range()` only when BOTH are integers,
+ so a bare `limit` (injected or caller-supplied) silently paginated nothing
+ and an argless list read returned up to PostgREST's 1000-row cap.
+- `describe_tool` prints the schema compactly, and the generator strips
+ `pattern` wherever a sibling `format` exists (`stripRedundantPatterns` —
+ zod's email conversion emits a ~200-char regex next to `format: "email"`).
+ Pinned by `mcp-tool-metadata.test.ts` ("never publishes pattern alongside
+ format") and `format-result.test.ts`.
+- `search_tools` returns just the grouped list — the old how-to footer
+ duplicated the server instructions and re-listed every name a second time.
+
## How `call_tool` actually runs a tool (the canonical oRPC dispatch)
`call_tool` does **not** go back through the MCP protocol — it calls
@@ -306,3 +332,18 @@ exports into the same module namespace), and writes `apps/erp/app/routes/api+/mc
and `registry.server.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`.
+- **A same-named `{module}.mcp.server.ts` export SHADOWS the service function** —
+ the generator dedupes by name (mcp wins, matching the runtime registry spread),
+ so an orchestration wrapper can replace a bare service function without
+ renaming the published tool. Precedent: `upsertJobMaterial` — the ROUTES run
+ the requirements recalc themselves (`recalculateJobMakeMethodRequirements`,
+ which fills `estimatedQuantity`; the generated `quantityToIssue` derives from
+ it), so a connector call to the bare service left every imported material at
+ estimatedQuantity 0 and issue/picking pulled nothing. The wrapper mirrors both
+ routes' orchestration (MTO method pull on transition, recalc released creates /
+ all updates) and keeps the exact service payload type so the published schema
+ hash is unchanged. Body scans (classification, `_operation`) read the FIRST
+ match in the concatenated content — the service body — so a wrapper must keep
+ the same discriminator convention as the function it shadows. Pinned by
+ `mcp-upsert-job-material.test.ts` and the "registers a shadowed mcp.server
+ function exactly once" case in `mcp-tool-metadata.test.ts`.
diff --git a/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts b/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts
new file mode 100644
index 0000000000..07a5f77df6
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import { formatMcpResult, MCP_MAX_ROWS, stripNulls } from "./format-result";
+
+describe("stripNulls", () => {
+ it("drops null and undefined object entries, recursively", () => {
+ expect(
+ stripNulls({
+ id: "a",
+ fax: null,
+ customFields: undefined,
+ nested: { workPhone: null, name: "x" }
+ })
+ ).toEqual({ id: "a", nested: { name: "x" } });
+ });
+
+ it("keeps array elements positionally and empty values", () => {
+ expect(stripNulls([1, null, { a: null, b: "" }])).toEqual([
+ 1,
+ null,
+ { b: "" }
+ ]);
+ expect(stripNulls({ tags: [], notes: "" })).toEqual({
+ tags: [],
+ notes: ""
+ });
+ });
+});
+
+describe("formatMcpResult", () => {
+ it("serializes compactly with nulls stripped", () => {
+ const text = formatMcpResult([{ id: "a", fax: null }]);
+ expect(text).toBe('[{"id":"a"}]');
+ });
+
+ it("caps rows at MCP_MAX_ROWS with an omission marker", () => {
+ const rows = Array.from({ length: MCP_MAX_ROWS + 40 }, (_, i) => ({
+ id: i
+ }));
+ const text = formatMcpResult(rows);
+ expect(text).toContain('{"id":0}');
+ expect(text).not.toContain(`{"id":${MCP_MAX_ROWS}}`);
+ expect(text).toContain("… 40 more rows omitted");
+ });
+
+ it("appends the count line when the read was paginated short", () => {
+ const text = formatMcpResult([{ id: "a" }], 240);
+ expect(text).toContain("(showing 1 of 240 rows)");
+ });
+
+ it("omits the count line when everything was returned", () => {
+ expect(formatMcpResult([{ id: "a" }], 1)).toBe('[{"id":"a"}]');
+ });
+});
diff --git a/apps/erp/app/routes/api+/mcp+/lib/format-result.ts b/apps/erp/app/routes/api+/mcp+/lib/format-result.ts
new file mode 100644
index 0000000000..9cb6b327ee
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/format-result.ts
@@ -0,0 +1,56 @@
+// call_tool result formatting for the MCP surface ONLY — the HTTP API, the
+// in-app agent, and the workflow dispatcher consume callOperation's structured
+// data untouched. Everything here trades bytes for nothing an agent needs:
+// compact JSON (indentation roughly doubles whitespace tokens on row arrays),
+// null-stripped rows (an ERP row is ~half null columns), and a hard row cap as
+// a backstop for the unpaginated `get*List` operations that ignore `limit`.
+
+/** Injected into list-operation args when the caller passes no `limit`. */
+export const MCP_DEFAULT_LIMIT = 25;
+
+/** Backstop cap on serialized rows, for operations that cannot page. */
+export const MCP_MAX_ROWS = 100;
+
+/**
+ * Drop null/undefined OBJECT ENTRIES recursively. Array elements are kept
+ * positionally (a null element may be meaningful; a null field is just an
+ * unset column). Documented to agents in the server instructions: an absent
+ * field reads as null.
+ */
+export function stripNulls(value: unknown): unknown {
+ if (Array.isArray(value)) {
+ return value.map(stripNulls);
+ }
+ if (value !== null && typeof value === "object") {
+ const out: Record<string, unknown> = {};
+ for (const [key, entry] of Object.entries(value)) {
+ if (entry === null || entry === undefined) continue;
+ out[key] = stripNulls(entry);
+ }
+ return out;
+ }
+ return value;
+}
+
+/**
+ * Serialize a call_tool result for the MCP text response. `count` is the
+ * operation's total-row count when the read was paginated — surfaced so an
+ * agent pages deliberately instead of assuming it saw everything.
+ */
+export function formatMcpResult(data: unknown, count?: number): string {
+ let rows = data;
+ let omitted = 0;
+ if (Array.isArray(data) && data.length > MCP_MAX_ROWS) {
+ rows = data.slice(0, MCP_MAX_ROWS);
+ omitted = data.length - MCP_MAX_ROWS;
+ }
+
+ let text = JSON.stringify(stripNulls(rows));
+ if (omitted > 0) {
+ text += `\n… ${omitted} more rows omitted — pass limit/offset to page, or use a more specific tool`;
+ }
+ if (typeof count === "number" && Array.isArray(data) && count > data.length) {
+ text += `\n(showing ${Array.isArray(rows) ? rows.length : data.length} of ${count} rows)`;
+ }
+ return text;
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/server.ts b/apps/erp/app/routes/api+/mcp+/lib/server.ts
index 6a841ffaa5..e4713e6171 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/server.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/server.ts
@@ -7,6 +7,11 @@ import { withErrorHandling, READ_ONLY_ANNOTATIONS, WRITE_ANNOTATIONS } from "./t
import toolMetadata from "./tool-metadata.json";
import { isMcpBlockedTool } from "./mcp-blocked-tools";
import { callOperation } from "../../v1+/lib/call.server";
+import {
+ isListOperation,
+ operationsByName
+} from "../../v1+/lib/operations.server";
+import { formatMcpResult, MCP_DEFAULT_LIMIT } from "./format-result";
const logger = getLogger("erp", "mcp");
@@ -49,6 +54,8 @@ KEY PATTERNS:
- companyId/userId are auto-filled
- call_tool.arguments is always a JSON object (never a stringified JSON blob)
- Responses: { data, error?, count? }
+- Results omit null fields — an absent field means null
+- List reads default to 25 rows; pass limit/offset to page
- Dates: ISO 8601 (YYYY-MM-DD)
- Pagination: limit/offset`;
}
@@ -99,8 +106,10 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
output += `Classification: ${tool.classification}\n`;
output += `Description: ${tool.description}\n\n`;
+ // Compact on purpose — pretty-printing roughly doubles the whitespace
+ // tokens of a schema, and models parse compact JSON just as well.
output += `Input Schema:\n`;
- output += JSON.stringify(tool.schema || {}, null, 2);
+ output += JSON.stringify(tool.schema || {});
return {
content: [{ type: "text" as const, text: output }]
@@ -147,6 +156,39 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
};
}
+ // List reads apply no limit unless the caller passes one (the schema's
+ // `default: 100` is documentation, not enforcement — an argless call
+ // returned up to PostgREST's 1000-row cap). Inject a modest default so
+ // agents page deliberately; MCP-only, the other callOperation callers
+ // (HTTP, agent, workflows) are untouched. Unknown keys are inert for
+ // list-shaped ops that don't page, so injecting unconditionally is safe.
+ // setGenericQueryFilters applies its `.range()` only when BOTH limit and
+ // offset are integers, so the pair is always filled together — a bare
+ // `limit` (injected OR caller-supplied) would silently paginate nothing.
+ const fillPagination = (target: Record<string, unknown>) => {
+ if (target.limit === undefined) target.limit = MCP_DEFAULT_LIMIT;
+ if (target.offset === undefined) target.offset = 0;
+ };
+ const meta = operationsByName.get(name);
+ if (meta && isListOperation(meta)) {
+ if (args === undefined || args === null) {
+ // The argless call is the worst offender — no limit at all.
+ args = { limit: MCP_DEFAULT_LIMIT, offset: 0 };
+ } else if (typeof args === "object" && !Array.isArray(args)) {
+ const body = args as Record<string, unknown>;
+ const wrapped = body.args;
+ if (
+ wrapped &&
+ typeof wrapped === "object" &&
+ !Array.isArray(wrapped)
+ ) {
+ fillPagination(wrapped as Record<string, unknown>);
+ } else {
+ fillPagination(body);
+ }
+ }
+ }
+
// Runs through the canonical oRPC dispatch (gate middleware included); the
// Supabase envelope arrives already unwrapped to `data`/`count`.
const result = await callOperation(name, ctx, args);
@@ -161,7 +203,7 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
const output =
result.data === undefined
? "Operation completed successfully"
- : JSON.stringify(result.data, null, 2);
+ : formatMcpResult(result.data, result.count);
return { content: [{ type: "text" as const, text: output }] };
}
logger.error("Tool execution failed", { error: result.error });
@@ -246,23 +288,10 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
output += "\n";
}
- // Add instructions for using call_tool
- if (toolNames.length > 0) {
- output += `\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
- output += `To use these tools:\n`;
- output += `1. Use describe_tool({ name: "tool_name" }) to see the schema\n`;
- output += `2. Use call_tool({ name: "tool_name", arguments: {...} })\n\n`;
- output += `Example:\n`;
- output += `call_tool({ \n`;
- output += ` name: "${toolNames[0]}",\n`;
- output += ` arguments: { /* tool parameters */ }\n`;
- output += `})\n`;
- output += `\nAvailable tools:\n`;
- output += toolNames.map(name => ` • ${name}`).join('\n');
- output += `\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
- }
-
- output += `\nSTATUS: ${toolMetadata.totalTools} tools available via call_tool`;
+ // No usage footer: the describe_tool/call_tool how-to ships once in the
+ // server instructions at connect, and re-listing the names duplicated
+ // the grouped list above on every search.
+ output += `STATUS: ${toolMetadata.totalTools} tools available via call_tool`;
return {
content: [{ type: "text" as const, text: output }],
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 dc00c0b8f2..fb785340dc 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
@@ -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":"a4238ea3fb56","injectAuth":"companyId","permission":"inventory:view"},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"dc7546a2e5ad","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"},
@@ -293,7 +293,7 @@
{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":9,"schema":"893e85262ecf","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update"},
{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update"},
{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"a9944c8799d0","response":"none","injectAuth":"companyId","permission":"invoicing:update"},
- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"d8bb760d2850","injectAuth":"companyId","permission":"invoicing:view"},
+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"dc7546a2e5ad","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view"},
{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create"},
{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create"},
@@ -393,7 +393,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":"a4238ea3fb56","injectAuth":"companyId","permission":"parts:view"},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"dc7546a2e5ad","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"},
@@ -580,7 +580,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":"6752ec5720d7","injectAuth":"companyId","permission":"people:view"},
+ {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"7dd467066555","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"},
@@ -768,11 +768,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":"a4238ea3fb56","injectAuth":"companyId","permission":"production:update"},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"dc7546a2e5ad","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":"ba6a256056b4","injectAuth":"companyId","permission":"production:update"},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"133d83f1706f","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"},
@@ -923,7 +923,7 @@
{"name":"purchasing_insertPurchaseOrder","classification":"WRITE","paramCount":15,"schema":"27513cc48e8d","response":"f5212679d580","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create"},
{"name":"purchasing_insertPurchasingRFQ","classification":"WRITE","paramCount":8,"schema":"cb4ec49c926e","response":"0c1a1b93cca3","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create"},
{"name":"purchasing_insertSupplier","classification":"WRITE","paramCount":9,"schema":"2ec780d8d3b7","response":"9d2416e8ad75","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create"},
- {"name":"purchasing_insertSupplierContact","classification":"WRITE","paramCount":4,"schema":"14739cbcfbcc","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create"},
+ {"name":"purchasing_insertSupplierContact","classification":"WRITE","paramCount":4,"schema":"987f8dd2f02d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create"},
{"name":"purchasing_insertSupplierInteraction","classification":"WRITE","paramCount":1,"schema":"67043a31b1b5","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create"},
{"name":"purchasing_insertSupplierLocation","classification":"WRITE","paramCount":4,"schema":"c903cae736f0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create"},
{"name":"purchasing_insertSupplierQuote","classification":"WRITE","paramCount":13,"schema":"aa8560bfb767","response":"77e21c1e2e32","injectAuth":"companyId+createdBy+updatedBy","permission":"purchasing:create"},
@@ -940,7 +940,7 @@
{"name":"purchasing_updatePurchasingRFQLineOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"none","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
{"name":"purchasing_updatePurchasingRFQStatus","classification":"WRITE","paramCount":3,"schema":"8dc0490a9402","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
{"name":"purchasing_updateSupplierAccounting","classification":"WRITE","paramCount":2,"schema":"00634b037a3e","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
- {"name":"purchasing_updateSupplierContact","classification":"WRITE","paramCount":4,"schema":"151f3d45ba52","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
+ {"name":"purchasing_updateSupplierContact","classification":"WRITE","paramCount":4,"schema":"f6b4a36788e6","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
{"name":"purchasing_updateSupplierLocation","classification":"WRITE","paramCount":4,"schema":"9d205b68ee4f","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
{"name":"purchasing_updateSupplierPayment","classification":"WRITE","paramCount":5,"schema":"fb1e83d5ea1d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
{"name":"purchasing_updateSupplierQuote","classification":"WRITE","paramCount":8,"schema":"64e0b2d29d98","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"purchasing:update"},
@@ -1259,7 +1259,7 @@
{"name":"sales_getSalesRFQLines","classification":"READ","paramCount":1,"schema":"1f7e47a99145","response":"17f5b7f57e4c","injectAuth":"companyId","permission":"sales:view"},
{"name":"sales_getSalesRFQs","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"cb436531316b","injectAuth":"companyId","permission":"sales:view"},
{"name":"sales_getSalesTerms","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"9819ae68df9b","injectAuth":"companyId","permission":"sales:view"},
- {"name":"sales_insertCustomerContact","classification":"WRITE","paramCount":4,"schema":"19b4d491ac64","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create"},
+ {"name":"sales_insertCustomerContact","classification":"WRITE","paramCount":4,"schema":"c5775e935035","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create"},
{"name":"sales_insertCustomerLocation","classification":"WRITE","paramCount":4,"schema":"c30fcaea26e0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create"},
{"name":"sales_insertQuote","classification":"WRITE","paramCount":16,"schema":"a6c40455c9f1","response":"9e29b49e1dc8","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create"},
{"name":"sales_insertSalesOrder","classification":"WRITE","paramCount":17,"schema":"b76b79d52d88","response":"dbfc22813350","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create"},
@@ -1272,7 +1272,7 @@
{"name":"sales_resolvePurchaseToOrderPrices","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update"},
{"name":"sales_resolveQuoteLinePrices","classification":"WRITE","paramCount":3,"schema":"160e0d2cf116","response":"af602e7b257e","injectAuth":"companyId","permission":"sales:update"},
{"name":"sales_updateCustomerAccounting","classification":"WRITE","paramCount":2,"schema":"165c42d97441","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update"},
- {"name":"sales_updateCustomerContact","classification":"WRITE","paramCount":4,"schema":"d9d3a980dbfa","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update"},
+ {"name":"sales_updateCustomerContact","classification":"WRITE","paramCount":4,"schema":"f0fc7be0eef2","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update"},
{"name":"sales_updateCustomerLocation","classification":"WRITE","paramCount":4,"schema":"9d205b68ee4f","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update"},
{"name":"sales_updateCustomerPayment","classification":"WRITE","paramCount":5,"schema":"f4b0bf1f4ec1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update"},
{"name":"sales_updateCustomerShipping","classification":"WRITE","paramCount":7,"schema":"1c4be8a465fb","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update"},
@@ -1365,10 +1365,10 @@
{"name":"settings_resolveSections","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"9cf53d9645e3","injectAuth":"companyId","permission":"settings:update"},
{"name":"settings_updateAccountingEnabledSetting","classification":"WRITE","paramCount":1,"schema":"82d5e14a67e0","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
{"name":"settings_updateAccountsPayableAddressSetting","classification":"WRITE","paramCount":1,"schema":"7a679bb0d746","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
- {"name":"settings_updateAccountsPayableBillingAddress","classification":"WRITE","paramCount":10,"schema":"e8f633d64584","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
+ {"name":"settings_updateAccountsPayableBillingAddress","classification":"WRITE","paramCount":10,"schema":"1d9ef8425567","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
{"name":"settings_updateAccountsPayableEmail","classification":"WRITE","paramCount":1,"schema":"5ea2ba22400c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
{"name":"settings_updateAccountsReceivableAddressSetting","classification":"WRITE","paramCount":1,"schema":"aee1361e5321","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
- {"name":"settings_updateAccountsReceivableBillingAddress","classification":"WRITE","paramCount":10,"schema":"e8f633d64584","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
+ {"name":"settings_updateAccountsReceivableBillingAddress","classification":"WRITE","paramCount":10,"schema":"1d9ef8425567","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
{"name":"settings_updateAccountsReceivableEmail","classification":"WRITE","paramCount":1,"schema":"0bd52dc112c3","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
{"name":"settings_updateAllowLowercaseItemIdsSetting","classification":"WRITE","paramCount":1,"schema":"4bfa8b2e5538","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
{"name":"settings_updateAssetTaxDepreciationSettings","classification":"WRITE","paramCount":2,"schema":"6decaad55e9c","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"settings:update"},
diff --git a/apps/erp/test/mcp-tool-metadata.test.ts b/apps/erp/test/mcp-tool-metadata.test.ts
index da17c7081a..6165394463 100644
--- a/apps/erp/test/mcp-tool-metadata.test.ts
+++ b/apps/erp/test/mcp-tool-metadata.test.ts
@@ -108,6 +108,44 @@ describe("mcp tool-metadata generator", () => {
expect(insertContact?.required ?? []).not.toContain("email");
});
+ // zod's email conversion emits a ~200-char `pattern` next to
+ // `format: "email"` on every email field — the format keyword carries the
+ // contract; the regex is stripped to keep describe_tool responses lean.
+ it("never publishes pattern alongside format", () => {
+ const walk = (node: unknown, path: string): void => {
+ if (Array.isArray(node)) {
+ node.forEach((item, i) => walk(item, `${path}[${i}]`));
+ return;
+ }
+ if (node !== null && typeof node === "object") {
+ const record = node as Record<string, unknown>;
+ if (typeof record.format === "string") {
+ expect(record.pattern, path).toBeUndefined();
+ }
+ for (const [key, value] of Object.entries(record)) {
+ walk(value, `${path}.${key}`);
+ }
+ }
+ };
+ for (const t of tools) walk(t.schema, t.name);
+ // The format itself survives the strip.
+ const email = props(get("sales_insertCustomerContact")).contact?.properties
+ ?.email;
+ expect(email?.format).toBe("email");
+ });
+
+ // A `{mod}.mcp.server.ts` export that shares a service function's name
+ // SHADOWS it — one tool, the wrapper's implementation, the same published
+ // name/schema. Without the generator dedupe the tool appeared twice.
+ it("registers a shadowed mcp.server function exactly once", () => {
+ const entries = tools.filter(
+ (t) => t.name === "production_upsertJobMaterial"
+ );
+ expect(entries).toHaveLength(1);
+ // The wrapper keeps the service's discriminated-upsert contract.
+ expect(props(entries[0]!)._operation?.enum).toEqual(["create", "update"]);
+ });
+
// A parenthesized discriminated-upsert union branch resolves instead of
// publishing an opaque {} member (and the leading-pipe union style must not
// contribute an empty first member).
diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.ts
index daaa84fde1..2b9c80f573 100644
--- a/scripts/lib/service-metadata.ts
+++ b/scripts/lib/service-metadata.ts
@@ -1189,6 +1189,27 @@ function stripComments(source: string): string {
.replace(/(^|[^:])\/\/.*$/gm, "$1");
}
+/**
+ * Delete `pattern` wherever a sibling `format` is present, recursively. zod
+ * v4's email conversion emits BOTH — `format: "email"` plus a ~200-character
+ * regex — on every email field of every validator-derived schema. The format
+ * keyword carries the same contract for a fraction of the tokens, and MCP
+ * clients read these schemas far more often than they validate against them.
+ */
+function stripRedundantPatterns(node: unknown): void {
+ if (Array.isArray(node)) {
+ for (const item of node) stripRedundantPatterns(item);
+ return;
+ }
+ if (node !== null && typeof node === "object") {
+ const record = node as Record<string, unknown>;
+ if (typeof record.format === "string" && "pattern" in record) {
+ delete record.pattern;
+ }
+ for (const value of Object.values(record)) stripRedundantPatterns(value);
+ }
+}
+
function addOperationArg(schema: Record<string, unknown>): void {
const properties = (schema.properties ?? {}) as Record<string, unknown>;
properties._operation = {
@@ -1453,7 +1474,19 @@ export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {
if (fs.existsSync(mcpServerFile)) {
const mcpServerContent = fs.readFileSync(mcpServerFile, "utf-8");
content = `${content}\n${mcpServerContent}`;
- functions.push(...parseExportedFunctions(mcpServerContent));
+ // A same-named mcp.server export SHADOWS the service one — matching the
+ // runtime registry, where the mcp.server spread wins — so an orchestration
+ // wrapper can replace a bare service function without renaming the
+ // published tool. Its PARAMS come from the wrapper; note that body scans
+ // (classification, the `_operation` discriminator) read the FIRST match in
+ // the concatenated content, i.e. the service body — a wrapper must keep
+ // the same discriminator convention as the function it shadows.
+ const mcpFunctions = parseExportedFunctions(mcpServerContent);
+ const shadowed = new Set(mcpFunctions.map((f) => f.name));
+ for (let i = functions.length - 1; i >= 0; i--) {
+ if (shadowed.has(functions[i].name)) functions.splice(i, 1);
+ }
+ functions.push(...mcpFunctions);
}
// Sources searched when a param references a bare type alias, most
@@ -1494,6 +1527,7 @@ export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {
onResolved: (validatorName, how) =>
opts.onValidatorResolved?.(toolName, validatorName, how),
});
+ stripRedundantPatterns(schema);
if (
injectAuth.includes("createdBy") &&
usesOperationDiscriminator(content, func.name)