Building a Cost-Efficient, Extensible MCP Server Infrastructure: Inside JAI MCP Cluster for Super Agent Platform

⭐️This is Day 21 of the JAPAN AI Advent Calendar 2025⭐️
I'm Amry Fitra Amanah, an Engineer on the Agent Core team at JAPAN AI株式会社, where we build frameworks for AI Agent Services. Our team develops the underlying platform that enables users to implement their own AI solutions. Working on this infrastructure gives our team visibility into how diverse organizations use the framework to solve different problems. Through analyzing usage patterns, token consumption data, and user feedback across our platform, we've observed that successful AI implementations aren't about using the most powerful models—they're about matching capabilities to actual needs.
Introduction
As part of our release of JAPAN AI's super agent platform—we faced a significant engineering challenge: how do we integrate with the rapidly growing Model Context Protocol (MCP) ecosystem while maintaining cost efficiency and multi-tenant isolation?
The MCP standard has fostered a thriving ecosystem of specialized servers developed by the open-source community and various organizations. These servers cover diverse use cases—from GitHub and Gmail integrations to Slack, Notion, and enterprise-specific workflows. The value proposition is clear: by integrating with MCP, we unlock immediate access to this expanding toolkit for our users.
However, the standard MCP deployment model presents a fundamental problem. Each MCP server instance is tied to a specific user's authentication token. For example, a GitHub MCP server requires a user's personal access token to operate. This creates a strict 1:1 mapping between user+token and server instance—if we kept all instances running continuously for every user, our infrastructure costs would skyrocket.
This article details how we built JAI MCP Cluster: a Kubernetes-native infrastructure that dynamically provisions per-user MCP servers with scale-to-zero capabilities, achieving production cold starts under 16 seconds with sub-200ms median response times for warm requests—acceptable latency for agentic workflows where LLM reasoning already takes several seconds.
TL;DR
We built JAI MCP Cluster to solve the cost problem of per-user MCP servers. Using Kubernetes + Knative, we achieve:
- Scale-to-zero: Pay only when servers are actively processing requests
- 15-second cold starts with 0.18-second median warm requests
- Per-user isolation with automatic credential management
- ~95% cost reduction compared to always-on infrastructure
- 74% of requests complete in under 0.5 seconds
- Transparent OAuth token lifecycle management
Main Section (1)
What is JAI MCP Cluster?
JAI MCP Cluster is our self-hosted MCP server orchestration platform built on Kubernetes and Knative. It solves the core tension between per-user isolation requirements and cost efficiency through intelligent autoscaling and dynamic provisioning.
The Problem: Per-User Isolation vs. Cost
Consider the standard deployment pattern for an MCP server like a GitHub integration:
docker run -p 5000:5000 \
-e AUTH_DATA='{"access_token":"ghp_user_token"}' \
ghcr.io/klavis-ai/github-mcp-server:latest
Each container requires the user's OAuth token baked into its environment. You cannot share a single container across multiple users—the authentication is intrinsic to the instance. With potentially thousands of users across multiple organizations, each needing access to multiple MCP providers (GitHub, Gmail, Slack, etc.), the naive approach of running dedicated containers would be prohibitively expensive.
Cost Impact: Always-On vs. Scale-to-Zero
Let's quantify the problem with a realistic scenario:
Example: 1,000 users × 3 MCP providers each
Always-on containers:
3,000 containers × $0.02/hour = ~$43,200/month
Scale-to-zero (typical 5% active at any time):
~150 containers average × $0.02/hour = ~$2,160/month
─────────────
Estimated savings: ~$41,000/month (~95%)Even with conservative estimates, the scale-to-zero approach delivers dramatic cost reduction. In our production environment with typical enterprise usage patterns (intermittent tool invocations throughout the workday rather than continuous usage), we observe approximately 90-95% cost savings compared to dedicated always-on infrastructure.
The Solution: Knative Scale-to-Zero
Knative Serving provides the key capability we needed: automatic scaling including scale-to-zero. Each user's MCP server runs as an independent Knative Service that automatically scales up on request and scales down to zero replicas when idle.
This approach offers several advantages:
- Pay only while requests are being served: When a user isn't actively using their MCP tools, their containers consume zero compute resources.
- Fast warm request performance: The Knative Activator buffers initial traffic and spins up pods transparently, achieving sub-200ms median latency for warm requests.
- Simple per-user isolation: One Knative Service and Secret per user+token combination, with straightforward garbage collection and credential rotation.
Production Performance Metrics
Based on production measurements across 30 cold starts and 85 warm requests, we observed the following performance characteristics:
| Metric | Value | Notes |
|---|---|---|
| Cold Start (n=30) | ||
| Average | 15.28 sec | Container pull, init, credential loading |
| Min / Max | 15.19 / 15.47 sec | Very consistent performance |
| Warm Requests (n=85) | ||
| P50 (Median) | 0.18 sec | Majority of requests sub-200ms |
| P90 / P95 | 3.00 / 3.31 sec | Tail latency from network/GC |
| Fast Requests (<0.5s) | 74% (63/85) | Average 0.19 sec for fast requests |
Table 1: JAI MCP Cluster Production Performance Metrics
The cold start latency of approximately 15 seconds reflects the reality of production workloads with heavier container images, comprehensive initialization code for credential loading, and secure connection establishment. While higher than minimal PoC environments, this latency remains acceptable for agentic workflows where tool invocations are typically preceded by LLM reasoning steps that take several seconds themselves.
Warm requests show excellent performance with a P50 of 0.18 seconds, meaning the majority of requests complete in under 200ms. The P90 of 3.00 seconds accounts for occasional network variability and garbage collection pauses, while 74% of warm requests (63 out of 85) completed in under 0.5 seconds with an average of just 0.19 seconds.
Architecture Overview
JAI MCP Cluster consists of three primary components:
- MCP API
A REST API that handles requests from our agent service. It accepts user credentials and provider specifications, returning the dynamically-generated SSE endpoint for that user's MCP server.
- MCP Operator
A Kubernetes operator that watches for McpServer custom resources and reconciles them into Knative Services, Secrets, and related infrastructure.
- Knative Serving
Provides the serverless runtime with automatic scaling, traffic routing, and revision management.

