Guide

How to build an MCP server with OAuth 2.1

We run two remote MCP servers in production. One lets Claude operate our sales CRM, the other lets online sellers hand their Salestreak workspace to an AI agent. Both come with their own OAuth 2.1 authorization server, built in Rails. This guide covers what we built, why we built it that way, and what we'd tell anyone building their own.

Martin Balk Founder of Balk.dev Updated 9 min read
On this page
  1. What an MCP server actually is
  2. How authorization works in MCP
  3. The two discovery documents
  4. Dynamic registration and PKCE
  5. Tokens: audience, lifetime and storage
  6. Consent screens decide who may connect
  7. Design tools around tasks, not endpoints
  8. Guardrails belong on the server
  9. Standing instructions and testing with Claude

What an MCP server actually is

The Model Context Protocol (MCP) is an open standard that lets AI assistants such as Claude and ChatGPT call tools in other software. An MCP server describes its tools (a name, a description and a JSON Schema for the input), the assistant decides when to call them, and the server runs each call inside whatever rules you put around it. The full protocol is in the specification.

A local MCP server runs on the user's machine and talks over stdio. A remote server is a web endpoint that many people connect to, and that's where authorization comes in. Both of ours are remote: one for our own sales CRM and POST /mcp/shop for Salestreak workspaces.

Under the hood it's JSON-RPC 2.0. In protocol version 2025-06-18 a session starts with initialize, the client lists tools with tools/list and calls them with tools/call. Our servers reply with plain JSON instead of an SSE stream, which the streamable HTTP transport allows, so a tool call is one POST and one response:

POST /mcp/shop HTTP/1.1
Host: app.example.com
Authorization: Bearer <access token>
Content-Type: application/json

{"jsonrpc": "2.0", "id": 7, "method": "tools/call",
 "params": {"name": "adjust_stock",
            "arguments": {"variant_id": "MUG-0141", "delta": 12, "reason": "received"}}}
{
  "jsonrpc": "2.0",
  "id": 7,
  "result": {
    "content": [{ "type": "text", "text": "{\"sku\": \"MUG-0141\", \"on_hand\": 53, \"previous\": 41}" }],
    "isError": false
  }
}

How authorization works in MCP

MCP doesn't invent its own auth. The authorization spec builds on OAuth 2.1 and a handful of RFCs, and the whole flow is discoverable: the user pastes one URL into their assistant and the client works out the rest.

  1. 1

    The client calls the server without a token

    The server answers 401 Unauthorized with a WWW-Authenticate header that points to its protected resource metadata (RFC 9728).

  2. 2

    The client reads the protected resource metadata

    That document names the resource and the authorization server that issues tokens for it.

  3. 3

    The client reads the authorization server metadata

    From /.well-known/oauth-authorization-server (RFC 8414) it learns the authorize, token and registration endpoints, and that S256 PKCE is required.

  4. 4

    The client registers itself

    With dynamic client registration (RFC 7591) it gets a client_id without anyone filling in a form.

  5. 5

    The user approves on a consent screen

    The client opens the authorize URL with a PKCE challenge and a resource parameter naming the MCP server (RFC 8707). The user signs in and approves.

  6. 6

    The client swaps the code for tokens

    It sends the code and the PKCE verifier to the token endpoint and gets an access token and a refresh token. The access token goes along as a bearer header on every MCP request.

# Every unauthenticated request gets a pointer to the discovery document (RFC 9728).
def unauthorized_with_discovery_hint
  response.set_header(
    "WWW-Authenticate",
    %(Bearer resource_metadata="#{request.base_url}/.well-known/oauth-protected-resource/mcp/#{audience}")
  )
  head :unauthorized
end

The two discovery documents

Both documents are small JSON responses. We build them per request from the host, so staging and production never point at each other.

# GET /.well-known/oauth-authorization-server  (RFC 8414)
def authorization_server_metadata
  render json: {
    issuer: request.base_url,
    authorization_endpoint: "#{request.base_url}/oauth/authorize",
    token_endpoint: "#{request.base_url}/oauth/token",
    registration_endpoint: "#{request.base_url}/oauth/register",
    response_types_supported: ["code"],
    grant_types_supported: %w[authorization_code refresh_token],
    code_challenge_methods_supported: ["S256"],
    token_endpoint_auth_methods_supported: ["none"]
  }
end

# GET /.well-known/oauth-protected-resource/mcp/shop  (RFC 9728)
def protected_resource_metadata
  render json: {
    resource: "#{request.base_url}/mcp/shop",
    authorization_servers: [request.base_url],
    bearer_methods_supported: ["header"]
  }
