← All articles

AI Development · · by

How to Build a Production MCP Server: Architecture, Tools and OAuth 2.1

A production MCP server is a thin bridge over your API: semantic tools, OAuth 2.1, audience-bound tokens, no token passthrough. Each layer from a real build.

Key takeaways

  • An MCP server lets AI clients such as Claude and Cursor use your product through tools. In production it should be a thin bridge over your existing API, not a second backend with its own database access.
  • Design semantic tools for the jobs an agent actually does, with strict input schemas and trimmed output. Do not mirror every endpoint.
  • Return failures as tool results with isError, so the model can read a 403 or a timeout and react, instead of the session breaking.
  • A remote MCP server is an OAuth 2.1 resource server. It must publish Protected Resource Metadata (RFC 9728) and accept only tokens issued for its own audience.
  • Never pass the client's token through to your API. Mint a separate short-lived token for each user and keep authentication and tenant isolation in one place.

The short answer: a production MCP server is a small, stateless service that sits between AI clients and your existing API. It exposes a handful of purpose-built tools, authenticates every user through OAuth 2.1, and calls your API on that user's behalf with a token of its own. It never touches your database, so your permission and tenant checks keep working exactly as they do for the web app.

I worked on the MCP server for JARVIS RCSA, an enterprise AI platform used by risk and compliance teams at banks. The server lets Claude, Cursor and other MCP clients work the platform's project board: pull the task queue, read a task, post a QA verdict, create and move work. This guide walks through every layer of that build, the decisions behind each one, and the mistakes it avoids. I checked the protocol details against the official MCP specification (revision 2026-07-28) and the OAuth RFCs listed at the end.

What is an MCP server?

The Model Context Protocol is an open standard, introduced by Anthropic in November 2024, for connecting AI applications to outside systems. An MCP client, such as Claude Desktop, claude.ai or Cursor, connects to an MCP server and discovers what it offers. The most common offering is tools: named actions with a description and an input schema that the model can decide to call. Messages are JSON-RPC 2.0.

For a business, that means one integration works across every MCP-capable AI client. You build the server once, and your customers or your own team can use your product from whichever assistant they already work in.

The architecture: a thin bridge, not a second backend

The most important decision comes before any code. The MCP server should call your existing REST API, not your database. If it talks to the database directly, you have built a second access path with its own authentication, its own permission checks and its own tenant isolation, and every one of them has to be kept in step with the main app forever. As a thin bridge, it adds no security rules of its own, and it cannot drift.

These are the layers, from the AI client down to your product:

LayerWhat it doesIn JARVIS
TransportCarries JSON-RPC messages between client and serverstdio for local use, Streamable HTTP for the hosted server
Auth gateRejects requests without a valid token, and points the client to the authorization serverOAuth 2.1 bearer check with RFC 9728 metadata
Tool layerDefines the tools, validates input, shapes output19 tools with Zod schemas
API clientCalls your REST API with a per-user token, timeouts and error shapingShort-lived on-behalf-of token, 20-second timeout
Your existing APIDoes all permission and tenant checks, as it already does for the web appUnchanged

Keep the core transport-independent. In JARVIS, one function builds the server and registers the tools, and two small entry points attach a transport: one for stdio, one for HTTP. The tool code is identical in both, so a fix lands everywhere at once.

Layer 1: choose the transport

The MCP transports spec defines two standard transports. Most teams need both, at different stages.

stdioStreamable HTTP
How it runsThe client starts the server as a child process on the user's machineA hosted service that clients connect to over HTTPS
AuthenticationOne token in an environment variableOAuth 2.1, each user signs in as themselves
Good forOne developer, prototypes, internal testingTeams, customers, claude.ai and other hosted clients
Main riskA long-lived token sitting in a config fileGetting the OAuth layer wrong

We started JARVIS on stdio with a single operator token, which made it quick to prove the tools were useful. The hosted HTTP version came next, so that every teammate could click Connect and sign in under their own account, with no tokens or config files to hand around. Build the stateless version if you can: with no session store, the server scales by adding replicas.

Layer 2: design semantic tools, not an API mirror

