DEV Community

Tamiz Uddin
Tamiz Uddin

Posted on Originally published at tamiz.pro

MCP Gateways in Practice: Connect, Secure, and Orchestrate Coding Agents with VS Code, Browsers, and Kubernetes

Originally published on tamiz.pro.

The Model Context Protocol (MCP) has become a practical integration layer for AI agents, but connecting every client directly to every tool server creates an operational problem: credentials sprawl, authorization rules diverge, and observability disappears into local processes. An MCP gateway solves this by placing a controlled, inspectable hop between clients and tools.

This tutorial builds a production-oriented MCP gateway using TypeScript and Fastify. You will expose it to Visual Studio Code, a browser-based agent, and a Kubernetes-hosted coding agent while enforcing authentication, per-user tool permissions, request limits, and structured audit logs.

Scope: This implementation focuses on MCP Streamable HTTP transport and OAuth 2.1 resource-server behavior. It does not implement the older HTTP+SSE transport, legacy OAuth authorization-server flows, or stdio proxying.

Table of Contents

1. Architecture Overview

A direct MCP deployment looks deceptively simple:

VS Code ─────┐
Browser ────┼──> GitHub MCP Server ──> GitHub API
Kubernetes ──┘
Enter fullscreen mode Exit fullscreen mode

Every client must now know where the tool server lives, how to obtain credentials, and which tools it may call. More importantly, every client can bypass policies implemented elsewhere.

The gateway changes the topology:

                         ┌─────────────────────────┐
                         │       Identity Provider  │
                         │        (OIDC / OAuth)    │
                         └────────────┬────────────┘
                                      │ JWT validation
                                      ▼
┌────────────┐   ┌────────────┐   ┌────────────┐   ┌─────────────────────────┐
│   VS Code  │   │  Browser  │   │ Kubernetes │──▶│       MCP Gateway       │
│   Client   │──▶│   Client  │──▶│   Client   │   │                         │
└────────────┘   └────────────┘   └────────────┘   │ • Token validation      │
                                                │ • Tool allowlists       │
                                                │ • Rate limits           │
                                                │ • Audit logging         │
                                                │ • Credential injection  │
                                                └───────────┬─────────────┘
                                                            │
                                            ┌───────────────┴───────────────┐
                                            ▼                               ▼
                                   ┌─────────────────┐           ┌──────────────────┐
                                   │ Local MCP Server│           │ Remote MCP Server│
                                   │ (stdio bridge)  │           │ (Streamable HTTP)│
                                   └─────────────────┘           └──────────────────┘
Enter fullscreen mode Exit fullscreen mode

The gateway performs four jobs:

  1. Protocol termination: Accepts MCP Streamable HTTP requests and forwards them to one or more upstream MCP servers.
  2. Identity enforcement: Validates bearer tokens and resolves the caller to a stable subject identifier.
  3. Policy enforcement: Applies tool-level and argument-level authorization before forwarding a request.
  4. Operational visibility: Records latency, errors, tool usage, and denied operations in structured logs.

The MCP specification describes several transports, but the gateway in this tutorial uses Streamable HTTP. A client sends JSON-RPC requests to a single MCP endpoint. The server may respond with JSON or an SSE stream, and it can return an MCP session identifier that must be included on subsequent requests.

Trust boundaries

Treat these as separate trust domains:

Component Trust level Sensitive data it handles
Gateway Trusted control plane Access tokens, policy decisions, audit metadata
MCP server Trusted downstream service Provider credentials, repository data
Client Untrusted caller Bearer token, user prompts
Identity provider External trusted authority User identity and authentication events

The gateway should never forward the caller's bearer token to an upstream server. Instead, it should use a scoped credential appropriate for that server. A common pattern is one upstream credential per tool server, selected by the gateway after authorization succeeds.

2. Prerequisites

You need:

  • Node.js 20 or later
  • npm 10 or later
  • Docker Desktop, Docker Engine, or another OCI-compatible runtime
  • kubectl and a Kubernetes cluster for the deployment section
  • An MCP client such as Visual Studio Code with MCP support
  • An identity provider that issues JWT access tokens

For local testing, you can generate a short-lived JWT using the scripts included in the project. Do not use a self-signed development token in production.

3. Project Setup

Create the project and install its dependencies:

mkdir mcp-gateway && cd mcp-gateway
npm init -y
npm install @modelcontextprotocol/sdk fastify @fastify/jwt fastify/rate-limit pino zod jose
npm install -D typescript tsx @types/node vitest
Enter fullscreen mode Exit fullscreen mode

Create tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "noUncheckedIndexedAccess": true
  },
  "include": ["src/**/*.ts", "test/**/*.ts"]
}
Enter fullscreen mode Exit fullscreen mode

Set the package scripts:

npm pkg set scripts.dev="tsx watch src/server.ts"
npm pkg set scripts.build="tsc -p tsconfig.json"
npm pkg set scripts.start="node dist/src/server.js"
npm pkg set scripts.test="vitest run"
npm pkg set type="module"
Enter fullscreen mode Exit fullscreen mode

Create the environment file used during local development:

cat > .env <<'EOF'
PORT=8080
LOG_LEVEL=info
OIDC_ISSUER=https://your-tenant.example.com/
OIDC_AUDIENCE=mcp-gateway
OIDC_JWKS_URL=https://your-tenant.example.com/.well-known/jwks.json
UPSTREAM_BASE_URL=http://127.0.0.1:9090
UPSTREAM_BEARER_TOKEN=replace-with-a-local-development-token
EOF
Enter fullscreen mode Exit fullscreen mode

Do not commit .env. Add it to .gitignore:

printf '.env\nnode_modules\ndist\n' > .gitignore
Enter fullscreen mode Exit fullscreen mode

The environment variables have clear responsibilities:

Variable Purpose
OIDC_ISSUER Expected JWT issuer; also used to discover the JWKS endpoint
OIDC_AUDIENCE Required access-token audience
OIDC_JWKS_URL JSON Web Key Set used to verify JWT signatures
UPSTREAM_BASE_URL MCP server that receives forwarded requests
UPSTREAM_BEARER_TOKEN Gateway-owned credential for the upstream server

4. Implement the MCP Gateway

The gateway is an HTTP proxy with MCP-aware semantics. It must preserve the Accept header required by Streamable HTTP, forward the MCP session identifier, and avoid buffering server-sent events.

Create src/config.ts:

import { z } from "zod";

const envSchema = z.object({
  PORT: z.coerce.number().int().positive().default(8080),
  LOG_LEVEL: z.string().default("info"),
  OIDC_ISSUER: z.string().url(),
  OIDC_AUDIENCE: z.string().min(1),
  OIDC_JWKS_URL: z.string().url(),
  UPSTREAM_BASE_URL: z.string().url(),
  UPSTREAM_BEARER_TOKEN: z.string().min(1)
});

export type Config = z.infer<typeof envSchema>;

export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
  const result = envSchema.safeParse(env);

  if (!result.success) {
    const issues = result.error.issues
      .map((issue) => `${issue.path.join(".")}: ${issue.message}`)
      .join("; ");

    throw new Error(`Invalid configuration: ${issues}`);
  }

  return result.data;
}
Enter fullscreen mode Exit fullscreen mode

Create src/policy.ts:

import { z } from "zod";

export const toolCallSchema = z.object({
  method: z.literal("tools/call"),
  params: z.object({
    name: z.string().min(1),
    arguments: z.record(z.unknown()).default({})
  })
});

export type ToolCall = z.infer<typeof toolCallSchema>;

export interface Subject {
  sub: string;
  scopes: string[];
}

export interface PolicyDecision {
  allowed: boolean;
  reason?: string;
}

const allowedTools = new Set([
  "search_repositories",
  "get_file_contents",
  "create_issue"
]);

export function authorizeToolCall(
  subject: Subject,
  call: ToolCall
): PolicyDecision {
  if (!allowedTools.has(call.params.name)) {
    return {
      allowed: false,
      reason: `Tool '${call.params.name}' is not registered in the gateway policy`
    };
  }

  if (
    call.params.name === "create_issue" &&
    !subject.scopes.includes("issues:write")
  ) {
    return {
      allowed: false,
      reason: "The 'issues:write' scope is required"
    };
  }

  return { allowed: true };
}
Enter fullscreen mode Exit fullscreen mode

The policy layer deliberately operates on the JSON-RPC request body. It does not infer permissions from a tool name alone. For example, create_issue requires a separate write scope.

Create src/upstream.ts:

import type { ToolCall } from "./policy.js";

export interface UpstreamResult {
  status: number;
  headers: Headers;
  body: ReadableStream<Uint8Array> | null;
}