end

The value none for token_endpoint_auth_methods_supported means public clients: there is no client secret, so PKCE does the job a secret would otherwise do. That's the right setup when every assistant registers itself. A client_id grants nothing on its own, because every authorization still goes through your consent screen.

If you run more than one connector on the same authorization server, give each one its own protected resource document. Salestreak serves one per connector, so a client asking about the shop endpoint is told it needs a shop token, not a sales token.

Dynamic registration and PKCE

Dynamic registration lets any compliant client register itself. We accept it with two checks: redirect URIs must be absolute https URLs (or http://localhost for development), and later only exactly registered URIs are accepted. A registered client has no privileges of its own. It can only start an authorization that a person then has to approve.

# Authorization codes are single use, expire after ten minutes and are
# stored only as a SHA-256 digest. Redemption checks the PKCE verifier.
def redeem!(code_verifier:, redirect_uri:)
  return false if redeemed_at.present? || expires_at.past?
  return false unless redirect_uri.to_s == self.redirect_uri
  return false unless pkce_valid?(code_verifier)

  update!(redeemed_at: Time.current)
  true
end

def pkce_valid?(verifier)
  return false if verifier.blank?

  expected = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)
  ActiveSupport::SecurityUtils.secure_compare(expected, code_challenge)
end

We only accept S256 as the challenge method, and every mismatch gets the same invalid_grant answer, so a failed exchange reveals nothing about why it failed.

Tokens: audience, lifetime and storage

The spec is explicit: an MCP server must only accept tokens that were issued for it, and must never pass a client's token on to another API. In practice that comes down to three rules.

  • One audience per token. The resource parameter decides which connector a token is for. Salestreak stores that audience on the grant and the token and checks it on every request, so a shop token never opens the sales endpoint.
  • One workspace and one user. For the shop connector the consent screen asks which workspace to connect. The token is bound to that workspace and to the person who approved it, and the agent acts with that person's role. When they leave the workspace, the agent loses its access with them.
  • Short-lived, hashed, rotated. Access tokens live 24 hours and refresh tokens 90 days. Raw tokens are returned once and we store only SHA-256 digests. Every refresh revokes the old pair and issues a new one, which the spec requires for public clients.
ACCESS_TTL  = 24.hours
REFRESH_TTL = 90.days

# Raw tokens are returned once; only SHA-256 digests are stored.
def self.authenticate(raw_access, audience:)
  return nil if raw_access.blank?

  token = find_by(access_token_digest: Digest::SHA256.hexdigest(raw_access))
  return nil if token.nil? || token.revoked_at.present? || token.expires_at.past?
  return nil if token.audience != audience # a shop token never opens the sales endpoint

  token
end

# Rotation: the old pair is revoked in the same transaction that issues the new one.
def self.refresh!(raw_refresh, client:)
  token = find_by(refresh_token_digest: Digest::SHA256.hexdigest(raw_refresh.to_s))
  return nil if token.nil? || token.oauth_client_id != client.id
  return nil if token.revoked_at.present? || token.refresh_expires_at.past?

  transaction do
    token.update!(revoked_at: Time.current)
    issue!(client: client, user: token.user, audience: token.audience, organization: token.organization)
  end
end

The consent screen is where your business rules about access live. Ours differ per connector:

  • Sales connector: only a signed-in admin can approve it, because it opens up the whole sales database. Anyone else gets a clear refusal.
  • Shop connector: any member of a workspace can approve it, but they pick one of their own workspaces and the token carries their role. Owners and admins can write; editors and viewers can only read.

Explain in plain language what the connector will be able to do, and give people a way to revoke it later. In Salestreak, connected agents are listed in the workspace settings, where the seller can disconnect them in one click.

Design tools around tasks, not endpoints

An assistant picks tools by reading their names and descriptions. Mirror your REST API one to one and it gets dozens of low-level calls and no idea how they fit together. We design tools around the jobs people actually hand over: adjust_stock with a reason and a note, generate_description for every language at once, verify_email before any effort goes into a contact.

  • Say what the tool is for and when to use it. A description like ‘use set for a count, delta for a change’ saves the model a guess.
  • Accept the identifiers people use. Our shop tools take a product id or slug, a variant id or SKU, an order id or order number.
  • Return errors the agent can act on. A refused call names the reason and the fix: which role is needed, which plan limit was hit, which field is missing.
  • Refuse work that's already running. Renders and marketplace publishes run as background jobs; the tools report their state and won't queue the same work twice.
{
  name: "adjust_stock",
  description: "Set or change the on-hand stock of a tracked variant at one location, " \
               "with a ledger entry. Use set for a count, delta for a change (+12 received, -1 damaged).",
  inputSchema: {
    type: "object",
    properties: {
      variant_id: { type: "string", description: "Variant id or SKU" },
      set:        { type: "integer", description: "New on-hand count" },
      delta:      { type: "integer", description: "Change to apply instead of set" },
      reason:     { type: "string", enum: MOVEMENT_REASONS }
    },
    required: ["variant_id"]
  }
}

