Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(mcp): serve an MCP manifest at /.well-known/mcp.json, correct the rate-limit docs (#1459)

Brad Barbina4b9f40efb28
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/api-keys.md b/apps/erp/app/modules/agent/kb/docs/reference/api-keys.md
index ca333abbf3..e62fcac3f1 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/api-keys.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/api-keys.md
@@ -1,8 +1,8 @@
# API keys
-> A scoped secret that lets an external system call the Carbon API on your behalf, with its own permissions and rate limit.
+> A scoped secret that lets an external system call the Carbon API on your behalf, with its own permissions.
-An API key is a secret string that authenticates programmatic calls to Carbon. Where a person signs in and Carbon reads their permissions from a session, a script sends its key on every request and Carbon reads the key's own permissions instead. A key belongs to one company, carries an explicit set of scopes, and has its own rate limit, so you can hand a partner or a job exactly the access it needs and nothing more.
+An API key is a secret string that authenticates programmatic calls to Carbon. Where a person signs in and Carbon reads their permissions from a session, a script sends its key on every request and Carbon reads the key's own permissions instead. A key belongs to one company and carries an explicit set of scopes, so you can hand a partner or a job exactly the access it needs and nothing more.
Create and manage keys under **Settings → API Keys**. Every key you see is listed by **Name**, a masked **Key** preview (only the last five characters, e.g. `crbn_•••abcde`), its **Scopes**, **Rate Limit**, who created it, and when it expires.
@@ -46,9 +46,13 @@ Because scopes are checked on every request against the key's own record, tighte
## Rate limiting
-Each key has its own limit. By default a key allows **1000 requests per hour**; both the count and the window (`1m`, `1h`, or `1d`) are stored on the key. Carbon counts each authenticated request against the current window and rejects anything over the limit with "Rate limit exceeded" until the window rolls over.
+Every key allows **60 requests per minute**. Carbon counts each authenticated request against the current window and rejects anything over the limit with "Rate limit exceeded" until the window rolls over.
-The limit is per key, not per company, so you can give a high-traffic integration a larger allowance and keep a throwaway key tight. Build your client to back off when it's throttled rather than hammering through the rejection.
+The limit is platform-controlled, not something you set: the key's form has no rate-limit field, and `insertApiKey`/`updateApiKey` strip the columns from whatever is submitted (`apps/erp/app/modules/settings/settings.service.ts:1282`). The **Rate Limit** column in the key list reports the limit in force; it is not an input.
+
+The limit is counted per key, not per company, so one integration burning its allowance does not throttle another.
+
+A rejected request comes back `429` with `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and `Retry-After` (`packages/auth/src/services/auth.server.ts:255`). Read `Retry-After` and wait it out rather than hammering through the rejection.
## The REST and OpenAPI surface
@@ -80,7 +84,7 @@ The exact rejections an API key can return, and the one-time-secret gotcha.
The call needs a `module_action` scope the key doesn't carry. Scopes are checked per request against the key's own record (`packages/database/supabase/functions/lib/supabase.ts:315`), not the creator's permissions — a key with no scopes can authenticate but read and write nothing. Add the exact `module_action` (e.g. `purchasing_update`) to the key in the permission matrix under **Settings → API Keys**. It takes effect immediately, no session to wait out.
### "Rate limit exceeded"
-The key exceeded its allowance for the current window (`supabase.ts:304`). A key defaults to 1000 requests per hour; both the count and the window (`1m`/`1h`/`1d`) are stored on the key. Wait for the window to roll over, or raise the limit on the key. Build your client to back off when throttled rather than retrying immediately.
+The key exceeded its allowance for the current window (`supabase.ts:304`). Every key allows 60 requests per minute, and the limit is platform-controlled — there is no field to raise it, and the API-key service strips the columns from any submitted value. The `429` carries `Retry-After` and `X-RateLimit-*` headers; wait out `Retry-After` rather than retrying immediately. If 60/minute is genuinely too tight for your integration, batch your reads (PostgREST `in.(...)` filters and embedded relations fetch in one call) or talk to us.
### "API key has expired"
The key's `expiresAt` is in the past, so it's rejected before any work (`supabase.ts:293`). Create a new key (optionally with a later **Expires At**, or leave it blank to never expire) and swap it in — expiry can't be extended on a used key.
diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.json
index 016ea59c34..357521a8c4 100644
--- a/apps/erp/app/modules/agent/kb/manifest.json
+++ b/apps/erp/app/modules/agent/kb/manifest.json
@@ -293,7 +293,7 @@
{
"slug": "docs/reference/api-keys",
"title": "API keys",
- "description": "A scoped secret that lets an external system call the Carbon API on your behalf, with its own permissions and rate limit.",
+ "description": "A scoped secret that lets an external system call the Carbon API on your behalf, with its own permissions.",
"keywords": ["api", "keys", "docs", "reference"],
"headings": [
"Creating a key",
diff --git a/apps/erp/app/routes/[.]well-known.mcp[.]json.ts b/apps/erp/app/routes/[.]well-known.mcp[.]json.ts
new file mode 100644
index 0000000000..d9d31ac01c
--- /dev/null
+++ b/apps/erp/app/routes/[.]well-known.mcp[.]json.ts
@@ -0,0 +1,26 @@
+import { getAppUrl } from "@carbon/env";
+import type { LoaderFunctionArgs } from "react-router";
+import { buildMcpManifest } from "./api+/mcp+/lib/manifest";
+
+/**
+ * The MCP server manifest, at the well-known path a client or registry probes.
+ *
+ * Public and unauthenticated by design: it carries no company data, only how to
+ * reach `/api/mcp` and how to authenticate against it. CORS is open because
+ * browser-based agents fetch it cross-origin, and a CORS error there reads to
+ * the agent as "no manifest exists".
+ */
+export async function loader({ request }: LoaderFunctionArgs) {
+ const url = new URL(request.url);
+ const origin = getAppUrl() || url.origin;
+
+ return new Response(JSON.stringify(buildMcpManifest(origin), null, 2), {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
+ "Cache-Control": "public, max-age=3600"
+ }
+ });
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/manifest.test.ts b/apps/erp/app/routes/api+/mcp+/lib/manifest.test.ts
new file mode 100644
index 0000000000..b1a5292dc2
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/manifest.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from "vitest";
+import { buildMcpManifest, MCP_META_KEY, MCP_SERVER_NAME } from "./manifest";
+import toolMetadataJson from "./tool-metadata.json";
+
+const toolMetadata = toolMetadataJson as unknown as {
+ totalTools: number;
+ tools: { module: string; classification: string }[];
+};
+
+const ORIGIN = "https://app.carbon.ms";
+const manifest = buildMcpManifest(ORIGIN);
+const meta = manifest._meta[MCP_META_KEY];
+
+describe("buildMcpManifest", () => {
+ it("declares the registry schema and a reverse-DNS name", () => {
+ expect(manifest.$schema).toMatch(/server\.schema\.json$/);
+ expect(manifest.name).toBe(MCP_SERVER_NAME);
+ expect(manifest.name).toMatch(/^[a-z0-9.-]+\/[a-z0-9-]+$/);
+ });
+
+ it("advertises Streamable HTTP at this deployment's own endpoint", () => {
+ expect(manifest.remotes[0].type).toBe("streamable-http");
+ expect(manifest.remotes[0].url).toBe(`${ORIGIN}/api/mcp`);
+ expect(meta.transport).toBe("streamable-http");
+ expect(meta.endpoint).toBe(`${ORIGIN}/api/mcp`);
+ });
+
+ it("follows the origin, so a self-hosted instance points at itself", () => {
+ // A manifest that hard-codes app.carbon.ms sends every self-hosted client
+ // to the wrong tenant's server.
+ const selfHosted = buildMcpManifest("https://erp.example.com");
+ const selfHostedMeta = selfHosted._meta[MCP_META_KEY];
+
+ expect(selfHosted.remotes[0].url).toBe("https://erp.example.com/api/mcp");
+ expect(selfHostedMeta.authentication.protectedResourceMetadata).toBe(
+ "https://erp.example.com/.well-known/oauth-protected-resource"
+ );
+ expect(selfHostedMeta.clientConfig.mcpServers.carbon.url).toBe(
+ "https://erp.example.com/api/mcp"
+ );
+ });
+
+ it("points at the OAuth metadata this app actually serves", () => {
+ // Both paths have routes in apps/erp/app/routes/.
+ expect(meta.authentication.protectedResourceMetadata).toBe(
+ `${ORIGIN}/.well-known/oauth-protected-resource`
+ );
+ expect(meta.authentication.authorizationServerMetadata).toBe(
+ `${ORIGIN}/.well-known/oauth-authorization-server`
+ );
+ expect(meta.authentication.schemes).toContain("bearer");
+ });
+
+ it("marks the credential required and secret", () => {
+ const header = manifest.remotes[0].headers[0];
+ expect(header.name).toBe("Authorization");
+ expect(header.isRequired).toBe(true);
+ expect(header.isSecret).toBe(true);
+ });
+
+ it("describes exactly the tools the server registers", () => {
+ expect(meta.tools.map((tool) => tool.name)).toEqual([
+ "search_tools",
+ "describe_tool",
+ "call_tool"
+ ]);
+ for (const tool of meta.tools) {
+ expect(tool.description.length, tool.name).toBeGreaterThan(40);
+ }
+ });
+
+ it("derives its counts from tool-metadata rather than restating them", () => {
+ // This is the anti-drift property: remove a module and the manifest stops
+ // advertising it without anyone remembering to edit this file.
+ const modules = [
+ ...new Set(toolMetadata.tools.map((t) => t.module))
+ ].sort();
+ const classifications = [
+ ...new Set(toolMetadata.tools.map((t) => t.classification))
+ ].sort();
+
+ expect(meta.operations.total).toBe(toolMetadata.totalTools);
+ expect(meta.operations.modules).toEqual(modules);
+ expect(meta.operations.classifications).toEqual(classifications);
+ expect(modules.length).toBeGreaterThan(0);
+ });
+
+ it("leaves the client-config credential as an unexpanded placeholder", () => {
+ // If someone turns this into a template literal it interpolates to
+ // "Bearer " and the published config hands out an empty credential.
+ // The `\{` escape keeps this an independent literal — no interpolation
+ // here, and no lint suppression needed to assert on a `${...}` placeholder.
+ expect(meta.clientConfig.mcpServers.carbon.headers.Authorization).toBe(
+ `Bearer $\{CARBON_API_KEY}`
+ );
+ });
+
+ it("keeps every Carbon-specific field inside _meta", () => {
+ // Unknown top-level keys risk failing a strict registry validator.
+ expect(Object.keys(manifest).sort()).toEqual([
+ "$schema",
+ "_meta",
+ "description",
+ "name",
+ "remotes",
+ "repository",
+ "version",
+ "websiteUrl"
+ ]);
+ });
+
+ it("serializes to JSON without loss", () => {
+ expect(JSON.parse(JSON.stringify(manifest))).toEqual(manifest);
+ });
+});
+
+describe("/.well-known/mcp.json", () => {
+ it("serves the manifest as public, CORS-open JSON", async () => {
+ const { loader } = await import("../../../[.]well-known.mcp[.]json");
+
+ const response = await loader({
+ request: new Request("https://app.carbon.ms/.well-known/mcp.json")
+ } as Parameters<typeof loader>[0]);
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Content-Type")).toBe("application/json");
+ expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*");
+ expect(response.headers.get("Cache-Control")).toBe("public, max-age=3600");
+
+ const body = await response.json();
+ expect(body.name).toBe(MCP_SERVER_NAME);
+ expect(body.remotes[0].type).toBe("streamable-http");
+ expect(body.remotes[0].url).toMatch(/\/api\/mcp$/);
+ });
+});
diff --git a/apps/erp/app/routes/api+/mcp+/lib/manifest.ts b/apps/erp/app/routes/api+/mcp+/lib/manifest.ts
new file mode 100644
index 0000000000..bbc88d9642
--- /dev/null
+++ b/apps/erp/app/routes/api+/mcp+/lib/manifest.ts
@@ -0,0 +1,167 @@
+/**
+ * The MCP server's own manifest, served at `/.well-known/mcp.json`.
+ *
+ * Shaped as the Model Context Protocol registry's `server.json`: `remotes[]`
+ * with `type: "streamable-http"` is the field a client or a registry reads to
+ * learn how to connect. Everything Carbon-specific lives under `_meta`, so the
+ * document stays valid against that schema rather than growing ad-hoc top-level
+ * keys a strict validator would reject.
+ *
+ * The tool counts and module list are derived from `tool-metadata.json` — the
+ * same file the server registers from — so the manifest cannot drift from what
+ * `search_tools` actually returns. Hard-coding them here is how a manifest ends
+ * up promising a module that was removed two releases ago.
+ */
+
+import toolMetadataJson from "./tool-metadata.json";
+
+type ToolSummary = {
+ name: string;
+ module: string;
+ classification: string;
+};
+
+const toolMetadata = toolMetadataJson as unknown as {
+ totalTools: number;
+ modules: number;
+ tools: ToolSummary[];
+};
+
+const SERVER_JSON_SCHEMA =
+ "https://static.modelcontextprotocol.io/schemas/2025-09-29/server.schema.json";
+
+/**
+ * The credential line in the paste-ready client config. Assembled rather than
+ * written inline so `${CARBON_API_KEY}` stays what it is — a placeholder the MCP
+ * client expands from its own environment — instead of reading as a template
+ * literal someone will later "fix" into an empty string.
+ */
+const PLACEHOLDER_BEARER = ["Bearer $", "{CARBON_API_KEY}"].join("");
+
+/** Reverse-DNS server name, as the MCP registry requires. */
+export const MCP_SERVER_NAME = "ms.carbon/carbon-erp";
+
+/** `_meta` namespace key — reverse-DNS, per the MCP `_meta` convention. */
+export const MCP_META_KEY = "ms.carbon/v1";
+
+export const MARKETING_URL = "https://carbon.ms";
+export const REPOSITORY_URL = "https://github.com/crbnos/carbon";
+export const DOCS_URL = "https://docs.carbon.ms";
+
+/**
+ * The three tools the server registers. Carbon publishes meta-tools rather than
+ * ~1,400 flat ones: a client that loaded every ERP operation as a tool would
+ * spend its whole context on definitions before doing any work.
+ */
+const TOOLS = [
+ {
+ name: "search_tools",
+ description:
+ "Search Carbon's ERP operations by name, module or classification (READ, WRITE, DESTRUCTIVE), and make the matches available to call.",
+ readOnly: true
+ },
+ {
+ name: "describe_tool",
+ description:
+ "Return the full input schema and description for one operation, so its arguments can be built correctly before calling it.",
+ readOnly: true
+ },
+ {
+ 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.",
+ readOnly: false
+ }
+] as const;
+
+const MODULES = [
+ ...new Set(toolMetadata.tools.map((tool) => tool.module))
+].sort();
+
+const CLASSIFICATIONS = [
+ ...new Set(toolMetadata.tools.map((tool) => tool.classification))
+].sort();
+
+/**
+ * Build the manifest for a given origin.
+ *
+ * The origin is passed in rather than read from env so a self-hosted or ITAR
+ * instance advertises its OWN endpoint. A manifest that points every deployment
+ * at app.carbon.ms is worse than no manifest — the client connects to the wrong
+ * tenant's server and fails auth with no clue why.
+ */
+export function buildMcpManifest(origin: string) {
+ const endpoint = `${origin}/api/mcp`;
+
+ return {
+ $schema: SERVER_JSON_SCHEMA,
+ name: MCP_SERVER_NAME,
+ description:
+ "Carbon is an API-first operating system for manufacturing (ERP, MRP, MES, QMS). This MCP server exposes its ERP operations — items, sales, purchasing, production, inventory, quality and accounting — as tools an agent can search, inspect and call.",
+ version: "1.0.0",
+ websiteUrl: MARKETING_URL,
+ repository: {
+ url: REPOSITORY_URL,
+ source: "github"
+ },
+ remotes: [
+ {
+ type: "streamable-http",
+ url: endpoint,
+ headers: [
+ {
+ name: "Authorization",
+ description:
+ "Bearer <api-key>. Create a scoped key in Settings → API Keys. OAuth is also supported; an unauthenticated request returns 401 with a WWW-Authenticate header pointing at the protected-resource metadata.",
+ isRequired: true,
+ isSecret: true
+ }
+ ]
+ }
+ ],
+ _meta: {
+ [MCP_META_KEY]: {
+ transport: "streamable-http",
+ endpoint,
+ serverName: "carbon-erp",
+ authentication: {
+ schemes: ["bearer", "oauth2"],
+ /** RFC 9728 metadata, served by this same app. */
+ protectedResourceMetadata: `${origin}/.well-known/oauth-protected-resource`,
+ authorizationServerMetadata: `${origin}/.well-known/oauth-authorization-server`,
+ scopeModel:
+ "A key is scoped to one company and to explicit module permissions; row-level security in the database enforces the same boundary as the app."
+ },
+ tools: TOOLS,
+ operations: {
+ description:
+ "search_tools, describe_tool and call_tool reach every ERP operation Carbon exposes, each classified READ, WRITE or DESTRUCTIVE.",
+ total: toolMetadata.totalTools,
+ modules: MODULES,
+ classifications: CLASSIFICATIONS
+ },
+ documentation: {
+ mcpGuide: `${DOCS_URL}/mcp`,
+ apiReference: `${DOCS_URL}/api-reference`,
+ authentication: `${DOCS_URL}/api-reference/authentication`,
+ openapi: `${MARKETING_URL}/openapi.json`
+ },
+ /** Drop-in config for Claude Desktop, Claude Code and compatible clients. */
+ clientConfig: {
+ mcpServers: {
+ carbon: {
+ type: "http",
+ url: endpoint,
+ headers: {
+ // The `${...}` is a literal placeholder the MCP CLIENT expands
+ // from its own environment — not a template literal. Making it
+ // one would interpolate here and publish an empty credential.
+ Authorization: PLACEHOLDER_BEARER
+ }
+ }
+ }
+ }
+ }
+ }
+ };
+}
diff --git a/docs/app/api-reference/authentication/page.tsx b/docs/app/api-reference/authentication/page.tsx
index 869c1866bb..f476b45d8b 100644
--- a/docs/app/api-reference/authentication/page.tsx
+++ b/docs/app/api-reference/authentication/page.tsx
@@ -184,7 +184,7 @@ export default async function AuthenticationPage() {
cols="72px 1fr"
cells={[
<Code key="c">429</Code>,
- "Rate limit exceeded — back off and retry per the X-RateLimit-* response headers."
+ "Rate limit exceeded — every key allows 60 requests per minute. Back off and retry per the X-RateLimit-* and Retry-After response headers."
]}
/>
</Table>
diff --git a/docs/content/docs/reference/api-keys.mdx b/docs/content/docs/reference/api-keys.mdx
index d1396e79ec..19bc9ef99c 100644
--- a/docs/content/docs/reference/api-keys.mdx
+++ b/docs/content/docs/reference/api-keys.mdx
@@ -1,9 +1,9 @@
---
title: API keys
-description: A scoped secret that lets an external system call the Carbon API on your behalf, with its own permissions and rate limit.
+description: A scoped secret that lets an external system call the Carbon API on your behalf, with its own permissions.
---
-An <Term id="api-key">API key</Term> is a secret string that authenticates programmatic calls to Carbon. Where a person signs in and Carbon reads their permissions from a session, a script sends its key on every request and Carbon reads the key's own permissions instead. A key belongs to one company, carries an explicit set of scopes, and has its own rate limit, so you can hand a partner or a job exactly the access it needs and nothing more.
+An <Term id="api-key">API key</Term> is a secret string that authenticates programmatic calls to Carbon. Where a person signs in and Carbon reads their permissions from a session, a script sends its key on every request and Carbon reads the key's own permissions instead. A key belongs to one company and carries an explicit set of scopes, so you can hand a partner or a job exactly the access it needs and nothing more.
Create and manage keys under **Settings → API Keys**. Every key you see is listed by **Name**, a masked **Key** preview (only the last five characters, e.g. `crbn_•••abcde`), its **Scopes**, **Rate Limit**, who created it, and when it expires.
@@ -51,9 +51,13 @@ Because scopes are checked on every request against the key's own record, tighte
## Rate limiting
-Each key has its own limit. By default a key allows **1000 requests per hour**; both the count and the window (`1m`, `1h`, or `1d`) are stored on the key. Carbon counts each authenticated request against the current window and rejects anything over the limit with "Rate limit exceeded" until the window rolls over.
+Every key allows **60 requests per minute**. Carbon counts each authenticated request against the current window and rejects anything over the limit with "Rate limit exceeded" until the window rolls over.
-The limit is per key, not per company, so you can give a high-traffic integration a larger allowance and keep a throwaway key tight. Build your client to back off when it's throttled rather than hammering through the rejection.
+The limit is platform-controlled, not something you set: the key's form has no rate-limit field, and `insertApiKey`/`updateApiKey` strip the columns from whatever is submitted (`apps/erp/app/modules/settings/settings.service.ts:1282`). The **Rate Limit** column in the key list reports the limit in force; it is not an input.
+
+The limit is counted per key, not per company, so one integration burning its allowance does not throttle another.
+
+A rejected request comes back `429` with `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and `Retry-After` (`packages/auth/src/services/auth.server.ts:255`). Read `Retry-After` and wait it out rather than hammering through the rejection.
## The REST and OpenAPI surface
@@ -92,7 +96,7 @@ The exact rejections an API key can return, and the one-time-secret gotcha.
The call needs a `module_action` scope the key doesn't carry. Scopes are checked per request against the key's own record (`packages/database/supabase/functions/lib/supabase.ts:315`), not the creator's permissions — a key with no scopes can authenticate but read and write nothing. Add the exact `module_action` (e.g. `purchasing_update`) to the key in the permission matrix under **Settings → API Keys**. It takes effect immediately, no session to wait out.
### "Rate limit exceeded"
-The key exceeded its allowance for the current window (`supabase.ts:304`). A key defaults to 1000 requests per hour; both the count and the window (`1m`/`1h`/`1d`) are stored on the key. Wait for the window to roll over, or raise the limit on the key. Build your client to back off when throttled rather than retrying immediately.
+The key exceeded its allowance for the current window (`supabase.ts:304`). Every key allows 60 requests per minute, and the limit is platform-controlled — there is no field to raise it, and the API-key service strips the columns from any submitted value. The `429` carries `Retry-After` and `X-RateLimit-*` headers; wait out `Retry-After` rather than retrying immediately. If 60/minute is genuinely too tight for your integration, batch your reads (PostgREST `in.(...)` filters and embedded relations fetch in one call) or talk to us.
### "API key has expired"
The key's `expiresAt` is in the past, so it's rejected before any work (`supabase.ts:293`). Create a new key (optionally with a later **Expires At**, or leave it blank to never expire) and swap it in — expiry can't be extended on a used key.