MCP Gateway E3d14811

MCP数据服务

提供方 PanosSalt

数据服务 stdio · 本地进程 OAuth 授权 社区 / 第三方 Claude DesktopClaude
查看接入方式

MCP Gateway是一个连接AI助手与数据库的安全网关,提供认证、访问控制和审计功能,支持多种数据库和文件系统操作。

一句话选型结论

按资料字段整理

MCP Gateway E3d14811 属于数据服务类 MCP 服务器,stdio · 本地进程,OAuth 授权,可直接接入 Claude Desktop、Claude,有可直接复制的远程端点配置。接入前先确认权限范围;涉及写入、删除或付款的操作,建议先在测试环境验证。

分类数据服务 传输方式stdio · 本地进程 鉴权OAuth 授权 部署方式支持远程部署
GitHub 星标 6 仓库热度,无公开仓库时显示未标注
工具数 12 暴露给模型的工具数量
资源 / 提示词 0 / 0 资源与提示词模板数量
维护方 社区 / 第三方 核验等级 仅资料核对

工具与能力

数据服务
数量来自来源目录的标注,具体工具清单以官方文档为准
工具数量12暴露给模型可调用的工具个数
资源数量0可读取的资源条目
提示词数量0内置提示词模板数量

能力标签

支持客户端

适用场景

数据库连接Python本地部署访问控制审计日志SQL查询文件系统访问

安装与配置

stdio · 本地进程 OAuth 授权
客户端在本机拉起子进程,数据不出本机
python3 -c "import secrets; print(secrets.token_hex(32))"

这条命令只是入口,具体启动参数请按官方文档补齐,不要直接照搬到别的服务器。

  1. 1
    准备运行环境

    确认你的客户端支持远程端点,并拿到服务地址。

  2. 2
    安装服务

    复制上面的安装命令执行;命令里带占位符的位置,换成自己的密钥或路径。

  3. 3
    写入客户端配置

    在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,让新配置生效。

  4. 4
    验证是否可用

    连接成功后客户端会列出约 12 个工具,随便调一个只读工具确认能返回结果。

典型使用场景

3 类
按分类与标签整理的常见用法,具体以官方文档为准
数据库查询

用自然语言查库、取数,不用手写 SQL。

数据同步与清洗

把多来源数据拉到一处做整理。

报表取数

按口径快速拉出统计结果。

选择建议

选之前先看这几条
按条目字段给出的判断,不替你决定用不用

值得选的地方

  • 资料标注 12 个工具,覆盖面较广,能满足多种调用。
  • 有现成的安装命令,不用自己找入口,照着跑就能起服务。
  • 已适配 Claude Desktop、Claude,换客户端不用重新研究配置。

先想清楚的地方

  • stdio 方式要求本地装好运行时(如 Node.js),换机器要重新装一遍。
  • 使用前要准备好OAuth 授权对应的凭据,并按最小权限配置。
  • 版本更新与行为细节以官方仓库为准。

更适合

  • 需要在数据服务场景里让模型直接调用外部能力的人。
  • 已经在用 Claude Desktop、Claude 的用户,接入路径最短。
  • 想先快速试一下、能接受在本地或自有环境跑服务的人。

不太适合

  • 完全不想在本地装环境的人。
  • 不方便管理密钥或第三方授权的人。
  • 需要厂商级 SLA 和技术支持的生产环境。

同类对比

6 个同类
同分类里挑最接近的几条,字段以各自详情页为准
MCP 服务器工具数传输方式部署方式安装命令最后核验
MCP Gateway E3d14811当前 12 stdio · 本地进程 支持远程部署 有 2026-05-17
Memory 9d25f64e 9 未标注 未标注 无 2026-05-17
Getzep MCP 9 stdio · 本地进程 本地部署 有 2026-05-17
anything-llm 未标注 stdio · 本地进程 本地部署 有 2026-04-11
Prisma MCP Server 未标注 stdio · 本地进程 本地部署 有 2026-05-17
Astr Bot 未标注 stdio · 本地进程 本地部署 有 2026-05-17

服务器档案

数据服务
字段来自项目仓库与公开索引,中文说明由本站标注
提供方PanosSalt上游标注的维护方 PanosSalt
分类数据服务本站按上游分类展示
连接方式stdio · 本地进程客户端在本机拉起子进程,数据不出本机
鉴权方式OAuth 授权远程服务建议用最小权限凭据
维护方社区 / 第三方核验等级 仅资料核对
包名 / 运行时未标注 · Python本地安装时用到的包标识与运行时
部署类型支持远程部署上游给出的部署形态
最近核验2026-05-17上游最后核验时间

详细介绍

41.0 KB
来自项目仓库与上游目录的原文,未做删改

MCP Gateway