Tool design decides whether the model uses your server well. Exposing every REST endpoint as a tool gives the model dozens of near-duplicates and raw database rows to wade through. Design tools around the jobs an agent actually does instead. These are the rules we followed:

  • One tool per real job: list_tasks, get_task, add_comment, set_status, not one tool per endpoint
  • Strict input schemas with Zod, including enums for types, priorities and statuses, so bad input fails before it reaches the API
  • Descriptions that teach: when to use the tool, which role it needs, and what to use instead, such as "prefer set_status to close work, delete is permanent"
  • Trimmed, model-friendly output: a one-line summary plus compact JSON, never raw rows
  • Sensible pagination: a default page of 50, a hard cap, and the total, so the model knows when there is more
  • Behaviour hints from the SDK, such as readOnlyHint and destructiveHint, so clients can ask before running a destructive tool

What you leave out matters as much. In JARVIS, comments are create-only, with no edit or delete tool, so an assignee can never find that a comment they were working from has been silently changed. Deleting a whole board section and every project-level operation stay in the web app. An agent that can do anything is an agent you have to watch all the time.

Layer 3: return errors as tool results

The MCP tools spec separates two kinds of error. Protocol errors, such as an unknown tool, are JSON-RPC errors. Tool execution errors are returned inside the tool result with isError set to true. That second kind is the one to get right, because the model can read it.

Every JARVIS tool runs inside a small wrapper that catches API failures and turns them into plain sentences. A 403 becomes "Not allowed: this needs editor or admin on the project." A 404 becomes "Not found." A timeout becomes "Cannot reach Jarvis." The model reads that, explains it to the user or tries another way, and the process never crashes on an expected failure.

Layer 4: OAuth 2.1 for a remote MCP server

Under the MCP authorization spec, a protected MCP server acts as an OAuth 2.1 resource server. Your product, or your identity provider, is the authorization server. Keeping the two roles apart is what keeps the design simple. In JARVIS, the main backend issues tokens, the existing React app shows the login and consent screen, and the MCP server only checks tokens. A connection runs like this:

  1. The client calls the MCP endpoint without a token and gets HTTP 401 with a WWW-Authenticate header pointing to the server's Protected Resource Metadata.
  2. It reads that metadata (RFC 9728), which names the resource, the authorization server and the supported scopes.
  3. It reads the authorization server's own metadata to find the authorize, token and registration endpoints.
  4. It identifies itself. The spec recommends Client ID Metadata Documents, where the client_id is an HTTPS URL that hosts the client's details, which is what claude.ai uses. Dynamic Client Registration (RFC 7591) is still allowed but now deprecated, so JARVIS supports both and caches a fetched document as a client record.
  5. It sends the user to the authorize endpoint with a PKCE code challenge (RFC 7636) and a resource parameter (RFC 8707) naming the MCP server. JARVIS refuses any request without an S256 challenge.
  6. The user logs in and approves access on your own consent screen. The redirect URI must exactly match a registered one, with the loopback port exception from RFC 8252 for desktop clients.
  7. The client swaps a single-use code, valid for 60 seconds, for an access token bound to the MCP server's audience, valid for one hour, plus a refresh token.

Refresh tokens are where many implementations get lazy. In JARVIS they rotate on every use, so a stolen one stops working the next time the real client refreshes. They are stored only as SHA-256 hashes, last up to 90 days, and a refresh can narrow the scope but never widen it.

Layer 5: no token passthrough

This is the mistake I see most. The access token the client holds was issued for the MCP server, so the MCP server must not forward it to your API. The MCP security best practices forbid token passthrough outright, because it lets a token meant for one service be replayed against another and blurs who actually made the call. That is the confused deputy problem.

In JARVIS, the bridge mints a separate token for each request: about two minutes long, carrying only the user, tenant and role, and marked as coming from MCP so every call stays traceable. The API accepts it like any other session token and runs its normal permission and tenant checks. The client's token never leaves the bridge.

Layer 6: verify every token like you mean it

