Skip to main content
Glama

mcpgate

CI Stars Last commit License Go version

MCP servers exist everywhere. The production layer doesn't.

MCP (Model Context Protocol) servers are easy to write and easy to expose — and that's the problem. A raw MCP server has no authentication, no rate limiting, no caching, no circuit breaking, and no observability. Put one behind your product and the first abusive client, the first slow backend, or the first retry storm takes it down.

mcpgate is the production layer: a gateway that sits in front of your MCP servers and adds auth, per-key rate limits, response caching, circuit breakers, structured logs, and Prometheus metrics — without touching the servers themselves.

Fast: ~80µs overhead per tools/call in-process; ~4,000 QPS live against a mock backend at 10-way concurrency with zero errors. Method, environment, and full numbers in BENCHMARKS.md.

                    ┌─────────────────────────────────────────────┐
  MCP client ──────▶│  mcpgate                                    │
  (any MCP client)  │                                             │
                    │  ┌─────────┐  ┌──────────┐  ┌───────────┐  │
                    │  │ API key │─▶│ token    │─▶│ cache     │  │
                    │  │ auth    │  │ bucket   │  │ (TTL)     │  │
                    │  └─────────┘  └──────────┘  └─────┬─────┘  │
                    │  ┌───────────┐  ┌───────────┐     │        │
                    │  │ circuit   │─▶│ backend   │◀────┘        │
                    │  │ breaker   │  │ stdio /   │              │
                    │  └───────────┘  │ HTTP      │              │
                    │  /metrics /healthz /readyz └───────────┘   │
                    └─────────────────────────────────────────────┘
                                        │                │
                                   stdio child       Streamable HTTP
                                   MCP server        MCP server

Try it in 30 seconds

mcpgate demo: a 401 without an API key, cache MISS then HIT, a tools/call, rate-limit 429s, and /healthz plus /metrics

git clone https://github.com/sunwen1983/mcpgate && cd mcpgate
bash demo/demo.sh

The demo builds the gateway and an echo backend (needs Go 1.27+), then walks through five acts: a 401 without an API key, cache MISS then HIT, a tools/call, rate-limit 429s, and /healthz + /metrics. No config editing, no external services.

Related MCP server: mcp-streamable-http-bridge

Quickstart

Install

# Go 1.27+ — installs the latest release binary
go install github.com/sunwen1983/mcpgate/cmd/mcpgate@latest

# Or Docker — the image ships the gateway plus the echo demo backend,
# so it serves on :8080 with no config file of your own (demo key
# "demo-key-123" — rotate it for real use, as with the example config)
docker run --rm -p 8080:8080 ghcr.io/sunwen1983/mcpgate:main

For your own backends, mount a config file: -v $PWD/config.yaml:/app/config.yaml (and point it at your backends instead of the demo echo backend). Release binaries for Linux, macOS, and Windows are attached to every release.

# Build
go build -o mcpgate ./cmd/mcpgate
go build -o echo-backend ./examples/echo-backend

# Run (examples/config.yaml uses the demo key "demo-key-123" — rotate it)
./mcpgate -config examples/config.yaml

List tools through the gateway:

curl -X POST http://localhost:8080/mcp/echo \
  -H 'Content-Type: application/json' \
  -H 'X-API-Key: demo-key-123' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

Call a tool:

curl -X POST http://localhost:8080/mcp/echo \
  -H 'Content-Type: application/json' \
  -H 'X-API-Key: demo-key-123' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"add","arguments":{"a":2,"b":3}}}'
# {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"5"}]}}

Or run the full guided demo (auth failure, cache MISS/HIT, rate-limit 429s, health + metrics):

bash demo/demo.sh

Stdio mode

With -stdio, mcpgate itself runs as a stdio MCP server, aggregating every configured backend behind one stdin/stdout stream — for stdio-only clients (Claude Desktop, IDE extensions, MCP inspectors) and server directories:

./mcpgate -config examples/config.yaml -stdio