The production platform for MCP tools.

Claude Desktop can connect to your internal tools — databases, filesystems, APIs, anything — through a single authenticated endpoint. You control who can use which tools, every action is logged, and no raw credentials ever leave your server.

Built-in tools: SQL query (Postgres, MySQL, SQLite, MSSQL), filesystem access.
Custom tools: plug in anything that implements the MCP tool interface.

> See it in action — short demo of Claude Desktop querying a database through MCP Gateway.

Table of Contents

  • Overview
  • Features
  • Architecture
  • Quick Start
  • Configuration
  • Authentication
  • API Reference
  • MCP Integration
  • Role-Based Access Control
  • Entra ID / SSO
  • Development
  • Troubleshooting
  • Security
  • Additional Documentation

Overview

MCP Gateway sits between AI assistants and your databases. It:

  1. Authenticates users via password login, Microsoft Entra ID (Azure AD), or API keys
  2. Enforces role-based access control (viewer / analyst / admin)
  3. Exposes databases as MCP tools that AI assistants can discover and call
  4. Translates natural language questions into SQL via Claude, executes queries, and summarizes results
  5. Logs all activity to a structured audit trail```
    Claude Desktop / mcp-remote
    │
    │ MCP over SSE (OAuth 2.1 + PKCE)
    ▼
    ┌─────────────────────────────────────────────────────────┐
    │ MCP Gateway │
    │ │
    │ ┌──────────┐ ┌──────────┐ ┌───────────────────────┐ │
    │ │ Auth / │ │ Admin │ │ MCP SSE Endpoint │ │
    │ │ OAuth │ │ UI │ │ /t/{slug}/mcp/sse │ │
    │ └──────────┘ └──────────┘ └───────────────────────┘ │
    │ │ │
    │ ┌──────────────────────────────────────┐│ │
    │ │ Tool Providers ││ │
    │ │ sql.py → get_schema / execute_sql ││ │
    │ └──────────────────────────────────────┘│ │
    └─────────────────────────────────────────┼───────────────┘
    │ Decrypted DSN
    ┌─────────────────────┼────────────────┐
    │ Your Databases │ │
    │ Postgres MySQL MSSQL SQLite │
    └──────────────────────────────────── ┘

---

## What you get out of the box

**For your organisation**
- One URL for Claude Desktop — users authenticate once, access everything they're allowed
- Microsoft Entra ID SSO — roles assigned automatically from Azure AD groups
- Full audit trail — every tool call, every query, every login, who did what and when

**For your tools**
- Drop any MCP tool into the gateway and it inherits auth, RBAC, and logging automatically
- Per-tool role overrides — restrict SQL execution to analysts, filesystem writes to admins
- Bundled: SQL tools (4 databases), filesystem tools (read, write, search, tree)

**For your security team**
- No credentials on employee machines
- Tenant isolation — org A cannot see org B's tools or data
- API keys for CI/CD, OAuth 2.1 + PKCE for human users

### Supported Databases

| Database | Driver | DSN Format |
|----------|--------|------------|
| PostgreSQL | psycopg2 | `postgresql://user:pass@host/db` |
| MySQL / MariaDB | PyMySQL | `mysql+pymysql://user:pass@host/db` |
| Microsoft SQL Server | pymssql | `mssql+pymssql://user:pass@host/db` |
| SQLite | Built-in | `sqlite:///path/to/file.db` |

### Filesystem Tools
- Sandboxed file read/write/search exposed as MCP tools
- Enabled via `FILESYSTEM_ALLOWED_DIRS` environment variable
- Read operations (analyst+): `fs_read_file`, `fs_list_directory`, `fs_directory_tree`, `fs_search_files`, `fs_get_file_info`
- Write operations (admin): `fs_write_file`, `fs_create_directory`, `fs_move_file`

### Admin UI
- Web interface served at `/admin/`
- Manage connections, users, SSO config, API keys, and tool roles
- View audit logs, generated SQL, and query results

---

## Architecture

### Technology Stack

| Layer | Technology | Version |
|-------|-----------|---------|
| API Framework | FastAPI + Starlette | 0.136.1 / 1.3.1 |
| ASGI Server | Uvicorn | 0.34.0 |
| Validation | Pydantic + pydantic-settings | 2.12.5 / 2.7.1 |
| ORM | SQLAlchemy | 2.0.30 |
| Migrations | Alembic | 1.13.1 |
| Auth / JWT | PyJWT + bcrypt | 2.14.0 / 4.0.1 |
| Encryption | cryptography (Fernet) | 50.0.0 |
| LLM | Anthropic SDK | 0.42.0 |
| MCP Protocol | mcp | 1.28.1 |
| SQL Validation | sqlglot | 25.1.0 |
| Rate Limiting | slowapi | 0.1.9 |
| HTTP Client | httpx | 0.28.1 |
| DB Drivers | psycopg2-binary / PyMySQL / pymssql | 2.9.10 / 1.1.1 / 2.3.1 |
| Frontend | React 18 + TypeScript + Vite | — |

