Zero Labs
Industry News / AI

Building a Production-Grade MCP Server with JWT Auth and Role-Based Tool Access

Source · Towards AI By MD. SHARIF ALAM

From the publisher’s feed, collected in the ZeroLabs newsroom.

Figure: Production-Grade MCP Server with JWT Auth and Role-Based Tool AccessHow I designed a secure, multi-tenant Model Context Protocol server that gives every user role exactly the tools they need — nothing more, nothing lessMost MCP tutorials show you how to wire up a tool and call it from Claude. That is fine for a weekend experiment. But when you are building MCP into a real enterprise system, one with HR data, procurement approvals, financial records, and five distinct user roles — “wire up a tool” is nowhere near enough.This article documents the architecture I designed for exactly that situation. I will walk you through the full system: dual transport, auth context loading, role-derived toolpacks, a confirmation gate for risky writes, tenant scoping, audit logging, and rate limiting. By the end, you will have a blueprint you can take into any production MCP deployment.Everything here is generic and applicable to any stack. The patterns are what matter.Why is MCP security harder than REST security?With a REST API, the boundary is clear. A request hits your server, your JWT guard checks the token, your RBAC middleware checks the role, and the handler either runs or returns 403. The client never sees the endpoints it cannot call — it just gets rejected if it tries.MCP is different in a fundamental way: the client receives a list of tools at connection time. Claude (or any other AI client) can only reason about tools it knows exist. If you register delete_employee for every user and rely solely on the backend to reject unauthorised calls, you are leaking your data model to every session and trusting the LLM not to attempt operations it should never even know about.The better pattern is role-aware tool registration: derive the user’s role at connection time, then register only the tools that the role is permitted to see. An unauthenticated guest gets a login tool and public lookups. An approver gets request management tools. An admin gets everything. The AI model is contextually limited from the start.This is the core design insight around which the entire architecture is built.The six-layer architectureBefore diving into each component, here is the end-to-end picture:Figure: The six-layer architectureLayer 1: Dual transportThe MCP spec supports multiple transport mechanisms. In this architecture, I support two:Stdio is for local developer tooling and AI coding agents running on the same machine. The MCP Inspector, Claude Code, and similar tools connect this way. The JWT is injected via an environment variable (JWT_SECRET in .env) — the process inherits it at startup. This is important to document explicitly because it is the most common gap in stdio-based MCP setups: people assume auth just works and then discover their local agent is running as an unauthenticated guest.Streamable HTTP /mcp is for remote clients — web frontends, mobile apps, third-party integrations. The JWT arrives as a standard Authorization: Bearer header on each request.Both transports converge on the same mcp-server process. The transport layer is purely about the channel; everything above it is identical.Layer 2: Auth context loadingThe first thing mcp-server does when a session starts is call GET /auth/me with the Bearer token it received. This endpoint returns the full user context:Figure: Auth context loading{ "user_id": "usr_abc123", "name": "Sarah Chen", "email": "sarah@example.com", "roles": ["approver", "item_viewer"], "permissions": ["requests.read", "requests.approve", "items.read"], "tenant_id": "org_abc_group", "scopes": ["procurement", "finance_read"]}Notice tenant_id. In a multi-entity organisation, this is not optional. Every downstream operation — every tool call, every database query — must be scoped to this tenant. I will come back to this.If the token is missing or invalid, the backend returns 401. The server does not crash; it falls back to a guest toolpack containing only login and public lookup tools. The session is still usable — the AI can prompt the user to authenticate.If the token expires mid-session (JWT exp reached), the next tool call returns 401 from the backend. The server catches this, sends a re-authenticate MCP error to the client, and waits for a new JWT before reinitialising the session. This path is almost always missing from MCP implementations and causes silent failures in long-running agent sessions.Layer 3: Role derivation and toolpack assignmentWith the user profile in hand, the server derives the toolpack for this session. Here is the decision logic:Figure: Role derivation and toolpack assignmentA few things worth highlighting:Toolpacks are additive. An admin does not get a separate admin-only experience — they get everything an approver sees, plus additional capabilities. This keeps the UX coherent.The tenant scope step is non-negotiable in multi-entity systems. Before registering any tool, every tool’s data scope must be bound to tenant_id. An approver at one subsidiary must not be able to see another subsidiary's procurement requests, even if they somehow share the same role label. This is enforced at the tool level, not just at the backend query level.Role derivation uses keyword matching on normalised text, not exact enum matching. This makes it resilient to role label variations across different backend configurations ("APPROVER", "Approver", "procurement_approver" all match). You pay a small cost in explicitness; you gain robustness against real-world data inconsistency.Layer 4: The confirmation gate for risky writesRead operations are straightforward — validate the input, call the backend, return the result. Write operations that touch sensitive data need a second layer of protection.I classify the following as risky writes: update, delete, approve, reject, settings, RBAC changes. Any tool in these categories requires confirm: true in its input schema.The execution flow:Figure: The confirmation gate for risky writesThe 428 response is a signal to the AI model: “You need explicit confirmation from the user before proceeding.” A well-prompted agent will surface this to the user as a confirmation step rather than retrying blindly. This is the human-in-the-loop pattern at the tool layer — lightweight, effective, and requiring no special framework.The audit write happens after every tool outcome, success or failure. I will cover why this matters in layer 6.Layer 5: The state machineLooking at tool execution as a state machine makes the logic clearer and makes it easier to test:Figure: The state machineThe key design decision here is that AuditWritten is not optional. Every path — allowed, denied, blocked — flows through it before terminating. You cannot have a risky write that succeeds silently, and you cannot have a failed attempt that goes unrecorded.Layer 6: Audit logging and rate limitingThese two layers were the gaps I identified when reviewing a naive MCP implementation. They are also the ones most likely to get you in trouble if you are building for a regulated industry.Audit logging should be a write-only append store. The schema for each event is minimal:{ "event_id": "evt_xyz789", "timestamp": "2026-05-21T14:32:11Z", "tool": "approve__request", "user_id": "usr_abc123", "tenant_id": "org_abc_group", "input_summary": "request_id: req_456", "result": "success", "backend_status": 200}Do not log raw inputs for sensitive tools — summarise them. Do log enough to reconstruct what happened, who did it, and when. For procurement and HR data, this is not a nice-to-have; it is a compliance requirement in most jurisdictions.Rate limiting is per-tenant, not per-user. This is a deliberate choice. In a multi-tenant system, one tenant’s AI agent going rogue should not degrade the experience for other tenants. Per-tenant quotas give you blast radius control. I implement this as middleware on the mcp-server before the backend call, so the rate limiter takes the hit rather than propagating unnecessary load to the backend.Local development topologyOne of the things I always document explicitly for my teams is what the local dev environment actually looks like, because it is where most auth confusion originates:Figure: Local development topologyThe stdio path gets its JWT from .env. The HTTP path gets it from the Authorization header. Both hit the same backend. The audit log runs locally too — do not skip it in development, or you will deploy to production without ever having tested the audit path.Key takeawaysIf you are building MCP into a production system, here is what to hold onto:Register only what the role can see. Do not rely on the backend to reject tools that the AI should never know exist. Derive the toolpack at session start.Always handle the 401 mid-session. JWTs expire. Build the re-auth path before you need it.Scope everything to tenant_id. In any multi-entity or multi-tenant system, this is not a database concern — it is a session concern. It belongs in the toolpack derivation step.Treat the audit log as a first-class citizen. Put it in the state machine. Make it mandatory. Do not leave it as a “we’ll add it later” item.Confirm before you mutate. The 428 confirmation gate is lightweight and keeps humans in the loop for irreversible operations. It costs almost nothing to implement and prevents a class of agent mistakes that are genuinely hard to recover from.What is nextThe architecture here handles authentication, authorisation, and safe execution for a single MCP server. The natural next steps are:MCP server federation: multiple domain-specific servers (HR, procurement, finance) behind a common gateway, with a unified toolpack derived from cross-server rolesStreaming tool responses: long-running approval workflows that push progress updates back to the AI client rather than blocking on a single responseLLM evaluation harness: automated tests that send tool sequences to the MCP server and verify the state machine transitions — essential before trusting autonomous agents with write accessI am building all three. I will write about each one as they mature.If this was useful, follow me here on Medium or connect on LinkedIn. I write about agentic systems, LLMOps, MCP architecture, and the practical side of AI engineering.The patterns and diagrams in this article originated from a real production-oriented MCP implementation focused on secure, role-aware AI systems.All architecture diagrams were initially modelled in Mermaid and later refined through AI-assisted design workflows.Building a Production-Grade MCP Server with JWT Auth and Role-Based Tool Access was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.