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.

feat(mcp): ranked catalog search, batch describe, JSDoc tool descriptions

Sidwebworks9eb8095c0ac1
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index 676a22f05e..0e6b6c0f1c 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -85,10 +85,42 @@ registered individually:
| Tool | Purpose |
|------|---------|
-| `search_tools` | Discover tool names. Filters: `query`, `module`, `classification` (`READ`/`WRITE`/`DESTRUCTIVE`), `limit`/`offset`. Reads `tool-metadata.json`. |
-| `describe_tool` | Return the JSON-Schema + classification + description for one tool name. |
+| `search_tools` | Relevance-ranked discovery (see "Catalog search" below). Filters: `query`, `module` (substring), `classification` (`READ`/`WRITE`/`DESTRUCTIVE`), `limit`/`offset`. |
+| `describe_tool` | Full contract for one `name` or up to 10 `names`: description, permission scope, list-op marker, input schema AND response schema. |
| `call_tool` | Execute any ERP tool: `{ name, arguments }`. `arguments` may arrive as a JSON string and is normalized to an object. |
+### Catalog search (`lib/catalog-search.ts`)
+
+`search_tools` runs BM25 full-text search via **zbsearch** (pnpm catalog dep;
+in-process, index built lazily once per process over `tool-metadata.json`),
+not substring filtering. The typed, tested logic lives OUTSIDE the
+`@ts-nocheck` server.ts:
+
+- Indexed fields with boosts: raw `name` (4), camelCase-split `tokens` (3),
+ `description` (1.5), schema property names `fields` (0.5) — so a query can
+ find a tool by a field it accepts (`unitPrice`). Prefix expansion is on;
+ when a query matches nothing, a second pass runs with `tolerance: 1`
+ (typo forgiveness) — the engine can't do both at once.
+- `SEARCH_ALIASES` expands domain abbreviations ADDITIVELY before the index
+ is queried (`rma`→return, `po`→purchase order, `shelf`→storage unit,
+ `bom`→method material, …). Curate it there; the original token always
+ still participates.
+- `module` keeps substring semantics ("sale" matches "sales") by resolving to
+ concrete names for the enum `where` filter. Filter-only calls (no `query`)
+ bypass the index and keep metadata order.
+- Output is one line per tool — `name [READ] (requiredParams, +N optional)`
+ (`formatParamSummary`, `lib/describe-format.ts`); the description line only
+ renders when it differs from the name-derived text
+ (`deriveNameDescription`). `describe_tool` output (`formatToolDescription`)
+ adds `Permission:` and, for list ops (`isListOperation`), the default page
+ size, plus the compact response schema when the generator derived one.
+- Server instructions live in `lib/instructions.ts` (module list + interpolated
+ `MCP_DEFAULT_LIMIT`), importable by tests without server.ts's auth/env chain.
+- Pinned by `lib/catalog-search.test.ts` and `lib/describe-format.test.ts`;
+ `lib/manifest.ts` carries its own copies of the meta-tool descriptions
+ (pinned >40 chars by `manifest.test.ts`) — keep them in sync with
+ `server.ts` by hand.
+
### Response formatting is token-lean BY CONTRACT (`lib/format-result.ts`)
MCP text responses deliberately differ from the HTTP API's exact data — the
@@ -271,6 +303,16 @@ exports into the same module namespace), and writes `apps/erp/app/routes/api+/mc
destructive-by-omission and the client must treat it as such; everything else →
`WRITE`. Drives the MCP annotations (`READ_ONLY_/WRITE_/DESTRUCTIVE_ANNOTATIONS`
in `lib/types.ts`).
+- **Description** precedence: a function-level **JSDoc** on the service export
+ (first sentence, `@tag`s stripped, trailing period removed, leading letter
+ lowercased unless it starts an acronym, capped ~160 chars —
+ `extractJsdocSummary` in `scripts/lib/service-metadata.ts`) beats the
+ `DESCRIPTION_OVERRIDES` table, which beats the de-camelCased name
+ (`generateDescription`). ~130 services already carry one. Descriptions flow
+ to the public OpenAPI `summary` and the docs pages (which capitalize and
+ append a period — hence the normalization), and are NOT part of the digest,
+ so a description change is invisible in review by design. Pinned by
+ `apps/erp/test/mcp-jsdoc-description.test.ts`.
- **injectAuth** (`computeInjectAuth`): keyed off the **name verb, not the
classification** — only `READ` takes `["companyId"]`. `upsert|create|insert|
add|new|copy|duplicate|generate*` → `["companyId","createdBy","updatedBy"]`;
diff --git a/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts b/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts
new file mode 100644
index 0000000000..ffd1f4ed31
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts
@@ -0,0 +1,154 @@
+import type { ManifestEntry } from "@carbon/api";
+import { describe, expect, test } from "vitest";
+import {
+ collectFieldNames,
+ createCatalogSearch,
+ expandQueryTerm,
+ splitWords
+} from "./catalog-search";
+import toolMetadata from "./tool-metadata.json";
+
+const tools = toolMetadata.tools as unknown as ManifestEntry[];
+const catalog = createCatalogSearch(tools);
+
+const page = { limit: 20, offset: 0 };
+
+describe("splitWords", () => {
+ test("splits camelCase and separators", () => {
+ expect(splitWords("getJobOperationsList")).toBe("get job operations list");
+ expect(splitWords("sales_getCustomers")).toBe("sales get customers");
+ expect(splitWords("HTMLParser")).toBe("html parser");
+ });
+});
+
+describe("expandQueryTerm", () => {
+ test("keeps the original tokens alongside camel-split words", () => {
+ const term = expandQueryTerm("getCustomers").split(" ");
+ expect(term).toContain("getcustomers");
+ expect(term).toContain("customers");
+ });
+
+ test("expands domain aliases additively", () => {
+ const term = expandQueryTerm("RMA status").split(" ");
+ expect(term).toContain("rma");
+ expect(term).toContain("return");
+ expect(term).toContain("status");
+ });
+});
+
+describe("collectFieldNames", () => {
+ test("walks nested objects, arrays and unions", () => {
+ const fields = collectFieldNames({
+ type: "object",
+ properties: {
+ id: { type: "string" },
+ lines: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: { unitPrice: { type: "number" } }
+ }
+ },
+ variant: {
+ anyOf: [{ type: "object", properties: { jobId: { type: "string" } } }]
+ }
+ }
+ });
+ expect([...fields].sort()).toEqual([
+ "id",
+ "jobId",
+ "lines",
+ "unitPrice",
+ "variant"
+ ]);
+ });
+});
+
+describe("catalog search", () => {
+ test("ranks the exact name match first", async () => {
+ const { matches } = await catalog.search({
+ query: "getCustomers",
+ ...page
+ });
+ expect(matches[0]?.name).toBe("sales_getCustomers");
+ });
+
+ test("multi-word queries do not require a contiguous substring", async () => {
+ const { matches, total } = await catalog.search({
+ query: "job operation",
+ ...page
+ });
+ expect(total).toBeGreaterThan(0);
+ expect(matches.some((t) => t.name.includes("JobOperation"))).toBe(true);
+ });
+
+ test("finds return tools for the RMA abbreviation", async () => {
+ const { matches } = await catalog.search({ query: "rma", ...page });
+ expect(matches.length).toBeGreaterThan(0);
+ expect(matches.some((t) => t.name.toLowerCase().includes("return"))).toBe(
+ true
+ );
+ });
+
+ test("finds storage units for the renamed shelf concept", async () => {
+ const { matches } = await catalog.search({ query: "shelf", ...page });
+ expect(matches.some((t) => t.name.includes("StorageUnit"))).toBe(true);
+ });
+
+ test("matches schema field names", async () => {
+ const { matches, total } = await catalog.search({
+ query: "supersession",
+ ...page
+ });
+ expect(total).toBeGreaterThan(0);
+ expect(matches.length).toBeGreaterThan(0);
+ });
+
+ test("second pass tolerates typos", async () => {
+ const { matches } = await catalog.search({ query: "cutomers", ...page });
+ expect(matches.some((t) => t.name.toLowerCase().includes("customer"))).toBe(
+ true
+ );
+ });
+
+ test("module filter keeps substring semantics", async () => {
+ const { total } = await catalog.search({ module: "sale", ...page });
+ expect(total).toBe(tools.filter((t) => t.module === "sales").length);
+ });
+
+ test("classification filter composes with a query", async () => {
+ const { matches } = await catalog.search({
+ query: "customer",
+ classification: "READ",
+ ...page
+ });
+ expect(matches.length).toBeGreaterThan(0);
+ expect(matches.every((t) => t.classification === "READ")).toBe(true);
+ });
+
+ test("unknown module filter returns nothing rather than everything", async () => {
+ const { matches, total } = await catalog.search({
+ module: "nope",
+ ...page
+ });
+ expect(matches).toEqual([]);
+ expect(total).toBe(0);
+ });
+
+ test("filter-only search keeps metadata order and paginates", async () => {
+ const first = await catalog.search({ limit: 3, offset: 0 });
+ expect(first.matches.map((t) => t.name)).toEqual(
+ tools.slice(0, 3).map((t) => t.name)
+ );
+ expect(first.total).toBe(tools.length);
+ });
+
+ test("query pagination pages ranked results without overlap", async () => {
+ const a = await catalog.search({ query: "customer", limit: 5, offset: 0 });
+ const b = await catalog.search({ query: "customer", limit: 5, offset: 5 });
+ const overlap = a.matches.filter((t) =>
+ b.matches.some((u) => u.name === t.name)
+ );
+ expect(overlap).toEqual([]);
+ });
+});
diff --git a/apps/erp/app/routes/api+/mcp+/lib/catalog-search.ts b/apps/erp/app/routes/api+/mcp+/lib/catalog-search.ts
new file mode 100644
index 0000000000..65a2772883
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/catalog-search.ts
@@ -0,0 +1,240 @@
+// Ranked full-text search over the tool catalog, extracted from server.ts so it
+// is typed and unit-testable. Backed by zbsearch (BM25 + prefix expansion) with
+// a curated alias layer in front — the engine knows nothing about ERP domain
+// vocabulary, so "RMA" reaching the returns tools is our job, not its.
+import type { Classification, ManifestEntry } from "@carbon/api";
+import { create, insertMultiple, search } from "zbsearch";
+
+/**
+ * Domain synonyms expanded into the query before it hits the index. Keys are
+ * single lowercase query tokens; values are the extra terms tried alongside
+ * them. Additive only — the original token still participates, so an alias can
+ * never hide an exact match. Keep entries defensible: each one maps an
+ * industry-standard term to Carbon's own naming.
+ */
+export const SEARCH_ALIASES: Record<string, string[]> = {
+ // documents & orders
+ po: ["purchase", "order"],
+ so: ["sales", "order"],
+ wo: ["job", "work", "order"],
+ rfq: ["quote"],
+ quotation: ["quote"],
+ quotations: ["quote"],
+ grn: ["receipt"],
+ receiving: ["receipt"],
+ // quality & engineering
+ ncr: ["nonconformance", "issue"],
+ ncrs: ["nonconformance", "issue"],
+ capa: ["issue", "action", "corrective"],
+ eco: ["change", "order", "engineering"],
+ ecn: ["change", "order"],
+ coc: ["certificate"],
+ rma: ["return"],
+ // items & methods
+ bom: ["method", "material"],
+ boms: ["method", "material"],
+ routing: ["method", "operation"],
+ routings: ["method", "operation"],
+ uom: ["unit", "of", "measure"],
+ sku: ["item", "part"],
+ // inventory ("shelf" was renamed to storage unit)
+ shelf: ["storage", "unit"],
+ shelves: ["storage", "unit"],
+ bin: ["storage", "unit"],
+ bins: ["storage", "unit"],
+ // parties
+ vendor: ["supplier"],
+ vendors: ["supplier"],
+ // accounting
+ ap: ["purchase", "invoice", "payable"],
+ ar: ["sales", "invoice", "receivable"],
+ gl: ["ledger", "account"],
+ // planning
+ mrp: ["planning", "requirement"],
+ wip: ["production", "job"]
+};
+
+/** "getJobOperationsList" / "sales_getCustomers" → "get job operations list". */
+export function splitWords(identifier: string): string {
+ return identifier
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
+ .replace(/[^a-zA-Z0-9]+/g, " ")
+ .trim()
+ .toLowerCase();
+}
+
+/** Every property key reachable in a JSON Schema, nested objects/arrays/unions included. */
+export function collectFieldNames(
+ schema: unknown,
+ out = new Set<string>()
+): Set<string> {
+ if (!schema || typeof schema !== "object") return out;
+ const node = schema as Record<string, unknown>;
+ if (node.properties && typeof node.properties === "object") {
+ for (const [key, value] of Object.entries(node.properties)) {
+ out.add(key);
+ collectFieldNames(value, out);
+ }
+ }
+ if (node.items) collectFieldNames(node.items, out);
+ for (const branch of ["anyOf", "oneOf", "allOf"]) {
+ const variants = node[branch];
+ if (Array.isArray(variants)) {
+ for (const variant of variants) collectFieldNames(variant, out);
+ }
+ }
+ return out;
+}
+
+/**
+ * Build the search term: the query's words (camelCase split AND raw, so
+ * "getCustomers" matches both the tokenized and the literal name) plus alias
+ * expansions. BM25 scores documents matching more of the terms higher, so the
+ * expansions never need to all hit.
+ */
+export function expandQueryTerm(query: string): string {
+ const words = new Set<string>();
+ for (const token of query.split(/[^a-zA-Z0-9]+/)) {
+ if (!token) continue;
+ words.add(token.toLowerCase());
+ for (const word of splitWords(token).split(" ")) {
+ if (word) words.add(word);
+ }
+ }
+ for (const word of [...words]) {
+ for (const alias of SEARCH_ALIASES[word] ?? []) {
+ words.add(alias);
+ }
+ }
+ return [...words].join(" ");
+}
+
+export type CatalogSearchOptions = {
+ query?: string;
+ module?: string;
+ classification?: Classification;
+ limit: number;
+ offset: number;
+};
+
+export type CatalogSearchResult = {
+ matches: ManifestEntry[];
+ total: number;
+};
+
+export type CatalogSearch = {
+ search: (options: CatalogSearchOptions) => Promise<CatalogSearchResult>;
+ moduleNames: string[];
+};
+
+function fieldWords(tool: ManifestEntry): string {
+ const words = new Set<string>();
+ for (const field of collectFieldNames(tool.schema)) {
+ for (const word of splitWords(field).split(" ")) {
+ if (word) words.add(word);
+ }
+ }
+ return [...words].join(" ");
+}
+
+const INDEX_SCHEMA = {
+ name: "string",
+ tokens: "string",
+ description: "string",
+ fields: "string",
+ module: "enum",
+ classification: "enum"
+} as const;
+
+async function buildIndex(tools: ManifestEntry[]) {
+ const db = create({ schema: INDEX_SCHEMA });
+ await insertMultiple(
+ db,
+ tools.map((tool) => ({
+ name: tool.name,
+ tokens: splitWords(tool.name),
+ description: tool.description,
+ fields: fieldWords(tool),
+ module: tool.module,
+ classification: tool.classification
+ }))
+ );
+ return db;
+}
+
+export function createCatalogSearch(tools: ManifestEntry[]): CatalogSearch {
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
+ const moduleNames = [...new Set(tools.map((tool) => tool.module))].sort();
+
+ // Built lazily on the first query so importing this module stays free.
+ let indexPromise: ReturnType<typeof buildIndex> | null = null;
+ const getIndex = () => (indexPromise ??= buildIndex(tools));
+
+ async function searchCatalog(
+ options: CatalogSearchOptions
+ ): Promise<CatalogSearchResult> {
+ const { query, module, classification, limit, offset } = options;
+
+ // The module filter keeps its historic substring semantics ("sale" matches
+ // "sales") by resolving to concrete module names for the enum filter.
+ let modules: string[] | null = null;
+ if (module) {
+ const needle = module.toLowerCase();
+ modules = moduleNames.filter((name) => name.includes(needle));
+ if (modules.length === 0) return { matches: [], total: 0 };
+ }
+
+ const term = query ? expandQueryTerm(query) : "";
+
+ if (!term) {
+ const filtered = tools.filter(
+ (tool) =>
+ (!modules || modules.includes(tool.module)) &&
+ (!classification || tool.classification === classification)
+ );
+ return {
+ matches: filtered.slice(offset, offset + limit),
+ total: filtered.length
+ };
+ }
+
+ const where: Record<string, unknown> = {};
+ if (modules) {
+ where.module =
+ modules.length === 1 ? { eq: modules[0] } : { in: modules };
+ }
+ if (classification) where.classification = { eq: classification };
+
+ const params = {
+ term,
+ properties: ["name", "tokens", "description", "fields"] as (
+ | "name"
+ | "tokens"
+ | "description"
+ | "fields"
+ )[],
+ boost: { name: 4, tokens: 3, description: 1.5, fields: 0.5 },
+ ...(Object.keys(where).length > 0 ? { where } : {}),
+ limit,
+ offset
+ };
+
+ const db = await getIndex();
+ let results = await search(db, params);
+ if (results.count === 0) {
+ // Prefix expansion and typo tolerance are mutually exclusive in the
+ // engine, so typos get a second pass rather than degrading every query.
+ results = await search(db, { ...params, tolerance: 1 });
+ }
+
+ return {
+ matches: results.hits
+ .map((hit) => byName.get((hit.document as { name: string }).name))
+ .filter((tool): tool is ManifestEntry => tool !== undefined),
+ total: results.count
+ };
+ }
+
+ return { search: searchCatalog, moduleNames };
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts b/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts
new file mode 100644
index 0000000000..7323d6f1ab
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts
@@ -0,0 +1,115 @@
+import type { ManifestEntry } from "@carbon/api";
+import { describe, expect, test } from "vitest";
+import {
+ deriveNameDescription,
+ formatParamSummary,
+ formatToolDescription
+} from "./describe-format";
+import { MCP_DEFAULT_LIMIT } from "./format-result";
+import { getServerInstructions } from "./instructions";
+import toolMetadata from "./tool-metadata.json";
+
+const baseTool: ManifestEntry = {
+ name: "sales_getCustomer",
+ module: "sales",
+ classification: "READ",
+ description: "get customer",
+ paramCount: 1,
+ serviceParams: ["client", "id"],
+ injectAuth: ["companyId"],
+ permission: { module: "sales", actions: ["view"] },
+ schema: {
+ type: "object",
+ properties: {
+ id: { type: "string" },
+ includeContacts: { type: "boolean" },
+ status: { type: "string" }
+ },
+ required: ["id"]
+ },
+ responseSchema: {
+ type: "object",
+ properties: { id: { type: "string" }, name: { type: "string" } }
+ }
+};
+
+describe("deriveNameDescription", () => {
+ test("mirrors the generator's name-derived description", () => {
+ expect(deriveNameDescription("sales_getCustomers")).toBe("get customers");
+ expect(deriveNameDescription("production_upsertJobMaterial")).toBe(
+ "upsert job material"
+ );
+ });
+});
+
+describe("formatParamSummary", () => {
+ test("spells out required params and counts optionals", () => {
+ expect(formatParamSummary(baseTool)).toBe("(id, +2 optional)");
+ });
+
+ test("renders an argless tool as empty parens", () => {
+ expect(
+ formatParamSummary({
+ ...baseTool,
+ schema: { type: "object", properties: {} }
+ })
+ ).toBe("()");
+ });
+});
+
+describe("formatToolDescription", () => {
+ test("prints the full contract including the response schema", () => {
+ const text = formatToolDescription(baseTool, { isList: false });
+ expect(text).toContain("Tool: sales_getCustomer");
+ expect(text).toContain("Permission: sales_view");
+ expect(text).toContain("Input Schema:\n{");
+ expect(text).toContain(
+ "Response Schema (null fields are omitted from results):"
+ );
+ expect(text).not.toContain("List operation:");
+ });
+
+ test("marks list operations with the default page size", () => {
+ const text = formatToolDescription(baseTool, { isList: true });
+ expect(text).toContain(
+ `List operation: pages with limit/offset (default limit ${MCP_DEFAULT_LIMIT})`
+ );
+ });
+
+ test("omits the permission line for key-only operations", () => {
+ const text = formatToolDescription(
+ { ...baseTool, permission: { module: null, actions: ["view"] } },
+ { isList: false }
+ );
+ expect(text).not.toContain("Permission:");
+ });
+
+ test("omits the response schema section when none was derived", () => {
+ const text = formatToolDescription(
+ { ...baseTool, responseSchema: undefined },
+ { isList: false }
+ );
+ expect(text).not.toContain("Response Schema");
+ });
+});
+
+describe("getServerInstructions", () => {
+ const instructions = getServerInstructions("2026-09-11");
+
+ test("lists every module name", () => {
+ const modules = [...new Set(toolMetadata.tools.map((t) => t.module))];
+ for (const module of modules) {
+ expect(instructions).toContain(module);
+ }
+ });
+
+ test("derives the default page size from the constant", () => {
+ expect(instructions).toContain(
+ `List reads default to ${MCP_DEFAULT_LIMIT} rows`
+ );
+ });
+
+ test("documents describe_tool batching", () => {
+ expect(instructions).toContain('names: ["sales_getCustomers"');
+ });
+});
diff --git a/apps/erp/app/routes/api+/mcp+/lib/describe-format.ts b/apps/erp/app/routes/api+/mcp+/lib/describe-format.ts
new file mode 100644
index 0000000000..afc4221ec3
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/describe-format.ts
@@ -0,0 +1,67 @@
+// Text formatting for describe_tool / search_tools output, extracted from the
+// @ts-nocheck server.ts so it is typed and unit-testable. Schemas print as
+// compact JSON on purpose — pretty-printing roughly doubles the whitespace
+// tokens and models parse compact JSON just as well.
+import type { ManifestEntry } from "@carbon/api";
+import { MCP_DEFAULT_LIMIT } from "./format-result";
+
+/**
+ * The description the generator derives from a bare tool name
+ * ("sales_getCustomers" → "get customers"). A tool whose description equals
+ * this carries no information beyond its name, so search output skips it.
+ */
+export function deriveNameDescription(name: string): string {
+ const separator = name.indexOf("_");
+ const func = separator === -1 ? name : name.slice(separator + 1);
+ return func
+ .replace(/([A-Z])/g, " $1")
+ .trim()
+ .toLowerCase();
+}
+
+/**
+ * One-line argument summary for search results: required params spelled out,
+ * optionals as a count — enough to call a simple tool without a describe round
+ * trip. "(id)" / "(jobId, _operation, +12 optional)" / "()".
+ */
+export function formatParamSummary(tool: ManifestEntry): string {
+ const schema = tool.schema as {
+ properties?: Record<string, unknown>;
+ required?: string[];
+ };
+ const properties = Object.keys(schema?.properties ?? {});
+ const required = Array.isArray(schema?.required)
+ ? schema.required.filter((name) => properties.includes(name))
+ : [];
+ const optionalCount = properties.length - required.length;
+ const parts = [...required];
+ if (optionalCount > 0) parts.push(`+${optionalCount} optional`);
+ return `(${parts.join(", ")})`;
+}
+
+/** Full describe_tool text for one tool. */
+export function formatToolDescription(
+ tool: ManifestEntry,
+ options: { isList: boolean }
+): string {
+ let output = `Tool: ${tool.name}\n`;
+ output += `Module: ${tool.module}\n`;
+ output += `Classification: ${tool.classification}\n`;
+ output += `Description: ${tool.description}\n`;
+ if (tool.permission.module) {
+ const scopes = tool.permission.actions
+ .map((action) => `${tool.permission.module}_${action}`)
+ .join(" or ");
+ output += `Permission: ${scopes} (required for API-key callers)\n`;
+ }
+ if (options.isList) {
+ output += `List operation: pages with limit/offset (default limit ${MCP_DEFAULT_LIMIT})\n`;
+ }
+ output += `\nInput Schema:\n${JSON.stringify(tool.schema ?? {})}`;
+ if (tool.responseSchema) {
+ output += `\n\nResponse Schema (null fields are omitted from results):\n${JSON.stringify(
+ tool.responseSchema
+ )}`;
+ }
+ return output;
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/instructions.ts b/apps/erp/app/routes/api+/mcp+/lib/instructions.ts
new file mode 100644
index 0000000000..b61bf87025
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/instructions.ts
@@ -0,0 +1,54 @@
+// The MCP server's connect-time instructions, in their own module so they are
+// testable without server.ts's import chain (callOperation → auth → env).
+import { MCP_DEFAULT_LIMIT } from "./format-result";
+import toolMetadata from "./tool-metadata.json";
+
+const MODULE_NAMES = [
+ ...new Set(toolMetadata.tools.map((tool) => tool.module))
+].sort();
+
+export function getServerInstructions(today: string): string {
+ return `Carbon ERP Manufacturing System
+==========================================
+Date: ${today}
+
+IMPORTANT: Tool Discovery System
+This server has ${toolMetadata.totalTools} tools available across ${toolMetadata.modules} modules:
+${MODULE_NAMES.join(", ")}
+
+To prevent context exhaustion, tools are loaded on-demand using call_tool.
+
+USAGE:
+1. Use search_tools to discover available tool names
+2. Use describe_tool to get the schema for one or more tools
+3. Use call_tool to execute any tool with its parameters
+
+EXAMPLES:
+// Step 1: Discover tools (ranked search; abbreviations like PO/RMA/BOM work)
+search_tools({ query: "customer" })
+// Returns tool names like: sales_getCustomers, sales_getCustomersList
+
+// Step 2 (optional): Get tool schemas — batch several names in one call
+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)
+call_tool({
+ name: "sales_getCustomers",
+ arguments: { args: { limit: 10 } }
+})
+
+SEARCH EXAMPLES:
+search_tools({ query: "customer" }) // Find customer-related tools
+search_tools({ module: "sales" }) // Find all sales module tools
+search_tools({ classification: "READ" }) // Find read-only tools
+
+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 ${MCP_DEFAULT_LIMIT} rows; pass limit/offset to page
+- Dates: ISO 8601 (YYYY-MM-DD)
+- Pagination: limit/offset`;
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/manifest.ts b/apps/erp/app/routes/api+/mcp+/lib/manifest.ts
index bbc88d9642..8dc9aedf05 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/manifest.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/manifest.ts
@@ -57,13 +57,13 @@ const TOOLS = [
{
name: "search_tools",
description:
- "Search Carbon's ERP operations by name, module or classification (READ, WRITE, DESTRUCTIVE), and make the matches available to call.",
+ "Relevance-ranked search over Carbon's ERP operations by keyword, module or classification (READ, WRITE, DESTRUCTIVE); understands common abbreviations and schema field names.",
readOnly: true
},
{
name: "describe_tool",
description:
- "Return the full input schema and description for one operation, so its arguments can be built correctly before calling it.",
+ "Return the full contract for one or more operations — description, permission, input schema and response schema — so arguments can be built correctly before calling.",
readOnly: true
},
{
diff --git a/apps/erp/app/routes/api+/mcp+/lib/server.ts b/apps/erp/app/routes/api+/mcp+/lib/server.ts
index 1e9a8ce25a..95dd523b00 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/server.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/server.ts
@@ -12,53 +12,18 @@ import {
operationsByName
} from "../../v1+/lib/operations.server";
import { formatMcpResult, MCP_DEFAULT_LIMIT } from "./format-result";
+import { createCatalogSearch } from "./catalog-search";
+import {
+ deriveNameDescription,
+ formatParamSummary,
+ formatToolDescription
+} from "./describe-format";
+import { getServerInstructions } from "./instructions";
const logger = getLogger("erp", "mcp");
-function getServerInstructions(today: string): string {
-
- return `Carbon ERP Manufacturing System
-==========================================
-Date: ${today}
-
-IMPORTANT: Tool Discovery System
-This server has ${toolMetadata.totalTools} tools available across ${toolMetadata.modules} modules.
-
-To prevent context exhaustion, tools are loaded on-demand using call_tool.
-
-USAGE:
-1. Use search_tools to discover available tool names
-2. Use describe_tool to get the schema for a specific tool
-3. Use call_tool to execute any tool with its parameters
-
-EXAMPLES:
-// Step 1: Discover tools
-search_tools({ query: "customer" })
-// Returns tool names like: sales_getCustomers, sales_getCustomersList
-
-// Step 2 (optional): Get tool schema
-describe_tool({ name: "sales_getCustomers" })
-
-// Step 3: Call the tool (arguments must be a JSON object, not a string)
-call_tool({
- name: "sales_getCustomers",
- arguments: { args: { limit: 10 } }
-})
-
-SEARCH EXAMPLES:
-search_tools({ query: "customer" }) // Find customer-related tools
-search_tools({ module: "sales" }) // Find all sales module tools
-search_tools({ classification: "READ" }) // Find read-only tools
-
-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`;
-}
+// One index for the process; createMcpServer runs per request.
+const catalogSearch = createCatalogSearch(toolMetadata.tools);
export function createMcpServer(ctx: McpContext, today: string): McpServer {
const server = new McpServer(
@@ -76,42 +41,57 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
server.registerTool(
"describe_tool",
{
- description: "Get the schema and description for a specific tool",
+ description: "Get the full contract for one or more tools: description, permission, input schema and response schema",
inputSchema: z.object({
- name: z.string().describe("The name of the tool to describe")
+ name: z.string().optional().describe("The name of the tool to describe"),
+ names: z
+ .array(z.string())
+ .max(10)
+ .optional()
+ .describe("Several tool names to describe in one call")
}),
annotations: READ_ONLY_ANNOTATIONS
},
withErrorHandling(async (params: any) => {
- const { name } = params;
-
- logger.info("describe_tool invoked", { name });
+ const { name, names } = params;
+ const requested: string[] = names?.length ? names : name ? [name] : [];
- // Find the tool in metadata
- const tool = toolMetadata.tools.find(t => t.name === name);
- if (!tool) {
- // A caller typo, not a server fault — warn, not error.
- logger.warn("Tool not found", { name });
+ logger.info("describe_tool invoked", { names: requested });
+
+ if (requested.length === 0) {
return {
- content: [{ type: "text" as const, text: `Tool '${name}' not found` }],
+ content: [{
+ type: "text" as const,
+ text: "Pass a tool `name` or a `names` array"
+ }],
isError: true
};
}
- // Tool schemas are provided via metadata, no need to load modules
-
- let output = `Tool: ${name}\n`;
- output += `Module: ${tool.module}\n`;
- 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 || {});
-
+ const sections: string[] = [];
+ const missing: string[] = [];
+ for (const toolName of requested) {
+ const meta = operationsByName.get(toolName);
+ if (!meta) {
+ missing.push(toolName);
+ continue;
+ }
+ sections.push(
+ formatToolDescription(meta, { isList: isListOperation(meta) })
+ );
+ }
+
+ if (missing.length > 0) {
+ // A caller typo, not a server fault — warn, not error.
+ logger.warn("Tool not found", { names: missing });
+ sections.push(
+ missing.map((toolName) => `Tool '${toolName}' not found`).join("\n")
+ );
+ }
+
return {
- content: [{ type: "text" as const, text: output }]
+ content: [{ type: "text" as const, text: sections.join("\n\n---\n\n") }],
+ ...(missing.length === requested.length ? { isError: true } : {})
};
}, "Describe tool failed")
);
@@ -227,9 +207,9 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
server.registerTool(
"search_tools",
{
- description: "Search for ERP tools and automatically make them available for use",
+ description: "Relevance-ranked search over ERP tools; understands common abbreviations (PO, RMA, BOM, NCR) and matches schema field names too",
inputSchema: z.object({
- query: z.string().optional().describe("Search in tool names/descriptions"),
+ query: z.string().optional().describe("Keywords to match against tool names, descriptions and schema field names"),
module: z.string().optional().describe("Filter by module name"),
classification: z.enum(["READ", "WRITE", "DESTRUCTIVE"]).optional(),
limit: z.number().int().min(1).max(100).default(20),
@@ -240,26 +220,16 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
withErrorHandling(async (params: any) => {
const { query, module, classification, limit = 20, offset = 0 } = params;
- let results = toolMetadata.tools;
-
- // Apply filters
- if (module) {
- results = results.filter(t => t.module.toLowerCase().includes(module.toLowerCase()));
- }
- if (classification) {
- results = results.filter(t => t.classification === classification);
- }
- if (query) {
- const q = query.toLowerCase();
- results = results.filter(t =>
- t.name.toLowerCase().includes(q) ||
- t.description.toLowerCase().includes(q) ||
- t.module.toLowerCase().includes(q)
- );
- }
-
- const foundTools = results.slice(offset, offset + limit);
- const toolNames = foundTools.map(t => t.name);
+ // BM25-ranked with alias expansion (see catalog-search.ts); filter-only
+ // calls keep metadata order.
+ const { matches, total } = await catalogSearch.search({
+ query,
+ module,
+ classification,
+ limit,
+ offset
+ });
+ const toolNames = matches.map(t => t.name);
logger.info("search_tools invoked", {
query,
@@ -267,47 +237,51 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
classification,
limit,
offset,
- matched: results.length,
+ matched: total,
returned: toolNames.length
});
// Build response
- let output = `Found ${results.length} tools`;
- if (results.length > limit) {
- output += ` (showing ${offset + 1}-${offset + foundTools.length})`;
+ let output = `Found ${total} tools`;
+ if (total > limit) {
+ output += ` (showing ${offset + 1}-${offset + matches.length}, ranked by relevance)`;
}
output += ":\n\n";
-
- // Group by module
- const byModule = new Map<string, typeof foundTools>();
- for (const tool of foundTools) {
+
+ // Group by module, preserving the ranked order within each group
+ const byModule = new Map<string, typeof matches>();
+ for (const tool of matches) {
if (!byModule.has(tool.module)) {
byModule.set(tool.module, []);
}
byModule.get(tool.module)!.push(tool);
}
-
- // Format results
+
+ // One line per tool: required args inline so simple tools need no
+ // describe round trip; the description only when it says more than the
+ // name does (today that means a hand-written override).
for (const [mod, tools] of byModule.entries()) {
output += `${mod.toUpperCase()} MODULE:\n`;
-
+
for (const tool of tools) {
- output += ` • ${tool.name} [${tool.classification}]\n`;
- output += ` ${tool.description}\n`;
+ output += ` • ${tool.name} [${tool.classification}] ${formatParamSummary(tool)}\n`;
+ if (tool.description !== deriveNameDescription(tool.name)) {
+ output += ` ${tool.description}\n`;
+ }
}
output += "\n";
}
-
+
// 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 }],
metadata: {
toolNames,
- totalResults: results.length
+ totalResults: total
}
};
}, "Search failed")
diff --git a/apps/erp/package.json b/apps/erp/package.json
index d355c0e865..9e9a68d262 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -137,6 +137,7 @@
"unified": "11.0.5",
"unist-util-visit": "5.1.0",
"use-stick-to-bottom": "1.1.3",
+ "zbsearch": "catalog:",
"zod": "catalog:",
"zod-form-data": "catalog:",
"zod-to-json-schema": "3.25.2",
diff --git a/apps/erp/test/mcp-jsdoc-description.test.ts b/apps/erp/test/mcp-jsdoc-description.test.ts
new file mode 100644
index 0000000000..3e81ac71e2
--- /dev/null
+++ b/apps/erp/test/mcp-jsdoc-description.test.ts
@@ -0,0 +1,61 @@
+// Pins the generator's function-level JSDoc → tool description extraction.
+// The unit cases exercise the summary normalizer directly; the integration
+// case proves the wiring against the generated manifest without pinning any
+// one function's prose (comments are free to change).
+import { describe, expect, test } from "vitest";
+import { extractJsdocSummary } from "../../../scripts/lib/service-metadata";
+import toolMetadata from "../app/routes/api+/mcp+/lib/tool-metadata.json";
+
+function nameDerived(name: string): string {
+ const func = name.slice(name.indexOf("_") + 1);
+ return func
+ .replace(/([A-Z])/g, " $1")
+ .trim()
+ .toLowerCase();
+}
+
+describe("extractJsdocSummary", () => {
+ test("takes the first sentence and strips the trailing period", () => {
+ expect(
+ extractJsdocSummary(
+ "\n * Customers with contact and payment terms. Prefer the list variant for dropdowns.\n "
+ )
+ ).toBe("customers with contact and payment terms");
+ });
+
+ test("ignores tag sections", () => {
+ expect(
+ extractJsdocSummary("\n * Resolves the swap.\n * @param client supabase\n ")
+ ).toBe("resolves the swap");
+ });
+
+ test("keeps a leading acronym's casing", () => {
+ expect(extractJsdocSummary(" MRP demand for one item. ")).toBe(
+ "MRP demand for one item"
+ );
+ });
+
+ test("returns undefined for tag-only or empty blocks", () => {
+ expect(extractJsdocSummary("\n * @deprecated use the other one\n ")).toBe(
+ undefined
+ );
+ expect(extractJsdocSummary(" \n * \n ")).toBe(undefined);
+ });
+
+ test("caps runaway summaries", () => {
+ const summary = extractJsdocSummary(`long ${"word ".repeat(80)}`);
+ expect(summary!.length).toBeLessThanOrEqual(160);
+ expect(summary!.endsWith("…")).toBe(true);
+ });
+});
+
+describe("generated manifest", () => {
+ test("carries JSDoc-derived descriptions, not only name-derived ones", () => {
+ const informative = toolMetadata.tools.filter(
+ (tool) => tool.description !== nameDerived(tool.name)
+ );
+ // ~130 service functions already carry a function-level JSDoc; if this
+ // drops to a handful the extraction wiring broke.
+ expect(informative.length).toBeGreaterThan(50);
+ });
+});
diff --git a/package.json b/package.json
index d6d4331c60..5477a5c9e1 100755
--- a/package.json
+++ b/package.json
@@ -84,6 +84,7 @@
],
"packageManager": "[email protected]",
"dependencies": {
+ "@carbon/api": "workspace:*",
"@opentelemetry/semantic-conventions": "1.40.0",
"@react-router/remix-routes-option-adapter": "catalog:",
"cookie": "catalog:",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 002d352238..992bf3e208 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -288,6 +288,9 @@ catalogs:
wait-on:
specifier: 7.2.0
version: 7.2.0
+ zbsearch:
+ specifier: 4.0.0
+ version: 4.0.0
zod:
specifier: 4.5.4
version: 4.5.4
@@ -357,6 +360,9 @@ importers:
.:
dependencies:
+ '@carbon/api':
+ specifier: workspace:*
+ version: link:packages/api
'@opentelemetry/semantic-conventions':
specifier: 1.40.0
version: 1.40.0
@@ -1020,6 +1026,9 @@ importers:
use-stick-to-bottom:
specifier: 1.1.3
version: 1.1.3([email protected])
+ zbsearch:
+ specifier: 'catalog:'
+ version: 4.0.0
zod:
specifier: 'catalog:'
version: 4.5.4
@@ -16644,6 +16653,10 @@ packages:
resolution: {integrity: sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==}
+ resolution: {integrity: sha512-gm4zfO31n2ZdruTTRQoWVWO4Q2+zrDt2GlrvIc+5JulRQNAm4IanCxER82vQ7Ug96FYkGqWUJBXFe1kGAcDWaQ==}
+ engines: {node: '>= 20.0.0'}
+
resolution: {integrity: sha512-1qXJ6hayyUr3TqxfXqmm5qwCa8f/mnG/o8Itcny03iFyrwX/dZkCwfCcYoJDyQP8RxEkycw0c/ldCJXBeaCstg==}
peerDependencies:
@@ -32339,6 +32352,8 @@ snapshots:
+
dependencies:
'@rvf/set-get': 7.0.2
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 526684a095..9613df0c6f 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -154,6 +154,7 @@ catalog:
vite-plugin-babel-macros: 1.0.6
vitest: 4.1.6
wait-on: 7.2.0
+ zbsearch: 4.0.0
zod: 4.5.4
zod-form-data: 3.0.3
zustand: 5.0.12
diff --git a/scripts/lib/service-metadata.ts b/scripts/lib/service-metadata.ts
index f730dd3e35..5391249465 100644
--- a/scripts/lib/service-metadata.ts
+++ b/scripts/lib/service-metadata.ts
@@ -143,6 +143,8 @@ interface ParsedParam {
interface ParsedFunction {
name: string;
params: ParsedParam[];
+ /** Body of a JSDoc block comment immediately preceding the export, if any. */
+ jsdoc?: string;
}
// ---------------------------------------------------------------------------
@@ -265,6 +267,41 @@ function destructuredParamName(raw: string, existing: ParsedParam[]): string {
return `${base}${i}`;
}
+/** The body of a JSDoc block whose closing marker directly precedes `index`. */
+function precedingJsdoc(content: string, index: number): string | undefined {
+ const before = content.slice(0, index);
+ const end = before.lastIndexOf("*/");
+ if (end === -1 || before.slice(end + 2).trim() !== "") return undefined;
+ const start = before.lastIndexOf("/**", end);
+ if (start === -1) return undefined;
+ return before.slice(start + 3, end);
+}
+
+/**
+ * Reduce a function-level JSDoc body to a one-line tool description: the prose
+ * before the first `@tag`, first sentence only, whitespace collapsed. The
+ * trailing period is stripped and the leading letter lowercased (unless it
+ * starts an acronym) to match the name-derived convention — the docs site
+ * capitalizes and appends its own period, so a sentence-cased summary would
+ * render doubled there.
+ */
+export function extractJsdocSummary(raw: string): string | undefined {
+ const prose = raw
+ .split("\n")
+ .map((line) => line.replace(/^\s*\*?\s?/, ""))
+ .join("\n");
+ const beforeTags = prose.split(/^\s*@\w/m)[0];
+ const text = beforeTags.replace(/\s+/g, " ").trim();
+ if (!text) return undefined;
+ const sentence = text.match(/^(.*?[.!?])(?:\s|$)/)?.[1] ?? text;
+ const normalized = sentence.replace(/[.!?]+$/, "").trim();
+ if (!normalized) return undefined;
+ const cased = /^[A-Z][a-z]/.test(normalized)
+ ? normalized.charAt(0).toLowerCase() + normalized.slice(1)
+ : normalized;
+ return cased.length > 160 ? `${cased.slice(0, 159).trimEnd()}…` : cased;
+}
+
function parseExportedFunctions(content: string): ParsedFunction[] {
const results: ParsedFunction[] = [];
const regex = /export\s+(?:async\s+)?function\s+(\w+)\s*\(/g;
@@ -272,12 +309,13 @@ function parseExportedFunctions(content: string): ParsedFunction[] {
while ((match = regex.exec(content)) !== null) {
const name = match[1];
+ const jsdoc = precedingJsdoc(content, match.index);
const openParen = match.index + match[0].length - 1;
const closeParen = findMatchingBrace(content, openParen);
const rawParams = content.substring(openParen + 1, closeParen).trim();
if (!rawParams) {
- results.push({ name, params: [] });
+ results.push({ name, params: [], jsdoc });
continue;
}
@@ -336,7 +374,7 @@ function parseExportedFunctions(content: string): ParsedFunction[] {
});
}
- results.push({ name, params });
+ results.push({ name, params, jsdoc });
}
return results;
@@ -1571,8 +1609,12 @@ export function buildAllToolMetadata(opts: BuildOptions = {}): ManifestEntry[] {
const injectAuth =
INJECT_AUTH_OVERRIDES[toolName] ||
computeInjectAuth(func.name, classification);
+ // A JSDoc on the function itself beats the override table (code closest
+ // wins); the de-camelCased name remains the fallback.
const description =
- DESCRIPTION_OVERRIDES[toolName] || generateDescription(func.name);
+ (func.jsdoc && extractJsdocSummary(func.jsdoc)) ||
+ DESCRIPTION_OVERRIDES[toolName] ||
+ generateDescription(func.name);
const serviceParams = func.params.map((p) => p.name);
const permission = derivePermission(
toolName,