Dev tooling (`requirements-dev.txt`): pytest, pytest-asyncio, ruff, mypy.
The pinned versions above are generated from `requirements.txt` — update both together.

### Project Structure```
app/
├── main.py               # FastAPI app setup, middleware, routing
├── config.py             # Environment config (Pydantic Settings)
├── database.py           # SQLAlchemy engine + session factory
├── api/
│   ├── auth.py           # POST /auth/login
│   ├── auth_entra.py     # Entra SSO (legacy admin UI paths)
│   ├── oauth.py          # OAuth 2.1 endpoints (/t/{slug}/oauth/*)
│   ├── connections.py    # DB connection CRUD
│   ├── query.py          # Natural language query endpoint
│   ├── tenants.py        # Tenant + user management
│   ├── tools.py          # Tool listing + role overrides
│   ├── mcp_sse.py        # MCP SSE transport
│   ├── api_keys.py       # API key management
│   └── audit_logs.py     # GET /audit-logs/ (admin)
├── core/
│   ├── auth.py           # JWT creation/validation, password hashing
│   ├── dependencies.py   # FastAPI dependency injection
│   ├── rbac.py           # Role hierarchy helpers
│   ├── security.py       # Fernet encrypt/decrypt
│   ├── api_keys.py       # API key generation + hashing
│   ├── limiter.py        # slowapi rate limiter setup
│   └── log_filter.py     # Health-check log noise filter
├── constants.py          # Non-tunable application-wide constants (pagination caps, etc.)
├── models/__init__.py    # All SQLAlchemy ORM models
├── schemas/__init__.py   # All Pydantic request/response schemas
├── services/
│   ├── entra.py          # Microsoft Graph API client
│   ├── llm.py            # Anthropic API (SQL gen + summarization)
│   ├── mcp_client.py     # Direct SQLAlchemy schema introspection + query execution
│   └── audit.py          # Audit log writer
└── tools/
    ├── __init__.py       # Tool provider framework + registry
    ├── sql.py            # DB schema + execute_sql tools
    ├── example.py        # Example custom tools
    └── filesystem.py     # Sandboxed file read/write/search tools

app/static/               # Built admin UI, served at /admin/ (generated by the
                          # frontend build; not edited by hand)

frontend/src/
├── main.tsx              # Vite entry point
├── App.tsx               # Root component, auth context, tab routing
├── api.ts                # API client, token management
├── types.ts              # TypeScript types (mirrors Pydantic schemas)
├── constants.ts          # Frontend constants (timeouts, retry config)
├── app.css               # Global styles
├── hooks/
│   └── useForm.ts        # Shared form state helper
└── components/
    ├── Login.tsx          # Sign-in form
    ├── Setup.tsx          # Tenant registration
    ├── Dashboard.tsx      # Tenant info + role display
    ├── Connections.tsx    # DB connection management
    ├── ConnectionCreateForm.tsx  # Add-connection form
    ├── ConnectionEditRow.tsx     # Inline connection editor
    ├── Query.tsx          # Natural language query UI
    ├── Users.tsx          # User management (admin)
    ├── SsoConfig.tsx      # Entra ID configuration (admin)
    ├── Tools.tsx          # Tool browser + role overrides
    ├── ToolGroup.tsx      # Grouped tool listing
    ├── ToolRoleOverride.tsx      # Per-tool role control
    ├── ApiKeys.tsx        # API key management
    ├── AuditLog.tsx       # Filterable audit log viewer (admin)
    ├── AuditLogFilters.tsx       # Audit log filter controls
    ├── AuditLogDetail.tsx        # Single audit entry detail
    ├── ConfirmModal.tsx   # Reusable confirmation dialog
    └── ErrorBoundary.tsx  # Top-level error boundary

alembic/versions/         # Database migrations
docs/                     # Guides (OAuth flow, deployment, audit logging, …)
tests/                    # pytest suite (SQLite in-memory, no services needed)

Database Schema```

Tenants ─┬─► Users ──────► APIKeys
├─► APIKeys (also a direct tenant_id FK, not only via Users)
├─► DBConnections
├─► TenantEntraConfig
├─► AuditLogs (tenant_id and user_id both nullable)
├─► OAuthAuthorizationCodes
├─► OAuthRefreshTokens
└─► ToolRoleOverrides

OAuthStates (no tenant_id FK — holds a plain
tenant_slug string, since the row is
created before the tenant is resolved)


---

## Quick Start

### Prerequisites

- Docker and Docker Compose
- An Anthropic API key (for the `/query/` endpoint; not needed for raw MCP tool access)

### 1. Clone and configure```bash
git clone <repo-url>
cd MCP-Gateway
cp .env.example .env

