Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(mcp): leaner tool output, exact-name search, MCP SDK v2
Sidwebworks3a0920553ccb
diff --git a/.claude/rules/commercial-licensing.md b/.claude/rules/commercial-licensing.mdindex 6b32944537..680f4de527 100644--- a/.claude/rules/commercial-licensing.md+++ b/.claude/rules/commercial-licensing.md@@ -184,12 +184,11 @@ Refactor one at a time; each PR should leave the tree green.edge would be a `lib → ee → lib` cycle. (The job-side executors in`packages/jobs/src/workflows/` stay in jobs — Inngest-coupled, like backups.)- ✅ **MCP** — protocol engine moved to `packages/ee/src/mcp/` (`@carbon/ee/mcp`- pure logic; `@carbon/ee/mcp.server` = `server.ts`). `createMcpServer` embeds+ pure logic; `@carbon/ee/mcp.server` = `server.ts`). `serveMcpRequest` embeds`requireEntitlement("MCP")` (route catches `EntitlementError` → 402), replacingthe former deletable in-route `companyHasFeature`. The dispatch, tool manifest andgenerated `tool-metadata.json` STAY in the app (derive from `~/modules/*`) and are- INJECTED as `deps`. Note: `server.ts` is `@ts-nocheck`, so the live endpoint needs a- smoke test before merge (typecheck can't cover its body).+ INJECTED as `deps`.- Note (context): Planning was NOT a gated feature — MRP + scheduling are now thecommunity `@carbon/planning` package.- ⬜ Still on `requirePlan`/`companyHasPlan`, pending an architecture/policy decisiondiff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.mdindex 4887e8617f..cd43c96fa1 100644--- a/.claude/rules/mcp-tools-reference.md+++ b/.claude/rules/mcp-tools-reference.md@@ -125,11 +125,21 @@ The procedure (`api+/v1+/lib/router.server.ts`) is the same one HTTP serves:## Endpoint & transport- Route: `POST /api/mcp` (`api+/mcp+/_index.ts`). `loader` rejects non-POST (405);- `OPTIONS` → 204 with CORS. JSON-RPC over- `WebStandardStreamableHTTPServerTransport` (`enableJsonResponse: true`,- `sessionIdGenerator: undefined`: stateless).-- A fresh server (`await createMcpServer(ctx, today, deps)`) is built per- request. It is async because it awaits `requireEntitlement("MCP")` first.+ `OPTIONS` → 204 with CORS. The route authenticates, then makes one call:+ `serveMcpRequest(request, ctx, today, deps)` (`@carbon/ee/mcp.server`, MCP+ TypeScript SDK v2, `@modelcontextprotocol/server`). It awaits+ `requireEntitlement("MCP")`, then builds a fresh server for the request.+- Both protocol eras, one server definition. `isLegacyRequest` sends 2025-era+ requests (every client's default `initialize` handshake) to+ `WebStandardStreamableHTTPServerTransport` with `sessionIdGenerator:+ undefined` and `enableJsonResponse: true`, the wiring SDK v1 had: the SDK's+ own stateless fallback answers with SSE. 2026-07-28 requests go to+ `createMcpHandler(factory, { legacy: "reject", maxSubscriptions: 0 })`.+ `maxSubscriptions: 0` refuses `subscriptions/listen` in-band, because it holds+ a stream open that a per-request serverless function cannot keep, and the tool+ list never changes at runtime.+- Pinned by `packages/ee/src/mcp/server.test.ts`: an SDK client over HTTP+ against `serveMcpRequest` in each era.## Public discovery endpoints (unauthenticated)@@ -158,7 +168,7 @@ instance advertises its own endpoint. Never hard-code `app.carbon.ms`.`companyId` / `userId` always come from the credential, never from arguments.**Edition/plan gate.** MCP is a Business+ feature, locked inside the commercial-engine: `createMcpServer` throws `EntitlementError`, which the route turns into+engine: `serveMcpRequest` throws `EntitlementError`, which the route turns intoa 402 (`makeMcpDisabledResponse`). One check covers both auth paths, theCommunity edition and Cloud Starter. The discovery endpoints are not gated.@@ -169,9 +179,13 @@ operation is reached through them.| Tool | Purpose ||------|---------|-| `search_tools` | Ranked discovery. Filters: `query`, `module` (substring), `classification`, `limit`/`offset`. |+| `search_tools` | Ranked discovery. Filters: `query`, `module` (substring), `classification`, `limit` (default 10) / `offset`. || `describe_tool` | The contract for one `name` or up to 10 `names`: description, permission, list marker, input and response schema. |-| `call_tool` | Run a tool: `{ name, arguments }`. `arguments` may arrive as a JSON string. Parameters go flat, exactly as `describe_tool` lists them. |+| `call_tool` | Run a tool: `{ name, arguments, fields? }`. `arguments` may arrive as a JSON string. Parameters go flat, exactly as `describe_tool` lists them. |++An unknown name in `call_tool` or `describe_tool` is answered with the three+closest tools from catalog search ("Did you mean: …"); `call_tool` does not+dispatch it.### Catalog search (`packages/ee/src/mcp/catalog-search.ts`)@@ -182,12 +196,28 @@ the manifest.(1.5), input property names `fields` (0.5). Prefix expansion is on; a querywith no match retries with `tolerance: 1`.- `SEARCH_ALIASES` expands domain abbreviations additively (`rma`, `po`,- `bom`, `shelf` → storage unit, …). `expandQueryTerm` adds each word's- inflection stem to the QUERY, never the index. The in-app agent's- `search_docs` (`doc-search.ts`) shares it.+ `bom`, `nonconformance` → issue, `shelf` → storage unit, …), and+ `PHRASE_ALIASES` multi-word terms (`work orders` → jobs, `non conformance` →+ issue). `expandQueryTerm` adds each word's inflection stem to+ the QUERY, never the index. The in-app agent's `search_docs`+ (`doc-search.ts`) shares it.+- BM25 only gathers candidates (top `RERANK_POOL`, 200). `rerankByName` orders+ them by the tool NAME: query words it covers, then words matched in full+ (an `ACTION_SYNONYMS` word such as create → insert, or every word of an+ alias), then READ first when the query names no action, then fewer extra name+ words, then a database-paged tool before a `get*List` that reads the whole+ table, then BM25. An exact tool name, with or without its module, is put+ first. BM25 alone ranked `inventory_getInventoryItems` tenth for its own name.+ `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`).+ (`formatParamSummary`, `describe-format.ts`), plus the description's first+ paragraph when it says more than the name (`searchLineDescription`).+- `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+ the text is under half the JSON Schema's size.- Server instructions: `packages/ee/src/mcp/instructions.ts`. `lib/manifest.ts`keeps its own copies of the meta-tool descriptions; keep them in sync by hand.- Pinned by `lib/catalog-search.test.ts` and `lib/describe-format.test.ts`.@@ -197,9 +227,14 @@ the manifest.MCP text differs from the HTTP body on purpose; the other `callOperation`callers get the exact data.-- Compact JSON with null fields omitted (the instructions say so). Top-level- arrays are capped at `MCP_MAX_ROWS` (100) with an "… N more rows omitted"- marker; a paged read short of its total appends `(showing R of C rows)`.+- Compact JSON with null fields omitted (the instructions say so). 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 `MCP_MAX_ROWS` is+ clamped before the call.+- `call_tool.fields` (beside `arguments`, not inside them) keeps only those+ top-level fields of each row (`projectFields`). A wide row is 50+ columns;+ `limit: 1` plus `fields: ["id"]` is the cheap way to read a total.- **Paging splits on `paginates`**:- `paginates: true` (a `paged` service function): `call_tool` fills `limit`(`MCP_DEFAULT_LIMIT`, 25) and `offset` (0) when the caller leaves them out.@@ -221,6 +256,16 @@ compared to, as a path into the tool's input; the few nothing can answer are inIt gates on `read-tools.baseline.json`, which stays empty unless a failure isknowingly accepted. Seed first (`pnpm db:seed:dev`). Not part of `pnpm test`.+## The agent evaluation++`apps/erp/test/mcp-eval/satellite.xml`: ten read-only, multi-hop questions in+the mcp-builder skill's format, answered only through the three meta-tools,+each with one answer checked by string comparison. The answers come from the+satellite demo dataset (no dates or sequence ids), so they hold for any company+seeded with it; the file's header names the traps it sets on purpose. Run it+with that skill's `scripts/evaluation.py` and a `crbn_` key holding the view+scopes. Not part of `pnpm test`.+## The 14 modules`accounting` · `documents` · `inventory` · `invoicing` · `items` · `people` ·diff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.tsindex 205af4e8e2..0912183003 100644--- a/apps/erp/app/routes/api+/mcp+/_index.ts+++ b/apps/erp/app/routes/api+/mcp+/_index.ts@@ -5,12 +5,11 @@import type { ManifestEntry } from "@carbon/api";import { EntitlementError } from "@carbon/ee/entitlements.server";import { createCatalogSearch } from "@carbon/ee/mcp";-import { createMcpServer } from "@carbon/ee/mcp.server";+import { serveMcpRequest } from "@carbon/ee/mcp.server";import { getAppUrl } from "@carbon/env";import { Ratelimit, redis } from "@carbon/kv";import { withLogContext } from "@carbon/logger/middleware.server";import { datetime, getRequestOrigin } from "@carbon/utils";-import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import type { ActionFunctionArgs } from "react-router";import { getCompanyTimeZone } from "~/modules/shared/shared.service";import {@@ -170,10 +169,11 @@ export async function action({ request }: ActionFunctionArgs) {async () => {// The agent is told what "today" is; it has to be the company's day, not// the server's, or every relative-date tool call it makes lands a day off.- // `createMcpServer` embeds the MCP entitlement LOCK (Business+), covering+ // `serveMcpRequest` embeds the MCP entitlement LOCK (Business+), covering// every auth path since both resolve to an authed context first — it// throws `EntitlementError` for community/starter, caught below as 402.- const server = await createMcpServer(+ return serveMcpRequest(+ authedRequest,ctx,datetime.today(await getCompanyTimeZone(ctx.client, ctx.companyId))@@ -186,13 +186,6 @@ export async function action({ request }: ActionFunctionArgs) {toolMetadata});- const transport = new WebStandardStreamableHTTPServerTransport({- sessionIdGenerator: undefined,- enableJsonResponse: true- });-- await server.connect(transport);- return transport.handleRequest(authedRequest);});} catch (err) {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.tsindex cfc2f78093..178e4ee9ab 100644--- a/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts@@ -7,6 +7,7 @@ import {collectFieldNames,createCatalogSearch,expandQueryTerm,+ rerankByName,splitWords} from "@carbon/ee/mcp";import { describe, expect, test } from "vitest";@@ -156,3 +157,90 @@ describe("catalog search", () => {expect(overlap).toEqual([]);});});++describe("ranking by name", () => {+ const top = async (query: string) =>+ (await catalog.search({ query, limit: 3, offset: 0 })).matches.map(+ (tool) => tool.name+ );++ test("an exact tool name comes first, with or without its module", async () => {+ expect((await top("inventory_getInventoryItems"))[0]).toBe(+ "inventory_getInventoryItems"+ );+ expect((await top("getInventoryItems"))[0]).toBe(+ "inventory_getInventoryItems"+ );+ });++ test("the tool whose name covers every query word beats repeated common words", async () => {+ expect((await top("inventory items"))[0]).toBe(+ "inventory_getInventoryItems"+ );+ expect((await top("get inventory items"))[0]).toBe(+ "inventory_getInventoryItems"+ );+ });++ test("a bare noun is a lookup: reads before writes", async () => {+ expect((await top("bom"))[0]).toBe("items_getMethodMaterials");+ expect((await top("jobs"))[0]).toBe("production_getJobs");+ });++ test("an action word picks that action, synonyms included", async () => {+ expect((await top("delete customer"))[0]).toBe("sales_deleteCustomer");+ expect((await top("create purchase order"))[0]).toBe(+ "purchasing_insertPurchaseOrder"+ );+ });++ test("industry phrases and plurals reach Carbon's names", async () => {+ expect((await top("work orders"))[0]).toBe("production_getJobs");+ expect((await top("vendors"))[0]).toBe("purchasing_getSuppliers");+ for (const query of ["nonconformance items", "non-conformance items"]) {+ expect(await top(query)).toContain("quality_getIssueItems");+ }+ });++ test("a database-paged tool beats a List that reads the whole table", async () => {+ expect((await top("list customers"))[0]).toBe("sales_getCustomers");+ expect((await top("list sales orders"))[0]).toBe("sales_getSalesOrders");+ });++ test("filters still apply to an exact name", async () => {+ const { matches } = await catalog.search({+ query: "getInventoryItems",+ module: "sales",+ limit: 5,+ offset: 0+ });+ expect(matches.map((t) => t.name)).not.toContain(+ "inventory_getInventoryItems"+ );+ });+});++describe("rerankByName", () => {+ const entry = (+ name: string,+ classification: ManifestEntry["classification"] = "READ"+ ) => ({ ...tools[0]!, name, classification }) as ManifestEntry;+ const actions = new Set(["get", "delete", "insert"]);++ test("prefers the tighter name when coverage ties", () => {+ const ranked = rerankByName(+ "job",+ [entry("production_getJobOperations"), entry("production_getJob")],+ actions+ );+ expect(ranked.map((t) => t.name)).toEqual([+ "production_getJob",+ "production_getJobOperations"+ ]);+ });++ test("keeps the BM25 order when the query has no usable words", () => {+ const candidates = [entry("a_getX"), entry("b_getY")];+ expect(rerankByName("the of", candidates, actions)).toBe(candidates);+ });+});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.tsindex dda2b2a76e..9a1b3b2bef 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@@ -4,12 +4,15 @@import type { ManifestEntry } from "@carbon/api";import {+ closestToolNames,deriveNameDescription,formatParamSummary,+ formatSchemaType,formatToolDescription,getServerInstructions,MCP_DEFAULT_LIMIT,- paginatingSibling+ paginatingSibling,+ searchLineDescription} from "@carbon/ee/mcp";import { describe, expect, test } from "vitest";import toolMetadata from "./tool-metadata.json";@@ -66,9 +69,11 @@ describe("formatToolDescription", () => {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):"+ "Input: { id: string; includeContacts?: boolean; status?: string }"+ );+ expect(text).toContain(+ "Returns (null fields are omitted): { id?: string; name?: string }");expect(text).not.toContain("List operation:");});@@ -112,7 +117,98 @@ describe("formatToolDescription", () => {{ ...baseTool, responseSchema: undefined },{ isList: false });- expect(text).not.toContain("Response Schema");+ expect(text).not.toContain("Returns");+ });+});++describe("formatSchemaType", () => {+ test("renders nullable, enum, array and nested object types", () => {+ expect(+ formatSchemaType({+ type: ["array", "null"],+ items: {+ type: "object",+ properties: {+ id: { type: "string" },+ status: { type: "string", enum: ["Draft", "Posted"] },+ tags: { type: "array", items: { type: "string" } },+ lines: {+ type: "array",+ items: { anyOf: [{ type: "string" }, { type: "number" }] }+ },+ "odd-key": { type: "integer" },+ note: { type: ["string", "null"], description: "free text" }+ },+ required: ["id", "status"],+ additionalProperties: {}+ }+ })+ ).toBe(+ '{ id: string; status: "Draft" | "Posted"; tags?: string[]; lines?: (string | number)[]; "odd-key"?: number; note?: string | null /* free text */ }[] | null'+ );+ });++ test("renders records, empty schemas and bare objects", () => {+ expect(+ formatSchemaType({+ type: "object",+ additionalProperties: { type: "number" }+ })+ ).toBe("Record<string, number>");+ expect(formatSchemaType({})).toBe("unknown");+ expect(formatSchemaType({ type: "object" })).toBe("object");+ });++ test("is far shorter than the JSON Schema across the manifest", () => {+ let json = 0;+ let typed = 0;+ for (const tool of toolMetadata.tools as unknown as ManifestEntry[]) {+ for (const schema of [tool.schema, tool.responseSchema]) {+ if (!schema) continue;+ json += JSON.stringify(schema).length;+ typed += formatSchemaType(schema).length;+ }+ }+ expect(typed).toBeLessThan(json / 2);+ });+});++describe("closestToolNames", () => {+ const names = (toolMetadata.tools as unknown as ManifestEntry[]).map(+ (tool) => tool.name+ );++ test("puts the real name first for a near-typo", () => {+ expect(closestToolNames("inventory_getInventoryItem", names)[0]).toBe(+ "inventory_getInventoryItems"+ );+ expect(closestToolNames("sales_getCustomr", names)[0]).toBe(+ "sales_getCustomer"+ );+ });++ test("suggests nothing for a name nowhere near a tool", () => {+ expect(closestToolNames("weather_forecast", names)).toEqual([]);+ });+});++describe("searchLineDescription", () => {+ test("keeps the first paragraph of a long description", () => {+ expect(+ searchLineDescription({+ name: "inventory_getSerialUnitCosts",+ description: "Value an item's serial units on hand.\n\nWhat each unit…"+ })+ ).toBe("Value an item's serial units on hand.");+ });++ test("skips a description that restates the name", () => {+ expect(+ searchLineDescription({+ name: "sales_getCustomers",+ description: "get customers"+ })+ ).toBe(null);});});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.tsindex 93b71110ac..962ce5597f 100644--- a/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts@@ -4,8 +4,10 @@import {formatMcpResult,+ MCP_MAX_CHARS,MCP_MAX_ROWS,pageMcpListResult,+ projectFields,stripNulls} from "@carbon/ee/mcp";import { describe, expect, it } from "vitest";@@ -41,23 +43,67 @@ describe("formatMcpResult", () => {expect(text).toBe('[{"id":"a"}]');});- it("caps rows at MCP_MAX_ROWS with an omission marker", () => {+ it("caps rows at MCP_MAX_ROWS and names the next offset", () => {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");+ expect(text).toContain(+ `(rows 1-${MCP_MAX_ROWS} of ${MCP_MAX_ROWS + 40}; next page: offset ${MCP_MAX_ROWS}, output capped`+ );});- 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("stops at the character budget but always returns one row", () => {+ const wide = { id: 0, notes: "x".repeat(MCP_MAX_CHARS / 4) };+ const rows = Array.from({ length: 10 }, (_, i) => ({ ...wide, id: i }));+ const text = formatMcpResult(rows, 50, 20);+ const body = text.slice(0, text.indexOf("\n"));+ expect(JSON.parse(body)).toHaveLength(3);+ expect(text).toContain("(rows 21-23 of 50; next page: offset 23");+ expect(text).toContain("pass `fields`");++ const huge = [{ notes: "x".repeat(MCP_MAX_CHARS * 2) }, { id: 1 }];+ expect(formatMcpResult(huge)).toContain("(rows 1-1 of 2;");});- it("omits the count line when everything was returned", () => {+ it("names the next offset when the read was paginated short", () => {+ const text = formatMcpResult([{ id: "a" }], 240, 25);+ expect(text).toBe(+ '[{"id":"a"}]\n(rows 26-26 of 240; next page: offset 26)'+ );+ });++ it("omits the footer when everything was returned", () => {expect(formatMcpResult([{ id: "a" }], 1)).toBe('[{"id":"a"}]');+ expect(formatMcpResult([{ id: "b" }], 26, 25)).toBe('[{"id":"b"}]');+ });++ it("serializes a single object whole", () => {+ expect(formatMcpResult({ id: "a", fax: null })).toBe('{"id":"a"}');+ });+});++describe("projectFields", () => {+ it("keeps only the named fields of each row", () => {+ expect(+ projectFields(+ [+ { id: "a", name: "A", wide: 1 },+ { id: "b", wide: 2 }+ ],+ ["id", "name"]+ )+ ).toEqual([{ id: "a", name: "A" }, { id: "b" }]);+ expect(projectFields({ id: "a", wide: 1 }, ["id"])).toEqual({ id: "a" });+ });++ it("passes data through when no fields are named", () => {+ const rows = [{ id: "a" }];+ expect(projectFields(rows, undefined)).toBe(rows);+ expect(projectFields(rows, [])).toBe(rows);+ expect(projectFields(["a", 1], ["id"])).toEqual(["a", 1]);});});@@ -87,7 +133,7 @@ describe("pageMcpListResult", () => {offset: 0});expect(formatMcpResult(page, total)).toBe(- '[{"id":0}]\n(showing 1 of 10 rows)'+ '[{"id":0}]\n(rows 1-1 of 10; next page: offset 1)');});});diff --git a/apps/erp/app/routes/api+/mcp+/lib/manifest.ts b/apps/erp/app/routes/api+/mcp+/lib/manifest.tsindex 5b2e78df3b..9f3c590861 100644--- a/apps/erp/app/routes/api+/mcp+/lib/manifest.ts+++ b/apps/erp/app/routes/api+/mcp+/lib/manifest.ts@@ -73,7 +73,7 @@ const TOOLS = [{name: "call_tool",description:- "Call an operation by name with its arguments. The company and user are taken from the credential, never from the arguments.",+ "Call an operation by name with its arguments, optionally returning only the named fields of each row. The company and user are taken from the credential, never from the arguments.",readOnly: false}] as const;diff --git a/apps/erp/package.json b/apps/erp/package.jsonindex 7e975d6db3..0dd7be7ae1 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -41,7 +41,6 @@"@internationalized/date": "catalog:","@lingui/core": "catalog:","@lingui/react": "catalog:",- "@modelcontextprotocol/sdk": "1.31.0","@monaco-editor/react": "4.7.0","@orpc/openapi": "catalog:","@orpc/server": "catalog:",diff --git a/apps/erp/test/mcp-eval/satellite.xml b/apps/erp/test/mcp-eval/satellite.xmlnew file mode 100644index 0000000000..3ab589ab0d--- /dev/null+++ b/apps/erp/test/mcp-eval/satellite.xml@@ -0,0 +1,65 @@+<!--+ Agent evaluation for the Carbon MCP server (mcp-builder skill format).++ Ten read-only questions an agent answers using only search_tools /+ describe_tool / call_tool. Each needs several hops: a BOM walked through its+ sub-assemblies, a supersession to its successor's replenishment, an NCR to+ the disposition on one of its items.++ Answers come from the satellite demo dataset+ (packages/database/src/datasets/data/satellite), so they hold for any company+ seeded with the satellite dataset (`pnpm db:seed:dev`). They avoid dates and+ sequence ids, which change on every apply. Verified against the live database+ and the MCP server on 2026-10-17.++ Traps on purpose:+ - Q1: HARNESS-001 also exists as revision A under an open change notice,+ whose BOM has no M4 fasteners. Reading it gives 72, not 84.+ - Q2: SAW-001 has an Active v1 and a Draft v2. Both hold 64 cells, so either+ one gives 128.++ Run with the mcp-builder skill's scripts/evaluation.py against+ https://<erp>/api/mcp, with a `crbn_` API key that holds the view scopes.+-->+<evaluation>+ <qa_pair>+ <question>Counting every level of the bill of materials, and ignoring revisions that are still under an open change notice, how many M4 titanium fasteners does one complete ESPA-class smallsat bus consume? Answer with a whole number.</question>+ <answer>84</answer>+ </qa_pair>+ <qa_pair>+ <question>How many photovoltaic cells go into one complete smallsat bus, counting every sub-assembly? Answer with a whole number.</question>+ <answer>128</answer>+ </qa_pair>+ <qa_pair>+ <question>Among the purchased components of the propulsion module, which one takes the longest to replenish? Answer with the item's name exactly as Carbon shows it.</question>+ <answer>Hydrazine Thruster 1N</answer>+ </qa_pair>+ <qa_pair>+ <question>One valve in the propulsion module is being phased out in favour of a successor part. What is the successor's replenishment lead time in days? Answer with a whole number.</question>+ <answer>30</answer>+ </qa_pair>+ <qa_pair>+ <question>At the prices quoted by their supplier, what do the reaction wheels and star trackers needed for one attitude determination and control system cost in total, in USD? Answer with a whole number and no currency symbol or separators.</question>+ <answer>114000</answer>+ </qa_pair>+ <qa_pair>+ <question>Our defense customer orders the complete smallsat bus under their own part number. What is that part number, without the revision? Answer with the part number only.</question>+ <answer>ORB-BUS-4400</answer>+ </qa_pair>+ <qa_pair>+ <question>A customer-reported quality problem has already been closed. What disposition was recorded for the item involved? Answer with the disposition exactly as Carbon shows it.</question>+ <answer>Rework</answer>+ </qa_pair>+ <qa_pair>+ <question>For the most severe non-conformance that is still open, what disposition was recorded for the purchased part involved? Answer with the disposition exactly as Carbon shows it.</question>+ <answer>Return to Supplier</answer>+ </qa_pair>+ <qa_pair>+ <question>One engineering change to a sub-assembly of the smallsat bus is currently being implemented. Which item does it affect? Answer with the item's name exactly as Carbon shows it.</question>+ <answer>Spacecraft Wiring Harness</answer>+ </qa_pair>+ <qa_pair>+ <question>Which work center has a monthly preventive maintenance schedule and also a maintenance dispatch that needs the equipment maker's help at the highest priority? Answer with the work center's name.</question>+ <answer>TVAC Chamber 1</answer>+ </qa_pair>+</evaluation>diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.mdindex 1d21759f9c..5b0070e00b 100644--- a/packages/ee/AGENTS.md+++ b/packages/ee/AGENTS.md@@ -49,7 +49,7 @@ pnpm --filter @carbon/ee typecheck| `./sso.server` | SAML connection, domain verification, session, and provisioning helpers || `./rules`, `./rules.server` | Storage- and sales-rule schemas and query services (client-safe), and the evaluators plus the entitlement-gated rule writes (server) || `./workflows`, `./workflows/help`, `./workflows/labels` | The workflows engine — definition schema, normaliser, validator, generated catalog, pure runtime, and the `sync.ts` trigger/subscription reconciler (moved from `@carbon/workflows`). `./workflows/labels` (`WORKFLOW_LABELS`) is Vite-only — the `msg` macro throws in plain Node |-| `./mcp`, `./mcp.server` | The MCP protocol engine (moved from `apps/erp/.../api+/mcp+/lib`). `./mcp` = pure logic (catalog search, the agent's doc search `createDocSearch`, formatters, instructions, types) with no auth/entitlement chain — safe for tests; `./mcp.server` = `server.ts` (`createMcpServer`, embeds `requireEntitlement("MCP")`). The dispatch + generated tool metadata stay in the app and are injected as `deps`. `server.ts` is `@ts-nocheck` |+| `./mcp`, `./mcp.server` | The MCP protocol engine (moved from `apps/erp/.../api+/mcp+/lib`). `./mcp` = pure logic (catalog search, the agent's doc search `createDocSearch`, formatters, instructions, types) with no auth/entitlement chain — safe for tests; `./mcp.server` = `server.ts` (`serveMcpRequest`, embeds `requireEntitlement("MCP")`, on MCP SDK v2 `@modelcontextprotocol/server`; serves 2025-era and 2026-07-28 clients). The dispatch + generated tool metadata stay in the app and are injected as `deps` || `./workflows.server` | Workflows runtime lock: `workflowsEnabledForCompany(companyId)` (runtime DEGRADE — a non-entitled run settles Skipped, embedded in `@carbon/jobs` `engine/execute.ts`) and `requireWorkflowsEntitlement(client, companyId)` (authoring throw, embedded in the ERP's `publishWorkflowVersion`) || `./jira`, `./jira.server`, `./linear`, `./linear.server`, `./onshape`, `./paperless-parts` | Integration client/server seams || `./onshape`, `./onshape.server` | Onshape runtime shared by BOTH Onshape integrations — `onshape` (the public App Store app, client from `ONSHAPE_CLIENT_*`) and `onshape-government` (a customer-owned private OAuth app on their own tenant URL; tenant URL and client id/secret entered in settings; the tenant URL also serves OAuth, secret vaulted; always offered). Runtime code resolves the company's connection with `getOnshapeIntegration` rather than naming an id; `getOnshapeOAuthConfig` picks the client per variant; `./onshape.server` (`lib/index.server.ts`) has `beginOnshapeAuthorization` / `loadOnshapeOAuthConfig`, the metadata patch helpers of `lib/state.ts` (`patchOnshapeOAuthGrant`, `patchOnshapeSettings`, …) and the panel's server-side property reads (`lib/panel-properties.server.ts`). `externalIntegrationMapping` rows stay under `"onshape"` for both. A company holds one active Onshape connection at a time (`getConflictingOnshapeIntegration`, app-level). The Onshape panel (`onshape-v2`, id from `./onshape/integration-id`) is a third grant outside that rule, on its own Onshape app (client from `ONSHAPE_V2_CLIENT_*`, never `ONSHAPE_CLIENT_*`): panel code passes its id explicitly and keeps its own mapping namespace (`.claude/rules/onshape-panel.md`) |diff --git a/packages/ee/package.json b/packages/ee/package.jsonindex f593e15080..bbc6de9b87 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -84,7 +84,7 @@"@carbon/workflows-core": "workspace:*","@internationalized/date": "catalog:","@lingui/core": "catalog:",- "@modelcontextprotocol/sdk": "1.31.0",+ "@modelcontextprotocol/server": "2.3.1","@slack/bolt": "4.4.0","@slack/oauth": "3.0.5","@slack/types": "2.20.1",@@ -114,6 +114,7 @@"@carbon/content": "workspace:*","@logtape/logtape": "catalog:","@logtape/testing": "catalog:",+ "@modelcontextprotocol/client": "2.3.1","@types/nodemailer": "6.4.21","@types/react": "catalog:","typescript": "catalog:",diff --git a/packages/ee/src/mcp/catalog-search.ts b/packages/ee/src/mcp/catalog-search.tsindex 85470aec2b..fce14ad281 100644--- a/packages/ee/src/mcp/catalog-search.ts+++ b/packages/ee/src/mcp/catalog-search.ts@@ -30,6 +30,9 @@ export const SEARCH_ALIASES: Record<string, string[]> = {// quality & engineeringncr: ["nonconformance", "issue"],ncrs: ["nonconformance", "issue"],+ // Carbon names a non-conformance an issue (quality_getIssueItems, …).+ nonconformance: ["issue"],+ nonconformances: ["issues"],capa: ["issue", "action", "corrective"],eco: ["change", "order", "engineering"],ecn: ["change", "order"],@@ -49,7 +52,7 @@ export const SEARCH_ALIASES: Record<string, string[]> = {bins: ["storage", "unit"],// partiesvendor: ["supplier"],- vendors: ["supplier"],+ vendors: ["suppliers"],// accountingap: ["purchase", "invoice", "payable"],ar: ["sales", "invoice", "receivable"],@@ -59,6 +62,71 @@ export const SEARCH_ALIASES: Record<string, string[]> = {wip: ["production", "job"]};+/**+ * Multi-word domain terms, matched against the whole query. Same rules as+ * SEARCH_ALIASES: additive, industry term → Carbon's naming.+ */+export const PHRASE_ALIASES: Record<string, string[]> = {+ "non conformance": ["issue"],+ "non conformances": ["issues"],+ "work order": ["job"],+ "work orders": ["jobs"],+ "bill of materials": ["method", "material"],+ "purchase requisition": ["purchase", "order"],+ "stock on hand": ["quantities"],+ "on hand": ["quantities"]+};++/**+ * Query words that name an action, mapped to the first word Carbon's tool names+ * use for it ("list customers" wants getCustomers, "add a part" wants+ * insertPart/upsertPart). Used only to re-rank by name.+ */+export const ACTION_SYNONYMS: Record<string, string[]> = {+ list: ["get"],+ find: ["get"],+ show: ["get"],+ fetch: ["get"],+ read: ["get"],+ lookup: ["get"],+ view: ["get"],+ count: ["get"],+ create: ["create", "insert", "upsert"],+ add: ["create", "insert", "upsert", "add"],+ new: ["create", "insert", "upsert"],+ edit: ["update", "upsert"],+ change: ["update", "upsert"],+ modify: ["update", "upsert"],+ update: ["update", "upsert"],+ remove: ["delete", "remove"]+};++/** Query words that carry no meaning for a tool name. */+const STOPWORDS = new Set([+ "a",+ "an",+ "the",+ "of",+ "for",+ "in",+ "on",+ "to",+ "by",+ "all",+ "my",+ "me",+ "how",+ "many",+ "much",+ "what",+ "which",+ "do",+ "we",+ "have",+ "is",+ "are"+]);+/** "getJobOperationsList" / "sales_getCustomers" → "get job operations list". */export function splitWords(identifier: string): string {return identifier@@ -112,6 +180,12 @@ export function expandQueryTerm(query: string): string {words.add(alias);}}+ const phrase = ` ${splitWords(query)} `;+ for (const [key, aliases] of Object.entries(PHRASE_ALIASES)) {+ if (phrase.includes(` ${key} `)) {+ for (const alias of aliases) words.add(alias);+ }+ }// Stems join the QUERY only, like aliases. Stemming the index collapsed "orders"// into "order", so list tools (getSalesOrders) lost their edge to single-record// ones (deleteSalesOrder).@@ -121,6 +195,139 @@ export function expandQueryTerm(query: string): string {return [...words].join(" ");}+/**+ * Re-rank BM25 candidates by how well each tool's NAME answers the query. BM25+ * finds the right neighbourhood but scores repeated common words ("items",+ * "get") over the one exact tool: `inventory_getInventoryItems` ranked tenth+ * for its own name. Order, highest first:+ *+ * 1. query terms the name covers. A term is a query word, or a whole+ * PHRASE_ALIASES phrase ("work orders"), which then stands in for its words;+ * 2. of those, terms matched in full: the word itself, an ACTION_SYNONYMS+ * word ("create" → insert), every word of its alias ("po" → purchase order)+ * or its phrase. A stem or part of an alias covers but is not full;+ * 3. with no action word in the query, READ tools first (a bare noun is a+ * lookup);+ * 4. fewer name words the query did not ask for (getJob before+ * getJobOperations for "job");+ * 5. a tool that pages in the database before a `get*List` that reads the+ * whole table on every call ("list customers" wants getCustomers, not+ * getCustomersList);+ * 6. the BM25 order.+ *+ * `actions` is the set of first words of the catalog's function names (get,+ * insert, post, …), so a query counts as naming an action only when the+ * catalog has one.+ */+export function rerankByName(+ query: string,+ candidates: ManifestEntry[],+ actions: ReadonlySet<string>+): ManifestEntry[] {+ let words = [+ ...new Set(+ splitWords(query)+ .split(" ")+ .filter((word) => word && !STOPWORDS.has(word))+ )+ ];+ const phrases: string[][] = [];+ const text = ` ${splitWords(query)} `;+ for (const [key, aliases] of Object.entries(PHRASE_ALIASES)) {+ if (!text.includes(` ${key} `)) continue;+ const keyWords = key.split(" ");+ // Overlapping phrases ("stock on hand", "on hand") count once.+ if (!keyWords.some((word) => words.includes(word) || STOPWORDS.has(word))) {+ continue;+ }+ phrases.push(aliases);+ words = words.filter((word) => !keyWords.includes(word));+ }+ if (words.length === 0 && phrases.length === 0) return candidates;++ const hasAction = words.some(+ (word) => actions.has(word) || word in ACTION_SYNONYMS+ );++ const scored = candidates.map((tool, bm25Rank) => {+ const separator = tool.name.indexOf("_");+ const tokens = splitWords(tool.name).split(" ");+ const tokenSet = new Set(tokens);+ const used = new Set<string>();+ const use = (term: string) => {+ for (const token of tokens) {+ if (sameWord(token, term)) used.add(token);+ }+ };+ const hasStem = (term: string) =>+ tokens.some((token) => sameWord(token, term));++ let covered = 0;+ let full = 0;+ const matchAliases = (aliases: string[]) => {+ const present = aliases.filter(hasStem);+ if (present.length === 0) return false;+ covered++;+ if (present.length === aliases.length) full++;+ present.forEach(use);+ return true;+ };++ for (const word of words) {+ const action = (ACTION_SYNONYMS[word] ?? []).find((alt) =>+ tokenSet.has(alt)+ );+ if (tokenSet.has(word) || action) {+ covered++;+ full++;+ use(action ?? word);+ } else if (SEARCH_ALIASES[word] && matchAliases(SEARCH_ALIASES[word]!)) {+ // counted by matchAliases+ } else if (hasStem(word)) {+ covered++;+ use(word);+ }+ }+ for (const aliases of phrases) matchAliases(aliases);++ // The module prefix and a lookup's "get" are never extra.+ const moduleWords = new Set(+ splitWords(tool.name.slice(0, Math.max(separator, 0))).split(" ")+ );+ const extra = tokens.filter(+ (token) => !used.has(token) && !moduleWords.has(token) && token !== "get"+ ).length;+ const readFirst = !hasAction && tool.classification === "READ" ? 1 : 0;+ const fullSet = !tool.paginates && tool.name.endsWith("List") ? 1 : 0;+ return { tool, covered, full, readFirst, extra, fullSet, bm25Rank };+ });++ scored.sort(+ (a, b) =>+ b.covered - a.covered ||+ b.full - a.full ||+ b.readFirst - a.readFirst ||+ a.extra - b.extra ||+ a.fullSet - b.fullSet ||+ a.bm25Rank - b.bm25Rank+ );+ return scored.map((entry) => entry.tool);+}++/**+ * One word in two inflections. `stemInflection` alone misses plurals Porter+ * over-stems ("materials" stays "materials" because Porter makes it "materi"),+ * so a plain -s/-es plural also counts.+ */+function sameWord(a: string, b: string): boolean {+ if (a === b || stemInflection(a) === stemInflection(b)) return true;+ const [short, long] = a.length < b.length ? [a, b] : [b, a];+ return long === `${short}s` || long === `${short}es`;+}++/** How many BM25 hits the name re-rank reorders. */+const RERANK_POOL = 200;+export type CatalogSearchOptions = {query?: string;module?: string;@@ -176,6 +383,21 @@ async function buildIndex(tools: ManifestEntry[]) {export function createCatalogSearch(tools: ManifestEntry[]): CatalogSearch {const byName = new Map(tools.map((tool) => [tool.name, tool]));+ const byLowerName = new Map(+ tools.map((tool) => [tool.name.toLowerCase(), tool])+ );+ // "getJobs" without its module: every tool whose function part is that name.+ const byFunction = new Map<string, ManifestEntry[]>();+ for (const tool of tools) {+ const fn = tool.name.slice(tool.name.indexOf("_") + 1).toLowerCase();+ byFunction.set(fn, [...(byFunction.get(fn) ?? []), tool]);+ }+ const actions = new Set(+ tools.map(+ (tool) =>+ splitWords(tool.name.slice(tool.name.indexOf("_") + 1)).split(" ")[0]!+ )+ );const moduleNames = [...new Set(tools.map((tool) => tool.module))].sort();// Built lazily on the first query so importing this module stays free.@@ -227,8 +449,8 @@ export function createCatalogSearch(tools: ManifestEntry[]): CatalogSearch {)[],boost: { name: 4, tokens: 3, description: 1.5, fields: 0.5 },...(Object.keys(where).length > 0 ? { where } : {}),- limit,- offset+ limit: Math.max(RERANK_POOL, offset + limit),+ offset: 0};const db = await getIndex();@@ -239,11 +461,31 @@ export function createCatalogSearch(tools: ManifestEntry[]): CatalogSearch {results = await search(db, { ...params, tolerance: 1 });}+ const passesFilters = (tool: ManifestEntry) =>+ (!modules || modules.includes(tool.module)) &&+ (!classification || tool.classification === classification);++ // An exact tool name, with or without its module, always comes first.+ const needle = query!.trim().toLowerCase();+ const exactHits = (+ byLowerName.has(needle)+ ? [byLowerName.get(needle)!]+ : (byFunction.get(needle) ?? [])+ ).filter(passesFilters);++ const hits = results.hits+ .map((hit) => byName.get((hit.document as { name: string }).name))+ .filter((tool): tool is ManifestEntry => tool !== undefined);+ const ranked = [+ ...exactHits,+ ...rerankByName(query!, hits, actions).filter(+ (tool) => !exactHits.includes(tool)+ )+ ];+return {- matches: results.hits- .map((hit) => byName.get((hit.document as { name: string }).name))- .filter((tool): tool is ManifestEntry => tool !== undefined),- total: results.count+ matches: ranked.slice(offset, offset + limit),+ total: Math.max(results.count, exactHits.length)};}diff --git a/packages/ee/src/mcp/describe-format.ts b/packages/ee/src/mcp/describe-format.tsindex 2cc0ac9b72..27bc876ca1 100644--- a/packages/ee/src/mcp/describe-format.ts+++ b/packages/ee/src/mcp/describe-format.ts@@ -4,8 +4,9 @@// 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.+// TypeScript types: the generator derives them from TS types and uses only+// type/enum/anyOf/properties/required/items/additionalProperties, so the type+// says everything the JSON Schema does in about a third of the characters.import type { ManifestEntry } from "@carbon/api";import { MCP_DEFAULT_LIMIT } from "./format-result";@@ -23,6 +24,133 @@ export function deriveNameDescription(name: string): string {.toLowerCase();}+/**+ * The description search_tools prints under a tool: its first paragraph (the+ * summary; `describe_tool` has the rest), or null when that only restates the+ * name.+ */+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)+ ? summary+ : null;+}++type JsonSchema = {+ type?: string | string[];+ enum?: unknown[];+ anyOf?: JsonSchema[];+ properties?: Record<string, JsonSchema>;+ required?: string[];+ items?: JsonSchema;+ additionalProperties?: JsonSchema | boolean;+ description?: string;+};++const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;++/**+ * Render a manifest JSON Schema as a TypeScript type:+ * `{ id: string; limit?: number; status?: "Draft" | "Posted" | null }`.+ * An empty schema reads `unknown`; an open object's extra keys are not shown.+ */+export function formatSchemaType(schema: unknown): string {+ return unionMembers(schema).join(" | ");+}++/** The top-level alternatives of a schema's type, deduplicated. */+function unionMembers(schema: unknown): string[] {+ const node = (schema ?? {}) as JsonSchema;+ if (node.enum) {+ return [...new Set(node.enum.map((value) => JSON.stringify(value)))];+ }+ if (node.anyOf) return [...new Set(node.anyOf.flatMap(unionMembers))];+ const types =+ node.type === undefined+ ? node.properties+ ? ["object"]+ : node.items+ ? ["array"]+ : []+ : Array.isArray(node.type)+ ? node.type+ : [node.type];+ if (types.length === 0) return ["unknown"];+ return [+ ...new Set(+ types.map((type) => {+ if (type === "integer") return "number";+ if (type === "array") {+ const item = unionMembers(node.items);+ return item.length > 1 ? `(${item.join(" | ")})[]` : `${item[0]}[]`;+ }+ if (type === "object") return formatObjectType(node);+ return type;+ })+ )+ ];+}++function formatObjectType(node: JsonSchema): string {+ const properties = Object.entries(node.properties ?? {});+ if (properties.length === 0) {+ const extra = node.additionalProperties;+ return extra && typeof extra === "object"+ ? `Record<string, ${formatSchemaType(extra)}>`+ : "object";+ }+ const required = new Set(node.required ?? []);+ const fields = properties.map(([key, value]) => {+ const name = IDENTIFIER.test(key) ? key : JSON.stringify(key);+ const note = value.description ? ` /* ${value.description} */` : "";+ return `${name}${required.has(key) ? "" : "?"}: ${formatSchemaType(value)}${note}`;+ });+ return `{ ${fields.join("; ")} }`;+}++/**+ * The tool names closest to a name that does not exist, by edit distance, for+ * a "did you mean" answer. A typo ("getInventoryItem") is one or two edits from+ * the real name, which ranked search does not reward. Names further than a+ * third of the name's length away are not suggested.+ */+export function closestToolNames(+ name: string,+ names: Iterable<string>,+ limit = 3+): string[] {+ const target = name.toLowerCase();+ const maxDistance = Math.max(3, Math.floor(target.length / 3));+ return [...names]+ .map((candidate) => ({+ candidate,+ distance: editDistance(target, candidate.toLowerCase())+ }))+ .filter(({ distance }) => distance <= maxDistance)+ .sort((a, b) => a.distance - b.distance)+ .slice(0, limit)+ .map(({ candidate }) => candidate);+}++/** Levenshtein distance, one row at a time. */+function editDistance(a: string, b: string): number {+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);+ for (let i = 1; i <= a.length; i++) {+ const current = [i];+ for (let j = 1; j <= b.length; j++) {+ current[j] = Math.min(+ previous[j]! + 1,+ current[j - 1]! + 1,+ previous[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1)+ );+ }+ previous = current;+ }+ return previous[b.length]!;+}+/*** 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@@ -87,9 +215,9 @@ export function formatToolDescription(output += "\n";}}- output += `\nInput Schema:\n${JSON.stringify(tool.schema ?? {})}`;+ output += `\nInput: ${formatSchemaType(tool.schema ?? {})}`;if (tool.responseSchema) {- output += `\n\nResponse Schema (null fields are omitted from results):\n${JSON.stringify(+ output += `\nReturns (null fields are omitted): ${formatSchemaType(tool.responseSchema)}`;}diff --git a/packages/ee/src/mcp/format-result.ts b/packages/ee/src/mcp/format-result.tsindex db2da0aeed..c724c89a1d 100644--- a/packages/ee/src/mcp/format-result.ts+++ b/packages/ee/src/mcp/format-result.ts@@ -6,15 +6,18 @@// 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`.+// null-stripped rows (an ERP row is ~half null columns), optional field+// projection, and a row and character budget so one wide page cannot flood the context./** 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. */+/** Most rows one call returns; a larger `limit` is clamped to it. */export const MCP_MAX_ROWS = 100;+/** Most characters of rows one call returns (~5k tokens). */+export const MCP_MAX_CHARS = 20_000;+/*** Drop null/undefined OBJECT ENTRIES recursively. Array elements are kept* positionally (a null element may be meaningful; a null field is just an@@ -51,24 +54,62 @@ export function pageMcpListResult(}/**- * 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.+ * Keep only the named top-level fields of each row (or of a single object).+ * Wide ERP rows carry 50+ columns; an agent that needs three of them should not+ * pay for the rest.*/-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;- }+export function projectFields(data: unknown, fields?: string[]): unknown {+ if (!fields?.length) return data;+ const pick = (row: unknown) => {+ if (row === null || typeof row !== "object" || Array.isArray(row)) {+ return row;+ }+ const out: Record<string, unknown> = {};+ for (const field of fields) {+ if (field in row) out[field] = (row as Record<string, unknown>)[field];+ }+ return out;+ };+ return Array.isArray(data) ? data.map(pick) : pick(data);+}- 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`;+/**+ * Serialize a call_tool result for the MCP text response. A list is cut at+ * `MCP_MAX_ROWS` rows or `MCP_MAX_CHARS` characters, whichever comes first,+ * and any list short of its total ends with the offset of the next page, so an+ * agent pages deliberately instead of assuming it saw everything. `count` is+ * the operation's total when the read was paginated; `offset` is where this+ * page starts.+ */+export function formatMcpResult(+ data: unknown,+ count?: number,+ offset = 0+): string {+ if (!Array.isArray(data)) return JSON.stringify(stripNulls(data)) ?? "";++ const serialized: string[] = [];+ let length = 2;+ for (const row of data) {+ if (serialized.length === MCP_MAX_ROWS) break;+ const text = JSON.stringify(stripNulls(row)) ?? "null";+ // Always emit one row: a single row over budget still answers the call.+ if (serialized.length > 0 && length + text.length + 1 > MCP_MAX_CHARS) {+ break;+ }+ serialized.push(text);+ length += text.length + 1;}- if (typeof count === "number" && Array.isArray(data) && count > data.length) {- text += `\n(showing ${Array.isArray(rows) ? rows.length : data.length} of ${count} rows)`;++ let text = `[${serialized.join(",")}]`;+ const total = typeof count === "number" ? count : offset + data.length;+ const next = offset + serialized.length;+ if (next < total) {+ text += `\n(rows ${serialized.length ? `${offset + 1}-${next}` : "none"} of ${total}; next page: offset ${next}`;+ if (serialized.length < data.length) {+ text += `, output capped at ${MCP_MAX_CHARS} characters, pass \`fields\` to return only the columns you need`;+ }+ text += ")";}return text;}diff --git a/packages/ee/src/mcp/instructions.ts b/packages/ee/src/mcp/instructions.tsindex c3075a0497..4802ba6169 100644--- a/packages/ee/src/mcp/instructions.ts+++ b/packages/ee/src/mcp/instructions.ts@@ -7,7 +7,7 @@// tool catalog is passed in (the generated `tool-metadata.json` lives in the app,// derived from its `~/modules/*`), never imported here.import type { ManifestEntry } from "@carbon/api";-import { MCP_DEFAULT_LIMIT } from "./format-result";+import { MCP_DEFAULT_LIMIT, MCP_MAX_ROWS } from "./format-result";export type ToolCatalogSummary = {tools: Pick<ManifestEntry, "module">[];@@ -22,49 +22,16 @@ export function getServerInstructions(const moduleNames = [...new Set(toolMetadata.tools.map((tool) => tool.module))].sort();- return `Carbon ERP Manufacturing System-==========================================-Date: ${today}--IMPORTANT: Tool Discovery System-This server has ${toolMetadata.totalTools} tools available across ${toolMetadata.modules} modules:-${moduleNames.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. The parameters go straight in "arguments" — the ones-// describe_tool lists, nothing wrapped around them.-call_tool({- name: "sales_getCustomers",- arguments: { 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)-- Pass parameters flat in "arguments", exactly as describe_tool lists them-- 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`;+ return `Carbon ERP (manufacturing). Today is ${today}.++${toolMetadata.totalTools} operations across ${toolMetadata.modules} modules (${moduleNames.join(", ")}) are reached through three tools:+1. search_tools({ query: "purchase orders" }): ranked search. Takes an exact operation name, or abbreviations like PO, RMA, BOM, NCR; filter with module or classification (READ, WRITE, DESTRUCTIVE).+2. describe_tool({ names: ["sales_getCustomers", "sales_upsertCustomer"] }): input and response types, up to 10 per call. Simple reads need no describe: search lists their required parameters.+3. call_tool({ name: "sales_getCustomers", arguments: { limit: 10 }, fields: ["id", "name"] }): run one. "arguments" is a JSON object of the parameters describe_tool lists, flat.++- companyId and userId come from your credential; never pass them.+- Results are compact JSON with null fields omitted: an absent field means null.+- List reads default to ${MCP_DEFAULT_LIMIT} rows and return at most ${MCP_MAX_ROWS}. A list short of its total ends with "(rows A-B of TOTAL; next page: offset N)".+- Pass "fields" to return only the columns you need. To count rows, call with arguments.limit 1 and fields ["id"], then read TOTAL.+- Dates: ISO 8601 (YYYY-MM-DD).`;}diff --git a/packages/ee/src/mcp/server.test.ts b/packages/ee/src/mcp/server.test.tsindex 44cf753faf..78bd851c96 100644--- a/packages/ee/src/mcp/server.test.ts+++ b/packages/ee/src/mcp/server.test.ts@@ -8,10 +8,14 @@ import {nameRequestSpan,withSpan} from "@carbon/logger/tracing.server";-import { Client } from "@modelcontextprotocol/sdk/client/index.js";-import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import {+ Client,+ StreamableHTTPClientTransport+} from "@modelcontextprotocol/client";import { beforeEach, describe, expect, it, vi } from "vitest";-import { createMcpServer } from "./server";+import { requireEntitlement } from "../entitlements.server";+import { serveMcpRequest } from "./server";+import type { McpCallResult } from "./types";vi.mock("@carbon/logger/tracing.server", () => ({annotateRequestSpan: vi.fn(),@@ -27,34 +31,56 @@ vi.mock("../entitlements.server", () => ({requireEntitlement: vi.fn(async () => undefined)}));-const callOperation = vi.fn(async () => ({- success: true as const,- data: [{ id: "cust_1" }]-}));+const callOperation = vi.fn(+ async (): Promise<McpCallResult> => ({+ success: true,+ data: [{ id: "cust_1" }]+ })+);-async function connect() {- const server = await createMcpServer(+const ctx = {+ client: {},+ companyId: "co1",+ companyGroupId: "g1",+ userId: "u1"+} as never;++/**+ * A real MCP client talking HTTP to `serveMcpRequest`, the function the route+ * calls. `era` picks the protocol: "legacy" is the 2025 `initialize` handshake+ * every client uses by default; "modern" pins the 2026-07-28 revision.+ */+async function connect(+ entry: Record<string, unknown> = {+ name: "sales_getCustomer",+ module: "sales"+ },+ isList = false,+ era: "legacy" | "modern" = "legacy"+) {+ const deps = {+ callOperation,+ operationsByName: new Map([[entry.name, entry]]),+ isListOperation: () => isList,+ catalogSearch: { search: async () => ({ matches: [], total: 0 }) },+ toolMetadata: { tools: [{ module: "sales" }], totalTools: 1, modules: 1 }+ } as never;+ const transport = new StreamableHTTPClientTransport(+ new URL("https://carbon.test/api/mcp"),{- client: {},- companyId: "co1",- companyGroupId: "g1",- userId: "u1"- } as never,- "2026-10-01",+ fetch: (url, init) =>+ serveMcpRequest(new Request(url, init), ctx, "2026-10-01", deps)+ }+ );+ const client = new Client(+ { name: "test", version: "0.0.0" },{- callOperation,- operationsByName: new Map([- ["sales_getCustomer", { name: "sales_getCustomer", module: "sales" }]- ]),- isListOperation: () => false,- catalogSearch: { search: async () => ({ matches: [], total: 0 }) },- toolMetadata: { tools: [{ module: "sales" }], totalTools: 1, modules: 1 }- } as never+ versionNegotiation: {+ mode: era === "modern" ? { pin: "2026-07-28" } : "legacy"+ }+ });- const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();- await server.connect(serverSide);- const client = new Client({ name: "test", version: "0.0.0" });- await client.connect(clientSide);+ await client.connect(transport);return client;}@@ -118,3 +144,149 @@ describe("MCP tool calls are traced", () => {);});});++describe("call_tool keeps list output small", () => {+ beforeEach(() => vi.clearAllMocks());++ it("clamps a paged read's limit, projects fields and names the next page", async () => {+ callOperation.mockResolvedValueOnce({+ success: true,+ data: [{ id: "cust_1", name: "Acme", fax: "x", notes: "long" }],+ count: 300+ });+ const client = await connect(+ { name: "sales_getCustomers", module: "sales", paginates: true },+ true+ );++ const result = await client.callTool({+ name: "call_tool",+ arguments: {+ name: "sales_getCustomers",+ arguments: { limit: 1000, offset: 40 },+ fields: ["id", "name"]+ }+ });++ expect(callOperation).toHaveBeenCalledWith(+ "sales_getCustomers",+ expect.anything(),+ { limit: 100, offset: 40 }+ );+ expect(result.content).toEqual([+ {+ type: "text",+ text: '[{"id":"cust_1","name":"Acme"}]\n(rows 41-41 of 300; next page: offset 41)'+ }+ ]);+ });++ it("pages a full-set read at the boundary with the clamped limit", async () => {+ callOperation.mockResolvedValueOnce({+ success: true,+ data: Array.from({ length: 250 }, (_, i) => ({ id: i }))+ });+ const client = await connect(+ { name: "sales_getCustomersList", module: "sales", paginates: false },+ true+ );++ const result = await client.callTool({+ name: "call_tool",+ arguments: {+ name: "sales_getCustomersList",+ arguments: { limit: 500, offset: 200 }+ }+ });++ const text = (result.content as { text: string }[])[0]!.text;+ expect(text.startsWith('[{"id":200},')).toBe(true);+ expect(text).not.toContain('"id":199');+ expect(text).not.toContain("next page");+ });+});++describe("serveMcpRequest", () => {+ beforeEach(() => vi.clearAllMocks());++ it("serves a 2026-07-28 client with the same tools", async () => {+ const client = await connect(undefined, false, "modern");+ expect(client.getNegotiatedProtocolVersion()).toBe("2026-07-28");+ expect(client.getInstructions()).toContain("search_tools");++ const result = await client.callTool({+ name: "call_tool",+ arguments: { name: "sales_getCustomer", arguments: { customerId: "c" } }+ });+ expect(result.content).toEqual([+ { type: "text", text: '[{"id":"cust_1"}]' }+ ]);+ const { tools } = await client.listTools();+ expect(tools.map((tool) => tool.name).sort()).toEqual([+ "call_tool",+ "describe_tool",+ "search_tools"+ ]);+ });++ it("answers a 2025 client with JSON, not an event stream", async () => {+ const response = await serveMcpRequest(+ new Request("https://carbon.test/api/mcp", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ accept: "application/json, text/event-stream"+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: 1,+ method: "tools/list",+ params: {}+ })+ }),+ ctx,+ "2026-10-01",+ {+ callOperation,+ operationsByName: new Map(),+ isListOperation: () => false,+ catalogSearch: { search: async () => ({ matches: [], total: 0 }) },+ toolMetadata: { tools: [], totalTools: 0, modules: 0 }+ } as never+ );+ expect(response.headers.get("content-type")).toContain("application/json");+ const body = await response.json();+ expect(body.result.tools).toHaveLength(3);+ });++ it("refuses a subscription instead of holding the request open", async () => {+ const client = await connect(undefined, false, "modern");+ await expect(client.listen({ toolsListChanged: true })).rejects.toThrow(+ "Subscription limit reached"+ );+ });++ it("names the closest tools for an unknown one instead of calling it", async () => {+ const client = await connect();+ const result = await client.callTool({+ name: "call_tool",+ arguments: { name: "sales_getCustomr", arguments: {} }+ });+ expect(result.isError).toBe(true);+ expect(result.content).toEqual([+ {+ type: "text",+ text: "Tool 'sales_getCustomr' not found. Did you mean: sales_getCustomer?"+ }+ ]);+ expect(callOperation).not.toHaveBeenCalled();+ });++ it("refuses before serving when the company is not entitled", async () => {+ vi.mocked(requireEntitlement).mockRejectedValueOnce(+ new Error("not entitled")+ );+ await expect(connect()).rejects.toThrow("not entitled");+ expect(callOperation).not.toHaveBeenCalled();+ });+});diff --git a/packages/ee/src/mcp/server.ts b/packages/ee/src/mcp/server.tsindex eca6be26c6..645648623d 100644--- a/packages/ee/src/mcp/server.ts+++ b/packages/ee/src/mcp/server.ts@@ -2,7 +2,6 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-// @ts-nocheckimport { getLogger } from "@carbon/logger";import { describeRequest } from "@carbon/logger/middleware.server";import {@@ -10,19 +9,27 @@ import {nameRequestSpan,withSpan} from "@carbon/logger/tracing.server";-import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import {+ createMcpHandler,+ isLegacyRequest,+ McpServer,+ WebStandardStreamableHTTPServerTransport+} from "@modelcontextprotocol/server";import { z } from "zod";import { requireEntitlement } from "../entitlements.server";import {- deriveNameDescription,+ closestToolNames,formatParamSummary,formatToolDescription,- paginatingSibling+ paginatingSibling,+ searchLineDescription} from "./describe-format";import {formatMcpResult,MCP_DEFAULT_LIMIT,- pageMcpListResult+ MCP_MAX_ROWS,+ pageMcpListResult,+ projectFields} from "./format-result";import { getServerInstructions } from "./instructions";import {@@ -35,19 +42,62 @@ import {const logger = getLogger("erp", "mcp");-// The MCP protocol server — the commercial feature body. The app's dispatch,-// tool manifest and generated catalog are INJECTED via-// `deps` (they derive from `apps/erp`'s `~/modules/*` and cannot move into a-// package); the entitlement LOCK lives here so serving MCP requires executing-// commercial code. `Ctx` is the caller's full auth context (the app's-// `AuthedContext`), passed straight through to `deps.callOperation`.-export async function createMcpServer<Ctx extends McpContext>(+/** search_tools results per call when the caller passes no `limit`. */+const SEARCH_DEFAULT_LIMIT = 10;++type ToolResult = {+ content: { type: "text"; text: string }[];+ isError?: boolean;+};++/**+ * Serve one MCP request. The commercial feature body: the app's dispatch, tool+ * manifest and generated catalog are INJECTED via `deps` (they derive from+ * `apps/erp`'s `~/modules/*` and cannot move into a package); the entitlement+ * LOCK lives here so serving MCP requires executing commercial code. `Ctx` is+ * the caller's full auth context (the app's `AuthedContext`), passed straight+ * through to `deps.callOperation`. Throws `EntitlementError` before anything is+ * served.+ *+ * Both protocol eras are served by one server definition:+ * - 2025-era requests (every client's default handshake) keep the wiring they+ * had on SDK v1: a stateless transport with JSON responses. The SDK's own+ * stateless fallback would answer them with SSE instead.+ * - 2026-07-28 requests go through `createMcpHandler`. `maxSubscriptions: 0`+ * refuses `subscriptions/listen` in-band: it holds a stream open, which a+ * per-request serverless function cannot keep, and the tool list never+ * changes at runtime.+ */+export async function serveMcpRequest<Ctx extends McpContext>(+ request: Request,ctx: Ctx,today: string,deps: McpServerDeps<Ctx>-): Promise<McpServer> {+): Promise<Response> {await requireEntitlement(ctx.client, ctx.companyId, "MCP");+ const factory = () => buildMcpServer(ctx, today, deps);++ if (await isLegacyRequest(request)) {+ const transport = new WebStandardStreamableHTTPServerTransport({+ sessionIdGenerator: undefined,+ enableJsonResponse: true+ });+ await factory().connect(transport);+ return transport.handleRequest(request);+ }+ return createMcpHandler(factory, {+ legacy: "reject",+ maxSubscriptions: 0,+ onerror: (error) => logger.warn("MCP request refused", { error })+ }).fetch(request);+}++function buildMcpServer<Ctx extends McpContext>(+ ctx: Ctx,+ today: string,+ deps: McpServerDeps<Ctx>+): McpServer {const {callOperation,operationsByName,@@ -68,12 +118,16 @@ export async function createMcpServer<Ctx extends McpContext>(// One span per tool call. An operation name comes from the client, so it is// put in the span name only when it is a real operation.- const registerTool = server.registerTool.bind(server);- server.registerTool = (tool, config, handler) =>- registerTool(tool, config, (params, extra) => {- const operation = operationsByName.has(params?.name)- ? params.name- : undefined;+ const traced =+ <P extends Record<string, unknown>>(+ tool: string,+ handler: (params: P) => Promise<ToolResult>+ ) =>+ (params: P) => {+ const operation =+ typeof params?.name === "string" && operationsByName.has(params.name)+ ? params.name+ : undefined;const attributes = {"carbon.mcp.tool": tool,...(operation ? { "carbon.operation": operation } : {})@@ -82,8 +136,17 @@ export async function createMcpServer<Ctx extends McpContext>(annotateRequestSpan(attributes);nameRequestSpan(`POST /api/mcp ${call}`);describeRequest(call);- return withSpan(`mcp ${call}`, attributes, () => handler(params, extra));- });+ return withSpan(`mcp ${call}`, attributes, () => handler(params));+ };++ // An unknown name is usually a typo; naming the closest tools saves the+ // agent a search round trip.+ const notFound = (toolName: string) => {+ const closest = closestToolNames(toolName, operationsByName.keys());+ return closest.length > 0+ ? `Tool '${toolName}' not found. Did you mean: ${closest.join(", ")}?`+ : `Tool '${toolName}' not found. Use search_tools to find it.`;+ };// Register describe_tool to get schema information for any toolserver.registerTool(@@ -104,57 +167,58 @@ export async function createMcpServer<Ctx extends McpContext>(}),annotations: READ_ONLY_ANNOTATIONS},- withErrorHandling(async (params: any) => {- const { name, names } = params;- const requested: string[] = names?.length ? names : name ? [name] : [];+ traced(+ "describe_tool",+ withErrorHandling(async (params: any) => {+ const { name, names } = params;+ const requested: string[] = names?.length ? names : name ? [name] : [];++ logger.info("describe_tool invoked", { names: requested });++ if (requested.length === 0) {+ return {+ content: [+ {+ type: "text" as const,+ text: "Pass a tool `name` or a `names` array"+ }+ ],+ isError: true+ };+ }++ 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),+ sibling: meta.paginates+ ? null+ : paginatingSibling(meta.name, (n) => operationsByName.get(n))+ })+ );+ }- logger.info("describe_tool invoked", { names: requested });+ 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(notFound).join("\n"));+ }- if (requested.length === 0) {return {content: [- {- type: "text" as const,- text: "Pass a tool `name` or a `names` array"- }+ { type: "text" as const, text: sections.join("\n\n---\n\n") }],- isError: true+ ...(missing.length === requested.length ? { isError: true } : {})};- }-- 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),- sibling: meta.paginates- ? null- : paginatingSibling(meta.name, (n) => operationsByName.get(n))- })- );- }-- 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: sections.join("\n\n---\n\n") }- ],- ...(missing.length === requested.length ? { isError: true } : {})- };- }, "Describe tool failed")+ }, "Describe tool failed")+ ));// Register call_tool with direct execution@@ -164,119 +228,152 @@ export async function createMcpServer<Ctx extends McpContext>(description: "Call any ERP tool by name with the specified parameters",inputSchema: z.object({name: z.string().describe("The name of the tool to call"),- arguments: z.any().describe("The arguments to pass to the tool")+ arguments: z.any().describe("The arguments to pass to the tool"),+ fields: z+ .array(z.string())+ .optional()+ .describe(+ 'Return only these top-level fields of each row, e.g. ["id", "name"]. Rows can have 50+ fields; name the ones you need'+ )}),annotations: WRITE_ANNOTATIONS},- withErrorHandling(async (params: any) => {- const { name, arguments: rawArgs } = params;- let args = rawArgs;-- // Some MCP clients send arguments as a JSON string; normalize to object.- if (typeof args === "string") {- try {- args = args.trim().length > 0 ? JSON.parse(args) : {};- } catch {+ traced(+ "call_tool",+ withErrorHandling(async (params: any) => {+ const { name, arguments: rawArgs, fields } = params;+ if (!operationsByName.has(name)) {+ logger.warn("Tool not found", { names: [name] });return {- content: [- {- type: "text" as const,- text: "Invalid JSON in call_tool.arguments"- }- ],+ content: [{ type: "text" as const, text: notFound(name) }],isError: true};}- }-- logger.info("call_tool invoked", { name, arguments: args });-- // 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). MCP-only; the other- // callOperation callers (HTTP, agent, workflows) are untouched.- // Two kinds of list service (manifest `paginates`):- // - paginating (setGenericQueryFilters/.range): inject the PAIR — its- // `.range()` applies only when BOTH limit and offset are integers, so- // a bare `limit` silently paginated nothing.- // - fetchAll (`get*List`): limit/offset are inert in the service, so the- // caller's paging is captured here and applied to the RESPONSE below —- // without this, `limit: 1` returned every row.- 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);- let mcpPaging: { limit: number; offset: number } | null = null;- if (meta && isListOperation(meta)) {- const body =- args && typeof args === "object" && !Array.isArray(args)- ? (args as Record<string, unknown>)- : null;- if (meta.paginates) {- if (!body) {- // The argless call is the worst offender — no limit at all.- args = { limit: MCP_DEFAULT_LIMIT, offset: 0 };+ let args = rawArgs;++ // Some MCP clients send arguments as a JSON string; normalize to object.+ if (typeof args === "string") {+ try {+ args = args.trim().length > 0 ? JSON.parse(args) : {};+ } catch {+ return {+ content: [+ {+ type: "text" as const,+ text: "Invalid JSON in call_tool.arguments"+ }+ ],+ isError: true+ };+ }+ }++ logger.info("call_tool invoked", { name, arguments: args });++ // 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). MCP-only; the other+ // callOperation callers (HTTP, agent, workflows) are untouched.+ // Two kinds of list service (manifest `paginates`):+ // - paginating (setGenericQueryFilters/.range): inject the PAIR — its+ // `.range()` applies only when BOTH limit and offset are integers, so+ // a bare `limit` silently paginated nothing.+ // - fetchAll (`get*List`): limit/offset are inert in the service, so the+ // caller's paging is captured here and applied to the RESPONSE below —+ // without this, `limit: 1` returned every row.+ // A limit above MCP_MAX_ROWS is clamped: the formatter would drop the+ // extra rows anyway, after the database had read them.+ const fillPagination = (target: Record<string, unknown>) => {+ if (target.limit === undefined) target.limit = MCP_DEFAULT_LIMIT;+ if (typeof target.limit === "number" && target.limit > MCP_MAX_ROWS) {+ target.limit = MCP_MAX_ROWS;+ }+ if (target.offset === undefined) target.offset = 0;+ };+ const meta = operationsByName.get(name);+ let mcpPaging: { limit: number; offset: number } | null = null;+ if (meta && isListOperation(meta)) {+ const body =+ args && typeof args === "object" && !Array.isArray(args)+ ? (args as Record<string, unknown>)+ : null;+ if (meta.paginates) {+ if (!body) {+ // The argless call is the worst offender — no limit at all.+ args = { limit: MCP_DEFAULT_LIMIT, offset: 0 };+ } else {+ fillPagination(body);+ }} else {- fillPagination(body);+ const source = body ?? {};+ const limit = source.limit;+ const offset = source.offset;+ mcpPaging = {+ limit:+ Number.isInteger(limit) && (limit as number) > 0+ ? Math.min(limit as number, MCP_MAX_ROWS)+ : MCP_DEFAULT_LIMIT,+ offset:+ Number.isInteger(offset) && (offset as number) >= 0+ ? (offset as number)+ : 0+ };}- } else {- const source = body ?? {};- const limit = source.limit;- const offset = source.offset;- mcpPaging = {- limit:- Number.isInteger(limit) && (limit as number) > 0- ? (limit as number)- : MCP_DEFAULT_LIMIT,- offset:- Number.isInteger(offset) && (offset as number) >= 0- ? (offset as number)- : 0- };}- }- // Runs the operation's oRPC procedure (gate included); a list arrives as- // `data` with its `count`.- const start = performance.now();- const result = await callOperation(name, ctx, args);- const responseTime = performance.now() - start;+ // Runs the operation's oRPC procedure (gate included); a list arrives as+ // `data` with its `count`.+ const start = performance.now();+ const result = await callOperation(name, ctx, args);+ const responseTime = performance.now() - start;- if (result.success) {- logger.info("Execution result", {+ if (result.success) {+ logger.info("Execution result", {+ name,+ success: true,+ hasData: result.data !== undefined,+ responseTime+ });+ let output: string;+ if (result.data === undefined) {+ output = "Operation completed successfully";+ } else if (mcpPaging) {+ const { rows, total } = pageMcpListResult(result.data, mcpPaging);+ output = formatMcpResult(+ projectFields(rows, fields),+ total,+ mcpPaging.offset+ );+ } else {+ const offset =+ meta?.paginates && Number.isInteger(args?.offset)+ ? args.offset+ : 0;+ output = formatMcpResult(+ projectFields(result.data, fields),+ result.count,+ offset+ );+ }+ return { content: [{ type: "text" as const, text: output }] };+ }+ logger.error("Tool execution failed", {name,- success: true,- hasData: result.data !== undefined,+ error: result.error,+ errorKind: result.errorKind,responseTime});- let output: string;- if (result.data === undefined) {- output = "Operation completed successfully";- } else if (mcpPaging) {- const { rows, total } = pageMcpListResult(result.data, mcpPaging);- output = formatMcpResult(rows, total);- } else {- output = formatMcpResult(result.data, result.count);- }- return { content: [{ type: "text" as const, text: output }] };- }- logger.error("Tool execution failed", {- name,- error: result.error,- errorKind: result.errorKind,- responseTime- });- return {- content: [- {- type: "text" as const,- text: `Error: ${result.error}`- }- ],- isError: true- };- }, "Call tool failed")+ return {+ content: [+ {+ type: "text" as const,+ text: `Error: ${result.error}`+ }+ ],+ isError: true+ };+ }, "Call tool failed")+ ));// Register search_tools for discovery@@ -294,79 +391,79 @@ export async function createMcpServer<Ctx extends McpContext>(),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),+ limit: z.number().int().min(1).max(100).default(SEARCH_DEFAULT_LIMIT),offset: z.number().int().min(0).default(0)}),annotations: READ_ONLY_ANNOTATIONS},- withErrorHandling(async (params: any) => {- const { query, module, classification, limit = 20, offset = 0 } = params;-- // 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,- module,- classification,- limit,- offset,- matched: total,- returned: toolNames.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, []);+ traced(+ "search_tools",+ withErrorHandling(async (params: any) => {+ const {+ query,+ module,+ classification,+ limit = SEARCH_DEFAULT_LIMIT,+ offset = 0+ } = params;++ // 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+ });++ logger.info("search_tools invoked", {+ query,+ module,+ classification,+ limit,+ offset,+ matched: total,+ returned: matches.length+ });++ // Build response+ let output = `Found ${total} tools`;+ if (total > limit) {+ output += ` (showing ${offset + 1}-${offset + matches.length}, ranked by relevance)`;}- 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`;- if (tool.description !== deriveNameDescription(tool.name)) {- output += ` ${tool.description}\n`;+ 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);}- 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: total++ // 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";}- };- }, "Search failed")++ // No footer: the describe_tool/call_tool how-to and the catalog size+ // ship once in the server instructions at connect.+ output = output.trimEnd();++ return { content: [{ type: "text" as const, text: output }] };+ }, "Search failed")+ ));return server;diff --git a/packages/ee/src/mcp/types.ts b/packages/ee/src/mcp/types.tsindex 7209b4011c..20c1b2a324 100644--- a/packages/ee/src/mcp/types.ts+++ b/packages/ee/src/mcp/types.ts@@ -12,7 +12,7 @@ const logger = getLogger("erp", "mcp");/** The minimum an MCP request context must carry for the engine — the caller* (the app route) passes its full `AuthedContext`, which is a superset. The- * engine is generic over the concrete context (see `createMcpServer`), so the+ * engine is generic over the concrete context (see `serveMcpRequest`), so the* app's dispatch (`deps.callOperation`) receives the real context unchanged;* the engine itself only reads `client`/`companyId` (for the entitlement gate). */export type McpContext = {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6154872484..0cdf9a46b0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -786,9 +786,6 @@ importers:'@lingui/react':specifier: 'catalog:'- '@modelcontextprotocol/sdk':- specifier: 1.31.0- version: 1.31.0([email protected])'@monaco-editor/react':specifier: 4.7.0@@ -1859,13 +1856,13 @@ importers:version: 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])fumadocs-core:specifier: ^16.14.0- version: 16.15.14(@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 16.15.14(@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])fumadocs-mdx:specifier: ^15.4.0- version: 15.4.5(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 15.4.5(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))fumadocs-ui:specifier: ^16.14.0- version: 16.15.14(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])+ version: 16.15.14(@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])motion:specifier: ^12version: 12.38.0(@emotion/[email protected])([email protected]([email protected]))([email protected])@@ -2565,9 +2562,9 @@ importers:'@lingui/core':specifier: 'catalog:'version: 6.9.0(@babel/[email protected])([email protected])- '@modelcontextprotocol/sdk':- specifier: 1.31.0- version: 1.31.0([email protected])+ '@modelcontextprotocol/server':+ specifier: 2.3.1+ version: 2.3.1'@slack/bolt':specifier: 4.4.0version: 4.4.0(@types/[email protected])@@ -2650,6 +2647,9 @@ importers:'@logtape/testing':specifier: 'catalog:'version: 2.2.3(@logtape/[email protected])+ '@modelcontextprotocol/client':+ specifier: 2.3.1+ version: 2.3.1'@types/nodemailer':specifier: 6.4.21version: 6.4.21@@ -5638,12 +5638,6 @@ packages:'@hexagon/[email protected]':resolution: {integrity: sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==}- '@hono/[email protected]':- resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==}- engines: {node: '>=20'}- peerDependencies:- hono: 4.13.7-'@hookform/[email protected]':resolution: {integrity: sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==}peerDependencies:@@ -6184,26 +6178,16 @@ packages:'@mjackson/[email protected]':resolution: {integrity: sha512-EMlH1e30yzmTpGLQjlFmaDAjyOeZhng1/XCd7DExR8PNAnG/G1tyruZxEoUe11ClnwGhGrtsdnyyUx1frSzjng==}- '@modelcontextprotocol/[email protected]':- resolution: {integrity: sha512-LxCou/CSYQ6dwEnjhLZY0KnEuc8V4UJ3IEQCl/uR2yHobSQIEdJKUlKLRYRF5i5FqRGHy1eK7une3aAWDHLtig==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==}engines: {node: '>=20'}- '@modelcontextprotocol/[email protected]':- resolution: {integrity: sha512-iLhmprRmWI8EcosOA3wVvww22z02NkgqhV4fBH6f/odQBsi7xnJc0HGmi21yWO+/iKw2yzqVE127Zhna5/+JXw==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==}engines: {node: '>=20'}- '@modelcontextprotocol/[email protected]':- resolution: {integrity: sha512-UvTMgnNlnIBO/22ob2RcVGDlcvOslQs8T59+FTGdA0L27a39fdGF/EDETNtDVK4DZGpwomlsYpRdA8UXcVL/pw==}- engines: {node: '>=18'}- peerDependencies:- '@cfworker/json-schema': ^4.1.1- zod: ^3.25 || ^4.0- peerDependenciesMeta:- '@cfworker/json-schema':- optional: true-- '@modelcontextprotocol/[email protected]':- resolution: {integrity: sha512-qFnltjus6Gk8Lx6J1w2RXmr3YPN22MNT6qD6zjAkaiWIlFIFxWClz0rXHNuJF/KSUyn5YGhkSvXkWDbQHVLFEQ==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw==}engines: {node: '>=20'}'@monaco-editor/[email protected]':@@ -12815,12 +12799,6 @@ packages:resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}engines: {node: '>=12.0.0'}- resolution: {integrity: sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==}- engines: {node: '>= 16'}- peerDependencies:- express: '>= 4.11'-resolution: {integrity: sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==}engines: {node: '>= 0.10.0'}@@ -13625,10 +13603,6 @@ packages:resolution: {integrity: sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==}engines: {node: '>=12.22.0'}- resolution: {integrity: sha512-4OUAqU9Z1i3vCnS05hzGiFnEMDpQ+62pAD/MVQOp83fYyNC8GleCqaS0QikQBmcWCrKFiUs/B8ztRRiYOAXuCA==}- engines: {node: '>= 12'}-resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}engines: {node: '>= 0.10'}@@ -18624,8 +18598,8 @@ snapshots:dependencies:- '@modelcontextprotocol/client': 2.2.0- '@modelcontextprotocol/server': 2.2.0+ '@modelcontextprotocol/client': 2.3.1+ '@modelcontextprotocol/server': 2.3.1h3: 2.0.1-rc.32([email protected]([email protected]))pathe: 2.0.3@@ -19238,10 +19212,6 @@ snapshots:'@hexagon/[email protected]': {}- '@hono/[email protected]([email protected])':- dependencies:- hono: 4.13.7-dependencies:react-hook-form: 7.75.0([email protected])@@ -19812,9 +19782,9 @@ snapshots:'@mjackson/[email protected]': {}- '@modelcontextprotocol/[email protected]':+ '@modelcontextprotocol/[email protected]':dependencies:- '@modelcontextprotocol/core': 2.2.0+ '@modelcontextprotocol/core': 2.3.1cross-spawn: 7.0.6eventsource: 3.0.7eventsource-parser: 3.1.1@@ -19822,35 +19792,13 @@ snapshots:pkce-challenge: 5.0.1zod: 4.6.5- '@modelcontextprotocol/[email protected]':+ '@modelcontextprotocol/[email protected]':dependencies:zod: 4.6.5- '@modelcontextprotocol/[email protected]([email protected])':- dependencies:- '@hono/node-server': 2.1.5([email protected])- ajv: 8.18.0- ajv-formats: 3.0.1([email protected])- content-type: 1.0.5- cors: 2.8.6- cross-spawn: 7.0.6- eventsource: 3.0.7- eventsource-parser: 3.1.1- express: 5.2.1- express-rate-limit: 8.3.2([email protected])- hono: 4.13.7- jose: 6.2.2- json-schema-typed: 8.0.2- pkce-challenge: 5.0.1- raw-body: 3.0.2- zod: 4.5.4- zod-to-json-schema: 3.25.2([email protected])- transitivePeerDependencies:- - supports-color-- '@modelcontextprotocol/[email protected]':+ '@modelcontextprotocol/[email protected]':dependencies:- '@modelcontextprotocol/core': 2.2.0+ '@modelcontextprotocol/core': 2.3.1zod: 4.6.5'@monaco-editor/[email protected]':@@ -27842,11 +27790,6 @@ snapshots:- dependencies:- express: 5.2.1- ip-address: 10.7.1-dependencies:accepts: 1.3.8@@ -28189,7 +28132,7 @@ snapshots:optional: true- [email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]):+ [email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]):dependencies:'@fumari/image-size': 0.1.1estree-util-value-to-estree: 3.5.0@@ -28212,7 +28155,7 @@ snapshots:zbsearch: 4.0.0optionalDependencies:'@mdx-js/mdx': 3.1.1- '@modelcontextprotocol/server': 2.2.0+ '@modelcontextprotocol/server': 2.3.1'@types/estree-jsx': 1.0.5'@types/hast': 3.0.5'@types/mdast': 4.0.4@@ -28226,14 +28169,14 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@mdx-js/mdx': 3.1.1'@standard-schema/spec': 1.1.0chokidar: 5.0.0esbuild: 0.28.2estree-util-value-to-estree: 3.5.0- fumadocs-core: 16.15.14(@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])+ fumadocs-core: 16.15.14(@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])github-slugger: 2.0.0magic-string: 1.4.2mdast-util-mdx: 3.0.0@@ -28259,7 +28202,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected]):+ [email protected](@types/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected](@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected]):dependencies:'@fuma-translate/react': 1.0.2(@types/[email protected])([email protected]([email protected]))([email protected])'@fumadocs/tailwind': 0.1.2([email protected])@@ -28275,7 +28218,7 @@ snapshots:'@radix-ui/react-tabs': 1.1.21(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])class-variance-authority: 0.7.1cn: 0.3.3- fumadocs-core: 16.15.14(@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])+ fumadocs-core: 16.15.14(@mdx-js/[email protected])(@modelcontextprotocol/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])lucide-react: 1.48.0([email protected])@@ -28602,7 +28545,8 @@ snapshots:- [email protected]: {}+ optional: true@@ -28890,8 +28834,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]: {}-