export interface UpstreamClient {
  forward(
    request: {
      body: string;
      sessionId?: string;
      accept: string;
    }
  ): Promise<UpstreamResult>;
}

export class HttpUpstreamClient implements UpstreamClient {
  constructor(
    private readonly baseUrl: string,
    private readonly bearerToken: string
  ) {}

  async forward(request: {
    body: string;
    sessionId?: string;
    accept: string;
  }): Promise<UpstreamResult> {
    const headers = new Headers({
      authorization: `Bearer ${this.bearerToken}`,
      "content-type": "application/json",
      accept: request.accept
    });

    if (request.sessionId) {
      headers.set("mcp-session-id", request.sessionId);
    }

    const response = await fetch(`${this.baseUrl}/mcp`, {
      method: "POST",
      headers,
      body: request.body
    });

    return {
      status: response.status,
      headers: response.headers,
      body: response.body
    };
  }
}
Enter fullscreen mode Exit fullscreen mode

This client replaces the caller's authorization header. The upstream never receives the gateway's inbound token.

Now create src/server.ts:

import Fastify from "fastify";
import fastifyJwt from "@fastify/jwt";
import fastifyRateLimit from "@fastify/rate-limit";
import { createRemoteJWKSet, jwtVerify } from "jose";
import { loadConfig } from "./config.js";
import { authorizeToolCall, toolCallSchema } from "./policy.js";
import { HttpUpstreamClient } from "./upstream.js";

const config = loadConfig();
const app = Fastify({
  logger: {
    level: config.LOG_LEVEL,
    redact: [
      "req.headers.authorization",
      "req.headers.cookie",
      "headers.authorization"
    ]
  },
  bodyLimit: 1024 * 1024,
  trustProxy: true
});

await app.register(fastifyRateLimit, {
  max: 120,
  timeWindow: "1 minute",
  keyGenerator: (request) => request.user?.sub ?? request.ip
});

const jwks = createRemoteJWKSet(new URL(config.OIDC_JWKS_URL));

app.decorate("authenticate", async function (request, reply) {
  try {
    await jwtVerify(request.headers.authorization ?? "", jwks, {
      issuer: config.OIDC_ISSUER,
      audience: config.OIDC_AUDIENCE
    });
  } catch {
    return reply.code(401).send({
      error: "invalid_token",
      error_description: "The access token is missing, invalid, or expired"
    });
  }
});

await app.register(fastifyJwt, {
  secret: "unused-for-external-issuer-validation",
  verify: {
    extractToken: false
  }
});

app.get("/health/live", async () => ({ status: "ok" }));

app.get("/health/ready", async (_request, reply) => {
  try {
    const response = await fetch(
      `${config.UPSTREAM_BASE_URL}/health`,
      {
        headers: {
          authorization: `Bearer ${config.UPSTREAM_BEARER_TOKEN}`
        },
        signal: AbortSignal.timeout(2000)
      }
    );

    if (!response.ok) {
      throw new Error(`Upstream returned ${response.status}`);
    }
  } catch (error) {
    app.log.error({ err: error }, "Readiness check failed");
    return reply.code(503).send({ status: "not_ready" });
  }

  return { status: "ready" };
});