The gateway answers initialize/ping itself, merges all backends' tool lists into one tools/list (a tool name claimed by more than one backend is listed once — calls can only route to the first owner, in sorted backend-name order), and routes each tools/call to the backend that owns the tool. Per backend, the tool filter, circuit breaker, and response cache apply exactly as on the HTTP path. Two HTTP concerns do not apply: stdio is a local trust boundary, so there is no API-key auth or rate limiting — whoever can spawn the process already controls it. Logs go to stderr; stdout carries protocol traffic only.

How it works

POST /mcp/{backend} runs one JSON-RPC 2.0 request through this pipeline:

  1. Auth — X-API-Key header or Authorization: Bearer <key> for API keys; when oidc is configured, a Bearer JWT signed by the issuer is also accepted (identity oidc:<sub>); when oauth is configured, an opaque Bearer token is checked with the authorization server's introspection endpoint (identity oauth:<sub>). Missing/invalid credentials get 401. Key values and token contents are never logged.

  2. Rate limit — token bucket per API key. Exhausted buckets get 429 with a JSON-RPC error. Per-key overrides in config.

  3. Backend lookup — unknown backends get 404 / JSON-RPC -32601.

  4. Tool filter — a backend's tool_filter hides tools: denied tools are removed from tools/list results, and tools/call for a filtered tool is rejected with 403 / JSON-RPC -32602 before touching the backend, cache, or breaker. A backend's schema_rewrites also apply here: tools/list shows renamed/hidden arguments, and tools/call arguments are translated back to the backend's names before forwarding.

  5. Circuit breaker — an open breaker fails fast with 503 and never touches the backend. After the cooldown, one probe is allowed; success closes the breaker, failure re-opens it.

  6. Cache — tools/list responses are cached per backend. tools/call responses are cached only for tools explicitly listed in cacheable_tools, because tool calls can have side effects. Cache hits return X-Cache: HIT; the cached payload is re-wrapped with the current request's id, because JSON-RPC requires the response id to match. Operators can drop cached entries without restarting the gateway: POST /admin/cache/invalidate clears every backend's cache, POST /admin/cache/invalidate/{backend} clears one (API key required, answered with {"status":"ok","backends":[...],"cleared":N}). They can also reload the config without restarting: POST /admin/reload re-reads the config file, validates it with the same strict checks as startup, and applies the reloadable parts live — API keys, per-tool scopes, rate limits, and per-backend tool filters, schema rewrites, response rewrites, cache settings, breaker settings, health-check settings, a backend's connection identity (transport, command, URL, endpoints, auth, headers, timeout), and adding or removing a backend. A repointed backend gets a fresh client: the replacement is built first, so a build failure rejects the whole reload and the old client keeps serving; the new connection starts with a fresh breaker and an empty cache, and a request already in flight on the old connection may fail — the same as a restart would do to it, but scoped to that one backend. An added backend starts serving the same way; a removed backend is stopped and closed, and a request already in flight on it may fail the same way. Sending the process SIGHUP (kill -HUP <pid>) triggers the same reload, for operators without an API key; an invalid config is logged and ignored either way. Anything else (listen address, TLS, Redis, OIDC/OAuth endpoints) is reported in requires_restart and needs a restart; an invalid config is rejected whole with 400 and the running config keeps serving. GET /admin/status reports uptime, when the config was last loaded, the API key names, and every backend's breaker and health state (API key required; key values never appear in the response).

  7. Forward — the request goes to the backend (stdio child process or Streamable HTTP POST). Configured static headers are injected into HTTP backend requests. Transport failures return 502 and count toward the breaker. JSON-RPC error objects from the backend are forwarded verbatim and are not cached. A Streamable HTTP backend that answers with text/event-stream has its stream parsed incrementally: the JSON-RPC response matching the request id is returned as soon as its event arrives, instead of waiting for the stream to close. A tools/call result is rewritten per the backend's response_rewrites before it is cached and returned — on the single-response path and on the SSE stream alike (see "Response rewriting").

Clients that send Accept: text/event-stream get the backend's SSE events relayed live: progress notifications and other server messages arrive as data: events as the backend sends them, including notifications that arrive after the JSON-RPC response matching the request id — the stream stays open until the backend closes it, the client disconnects, or the per-request timeout fires. A failure after the response ends the stream quietly: the client already has its answer, so no error event is sent. Streaming responses are never cached, and the per-request timeout bounds the whole stream. A backend that cannot stream (stdio) answers with a single SSE event carrying the response. Clients that only accept JSON keep the single-response behavior.