Edit .env:```bash

Required — generate unique values

SECRET_KEY=<random 64-char string>
ENCRYPTION_KEY=<random string, min 32 chars — longer is better>
POSTGRES_PASSWORD=<strong password>

Required for natural language query

ANTHROPIC_API_KEY=sk-ant-...

Update to your server's public URL in production

BASE_URL=http://localhost:8000


Generate secure random values:```bash
# SECRET_KEY
python3 -c &quot;import secrets; print(secrets.token_hex(32))&quot;

# ENCRYPTION_KEY (min 32 chars; full key consumed via BLAKE2b derivation)
python3 -c &quot;import secrets; print(secrets.token_hex(32))&quot;

2. Start the stack```bash

docker compose up -d


Services started:
- `api` on port **8000** (FastAPI + admin UI)
- `db` on port 5432 (PostgreSQL, internal only)

### 3. Register your first tenant```bash
curl -s -X POST http://localhost:8000/tenants/ \
  -H &quot;Content-Type: application/json&quot; \
  -d &#x27;{
    &quot;name&quot;: &quot;My Organization&quot;,
    &quot;slug&quot;: &quot;my-org&quot;,
    &quot;admin_email&quot;: &quot;admin@example.com&quot;,
    &quot;admin_password&quot;: &quot;SuperSecret123!&quot;
  }&#x27; | jq

The slug becomes part of your MCP URL: http://localhost:8000/t/my-org/mcp/sse

4. Open the admin UI

Navigate to http://localhost:8000/admin/ and sign in with your admin credentials.

5. Add a database connection

In the admin UI → Connections → Create connection, or via API:```bash
TOKEN=$(curl -s -X POST http://localhost:8000/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"admin@example.com","password":"SuperSecret123!"}' \
| jq -r .access_token)

curl -s -X POST http://localhost:8000/connections/ \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Production DB",
"db_type": "postgres",
"connection_string": "postgresql://user:pass@host/mydb",
"min_role": "viewer"
}' | jq


### 6. Connect Claude Desktop

Add to your Claude Desktop MCP config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):```json
{
  &quot;mcpServers&quot;: {
    &quot;my-org-gateway&quot;: {
      &quot;command&quot;: &quot;npx&quot;,
      &quot;args&quot;: [
        &quot;-y&quot;,
        &quot;mcp-remote&quot;,
        &quot;http://localhost:8000/t/my-org/mcp/sse&quot;
      ]
    }
  }
}

Restart Claude Desktop. It will open a browser window for OAuth login. After authenticating, Claude can use your database tools.


Configuration

All configuration is via environment variables. See .env.example for a template.

Required

Variable Description
SECRET_KEY JWT signing secret — use a random 64-char string
ENCRYPTION_KEY Fernet AES key for DB credentials — minimum 32 characters; full key consumed via BLAKE2b
DATABASE_URL PostgreSQL DSN — set automatically by docker-compose; only needed for local (non-Docker) dev. No default: the app will not start without it

POSTGRES_PASSWORD is also required, but by docker-compose, not by the application — it seeds the db service and is interpolated into DATABASE_URL. Compose fails fast if it, SECRET_KEY or ENCRYPTION_KEY are unset.

Optional

Variable Default Description
ANTHROPIC_API_KEY — Required for /query/ NL query endpoint
BASE_URL http://localhost:8000 Public-facing URL (used in OAuth callbacks)
CORS_ORIGINS BASE_URL Comma-separated allowed origins for CORS. Must be absolute URLs — wildcards (*) are rejected
ACCESS_TOKEN_EXPIRE_MINUTES 15 JWT access token lifetime
REFRESH_TOKEN_EXPIRE_DAYS 30 OAuth refresh token lifetime
OAUTH_STATE_TTL_MINUTES 10 OAuth PKCE state validity window — increase for high-latency SSO providers
OAUTH_CODE_TTL_MINUTES 5 OAuth authorization code validity window
LLM_MODEL claude-sonnet-4-6 Anthropic model for SQL generation
LLM_MAX_TOKENS_SQL 1024 Max tokens for SQL generation
LLM_MAX_TOKENS_SUMMARY 500 Max tokens for result summarization
FILESYSTEM_ALLOWED_DIRS — Comma-separated directories the MCP filesystem tools may access. Entries must be absolute and must not contain .., or the app refuses to start. When empty, no filesystem tools are exposed
LOG_LEVEL INFO Root log level (DEBUG, INFO, WARNING, ERROR)
ALGORITHM HS256 JWT signing algorithm
REDIS_URL — Shared rate-limiter storage. When empty, limits are in-memory and therefore per worker
WEB_CONCURRENCY 1 Uvicorn worker count. Above 1 without REDIS_URL, rate limits are multiplied by this number
TRUST_PROXY_HEADERS false Derive the rate-limit key from X-Forwarded-For. Enable only behind a trusted proxy — otherwise clients can spoof it

