Open MercatoDocsSearch docsAPI reference

Framework

MCP Server (Claude Code & external clients)

Connect an MCP client to the same installation and identity that own your business data. Inspect its tool list before the first call. The tools visible to an administrator can differ from those visible to the person who will actually use the integration.

Open Mercato ships an MCP (Model Context Protocol) server that exposes your tenant's tools to an external AI client – Claude Code, the MCP Inspector, or any MCP-compatible client – over HTTP. Point the client at a running Open Mercato server and it can discover and call your tools, scoped to an API key's permissions.

Note · Two complementary AI surfaces

This is the client-facing MCP entry point. It is distinct from the in-app AI Framework (typed agents, mutation approvals, <AiChat>) documented in AI Framework Overview. The MCP server serves tools; agents are a separate in-app surface (see the "Tools vs agents" note below).

Setup & connecting Claude Code

The MCP server exposes Open Mercato's tools to an external AI client – Claude Code, MCP Inspector, or any MCP-compatible client – over HTTP using the MCP StreamableHTTP transport. Point Claude Code at a running Open Mercato dev server and it can call your tenant's tools directly.

Two server modes

The server runs in one of two modes depending on how you intend to use it:

Dev (yarn mcp:dev)Production (yarn mcp:serve)
Alias formercato ai_assistant mcp:devmercato ai_assistant mcp:serve-http
Use forClaude Code / local testingIn-app web chat
Port3001 (override with MCP_DEV_PORT) –
Bind address127.0.0.1 (loopback) – override with MCP_DEV_HOST127.0.0.1 (loopback) – override with MCP_HTTP_HOST env var or --host flag
Endpointhttp://localhost:3001/mcp –
Healthhttp://localhost:3001/health –
AuthA single API key, read once at startupTwo-tier: server key + per-user session tokens, checked per tool call
Key source.mcp.json → mcpServers.open-mercato.headers.x-api-key (no env fallback)MCP_SERVER_API_KEY env var + session tokens

Caution · Loopback by default – think before widening it

Both servers bind to 127.0.0.1 unless you explicitly override the host. The one exception is yarn dev on native Linux, which binds 0.0.0.0 so the OpenCode container can reach the host over the bridge IP (Docker Desktop keeps loopback); MCP_HTTP_HOST overrides either way. The dev server especially: it authenticates a single API key once at startup and reuses that same superadmin-equivalent context for every request afterward, with no per-request ACL re-check. Exposing either server beyond loopback (a LAN, a misconfigured firewall, a cloud security group) turns a leaked or brute-forced key into admin-equivalent access to tenant data. Only widen the bind address for a deployment topology that genuinely needs it (e.g. a Docker bridge address), and pair it with a firewall and a strong, rotated MCP_SERVER_API_KEY.

Note

You do not need MCP_SERVER_API_KEY for mcp:dev. The MCP_SERVER_API_KEY not set message on the in-app AI Assistant Settings page is only a status badge for the production/web-chat path – it does not block Claude Code connecting via mcp:dev.

Note · Managed MCP during yarn dev

The root and standalone yarn dev launchers manage mcp:serve-http separately from the direct commands above. MCP_PORT is their preferred port: when another process already owns it, the launcher selects a free port and prints the resulting endpoint. That endpoint is propagated to the managed app and to a running OpenCode compose service. Explicit external MCP_URL and OPENCODE_MCP_URL values are never replaced.

Info · Route modules outside Next.js

Both servers run in plain Node, and a tool call imports the API route module behind it. Route modules say from 'next/server', a bare subpath only a bundler resolves (next ships no exports map). The mercato CLI (and with it every mercato ai_assistant command) therefore installs a small resolve hook at startup that retries next/<subpath>.js when Node cannot resolve next/<subpath>. If you embed the operation runner in your own Node process instead of these commands, call installNextSubpathResolveHook() from @open-mercato/shared/lib/bootstrap/next-subpath-resolve-hook (also re-exported from @open-mercato/ai-assistant/modules/ai_assistant/lib/next-subpath-resolve-hook) before the first tool call, or tools backed by such routes fail with Failed to load route module: Cannot find module '…/next/server'.

How ACL gates which tools appear