def tool_adjust_stock(args)
  require_manage!("adjust stock")   # owners and admins only
  variant = find_variant(args)      # looked up inside the token's workspace
  raise ToolError, "pass set (a count) or delta (a change)" if args[:set].blank? && args[:delta].blank?
  # ... update the stock level and write a ledger entry in one transaction
end

It's the same thinking we apply when we add AI to an existing product: start from the work people do, not from the API you happen to have.

Guardrails belong on the server

Instructions in a prompt are a request. Checks on the server are a guarantee. We use both, but anything that matters is enforced in code.

  • Scope every query. Every shop tool looks records up through the token's workspace, so an id from another workspace simply reads as not found.
  • Respect plan limits. Tools check the same entitlements as the app: product allowance, image allowance, resolution. A refused call names the limit and where to upgrade.
  • Put a person in front of irreversible actions. On the sales connector, the tools that approve and queue emails only run when the person in the conversation explicitly asks, and the user behind the OAuth token is recorded as the reviewer.
  • Refuse input that breaks the rules. The server rejects drafts that break the house style or the follow-up limits, whatever the agent intended.
  • Log everything. Every approval is stored as an event, with who approved it and through which channel.
# @user is the person behind the OAuth token, recorded as the reviewer.
def approve_one(draft)
  if draft.company.suppressed_for_push?
    return { draft_id: draft.id, approved: false, reason: "company is suppressed" }
  end

  draft.approve!(@user)
  OutreachEvent.record!(draft: draft, event_type: "draft_approved",
                        payload: { "reviewed_by" => @user.email, "via" => "mcp" })
  { draft_id: draft.id, approved: true }
end

Standing instructions and testing with Claude

The initialize response can carry instructions: text the client loads as standing context for the whole session. We use it for the playbook: the order of work, what to verify first, house style, and what the agent must never do on its own. Salestreak's shop server teaches the route from creating a product to publishing it, plus rules like never inventing prices, stock or materials.

Then test with the real client. Add the server in Claude as a custom connector, run the consent flow on a staging host and give it real tasks. Watch which tool it picks, which arguments it guesses wrong and where it asks for something the server could have told it. Every surprise becomes a better description, a clearer error message or a new check on the server.

Keep automated tests for the boring parts: every tool descriptor has a handler and serializes to JSON, a token for one audience is refused on the other, and a member who leaves a workspace takes the agent's access with them.

Frequently asked questions

Do I need OAuth for an MCP server?

Only for remote servers that act on behalf of a user. The spec makes authorization optional, and local servers that run over stdio take their credentials from the environment instead. As soon as several people connect to a server over the internet, OAuth is how you know who is calling and what they may do.

Can I use my existing login system as the authorization server?

Yes. The authorization server can live inside your app, as ours do, or be a separate identity provider, as long as it publishes the metadata MCP clients look for and supports PKCE. The consent screen is the part you'll want to design yourself.

What is the resource parameter for?

It tells the authorization server which MCP server the token is for (RFC 8707). Store it on the token and check it on every request, so a token issued for one connector can't be used on another.

How long should MCP access tokens live?

Not long. The spec asks authorization servers to issue short-lived access tokens and to rotate refresh tokens for public clients. We use 24 hours for access tokens and 90 days for rotating refresh tokens, stored as hashes.

Can an AI agent send emails or spend money through MCP?

Technically yes, which is exactly why we don't let it decide alone. On our servers, tools that send or spend only run on an explicit human instruction, the server checks the rules, and we record who approved what. See how we build MCP servers for clients.

Want an MCP server for your product?

We've built two, with OAuth, scoped tools and human approval. Tell us what an agent should be able to do in your software and we'll tell you what it takes.

martin@balk.dev

Typically a reply within one business day.

Useful to mention

  • What you want to build, in a few sentences
  • Who is going to use it
  • Any deadline or launch date
  • Tools and systems it should connect to