Entra ID

Variable Default Description
ENTRA_AUTHORITY_URL https://login.microsoftonline.com Microsoft identity platform base URL
ENTRA_GRAPH_URL https://graph.microsoft.com/v1.0 Microsoft Graph API base URL

Authentication

Local login```http

POST /auth/login
Content-Type: application/json

{
"email": "user@example.com",
"password": "SuperSecret123!",
"tenant_slug": "my-org" // optional, disambiguates if same email is in multiple tenants
}


Response:```json
{
  &quot;access_token&quot;: &quot;eyJ...&quot;,
  &quot;token_type&quot;: &quot;bearer&quot;
}

Include the token in subsequent requests:```
Authorization: Bearer eyJ...


Access tokens expire after 15 minutes by default. Use the OAuth token endpoint with a refresh token to get a new pair.

### API keys

Generate a key (requires authentication):```bash
curl -s -X POST http://localhost:8000/api-keys \
  -H &quot;Authorization: Bearer $TOKEN&quot; \
  -H &quot;Content-Type: application/json&quot; \
  -d &#x27;{&quot;name&quot;: &quot;CI pipeline&quot;}&#x27; | jq

The raw_key in the response is shown once only — store it immediately:```json
{
"id": "...",
"name": "CI pipeline",
"prefix": "mgw_abcd1234",
"raw_key": "mgw_abcd1234...",
"created_at": "..."
}


Use via query parameter:```bash
curl &quot;http://localhost:8000/connections/?api_key=mgw_abcd1234...&quot;

OAuth 2.1 (MCP browser clients)

The gateway implements RFC 8414 OAuth discovery. MCP clients follow this flow automatically:

  1. Client connects to /t/{slug}/mcp/sse — receives 401 + WWW-Authenticate header pointing to the OAuth discovery URL
  2. Client fetches /.well-known/oauth-authorization-server/t/{slug}
  3. Client registers dynamically via POST /t/{slug}/oauth/register
  4. Client opens browser → user logs in at /t/{slug}/oauth/authorize
  5. Client exchanges code + PKCE verifier for tokens via POST /t/{slug}/oauth/token
  6. Client reconnects with Bearer token

No manual configuration needed — just point mcp-remote at your tenant's SSE URL.

API key auth (MCP non-interactive clients)

For CI/CD, scripts, or when you want to skip the browser login, pass an API key in the URL:```json
{
"mcpServers": {
"gateway": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:8000/t/my-org/mcp/sse?api_key=mgw_..."]
}
}
}


The SSE endpoint validates the key and establishes the session directly — no OAuth flow, no browser window. See API Keys for details.

---

## API Reference

All management endpoints are available at both their canonical paths (e.g. `/tenants/`) and the versioned prefix `/api/v1/` (e.g. `/api/v1/tenants/`). The unversioned paths are kept for backward compatibility with the current frontend; new integrations should use `/api/v1/`. Protocol-defined routes (OAuth `/t/{slug}/…`, MCP `/t/{slug}/…`, `/.well-known/`) and infrastructure routes (`/health`, `/admin`) are intentionally unversioned.

&gt; The `curl` examples below use the unversioned paths so they match the running
&gt; admin UI. Prefix them with `/api/v1` for new integrations.

### Authentication

| Method | Path | Role | Description |
|--------|------|------|-------------|
| `POST` | `/auth/login` | Public | Email + password login, returns a JWT |

### Tenants &amp; Users

| Method | Path | Role | Description |
|--------|------|------|-------------|
| `POST` | `/tenants/` | Public | Register new tenant + admin user |
| `GET` | `/tenants/me` | Any | Get your tenant details |
| `GET` | `/tenants/users` | Admin | List all users in your tenant |
| `POST` | `/tenants/users` | Admin | Create a local user |
| `PATCH` | `/tenants/users/{user_id}` | Admin | Update user role |
| `DELETE` | `/tenants/users/{user_id}` | Admin | Remove a user from the tenant |

### Entra ID / SSO

| Method | Path | Role | Description |
|--------|------|------|-------------|
| `POST` | `/auth/entra/config` | Admin | Create or replace the tenant&#x27;s Entra config |
| `GET` | `/auth/entra/config` | Admin | Read the current Entra config (secret redacted) |
| `DELETE` | `/auth/entra/config` | Admin | Remove the Entra config |
| `GET` | `/auth/entra/login` | Public | Begin admin-UI SSO login (redirects to Microsoft) |
| `GET` | `/auth/entra/callback` | Public | Microsoft redirect target for the admin-UI flow |
| `GET` | `/auth/entra/exchange` | Public | Exchange the one-time SSO nonce for a JWT |

**Register tenant:**```bash
curl -X POST http://localhost:8000/tenants/ \
  -H &quot;Content-Type: application/json&quot; \
  -d &#x27;{
    &quot;name&quot;: &quot;Acme Corp&quot;,
    &quot;slug&quot;: &quot;acme&quot;,
    &quot;admin_email&quot;: &quot;admin@acme.com&quot;,
    &quot;admin_password&quot;: &quot;SuperSecret123!&quot;
  }&#x27;