Every server lists only the tools the caller may call. The dev server filters by the API key's ACL at startup; the production HTTP server (mcp:serve-http) filters tools/list per request (see Filtered tools/list); the stdio server filters by its resolved auth context. The exposure config is applied first in all three. The key's roles and features decide which tools are visible:

Setup steps

  1. Create an API key. Via the CLI:

    yarn mercato api_keys add --name claude-code \
      --tenantId <tenant-uuid> \
      --organizationId <org-uuid> \
      --roles admin
    

    This prints a secret like omk_<prefix>.<secret> once – store it immediately. You can also create or edit keys in the app UI under Settings → Auth → API Keys.

  2. Write .mcp.json. Place it at your project root, where Claude Code auto-discovers it. The same file serves two purposes: it tells Claude Code how to connect, and the dev server reads its own API key from it.

    {
      "mcpServers": {
        "open-mercato": {
          "type": "http",
          "url": "http://localhost:3001/mcp",
          "headers": { "x-api-key": "omk_your_key_here" }
        }
      }
    }
    
  3. Start the dev server.

    yarn mcp:dev
    

    The server authenticates once at startup using the x-api-key from .mcp.json and filters tools by that key's ACL.

Tip

Some tools – the execute Code Mode tool and the API-backed module tools – call back into the running Next.js app over HTTP (base URL defaults to http://localhost:3000). For those to work, also run yarn dev in a separate terminal. The context_whoami and search tools do not need the app running.

  1. Connect in Claude Code. Run /mcp to approve and trust the project server. After editing .mcp.json or restarting the server, restart Claude Code or reconnect via /mcp.

  2. Verify connectivity.

    curl http://localhost:3001/health
    

    A healthy server returns:

    {"status":"ok","mode":"development","tools":N,...}
    

Warning

Zero-features pitfall: if your API key has no roles or features, the server starts fine but exposes only context_whoami – every other tool silently disappears. If Claude Code sees just one tool, your key is missing grants. Bind it to a role such as admin (or a role with the relevant <module>.* wildcard grants) and reconnect.

Stdio server authentication (mercato ai_assistant mcp:serve)

The mercato ai_assistant mcp:serve command runs the MCP server over stdio (one process per client, used by some local MCP clients). It is a distinct command from the HTTP servers above – note that the yarn mcp:serve script is aliased to mcp:serve-http, so this stdio command is reached by invoking the mercato CLI directly.

The stdio server resolves its auth context in priority order:

  1. API key – pass --api-key <secret>, or set OPEN_MERCATO_API_KEY (preferred – keeps the secret off argv, which is world-readable via ps / /proc). The key's tenant, organization, user, and ACL are loaded from the key.
  2. Manual context – pass --tenant <id> together with --user <id> (and optionally --org <id>). The named user's ACL is loaded and enforced.
  3. Explicit unauthenticated opt-in – --allow-unauthenticated-superadmin (see below).

Warning · Fail-closed by default (#3015, #2673)

If you supply none of the above – for example --tenant without --user and without an API key – the server refuses to start rather than silently escalating to an unscoped superadmin. You will see:

MCP server refused to start: no authentication provided. Supply a valid apiKeySecret,
a context with a non-empty userId, or explicitly set allowUnauthenticatedSuperadmin: true
for local development.

An empty or whitespace-only API key is treated as missing, so a blank --api-key cannot fall through into an unauthenticated branch. With --tenant, --user is therefore effectively required unless you pass the explicit opt-in below.

--allow-unauthenticated-superadmin (dev/test only)

For local development and testing you can restore the legacy "no user → superadmin" behavior with an explicit, loud opt-in:

mercato ai_assistant mcp:serve \
  --tenant 123e4567-e89b-12d3-a456-426614174000 \
  --allow-unauthenticated-superadmin

When enabled, the server runs as superadmin with no per-user ACL (scoped only to whatever --tenant / --org you pin) and logs a loud startup warning:

[MCP Server] WARNING: allowUnauthenticatedSuperadmin is enabled — running with
UNAUTHENTICATED SUPERADMIN access and no per-user ACL. Do not use this outside
local development/testing.

The same switch is available programmatically as the optional McpServerOptions.allowUnauthenticatedSuperadmin flag on runMcpServer(...) / createMcpServer(...). It defaults to off.

Danger · Never enable in production

--allow-unauthenticated-superadmin bypasses per-user RBAC entirely. Use it only for local development or automated tests. In production, always authenticate with an API key or a --tenant + --user context.

Migration impact

allowUnauthenticatedSuperadmin is an additive, optional field (default off), so the only behavior change is that a previously fail-open misconfiguration now fails closed. If you previously started the stdio mcp:serve with --tenant but no --user (and no API key) and relied on the implicit superadmin context, that invocation now refuses to start. Migrate it by either:

What's available & how to use it

After a correct setup with an admin-scoped API key, the MCP server exposes 70 tools total, organized into three groups. The key thing to internalize: MCP serves tools, and any documented API route is reachable through the Code Mode meta-tools – you do not get one MCP tool per route, and an agent only appears over MCP when it is published as one tool.

GroupToolsRequired featureWhat it does
Built-in contextcontext_whoaminoneReturns the current auth context – tenantId, organizationId, userId, isSuperAdmin, and the granted features. Use it to confirm your scope.
Code Mode meta-toolssearch, executeai_assistant.viewDiscover and call the full API surface from JavaScript (see below).
Module tool packs67 typed toolsper-tool requiredFeaturesTyped defineAiTool tools such as customers.list_people, customers.list_companies, customers.list_deals, catalog.list_products, catalog.list_offers, catalog.search_products, search.hybrid_search, search.get_record_context, attachments.list_record_attachments, attachments.read_attachment, meta.list_agents, meta.describe_agent, and more.

Each module tool declares its own requiredFeatures, so a tool appears only if the caller's ACL covers it and the exposure config lets it through. In dev the tool list is filtered by the key's features at startup; in production tools/list is filtered per request and every call is checked again. Wildcard grants (module.*, *) match concrete required features. The counts above are for an unrestricted exposure config.

Reaching any API endpoint

The boot log line Registered N API route manifests for API-backed tools refers to an internal registry that API-backed tools (like customers.list_companies) use to call documented routes in-process. Those ~500+ routes are not exposed as hundreds of individual MCP tools.

To reach any endpoint from MCP, use the two Code Mode meta-tools – search to discover, execute to call:

  1. search – the AI writes a JavaScript arrow function that queries the OpenAPI spec (paths + entity schemas) to discover endpoints and shapes:

    search({ code: 'async () => Object.keys(spec.paths).filter(p => p.includes("customer"))' })
    
  2. execute – the AI writes JS that calls api.request({ method, path, query, body }) against the live app to read or write data:

    execute({ code: 'async () => api.request({ method: "GET", path: "/api/customers/companies", query: { city: "New York" } })' })
    

execute runs in a node:vm sandbox: fetch, require, process, and fs are blocked, there is a 30-second timeout, and a maximum of 50 API calls per execution. Between search and execute, the entire documented API surface is reachable from MCP – via code, not via one-tool-per-route.

Code Mode's api.request({ method, path, query, body }) does not follow HTTP redirects, including redirects within the application. A redirect returns { success: false, statusCode: 307, error: "API redirect 307 blocked" } with the actual 3xx status. Redirect headers and bodies are omitted so credentials, request bodies, and sensitive redirect URLs cannot reach another endpoint or the model. Call the intended documented API path directly; browser flows such as SSO login must run in the browser.

Note · Tools vs agents

MCP serves tools; an agent can be published as one tool (see Agent tools). The typed AI agents (defineAiAgent definitions such as catalog.catalog_assistant, catalog.merchandising_assistant, and the customers agents) are otherwise a separate in-app surface served by the Next.js app at POST /api/ai_assistant/ai/chat?agent=<module>.<agent> and listed at GET /api/ai_assistant/ai/agents. The MCP server does not expose the chat orchestration layer: an MCP client calls an agent only through the single tool the agent opts into, and gets one structured result back.

You can still see the agent catalog from within MCP: meta.list_agents enumerates the agents the caller is allowed to invoke, and meta.describe_agent returns an agent's details. And because every tool an agent is allowed to call is itself in the MCP tool list, an MCP client already has the full underlying toolset.

Agent tools

An agent tool is a normal MCP tool whose handler runs an AI agent once and returns the agent's structured output. It shows up in tools/list next to the other tools, is called through tools/call (or POST /api/ai_assistant/tools/execute), and is subject to the same exposure config, ACL checks and audit as any other tool.

Publishing an agent: mcpTool

Add mcpTool to the agent definition. It is valid only for an object-mode agent that declares output; the tool loader logs an error and skips any other declaration.

import { z } from 'zod'
import { defineAiAgent } from '@open-mercato/ai-assistant'

export const aiAgents = [
  defineAiAgent({
    id: 'catalog.title_reviewer',
    moduleId: 'catalog',
    label: 'Title reviewer',
    description: 'Scores a product title and suggests a better one.',
    systemPrompt: 'Review the product title you are given.',
    allowedTools: ['catalog.list_products'],
    requiredFeatures: ['catalog.products.view'],
    executionMode: 'object',
    output: {
      schemaName: 'TitleReview',
      schema: z.object({ score: z.number(), suggestion: z.string() }),
    },
    mcpTool: {},
  }),
]
mcpTool fieldDefaultNotes
name<agentId>.runTool name. A name that is already registered is rejected.
descriptionthe agent description (or label)Shown to MCP clients.
inputSchemaz.object({ input: z.string() })Zod input schema. With the default schema the input string is the prompt. A custom schema without toPrompt is sent to the agent as JSON.
toPromptthe input stringTurns validated input into the agent prompt.
requiredFeaturesthe agent's requiredFeaturesMust cover every feature the agent requires (superset rule); a narrower list is rejected. An agent with no required features accepts any list.
exposetruefalse keeps the tool out of tools/list and rejects it on the MCP servers. POST /api/ai_assistant/tools/execute does not apply exposure (see Exposure, audit and mutation modes).

The result schema advertised to clients is built from the agent's output.schema.

Any engine: defineAgentTool

defineAgentTool is the single helper behind mcpTool. Use it directly in a module's ai-tools.ts for an agent that is not an ai_assistant agent, for example one owned by another engine, or when you need full control of the tool name and schemas.

import { z } from 'zod'
import { defineAgentTool } from '@open-mercato/ai-assistant'

export const aiTools = [
  defineAgentTool({
    name: 'catalog.review_title',
    description: 'Scores a product title and suggests a better one.',
    agentId: 'catalog.title_reviewer',
    inputSchema: z.object({ title: z.string().min(1) }),
    outputSchema: z.object({ score: z.number(), suggestion: z.string() }),
    toPrompt: (input) => `Review this product title: ${input.title}`,
    requiredFeatures: ['catalog.products.view'],
    timeoutMs: 60_000,
  }),
]

The default timeout is 120 seconds. The tool is registered as a non-mutation tool tagged agent, with an agentRef that links it to its agent.

How the call runs

  1. When the ai_assistant registry knows the agent, the agent policy check (requiredFeatures, execution mode) runs first. If a registered dispatcher owns the agent id, the call then goes through it, and the dispatcher runs its own checks. Otherwise the ai_assistant runtime runs the agent in object mode.
  2. The handler returns { result, agentId, runId, agentRunId }, plus pendingActionIds when the run queued writes for approval. runId is the ai_assistant run id; agentRunId is the run id assigned by a dispatcher engine. Each is null when the other engine ran the agent.
  3. Output that does not match the schema fails the call.

Result shape

An MCP agent tool call returns:

tools/list advertises the matching outputSchema (result typed from the agent's output, the three id fields, and the optional pendingActionIds). POST /api/ai_assistant/tools/execute returns the same payload as its tool result.

Read-only by default

On the mcp and tools-api channels the agent runs read-only: its mutation tools are stripped, whatever the agent's own mutationPolicy says. The exception is OM_MCP_MUTATION_MODE=approval: the agent keeps its own mutationPolicy, and every write it makes is queued as a pending action exactly like other mutation tools (the result lists the pendingActionIds). That includes the non-destructive writes of a destructive-confirm-required agent, which run directly only in chat. direct and deny never enable agent writes.

Tools the agent calls see the caller's channel, mutation mode, API key id and correlation id. An agent tool nested inside another agent therefore follows the same channel rule, and tools that resolve their own principal (search.*, the document-section tools) run as the API key when the call came in with one, the same as a direct call to that tool.

Availability and errors

CodeMeaning
AGENT_POLICY_DENIEDThe agent policy or the dispatcher refused the call: missing agent features, a disallowed execution mode, no resolvable calling user or tenant scope.
AGENT_DISPATCHER_UNAVAILABLEThe agent id is unknown to this deployment, or the engine that owns it is not available.

Switch agent tools off for a server with --no-agent-tools or OM_MCP_AGENT_TOOLS=false (see exposure config). /tools/execute is not affected by that switch, as for every exposure setting except the mutation mode.

The aiAgentRunDispatcher port

ai_assistant does not know about other agent engines. An engine, such as Agent Orchestrator, registers an object under the DI key aiAgentRunDispatcher that implements:

interface AiAgentRunDispatcher {
  owns(agentId: string): boolean
  isAvailable(agentId: string): Promise<boolean>
  runObject(input: AiAgentRunDispatchInput): Promise<AiAgentRunDispatchResult>
}

The key is resolved soft-optionally: when nothing is registered, or the registered value does not have these three methods, agent tools run through the ai_assistant runtime only. For an agent id the dispatcher owns, runObject receives the agent id, the input, the caller (tenant, organization, user, API key id, features, superuser flag), the channel (mcp, tools-api or chat), via: 'tool', the correlation id and the timeout, and returns { result, agentRunId }. It signals a refusal by throwing AiAgentDispatchDeniedError, which surfaces as AGENT_POLICY_DENIED.

Expose an Agent Orchestrator agent as a tool

When the enterprise agent_orchestrator module is enabled, it registers the aiAgentRunDispatcher and owns every agent declared with its defineAgent (code agents) or an AGENT.md file (file agents). To publish one of these agents, declare a defineAgentTool with its id in a module's ai-tools.ts. The agent_examples app module has a working example:

import { z } from 'zod'
import { defineAgentTool } from '@open-mercato/ai-assistant'
import { ticketTriageResult } from './data/validators'

export const aiTools = [
  defineAgentTool({
    name: 'agent_examples.triage_ticket',
    description: 'Classify a support ticket into a category and priority with a one-line summary.',
    agentId: 'support.ticket_triage',
    inputSchema: z.object({ subject: z.string().min(1), body: z.string().min(1) }),
    outputSchema: ticketTriageResult.shape.data,
    requiredFeatures: ['agent_orchestrator.agents.view'],
  }),
]

Rate limit

Each agent-tool call runs a full agent loop, so calls over the MCP servers (mcp:serve-http, mcp:serve, mcp:dev) and POST /api/ai_assistant/tools/execute are rate-limited. One bucket covers every agent tool, per tenant and per API key; a caller using a session token (_sessionToken or a staff session) gets a bucket per user instead. The default is 30 calls per 60 seconds, tunable with RATE_LIMIT_AI_AGENT_TOOL_POINTS, RATE_LIMIT_AI_AGENT_TOOL_DURATION and RATE_LIMIT_AI_AGENT_TOOL_BLOCK_DURATION. Plain (non-agent) tools and agent tools called from inside an agent's own loop are not counted.

To check the limit end to end, start the app with OM_TEST_RATE_LIMIT_MODE=enabled, RATE_LIMIT_AI_AGENT_TOOL_POINTS=1 and the agent_examples module (OM_ENABLE_ENTERPRISE_MODULES=true OM_ENABLE_ENTERPRISE_MODULES_AGENTS=true), then run the integration spec TC-AI-MCP-RATE-LIMIT-018 with the same two rate-limit variables. CI skips this spec and relies on the unit test tool-executor.agent-tool-rate-limit.test.ts.

Audit

A call to an agent tool writes the usual access_logs row (see Audit of MCP tool calls) with three extra context fields: agentId, aiAgentRunId (the runId above) and agentRunId, so a call can be traced to the agent run it started.

MCP exposure view

GET /api/ai_assistant/tools?view=mcp (feature ai_assistant.view) returns the effective MCP exposure of every tool the caller may use, as the HTTP server resolves it from the process environment (CLI flags are not visible to the app): mutationMode, allowlist, denylist, agentToolsEnabled, and per tool name, module, exposed, hiddenReason, isMutation and agentRef. hiddenReason is one of expose_false, denylist, not_allowlisted, mutation_mode, agent_tools_off or agent_unavailable. Agent tools whose agent cannot run are listed as hidden with agent_unavailable. The AI Assistant settings page shows the same data in a read-only MCP exposure section. Without view, the endpoint keeps returning the plain tool list.

Exposure, audit and mutation modes

These controls apply to all three MCP servers (mcp:dev, mcp:serve-http, stdio mcp:serve). None of them apply to POST /api/ai_assistant/tools/execute. That endpoint runs only read tools: it refuses every isMutation: true tool with 403 { success: false, error } before the handler runs, whatever the mutation mode, and writes a denied audit row. Mutations go through the agent chat or run-object dispatcher, or through an MCP server under the mutation mode below. The allowlist, denylist and agent-tool switch do not filter /tools/execute either: it can call any registered read tool the caller's features allow.

Exposure config

The exposure config decides which registered tools a server offers at all, before any per-caller ACL filtering:

SettingCLI flagEnv varDefault
Allowlist (tool names or prefix globs ending in *, comma-separated)--tools <csv>OM_MCP_TOOL_ALLOWLISTunset = every tool
Denylist (same syntax)--exclude-tools <csv>OM_MCP_TOOL_DENYLISTempty
Mutation mode--mutation-mode direct|deny|approvalOM_MCP_MUTATION_MODEdirect
Include tools that wrap AI agents--no-agent-tools (hides them)OM_MCP_AGENT_TOOLS (boolean)true

Precedence per setting: CLI flag, then env var, then default. The flags are accepted by mcp:serve and mcp:serve-http; mcp:dev reads the env vars only. An invalid --mutation-mode or OM_MCP_MUTATION_MODE refuses to start the server, so a typo can never silently turn approval off. Code that reads the env var without starting a server (the /api/ai_assistant/tools view, the pending-action re-check) treats an invalid value as deny.

A tool is exposed when all of these hold:

  1. it does not opt out with mcp: { expose: false } on its definition;
  2. it matches the allowlist (when one is set);
  3. it does not match the denylist (the denylist wins over the allowlist);
  4. it is not a mutation tool while the mode is deny (in deny mode mutation tools are hidden from tools/list);
  5. it is not an agent-wrapping tool while agent tools are disabled;
  6. it is not the Code Mode execute tool while the mode is approval (see below).

A tools/call for a tool that is not exposed is rejected as NOT_FOUND on every server, even when the client already knows the tool name.

# Only CRM read tools plus search, writes blocked
mercato ai_assistant mcp:serve-http --tools "customers.list_*,customers.get_*,search*" --mutation-mode deny

Inspect the effective set without starting a server:

# Exposure config only (OM_MCP_* env + flags)
yarn mercato ai_assistant mcp:list-tools --effective --tools "customers.*"
# Exposure config plus the ACL of an API key, exactly as mcp:serve-http computes tools/list
yarn mercato ai_assistant mcp:list-tools --as-api-key "$MCP_KEY"

The servers log the resolved config at startup. When the mode is direct and at least one mutation tool is exposed, they log a warning that lists those tools.

Filtered tools/list on mcp:serve-http

mcp:serve-http registers, per request, only the tools that pass the exposure config and the list principal's ACL, so tools/list and tools/call see the same set. Per-call ACL checks still run on every tools/call.

The list principal is:

Without the header, a server key that carries no features lists only context_whoami. Custom clients that act for a user can send the header so the list matches what that user can call.

OpenCode (the web chat and command palette) does not send the header: its MCP config is static and carries only x-api-key, so its tool list is the server key's own ACL. That key must therefore carry roles. The key that mercato ai_assistant mcp:ensure-api-key provisions copies its owner's roles, so the default setup works. If you set MCP_SERVER_API_KEY by hand, give that key the roles the web chat needs; a key with no roles lists only context_whoami and the chat cannot call any other tool.

GET /health on the HTTP server reports the exposure in effect (counts and mode, never tool names):

{"status":"ok","tools":70,"exposure":{"allowlist":false,"denylistCount":0,"mutationMode":"approval","toolCount":70,"agentToolCount":0},"timestamp":"..."}

Audit of MCP tool calls

Every tools/call on the three servers and every POST /api/ai_assistant/tools/execute writes one access_logs row (best effort, bounded to 500 ms, never blocks or fails the call):

FieldValue
resource_kindai_assistant.mcp_tool_call
resource_idthe tool name
access_typecall
actorthe session user, else the API key's session user, else the key's createdBy user
contextchannel (mcp / tools-api), mcpServer (http / dev / stdio / null), apiKeyId, sessionKeyId, principal, outcome (ok, denied, invalid_input, error, mutation_denied, pending_approval, dispatcher_unavailable), errorCode, durationMs, isMutation, agentId, aiAgentRunId, agentRunId (agent tools only, otherwise null), pendingActionIds, correlationId, argKeys

Argument values are never stored, only the argument names (argKeys, without _sessionToken; at most 64 names, each cut to 128 characters).

Refused calls are audited too. A call for an unknown tool, or for a tool hidden from the caller by the exposure config, the mutation mode or the ACL, writes outcome: 'denied' with errorCode: 'NOT_FOUND'; on mcp:serve-http and mcp:dev, arguments rejected by the tool's input schema write outcome: 'invalid_input' with errorCode: 'VALIDATION_ERROR'. The caller gets the same "not found" result for a hidden tool as for an unknown one. On mcp:serve-http a refused call is attributed to the request's verified principal (the x-om-session-token header user, else the API key), never to an unverified _sessionToken argument. In the row, a refused tool name is cut to 128 characters and control or formatting characters are replaced with ?.

Every call gets a correlation id: the x-correlation-id request header when it is valid (max 128 characters, [A-Za-z0-9._:-]), otherwise a fresh UUID. MCP tool results echo it as _meta.correlationId, so a client can quote it when reporting a problem.

Retention: access logs outside the core resource kinds rotate after AUDIT_LOGS_NON_CORE_RETENTION_HOURS (default 8 hours). To keep MCP audit rows for the core window (AUDIT_LOGS_CORE_RETENTION_DAYS), add the kind to AUDIT_LOGS_CORE_RESOURCE_KINDS_EXTRA:

AUDIT_LOGS_CORE_RESOURCE_KINDS_EXTRA=ai_assistant.mcp_tool_call

Mutation modes

OM_MCP_MUTATION_MODE (or --mutation-mode) decides what happens when an MCP client calls a tool with isMutation: true (/tools/execute always refuses them):

ModeBehaviour
direct (default)The tool handler runs immediately, as before.
denyMutation tools are hidden from tools/list. A call returns MUTATION_REQUIRES_APPROVAL.
approvalThe call is validated (exposure, the tool's requiredFeatures, input schema) and stored as a pending action; the handler does not run. A human approves or rejects it later.

Warning · Use approval in production

direct stays the default for backward compatibility, but it lets any API key with the right features write data with no human in the loop. Set OM_MCP_MUTATION_MODE=approval for production deployments that expose write tools over MCP, or deny when MCP clients should be read-only.

In approval mode:

Approving pending actions

Pending MCP actions are approved on the Pending AI actions page at /backend/config/ai-assistant/pending-actions. It lists rows with their tool, target, requester, channel, and expiry; the detail view shows the mutation preview and Approve / Reject (with an optional reason) buttons.

Environment variables

VariableDefaultPurpose
OM_MCP_TOOL_ALLOWLISTunsetComma-separated tool names or prefix* globs to expose. Unset exposes every tool.
OM_MCP_TOOL_DENYLISTunsetComma-separated tool names or prefix* globs to hide. Wins over the allowlist.
OM_MCP_MUTATION_MODEdirectdirect, deny, or approval. MCP servers only; /api/ai_assistant/tools/execute always refuses mutation tools. Recommended in production: approval.
OM_MCP_AGENT_TOOLStrueSet to false to hide tools that wrap AI agents.
RATE_LIMIT_AI_AGENT_TOOL_POINTS / _DURATION / _BLOCK_DURATION30 / 60 / unsetAgent-tool calls allowed per window, per tenant and API key (or session user). See Rate limit.
OM_MCP_PENDING_ACTION_TTL_SECONDS86400Expiry of pending actions created by MCP and /tools/execute.
AUDIT_LOGS_CORE_RESOURCE_KINDS_EXTRAunsetAdd ai_assistant.mcp_tool_call to keep MCP audit rows for the core retention window.

Extending the MCP server

There are two ways to add tools that become available over MCP.

1. Typed tool packs (preferred)

Define the tool with defineAiTool from @open-mercato/ai-assistant inside a module's ai-tools/ directory and export it from the module's ai-tools.ts. These typed tools are also what AI agents reference in their allowedTools.

import { z } from 'zod'
import { defineAiTool } from '@open-mercato/ai-assistant'

export const archiveCustomer = defineAiTool({
  name: 'customers.archive_customer',
  description: 'Archive a customer by id.',
  inputSchema: z.object({
    customerId: z.string().uuid(),
    reason: z.string().optional(),
  }),
  requiredFeatures: ['customers.manage'],
  isMutation: true,
  async handler(input, ctx) {
    const result = await ctx.someService.archive(input.customerId, input.reason)
    return { archived: true, customerId: result.id }
  },
})

A typed tool requires:

2. Low-level registerMcpTool

For a directly-registered MCP tool, call:

registerMcpTool(
  {
    name: 'mymodule.do_thing',
    description: 'Do the thing.',
    inputSchema: z.object({ id: z.string().uuid() }),
    requiredFeatures: ['mymodule.manage'],
    isMutation: true,
    handler: async (input) => ({ ok: true }),
  },
  { moduleId: 'mymodule' },
)

MUST rules when adding a tool

After adding or changing tools, run yarn generate (so the generated tool registry picks them up) and restart the MCP server.

Note

The API key's ACL still gates visibility – a new tool only appears for keys whose roles grant its requiredFeatures.

API-backed tools

API-backed tools are built with defineApiBackedAiTool, which wraps a documented API route.

Warning · Coverage rule (enforced fail-closed)

The tool's requiredFeatures MUST be a superset of the underlying route's requireFeatures. If they don't cover it, the operation runner rejects the call with:

AI tool "<name>" requiredFeatures do not cover route <METHOD> <path> requiredFeatures

Fix it by adding the route's feature(s) to the tool – never by weakening the route.

Troubleshooting

SymptomCauseFix
Only context_whoami is listed (just 1 tool)The API key has no roles/features, so RBAC strips every tool that requires featuresBind the key to a role like admin (CLI --roles admin or via Settings → Auth → API Keys) and reconnect
Tool error: AI tool "<name>" requiredFeatures do not cover route GET <path> requiredFeaturesAn API-backed tool declares fewer features than the route it callsAdd the route's required feature(s) to the tool's requiredFeatures
Operation runner manifest unavailable: No API route manifest registeredThe standalone server didn't register the API route manifestEnsure you are on a build where the MCP boot registers it; update or rebuild if missing
ERR_MODULE_NOT_FOUND: Cannot find package '@/.mercato' … then Registered 0 module-contributed AI tools (historical)The generated registry was imported through the Next.js-only @/ path alias, which a standalone Node process can't resolveUpdate to a build where the loader resolves the generated registry from disk for standalone servers
MCP_SERVER_API_KEY not set badge in the appOnly concerns the production mcp:serve / in-app web-chat pathIgnore it for mcp:dev + Claude Code; set MCP_SERVER_API_KEY only if you run yarn mcp:serve
execute / API-backed tools fail to reach dataThe Next.js app isn't runningRun yarn dev (the app on port 3000; override the base URL via APP_URL / NEXT_PUBLIC_APP_URL)
A tool is missing although the key has its featuresThe exposure config hides it (allowlist/denylist, deny mode for mutation tools, or OM_MCP_AGENT_TOOLS=false)Run mcp:list-tools --effective and check the OM_MCP_* env vars and CLI flags
A write returns pending_approvalOM_MCP_MUTATION_MODE=approvalApprove it on Pending AI actions (/backend/config/ai-assistant/pending-actions)
Claude Code doesn't see updated tools after a changeStale server or stale connectionyarn generate, restart yarn mcp:dev, then reconnect via /mcp in Claude Code

Notes

Tip · Verify the connection

Verify the integration with the intended role

In the client, list tools and run one read operation against a sample record the user is allowed to see. Repeat the listing under a narrower test role. A client that connects successfully can still have an empty or reduced tool list because of its effective permissions.

Previous: Global Launcher · Next: Input Moderation & Safety Identifiers