Agent MCP Gateway

MCP serverAI & models

Your AI can find the right tool at the moment a task needs it, instead of loading every tool you have connected all at once. You can also decide which tools each helper agent is allowed to use. The app handles both, keeping the AI's working memory free for the actual work.

Unavailable. This server has no hosted endpoint yet, so ahel can't serve it.

After adding it, set which tools each helper agent should be able to use. Your AI will then find the tools it needs on its own as tasks come up.

What your AI can do with it

  • Find the right tool only when a task calls for it
  • Work across all of your connected tools without loading them all at once
  • Give each helper agent its own set of allowed tools
  • Keep the AI's working memory clear for the task at hand

From the project's README

As published by roddutra/agent-mcp-gateway in README.md.

A Model Context Protocol (MCP) gateway that aggregates multiple MCP servers and provides policy-based access control for agents and subagents. Solves Claude Code's MCP context window waste by enabling on-demand tool discovery instead of loading all tool definitions upfront.

Status

  • M0: Foundation - Configuration, policy engine, audit logging, list_servers tool
  • M1: Core - Proxy infrastructure, get_server_tools, execute_tool, middleware, metrics, hot reload, OAuth support
  • 🚧 M2: Production - HTTP transport, health checks (planned)
  • 🚧 M3: DX - Single-agent mode, config validation CLI, Docker (planned)

Current Version: M1-Core Complete (with OAuth)

Table of Contents

  • Overview
  • Installation
  • Quick Start
  • Command-Line Options
  • Configuration File Discovery
  • Configuration
  • Usage
  • Gateway Tools
  • Security Considerations
  • Troubleshooting
  • Testing
  • Development
  • Architecture
  • Future Features
  • Documentation
  • Contributing
  • License
  • Support
  • Acknowledgments

Overview

The Problem

When multiple MCP servers are configured in development environments (Claude Code, Cursor, VS Code), all tool definitions from all servers load into every agent's and subagent's context window at startup:

  • 5,000-50,000+ tokens consumed upfront
  • 80-95% of loaded tools never used by individual agents
  • Context needed for actual work gets wasted on unused tool definitions

The Solution

The Agent MCP Gateway acts as a single MCP server that proxies to multiple downstream MCP servers based on configurable per-agent rules:

  • 3 gateway tools load at startup (~2k tokens)
  • Agents discover and request specific tools on-demand
  • 90%+ context reduction
  • Policy-based access control per agent/subagent

How It Works

The gateway sits between agents and downstream MCP servers, exposing only 3 lightweight tools. When an agent needs specific functionality, it discovers available servers and tools through the gateway, which filters visibility based on policy rules - agents only see servers and tools they have access to. This reduces each agent's context window to only relevant tools, while the gateway handles proxying authorized requests to downstream servers.

View detailed diagram with examples → (includes downstream servers, tools, and gateway rules examples)

Key Features

  • On-Demand Tool Discovery - Load tool definitions only when needed
  • Per-Agent Access Control - Configure which servers/tools each agent can access
  • Easy Agent Integration - Simple template to add gateway support to any agent (see guide)
  • Deny-Before-Allow Policies - Explicit deny rules take precedence
  • Wildcard Support - Pattern matching for tool names (get_*, *_user)
  • Session Isolation - Concurrent requests don't interfere
  • Transparent Proxying - Downstream servers unaware of gateway
  • Audit Logging - All operations logged for monitoring
  • Performance Metrics - Track latency and error rates per agent/operation
  • Hot Configuration Reload - Update rules/servers without restart
  • Thread-Safe Operations - Safe concurrent access during reloads
  • Diagnostic Tools - Health monitoring via get_gateway_status (debug mode only)

Installation

# Creates ~/.config/agent-mcp-gateway/ with template configuration files
uvx agent-mcp-gateway --init

This generates two template files ready to customize:

  • mcp.json - Your downstream MCP servers (Brave, Postgres, etc.)
  • mcp-gateway-rules.json - Per-agent access policies (who can use which servers/tools)

For local development: See Development section.

Quick Start

1. Configure Gateway Files

After running uvx agent-mcp-gateway --init (see Installation), edit the generated template files:

# Define your downstream MCP servers
nano ~/.config/agent-mcp-gateway/.mcp.json

# Define agent access policies
nano ~/.config/agent-mcp-gateway/.mcp-gateway-rules.json

See Configuration section for detailed examples and Configuration File Discovery for alternative file locations.

