The authorization half of the MCP server is covered in building a remote MCP server with OAuth 2.1. This post is about the order of work for a rank tracker API and the decisions that leak from the API into every client.
Why the order is contract, API, SDK, MCP
Every layer after the API is a client. The SDK is a typed client, the MCP server is a tool-shaped client, and the connectors are clients with their own auth. If the MCP server is built first, it stops being a client and becomes a second API with its own behaviour.
The failure mode is predictable. The MCP tool needs a compact result, so it gets its own query. The SDK needs a different shape, so it gets a mapper. Six months later there are three definitions of “latest ranking” and no way to tell which one is correct.
The contract prevents that by being the only definition. Every endpoint is described once, the SDK types are generated from the description, and the MCP tools dispatch to the same handlers the public API uses. A change to the contract is a change to every client at once, which is the point.
The build order
The platform was split into a foundation step and nine parallel workstreams, each in its own worktree with strict file ownership. The foundation owned the schema, the key format, the request wrapper and the shared helpers. Nothing else could touch those files.
- Foundation. Migration for API keys, usage, webhooks, deliveries, alert rules and firings; the key generator and verifier; the
apiRoutewrapper that does auth, scope, IP allowlist, plan check, rate limit, quota, validation, idempotency, usage counting, audit logging and error mapping; cursor pagination; the SSRF guard. - Read API. Every read endpoint, with queries that select only the fields they return and stay fast on a 4,000-keyword project.
- Write API. Keywords, runs, share links, and an extracted
requestManualRunshared by the UI action and the API so the run limit and credit check cannot diverge. - Keys UI. Key list, create, rotate with a grace period, revoke, and the usage page.
- Webhooks. Signing, delivery, retries, auto-disable, delivery log.
- Alerts. Rule evaluation with a cooldown, email, Slack and webhook channels.
- Docs and SDK.
openapi.yaml, a contract-test helper, the SDK, the docs pages and a Postman collection. - MCP. A stdio package that talks to the REST API, plus a hosted endpoint with OAuth.
- Connectors and marketing. Google Sheets, Looker Studio, Zapier, n8n, and the API and integrations pages.
The merge order matters as much as the build order. The foundation merged first because every endpoint depends on the wrapper. Read API merged before write API, and MCP merged after the SDK so it could be reviewed against the same contract.
The contract decisions every client inherits
An API convention is a decision a client cannot undo. These are the ones that shaped all four surfaces.
| Decision | What it means for a client |
|---|---|
snake_case JSON and ISO-8601 timestamps |
No casing mapper in the SDK; dates are unambiguous |
| Cursor pagination, default 50, max 500 | next_cursor is null on the last page; no page numbers to drift |
rank: null means checked but outside the top 100 |
Never 0, so a client cannot plot an unranked keyword at the top |
Error envelope { error: { code, message, request_id } } |
One parser for every failure; the request ID is quotable in support |
Idempotency-Key on POST, 24-hour replay, 409 on mismatch |
A retry is safe; a changed body with the same key is a bug you can see |
402 insufficient_credits and 429 rate_limited with Retry-After |
The client can distinguish “buy more” from “slow down” |
ts_test_ keys |
Full validation and realistic responses, no writes, no credits |
| No CORS headers | The API is server-to-server; a browser cannot hold the key |
The null rank decision is the one that causes the most argument and saves the most bugs. A zero is a valid rank to a charting library, so an unranked keyword becomes the best-performing one. Making absence explicit forces every client to handle it.
The test-key mode is the other decision that pays for itself. ts_test_ keys read a synthetic demo project, never call the search data provider and never touch credits. Write calls validate and return a realistic response without saving. That gives the docs a live example, the SDK a safe integration test, and a prospective customer a way to try the API before spending anything.
Generating the SDK from the spec
The SDK is generated, not hand-written. The generated types come from the OpenAPI document, and the client wrapper adds the behaviour that a generated client never has: auto-pagination, retries that honour Retry-After, idempotency keys and webhook verification.
const client = new SerpClient({ apiKey: process.env.SERP_API_KEY });
for await (const keyword of client.keywords.list(projectId)) {
if (keyword.rank === null) continue;
}
const run = await client.runs.trigger(projectId, {
keyword_ids: ids,
fresh: true,
dry_run: true,
});
Auto-pagination is the highest-value wrapper. A generated client returns next_cursor; a person writing a script forgets to follow it and silently analyses the first page. An async iterator makes the correct behaviour the easy one.
Retries are the second. A retry that ignores Retry-After turns a rate limit into a retry storm. The SDK waits for the header, and it only retries idempotent requests or requests that carry an idempotency key.
Webhook verification belongs in the SDK for the same reason. Every receiver needs to compute an HMAC over timestamp.body and compare it, and every receiver gets it slightly wrong. Shipping verifyWebhook with the client means the sample in the docs and the code in production are the same code.
The MCP server is a thin client
The MCP server does not query the database. It calls the REST API with an API key and maps tools onto endpoints. That constraint keeps the tool behaviour identical to the API’s: the same scopes, the same rate limits, the same quota, the same credit holds, the same audit rows.
| Surface | Who uses it | Auth | Shape |
|---|---|---|---|
| REST API | Backend services and scripts | API key | Resources and verbs |
| TypeScript SDK | Application code | API key | Typed methods and iterators |
| MCP server | AI assistants and agents | API key or OAuth 2.1 | Tools with JSON Schema |
| Webhooks | Receivers reacting to events | HMAC signature | Signed event envelopes |
Which should you choose? Use the REST API when you are integrating a system and want explicit control. Use the SDK when you are writing TypeScript and want types, pagination and retries handled. Use MCP when the caller is a model that needs to choose an operation from a list. Use webhooks when you need to react to a change rather than ask for it.
The MCP tools are deliberately compact. A tool that returns 4,000 ranking rows is useless to an assistant and expensive in tokens. get_ranking_movement returns the biggest gains and losses for a date range; get_keyword_history returns a series, not the whole table. The two write tools in the first MCP release both return the credit cost and dry-run unless called with confirm: true.
That dry-run rule is the same one described in designing MCP tools that models call correctly, applied to an API that already had a credit system. The tool does not estimate; it calls the same cost calculation the endpoint uses.
Webhooks belong in the contract
A webhook is part of the API, not an afterthought bolted onto the dashboard. The signing scheme, the retry schedule and the delivery log are promises a receiver builds against.
Deliveries carry a timestamp and an HMAC-SHA256 over timestamp.body, so a receiver can reject a replay by refusing anything older than five minutes. RFC 2104 defines the HMAC construction; the important part here is signing the timestamp with the body, not the body alone.
Retries run at 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 24 hours, for eight attempts in total. After 20 consecutive failures the endpoint is disabled and the account owner is emailed. The delivery log keeps 30 days of event, status, duration and attempt count, with response bodies truncated to 1 KB.
Registration and every delivery resolve the host and refuse private, loopback, link-local and metadata addresses, and redirects are not followed. A webhook URL is a server-side request that the customer controls, which makes it an SSRF surface by definition.
What isn’t published, and what broke
The honest status matters more than the feature list. The SDK and MCP packages are built and tested, but they are not on npm; they returned 404 on 2026-11-10. The marketplace connectors are built but wait on third-party accounts and review. The docs say what exists, and the packages are listed as built rather than published.
Three failures shaped the release:
- The MCP server reported a hard-coded version. Clients could not tell which build they had, and a bug report could not be tied to a release. It now reports
MCP_SERVER_VERSIONfrom the package. - Integration pages had broken and non-authoritative links. A source-verification pass over 53 guide and integration pages replaced every 404, redirecting or non-authoritative URL with an official primary source and updated the checked dates. Documentation drift is a product bug when the docs are the integration.
- The contract test made drift a merge failure. The helper validates a real response against the spec, and it runs against the read, write and webhook workstreams at merge. A shape mismatch fails the merge instead of reaching a client.
The remaining gap is publishing. The packages are versioned and changelogged, but the step that puts them on npm needs owner credentials and a final verification pass. Until that happens, the SDK is a repository artifact, not a product. Saying so is better than a docs page that tells a customer to run an install command that fails.
Related
Frequently asked questions
Should I build the SDK or the MCP server first?
Build the SDK first, and build both from the API contract. The SDK proves the API is usable by a typed client, and the MCP server can then reuse the generated types and the same endpoints. Building MCP first tends to produce a second API shaped around tool calls.
Do I need a separate API for MCP?
No. An MCP server should be a client of the public API, not a parallel implementation. That keeps scopes, rate limits, quotas, credit holds and audit logging identical, and it means a bug fixed in the API is fixed for the assistant too.
How do you keep the SDK and API from drifting?
Generate the SDK types from the OpenAPI document and run a contract test that validates real responses against the same document at merge time. Drift becomes a failing test rather than a support ticket. The spec is the source of truth, not a description written after the fact.
What should a webhook signature cover?
The timestamp and the raw body, signed together with HMAC-SHA256. Covering the timestamp lets the receiver reject old deliveries; covering the body prevents tampering. Publish the exact header format and a verification helper so receivers do not invent their own.
Should an MCP tool return the same payload as the API?
Usually not. A model needs the answer, not the table. Return a compact summary with the identifiers needed for a follow-up call, and let the API return the full rows. The tool's output schema is part of its contract, so keep it stable.
How do you test an API before the SDK is published?
Use test-mode keys against the live API. They validate every request and return realistic data without writing or spending credits. The SDK's own tests run against a mock server, and the contract test runs against the real endpoints in staging.
