Framework
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).
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.
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 for | mercato ai_assistant mcp:dev | mercato ai_assistant mcp:serve-http |
| Use for | Claude Code / local testing | In-app web chat |
| Port | 3001 (override with MCP_DEV_PORT) | – |
| Bind address | 127.0.0.1 (loopback) – override with MCP_DEV_HOST | 127.0.0.1 (loopback) – override with MCP_HTTP_HOST env var or --host flag |
| Endpoint | http://localhost:3001/mcp | – |
| Health | http://localhost:3001/health | – |
| Auth | A single API key, read once at startup | Two-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'.
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:
context_whoami tool – the one tool with no required features.admin (which aggregates every module's <module>.* grants) so all tools appear.module.*, *) satisfy concrete required features.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.
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" }
}
}
}
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.
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.
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.
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:
--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.--tenant <id> together with --user <id> (and optionally --org <id>). The named user's ACL is loaded and enforced.--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.
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:
--user <id> so a real user's ACL is enforced (recommended), or--allow-unauthenticated-superadmin if you genuinely need the unscoped superadmin context for local dev/test.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.
| Group | Tools | Required feature | What it does |
|---|---|---|---|
| Built-in context | context_whoami | none | Returns the current auth context – tenantId, organizationId, userId, isSuperAdmin, and the granted features. Use it to confirm your scope. |
| Code Mode meta-tools | search, execute | ai_assistant.view | Discover and call the full API surface from JavaScript (see below). |
| Module tool packs | 67 typed tools | per-tool requiredFeatures | Typed 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.
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:
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"))' })
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.
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.
mcpToolAdd 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 field | Default | Notes |
|---|---|---|
name | <agentId>.run | Tool name. A name that is already registered is rejected. |
description | the agent description (or label) | Shown to MCP clients. |
inputSchema | z.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. |
toPrompt | the input string | Turns validated input into the agent prompt. |
requiredFeatures | the agent's requiredFeatures | Must cover every feature the agent requires (superset rule); a narrower list is rejected. An agent with no required features accepts any list. |
expose | true | false 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.
defineAgentTooldefineAgentTool 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.
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.{ 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.An MCP agent tool call returns:
structuredContent: { result, agentId, runId, agentRunId }, where result matches the agent's output schema, plus pendingActionIds when the run queued writes for approval;structuredContent;_meta.correlationId, as for every MCP result.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.
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.
tools/list and the /api/ai_assistant/tools?view=mcp view when the agent cannot run on this deployment: it is not in the registry, or the engine that owns it reports it unavailable.requiredFeatures to see or call it, and the agent's own policy is checked again at call time.| Code | Meaning |
|---|---|
AGENT_POLICY_DENIED | The agent policy or the dispatcher refused the call: missing agent features, a disallowed execution mode, no resolvable calling user or tenant scope. |
AGENT_DISPATCHER_UNAVAILABLE | The 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.
aiAgentRunDispatcher portai_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.
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'],
}),
]
toPrompt is not used on this path.result is the agent's result payload: the data of a research result, the proposal of a proposal agent, or { artifacts, summary } for a file agent. The response carries runId: null and the orchestrator run id in agentRunId.requiredFeatures on the agent: on defineAgent({ requiredFeatures }), or with the requiredFeatures key in the AGENT.md frontmatter. Use features that already exist in an acl.ts. The orchestrator checks that the invoker holds them at every entry point: its run and rerun routes, the Playground, delegate_agent, workflow INVOKE_AGENT steps, eval replay, POST /api/ai_assistant/ai/run-object, agent tools, and the agent-token route below. A denial returns agent_invoke_denied, without the feature names. The tool's requiredFeatures must include every feature the agent requires.POST /api/ai_assistant/ai/run-object with an orchestrator agent id hands the run to the dispatcher too. That response carries runId: null and agentRunId. Such a run does not accept attachmentIds, pageContext or modelOverride: a request setting any of them returns 422 with dispatch_option_unsupported.POST /api/agent_orchestrator/agent-api/agents/{id}/run with Authorization: Bearer <agent token>. The route returns 404 unless OM_AGENT_API_ENABLED=true, is rate-limited per client IP, and requires a token whose scopes include agent_orchestrator.agents.run or agent:<id>. Every token failure is the same 401. The run executes as the token principal, so the agent's requiredFeatures are checked against that principal's role.OM_AGENT_INVOKE_ENFORCEMENT=off turns invoke denials into log entries (a warning is logged at boot). Use it only to unblock a rollout, and turn it back on.agent_orchestrator no dispatcher is registered and nothing else knows the agent id. The tool is then hidden from tools/list, a direct call returns AGENT_DISPATCHER_UNAVAILABLE, and the MCP server starts normally.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.
RATE_LIMITED without starting the agent; /tools/execute answers 429 with Retry-After. The audit row records outcome: denied.RATE_LIMIT_UNAVAILABLE (503 on /tools/execute, audit outcome: error) instead of running unmetered.RATE_LIMIT_ENABLED=false, calls are not limited.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.
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.
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.
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.
The exposure config decides which registered tools a server offers at all, before any per-caller ACL filtering:
| Setting | CLI flag | Env var | Default |
|---|---|---|---|
Allowlist (tool names or prefix globs ending in *, comma-separated) | --tools <csv> | OM_MCP_TOOL_ALLOWLIST | unset = every tool |
| Denylist (same syntax) | --exclude-tools <csv> | OM_MCP_TOOL_DENYLIST | empty |
| Mutation mode | --mutation-mode direct|deny|approval | OM_MCP_MUTATION_MODE | direct |
| 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:
mcp: { expose: false } on its definition;deny (in deny mode mutation tools are hidden from tools/list);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.
tools/list on mcp:serve-httpmcp: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:
x-om-session-token: sess_… header (the same session token that tool calls pass as _sessionToken). An invalid or expired header returns 401;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":"..."}
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):
| Field | Value |
|---|---|
resource_kind | ai_assistant.mcp_tool_call |
resource_id | the tool name |
access_type | call |
| actor | the session user, else the API key's session user, else the key's createdBy user |
context | channel (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
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):
| Mode | Behaviour |
|---|---|
direct (default) | The tool handler runs immediately, as before. |
deny | Mutation tools are hidden from tools/list. A call returns MUTATION_REQUIRES_APPROVAL. |
approval | The 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:
tools/call returns a normal (non-error) result whose structured content is { status: "pending_approval", pendingActionId, expiresAt, approvalPath, ... }.MUTATION_REQUESTER_UNRESOLVED._sessionToken); such rows store no API key, so the approval re-check follows that user's ACL. Only API-key principals record apiKeyId, and deleting or expiring that key fails the approval with requester_revoked.pending returns the same row. Once the row was approved, rejected, failed or expired, the same call queues a new row.OM_MCP_PENDING_ACTION_TTL_SECONDS (default 86400, 24 hours). Chat-created rows keep AI_PENDING_ACTION_TTL_SECONDS.execute tool is not available in approval mode. Its code runs arbitrary api.request() calls with the caller's credentials, which an approved execution does not have, so it cannot be queued meaningfully. It is hidden from tools/list, and a call on MCP or /tools/execute returns MUTATION_REQUIRES_APPROVAL with the message that execute is not available in approval mode. Tool authors mark such tools with mcp: { approvalMode: 'refuse' }. Use typed module tools (which queue normally) for writes, or search plus a read-only flow.mutationPolicy in approval mode, but every write is queued, including the non-destructive writes of a destructive-confirm-required agent (the tool result lists the pendingActionIds). In direct and deny modes agent tools are downgraded to read-only.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.
ai_assistant.pending_actions.approve feature (granted to admin by default). Everyone else gets 404. Chat-created rows stay owner-only. Approve and reject need a signed-in user: an API-key caller gets 403 api_key_cannot_decide.mcp or tools-api also re-check the requester (requester_revoked, requester_features_denied), so a revoked or expired API key cannot leave approvable writes behind.ai_assistant.pending_action.awaiting_approval); the notifications are removed when the row is approved, rejected, or expires.tool_not_exposed), that the approver holds the tool's requiredFeatures (approver_features_denied), and that the requester still exists and still holds them (requester_revoked, requester_features_denied). Record-version and schema-drift checks run as for chat approvals.correlationId, API key and pending-action id are passed to the tool handler only; they are not yet copied into the action_logs row, so link the write back to the MCP call through the pending action (resolvedByUserId, correlationId) and the access_logs row.GET /api/ai_assistant/ai/actions lists rows visible to the caller (filters status, channel, toolName, mine; pageSize ≤ 100) and returns channel and requester: { userId, apiKeyId } per row. GET /api/ai_assistant/ai/actions/:id, POST …/:id/confirm and POST …/:id/cancel (body { reason? }) act on one row.ai_assistant.get_pending_action returns the status of a pending action the caller can see, so an MCP client can poll the outcome of a queued write.| Variable | Default | Purpose |
|---|---|---|
OM_MCP_TOOL_ALLOWLIST | unset | Comma-separated tool names or prefix* globs to expose. Unset exposes every tool. |
OM_MCP_TOOL_DENYLIST | unset | Comma-separated tool names or prefix* globs to hide. Wins over the allowlist. |
OM_MCP_MUTATION_MODE | direct | direct, deny, or approval. MCP servers only; /api/ai_assistant/tools/execute always refuses mutation tools. Recommended in production: approval. |
OM_MCP_AGENT_TOOLS | true | Set to false to hide tools that wrap AI agents. |
RATE_LIMIT_AI_AGENT_TOOL_POINTS / _DURATION / _BLOCK_DURATION | 30 / 60 / unset | Agent-tool calls allowed per window, per tenant and API key (or session user). See Rate limit. |
OM_MCP_PENDING_ACTION_TTL_SECONDS | 86400 | Expiry of pending actions created by MCP and /tools/execute. |
AUDIT_LOGS_CORE_RESOURCE_KINDS_EXTRA | unset | Add ai_assistant.mcp_tool_call to keep MCP audit rows for the core retention window. |
There are two ways to add tools that become available over MCP.
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:
name – namespaced like mymodule.do_thing.description.inputSchema – a Zod schema.requiredFeatures – an array of ACL feature ids.isMutation – true for writes.handler(input, ctx) – an async function returning a serializable object.registerMcpToolFor 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' },
)
requiredFeatures for anything that reads or writes tenant data – never leave it empty for data tools.inputSchema – never raw JSON Schema.isMutation: true on every write tool. tools/list derives readOnlyHint from this flag, and MCP clients use that hint to decide whether a call needs human approval; an unflagged write is advertised as read-only.prepareMutation).acl.ts and grant them in setup.ts defaultRoleFeatures.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 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.
| Symptom | Cause | Fix |
|---|---|---|
Only context_whoami is listed (just 1 tool) | The API key has no roles/features, so RBAC strips every tool that requires features | Bind 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> requiredFeatures | An API-backed tool declares fewer features than the route it calls | Add the route's required feature(s) to the tool's requiredFeatures |
Operation runner manifest unavailable: No API route manifest registered | The standalone server didn't register the API route manifest | Ensure 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 resolve | Update to a build where the loader resolves the generated registry from disk for standalone servers |
MCP_SERVER_API_KEY not set badge in the app | Only concerns the production mcp:serve / in-app web-chat path | Ignore 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 data | The Next.js app isn't running | Run 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 features | The 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_approval | OM_MCP_MUTATION_MODE=approval | Approve it on Pending AI actions (/backend/config/ai-assistant/pending-actions) |
| Claude Code doesn't see updated tools after a change | Stale server or stale connection | yarn generate, restart yarn mcp:dev, then reconnect via /mcp in Claude Code |
context_whoami has no requiredFeatures, so it survives RBAC filtering while every data tool is stripped. Grant the key a role and reconnect.Registered N API route manifests for API-backed tools.MCP_SERVER_API_KEY is unrelated to the mcp:dev + Claude Code workflow. It only matters for the production yarn mcp:serve path and the in-app web chat.Tip · Verify the connection
curl http://localhost:3001/health checks the server is up./mcp shows the current connection state.yarn mercato ai_assistant mcp:list-tools --verbose lists all registered tools and their required features.yarn mercato ai_assistant mcp:list-tools --effective (or --as-api-key <secret>) lists only the tools the exposure config (and that key's ACL) would expose.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