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.

fix(mcp): tenant-aware logging via log context, less log noise

Sidwebworksae6f43295441
diff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.ts
index e427023953..3ac6be8c3e 100644
--- a/apps/erp/app/routes/api+/mcp+/_index.ts
+++ b/apps/erp/app/routes/api+/mcp+/_index.ts
@@ -5,6 +5,7 @@ import {
} from "@carbon/auth/client.server";
import { getAppUrl } from "@carbon/env";
import { Ratelimit, redis } from "@carbon/kv";
+import { withLogContext } from "@carbon/logger/middleware.server";
import { datetime } from "@carbon/utils";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import type { ActionFunctionArgs } from "react-router";
@@ -158,21 +159,28 @@ async function resolveAuth(request: Request): Promise<{
export async function action({ request }: ActionFunctionArgs) {
const { ctx, request: authedRequest } = await resolveAuth(request);
- // 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.
- const server = createMcpServer(
- ctx,
- datetime
- .today(await getCompanyTimeZone(ctx.client, ctx.companyId))
- .toString()
+ // Stamp the authenticated identity into the logging context so every log
+ // line in this request carries it alongside the middleware's requestId.
+ const response = await withLogContext(
+ { companyId: ctx.companyId, userId: ctx.userId, authKind: ctx.authKind },
+ 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.
+ const server = createMcpServer(
+ ctx,
+ datetime
+ .today(await getCompanyTimeZone(ctx.client, ctx.companyId))
+ .toString()
+ );
+ const transport = new WebStandardStreamableHTTPServerTransport({
+ sessionIdGenerator: undefined,
+ enableJsonResponse: true
+ });
+
+ await server.connect(transport);
+ return transport.handleRequest(authedRequest);
+ }
);
- const transport = new WebStandardStreamableHTTPServerTransport({
- sessionIdGenerator: undefined,
- enableJsonResponse: true
- });
-
- await server.connect(transport);
- const response = await transport.handleRequest(authedRequest);
return addCorsHeaders(response);
}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/server.ts b/apps/erp/app/routes/api+/mcp+/lib/server.ts
index e4713e6171..1e9a8ce25a 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/server.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/server.ts
@@ -90,15 +90,14 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
// Find the tool in metadata
const tool = toolMetadata.tools.find(t => t.name === name);
if (!tool) {
- logger.error("Tool not found", { name });
+ // A caller typo, not a server fault — warn, not error.
+ logger.warn("Tool not found", { name });
return {
content: [{ type: "text" as const, text: `Tool '${name}' not found` }],
isError: true
};
}
- logger.info("Found tool", { name: tool.name, module: tool.module });
-
// Tool schemas are provided via metadata, no need to load modules
let output = `Tool: ${name}\n`;
@@ -191,22 +190,29 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
// Runs through the canonical oRPC dispatch (gate middleware included); the
// Supabase envelope arrives already unwrapped to `data`/`count`.
+ const start = performance.now();
const result = await callOperation(name, ctx, args);
-
- logger.info("Execution result", {
- success: result.success,
- hasData: result.success && result.data !== undefined,
- error: result.success ? undefined : result.error
- });
+ const responseTime = performance.now() - start;
if (result.success) {
+ logger.info("Execution result", {
+ name,
+ success: true,
+ hasData: result.data !== undefined,
+ responseTime
+ });
const output =
result.data === undefined
? "Operation completed successfully"
: formatMcpResult(result.data, result.count);
return { content: [{ type: "text" as const, text: output }] };
}
- logger.error("Tool execution failed", { error: result.error });
+ logger.error("Tool execution failed", {
+ name,
+ error: result.error,
+ errorKind: result.errorKind,
+ responseTime
+ });
return {
content: [{
type: "text" as const,
@@ -233,12 +239,9 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
},
withErrorHandling(async (params: any) => {
const { query, module, classification, limit = 20, offset = 0 } = params;
-
- logger.info("search_tools invoked", { query, module, classification, limit, offset });
let results = toolMetadata.tools;
- logger.info("Total tools available", { count: results.length });
-
+
// Apply filters
if (module) {
results = results.filter(t => t.module.toLowerCase().includes(module.toLowerCase()));
@@ -257,10 +260,17 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
const foundTools = results.slice(offset, offset + limit);
const toolNames = foundTools.map(t => t.name);
-
- logger.info("Found tools after filtering", { count: results.length });
- logger.info("Returning tools", { toolNames });
-
+
+ logger.info("search_tools invoked", {
+ query,
+ module,
+ classification,
+ limit,
+ offset,
+ matched: results.length,
+ returned: toolNames.length
+ });
+
// Build response
let output = `Found ${results.length} tools`;
if (results.length > limit) {
diff --git a/apps/erp/app/routes/api+/mcp+/lib/types.ts b/apps/erp/app/routes/api+/mcp+/lib/types.ts
index 9a06e4b483..914ad558fc 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/types.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/types.ts
@@ -37,10 +37,9 @@ export function withErrorHandling<T extends Record<string, unknown>>(
) {
return async (params: T) => {
try {
- logger.info("Executing handler", { fallbackMessage });
- const result = await handler(params);
- logger.info("Handler completed successfully");
- return result;
+ // No info logging here — each handler logs its own invocation/result;
+ // this wrapper only reports the throw path.
+ return await handler(params);
} catch (error) {
logger.error("Error in handler", {
fallbackMessage,
diff --git a/packages/logger/src/middleware.server.ts b/packages/logger/src/middleware.server.ts
index d8f3a468dc..2d41f78cc6 100644
--- a/packages/logger/src/middleware.server.ts
+++ b/packages/logger/src/middleware.server.ts
@@ -24,6 +24,16 @@ export {
import { getLogger } from "./logger";
+/**
+ * Run `fn` inside a LogTape implicit-context scope so every log line emitted
+ * within it carries `properties` — the same mechanism `requestIdMiddleware`
+ * uses for `requestId`. Scopes nest and merge, so calling this inside a
+ * request adds to the request's context rather than replacing it. Use it to
+ * stamp identity that a whole request shares (e.g. `companyId`/`userId` once
+ * auth resolves) instead of repeating the fields at every log call site.
+ */
+export { withContext as withLogContext } from "@logtape/logtape";
+
export const REQUEST_ID_HEADER = "x-request-id";
/** Only these carry a body worth logging; GET/HEAD/OPTIONS don't. */