app.post("/mcp", { preHandler: app.authenticate }, async (request, reply) => {
  const rawBody = JSON.stringify(request.body);
  let parsed: unknown;

  try {
    parsed = JSON.parse(rawBody);
  } catch {
    return reply.code(400).send({
      jsonrpc: "2.0",
      id: null,
      error: { code: -32700, message: "Parse error" }
    });
  }

  const subject = {
    sub: request.user.sub as string,
    scopes: String(request.user.scope ?? "").split(" ").filter(Boolean)
  };

  const candidate = parsed as { method?: unknown; params?: unknown };

  if (candidate.method === "tools/call") {
    const result = toolCallSchema.safeParse(parsed);

    if (!result.success) {
      return reply.code(400).send({
        jsonrpc: "2.0",
        id: null,
        error: {
          code: -32602,
          message: "Invalid tools/call parameters"
        }
      });
    }

    const decision = authorizeToolCall(subject, result.data);

    app.log.info(
      {
        subject: subject.sub,
        tool: result.data.params.name,
        allowed: decision.allowed,
        reason: decision.reason
      },
      "Tool authorization evaluated"
    );

    if (!decision.allowed) {
      return reply.code(403).send({
        jsonrpc: "2.0",
        id: (parsed as { id?: unknown }).id ?? null,
        error: {
          code: -32001,\n          message: "Tool call denied by gateway policy",
          data: { reason: decision.reason }
        }
      });
    }
  }

  const upstream = new HttpUpstreamClient(
    config.UPSTREAM_BASE_URL,
    config.UPSTREAM_BEARER_TOKEN
  );

  const startedAt = performance.now();
  const response = await upstream.forward({
    body: rawBody,
    sessionId: request.headers["mcp-session-id"] as string | undefined,
    accept:
      (request.headers.accept as string | undefined) ??
      "application/json, text/event-stream"
  });

  const sessionId = response.headers.get("mcp-session-id");
  if (sessionId) {
    reply.header("mcp-session-id", sessionId);
  }

  const contentType = response.headers.get("content-type");
  if (contentType) {
    reply.header("content-type", contentType);
  }

  reply.code(response.status);

  app.log.info(
    {
      subject: subject.sub,
      status: response.status,
      durationMs: Math.round(performance.now() - startedAt)
    },
    "MCP request proxied"
  );

  if (!response.body) {
    return reply.send();
  }

  return reply.send(Readable.fromWeb(response.body as never));
});

await app.listen({ port: config.PORT, host: "0.0.0.0" });
Enter fullscreen mode Exit fullscreen mode

Import Readable from Node's stream module:

import { Readable } from "node:stream";
Enter fullscreen mode Exit fullscreen mode

One important detail is the Accept header. MCP Streamable HTTP clients commonly expect both media types:

Accept: application/json, text/event-stream
Enter fullscreen mode Exit fullscreen mode

The gateway forwards the client's accepted media types and preserves the upstream response's Content-Type. If the upstream returns text/event-stream, the body must be streamed rather than parsed and re-encoded as JSON.

5. Add Authentication and Authorization

Authentication and authorization solve different problems:

  • Authentication establishes who the caller is.
  • Authorization establishes what that caller may do.

The gateway validates an external JWT against the identity provider's JWKS. The jose library caches signing keys and refreshes them when an unknown key appears, avoiding a JWKS request for every tool call.

OAuth resource-server metadata

An OAuth-protected MCP server should advertise where clients can obtain authorization information. Add src/metadata.ts and mount it at /.well-known/oauth-protected-resource:

import type { FastifyInstance } from "fastify";

export function registerOAuthMetadata(
  app: FastifyInstance,
  publicIssuerUrl: string
): void {
  app.get("/.well-known/oauth-protected-resource", async () => ({
    resource: publicIssuerUrl,
    authorization_servers: [publicIssuerUrl],
    scopes_supported: ["mcp:read", "issues:write"],
    bearer_methods_supported: ["header"]
  }));
}
Enter fullscreen mode Exit fullscreen mode

Register it in server.ts:

import { registerOAuthMetadata } from "./metadata.js";

registerOAuthMetadata(app, "https://mcp.example.com");
Enter fullscreen mode Exit fullscreen mode

The resource identifier must match the audience configured for access tokens. Keep it stable across deployments; clients use it to bind tokens to the correct resource server.

Scope model

A minimal scope model might look like this:

Scope Allows
mcp:read Listing tools and reading repository content
issues:write Creating or modifying issues
admin:tools Administrative tool registration and policy changes

Do not use a single broad mcp:access scope if different clients or teams need different capabilities. Scopes should describe business capabilities, not UI roles.

Deny by default

The policy module uses an allowlist. A tool that is not explicitly registered is denied, even if the upstream server exposes it. This prevents a newly added upstream tool from becoming automatically available to every agent.

For production, load policy from a versioned configuration service or a database rather than recompiling the gateway for every change. Keep policy decisions auditable:

{
  "timestamp": "2026-03-18T10:22:41.031Z",
  "level": 30,
  "subject": "user_123",
  "tool": "create_issue",
  "allowed": false,
  "reason": "The 'issues:write' scope is required"
}
Enter fullscreen mode Exit fullscreen mode

Avoid logging raw tool arguments by default. They may contain source code, prompts, tokens, or personal information. Record argument metadata or hashes instead.

6. Connect VS Code

Visual Studio Code's MCP integration can connect to a remote Streamable HTTP server. The exact settings interface varies by release, so use the built-in MCP configuration file rather than relying on a particular UI layout.