Create user:```bash
curl -X POST http://localhost:8000/tenants/users \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"email": "analyst@acme.com",
"password": "AnotherSecret456!",
"role": "analyst"
}'


Roles: `viewer` (default), `analyst`, `admin`. Passwords must be at least 12 characters.

---

### Connections

| Method | Path | Role | Description |
|--------|------|------|-------------|
| `POST` | `/connections/` | Admin | Add a database connection |
| `GET` | `/connections/` | Viewer+ | List accessible connections |
| `PATCH` | `/connections/{id}` | Admin | Update connection |
| `DELETE` | `/connections/{id}` | Admin | Soft-delete connection |

**Add connection:**```bash
curl -X POST http://localhost:8000/connections/ \
  -H &quot;Authorization: Bearer $TOKEN&quot; \
  -H &quot;Content-Type: application/json&quot; \
  -d &#x27;{
    &quot;name&quot;: &quot;Sales DB&quot;,
    &quot;db_type&quot;: &quot;postgres&quot;,
    &quot;connection_string&quot;: &quot;postgresql://user:pass@db-host/sales&quot;,
    &quot;description&quot;: &quot;Production sales database&quot;,
    &quot;min_role&quot;: &quot;analyst&quot;
  }&#x27;

min_role controls who can query this connection. Users below this role cannot see or use it.


Natural Language Query

Method Path Role Rate Limit Description
POST /query/ Analyst+ 30/min Execute NL query
GET /query/history Admin 60/min Paginated query audit history

Query:```bash
curl -X POST http://localhost:8000/query/ \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"connection_id": "...",
"question": "What are the top 5 customers by total revenue this quarter?"
}'


Response:```json
{
  &quot;sql_generated&quot;: &quot;SELECT customer_name, SUM(amount) AS total FROM orders ...&quot;,
  &quot;result&quot;: [
    {&quot;customer_name&quot;: &quot;Acme Corp&quot;, &quot;total&quot;: 125000}
  ],
  &quot;summary&quot;: &quot;The top customer this quarter is Acme Corp with $125,000 in revenue.&quot;
}

The query pipeline:
1. Fetches schema from the database
2. Sends schema + question to Claude → generates SQL
3. Validates SQL is a SELECT statement (blocks all writes)
4. Executes SQL (30-second timeout)
5. Sends question + results to Claude → generates summary


Tools

Method Path Role Description
GET /tools/ Any List MCP tools with role metadata
PATCH /tools/{tool_name} Admin Set or reset role override

List tools:```bash
curl http://localhost:8000/tools/ \
-H "Authorization: Bearer $TOKEN"


Response:```json
[
  {
    &quot;tool_name&quot;: &quot;execute_sql_sales-db_abcd1234&quot;,
    &quot;description&quot;: &quot;Execute SQL on Sales DB&quot;,
    &quot;connection_id&quot;: &quot;...&quot;,
    &quot;default_min_role&quot;: &quot;analyst&quot;,
    &quot;effective_min_role&quot;: &quot;admin&quot;,
    &quot;accessible&quot;: false
  }
]

