Skip to main content
Glama
wxsh-hub

mcp-gateway

by wxsh-hub

MCP Gateway

A secure middle layer for the MCP ecosystem — building a protective barrier between LLMs and tool servers

License: MIT Python 3.10+

What problem does it solve?

When an LLM Agent calls external tools through the MCP protocol, there are three core risks:

  1. Credential leakage — tool responses may contain sensitive information such as API Keys, Tokens, etc., exposed directly to the LLM context

  2. Privacy data leakage — user personal information (names, ID card numbers, bank card numbers) may be passed along the tool call chain

  3. Malicious tool injection — tool descriptions may hide prompt injection instructions that trick the Agent into performing dangerous operations

MCP Gateway acts as a proxy layer that intercepts all traffic and performs security filtering before requests/responses reach the Agent.

Related MCP server: MCP Security Gateway

Architecture Overview

┌─────────────┐      ┌──────────────────────────────────┐      ┌─────────────┐
│             │      │          MCP Gateway             │      │             │
│   LLM Agent │ ───► │  ┌──────────┐  ┌──────────────┐  │ ───► │  MCP Server │
│             │      │  │ Sanitize │  │   Plugin     │  │      │  (tools)    │
│             │ ◄─── │  │ Request  │  │   Pipeline   │  │ ◄─── │             │
└─────────────┘      │  └──────────┘  └──────────────┘  │      └─────────────┘
                     │         ▲               │         │
                     │         │    ┌──────────▼──┐      │
                     │         │    │  Sanitize   │      │
                     │         │    │  Response   │      │
                     │         │    └─────────────┘      │
                     └──────────────────────────────────┘

Core flow:

  • Request direction: Plugin Pipeline desensitizes parameters (e.g., removes PII, filters out injection instructions)

  • Response direction: applies Token masking and sensitive information filtering to tool return values

  • Startup phase: Security Scanner performs reputation assessment on all configured MCP Servers

Quick Start

Installation

git clone <your-repo-url>
cd mcp-gateway
pip install -e .

Optional dependencies:

pip install -e .[presidio]   # 启用 PII 检测(基于 Microsoft Presidio)

Minimal configuration

Create mcp.json in the project root directory:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
    }
  }
}

Startup

# 启用基础 Token 掩码
mcp-gateway -p basic

# 启用 Token 掩码 + PII 检测
mcp-gateway -p basic -p presidio

# 调试模式
LOGLEVEL=DEBUG mcp-gateway -p basic

Integration with Cursor / Claude Desktop

{
  "mcpServers": {
    "mcp-gateway": {
      "command": "mcp-gateway",
      "args": [
        "--mcp-json-path", "~/.cursor/mcp.json",
        "-p", "basic",
        "-p", "xetrack"
      ],
      "servers": {
        "filesystem": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
        }
      }
    }
  }
}
{
  "mcpServers": {
    "mcp-gateway": {
      "command": "<python-path>",
      "args": [
        "-m", "mcp_gateway.server",
        "--mcp-json-path", "<path-to-config>",
        "-p", "basic"
      ],
      "servers": {
        "filesystem": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
        }
      }
    }
  }
}

Security Capabilities

Token Masking (basic plugin)

Automatically detects and replaces sensitive credentials in responses, supporting 12 major cloud platform and developer tool secret formats:

Type

Example format

AWS Access Key

AKIA...

GitHub Token

ghp_..., gho_...

JWT Token

eyJ...

HuggingFace Token

hf_...

Microsoft Teams Webhook

*.webhook.office.com

mcp-gateway -p basic

PII Detection (presidio plugin)

Based on the Microsoft Presidio engine, it automatically identifies and anonymizes personally identifiable information in text:

  • Credit card numbers, IP addresses, email addresses

  • Phone numbers, SSNs (ID card numbers)

  • See Presidio documentation for more entity types

pip install -e .[presidio]
mcp-gateway -p presidio

Security Scanner (--scan)

Before startup, it performs reputation assessment and tool description analysis on all MCP Servers:

mcp-gateway --scan -p basic