Open the user-level MCP configuration, commonly named mcp.json, and add:

{
  "servers": {
    "secure-github": {
      "type": "http",
      "url": "https://mcp.example.com/mcp"
    }
  }
}\n```
{% endraw %}


When the server requires OAuth, the client should detect the authentication challenge and initiate the authorization flow. If your client version requires explicit headers, use a local development token only:
{% raw %}


```json
{
  "servers": {
    "secure-github": {
      "type": "http",
      "url": "https://mcp.example.com/mcp",
      "headers": {
        "Authorization": "Bearer ${input:githubMcpToken}"
      }
    }
  }
}\n```
{% endraw %}


The {% raw %}`${input:...}`{% endraw %} syntax prompts the user for a value. It does not eliminate the need for secure storage or token rotation.

For a local test, start the gateway and a mock upstream server:
{% raw %}


```bash
npm run dev
Enter fullscreen mode Exit fullscreen mode

Then test initialization with a valid token:

curl -i http://127.0.0.1:8080/mcp \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  --data '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2025-03-26",
      "capabilities": {},
      "clientInfo": {
        "name": "curl",
        "version": "1.0.0"
      }
    }
  }'
Enter fullscreen mode Exit fullscreen mode

A successful response may include a session header:

HTTP/1.1 200 OK
Content-Type: text/event-stream
Mcp-Session-Id: 01JXYZ...
Enter fullscreen mode Exit fullscreen mode

The client must include that session identifier in subsequent requests for the same session.

7. Connect a Browser Agent

Browser-based agents introduce two additional concerns: credential storage and cross-origin access.

Recommended approach

Use Authorization Code with PKCE:

  1. The browser agent redirects the user to the identity provider.
  2. The provider authenticates the user and redirects back with an authorization code.
  3. The agent exchanges the code for an access token using a PKCE verifier.
  4. The agent sends the access token as a bearer token to the gateway.

Do not place access tokens in URLs, query strings, or local storage if you can avoid it. For highly sensitive applications, prefer a backend-for-frontend pattern in which the browser talks to a session-aware backend and the backend calls the gateway.

A browser client can use the Fetch API directly:\n

export async function initializeMcpSession(
  endpoint: string,
  accessToken: string
): Promise<{ sessionId: string | null; response: Response }> {
  const response = await fetch(endpoint, {
    method: "POST",
    headers: {
      authorization: `Bearer ${accessToken}`,
      "content-type": "application/json",
      accept: "application/json, text/event-stream"
    },
    body: JSON.stringify({
      jsonrpc: "2.0",
      id: 1,
      method: "initialize",
      params: {
        protocolVersion: "2025-03-26",
        capabilities: {},
        clientInfo: {
          name: "browser-agent",
          version: "1.0.0"
        }
      }
    })
  });

  if (!response.ok) {
    throw new Error(`MCP initialization failed: ${response.status}`);
  }

  return {
    sessionId: response.headers.get("mcp-session-id"),
    response
  };
}
Enter fullscreen mode Exit fullscreen mode

CORS

If the browser calls the gateway directly, configure CORS narrowly:

await app.register(
  async (instance) => {
    instance.addHook("onSend", async (_request, reply) => {
      reply.header("Access-Control-Allow-Origin", "https://agent.example.com");
      reply.header("Vary", "Origin");
      reply.header(
        "Access-Control-Allow-Headers",
        "Authorization, Content-Type, Accept, Mcp-Session-Id, MCP-Protocol-Version"
      );
      reply.header(
        "Access-Control-Expose-Headers",
        "Mcp-Session-Id, WWW-Authenticate"
      );
    });
  }
);
Enter fullscreen mode Exit fullscreen mode

Do not combine a specific origin with Access-Control-Allow-Credentials: true unless you validate the origin against an explicit allowlist. Never reflect arbitrary origins.

Browser security headers

The gateway should also send:

reply.header("X-Content-Type-Options", "nosniff");
reply.header("Referrer-Policy", "no-referrer");
reply.header("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'");
Enter fullscreen mode Exit fullscreen mode

These headers are particularly important when a response can contain agent-generated or upstream-provided content.

8. Deploy to Kubernetes

The gateway is stateless when it only proxies MCP requests and validates tokens. That makes horizontal scaling straightforward, with one caveat: MCP session affinity.