Verification happens locally on every request, with no call back to the authorization server, which is the point of a signed token. The checklist:

  • Pin the algorithm. Reject any token whose header names a different one, so an attacker cannot switch it.
  • Compare signatures in constant time. A plain equality check leaks how many bytes matched.
  • Check expiry, issuer and audience. The audience must be this server's exact URL. The spec requires this.
  • Check the token's purpose. JARVIS only accepts tokens marked for MCP use, so a normal web session token cannot be used here.
  • Check scope. Reading needs mcp:read, and the API still decides what each role may write.
  • Keep a kill switch. A session generation value in the token must match the server's. Bumping it signs out every MCP session at once after an incident.

A note on keys: JARVIS uses one shared HMAC secret, because the backend and the bridge are one trust domain run by the same team. If the authorization server belongs to someone else, use asymmetric keys and a published key set instead.

Layer 7: deploy it as its own service

  • Run the MCP server as a separate service with its own health check, so a bad deploy cannot take the main app down with it.
  • Fail at startup when configuration is wrong. A deployed process that would advertise a localhost issuer exits instead of serving broken metadata.
  • Use the same canonical resource URL on both sides, with no trailing slash. It is the token's audience, and a one-character difference fails every request.
  • Test the whole OAuth flow, not just the tools: metadata endpoints, the 401 challenge, PKCE, code reuse, refresh rotation and scope narrowing.
  • Probe production after each deploy: the metadata documents, the health check, and an unauthenticated call that must return 401.

Common mistakes in MCP servers

  • Talking to the database directly, so the MCP server has its own permission logic that slowly drifts from the app's
  • Forwarding the client's token to the API instead of minting a new one
  • Not checking the token audience, so a token for another service is accepted
  • One tool per endpoint, with raw database rows as output
  • Throwing errors instead of returning isError results the model can read
  • Destructive tools with no hints and no safer alternative
  • Long-lived tokens in config files, shared by the whole team

Do you need an MCP server?

You probably do if your customers already work inside AI assistants and your product holds data or actions they would want there: tickets, projects, CRM records, documents, reports. You probably do not if a simple webhook or a public API with good docs already covers the need. An MCP server earns its place when an agent needs to read context and take actions in the same conversation.

If you are planning one, I build MCP servers and AI integrations for SaaS products, including the OAuth layer that most of the work hides in. See the JARVIS RCSA case study, then tell me what you are building. I usually reply within a day.

Frequently asked questions

What is an MCP server?

An MCP server exposes tools, data and prompts to AI clients through the Model Context Protocol, an open standard introduced by Anthropic in November 2024. Clients such as Claude and Cursor connect to it and can call its tools during a conversation.

Should an MCP server access the database directly?

Usually not. Calling your existing API keeps authentication, permissions and tenant isolation in one place. A server with its own database access is a second security perimeter that has to be kept in step with the app forever.

Which transport should I use for an MCP server?

Use stdio for local, single-user setups and prototypes. Use Streamable HTTP for a hosted server that a team, customers or claude.ai connect to, with OAuth so each user signs in as themselves.

How does authentication work for a remote MCP server?

The MCP server is an OAuth 2.1 resource server. It publishes Protected Resource Metadata (RFC 9728), and clients sign users in through the authorization server with PKCE and a resource indicator. The server must accept only access tokens issued for its own audience.

What is token passthrough, and why is it forbidden?

Token passthrough means forwarding the client's access token to another API. The MCP security best practices forbid it because it breaks audience checks and creates a confused deputy problem. The server should use its own short-lived token for downstream calls.

Do I still need Dynamic Client Registration?

It is optional and now deprecated in the MCP spec. Clients should support Client ID Metadata Documents, where the client_id is an HTTPS URL, which is what claude.ai uses. Supporting both is the safest choice while older clients are still around.

How many tools should an MCP server have?

As few as cover the real jobs. Design tools around tasks an agent does, with clear descriptions and strict schemas, rather than mirroring every API endpoint. JARVIS uses 19 tools for its full project board.

Sources

About the author

Gaurav Singh Karki

Full-stack and AI developer based in India, working with clients in Europe, the US and Hong Kong. Top Rated Plus on Upwork with 30+ products in production.

Building something like this?

I take on freelance projects worldwide — usually replying within a day.

Get in touch