The workflow follows a declarative pattern: when the MCP API receives a provisioning request, it creates an McpServer custom resource. The MCP Operator detects this resource and reconciles it by creating the corresponding Knative Service with the user's credentials stored in a Kubernetes Secret. Knative then handles the actual pod lifecycle, scaling from zero when requests arrive and terminating after the configured idle period.
Custom Resource Definition
We defined our own Kubernetes custom resource type (McpServer) to declaratively manage MCP server instances:
apiVersion: platform.japan-ai.dev/v1alpha1
kind: McpServer
metadata:
name: m1a2b3c4
spec:
tenant: acme-corp
provider: github
port: 5000
auth:
fromSecret:
name: github-auth-m1a2b3c4This approach provides declarative management (describe desired state, operator makes it real), automation of complex operational tasks, self-healing through automatic reconciliation, and seamless integration with Kubernetes RBAC and CI/CD pipelines.
Main Section (2)Integration Challenges and Solutions
Integrating JAI MCP Cluster into our agent service presented several engineering challenges. The dynamic nature of MCP endpoints, combined with OAuth token lifecycle management, required careful architectural decisions.
Challenge 1: Dynamic Endpoint Resolution
Unlike static MCP server deployments where endpoints are known at configuration time, JAI MCP Cluster generates endpoints dynamically based on a hash of the user ID, authentication token, provider, and organization. The endpoint format follows RFC 1035/1123 DNS naming conventions:
https://mf9c8fa894425dbcb146014eb4a0af309ac43e38e.4473ac0e-6af7-4057-84c9-a7ebb11e0513.mcp.stg.japan-ai.dev
We implemented a pluggable URL resolver pattern with two concrete implementations:
- StaticMCPUrlResolver: Returns a pre-configured URL for traditional MCP deployments.
- JaiClusterUrlResolver: Fetches user credentials from our credential store, calls the JAI MCP Cluster provisioning API, caches the returned SSE endpoint, and handles cache invalidation on authentication failures.
This abstraction allows the same MCPClient code to work with both existing static deployments and dynamic JAI Cluster deployments.
Challenge 2: Authentication Lifecycle Management
OAuth tokens expire. When a user's GitHub or Gmail token expires mid-session, we need to detect this, refresh the token, update the stored credentials, invalidate the cached endpoint, and re-provision the MCP server with fresh credentials—all transparently to the user.
Our solution implements a two-phase detection and recovery mechanism:
- AuthExpirationDetector: Identifies authentication failures from HTTP 401 status codes and response body patterns ("invalid credentials", "token expired", etc.).
- Automatic retry loop: The MCPClient implements a max 2-attempt retry loop that, upon detecting auth errors, refreshes OAuth tokens, persists updated credentials, invalidates the resolver cache, and retries the request.
This ensures that transient authentication issues don't break tool execution while keeping credentials fresh.
Challenge 3: Graceful Degradation and Observability
In a production agentic system, MCP tool failures shouldn't crash the entire agent. We implemented comprehensive error handling with distinct error types:
- MCPServerError: For non-auth HTTP errors, with user-friendly messages truncated to 350 characters.
- MCPAuthenticationError: For credential issues, with provider-specific guidance prompting re-authentication.
All MCP operations use structured logging with consistent fields for effective monitoring and debugging. Critically, we ensure zero credential data appears in logs, error messages, or metrics.
When credentials are missing during initialization, we set an internal error flag but don't raise exceptions—errors surface only when tools are actually invoked. This prevents a single misconfigured MCP provider from blocking the entire tool loading process.
Trade-offs and Limitations
No solution is perfect. Here are the key trade-offs we accepted when building JAI MCP Cluster:
Cold start latency: 15-second cold starts are acceptable for agentic workflows where users expect multi-second response times, but this approach wouldn't suit real-time applications requiring sub-second tool response. We mitigate this with aggressive keep-alive policies for active sessions—once a user's container is warm, it stays available for their entire work session.
Third-party MCP quality: We depend on community-maintained MCP servers. Not all are production-grade—some lack comprehensive error handling, others have security vulnerabilities. We maintain an internal quality assessment process before onboarding new providers and contribute fixes upstream when possible.
Operational complexity: Kubernetes + Knative + custom operator adds operational overhead compared to simpler deployments. For organizations with fewer than 50 users, the engineering investment may not justify the cost savings. For us, serving thousands of users across multiple tenants makes this complexity worthwhile.
Security & Compliance
For enterprise deployments, JAI MCP Cluster implements multiple layers of security:
- Credentials stored in Kubernetes Secrets with encryption at rest enabled.
- Per-tenant namespace isolation prevents cross-tenant access through Kubernetes RBAC.
- Zero credential logging policy enforced via structured logging and automated audits.
- RBAC integration for comprehensive audit trails and access control.
- Network policies restrict pod-to-pod communication to authorized services only.
- Secret rotation support through the reconciliation loop—updating a Secret triggers automatic pod restart with new credentials.
User Experience
From a user's perspective, JAI MCP Cluster operates transparently:
- Connect accounts via OAuth (GitHub, Gmail, etc.) through the JAPAN AI interface.
- Tools appear immediately in the agent's available tool list.
- First invocation may take ~15 seconds (cold start while container spins up).
- Subsequent calls are sub-second for the duration of the session.
- No manual server management required—OAuth refresh and credential rotation happen automatically.
Conclusion and Future Roadmap
JAI MCP Cluster represents our solution to the fundamental tension between MCP's per-user authentication model and cost-efficient infrastructure. By leveraging Kubernetes and Knative's scale-to-zero capabilities, we've built a platform that:
- Provisions per-user MCP servers on-demand with ~15-second cold starts and sub-200ms median warm requests
- Scales to zero when idle, delivering ~95% cost reduction for typical enterprise usage patterns.
- Maintains strict tenant isolation through Kubernetes namespaces and RBAC
- Handles OAuth token lifecycle automatically and transparently
- Provides portable deployment across AWS, Azure, GCP, and on-premise environments
What's Next
Our roadmap for JAI MCP Cluster includes several exciting developments:
- Expanded MCP Provider Support: We're actively integrating additional MCP servers from the open-source ecosystem including Slack, Notion, Salesforce, and enterprise-specific integrations.
- Migration of Existing Services: Our Twitter MCP server and Playwright MCP (for browser automation) will be migrated to JAI MCP Cluster, providing consistent deployment patterns and enabling features like persistent sessions that prevent users from needing to re-login frequently.
- Security Enhancements: Fine-grained permission scoping, comprehensive audit logging for compliance requirements, and runtime protection against prompt injection attacks.
- Under Consideration - Multi-Region Deployment: Geographic distribution for reduced latency and improved disaster recovery capabilities.
References
- Kubernetes: The container orchestration platform that powers JAI MCP Cluster's infrastructure. https://kubernetes.io/
- Knative Serving: Serverless framework providing scale-to-zero capabilities and automatic scaling. https://knative.dev/docs/serving/
- Klavis AI: Open-source MCP server implementations for various integrations including GitHub, Gmail, Slack, and more. https://github.com/Klavis-AI
- Model Context Protocol (MCP): The open standard for connecting AI assistants to external data sources and tools. https://modelcontextprotocol.io/
For more information about JAPAN AI's agent platform, visit our website or reach out to our team.
Interested in building AI infrastructure at scale? We're hiring engineers who love solving hard problems at the intersection of AI and distributed systems. Learn more about
careers at JAPAN AI.
株式会社ジーニー JAPAN AI / Developer の求人一覧hrmos.co