0I Built a Fully Authenticated MCP Server Without Ma⁶naging Any Servers
From the publisher’s feed, collected in the ZeroLabs newsroom.
Building a production-ready MCP server with Cognito auth, RBAC, and zero infrastructure management using AWS Bedrock AgentCore Runtime.The MCP ecosystem is moving fast. Every AI platform is racing toward tool-enabled agents, but most tutorials stop at “hello world.” What is still missing are production patterns: authentication, authorization, deployment, and operational simplicity.This article focuses on exactly that.TL;DRMCP (Model Context Protocol) is emerging as a cross-provider standard for exposing tools to LLMs.An MCP server is fundamentally just an HTTPS endpoint — but deploying one in production usually means ECS, load balancers, TLS, JWT validation, logging, and deployment pipelines.AWS Bedrock AgentCore Runtime gives MCP servers a managed runtime with built-in HTTPS endpoints, autoscaling, session handling, streaming support, and JWT authentication.I integrated it with Amazon Cognito using native JWT validation.Then I added role-based tool access so different users see different tools in tools/list, and unauthorized tools/call requests are blocked before execution.The entire authorization layer fits into a small ASGI middleware.The result: a production-ready MCP server with authentication, authorization, and no infrastructure to operate.1. What is MCP, and why should you care?If you have built applications around LLMs, you have probably reinvented “tools” multiple times already.Every provider — OpenAI, Anthropic, Google — has slightly different formats for:defining functions,validating arguments,executing tools,and returning responses.The Model Context Protocol (MCP), originally introduced by Anthropic, is emerging as a cross-provider standard for exposing tools to LLMs.It is a lightweight JSON-RPC 2.0-based protocol that can run over transports like stdio or streamable HTTP.The contract is intentionally tiny:Client calls tools/listServer returns available toolsClient calls tools/callThe server executes the tool and returns the resultThat is basically the protocol.The official Python SDK lets you create a working MCP server in a few lines:from mcp.server.fastmcp import FastMCPmcp = FastMCP(host="0.0.0.0", stateless_http=True)@mcp.tool()def get_weather(city: str) -> str: return f"It is sunny and 24C in {city}."if __name__ == "__main__": mcp.run(transport="streamable-http")Run it locally and any MCP-compatible client — Claude Desktop, Cursor, or the MCP Inspector — can connect and call get_weather.Simple.The harder question is:Where does this server actually run in production2. The infrastructure problem nobody wants to solveMost production MCP deployments quickly turn into infrastructure projects.A typical setup ends up involving:ECS or EKSLoad balancersTLS terminationJWT validationlogging and metricsdeployment pipelinesautoscalingWAF rulesThat is a large amount of operational overhead for a service whose business logic may only be fifty lines long.Lambda can absolutely host MCP servers, but streamable HTTP, payload limits, and long-lived conversational workflows make the architecture more complex than it initially appears.This is exactly the gap that AWS Bedrock AgentCore Runtime tries to solve.3. AgentCore Runtime: a managed home for MCPAWS released Bedrock AgentCore Runtime as a managed execution environment specifically designed for agent workloads and MCP servers.The experience is surprisingly simple:Upload your code. Get a secure HTTPS endpoint.AgentCore handles:TLSautoscalingJWT validationpayload streamingsession persistenceCloudWatch loggingruntime lifecycle managementThe runtime exposes endpoints like:https://bedrock-agentcore.{region}.amazonaws.com/runtimes/{arn}/invocationsAnd importantly:FastMCP already listens on 0.0.0.0:8000/mcp, which is exactly what AgentCore expects.Minimal glue code.Architecture OverviewClaude Desktop / Cursor │ ▼AWS AgentCore Runtime(JWT Validation) │ ▼RBAC Middleware │ ┌────────┴────────┐ ▼ ▼get_time() get_weather()Lambda vs AgentCore RuntimeCapability Lambda Agent Core Runtime HTTPS Endpoint API Gateway required Built-in JWT Validation Custom authorizer required Native Streaming HTTP Awkward First-class Payload Size 6 MB sync 100 MB sync100 MBSession Persistence Stateless Native session support Long-running workflows Limited Better aligned Infra management Medium Minimal4. The MCP server we are going to buildTo keep things concrete, I built a tiny MCP server with two tools:get_weather(city)get_time(timezone)The tool implementations themselves are trivial.The interesting part is everything around them.from datetime import datetimefrom zoneinfo import ZoneInfofrom mcp.server.fastmcp import FastMCPmcp = FastMCP( host="0.0.0.0", port=8000, stateless_http=True, name="demo-tools", instructions="A small demo MCP server.",)@mcp.tool()def get_weather(city: str) -> str: """Return mocked weather data.""" return f"Weather in {city}: 24C, partly cloudy."@mcp.tool()def get_time(timezone: str = "UTC") -> str: """Return current time in the given timezone.""" now = datetime.now(ZoneInfo(timezone)) return now.isoformat()if __name__ == "__main__": mcp.run(transport="streamable-http")At this point:The server runs locally,MCP clients can connect,tools execute successfully.Now we make it production-ready.5. Adding Cognito authenticationAn open MCP endpoint is fine for demos.It is not fine for production systems.The moment your tools:access internal APIs,query databases,invoke expensive models,or touch customer data,you need authentication.The good news is that AgentCore Runtime has built-in JWT validation support.It integrates directly with Cognito (or any OIDC provider).Step 1: Create a Cognito user poolPOOL_ID=$(aws cognito-idp create-user-pool \ --pool-name "mcp-demo-pool" \ --policies '{"PasswordPolicy":{"MinimumLength":8}}' \ --region us-east-1 \ --query 'UserPool.Id' --output text)CLIENT_ID=$(aws cognito-idp create-user-pool-client \ --user-pool-id "$POOL_ID" \ --client-name "mcp-demo-client" \ --no-generate-secret \ --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH \ --region us-east-1 \ --query 'UserPoolClient.ClientId' --output text)Step 2: Configure JWT validation in AgentCore{ "customJWTAuthorizer": { "discoveryUrl": "https://cognito-idp.us-east-1.amazonaws.com/POOL_ID/.well-known/openid-configuration", "allowedAudience": ["CLIENT_ID"] }}AgentCore now validates:JWT signatureissueraudienceexpirationbefore requests ever reach your application code.Step 3: Authenticate from the clientimport boto3cognito = boto3.client("cognito-idp", region_name="us-east-1")resp = cognito.initiate_auth( AuthFlow="USER_PASSWORD_AUTH", AuthParameters={ "USERNAME": "alice@example.com", "PASSWORD": "Demo-Passw0rd!" }, ClientId="CLIENT_ID",)token = resp["AuthenticationResult"]["IdToken"]Now authenticated requests can call the MCP server successfully.Unauthenticated requests receive HTTP 401 responses automatically.6. The trap: where did my Authorization header go?This was the part that cost me nearly an entire day.The runtime successfully authenticated the user — but my application code had no identity context at all.I assumed I could simply read:Authorization: Bearer inside my FastMCP server.That assumption was wrong.By default:AgentCore strips the Authorization header before forwarding the request to your container.The security reasoning makes sense.But the consequence is important:Your application no longer knows who the caller is.I spent hours:dumping headers,inspecting middleware,decoding opaque internal tokens,searching CloudWatch logs,reading fragmented docs.Eventually, I found the solution buried in the authentication documentation.You must explicitly allow inbound headers.The fixWhen creating the runtime:--request-header-configuration \'{"requestHeaderAllowlist":["Authorization"]}'That single line changes everything.Now the JWT reaches your application code.Decoding the JWTSince AgentCore already validated the token, the application only needs to extract claims.import base64import jsondef decode_jwt_email(authorization: str) -> str: if not authorization: return "" token = authorization.removeprefix("Bearer ").strip() if token.count(".") != 2: return "" try: payload_b64 = token.split(".")[1] payload_b64 += "=" * ((4 - len(payload_b64) % 4) % 4) payload = json.loads(base64.b64decode(payload_b64)) return ( payload.get("email") or payload.get("cognito:username") or "" ) except Exception: return ""This only works because AgentCore performs JWT validation before forwarding the request. If you expose the container directly outside AgentCore, you must validate signatures yourself.That decoder becomes the foundation for authorization.7. Role-based tool accessAuthentication tells us:Who is calling?Authorization tells us:What are they allowed to do?For MCP, authorization means:Filter tools/listBlock unauthorized tools/callI implemented both in a small ASGI middleware.The role modelROLE_TOOLS = { "viewer": {"get_time"}, "admin": {"get_weather", "get_time"},}USER_ROLES = { "alice@example.com": "viewer", "bob@example.com": "admin",}In production, this would come from:DynamoDBPostgreSQLRedisJWT claimsIAM identity mappingsThe middleware itself does not change.The middlewareclass RBACMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): headers = dict(scope.get("headers", [])) auth = headers.get(b"authorization", b"").decode() email = decode_jwt_email(auth) allowed = allowed_tools_for(email) ...The middleware:extracts identity,determines permissions,filters tools/list,blocks forbidden tools/call requests.The important architectural detail is this:The authorization logic sits before FastMCP routing.That means unauthorized tools completely disappear from discovery.Why middleware instead of decorators?FastMCP decorators execute after the tool has already been exposed in tools/list.That is too late.We want unauthorized tools to be invisible entirely.The ASGI layer is the correct interception point.And importantly:The pattern is portable.It works with any ASGI-compatible MCP server implementation.8. Deploying to AgentCore RuntimeDeployment is container-based.The flow is familiar:build image,push to ECR,create runtime,receive endpoint.DockerfileFROM public.ecr.aws/docker/library/python:3.11-slimWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY server.py .EXPOSE 8000CMD ["python", "server.py"]Push image to ECRdocker build -t mcp-demo .docker tag mcp-demo:latest \ ACCOUNT.dkr.ecr.us-east-1.amazonaws.com/mcp-demo:latestdocker push \ ACCOUNT.dkr.ecr.us-east-1.amazonaws.com/mcp-demo:latestCreate runtimeaws bedrock-agentcore-control create-agent-runtime \ --agent-runtime-name "mcp-demo" \ --protocol-configuration '{"serverProtocol":"MCP"}' \ --request-header-configuration \ '{"requestHeaderAllowlist":["Authorization"]}'That is effectively the deployment process.No load balancer.No TLS certificates.No API Gateway.No ECS service management.No autoscaling configuration.9. The honest pros and consAfter running this setup for a while, here is the honest assessment.ProsMinimal operational overheadNo ALBs.No ECS service maintenance.No TLS rotation.No deployment orchestration complexity.Built-in authenticationJWT validation is native.Cognito integration is extremely clean.Session-aware runtimeAgentCore aligns naturally with conversational workflows and streaming MCP interactions.Better payload handling100 MB payload support is significantly more comfortable than Lambda’s synchronous limits.Cost efficiencyFor internal tooling workloads with sporadic traffic, the cost difference compared to always-on ECS services can be substantial.ConsThe documentation is unevenSome pages are excellent.Others omit critical details.The Authorization header allowlist is one of the most important settings in the entire flow, yet it is easy to miss.The tooling ecosystem is still immatureThere is no mature equivalent of:SAM,CDK patterns,polished Terraform modules,local emulators.You will likely write your own deployment scripts.Observability is basicCloudWatch logs exist.But identity-layer debugging still requires substantial custom logging.Vendor lock-in existsThe runtime model is AWS-specific.Migrating later would require rebuilding parts of the auth and deployment model.Cold starts still existSmaller than Lambda.Not zero.Interactive clients may notice first-request latency.10. What I would do differently next timeThree lessons stood out.Read the auth docs before the MCP docsThe inbound header forwarding detail lives in the authentication documentation.Missing that cost me nearly a full day.Add RBAC on day oneRetrofitting permissions later is painful.The middleware is small enough that it should exist from the beginning.Cache role lookupsThe demo uses in-memory dictionaries.Real systems should cache authorization lookups aggressively.Even a short-lived in-process cache dramatically reduces database overhead.Final thoughtsThe promise of serverless has always been:Infrastructure should stop being your problem.For MCP servers, that has not really been true until recently.Most teams still spend more time wiring infrastructure than building actual tools.AgentCore Runtime changes that equation.The development flow becomes surprisingly small:write FastMCP code,add middleware,push a container,create a runtime,connect a client.You get:authenticated endpoints,streaming support,autoscaling,session management,role-aware tool access,and zero infrastructure management.The ecosystem around MCP is still early, and production deployment patterns are evolving quickly. If you are building an authenticated MCP infrastructure or experimenting with AgentCore Runtime, I would love to compare notes.0I Built a Fully Authenticated MCP Server Without Ma⁶naging Any Servers was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.