If an upstream MCP server stores session state, requests carrying the same Mcp-Session-Id must reach the same gateway instance. You have three options:

  1. Use a sticky-session service.
  2. Route sessions through a shared session store.
  3. Make the upstream server itself stateless.

For a first deployment, session affinity is usually the simplest correct choice.

Container image

Create Dockerfile:

FROM node:20-alpine AS build
WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY tsconfig.json ./
COPY src ./src
RUN npm run build

FROM node:20-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production

COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force

COPY --from=build /app/dist ./dist

USER node
EXPOSE 8080
CMD ["node", "dist/src/server.js"]
Enter fullscreen mode Exit fullscreen mode

Build and push the image:

docker build -t registry.example.com/platform/mcp-gateway:1.0.0 .
docker push registry.example.com/platform/mcp-gateway:1.0.0
Enter fullscreen mode Exit fullscreen mode

Deployment manifest

Create deploy/kubernetes.yaml:

apiVersion: v1
kind: Namespace
metadata:
  name: ai-platform
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: mcp-gateway
  namespace: ai-platform
---
apiVersion: v1
kind: Secret
metadata:
  name: mcp-gateway-secrets
  namespace: ai-platform
type: Opaque
stringData:
  UPSTREAM_BEARER_TOKEN: replace-with-secret-manager-value
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mcp-gateway
  namespace: ai-platform
spec:
  replicas: 3
  selector:
    matchLabels:
      app: mcp-gateway
  template:
    metadata:
      labels:
        app: mcp-gateway
    spec:
      serviceAccountName: mcp-gateway
      securityContext:
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: gateway
          image: registry.example.com/platform/mcp-gateway:1.0.0
          ports:
            - containerPort: 8080
          env:
            - name: PORT
              value: "8080"
            - name: LOG_LEVEL
              value: "info"
            - name: OIDC_ISSUER
              value: "https://your-tenant.example.com/"
            - name: OIDC_AUDIENCE
              value: "mcp-gateway"
            - name: OIDC_JWKS_URL
              value: "https://your-tenant.example.com/.well-known/jwks.json"
            - name: UPSTREAM_BASE_URL
              value: "http://mcp-upstream.ai-platform.svc.cluster.local:9090"
          envFrom:
            - secretRef:
                name: mcp-gateway-secrets
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: "1"
              memory: 512Mi
          readinessProbe:
            httpGet:
              path: /health/ready
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health/live
              port: 8080
            initialDelaySeconds: 10
            periodSeconds: 20
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
---
apiVersion: v1
kind: Service
metadata:
  name: mcp-gateway
  namespace: ai-platform
spec:
  selector:
    app: mcp-gateway
  ports:
    - name: http
      port: 80
      targetPort: http
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: mcp-gateway
  namespace: ai-platform
spec:
  minAvailable: 2
  selector:
    matchLabels:
      app: mcp-gateway
Enter fullscreen mode Exit fullscreen mode

The example Secret is suitable only as a placeholder. In production, inject credentials through a secret manager, an external-secrets operator, or a cloud-native CSI driver.

Apply the manifests:

kubectl apply -f deploy/kubernetes.yaml
kubectl -n ai-platform rollout status deployment/mcp-gateway
Enter fullscreen mode Exit fullscreen mode

Ingress and TLS

Expose the service through an ingress controller with TLS termination:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: mcp-gateway
  namespace: ai-platform
  annotations:
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - mcp.example.com
      secretName: mcp-gateway-tls
  rules:
    - host: mcp.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: mcp-gateway
                port:
                  name: http
Enter fullscreen mode Exit fullscreen mode

Long-running SSE responses require proxy timeouts larger than the expected stream duration. Also disable response buffering for the MCP route. If your ingress controller buffers responses, streaming tool output will appear delayed or broken.

Kubernetes-hosted coding agents

A coding agent running in the cluster can use the in-cluster service:

env:
  - name: MCP_GATEWAY_URL
    value: "http://mcp-gateway.ai-platform.svc.cluster.local/mcp"
  - name: MCP_GATEWAY_TOKEN
    valueFrom:
      secretKeyRef:
        name: agent-mcp-credentials
        key: token
Enter fullscreen mode Exit fullscreen mode

Prefer workload identity over a long-lived bearer token. With an identity-aware proxy or service mesh, the gateway can validate a projected service-account token and derive the caller identity from Kubernetes metadata.