Scan dimensions:

  • Reputation assessment — calculates a comprehensive score based on GitHub data (stars, forks, issue activity) and NPM download counts

  • Tool description scanning — detects hidden prompt injection instructions, sensitive file path references, and dangerous operation instructions

  • Automatic blocking — servers with a reputation score below the threshold (default: 30 points) are marked as blocked and blocked from loading.

Scan results are written to the configuration file:

{
  "servers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
      "blocked": "passed"
    }
  }
}

Status values: "passed" (safe) | "blocked" (blocked) | "skipped" (manually skipped) | null (not scanned)

Call Tracing

Xetrack Tracing Plugin

Records the full context of every tool invocation, supporting SQLite and DuckDB queries:

pip install xetrack
mcp-gateway -p xetrack

Environment variable configuration:

  • XETRACK_DB_PATH — SQLite database path

  • XETRACK_LOGS_PATH — log file directory

{
  "mcpServers": {
    "mcp-gateway": {
      "command": "mcp-gateway",
      "args": ["--mcp-json-path", "~/.cursor/mcp.json", "-p", "xetrack"],
      "env": {
        "XETRACK_DB_PATH": "tracing.db",
        "XETRACK_LOGS_PATH": "logs/"
      }
    }
  }
}

Query examples:

from xetrack import Reader
df = Reader("tracing.db").to_df()
-- DuckDB
INSTALL sqlite; LOAD sqlite; ATTACH 'tracing.db' (TYPE sqlite);
SELECT server_name, capability_name, content_text FROM db.events LIMIT 10;

Proxy Tools

The Gateway exposes two standardized tools to the LLM:

Tool

Description

get_metadata

Retrieves the capability list of all registered MCP Servers, helping the LLM choose the right tool

run_tool

Executes any MCP tool invocation through the Gateway, automatically applying request/response security processing

Plugin Development

The plugin system is based on the ABC base class + decorator registration pattern:

from mcp_gateway.plugins.base import GuardrailPlugin
from mcp_gateway.plugins.manager import register_plugin

@register_plugin
class MyPlugin(GuardrailPlugin):
    @property
    def name(self) -> str:
        return "my-plugin"

    def process_request(self, context):
        # 请求方向的处理逻辑
        return context.arguments

    def process_response(self, context, response):
        # 响应方向的处理逻辑
        return response

Plugins are automatically discovered and loaded via PluginManager, supporting bidirectional request/response interception.

Project Structure

mcp_gateway/
├── __init__.py              # 包入口
├── server.py                # MCP Server 生命周期管理
├── gateway.py               # 动态工具注册、CLI 参数解析
├── config.py                # 配置文件加载
├── sanitizers.py            # 请求/响应安全分发
├── plugins/
│   ├── base.py              # Plugin ABC 基类
│   ├── manager.py           # 插件发现、注册、Pipeline
│   ├── guardrails/
│   │   ├── basic.py         # Token 掩码插件
│   │   └── presidio.py      # PII 检测插件
│   └── tracing/
│       └── xetrack.py       # 调用追踪插件
├── security_scanner/
│   ├── scanner.py           # 扫描器主入口
│   ├── github_collector.py  # GitHub API 数据采集
│   ├── npm_collector.py     # NPM Registry 数据采集
│   ├── smithery_collector.py# Smithery 市场数据采集
│   ├── project_analyzer.py  # 综合信誉评分算法
│   └── tool_poisoning_analyzer.py  # 工具描述安全分析
└── tests/
    ├── test_sanitizers.py
    ├── test_tool_poisoning_analyzer.py
    ├── test_plugin_pipeline.py
    └── test_config.py

License

MIT

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    C
    maintenance
    Enables safe use of any MCP server by proxying and live-scanning all tool requests and responses, blocking or redacting poison descriptions, indirect prompt injection, malicious arguments, and unauthorized destinations.
    -
  • A
    license
    Not graded
    quality
    F
    maintenance
    Enables transparent security for any MCP server by intercepting tool calls, blocking prompt injection attempts, masking PII in responses, and writing immutable audit logs.
    1,667 npm
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    Enforces MCP security by proxying between AI agents and MCP servers, scanning tools and results for prompt injection, enforcing allow/deny policies, redacting sensitive arguments, and logging all traffic.
    248 PyPI
    MIT