mcpgate
This MCP backend exposes two tools—echo and add—that can be listed and called through mcpgate.
List tools with
tools/listto discoverechoandadd.Echo text by calling
echowith a requiredtextstring; it returns the text unchanged.Add numbers by calling
addwith required numericaandb; it returns their sum.Use gateway features around these calls: API-key auth, per-key rate limits, caching where configured, circuit breaking, health checks, structured logs, and Prometheus metrics.
Accepts OIDC JWT bearer tokens as an alternative to API keys, validating them against an issuer's discovery document (/.well-known/openid-configuration) and JWKS with required audience and clock-skew checks, then using the token subject as the request identity.
Exposes gateway and per-backend telemetry in Prometheus exposition format at /metrics, including request counts by outcome, backend latency histograms, cache hit/miss counters, backend transport errors, circuit breaker state, and rate-limit rejections.
mcpgate
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/callin-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 serverTry it in 30 seconds

git clone https://github.com/sunwen1983/mcpgate && cd mcpgate
bash demo/demo.shThe 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:mainFor 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.yamlList 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.shStdio 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 -stdioThe 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:
Auth —
X-API-Keyheader orAuthorization: Bearer <key>for API keys; whenoidcis configured, a Bearer JWT signed by the issuer is also accepted (identityoidc:<sub>); whenoauthis configured, an opaque Bearer token is checked with the authorization server's introspection endpoint (identityoauth:<sub>). Missing/invalid credentials get401. Key values and token contents are never logged.Rate limit — token bucket per API key. Exhausted buckets get
429with a JSON-RPC error. Per-key overrides in config.Backend lookup — unknown backends get
404/ JSON-RPC-32601.Tool filter — a backend's
tool_filterhides tools: denied tools are removed fromtools/listresults, andtools/callfor a filtered tool is rejected with403/ JSON-RPC-32602before touching the backend, cache, or breaker. A backend'sschema_rewritesalso apply here:tools/listshows renamed/hidden arguments, andtools/callarguments are translated back to the backend's names before forwarding.Circuit breaker — an open breaker fails fast with
503and never touches the backend. After the cooldown, one probe is allowed; success closes the breaker, failure re-opens it.Cache —
tools/listresponses are cached per backend.tools/callresponses are cached only for tools explicitly listed incacheable_tools, because tool calls can have side effects. Cache hits returnX-Cache: HIT; the cached payload is re-wrapped with the current request'sid, because JSON-RPC requires the response id to match. Operators can drop cached entries without restarting the gateway:POST /admin/cache/invalidateclears 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/reloadre-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 processSIGHUP(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 inrequires_restartand needs a restart; an invalid config is rejected whole with400and the running config keeps serving.GET /admin/statusreports 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).Forward — the request goes to the backend (stdio child process or Streamable HTTP POST). Configured static
headersare injected into HTTP backend requests. Transport failures return502and count toward the breaker. JSON-RPC error objects from the backend are forwarded verbatim and are not cached. A Streamable HTTP backend that answers withtext/event-streamhas 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. Atools/callresult is rewritten per the backend'sresponse_rewritesbefore 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
scopeslist on the key in config.OIDC JWTs: the
scopeclaim (space-delimited string) or thescpclaim (array of strings).OAuth2 introspected tokens: the
scopeclaim 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
inputSchemais exposed with the renamed arguments (inpropertiesand inrequired), and atools/callthat 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'ssnake_casearguments ascamelCase), 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_casefields ascamelCase), 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 omittedThree 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 itsweightsentry (same order asendpoints, 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.2An 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 appsThe 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 underendpoints(up/down; only for backends withendpointsconfigured);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 |
| backend, method, status | Requests by outcome ( |
| backend | Backend call latency histogram |
| backend, method | Cache behavior |
| — | Redis-backed cache operations that errored and failed open |
| backend | Transport failures |
| backend |
|
| backend |
|
| backend | Endpoints currently in rotation (only for backends with |
| key_name | Rejected requests per API key name |
| — | Redis-backed rate-limit checks that errored and failed open |
| backend, method, status | Notifications by outcome ( |
| result | Config reload attempts by outcome ( |
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-streamgets 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, orSIGHUP), andGET /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 toolsTool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 2 tools
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.
Both names are single lowercase verbs (echo, add), following a clean and predictable pattern. The convention is minimal but perfectly consistent.
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.
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
Related MCP Connectors
Streamable HTTP MCP gateway for NV oOS fleets — one API key, namespaced tools, quotas and policy.
MCP Gateway: wrap any MCP server with cold-start retries, uptime SLA, and per-execution MPP billing.
REST-to-MCP for UK hospitality. Safety proxy: circuit-breakers, rate limits, whitelists. Apache 2.0.
Governed MCP gateway: one endpoint for your tools, with credential custody and audit log.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceAggregates multiple upstream MCP servers (stdio, streamable-http, sse, websocket) behind a single streamable-HTTP endpoint with declarative configuration, namespacing, filtering, and auto-reload.1MIT
- AlicenseNot gradedqualityDmaintenanceBridges 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

AISIX AI Gatewayofficial
AlicenseAqualityAmaintenanceSelf-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.1239Apache 2.0- AlicenseNot gradedqualityBmaintenanceHigh-performance Go gateway and reverse proxy for Model Context Protocol servers with rate-limiting, authorization, and pay-per-result metering.33 npm15MIT