If you use static tokens for service accounts, issue a separate token per agent workload and restrict it with a policy such as:

const serviceAccountPolicies: Record<string, string[]> = {
  "agent:code-review": ["mcp:read"],
  "agent:triage": ["mcp:read", "issues:write"]
};
Enter fullscreen mode Exit fullscreen mode

Do not give every workload the same token. Shared credentials destroy attribution and make revocation unnecessarily broad.

9. Add Observability and Operational Controls

An MCP gateway is a security boundary and an API gateway. Treat it like one.

Structured audit events

Emit a dedicated audit event for every tool call:

interface ToolAuditEvent {
  timestamp: string;
  requestId: string;
  subject: string;
  clientId?: string;
  tool: string;
  outcome: "allowed" | "denied" | "failed";
  durationMs: number;
  policyVersion: string;
}
Enter fullscreen mode Exit fullscreen mode

Include the request identifier in both application logs and upstream headers:

const requestId = request.id;
reply.header("x-request-id", requestId);
Enter fullscreen mode Exit fullscreen mode

The upstream can then correlate its logs with the gateway's decisions.

Metrics

At minimum, export:

  • Request count by tool and outcome
  • Latency histograms for gateway and upstream calls
  • Active MCP sessions
  • Authentication failures
  • Authorization denials
  • Upstream connection errors
  • Response body size
  • Rate-limit rejections

A Prometheus metric might look like this:

const toolCalls = new Counter({
  name: "mcp_gateway_tool_calls_total",
  help: "Total MCP tool calls",
  labelNames: ["tool", "outcome"]
});

toolCalls.inc({ tool: "create_issue", outcome: "denied" });
Enter fullscreen mode Exit fullscreen mode

Avoid using user identifiers or repository names as metric labels. High-cardinality labels can overwhelm the metrics backend.

Rate limiting

Rate limits should combine multiple dimensions:

per subject + per tool + per upstream
Enter fullscreen mode Exit fullscreen mode

A global IP limit is useful for abuse prevention, but it is not a substitute for per-user limits. In Kubernetes, multiple users may originate from the same ingress address, while one compromised agent may generate excessive traffic from a single identity.

Timeouts and cancellation

Long-running tool calls need explicit limits:

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 120_000);

try {
  const response = await fetch(upstreamUrl, {
    signal: controller.signal,
    // ...
  });
} finally {
  clearTimeout(timeout);
}
Enter fullscreen mode Exit fullscreen mode

Propagate client disconnects to the upstream request where possible. Otherwise, abandoned agent sessions can continue consuming provider API quota.

10. Production Hardening

A working gateway is not automatically a secure gateway. Apply the following controls before exposing it to real agents.

Enforce HTTPS everywhere

Terminate TLS at the ingress or service mesh, and use HTTPS for upstream connections. Never send bearer tokens over plaintext HTTP, even inside a supposedly private network.

Validate MCP protocol details

The gateway should validate:

  • The MCP-Protocol-Version header on requests when required by the negotiated protocol version
  • Request size and JSON-RPC structure
  • Session identifier format and ownership
  • Tool names against an allowlist
  • Tool arguments against a schema before forwarding

Argument validation is particularly important. A policy that allows get_file_contents is insufficient if the tool accepts arbitrary paths. Validate path boundaries, repository identifiers, and parameter types.

Bind sessions to callers

An MCP session identifier is a bearer-like capability. If one client learns another client's session ID, it may be able to reuse that session.

Store a mapping in a shared store:

interface SessionRecord {
  sessionId: string;
  subject: string;
  upstreamSessionId: string;
  createdAt: number;
  expiresAt: number;
}
Enter fullscreen mode Exit fullscreen mode

On every request, compare the authenticated subject with session.subject. Reject mismatches with 403 Forbidden.

Avoid open redirects and SSRF

If upstream URLs are configurable, validate them against an allowlist. Do not let a request parameter select an arbitrary destination:

const allowedUpstreams = new Set([
  "https://github-mcp.internal.example.com",
  "https://jira-mcp.internal.example.com"
]);

if (!allowedUpstreams.has(candidateUrl)) {
  throw new Error("Upstream is not registered");
}
Enter fullscreen mode Exit fullscreen mode

This prevents an attacker from using the gateway as an internal proxy.

