Customers asked to read their visibility data from their own AI agents instead of the dashboard. The Model Context Protocol gives an agent a list of tools it can call. The engineering question was how to add that door without building a second copy of the product behind it, and without giving an agent more authority than the person who created its key.

The problem

A second interface usually becomes a second implementation. The REST routes already resolve the workspace, enforce roles, charge credits and shape responses. If MCP tools called the use cases directly, each tool would have to repeat those steps, and the first forgotten check would be a hole: a tool that reads another workspace’s data, or a paid action that skips the charge.

The second problem is authority. An API key is a long-lived secret handed to software that runs unattended. It needs a narrower scope than a login session, an end date, and a way to die when the person behind it loses access.

One function for every tool

Two rows of boxes. Top row: an MCP client, the customer's agent with a Bearer sk_live key, calls McpAuthMiddleware, which does a hash lookup, checks expiry and the owner's current role; a bad, revoked or expired key gets 401 with JSON-RPC code minus 32001. Next is a rate limit with a token bucket per key; over the limit gets 429. Then the tool: readouts are free GETs and actions are paid with their flag off by default. Every tool calls one function, self_call, on the second row, where the write check runs before any request is built; a read-only key with a write method gets a tool error and the route is never reached. self_call calls the FastAPI route, the same route the web app calls, which calls the use case in a domain package, which reads workspace-scoped documents in MongoDB. A note says tools hold no business logic.
Figure 1. The path of an MCP call. Authentication and rate limiting wrap the whole MCP application. Every tool then goes through one function that checks the key's scope and calls the web app's own route in-process.

REST stays the single source of truth. An MCP tool is a thin adapter: a name, a description for the agent, and a call to an existing route. The call does not leave the process. It goes through httpx.ASGITransport straight into the FastAPI application, so the request passes the same dependencies as a browser request: workspace resolution, role gates and credit charging.

All tools share one request function.

async def _request(app, principal: ApiPrincipal, method: str, path: str, *,
                   json_body: dict | None = None,
                   params: dict[str, Any] | None = None) -> httpx.Response:
    _check_path(path)
    if not principal.allows(method):
        raise PermissionError(READ_ONLY_KEY_MESSAGE)
    token, ws = await _principal_token(principal)
    headers = {"Authorization": f"Bearer {token}"}
    if ws:
        headers["X-Workspace-Id"] = ws
    transport = httpx.ASGITransport(app=app)
    ...

The order of the first lines is the design.

  1. _check_path rejects a path that tries to climb out of the intended route, since some tool arguments end up inside a URL.
  2. principal.allows(method) is the scope check. It runs before a token is minted and before a request object exists.
  3. Only then is a short session issued for the key’s owner and the workspace pinned in a header.

A read-only key calling a write tool therefore never reaches a route. There is no handler that could forget to check, because the request is never built.

Keys

PropertyHow it works
Formatsk_live_ followed by a random URL-safe token
Storageonly the SHA-256 hash, under a unique index, plus a short display prefix; the plaintext is shown once
Scoperead or read_write; only read_write may use methods other than GET, HEAD and OPTIONS
Expirynever, or 30, 90 or 180 days chosen when the key is created
Revocationa revoked_at timestamp
Owner’s rolere-read on every request

verify_api_key returns nothing, and the caller gets a 401, when the prefix is wrong, the key is unknown, revoked or expired, or the row was purged. It also returns nothing when the key’s owner no longer holds a role that may write. The role is not copied into the key at creation. It is looked up each time, so demoting a teammate to viewer disables their keys in the same moment without anyone having to remember that the keys exist.

Feed keys for publishing channels use a different prefix and are refused by MCP, so a key meant for one narrow purpose cannot open the general door.

The gate order

Authentication wraps the whole MCP application as ASGI middleware, outside the protocol layer. Every HTTP request is authenticated before any tool is dispatched or even listed.

StepRefusalMeaning for the agent
McpAuthMiddlewareHTTP 401, JSON-RPC code -32001, with a WWW-Authenticate headerthe key is missing, wrong, revoked or expired; the message says how to fix it
Rate limit, a token bucket per keyHTTP 429too many calls this minute
Scope check in the shared request functiona tool result marked as an errorthe key is read-only and the tool writes
The route’s own role gate403 from the route, returned through the toolthe owner’s role does not allow this

The distinction between the first and third rows matters to an agent. A 401 means “your credentials are bad, stop”. A tool error means “this action is not available to you, the others still are”, and the agent can continue with read tools.

Check it yourself

The endpoint is public, so the first row of that table can be verified without an account.

curl -i -X POST https://mcp.traillabs.ai/mcp/ \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
HTTP/2 401
www-authenticate: Bearer realm="trail-search-mcp"

{"jsonrpc": "2.0", "error": {"code": -32001, "message": "Invalid, expired or revoked API key.
 Check the Authorization header value is Bearer sk_live_..."}, "id": null}

Listing tools is refused too. An agent without a key learns nothing about what the server can do.

Tool categories

Tools come in two groups.

Readouts are read-only and free. They are generated from one table of tool definitions and cover what the dashboard shows: brands, the visibility overview, per-engine visibility, citations and competitor gaps, prompts and their health, runs and their raw cells, weekly reports, site audits and their fixes, traffic status and the credit balance.

Actions write or spend credits. They are registered only when a flag is on, and the flag is off by default and pinned off in the process configuration that lives in version control. With the flag on, each workspace also has a daily cap, counted in its own collection under a unique index on workspace and day.

The transport itself is on by default, because a read-only door that needs a key spends nothing. The pieces that can spend money are the ones that default to off. No MCP tool starts a measurement run.

Failure modes

What goes wrongWhat the system doesRegression test
Request without a bearer key401 before any tooltest_mcp_requires_bearer
Bad key401 whose message says how to fix ittest_bad_key_gets_401_that_says_how_to_fix_it
Expired key401test_expired_key_gets_401
Read-only key calls a write toolRefused before the routetest_read_only_key_write_tool_is_refused_before_the_route
Read-write key calls a write toolReaches the routetest_read_write_key_write_tool_reaches_the_route
Owner demoted to viewerTheir keys stop workingtest_key_dies_on_demotion_to_viewer
A channel feed key is used for MCPRefusedtest_a_channel_key_cannot_open_mcp
Tool argument tries path traversalRejected by the path checktest_mcp_path_traversal.py
Paid tools flagOff unless settest_paid_flag_defaults_off
Daily cap reachedFurther paid calls refusedtest_daily_cap_counts_and_refuses

One more test, test_route_gates_match_expected, lists every route with the gate it is expected to carry, and its sibling fails when a non-GET route is added without a gate or an explicit excuse. That test is what lets the MCP layer trust the routes.

Limits I know about

The rate limit is kept in memory, per process. With one API process that is exact. With several it would allow each process its own budget, and the counter would have to move to the database or a shared cache.

Tools are generated for reading first. An agent can inspect everything the dashboard shows and cannot yet change tracked prompts or start runs. Opening those needs the same care as the paid actions: a flag that defaults to off, a daily cap, and a scope that the key’s creator chose on purpose.