MCP server design: tools, authentication, and rate limits

By

Updated

Tagged: AI

How to design a useful MCP interface for your product, with clear tools, account permissions, usage limits, predictable results, and safe writes.

Giving an AI agent access to your product looks simple at first. You wire up a few API endpoints through MCP and add a connection button so users can talk to your app from their assistant.

Once you start building it, though, you run straight into product decisions. What should an assistant be allowed to do without the user opening your dashboard? Which account pays when a tool triggers real usage? What happens if a request times out halfway through, or if the assistant runs while the user stepped away?

The best way to think about an MCP server is as another front end for your product. People will use it to get real work done, so it needs clear feedback and predictable limits, just like your web UI.

I ran into most of these questions while building the Registrar MCP server in my Cloudflare Domains Toolkit. It lets an assistant search for domain names, pull a real Cloudflare price quote, and buy a domain once I approve the exact charge. I used it to register hostingpicker.dev for $12.20. I’ll bring up examples from it throughout this post where a real bug or constraint forced a specific design.

Start with a job someone wants done

To make this concrete, take a SaaS app that generates social preview images.

In the browser, you pick a template, type in a title, tweak the layout, and download the image. An AI agent preparing a site launch wants something much more direct. It already knows the page title and where the image needs to go, so it wants to generate a preview image using the account’s usual template and get the image URL back.

Compare that with exposing your whole database through a generic query tool. The agent gets lots of flexibility, sure, but now it has to reconstruct your product’s rules on every single call. And the more raw access you give it, the harder those rules are to enforce.

Start small. For an image generator, listing templates and generating previews is plenty for a first version. Leave billing settings and account deletion in the web dashboard until you have a real reason to expose them.

If you’re new to MCP, read my introduction to the Model Context Protocol first. It explains how the assistant, the client, and your server connect to each other.

Design tools around completed actions

Name your tools after the concrete job they finish. generate_preview tells the model right away what it does, while something vague like execute_action taking a big string forces the model to guess.

Have generate_preview accept a template ID, a title, and an optional subtitle, then return the asset ID, the image URL, and the generation status. Pull the account from the authenticated connection, never from the tool arguments. Passing an account ID in the arguments never proves the caller owns that account.

Write tool descriptions like you’re warning a coworker before they run a script against production. Spell out which fields are required, whether calling the tool spends credits, and whether it saves a permanent asset. Otherwise the assistant will learn those details by making expensive mistakes.

In my Registrar server, I split the workflow into four narrow tools:

  • search for domain ideas
  • check one exact domain
  • create a short-lived price quote
  • purchase one quoted domain after approval

I kept DNS out of it completely. DNS lives in a separate cf-domains CLI with its own API token, so the Registrar token can’t edit DNS and the DNS token can’t buy domains. Notice how the input rules tighten as the stakes go up, too. Search accepts loose queries because you’re just exploring, while quote and purchase only accept one exact domain like hostingpicker.dev.

You can define these input schemas, structured results, and behavioral annotations using the MCP tools specification. Just remember that annotations are hints for the client. Flagging a tool as read-only won’t stop a bug in your handler from writing to the database, so your code still has to enforce that boundary itself.

Reuse the product’s business rules

Your website and your MCP server should call the exact same backend operation.

Fig 1 · 1/4One set of product rules
Website request

In our preview image app, that single operation checks the subscription, verifies access to the template, enforces the title length limit, and reserves the needed credits before creating the generation job.

Don’t copy that logic into a second implementation for MCP. Two copies of the same rules will drift apart over time, and before long the website will reject something the agent interface allows, or the two paths will charge differently.

Put all those rules behind one shared service function. Let the web route deal with HTTP and let the MCP handler translate tool arguments and results, while both call the same function underneath. That also makes testing cleaner: one test for credit reservation protects both interfaces, and your transport tests can focus on turning bad arguments or expired auth into clear errors.

