MCP Gateway
jadchene/mcp-gateway
Gateway MCP token-eficiente com ponto de entrada unificado
Ver no GitHubUm gateway leve do Model Context Protocol que oferece um ponto de entrada unificado para múltiplos serviços MCP downstream. Reduz consumo de tokens através de descoberta sob demanda e evita duplicação de configurações ao centralizar o gerenciamento de serviços MCP.
Instalação
npx convez-ai jadchene/mcp-gateway1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Gerenciar múltiplos agentes conectados a vários serviços MCP sem duplicação de config
- Reduzir consumo de tokens limitando a superfície de ferramentas exposta inicialmente
- Centralizar descoberta e roteamento dinâmico de serviços MCP com hot reload
Veredito

Uma solução pragmática para orquestração de múltiplos serviços MCP em ambientes multi-agente. Resolve problemas reais de escalabilidade e manutenção, com implementação sólida de hot reload e gerenciamento de ciclo de vida de processos.
README
A tradução para o português deste README ainda está na fila.
English | 简体中文
MCP Gateway
This project provides a lightweight Model Context Protocol (MCP) gateway for token-efficient, on-demand discovery and one unified entry point for multiple downstream services.
Instead of exposing every downstream MCP tool up front, the gateway keeps a small fixed tool surface and lets the client discover services, list tools for a specific service, fetch one tool schema when needed, and then forward the actual tool call.
Why Use This Gateway
This gateway is designed for a practical problem that appears quickly once you use multiple MCP services across multiple agents.
If every agent connects directly to every MCP service, two problems show up:
- The tool surface becomes too large.
- The MCP configuration becomes too repetitive.
1. Reduce token consumption
Many MCP services expose dozens or even hundreds of tools.
If an agent connects directly to several MCP services, the client often needs to expose or describe a very large tool inventory up front. That increases:
- prompt size
- tool discovery cost
- repeated schema/context overhead across sessions
This gateway avoids that by exposing a small fixed discovery interface instead of flattening every downstream tool into the initial tool list.
The normal flow becomes:
- list available services
- inspect tools for one selected service
- fetch schema for one selected tool
- call that tool
That means the model only sees the minimum amount of MCP metadata needed for the current task.
2. Provide one unified MCP entry point for multiple agents
Without a gateway, each agent usually needs its own MCP client configuration for multiple downstream services.
That quickly becomes hard to maintain:
- every agent config needs to be updated when services change
- command paths and environment variables are repeated
- secrets and local machine details are spread across multiple client configs
- different agents may drift out of sync over time
With this gateway, the downstream MCP pool is defined once in one config file, and every agent only needs to connect to the gateway itself.
That gives you a cleaner architecture:
- one MCP entry point for many services
- one place to add, remove, or update downstream MCP definitions
- one place to control what is exposed to agents
- less duplicated local configuration
- easier reuse across Codex, Claude Code, Gemini CLI, or other MCP-capable clients
In short, this gateway is useful when you want to treat multiple MCP services as a managed service pool rather than reconfiguring the same MCP stack separately for every agent.
Key Pillars
Token-Efficient Discovery
- Keep the public tool surface small and stable.
- Discover services first, then tools for one service, then schema for one tool.
- Avoid sending hundreds of downstream tools to the model at session start.
Stable Gateway Surface
- Expose a fixed gateway contract instead of dynamically flattening downstream tools.
- Return compact discovery payloads for service and tool enumeration.
- Forward downstream tool results directly to the caller for minimal wrapping.
Practical Operations
- Load a static service pool from JSON.
- Reload config automatically when the file changes.
- Stop removed, disabled, or replaced downstream processes during hot reload.
- Restart failed downstream processes up to 3 times before marking them unavailable.
- Preserve the last valid config snapshot when a reload fails.
Quick Start
Install globally
npm install -g @jadchene/mcp-gateway-service
Start the gateway:
mcp-gateway-service
With an explicit config path:
mcp-gateway-service --config ./config.json
Expose the same gateway over Streamable HTTP with CLI arguments:
mcp-gateway-service --config ./config.json --http --port 3100 --path /mcp
Use --json-response when the HTTP client expects stateless JSON-RPC responses directly from POST requests:
mcp-gateway-service --config ./config.json --http --port 3100 --json-response
Run from source
Create a local config.json from config.example.json, then start the gateway:
npm install
npm run dev
By default the gateway loads ./config.json.
Use --config <path> to override it for the current process. If --config is omitted, the gateway falls back to MCP_GATEWAY_CONFIG, then ./config.json.
Override it with:
$env:MCP_GATEWAY_CONFIG="config/gateway/config.json"
npm run dev
Version
mcp-gateway-service --version
Short form:
mcp-gateway-service -v
Configuration
The gateway supports stdio and Streamable HTTP downstream transports. Inbound Streamable HTTP is enabled only with CLI arguments, not with config.json, so stdio-based agents can safely share the same service-pool config without accidentally starting an HTTP listener.
A service is loaded only when enable is missing or set to true. If enable is set to false, the gateway skips that service entirely. During hot reload, disabling or removing a service also stops its existing downstream process if one is running.
logging.enableis optional and defaults tofalse.logging.pathis required only whenlogging.enableistrue.- When enabled, the gateway writes newline-delimited JSON logs to the configured file and never writes operational logs to MCP
stdoutorstderr. - Relative
logging.pathvalues are resolved from the config file directory. - Logging config supports hot reload, so changing
logging.enableorlogging.pathin the config file takes effect without restarting the gateway. enableis optional. When omitted, the gateway treats the service as enabled.cwdis optional. When omitted, the gateway uses its current working directory.envis optional.framingis optional. When omitted, the gateway trieslinefirst and thencontent-length.- HTTP downstream transports use
transport.type: "http"and a singletransport.url. transport.headerscan provide static headers for an HTTP downstream service.transport.enableJsonResponseenables stateless JSON response mode for an HTTP downstream service.
Config shape
{
"logging": {
"enable": false,
"path": "./logs/mcp-gateway.log"
},
"services": [
{
"serviceId": "demo-echo",
"enable": true,
"name": "Demo Echo Service",
"description": "Sample echo MCP service.",
"transport": {
"type": "stdio",
"command": "node",
"args": [
"--experimental-strip-types",
"examples/echo-service.ts"
]
}
},
{
"serviceId": "remote-http",
"enable": false,
"name": "Remote Streamable HTTP Service",
"description": "Example downstream MCP service over Streamable HTTP.",
"transport": {
"type": "http",
"url": "http://127.0.0.1:3200/mcp",
"headers": {
"Authorization": "Bearer replace-me"
},
"enableJsonResponse": false
}
}
]
}
Streamable HTTP notes
- The gateway uses one endpoint for both
GETandPOST. - Inbound HTTP is enabled only by the explicit
--httpCLI option, optionally with settings such as--port 3100 --path /mcp. - Passing
--port,--host,--path, or--json-responsewithout--httpdoes not start an HTTP listener. GET /mcpopens the SSE read channel and returns the session in theMcp-Session-Idheader.POST /mcpsends JSON-RPC messages. The preferred session binding is theMcp-Session-Idheader.- Query-string
sessionIdis accepted for compatibility, but new clients should use the header. - The
endpointSSE event advertises the single path, such as/mcp, without embedding the session id in the URL.
Public Gateway Tools
The gateway exposes a fixed set of discovery and routing tools:
gateway_list_servicesgateway_get_servicegateway_list_toolsgateway_get_tool_schemagateway_manage_servicegateway_call_tool
Response design
gateway_list_servicesreturns onlyserviceId,description, andavailable.gateway_list_toolsreturns onlynameanddescription; pass optionaltoolNameas a string or string array to filter names by substring.gateway_get_tool_schemareturns onlyinputSchemaandoutputSchema.gateway_manage_servicereturns onlyserviceId,action,enabled, andavailable.gateway_call_toolforwards the downstream MCP tool result directly without extra gateway metadata wrapping.
Default workflow vs diagnostics
- The default token-efficient workflow still uses four tools:
gateway_list_services,gateway_list_tools,gateway_get_tool_schema, andgateway_call_tool. gateway_get_serviceis primarily for diagnostics, such as checking recent service errors, connection state, protocol version, or downstream server info.gateway_manage_serviceis an operational tool for explicit service control, not part of the normal discovery flow.
gateway_manage_service
Use gateway_manage_service when you explicitly need to reconnect a service or persistently change its enabled state.
Input:
serviceId: logical service identifieraction: one ofreconnect,enable, ordisable
Action behavior:
reconnect: immediately tries to start and reinitialize the specified downstream MCP again. Use this when a service previously failed because its dependency was not ready, such as an IDE that was not open yet.enable: writesenable: trueto the config file for that service and triggers a reload.disable: writesenable: falseto the config file for that service and triggers a reload.
Important notes:
enableanddisableare persisted to the JSON config file. They are not session-only toggles.reconnectdoes not modify the config file. It only retries the current service lifecycle.
Recommended Client Workflow
For the best token efficiency, the MCP client should cache discovery results instead of repeatedly querying the gateway:
- Call
gateway_list_servicesonce at session start. - Call
gateway_list_tools(serviceId)only when a service is actually needed, optionally withtoolNameto narrow large tool lists by one or more keywords. - Call
gateway_get_tool_schema(serviceId, toolName)only before the first use of that tool. - Call
gateway_call_tool(...)for execution. - Use
gateway_get_serviceonly when diagnostics are explicitly needed. - Use
gateway_manage_serviceonly when a service must be reconnected or explicitly enabled/disabled. - Refresh discovery data only when a call fails, the config changes, or the client explicitly wants a refresh.
Skill Integration (Recommended)
This repository includes a public skill for agent frameworks that support skill loading:
- Skill path:
skills/mcp-gateway/SKILL.md
The skill focuses on:
- token-efficient discovery flow
- avoiding unnecessary schema/tool enumeration
- calling downstream tools through the minimal gateway contract
MCP Client Configuration
The examples below intentionally use relative config paths so they stay portable.
Codex
~/.codex/config.toml
[mcp_servers.gateway]
command = "mcp-gateway-service"
args = ["--config", "./config.json"]
Gemini CLI
~/.gemini/settings.json
{
"mcpServers": {
"gateway": {
"type": "stdio",
"command": "mcp-gateway-service",
"args": [
"--config",
"./config.json"
]
}
}
}
Claude Code
~/.claude.json
{
"mcpServers": {
"gateway": {
"type": "stdio",
"command": "mcp-gateway-service",
"args": [
"--config",
"./config.json"
]
}
}
}
Development Notes
- Repository-managed
config.jsonandconfig.example.jsonare examples only. - Copy
config.example.jsonto your own localconfig.jsonbefore running the gateway. - Keep real local configs and logs outside the repository.
- File logging is disabled by default so MCP startup stays quiet unless you explicitly enable it.
- Downstream output schema is returned only when the downstream service exposes it.
- Windows command resolution supports PowerShell shims such as
.ps1-backed command aliases. - On Windows, the gateway prefers
pwshfor.ps1shim resolution and execution, and automatically falls back topowershell.exewhenpwshis unavailable.
License
Released under the MIT License.