2. Add Gateway to Your MCP Client

Claude Code CLI:

claude mcp add agent-mcp-gateway uvx agent-mcp-gateway

Manual configuration:

{
  "mcpServers": {
    "agent-mcp-gateway": {
      "command": "uvx",
      "args": ["agent-mcp-gateway"],
      "env": {
        "GATEWAY_MCP_CONFIG": "~/.config/agent-mcp-gateway/.mcp.json",
        "GATEWAY_RULES": "~/.config/agent-mcp-gateway/.mcp-gateway-rules.json",
        "GATEWAY_DEFAULT_AGENT": "developer"
      }
    }
  }
}

Note: The env variables are optional if using default config locations. See Environment Variables Reference for all options.

3. Configure Your Agents

The gateway's tool descriptions are self-documenting, but for proper access control you should configure how your agents identify themselves. Choose the approach that fits your use case:

Approach 1: Multi-Agent Mode (Recommended)

For different agents with different permissions, configure each agent to pass its identity.

Add this to your agent's system prompt (e.g., CLAUDE.md, .claude/agents/agent-name.md):

## MCP Gateway Access

**Available Tools (via agent-mcp-gateway):**

You have access to MCP servers through the agent-mcp-gateway. The specific servers and tools available to you are determined by the gateway's access control rules.

**Tool Discovery Process:**

When you need to use tools from downstream MCP servers:
1. Use `agent_id: "YOUR_AGENT_NAME"` in ALL gateway tool calls for proper access control
2. Call `list_servers` to discover which servers you have access to
3. Call `get_server_tools` with the specific server name to discover available tools
4. Use `execute_tool` to invoke tools with appropriate parameters
5. If you cannot access a tool you need, immediately notify the user

**Important:** Always include `agent_id: "YOUR_AGENT_NAME"` in your gateway tool calls. This ensures proper access control and audit logging.

Replace YOUR_AGENT_NAME with your agent's identifier (e.g., "researcher", "backend", "admin").

Examples: See .claude/agents/researcher.md and .claude/agents/mcp-developer.md for complete configuration examples.

Approach 2: Single-Agent Mode

For simpler setups where all agents should have the same permissions, or when using MCP clients without system prompt configuration (e.g., Claude Desktop), configure a default agent using either method:

Option A: Environment Variable

# Set in your MCP client configuration
export GATEWAY_DEFAULT_AGENT=developer

Note: The agent specified (e.g., "developer") must exist in your .mcp-gateway-rules.json file with appropriate permissions.

Option B: "default" Agent in Rules

{
  "agents": {
    "default": {
      "allow": {
        "servers": ["*"]
      }
    }
  },
  "defaults": {
    "deny_on_missing_agent": false
  }
}

Note: Allowing all servers ("servers": ["*"]) without specifying tool restrictions grants access to all tools on all servers.

With either approach, agents can omit agent_id in tool calls - the gateway uses your configured default agent automatically.

Command-Line Options

# Show version
agent-mcp-gateway --version

# Initialize config directory (first-time setup)
agent-mcp-gateway --init

# Enable debug mode (exposes get_gateway_status diagnostic tool)
agent-mcp-gateway --debug

# Show help
agent-mcp-gateway --help

Configuration File Discovery

The gateway searches for configuration files in this order:

MCP Server Config (.mcp.json)

  1. GATEWAY_MCP_CONFIG environment variable (if set)
  2. .mcp.json in current directory
  3. ~/.config/agent-mcp-gateway/.mcp.json (home directory)
  4. ./config/.mcp.json (fallback)

Gateway Rules (.mcp-gateway-rules.json)

  1. GATEWAY_RULES environment variable (if set)
  2. .mcp-gateway-rules.json in current directory
  3. ~/.config/agent-mcp-gateway/.mcp-gateway-rules.json (home directory)
  4. ./config/.mcp-gateway-rules.json (fallback)

Tip: Use agent-mcp-gateway --init to create the home directory configs on first run.

Configuration

The gateway requires two configuration files:

1. MCP Servers Configuration

File: mcp.json (searched in multiple locations)

Defines the downstream MCP servers the gateway will proxy to. Uses the standard MCP config format compatible with Claude Code and other coding agents:

{
  "mcpServers": {
    "brave-search": {
      "description": "Web search via Brave Search API",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-brave-search"],
      "env": {
        "BRAVE_API_KEY": "${BRAVE_API_KEY}"
      }
    },
    "postgres": {
      "description": "PostgreSQL database access and query execution",
      "command": "uvx",
      "args": ["mcp-server-postgres"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    },
    "remote-server": {
      "description": "Custom remote API integration",
      "url": "https://example.com/mcp",
      "transport": "http",
      "headers": {
        "Authorization": "Bearer ${API_TOKEN}"
      }
    }
  }
}

Server Descriptions (Recommended): Adding a description field to each server helps AI agents understand what each server provides and when to use it. Descriptions are always returned by list_servers, enabling agents to make informed decisions about which servers to query for tools. While optional, descriptions significantly improve agent tool discovery and decision-making.

Supported Transports:

  • stdio - Local servers via npx/uvx (specified with command + args)
  • http - Remote HTTP servers (specified with url)

Environment Variables:

  • Use ${VAR_NAME} syntax for environment variable substitution
  • Set variables before running: export BRAVE_API_KEY=your-key

Important - GUI Applications (Claude Desktop, etc.): If you use ${VAR_NAME} syntax in .mcp.json, note that macOS GUI applications run in isolated environments without access to your shell's environment variables. For Claude Desktop and similar apps, add API keys to the gateway's env object in your MCP client configuration:

{
  "mcpServers": {
    "agent-mcp-gateway": {
      "command": "uvx",
      "args": ["agent-mcp-gateway"],
      "env": {
        "BRAVE_API_KEY": "your-actual-key-here",
        "DATABASE_URL": "postgresql://...",
        "GATEWAY_DEFAULT_AGENT": "claude-desktop"
      }
    }
  }
}

(If you hardcode values directly in .mcp.json without ${VAR_NAME} syntax, this is not necessary.)

2. Gateway Rules Configuration

File: mcp-gateway-rules.json (searched in multiple locations)

Defines per-agent access policies using deny-before-allow precedence:

{
  "agents": {
    "researcher": {
      "allow": {
        "servers": ["brave-search", "context7"],
        "tools": {
          "brave-search": ["brave_web_search"]
        }
      }
    },
    "backend": {
      "allow": {
        "servers": ["postgres", "laravel-boost"],
        "tools": {
          "postgres": ["query", "list_tables", "list_schemas"],
          "laravel-boost": ["get_*", "list_*", "read_*", "database_*", "search_*"]
        }
      },
      "deny": {
        "tools": {
          "postgres": ["drop_*", "delete_*"],
          "laravel-boost": ["database_query", "tinker"]
        }
      }
    },
    "admin": {
      "allow": {
        "servers": ["*"],
        "tools": {
          "brave-search": ["brave_web_search"]
        }
      },
      "deny": {
        "servers": ["notion"],
        "tools": {
          "playwright": ["browser_type"]
        }
      }
    },
    "claude-desktop": {
      "allow": {
        "servers": ["context7", "brave-search", "notion", "playwright"]
      },
      "deny": {
        "tools": {
          "playwright": ["browser_type", "browser_close_all", "launch_*"]
        }
      }
    },
    "default": {
      "deny": {
        "servers": ["*"]
      }
    }
  },
  "defaults": {
    "deny_on_missing_agent": false
  }
}

Agent Examples Explained:

researcher - Demonstrates implicit grant + explicit allow:

  • brave-search: ONLY brave_web_search tool (explicit allow narrows access)
  • context7: ALL tools (implicit grant - server allowed, no tool rules specified)

backend - Demonstrates wildcard allows with deny-before-allow precedence:

  • postgres: ONLY query, list_tables, list_schemas (explicit allows); deny rules serve as safety net
  • laravel-boost: Wildcard allows (get_*, list_*, read_*, database_*, search_*) grant broad access, BUT database_query explicitly denied despite matching database_* wildcard (deny wins), and tinker blocked as safety measure

admin - Demonstrates server wildcard + mixed access patterns:

  • notion: DENIED (server-level deny overrides wildcard server allow)
  • brave-search: ONLY brave_web_search (explicit restriction on one server)
  • playwright: ALL tools EXCEPT browser_type (implicit grant with explicit deny)
  • All other servers: ALL tools (implicit grant - no tool rules specified)

claude-desktop - Demonstrates implicit grant with multiple deny types:

  • context7, brave-search, notion: ALL tools (implicit grant)
  • playwright: ALL tools EXCEPT browser_type, browser_close_all, and tools matching launch_* (implicit grant with explicit + wildcard denies)

default - Principle of least privilege:

  • Used as fallback when agent_id not provided and deny_on_missing_agent is false
  • Denies all servers by default; use GATEWAY_DEFAULT_AGENT environment variable to specify a different default agent

Policy Precedence Order:

  1. Explicit deny rules (highest priority)
  2. Wildcard deny rules
  3. Explicit allow rules
  4. Wildcard allow rules
  5. Implicit grant (if server allowed but no tool rules specified)
  6. Default policy (deny)

Implicit Grant Behavior:

  • If agent has server access and no allow.tools.{server} entry, all tools from that server are implicitly granted
  • allow.tools.{server} entries narrow access to specified tools only
  • deny.tools.{server} entries filter out specific tools (evaluated in steps 1-2)
  • Rules are server-specific and don't affect other servers

Configuration Flexibility:

  • Rules can reference servers not currently in .mcp.json
  • Undefined server references treated as warnings (not errors)
  • Allows keeping rules for temporarily removed servers
  • Hot reload applies changes immediately without restart

Wildcard Patterns:

  • * - Matches everything
  • get_* - Matches tools starting with "get_"
  • *_user - Matches tools ending with "_user"

Agent Naming:

  • Use hierarchical names: team.role (e.g., backend.database, frontend.ui)
  • Alphanumeric characters, hyphens, underscores, and dots allowed
  • Configure your agents to pass their identity: See Configure Your Agents

Configuration Validation

The gateway validates configurations at startup and during hot reload. Example output:

✓ Configuration loaded from .mcp.json
⚠ Warning: Agent 'researcher' references undefined server 'unknown-server'
ℹ These rules will be ignored until the server is added

Validation Behavior:

  • Structural errors (invalid JSON, missing required fields) → Fail startup/reload
  • Undefined server references → Log warnings, continue with valid rules
  • Policy conflicts → Deny-before-allow precedence resolves automatically

3. OAuth Support for Downstream Servers

OAuth-protected downstream servers (Notion, GitHub) are automatically supported via auto-detection when servers return HTTP 401. The gateway uses FastMCP's OAuth support to handle authentication flows transparently - browser opens once for initial authentication, then tokens are cached for future use. See OAuth User Guide for detailed setup and troubleshooting.

OAuth Limitations:

The gateway supports OAuth servers that implement Dynamic Client Registration (RFC 7591).

  • Supported: OAuth with auto-detection (e.g., Notion MCP)
  • Not Supported: OAuth with pre-registered apps (e.g., GitHub OAuth flow)
  • 💡 For GitHub MCP: Use Personal Access Token instead

GitHub MCP with PAT Example:

{
  "mcpServers": {
    "github": {
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": {
        "Authorization": "Bearer ${GITHUB_PAT}"
      }
    }
  }
}