Protect secrets

  • Store upstream credentials in a secret manager.
  • Rotate them independently of gateway deployments.
  • Prefer short-lived credentials and workload identity.
  • Never log authorization headers.
  • Redact known secret patterns before logging.
  • Separate development and production identity providers.

Control prompt injection exposure

An MCP gateway cannot determine whether a tool result contains malicious instructions. It can reduce blast radius:

  • Expose read-only tools by default.
  • Require additional approval for destructive operations.
  • Restrict tool arguments to approved repositories and paths.
  • Return structured, typed results instead of arbitrary HTML.
  • Record the source and content hash of tool results for investigation.

For high-risk operations, require a human approval token or an out-of-band confirmation rather than relying on the agent's own judgment.

Apply egress restrictions

The gateway and upstream servers should have explicit network policies. A coding agent should not be able to reach arbitrary internal services:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: mcp-gateway-egress
  namespace: ai-platform
spec:
  podSelector:
    matchLabels:
      app: mcp-gateway
  policyTypes:
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: mcp-upstream
      ports:
        - protocol: TCP
          port: 9090
    - to:
        - namespaceSelector:
            matchLabels:
              name: external-services
      ports:
        - protocol: TCP
          port: 443
Enter fullscreen mode Exit fullscreen mode

Maintain an explicit deprecation policy

Clients and servers evolve independently. Test the gateway against supported MCP protocol versions, publish a compatibility matrix, and reject unsupported versions explicitly instead of forwarding ambiguous requests.

11. Verify the End-to-End Flow

A useful gateway test suite should cover protocol behavior, security boundaries, and failure modes.

Create test/policy.test.ts:

import { describe, expect, it } from "vitest";
import { authorizeToolCall } from "../src/policy.js";

describe("authorizeToolCall", () => {
  it("allows a registered read tool", () => {
    const decision = authorizeToolCall(
      { sub: "user-1", scopes: ["mcp:read"] },
      {
        method: "tools/call",
        params: {
          name: "get_file_contents",
          arguments: { path: "README.md" }
        }
      }
    );

    expect(decision.allowed).toBe(true);
  });

  it("denies an unregistered tool", () => {
    const decision = authorizeToolCall(
      { sub: "user-1", scopes: ["mcp:read", "issues:write"] },
      {
        method: "tools/call",
        params: {
          name: "delete_repository",
          arguments: {}
        }
      }
    );

    expect(decision.allowed).toBe(false);
  });

  it("denies a write tool without the required scope", () => {
    const decision = authorizeToolCall(
      { sub: "user-1", scopes: ["mcp:read"] },
      {
        method: "tools/call",
        params: {
          name: "create_issue",
          arguments: { title: "Example" }
        }
      }
    );

    expect(decision.allowed).toBe(false);
  });
});
Enter fullscreen mode Exit fullscreen mode

Run the tests:

npm test
Enter fullscreen mode Exit fullscreen mode

For an end-to-end check, verify these scenarios:

Scenario Expected result
Valid token, allowed tool Upstream response returned
Missing or expired token 401 with WWW-Authenticate
Valid token, forbidden tool 403 JSON-RPC error
Invalid tool arguments 400 JSON-RPC error
Session ID from another subject 403
Upstream timeout Bounded error, no hung request
Excessive request rate 429
SSE upstream response Streamed without buffering

One subtle failure mode deserves special attention: authorization must happen before upstream execution. If you forward first and inspect the response afterward, a denied tool may already have changed data. The gateway should parse and authorize the request before creating the upstream request.

Frequently Asked Questions

Should an MCP gateway be a separate service or a sidecar?

A separate service is usually better when multiple clients, teams, or agent workloads share the same tools. It centralizes policy, credentials, and audit logs. A sidecar is useful when an agent must access a tightly coupled local tool and the gateway's control plane is already centralized.

Can one gateway expose tools from multiple MCP servers?\n

Yes. Route each registered upstream server to a logical namespace, such as github.search_repositories or jira.create_issue. Keep upstream session state isolated and apply a consistent policy schema across servers. The implementation above proxies one upstream; production deployments should add an explicit registry mapping logical tool names to upstream servers.

Does MCP encryption replace the gateway's TLS and authorization?\n

No. Transport-level encryption protects data in transit; it does not decide which user may invoke which tool. MCP deployments still need authenticated identities, scoped authorization, and audit trails, especially when several clients share downstream credentials.

For broader background on agent infrastructure and platform design, explore Tamiz's Insights.

Top comments (0)