Imagine a marketing manager asking Claude, “Which channels brought visitors who were most likely to buy last week?” Hardal already has the data. Before Claude can read it, the service has to know who the user is, which workspaces they can access, and which reports the application may read. The answer also needs to agree with the dashboard.
Hardal MCP connects those pieces. An MCP-compatible client can connect with the user’s approval and read their Hardal reports.
I led this project. The first implementation reached production in eight days. Twenty-two days is the span from the planning document to the main build issue marked Done. The roughly two weeks between that production deployment and Done were the first-day failures, the quota proof, the dashboard fixes, and the review findings resolved before merge. This is the story of the decisions I made, the failures found after deployment, and the assumptions I had to change.
Why I started from scratch
Hardal already had an MCP server, tied to the legacy analytics platform. Nebula, the new platform, had a different data path and authorization model. The team could not find that remote server’s source code in the repositories, and it had no active users.
That gave me room to build for Nebula without a compatibility requirement for existing users. I left the legacy service alone during development and stopped it when the new service went live. The old documentation lagged behind the cutover for a while, which was one cost of that decision.
Before writing code, I prepared two documents.
The first was a tool contract: the question each tool answered, its inputs and outputs, the endpoint it called, and its errors. The schema and coverage validation eventually passed 459 checks. Those were contract checks; OAuth, runtime behavior, and dashboard parity still needed implementation tests.
The second was the security design: who could access what, through which credential, and for how long.
My first technical plan was too long. The feedback was direct: one page, in English, focused on outcomes. I reduced it to roughly 770 words. The team organized the work into milestones from discovery through launch, and the project eventually grew to 77 Linear issues. For every issue estimated M or larger, I wrote the implementation plan on the issue and got another person’s approval before coding.
That preparation gave me specific decisions to implement and a record to revisit when the design changed.
The architecture decisions
Two services already defined the boundaries of Nebula. Beacon managed users, roles, tenants, and access. Sirius computed reports from ClickHouse. I had to decide where MCP would connect and where its authority would come from.
Keep OAuth with the existing identity system
I put the OAuth authorization server inside Beacon API, with login and consent in Beacon Web. Beacon already knew the user and their current permissions. Keeping authorization there let OAuth applications and public Reports API keys share one access model.
The HTTP authorization flow followed the MCP authorization specification, which builds on OAuth 2.1 and related standards.
I chose to implement the required OAuth protocol operations directly, without an OAuth server library. That increased the code I owned: PKCE, token rotation, registration, introspection, and exchange. I made independent authentication and authorization review, together with security regression tests in CI, part of the release requirements.
The hosts below are placeholders. The sequence is the one I shipped: the user approves an opaque token in Beacon, the client presents that token to MCP, and MCP exchanges it for a separate Reports credential.
Choose opaque tokens for current-state authorization
I wanted disconnecting an application to remove access across replicas within seconds. I chose opaque user tokens over self-contained JWTs, stored only their hashes in PostgreSQL, and checked current authorization state on requests. MCP verified its incoming token through Beacon’s token introspection endpoint.
Access tokens lasted 15 minutes. A refresh-token family had a maximum lifetime of 30 days, with rotation on use. Reusing an already consumed refresh token revoked the family.
The tradeoff was an ongoing database and introspection cost. I accepted that cost to keep revocation tied to shared, authoritative state. Opaque tokens alone do not provide fast revocation; the checks around them do.
Separate the MCP and Reports API audiences
The token a client presents to MCP cannot be used directly against the Reports API.
MCP authenticates as a service and uses OAuth token exchange to obtain a separate Reports API credential on the user’s behalf. Its lifetime is capped at five minutes and by the remaining source-token lifetime. It cannot be refreshed or exchanged again, and it cannot expand the user’s approved scope.
I later added bounded reuse of exchanged credentials, avoiding a fresh exchange for every upstream request. Beacon still checks the grant and current permissions when the credential is used.
That is two audiences and one source of permission. A service identity by itself could not authorize access to a user’s reports.
The request MCP sends is a token exchange. The subject token is the user’s opaque token. MCP’s own service credential only authenticates the caller that is allowed to ask for the exchange.
POST /oauth/token HTTP/1.1
Host: beacon.example
Authorization: Basic <mcp-service-credentials>
Content-Type: application/x-www-form-urlencoded
grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&subject_token=<opaque-user-token>
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&audience=reports-apiA successful exchange returns a short-lived access token for that audience. Beacon still checks the grant and the user’s current permissions when the credential is used. The path and host here are illustrative; the production issuer is the one configured for the deployment, which is also why an audience change later broke existing connections.
Build on the public API and deploy MCP separately
MCP calls Beacon’s public /v1 API. Beacon then calls Sirius. Going through Beacon kept tenant checks, source ownership, rate limits, and reporting behavior in the same path used by the public API.
I reviewed 36 existing report routes. Twenty-eight aggregate or read-only helper operations were included; adding workspace discovery brought the authorized surface to 29 operations. Visitor-level event and session records, individual agent visit logs, and persistent mutations stayed outside the boundary.
The early plan placed MCP in the Beacon monorepo as a separate application. During implementation, I moved it into its own repository and Azure Container App, using the public usehardal/mcp repository. That gave it its own deployment, scaling, and debugging cycle. It ran on Bun and Elysia, with a fresh MCP server instance for each request and no persistent MCP session requirement.
I grouped the surface into six tools, around the questions customers ask:
get_context: discover authorized organizations, tenants, and sources.get_overview: read report summaries and trends.get_breakdown: explore supported dimensions and report details.compare_periods: compare two resolved date ranges.get_events: read aggregate event metrics and available event names.get_funnels: discover and analyze funnels, including read-only previews.
Some operations from the original contract became modes within these tools. I kept the selection surface small while retaining report coverage.
Each tool’s schema named the question, the inputs, and the errors. get_overview is the one that reads a summary and, when asked, a trend. includeTrend is a real input: a single-source overview failed in testing when a client sent includeTrend: false. The arguments below are the scope fields I compared against the dashboard, not a dump of every production property.
{
"name": "get_overview",
"description": "Read a report summary, and a trend when includeTrend is true.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
"required": ["sourceId", "from", "to", "timezone"],
"properties": {
"sourceId": { "type": "string" },
"from": { "type": "string" },
"to": { "type": "string" },
"timezone": { "type": "string" },
"includeTrend": { "type": "boolean" }
}
}
}A client call then looks like any other tool request. The user token rides on the MCP connection. It is not a field in the arguments, and it is not a credential the model is allowed to invent.
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "get_overview",
"arguments": {
"sourceId": "source_example",
"from": "2026-11-01",
"to": "2026-11-08",
"timezone": "Europe/Istanbul",
"includeTrend": true
}
}
}The first day in production
The first deployment exposed configuration problems immediately. Required URL variables were missing, leaving localhost defaults in place. Early revisions crash-looped even though the deployment pipeline appeared successful. There was no post-deploy application health check, probes only checked the TCP port, and alert rules were missing.
I started recording the deployed revision, image, environment configuration, certificate, and smoke-test results on the release issue. A successful workflow needed evidence from the running service.
Scaling introduced another problem. With the minimum replica count at zero, the first request took about 22 seconds. That was long enough to disrupt an AI client’s connection flow. I raised the minimum to two replicas.
The most useful finding came from testing disconnect while reports were already running. Of ten MCP report calls in flight at disconnect, eight still returned full reports. Beacon checked authorization at the start of the request, but report preparation took time. Revocation could happen between that check and the response.
I added a credential and grant check immediately before Beacon returned a /v1 response. In the production retest, none of eleven in-flight MCP calls—ten reports and one context request—returned data. That was an observed result for the tested run. A small forwarding window between Beacon’s response and MCP’s delivery remained outside that fix.
The next address change showed me how audience bindings persist. The team moved the Reports API and OAuth issuer to a new domain, and I moved MCP from /mcp to the host root. Existing credentials were still bound to the old audience. Refresh could succeed while issuing another credential for that old resource, leaving the connection broken afterward.
I corrected refresh handling to use the configured audience and treated the root URL with and without a trailing slash as the same resource. Existing connections still needed to be added again for the path migration. A URL change had become a token-lifecycle change.
Setting limits by measuring them
An AI client can send requests much faster than a person navigating a dashboard. I wrote the limits down before implementation. Each one had a reason, and an M-sized change still needed another person’s approval.
| Limit | Value | Reason |
|---|---|---|
| Tool-call budget | 20 seconds, covering token exchange and the report request | Sirius times out at 25 seconds, so MCP can return a structured error first |
| Upstream response body | 2 MiB | Bound the payload MCP will read |
| Tool output | 256 KiB | Bound what the model receives |
| Local MCP backstop | 300 calls per user per minute, and 600 per tenant | A local ceiling, not the shared quota |
Two measurements changed those numbers.
| Measurement | What it showed | What changed |
|---|---|---|
| Overview fan-out | One overview became 12 ClickHouse queries. A per-tenant queue depth of 10 sat too close to that. | I set 24 waiting operations beside the 3 concurrent slots already there per tenant per process. Overflow returns a retryable 429 with Retry-After. |
| Quota per replica | A cap of 300 on each replica applied on its own, so the shared total grew with the replica count. | Counters moved to one Redis instance. A teammate set up the shared Redis instance. The MCP caps stayed local backstops. |
| Limiter key | A key of credential ID treated each fresh exchange as a different caller. | Counters are keyed by grant and tenant. If Redis is down, the request is allowed through, and authorization still requires a valid current grant. |
With three Beacon replicas running, 330 requests to /v1/workspace/access in one minute returned 300 HTTP 200s and 30 HTTP 429s. That measured the shared quota on the context route. Report execution still needed its own check.
I kept the gaps visible:
- Deadline and concurrency failures were exercised in a controlled harness.
- The granted production tenant was too small to reproduce every failure live.
- Redis fail-open behavior was tested locally.
- The MCP deadline did not cancel work already running in Beacon and Sirius.
Testing answers against the dashboard
An endpoint returning successfully says little about the answer a person receives. The acceptance question I used was whether the client’s answer agreed with the dashboard for the same scope.
I tested in layers. The MCP repository’s automated suite grew from 88 to 180 tests during the work. Postman collections exercised OAuth, the Reports API, and MCP endpoints. MCP Inspector and purpose-built Dynamic Client Registration and PKCE clients exercised sign-in. I then tested real clients, including Claude, ChatGPT, Codex, and Grok.
Nebula had no staging environment. I ran isolated local and CI checks first, then controlled checks against deployed revisions.
For dashboard comparisons, I matched the tenant, source, dates, timezone, consent filter, and report settings. Where applicable, I also compared the result with a separately authorized /v1 API request.
The initial scenario tally was 17 of 20 passing in Claude and 19 of 22 in ChatGPT. The successful answers reproduced dashboard values, including real zeros. The failures showed why a “no invented numbers” result would still be insufficient:
- Multi-day AI-agent rankings followed first appearance rather than total visits, leaving the dashboard’s leading agent out of a five-row answer.
- A five-row AI page breakdown still carried enough time-series points to exceed the response limit.
- A single-source overview failed when the client supplied
includeTrend: false. - Country rankings used consented visitors while the dashboard ranked by sessions.
- Item conversion rate used a percentage scale where other rates used ratios, making 0.59% easy to interpret as roughly 59%.
Accurate raw values can still produce a misleading answer when ordering or units are wrong. I fixed these five findings, added regression coverage, and repeated the dashboard checks on production. All five passed in the Claude connector. That retest did not include ChatGPT, so I would not present it as a complete rerun of both clients’ original suites.
Clients brought their own behavior, too. One registered a new OAuth client on every connection. Another used a callback domain outside the allowlist. ChatGPT made parallel calls, encountered tenant-busy, and did not retry. During an earlier consent test, preselected workspaces led a tester to approve more than intended.
These observations changed both implementation and test cases. Consent defaults, retry behavior, and tool selection were part of the product I needed to verify.
Working with AI agents
I used Claude Code for much of the analysis, implementation, verification, and live testing. My rule was simple: agents could write code and run checks; I retained the decisions to commit, push, and open a pull request.
Before each PR, I asked an agent that had not seen the implementation to review it against the repository’s REVIEW.md. Codex reviewed the PR as well, and open review threads had to be resolved before merge. One review found two issues marked P1, and the response-envelope change drew six issues marked P2, before merge. P1 and P2 are severity levels from that review. Open threads had to be resolved before merge. The findings themselves, and the code changes that closed them, are not written down here.
Guard hooks blocked access to .env files and restricted production-database access. These rules made the boundary between automated work and human authorization explicit.
The agents also made ordinary, expensive mistakes. A multiline regex edit silently broke a CI YAML file. An agent overwrote an existing test file twice in one day. Renaming a GitHub branch closed its open pull requests.
Those incidents changed my verification habits. After a structured-file edit, I checked that it parsed. For workflow changes, I ran the actual steps. Before accepting a change, I read the full diff. Fast edits needed equally deliberate verification.
What I deferred and reversed
Keeping V1 focused required removing work as well as finishing it. Public documentation search moved to V2. The support-request tool was deferred and later cancelled. I also removed a feedback tool after its write behavior conflicted with the read-only tool surface and marketplace submissions.
I reversed another decision more substantially. My first approach to response restrictions removed fields that were absent from the contract document. When I reviewed the removal list, I realized I had treated the document as the requirement. The actual requirement was to preserve the report data people trusted in the dashboard.
I changed the rule: preserve existing fields and values, with the explicitly agreed normalization of query strings and fragments in path labels. Then I added a versioned response envelope around the data.
The envelope described the effective date range, timezone and its origin, source, applied filters, currency, completeness, missing values, and pagination. Errors carried stable codes and retry information. A real zero remained zero; an unavailable metric remained null with an explanation.
{
"data": { "visitors": 0 },
"range": { "from": "2026-11-01", "to": "2026-11-08" },
"timezone": { "value": "Europe/Istanbul", "origin": "request" },
"sourceId": "source_example",
"filters": [],
"currency": "EUR",
"completeness": "complete",
"missing": [],
"pagination": null
}visitors: 0 is a real zero. A metric the report cannot compute stays null and is named in missing, so the model has a reason to withhold a number instead of filling one in.
That context gave the model a clearer basis for explaining a number and acknowledging an incomplete result.
I also added PostHog usage events. Tool activity could be measured without sending argument values, report responses, or conversation contents to product analytics.
What I learned while leading it
-
Write the contract before implementation. I wrote the tool contract and the security design before any code. The first implementation reached production in eight days. The timeline and the contract sit next to each other here. This account does not trace those eight days back to the contract. Ambiguous parts of the contract still created work later.
-
Record decisions while they are being made. Written approval for scope, limits, and audience changes gave implementation and review a shared reference. It also made reversals easier to explain.
-
Check the requirement behind the document. I nearly removed useful report data because it was absent from a schema. The dashboard-parity requirement was the reason to change that schema.
-
Describe exactly what the evidence proves. A contract check, a harness result, a production smoke test, and a real client’s dashboard comparison answer different questions. I needed all of them, and I needed to name the gaps.
-
Make completion clear across the team. Teammates handled infrastructure, Redis, DNS, and marketplace work. The quota store is the handoff I can point to. A teammate set up the shared Redis instance. For me the handoff was done when the counters were keyed by grant and tenant, the MCP caps stayed local backstops, authorization still required a valid grant if Redis was down, and three Beacon replicas returned 300 HTTP 200s and 30 HTTP 429s from 330 requests to
/v1/workspace/accessin one minute.
For the current connection URL and instructions, see the Hardal MCP setup guide.