Override tool role:```bash

Restrict to admin only

curl -X PATCH "http://localhost:8000/tools/execute_sql_sales-db_abcd1234" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"min_role": "admin"}'

Reset to connection default

curl -X PATCH "http://localhost:8000/tools/execute_sql_sales-db_abcd1234" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"min_role": null}'


---

### API Keys

| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/api-keys` | Generate a new key |
| `GET` | `/api-keys` | List your keys |
| `DELETE` | `/api-keys/{id}` | Revoke a key |
```bash
# Generate (expires_at is optional)
curl -X POST http://localhost:8000/api-keys \
  -H &quot;Authorization: Bearer $TOKEN&quot; \
  -H &quot;Content-Type: application/json&quot; \
  -d &#x27;{&quot;name&quot;: &quot;CI pipeline&quot;, &quot;expires_at&quot;: &quot;2027-01-01T00:00:00Z&quot;}&#x27;

# List
curl http://localhost:8000/api-keys \
  -H &quot;Authorization: Bearer $TOKEN&quot;

# Revoke
curl -X DELETE &quot;http://localhost:8000/api-keys/{id}&quot; \
  -H &quot;Authorization: Bearer $TOKEN&quot;

Audit Logs

Method Path Role Rate Limit Description
GET /audit-logs/ Admin 60/min List audit events (filterable)
# All events (paginated)
curl &quot;http://localhost:8000/audit-logs/?limit=50&quot; \
  -H &quot;Authorization: Bearer $ADMIN_TOKEN&quot;

# Filter by event type (comma-separated prefixes)
curl &quot;http://localhost:8000/audit-logs/?event_prefix=query,tool&amp;limit=100&quot; \
  -H &quot;Authorization: Bearer $ADMIN_TOKEN&quot;

Query parameters: skip (offset, default 0), limit (max 200, default 50), event_prefix (comma-separated, e.g. query, login, fs).


Health Check```bash

curl http://localhost:8000/health

{"status": "ok"}


Returns `503` if the database is unreachable. Suitable for Kubernetes liveness and readiness probes.

---

## MCP Integration

### Connecting Claude Desktop

Install mcp-remote:```bash
npm install -g mcp-remote

Add to claude_desktop_config.json:```json
{
"mcpServers": {
"gateway": {
"command": "npx",
"args": ["mcp-remote", "http://localhost:8000/t/my-org/mcp/sse"]
}
}
}


On first connection, a browser window opens for OAuth login. After authenticating, mcp-remote caches the tokens and reconnects automatically. Tokens refresh silently in the background.

### Available MCP Tools

For each active database connection the user can access, the gateway exposes two tools:

**`get_schema_{connection-name}_{id}`**
Returns the full database schema (tables, columns, types, constraints, indexes). Claude calls this first to understand the data structure before generating SQL.

**`execute_sql_{connection-name}_{id}`**
Executes a `SELECT` statement and returns rows as JSON. Any non-SELECT statement is rejected (INSERT, UPDATE, DELETE, DROP, etc.). Execution timeout: 30 seconds.

**`list_connections`**
Returns all database connections the user can access with their names and types.

**`get_current_time`**
Returns the current UTC time in ISO 8601 format. Available to all roles.

**Filesystem tools** (only when `FILESYSTEM_ALLOWED_DIRS` is configured):

| Tool | Role | Description |
|------|------|-------------|
| `fs_read_file` | Analyst+ | Read a file as UTF-8 text |
| `fs_list_directory` | Analyst+ | List directory contents |
| `fs_directory_tree` | Analyst+ | Recursive directory tree (JSON) |
| `fs_search_files` | Analyst+ | Glob pattern search |
| `fs_get_file_info` | Analyst+ | File metadata (size, timestamps) |
| `fs_write_file` | Admin | Create or overwrite a file |
| `fs_create_directory` | Admin | Create a directory (with parents) |
| `fs_move_file` | Admin | Move or rename a file |

### SSE Endpoints

| Endpoint | Auth | Description |
|----------|------|-------------|
| `GET /t/{slug}/mcp/sse` | Bearer JWT or `?api_key=` | Tenant-scoped SSE (recommended) |
| `POST /t/{slug}/mcp/messages` | Bearer JWT, `?api_key=`, or session ID | Tenant-scoped message handler |
| `GET /mcp/sse` | `?api_key=` or `?token=` | Legacy SSE (deprecated, sunset 2027-03-01) |
| `POST /mcp/messages` | Bearer JWT, `?api_key=`, or `?token=` | Legacy message handler (deprecated) |

### OAuth Discovery Endpoints

| Endpoint | RFC | Description |
|----------|-----|-------------|
| `GET /.well-known/oauth-authorization-server/t/{slug}` | RFC 8414 | Authorization server metadata |
| `GET /.well-known/oauth-protected-resource/t/{slug}/mcp/sse` | RFC 9728 | Protected resource metadata |
| `GET /t/{slug}/.well-known/oauth-authorization-server` | — | Same metadata, tenant-prefixed path |
| `GET /t/{slug}/.well-known/oauth-protected-resource` | — | Same metadata, tenant-prefixed path |
| `POST /t/{slug}/oauth/register` | RFC 7591 | Dynamic client registration |
| `GET /t/{slug}/oauth/authorize` | RFC 6749 | Authorization endpoint (PKCE S256) |
| `POST /t/{slug}/oauth/login` | — | Local login form submission (non-SSO tenants) |
| `GET /t/{slug}/oauth/entra-callback` | — | Microsoft redirect target for the MCP OAuth flow |
| `POST /t/{slug}/oauth/token` | RFC 6749 | Token endpoint (code + refresh_token) |

---