Notifications (messages without an id) are forwarded to the backend fire-and-forget and the client gets 202 Accepted — the client asked for acceptance, not delivery confirmation, so a backend that can't be reached still gets a 202, and the failure is logged and counted instead of surfacing to the client. An open circuit breaker drops notifications without attempting the forward.

Configuration

mcpgate is configured with one YAML file. Minimal example:

listen: ":8080"

api_keys:
  - key: "demo-key-123"      # X-API-Key or Bearer token
    name: "demo"
default_rate_limit:
  requests_per_second: 10
  burst: 20

backends:
  - name: "echo"
    transport: "stdio"
    command: ["./echo-backend"]

The full reference — every field, with the annotated example config — lives in docs/configuration.md. The feature guides below explain what each part does: Per-tool authorization, Schema rewriting, Response rewriting, Backend health checks, Load balancing, Distributed rate limiting / shared cache (Redis), TLS termination.

Per-tool authorization (scopes)

tool_scopes gates individual tools behind OAuth-style scopes. A tool named there may be called only by a client holding at least one of its listed scopes; holding any one suffices. A gated tool is rejected on tools/call with a JSON-RPC -32602 error (HTTP 403) before the backend is touched, and hidden from tools/list for clients that lack a granting scope — exactly like the tool_filter deny list. Tools not named in tool_scopes stay open to any authenticated client, so adding the section never breaks existing callers.

Scopes come from the client's credential:

  • API keys: the scopes list on the key in config.

  • OIDC JWTs: the scope claim (space-delimited string) or the scp claim (array of strings).

  • OAuth2 introspected tokens: the scope claim from the introspection response.

Scope names are single tokens (no whitespace); a gated tool must list at least one scope — a tool nobody may call belongs in tool_filter.deny, not here. Scope filtering happens per request at output time, so a cached tools/list response never leaks one client's view of gated tools to another.

Schema rewriting

schema_rewrites reshapes one backend tool's input schema as clients see it, per backend:

backends:
  - name: "echo"
    schema_rewrites:
      - tool: "add"
        rename_arguments: {a: "first", b: "second"}
        hide_arguments: ["debug"]
  • Rename — the tool's inputSchema is exposed with the renamed arguments (in properties and in required), and a tools/call that passes the client-facing names is translated back to the backend's names before forwarding. Use it to present a consistent naming style across backends (e.g. a backend's snake_case arguments as camelCase), or to give a confusing argument a clearer name.

  • Hide — the argument disappears from the exposed schema, and a client that sends it anyway has it stripped from the call before forwarding. Use it for arguments clients should never set (an internal flag, a server-side default).

Tool names are never rewritten: the tool filter, per-tool authorization, and cache keys all keep using the backend's tool name. A rewrite may name an argument the backend does not expose — that part is simply a no-op, not an error. Renames must be unambiguous: two arguments may not rename to the same client-facing name, and a rename target may not also be a rename source (no chains). An argument may not be both renamed and hidden. Rewrites are static per backend, so a rewritten tools/list response is cached exactly like a filtered one, and the same rewriting applies on the HTTP path, the SSE stream, and stdio mode.

Do not hide an argument the backend requires unless the backend tolerates its absence: the gateway does not inject a value for it, so the call would fail at the backend.

Response rewriting

response_rewrites reshapes one backend tool's result payload as clients see it, per backend — the response-side mirror of schema_rewrites:

backends:
  - name: "echo"
    response_rewrites:
      - tool: "lookup"
        rename_fields: {user_id: "userId", user_name: "userName"}
        hide_fields: ["internal_id"]
  • Rename — the field appears under its client-facing name in the result. Use it to present a consistent naming style across backends (e.g. a backend's snake_case fields as camelCase), or to give a confusing field a clearer name.

  • Hide — the field disappears from the result. Use it for fields clients should never see (an internal id, a secret, a debug blob).

Rewriting applies to every JSON object in the result, at any depth — objects nested inside other objects, and objects inside arrays — in structuredContent and in any text content item whose text parses as JSON. Non-JSON text, image and resource content items pass through untouched, and a payload the rewrite does not change keeps its original text bytes (a rewrite never reformats a payload it does not touch). A rewrite may name a field the backend does not return — that part is simply a no-op, not an error. Renames must be unambiguous, with the same rules as schema rewrites: two fields may not rename to the same client-facing name, a rename target may not also be a rename source (no chains), and a field may not be both renamed and hidden. If a payload already contains a field with a rename target's name, the renamed value wins.

Rewrites are static per backend, so a rewritten tools/call response is cached exactly like an unrewritten one, and the same rewriting applies on the HTTP path, the SSE stream, and stdio mode. Like schema rewrites, response rewrites take effect on POST /admin/reload without a restart.

Backend health checks

The circuit breaker only learns a backend is down from real client traffic failing against it. Active health checks learn it sooner: when configured, the gateway probes the backend with a plain tools/list call — the lightest request that exercises exactly the path real traffic needs — and marks the backend unhealthy after a configurable number of consecutive failed probes. A probe fails on a transport error, a timeout, or a JSON-RPC error response.

backends:
  - name: "remote"
    transport: "http"
    url: "http://localhost:9000/mcp"
    health_check:
      interval: 30s           # 0 disables health checks (the default)
      timeout: 5s             # per-probe timeout (default 5s)
      failure_threshold: 3    # consecutive failed probes to mark unhealthy (default 3)

While a backend is unhealthy, requests to it fail fast with 503 (backend unavailable: health check failing) and notifications are dropped, instead of timing out against a backend that is already known to be down. One successful probe brings the backend back and traffic resumes automatically. A backend is healthy before its first probe, so enabling health checks never blocks startup, and probe failures never touch the circuit breaker — the breaker measures real traffic, health measures the backend, and the two signals stay independent. GET /readyz reports each backend's health (healthy, unhealthy, or disabled), and the mcpgate_backend_health gauge (1 healthy, 0 unhealthy) exposes it to Prometheus.

Load balancing

One backend name can front several identical endpoints: configure endpoints instead of a single url and requests spread across them. The pool is per backend name, so the breaker, cache, health checks, and SSE relay all keep seeing one logical backend; only the transport fans out.

backends:
  - name: "remote"
    transport: "http"
    endpoints:
      - "http://10.0.0.1:9000/mcp"
      - "http://10.0.0.2:9000/mcp"
    strategy: "round_robin"   # the default; may be omitted

Three strategies are available:

  • round_robin (the default) — endpoints take turns in order, skipping endpoints currently marked down.

  • weighted_round_robin — each endpoint gets traffic in proportion to its weights entry (same order as endpoints, each at least 1, default 1), using smooth weighted round-robin so a 2:1 pool serves a, b, a, a, b, a… instead of bursting. Use it when endpoints have unequal capacity — a bigger box gets a bigger weight.

  • least_connections — each request goes to the eligible endpoint with the fewest requests currently in flight, so a slow endpoint sheds load to faster ones; ties break in round-robin order. Calls, notifications, and open SSE streams all count as in flight until they finish or close.

backends:
  - name: "remote"
    transport: "http"
    endpoints:
      - "http://10.0.0.1:9000/mcp"
      - "http://10.0.0.2:9000/mcp"
    strategy: "weighted_round_robin"
    weights: [2, 1]   # 10.0.0.1 takes twice the traffic of 10.0.0.2

An endpoint that fails is taken out of rotation after 3 consecutive transport failures and tried again after a 30s cooldown; a success brings it straight back. JSON-RPC errors inside a well-formed response do not count — the endpoint answered. While every endpoint is down the pool degrades to plain round-robin over all of them instead of failing every request outright, so a recovered endpoint gets traffic again. A failed call is never retried on another endpoint: tools/call may have side effects, so retrying could execute the same call twice — the failed endpoint is skipped from the next request on. The mcpgate_backend_endpoints_healthy gauge reports how many endpoints of a backend are currently in rotation, and GET /readyz reports each endpoint's rotation state (up/down) under endpoints, so degraded redundancy is visible without Prometheus. Pooling is http-only (stdio backends are single processes); url and endpoints are mutually exclusive, and existing single-url configurations behave exactly as before.

Distributed rate limiting / shared cache (Redis)

By default each replica enforces its own per-key token budget, so a client can spend N× the limit against N replicas. Point the gateway at a shared Redis and every replica enforces one budget per key:

redis:
  addr: "localhost:6379"
  # password: "..."  # AUTH password; never logged
  # db: 0
  # key_prefix: "mcpgate:"  # namespace when Redis is shared with other apps

The bucket is a Lua script (atomic refill + consume), so concurrent replicas cannot overspend it; idle buckets expire once a full refill is guaranteed. Per-key rate_limit overrides and the default limit apply exactly as before — only the storage moves to Redis.

Failure behavior is availability-first: a Redis that is unreachable at startup logs a warning and the gateway falls back to in-process limiters and an in-process response cache until the next restart; a Redis error on a single request fails open (the request is allowed, a cache lookup misses) and is counted in mcpgate_rate_limit_errors_total / mcpgate_cache_errors_total.

The same redis: block also shares the response cache: with Redis configured, a cached tools/list or cacheable tools/call response is visible to every replica, and POST /admin/cache/invalidate clears the shared entries. Without Redis, caching stays in-process exactly as before. The cache keys are namespaced under <key_prefix>cache:, apart from the rate limiter's ratelimit: keys, so invalidation never touches token budgets.

TLS termination

By default the gateway serves plain HTTP — put a TLS-terminating reverse proxy in front of it. To terminate TLS in the gateway itself (direct HTTPS on the listen address, e.g. for a single-host deploy with no proxy), add a tls: block:

tls:
  cert_file: "tls/cert.pem"   # PEM chain, leaf first
  key_file: "tls/key.pem"     # PEM private key; never logged
  # min_version: "1.2"        # "1.2" (default) or "1.3"

The pair is loaded at startup, so a missing file, a mismatched key, or an unsupported min_version fails fast with a clear error instead of at first serve. Only the client-facing listener is affected — backends are reached exactly as configured, and the tls: block has no effect in stdio mode.

Observability

  • GET /healthz → {"status":"ok"} (liveness).

  • GET /readyz → {"status":"ready","backends":{"demo":"closed"},"health":{"demo":"healthy"},"endpoints":{"demo":{"http://10.0.0.1:9000/mcp":"up"}}} (readiness: per-backend circuit-breaker state and health-check state, plus pooled-endpoint rotation state under endpoints (up/down; only for backends with endpoints configured); 503 {"status":"degraded",...} when no backend can serve — use this for load-balancer health checks, not /healthz, which stays green while every backend is down). Endpoint state is informational: a pool with a down endpoint still serves through the healthy ones, so it does not by itself make the gateway degraded.

  • GET /metrics → Prometheus exposition:

Metric

Labels

Meaning

mcpgate_requests_total

backend, method, status

Requests by outcome (ok, rpc_error, backend_error, rejected)

mcpgate_request_duration_seconds

backend

Backend call latency histogram

mcpgate_cache_hits_total / mcpgate_cache_misses_total

backend, method

Cache behavior

mcpgate_cache_errors_total

—

Redis-backed cache operations that errored and failed open

mcpgate_backend_errors_total

backend

Transport failures

mcpgate_breaker_state

backend

0 closed, 1 half-open, 2 open

mcpgate_backend_health

backend

1 healthy, 0 unhealthy (only for backends with health checks enabled)

mcpgate_backend_endpoints_healthy

backend

Endpoints currently in rotation (only for backends with endpoints configured)

mcpgate_rate_limit_rejections_total

key_name

Rejected requests per API key name

mcpgate_rate_limit_errors_total

—

Redis-backed rate-limit checks that errored and failed open

mcpgate_notifications_total

backend, method, status

Notifications by outcome (forwarded, dropped, failed)

mcpgate_config_reloads_total

result

Config reload attempts by outcome (applied, rejected)

Logs are structured JSON (via log/slog) with request_id, api_key (name only), backend, method, cache outcome, and latency. Backend credentials and API key values never appear in logs.

Development

gofmt -l .          # must be clean
go build ./...
go vet ./...
go test ./...       # unit tests: rate limiter, cache, breaker, config,
                    # health checks, load balancing, backend transports (incl. stdio against echo-backend),
                    # gateway routing (auth, rate limit, cache, breaker, health, admin reload/status)

CI (GitHub Actions) runs format, build, vet, and test on every push/PR.

Roadmap — what's next

Everything in the sections above is shipped. What's still planned, in rough priority order:

  • Web console: a browser UI for the gateway — backends, breaker and health state, per-key traffic, cache controls — so operators can see and steer mcpgate without curl and Prometheus. (Next up after v0.3.)

  • Your idea: if the gateway is missing something for your setup, open an issue — that list drives the roadmap.

Shipped

  • SSE streaming (live relay): a client that sends Accept: text/event-stream gets the backend's SSE events relayed live, including notifications that arrive after the matching JSON-RPC response. (See "How it works".)

  • OAuth / OIDC: OIDC JWT bearer-token client auth (JWKS discovery, strict iss/aud/exp) and OAuth2 token introspection (RFC 7662), plus per-tool authorization via scopes. (See "Per-tool authorization".)

  • Request/response transformation: per-backend tool_filter, static header injection, per-tool schema rewriting, and response payload rewriting. (See "Schema rewriting" and "Response rewriting".)

  • Backend health checks / load balancing: active health checks with fast-fail 503s, and endpoint pools with round-robin, weighted round-robin, and least-connections strategies. (See "Backend health checks" and "Load balancing".)

  • Distributed rate limiting / shared cache: a redis: block shares one token budget per key and the response cache across replicas. (See "Distributed rate limiting / shared cache (Redis)".)

  • TLS termination: a tls: block serves HTTPS directly. (See "TLS termination".)

  • Admin API: POST /admin/cache/invalidate[/{backend}], POST /admin/reload (live config reload, or SIGHUP), and GET /admin/status. (See "How it works".)

Benchmarks

Measured gateway overhead, no tuning: ~80µs per tools/call in-process, ~4,000 QPS live against a mock backend at 10-way concurrency with zero errors. Method, environment, and full numbers in BENCHMARKS.md.

License

MIT. See LICENSE.

Available Tools

2 tools
addC

Add two numbers.

Inputs: a (required), b (required).

echoB

Return the input text unchanged.

Inputs: text (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.3/5.0

    Scored across 2 tools

    Disambiguation5/5

    echo and add target completely different operations (returning text vs arithmetic), so there is no risk of misselection. Each tool has a single, clearly distinct purpose.

    Naming Consistency5/5

    Both names are single lowercase verbs (echo, add), following a clean and predictable pattern. The convention is minimal but perfectly consistent.

    Tool Count3/5

    Two tools is very thin even for a gateway server; the surface feels like a demo rather than a functional set. It earns a borderline score rather than being egregiously mismatched.

    Completeness2/5

    There is no discernible domain to cover—echo and add are unrelated utility stubs with no lifecycle or workflow. This leaves significant gaps for almost any real use case.

    Maintenance

    ActivityActive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Aggregates multiple upstream MCP servers (stdio, streamable-http, sse, websocket) behind a single streamable-HTTP endpoint with declarative configuration, namespacing, filtering, and auto-reload.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Bridges stdio Model Context Protocol (MCP) servers to MCP Streamable HTTP behind a single gateway, enabling multi-tenant, multi-user deployment with per-tenant environment variables via HTTP headers.
      MIT
    • A
      license
      A
      quality
      A
      maintenance
      Self-hosted MCP gateway that registers upstream MCP servers and fronts them behind one governed Streamable HTTP endpoint: per-tool access control by caller API key, guardrails over tool arguments and results, rate limits, and usage logs. The same Rust gateway also proxies LLM and A2A agent traffic.
      1
      239
      Apache 2.0
    • A
      license
      Not graded
      quality
      B
      maintenance
      High-performance Go gateway and reverse proxy for Model Context Protocol servers with rate-limiting, authorization, and pay-per-result metering.
      33 npm
      15
      MIT

    Appeared in Searches