Authentication identifies the connection

If you host a remote MCP server, users need a straightforward way to link their own accounts and revoke access later.

For HTTP transports, the MCP authorization specification lays out an OAuth flow. Local servers talking over standard input and output work differently, so don’t force remote HTTP assumptions onto every setup. My Registrar server runs over stdio and uses its own narrowly scoped Cloudflare token.

When someone connects a remote server, make it obvious which account they’re authorizing. Show the account during setup, list the connection in your app’s settings, and let users revoke it there instead of digging through their AI client’s configuration.

Authentication only gets the request through the door. Inside each operation, check authorization again. A valid token doesn’t mean the caller can access every workspace or every paid feature, and a collaborator who can view an image library shouldn’t automatically be able to spend the team’s credits.

Avoid sharing one organization-wide credential across the whole team. When everyone uses the same key, revoking it is a headache and role boundaries disappear. Per-user access keeps roles intact and shows you who requested each change.

Put cost limits where the work happens

Even completely valid requests can turn expensive fast. An agent might retry a failing call, loop over a huge input, or misunderstand how many variants the user wanted. None of that takes a malicious user.

Put limits right where the work happens. For the image service, cap the maximum outputs per request, limit concurrent jobs, and apply one account usage budget across both the website and the agent interface.

Don’t rely on rate limiting alone, because each limit guards against a different failure:

  • Rate limits control how fast requests arrive, though one giant batch can still blow past them.
  • Concurrency limits protect your generation workers from getting flooded.
  • Credit budgets put a hard ceiling on spending.

In the Registrar server, I built in a hard $20 limit on the complete initial charge. Some domain extensions require more than one year, so the server adds the renewal price for the remaining required years before checking the cap. A domain advertised under $20 can still get rejected once those extra years are added in. Everything runs in integer cents, and the server rejects premium domains and non-USD prices.

When a client hits a limit, return an error the assistant can act on. Say whether it can retry later, reduce the batch size, or ask the user to raise the account’s allowance. A vague failure just encourages the model to try the exact same call again.

Reserve credits before starting expensive work

Picture an account with one credit left. The user requests an image from the website at the exact moment their assistant requests another through MCP.

Even inside a shared function, you still have a race condition if reading the balance and reserving the credit happen separately. Both requests see one credit available and both proceed.

Lock the account row while you check the balance, then reserve the credit and create the operation in the same transaction. That forces the second request to wait until the first transaction finishes before checking what’s left. PostgreSQL’s row-locking documentation shows one way to coordinate writes to the same account row. Your database might handle locking differently, but concurrent requests still share the same remaining allowance.

I hit a version of this in the Registrar server. My first version marked a quote as used after waiting for approval, so two purchase calls arriving close together could both reach the approval step and show two forms for one quote. Now the quote is consumed before the async approval starts. I also added a test that opens one approval, starts a second purchase with the same quote, and checks that the second call fails right away.

Once a credit is reserved, track it cleanly until the job finishes. Keep the credit reserved while the job runs, consume it when generation succeeds, and release it after a confirmed failure if that matches your refund policy. Show pending usage separately from completed charges so users can see what’s still in flight.

Hold the reservation until the generator confirms the outcome. A timeout can happen while the work is still running in the background, and returning the credit right away could let another request spend it while the first image finishes.

Watch out for the gap between saving a job and sending it to your queue, too. If the process crashes right there, the database holds a reservation for work no worker ever received. Keep enough durable job state so a background check can spot and resubmit orphaned operations, and make sure your worker recognizes an operation it has already seen so resubmitting doesn’t run it twice.

Retries need a product decision

Suppose your server creates an image, charges a credit, and sends the response, and the network drops before the client gets it. Agents are quick to retry when a call fails. If retrying creates another image and charges another credit, the user pays twice because of a connection hiccup.

For billable writes, support a client-provided request ID with idempotency semantics. Record the operation against that ID so repeating the same intended request returns the existing operation instead of creating a new one.

