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

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.
_check_pathrejects a path that tries to climb out of the intended route, since some tool arguments end up inside a URL.principal.allows(method)is the scope check. It runs before a token is minted and before a request object exists.- 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
| Property | How it works |
|---|---|
| Format | sk_live_ followed by a random URL-safe token |
| Storage | only the SHA-256 hash, under a unique index, plus a short display prefix; the plaintext is shown once |
| Scope | read or read_write; only read_write may use methods other than GET, HEAD and OPTIONS |
| Expiry | never, or 30, 90 or 180 days chosen when the key is created |
| Revocation | a revoked_at timestamp |
| Owner’s role | re-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.
| Step | Refusal | Meaning for the agent |
|---|---|---|
McpAuthMiddleware | HTTP 401, JSON-RPC code -32001, with a WWW-Authenticate header | the key is missing, wrong, revoked or expired; the message says how to fix it |
| Rate limit, a token bucket per key | HTTP 429 | too many calls this minute |
| Scope check in the shared request function | a tool result marked as an error | the key is read-only and the tool writes |
| The route’s own role gate | 403 from the route, returned through the tool | the 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 wrong | What the system does | Regression test |
|---|---|---|
| Request without a bearer key | 401 before any tool | test_mcp_requires_bearer |
| Bad key | 401 whose message says how to fix it | test_bad_key_gets_401_that_says_how_to_fix_it |
| Expired key | 401 | test_expired_key_gets_401 |
| Read-only key calls a write tool | Refused before the route | test_read_only_key_write_tool_is_refused_before_the_route |
| Read-write key calls a write tool | Reaches the route | test_read_write_key_write_tool_reaches_the_route |
| Owner demoted to viewer | Their keys stop working | test_key_dies_on_demotion_to_viewer |
| A channel feed key is used for MCP | Refused | test_a_channel_key_cannot_open_mcp |
| Tool argument tries path traversal | Rejected by the path check | test_mcp_path_traversal.py |
| Paid tools flag | Off unless set | test_paid_flag_defaults_off |
| Daily cap reached | Further paid calls refused | test_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.