For detailed OAuth setup and troubleshooting, see OAuth User Guide.

4. Environment Variables Reference

VariableDescriptionDefaultExample
GATEWAY_MCP_CONFIGPath to MCP servers configuration file.mcp.json, fallback: ./config/.mcp.jsonexport GATEWAY_MCP_CONFIG=./custom.json
GATEWAY_RULESPath to gateway rules configuration file.mcp-gateway-rules.json, fallback: ./config/.mcp-gateway-rules.jsonexport GATEWAY_RULES=~/.claude/rules.json
GATEWAY_DEFAULT_AGENTDefault agent identity when agent_id not provided (optional)Noneexport GATEWAY_DEFAULT_AGENT=developer
GATEWAY_DEBUGEnable debug mode to expose get_gateway_status toolfalseexport GATEWAY_DEBUG=true
GATEWAY_AUDIT_LOGPath to audit log file~/.cache/agent-mcp-gateway/logs/audit.jsonlexport GATEWAY_AUDIT_LOG=./audit.jsonl
GATEWAY_TRANSPORTTransport protocol (stdio or http)stdioexport GATEWAY_TRANSPORT=stdio
GATEWAY_INIT_STRATEGYInitialization strategy (eager or lazy)eagerexport GATEWAY_INIT_STRATEGY=eager

Note on GUI Applications: macOS GUI applications (Claude Desktop, etc.) run in isolated environments without access to shell environment variables. If using ${VAR_NAME} syntax in .mcp.json, add required API keys to the gateway's env object in your MCP client configuration.

Usage

The gateway runs automatically when your MCP client starts. See Quick Start for adding it to your MCP client configuration.

Custom configuration paths can be specified via environment variables in your MCP client config:

{
  "mcpServers": {
    "agent-mcp-gateway": {
      "command": "uvx",
      "args": ["agent-mcp-gateway"],
      "env": {
        "GATEWAY_MCP_CONFIG": "/path/to/custom-mcp.json",
        "GATEWAY_RULES": "/path/to/custom-rules.json"
      }
    }
  }
}

See Environment Variables Reference for all available options.

Startup Output

Loading MCP server configuration from: .mcp.json
Loading gateway rules from: .mcp-gateway-rules.json
Audit log will be written to: ~/.cache/agent-mcp-gateway/logs/audit.jsonl

Initializing proxy connections to downstream servers...
  - 2 proxy client(s) initialized
    * brave-search: ready
    * postgres: ready
  - Metrics collector initialized
  - Access control middleware registered

Agent MCP Gateway initialized successfully
  - 2 MCP server(s) configured
  - 3 agent(s) configured
  - Default policy: deny unknown agents
  - 3 gateway tools available: list_servers, get_server_tools, execute_tool
  (4 tools if GATEWAY_DEBUG=true: includes get_gateway_status)

Gateway is ready. Running with stdio transport...

Gateway Tools

The gateway exposes exactly 3 tools to agents. All tools accept an optional agent_id parameter for access control. When agent_id is not provided, the gateway uses a fallback chain to determine agent identity (see Agent Identity Modes).

For Agent Developers: To configure your agents to properly use these gateway tools with access control, see Configure Your Agents.

1. list_servers

Lists MCP servers available to the calling agent based on policy rules.

Parameters:

  • agent_id (string, optional) - Identifier of the agent making the request (see Agent Identity Modes)
  • include_metadata (boolean, optional) - Include technical details like transport, command, and url (default: false)

Returns:

[
  {
    "name": "brave-search",
    "description": "Web search via Brave Search API"
  },
  {
    "name": "postgres",
    "description": "PostgreSQL database access and query execution"
  }
]

With include_metadata=true:

[
  {
    "name": "brave-search",
    "description": "Web search via Brave Search API",
    "transport": "stdio",
    "command": "npx"
  },
  {
    "name": "postgres",
    "description": "PostgreSQL database access and query execution",
    "transport": "stdio",
    "command": "uvx"
  }
]

Note: Server descriptions are always included (when configured in .mcp.json) to help agents understand what each server provides. The include_metadata flag only controls whether technical details (transport, command, url) are included.

Example:

# Basic usage - returns names and descriptions
result = await client.call_tool("list_servers", {
    "agent_id": "researcher"
})

# With technical metadata
result = await client.call_tool("list_servers", {
    "agent_id": "researcher",
    "include_metadata": True
})

2. get_server_tools

Retrieves tool definitions from a specific MCP server, filtered by agent permissions.

Parameters:

  • agent_id (string, optional) - Identifier of the agent (see Agent Identity Modes)
  • server (string, required) - Name of the downstream MCP server
  • names (string, optional) - Comma-separated list of tool names (e.g., "tool1,tool2,tool3") or single tool name
  • pattern (string, optional) - Wildcard pattern for tool names (e.g., "get_*")
  • max_schema_tokens (integer, optional) - Token budget limit for schemas

Returns:

{
  "tools": [
    {
      "name": "brave_web_search",
      "description": "Search the web using Brave Search",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": {"type": "string"}
        },
        "required": ["query"]
      }
    }
  ],
  "server": "brave-search",
  "total_available": 5,
  "returned": 1,
  "tokens_used": 150
}

Example:

# Get all allowed tools
tools = await client.call_tool("get_server_tools", {
    "agent_id": "researcher",
    "server": "brave-search"
})

# Get specific tools by name (comma-separated)
tools = await client.call_tool("get_server_tools", {
    "agent_id": "researcher",
    "server": "brave-search",
    "names": "brave_web_search,brave_local_search"
})

# Get specific tools by pattern
tools = await client.call_tool("get_server_tools", {
    "agent_id": "backend",
    "server": "postgres",
    "pattern": "get_*"
})

Shortened here. Read the whole README on GitHub.

Signals

GitHub stars
41
Forks
5
Last commit
Dec 2025
Advanced
Delivery
agent-mcp-gateway MCP server → your ahel gateway (mcp.ahel.ai) → every connected AI client.
Catalog kind
mcp-server
Gateway key
io-github-roddutra-agent-mcp-gateway
Source
github.com/roddutra/agent-mcp-gateway