## Build your own tools

Any Python function becomes an authenticated, audited MCP tool:```python
# app/tools/my_tool.py
from app.tools import register_tool, ToolContext
from mcp.types import TextContent

@register_tool(name=&quot;my_custom_tool&quot;, min_role=&quot;analyst&quot;)
async def my_tool(arguments: dict, ctx: ToolContext) -&gt; list[TextContent]:
    # ctx.user gives you the authenticated user + their role
    # ctx.db gives you the database session
    result = do_something(arguments[&quot;input&quot;])
    return [TextContent(type=&quot;text&quot;, text=result)]

Restart the gateway. The tool appears in Claude Desktop automatically, with auth and audit logging included.


Role-Based Access Control

Three roles in ascending order of permission: viewer → analyst → admin

Default permissions

Action Viewer Analyst Admin
View connections ✓ ✓ ✓
Run NL queries — ✓ ✓
Use filesystem tools (read) — ✓ ✓
Use filesystem tools (write) — — ✓
View audit logs — — ✓
View query history — — ✓
Manage connections — — ✓
Manage users — — ✓
Configure SSO — — ✓
Manage API keys ✓ ✓ ✓
Override tool roles — — ✓

Per-connection roles

Each connection has a min_role. Users below this role cannot see or use that connection, or the MCP tools it generates.

Example: A sensitive production database with min_role: admin is invisible to analysts and viewers entirely — it won't appear in /connections/ or /tools/, and its MCP tools won't be listed.

Per-tool overrides

Admins can override the effective minimum role for any MCP tool independently of the connection's min_role:```bash

Lock down SQL execution on prod, but keep schema browsing open

PATCH /tools/execute_sql_prod-db_abcd1234 {"min_role": "admin"}
PATCH /tools/get_schema_prod-db_abcd1234 {"min_role": "analyst"}

Reset to connection default

PATCH /tools/execute_sql_prod-db_abcd1234 {"min_role": null}


---

## Entra ID / SSO

### Setup in Azure AD

1. Register an application in Azure Active Directory (App registrations → New registration)
2. Add redirect URIs:
   - `http:///auth/entra/callback` (admin UI SSO)
   - `http:///t//oauth/entra-callback` (MCP OAuth flow)
3. Under **API permissions**, add:
   - **Delegated** (Microsoft Graph): `openid`, `profile`, `email`, `User.Read`, `GroupMember.Read.All`
   - **Application** (Microsoft Graph): `GroupMember.Read.All` (required for role sync during token refresh)
   - Grant **admin consent** for both the delegated and the application `GroupMember.Read.All`
4. Create a **Client secret** (Certificates &amp; secrets → New client secret)
5. Note your Azure tenant ID, app client ID, and the client secret value

### Configure in MCP Gateway

Via admin UI: **SSO Config** tab, or via API:```bash
curl -X POST http://localhost:8000/auth/entra/config \
  -H &quot;Authorization: Bearer $ADMIN_TOKEN&quot; \
  -H &quot;Content-Type: application/json&quot; \
  -d &#x27;{

…(正文过长,页面只展示前面部分,完整内容见仓库)

常见问题

8 问
答案由本站依据条目字段整理,不引用上游原文
MCP Gateway E3d14811 怎么安装?

在客户端按下面的安装命令接入:python3 -c "import secrets; print(secrets.token_hex(32))"。装完在客户端配置里引用同一个包或端点。

MCP Gateway E3d14811 怎么在 Claude Desktop、Claude 里配置?

它的传输方式是stdio · 本地进程,在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,配置才会生效。

MCP Gateway E3d14811 收费吗?

本站不代收费用,也没有标注具体价格。是否收费取决于服务本身和背后的接口额度,正式使用前按官方说明确认。

MCP Gateway E3d14811 需要 API Key 吗?

资料标注需要OAuth 授权认证,使用前准备好对应凭据,并按最小权限配置。

MCP Gateway E3d14811 支持哪些客户端?

资料标注支持 Claude Desktop、Claude;其他客户端只要能配置 MCP Server,也能用同样的命令或地址接入。

MCP Gateway E3d14811 能提供哪些能力?

资料显示约 12 个工具;能力标签包括 数据库连接、访问控制、Python、Claude、审计日志。具体工具清单以官方文档为准。

MCP Gateway E3d14811 需要什么运行环境?

运行时为 Python;属于本地进程,需要在本机装好运行环境。

MCP Gateway E3d14811 是本地还是远程?

它是本地进程(stdio),由客户端在本机拉起。传输方式为stdio · 本地进程。

热门专题

按标签挑服务器
全部专题 →

服务器信息以作者仓库与官方文档为准;分类、传输方式与鉴权方式的中文说明为中文整理,最近核验 2026-05-17。