Be strict about how those IDs work:

  • Scope each ID to one account and one specific request.
  • Return a conflict if the caller reuses the same ID with different arguments.
  • Document how long you retain them.
  • Back them with storage that handles concurrent requests across instances, rather than an in-memory map inside one server process.

When the upstream API has no safe idempotency mechanism, don’t retry at all. My Registrar server never retries a domain registration. If the connection drops after the request reaches Cloudflare, it can’t tell whether the domain was bought, so the quote stays marked as used and I check my Cloudflare account before trying again.

For long-running work, give the agent a way to check status instead of hanging on one request. Return a job ID as soon as the job exists so the client can inspect it after a timeout. That’s what MCP Tasks give you.

Approval should describe the exact effect

Generating a private draft image is very different from publishing it to a live site. Keep those two actions separate. Let the agent create the draft and show it to the user, and make publishing its own step with a clear destination.

Whenever an action costs money or can’t be undone, the confirmation prompt needs to spell out what’s about to happen before anyone clicks confirm. Show the exact price, which account gets billed, and which resource is affected. Telling an assistant to help with a project isn’t the same as approving one specific, irreversible purchase.

The Registrar server enforces this before every domain purchase. First it checks that the caller passed back the exact quote ID, domain name, currency, and total in cents. Then it asks Cloudflare for availability and pricing one more time, stopping if anything changed. Only after that does it show an MCP elicitation form with the domain, the exact USD total, the registration term, a non-refundable warning, and a confirmation checkbox that defaults to false. If the client doesn’t support elicitation, the server blocks the purchase outright with no terminal fallback.

Don’t rely on tool descriptions to enforce approval. Putting a confirmation reminder in a tool description is only guidance. Sensitive actions need a hard boundary in your server code that the model can’t talk its way past. Here’s how that check looks in code:

Prepare and publish are separate operationsGenerating a private preview produces an asset for review. Publishing it requires a separate approved operation with a clear destination.YesNoGenerate privatepreviewReturn asset and URLShow exactpublishingdestinationPerson approves?Run publishingoperationKeep private draft

Tool results can contain hostile text

Suppose your image service later adds a feature that takes a URL and pulls the page title. You don’t control that page, so its text could contain instructions aimed right at the assistant. A template description written by another user carries the same risk.

Only send back what the task needs. If you’re fetching a title, return the title and leave out the full HTML, embedded scripts, and extra metadata. Sending less text gives hostile instructions less room to hide and keeps the model from getting confused.

If your server fetches user-supplied URLs, lock down outbound network access too. Validate both destinations and redirects, or an arbitrary URL field can turn into a way to reach your internal services.

The MCP security guidance covers these trust boundaries in detail, including token handling and server-side request forgery. Passing a token through to an unrelated upstream service is especially risky because it blurs who the token was issued for. Put these protections in your server code, no matter what the assistant’s instructions say.

Make the integration easy to operate

When someone reports a failed generation, you need a way to track it down fast.

Log who made the request, what action they ran, which resource it touched, and whether it succeeded or failed. Return an operation ID to the client so users can include it in a support message. Just don’t log access tokens or dump sensitive user input into every diagnostic message.

Track completed jobs and rejected requests separately. A raw connection count doesn’t tell you whether people can finish their work.

Be careful when changing existing tools, too. People save prompts and workflows around your tool inputs, so renaming a parameter or changing its meaning will break them. Keep old behavior working and add new capabilities explicitly.

Start with a narrow first release. Connect one client, generate one asset, trigger a failed request, revoke the connection, and check that the next call fails the way it should. Then test duplicate requests and exhausted credits. With the Registrar server, I kept all live testing read-only until the local policy tests passed, and ran the one real purchase last.

Once it’s live, watch which tasks still send users back to the website to finish. Those gaps will tell you which tool to add next.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: