How to Build a Stateless MCP Server for Your SaaS API Without Breaking Production
Introduction
A familiar request is landing in B2B product backlogs: "Can we use your product from our AI assistant?" Sales hears it from enterprise prospects, and engineering hears it from customers who have already started wiring agents to internal tools. The protocol most of those clients speak is MCP, an open standard that lets an AI application discover and call tools, read resources, and use prompt templates that a server exposes.
The quickest demo is a local MCP server running over stdio on a developer laptop. The trouble starts when that demo has to become a hosted, multi-tenant service. Teams often bolt on in-memory session maps, long-lived connections, and a separate API key scheme, and then discover that their load balancer, autoscaler, and deploy process all fight against it.
In this article you will learn what "stateless" means for an MCP server, how to map your existing REST API onto MCP tools, how to handle authentication and tenancy, and how to ship the server without putting your core API at risk.
What Stateless Means for an MCP Server
MCP defines two standard transports. The stdio transport runs the server as a local subprocess of the client. The Streamable HTTP transport exposes a single HTTP endpoint that accepts JSON-RPC messages via POST and can optionally stream responses back with Server-Sent Events. Streamable HTTP is the one you want for a hosted SaaS integration.
Streamable HTTP lets the server issue a session ID during initialization, which the client then sends on every request. That is useful when a server needs to remember something between calls, such as an open file handle or a long-running subscription. For most SaaS APIs it is unnecessary. Your API is already stateless: each request carries a token, the token identifies a tenant and a user, and the database holds the state.
A stateless MCP server follows the same rule. Every request is handled from scratch: authenticate, resolve the tenant, run the tool, return the result. No session map lives in process memory, so any replica can serve any request, a deploy can kill a pod mid-conversation without losing anything, and horizontal scaling works with your existing round-robin load balancer.
Mapping Your Existing API to MCP Tools
The biggest design decision is not the transport. It is which tools you expose and how you describe them. An AI client chooses tools from their names, descriptions, and input schemas, so a tool list is closer to a product surface than to an API reference.
A few rules work well in practice:
Expose tasks, not endpoints. "find_overdue_invoices" with a customer filter is easier for a model to use correctly than raw access to GET /invoices with twelve query parameters.
Keep inputs small and typed. Use enums for statuses and ISO dates for ranges and explicit limits with sensible defaults.
Return compact, structured results. Return the fields a model needs to answer the question, plus IDs it can pass to the next tool, instead of whole database rows.
Separate reads from writes. Start with read-only tools, and give write tools clear names such as "create_draft_credit_note" so both the model and the human approving the action know what will happen.
Behind each tool, call your existing service layer or public API rather than querying the database directly. That keeps validation, permissions, and business rules in one place, and it means the MCP server is a thin adapter you can change without touching core logic.
A Minimal Stateless Server in TypeScript
The official TypeScript SDK supports stateless Streamable HTTP by creating a new server and transport for each request and disabling session IDs. A trimmed version looks like this:
`import express from "express";
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
function buildServer(ctx: { tenantId: string; token: string }) {
const server = new McpServer({ name: "acme-billing", version: "1.4.0" });
server.registerTool("find_overdue_invoices", {
description: "List unpaid invoices past their due date for one customer",
inputSchema: { customerId: z.string(), limit: z.number().max(50).default(20) },
}, async ({ customerId, limit }) => {
const rows = await billingApi(ctx).overdueInvoices(customerId, limit);
return { content: [{ type: "text", text: JSON.stringify(rows) }] };
});
return server;
}
app.post("/mcp", requireBearerToken, async (req, res) => {
const server = buildServer(req.authContext);
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on("close", () => { transport.close(); server.close(); });
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});`
Building the server per request sounds expensive, but registering a handful of tools is cheap compared with the network and database work the tool does. More importantly, it means the authenticated context is captured in a closure for that request only, so there is no shared mutable state that could leak one tenant's context into another tenant's call.
Authentication, Tenancy, and Rate Limits
For remote servers, the MCP specification builds authorization on OAuth 2.1. Your MCP server acts as a protected resource, advertises which authorization server issues its tokens, and validates the bearer token on every request. If your SaaS already has an OAuth provider, reuse it and add a dedicated scope such as "mcp:read" so customers can grant AI access separately from full API access.
Resolve the tenant from the token, never from a tool argument. A model can be convinced to pass any customer ID it sees in a conversation, so tool inputs should only narrow results within the tenant the token already allows.
Apply the same per-tenant rate limits you use for your public API, with one addition: a per-request cap on how many tool calls one conversation can trigger in a short window. Agents retry and loop in ways human users do not, and a stateless design makes it easy to enforce these limits in shared infrastructure such as Redis or your API gateway.
Deploying Without Risk to the Core API
Treat the MCP server as a separate deployable that depends on your API, not as new routes inside the monolith. Run it in its own service with its own autoscaling, timeouts, and error budget. If an agent hammers a slow tool, the MCP service degrades, and your web app keeps working.
Set hard timeouts below your load balancer's idle timeout, return clear error messages the model can act on ("customerId not found in this workspace"), and log every tool call with tenant, tool name, latency, and result size. Those logs become your best source of truth about which tools customers rely on.
Practical Examples: Real-World Use Cases
A B2B invoicing platform exposes three read-only tools: find_overdue_invoices, get_customer_balance, and summarize_payment_history. A finance manager asks an assistant which customers are more than 60 days overdue, and the assistant chains two tools to produce a ranked list with balances. Nothing in the core billing service changed.
A field service SaaS adds a write tool, create_draft_work_order, which only creates drafts that a dispatcher must confirm in the web app. The model can save typing, but a person still approves anything that sends a technician to a site.
An internal operations team at a distributor connects its ERP-backed API to an internal agent. Because the MCP server is stateless, they run it on the same Kubernetes cluster as their other services and scale it with the same horizontal pod autoscaler rules.
Common Mistakes to Avoid
Keeping session state in memory. It works on one replica and breaks the moment you scale to two or deploy during business hours. If you truly need sessions, store them in Redis and keep handlers idempotent.
Mirroring every REST endpoint as a tool. Large, overlapping tool lists confuse models and increase the chance of the wrong call. Start with five to ten task-shaped tools.
Trusting tenant or user IDs from tool inputs. Always derive identity from the validated token.
Returning huge payloads. Large results waste the client's context window and slow everything down. Paginate and summarize.
Shipping write tools first. Begin with read-only access, measure usage, and then add writes with drafts or approval steps.
Best Practices: Actionable Tips
Version your server and tool descriptions, and record the version in every log line.
Write tool descriptions for a reader who has never seen your product. Include units, formats, and what the tool will not do.
o.Add contract tests that call each tool through the MCP protocol, not only the underlying function.
Use the MCP Inspector during development to check tool listings and responses.
Put the MCP service behind the same WAF, gateway, and monitoring as your public API.
Publish a short customer-facing page listing available tools, required scopes, and limits.
Conclusion
A stateless MCP server is the simplest way to make your SaaS usable from AI clients without changing how you run production. Use Streamable HTTP without sessions, authenticate every request with your existing OAuth setup, expose a small set of task-shaped tools that call your service layer, and deploy the server as its own service with its own limits. The takeaway: treat MCP as a thin, stateless adapter over the API you already trust, and it will scale the same way that API does.
Build Your MCP Integration With Parallaxis
Parallaxis designs and builds SaaS platforms and API integrations for B2B companies, including production-ready MCP servers that connect your product to AI assistants safely. If you want help choosing the right tools to expose, wiring up OAuth scopes, or load-testing an MCP service before launch, visit parallaxis.in or reach out to discuss your project with our SaaS development team.