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 search results and a shorter describe_tool header

Sidwebworks615050497f53
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index f835d284af..46309ea9fc 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -214,9 +214,17 @@ the manifest.
because it matches the expanded term, not the query. `stemInflection` leaves
"materials" unstemmed, so `sameWord` also accepts a plain -s/-es plural.
- `module` keeps substring semantics; filter-only calls bypass the index.
-- One line per tool: `name [READ] (requiredParams, +N optional)`
- (`formatParamSummary`, `describe-format.ts`), plus the description's first
- paragraph when it says more than the name (`searchLineDescription`).
+- `search_tools` output (`formatSearchResults`, `describe-format.ts`): one
+ line per tool in rank order, `name [READ] (requiredParams, +N optional)`
+ (`formatParamSummary`), plus ` — ` and the description's first paragraph when
+ it says more than the name (`searchLineDescription`; case, a closing full
+ stop and articles do not count, and 937 of 1,612 summaries only restate the
+ name). Results are not grouped by module: grouping put lower-ranked tools
+ above better ones, and the name already carries the module. A page short of
+ the total names the next offset.
+- `describe_tool` (`formatToolDescription`) opens with `name [CLASS]`, the
+ description, and `Permission:` (the gate checks it for every caller, not only
+ API keys).
- `describe_tool` prints input and response schemas as TypeScript types
(`formatSchemaType`): the manifest's schemas use only type, enum, anyOf,
properties, required, items and additionalProperties, so nothing is lost and
@@ -235,9 +243,18 @@ callers get the exact data.
reader is an agent, and stripping `=`/`+`/`-`/`@` would change values such
as `+1 555 0100`. The column names come once, then one line per record. An
empty cell is null or empty, a nested value (arrays included) is JSON in its
- cell, and a column empty in every row shown is left out. On real inventory rows that is 71% smaller than the JSON array it
- replaced, and the same budget holds 68 rows instead of 19. A single record,
- or a list of plain values, stays compact JSON with nulls removed.
+ cell, and a column empty in every row shown is left out. A single record, or
+ a list of plain values, stays compact JSON with nulls removed.
+- Why CSV, measured on 100 real inventory rows (o200k tokens, a proxy: Claude's
+ tokenizer is not public): compact JSON 27,207, CSV 13,778 (−49%), markdown
+ table 17,656, TOON 32,298, markdown key-value 29,631. TOON is larger than
+ JSON here because null-stripped rows are not uniform, and its compact form
+ needs uniform rows. With 6 `fields`: JSON 5,822, CSV 3,917, TOON 3,999.
+ Published comparisons find no single best format; markdown key-value reads
+ best for small models on 1,000-row tables, while at about 100 rows strong
+ models read CSV and JSON near-perfectly. Anthropic's tool-writing guidance
+ says to choose by your own evaluation. Measure tokens, not characters:
+ characters overstated CSV's saving (71% vs 49%).
- A list stops at `MCP_MAX_ROWS` (100) rows or `MCP_MAX_CHARS` (20,000)
characters, always with at least one row; any list short of its total ends
with `(rows A-B of TOTAL; next page: offset N)`. A `limit` above
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
index 9a1b3b2bef..5627013cd4 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts
@@ -8,6 +8,7 @@ import {
deriveNameDescription,
formatParamSummary,
formatSchemaType,
+ formatSearchResults,
formatToolDescription,
getServerInstructions,
MCP_DEFAULT_LIMIT,
@@ -67,8 +68,11 @@ describe("formatParamSummary", () => {
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.split("\n").slice(0, 3)).toEqual([
+ "sales_getCustomer [READ]",
+ "get customer",
+ "Permission: sales_view"
+ ]);
expect(text).toContain(
"Input: { id: string; includeContacts?: boolean; status?: string }"
);
@@ -173,6 +177,42 @@ describe("formatSchemaType", () => {
});
});
+describe("formatSearchResults", () => {
+ const tool = (
+ name: string,
+ description: string,
+ classification: ManifestEntry["classification"] = "READ"
+ ) => ({ ...baseTool, name, description, classification });
+
+ test("lists tools in rank order, one line each, with the next page", () => {
+ const text = formatSearchResults(
+ [
+ tool("sales_getCustomer", "get customer"),
+ tool("inventory_postReceipt", "Post a receipt.", "WRITE"),
+ tool(
+ "sales_deleteCustomer",
+ "Remove a customer and its contacts.",
+ "DESTRUCTIVE"
+ )
+ ],
+ 40,
+ 0
+ );
+ expect(text.split("\n")).toEqual([
+ "Found 40 tools, ranked by relevance (showing 1-3; next page: offset 3):",
+ "sales_getCustomer [READ] (id, +2 optional)",
+ "inventory_postReceipt [WRITE] (id, +2 optional)",
+ "sales_deleteCustomer [DESTRUCTIVE] (id, +2 optional) — Remove a customer and its contacts."
+ ]);
+ });
+
+ test("omits the page note when every match is shown", () => {
+ expect(formatSearchResults([tool("sales_getCustomer", "x")], 1, 0)).toBe(
+ "Found 1 tool, ranked by relevance:\nsales_getCustomer [READ] (id, +2 optional) — x"
+ );
+ });
+});
+
describe("closestToolNames", () => {
const names = (toolMetadata.tools as unknown as ManifestEntry[]).map(
(tool) => tool.name
@@ -203,12 +243,22 @@ describe("searchLineDescription", () => {
});
test("skips a description that restates the name", () => {
+ for (const [name, description] of [
+ ["sales_getCustomers", "get customers"],
+ ["inventory_getReceipt", "Get receipt."],
+ ["inventory_postReceipt", "Post a receipt."]
+ ]) {
+ expect(searchLineDescription({ name, description })).toBe(null);
+ }
+ });
+
+ test("keeps a description that says more than the name", () => {
expect(
searchLineDescription({
- name: "sales_getCustomers",
- description: "get customers"
+ name: "invoicing_postPayment",
+ description: "Post a Draft payment."
})
- ).toBe(null);
+ ).toBe("Post a Draft payment.");
});
});
diff --git a/packages/ee/src/mcp/describe-format.ts b/packages/ee/src/mcp/describe-format.ts
index 27bc876ca1..6afaaa5266 100644
--- a/packages/ee/src/mcp/describe-format.ts
+++ b/packages/ee/src/mcp/describe-format.ts
@@ -25,19 +25,30 @@ export function deriveNameDescription(name: string): string {
}
/**
- * The description search_tools prints under a tool: its first paragraph (the
+ * The description search_tools prints beside a tool: its first paragraph (the
* summary; `describe_tool` has the rest), or null when that only restates the
- * name.
+ * name. 937 of 1,612 summaries do ("Get receipt." on `inventory_getReceipt`,
+ * "Post a receipt." on `inventory_postReceipt`), so case, a closing full stop
+ * and articles do not count as saying more.
*/
export function searchLineDescription(
tool: Pick<ManifestEntry, "name" | "description">
): string | null {
const summary = tool.description.split("\n", 1)[0]!.trim();
- return summary && summary !== deriveNameDescription(tool.name)
+ const words = (text: string) =>
+ text
+ .toLowerCase()
+ .replace(/[.!]+$/, "")
+ .split(/\s+/)
+ .filter((word) => word && !ARTICLES.has(word))
+ .join(" ");
+ return summary && words(summary) !== words(deriveNameDescription(tool.name))
? summary
: null;
}
+const ARTICLES = new Set(["a", "an", "the"]);
+
type JsonSchema = {
type?: string | string[];
enum?: unknown[];
@@ -151,6 +162,31 @@ function editDistance(a: string, b: string): number {
return previous[b.length]!;
}
+/**
+ * search_tools output: one line per tool in rank order, then the next page's
+ * offset when there is one. Grouping by module put a lower-ranked tool above
+ * better ones, and the name already carries its module. Required params are
+ * inline so a simple tool needs no describe round trip; the summary only when
+ * it says more than the name.
+ */
+export function formatSearchResults(
+ matches: ManifestEntry[],
+ total: number,
+ offset: number
+): string {
+ const next = offset + matches.length;
+ let output = `Found ${total} ${total === 1 ? "tool" : "tools"}, ranked by relevance`;
+ if (next < total || offset > 0) {
+ output += ` (showing ${offset + 1}-${next}${next < total ? `; next page: offset ${next}` : ""})`;
+ }
+ output += ":";
+ for (const tool of matches) {
+ const summary = searchLineDescription(tool);
+ output += `\n${tool.name} [${tool.classification}] ${formatParamSummary(tool)}${summary ? ` — ${summary}` : ""}`;
+ }
+ return output;
+}
+
/**
* 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
@@ -187,20 +223,22 @@ export function paginatingSibling(
return sibling?.paginates ? sibling.name : null;
}
-/** Full describe_tool text for one tool. */
+/**
+ * Full describe_tool text for one tool: the name and classification, the
+ * description, the permission every caller needs, how a list pages, then the
+ * input and response types. The name already carries the module.
+ */
export function formatToolDescription(
tool: ManifestEntry,
options: { isList: boolean; sibling?: string | null }
): string {
- let output = `Tool: ${tool.name}\n`;
- output += `Module: ${tool.module}\n`;
- output += `Classification: ${tool.classification}\n`;
- output += `Description: ${tool.description}\n`;
+ let output = `${tool.name} [${tool.classification}]\n`;
+ output += `${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`;
+ output += `Permission: ${scopes}\n`;
}
if (options.isList) {
if (tool.paginates) {
diff --git a/packages/ee/src/mcp/format-result.ts b/packages/ee/src/mcp/format-result.ts
index 518067e46b..89642d5d41 100644
--- a/packages/ee/src/mcp/format-result.ts
+++ b/packages/ee/src/mcp/format-result.ts
@@ -90,8 +90,9 @@ export type McpResultOptions = {
* Serialize a call_tool result for the MCP text response.
*
* A list of records is CSV, written by `encodeCsv` (`@carbon/files/csv`): the
- * column names once, then one line per record, about 70% smaller than a JSON
- * array that repeats every key on every row. An empty cell is null or an empty
+ * column names once, then one line per record. On 100 real inventory rows that
+ * is about half the tokens of the JSON array it replaced (13,778 vs 27,207,
+ * o200k), which repeated every key on every row. An empty cell is null or an empty
* string, and a nested value is JSON inside its cell. Columns that are empty in
* every row shown are left out. String cells are kept as they are
* (`formulaSafe: false`): the reader is an agent, not a spreadsheet. Anything
diff --git a/packages/ee/src/mcp/server.ts b/packages/ee/src/mcp/server.ts
index b0da2afff0..41b9c9e3dc 100644
--- a/packages/ee/src/mcp/server.ts
+++ b/packages/ee/src/mcp/server.ts
@@ -19,10 +19,9 @@ import { z } from "zod";
import { requireEntitlement } from "../entitlements.server";
import {
closestToolNames,
- formatParamSummary,
+ formatSearchResults,
formatToolDescription,
- paginatingSibling,
- searchLineDescription
+ paginatingSibling
} from "./describe-format";
import {
formatMcpResult,
@@ -445,39 +444,9 @@ function buildMcpServer<Ctx extends McpContext>(
returned: matches.length
});
- // Build response
- let output = `Found ${total} tools`;
- if (total > limit) {
- output += ` (showing ${offset + 1}-${offset + matches.length}, ranked by relevance)`;
- }
- output += ":\n\n";
-
- // 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);
- }
-
- // 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}] ${formatParamSummary(tool)}\n`;
- const summary = searchLineDescription(tool);
- if (summary) output += ` ${summary}\n`;
- }
- output += "\n";
- }
-
- // No footer: the describe_tool/call_tool how-to and the catalog size
- // ship once in the server instructions at connect.
- output = output.trimEnd();
+ // The describe_tool/call_tool how-to ships once, in the server
+ // instructions, not under every search.
+ const output = formatSearchResults(matches, total, offset);
return { content: [{ type: "text" as const, text: output }] };
}, "Search failed")