MCP Gateway

The MCP Gateway exposes coreX Platform’s full API as MCP tools and brokers connections to external MCP servers. AI agents authenticate once and can call tools across all connected servers through a single endpoint, with policy enforcement, DLP, guardrails, rate limiting, and observability applied at the gateway.

Architecture

  AI Agent (Claude, Cursor, custom)

       │  MCP over Streamable HTTP
       │  Authorization: Bearer <PAT or JWT>

  ┌──────────────────────────────────────────────────────┐
  │  mcp-gateway-rs  (Rust, :8089)                       │
  │                                                      │
  │  1. Auth (PAT / JWT / OAuth)                         │
  │  2. Policy evaluation (allow/deny per expression)    │
  │  3. Rate limiting (per-identity, per-IP, concurrent) │
  │  4. DLP (block/redact/tokenize sensitive data)       │
  │  5. Guardrails (jailbreak/override/obfuscation)      │
  │  6. Skills (inject skill guides into agent context)  │
  │  7. Circuit breaker (per upstream server)            │
  │  8. Tool namespace prefixing (server__tool)          │
  │  9. Catalog aggregation (tools/resources/prompts)    │
  │ 10. Event logging (every JSON-RPC call)              │
  └──────────────────────┬───────────────────────────────┘

            ┌────────────┼──────────────┐
            ▼            ▼              ▼
     ┌────────────┐  ┌───────────┐  ┌───────────────────┐
     │ mcp-server │  │ external  │  │ external          │
     │ :8082      │  │ MCP srv 1 │  │ MCP srv 2 (stdio) │
     │ (coreX     │  │ (HTTP)    │  │ (spawned locally) │
     │  Manager)  │  │           │  │                   │
     └────────────┘  └───────────┘  └───────────────────┘

The gateway runs as a separate container (mcp-gateway-rs, Rust). The mcp-server container (Python) exposes the coreX Platform backend API as 339+ MCP tools via in-process ASGI execution. External MCP servers are connected via HTTP (Streamable HTTP transport) or stdio (local subprocess spawned by the gateway).

Enabling the Gateway

  1. Set MCP_GATEWAY_ENABLED=true in your environment (see Quick Start)
  2. Set MCP_SECRETS_KEY to a 32+ byte Fernet key (used to encrypt server auth secrets at rest)
  3. Restart the stack — the mcp-gateway-rs and mcp-server containers start automatically
  4. Navigate to Management > MCP Gateway in the UI
Self-registration

When MCP_GATEWAY_ENABLED=true, MCP_SELF_REGISTER=true (default), and MCP_SECRETS_KEY is set, the backend automatically creates a “platform” team, registers the corex-manager MCP server, and publishes a skill guide. No manual setup is needed to start using the gateway with coreX Platform tools.

UI Tabs

The MCP Gateway page has 12 tabs:

TabDescription
DashboardGateway live status, metrics, circuit breakers, catalog freshness, alerting config
TeamsCreate and manage teams; assign users to teams
ServersRegister external MCP servers (HTTP or stdio); manage replicas, OAuth, catalogs
MarketplaceSearch npm/PyPI for MCP server packages and install them
IdentitiesCreate PATs and JWT identities; sync from Auth0
PoliciesAuthorize/deny rules using the MCP expression language
DLPData loss prevention rules (block/redact/tokenize sensitive data)
GuardrailsJailbreak, instruction override, and obfuscation detection
SkillsPublish versioned skill guides that agents can reference
TrafficLive request inspection (see MCP Traffic)
EventsAudit log of every JSON-RPC call with filters
SettingsGateway configuration (CORS, JWT, rate limits, config bundle)

Teams

Teams are the top-level organizational unit. Servers, identities, policies, DLP rules, guardrails, and skills all belong to a team. Users are assigned to teams; a user can only see and manage resources in their teams (admins bypass this restriction).

  • Create a team — admin only. Name and slug.
  • Assign users — add users to a team via the Teams tab. Users in a team can view and (with write permission) manage that team’s resources.

Servers

Register external MCP servers that the gateway proxies. Each server belongs to a team and has a unique namespace (used to prefix tool names: namespace__tool_name).

Transport Types

TransportDescription
Streamable HTTPConnect to a remote MCP server over HTTP (MCP spec 2025-11-25). The server URL must be reachable from the gateway container.
stdioSpawn a local subprocess (e.g. npx -y @modelcontextprotocol/server-filesystem). The gateway runs the command and communicates over stdin/stdout. Requires command and args fields.

Server Fields

FieldDescription
NameUnique identifier within the team
Display nameHuman-friendly name shown in the UI
NamespacePrefix for tool/resource/prompt names (e.g. github, filesystem)
URLServer URL (HTTP transport only)
EnabledToggle to enable/disable the server
Verify TLSVerify the server’s TLS certificate (HTTP transport)
Auth typenone, bearer (token in Authorization header), or basic (username/password)
Auth headerCustom header name for the auth secret (default: Authorization)
Auth secretThe token or password (encrypted at rest with MCP_SECRETS_KEY)
Timeout (ms)Per-request timeout (default: 30000)
Max body bytesMaximum response body size (default: 1048576)
CommandExecutable to run (stdio transport only, e.g. npx)
ArgsCommand arguments (stdio transport only, e.g. -y @modelcontextprotocol/server-filesystem /data)
Env varsEnvironment variables for the subprocess (stdio transport only)

Replicas

For HTTP servers, you can add replica URLs for load balancing or failover. Replica URLs must have the same path as the primary URL. The gateway distributes requests across the primary and replicas.

OAuth

For servers that require OAuth 2.0 authentication, configure the OAuth client ID, client secret, scopes, and authorization server metadata URL. The gateway handles the OAuth flow:

  1. Configure OAuth credentials on the server
  2. Click Authorize — opens the authorization URL in a new tab
  3. Complete the consent flow
  4. The gateway stores the access token and refreshes it automatically
  5. Status badge shows authorized, pending, or error

Catalog Refresh

The gateway periodically fetches each server’s catalog (tools, resources, prompts). The Refresh Catalog button triggers an immediate refresh. The dashboard shows catalog freshness (tools/resources/prompts count and last fetch time).

Test Connection

The Test button sends an initialize JSON-RPC request to the server and reports the result. Use this to verify connectivity and authentication before enabling the server.

Marketplace

Search and install MCP server packages from npm and PyPI without leaving the UI.

  1. Navigate to Marketplace
  2. Select a package manager: npm or pypi
  3. Search for a package (e.g. filesystem, github)
  4. Click a result to view details (README, versions, install command)
  5. Click Install
  6. Choose a team, server name, and namespace
  7. The gateway installs the package and registers the server
  8. Configure any required env vars (discovered automatically from the package)

Installed packages show the package manager, source package name, and installed version on the Servers tab.

Identities

Identities authenticate AI agents to the gateway. Each identity belongs to a team.

Identity Kinds

KindDescription
PAT (Personal Access Token)A long-lived token generated by the gateway. The agent sends it as Authorization: Bearer <token>. The token is shown once on creation — copy it immediately. The prefix is stored for identification.
JWTA JWT issued by an external IdP. Configure the issuer, audience, and JWKS URL. The gateway validates the JWT signature against the JWKS. The JWT sub claim becomes the identity subject.

Auth0 Sync

Sync identities from Auth0:

  1. Click Sync from Auth0
  2. Select a team
  3. Optionally enable Dry run to preview without creating identities
  4. Optionally enable Require verified email
  5. The gateway creates/updates JWT identities for each Auth0 user

Identity Fields

FieldDescription
NameUnique identifier within the team
SubjectThe JWT sub claim value (JWT kind) or PAT prefix (PAT kind)
Kindpat or jwt
JWT issuerIssuer URL (JWT kind)
JWT audienceExpected audience (JWT kind)
JWKS URLURL to fetch signing keys (JWT kind)
EnabledToggle to enable/disable the identity
Expires atOptional expiration timestamp
Last usedUpdated on each authenticated request

Policies

Policies authorize or deny JSON-RPC calls based on an expression language. Policies are evaluated in order; the first match wins. If no policy matches, the call is allowed (default allow).

Expression Language

The expression language supports:

  • Fields: mcp.method, mcp.server, mcp.tool, mcp.resource, mcp.prompt, mcp.identity, mcp.identity.kind, mcp.team, mcp.arg["path"], auth.claim.sub, auth.claim.iss, auth.claim.aud, auth.claim["key"], ip.src
  • Operators: =, !=, ~ (regex match), in, not in, contains, and, or, not
  • Functions: mcp.arg["path"] resolves JSONPath-lite on tools/call arguments

MCP Methods

MethodDescription
initializeClient initialization handshake
notifications/initializedClient initialized notification
notifications/cancelledRequest cancellation
notifications/progressProgress notification
tools/listList available tools
tools/callCall a tool
resources/listList available resources
resources/readRead a resource
prompts/listList available prompts
prompts/getGet a prompt

Policy Fields

FieldTypeDescription
mcp.methodstringThe JSON-RPC method (e.g. tools/call)
mcp.serverstringThe server namespace
mcp.toolstringThe namespaced tool name (namespace__tool)
mcp.resourcestringThe wrapped resource URI
mcp.promptstringThe namespaced prompt name
mcp.identitystringThe identity name (PAT) or JWT sub
mcp.identity.kindstringpat or jwt
mcp.teamstringThe team slug
mcp.arg["path"]stringJSONPath-lite access to tools/call arguments
auth.claim.substringJWT sub claim
auth.claim.issstringJWT iss claim
auth.claim.audstringJWT aud claim
auth.claim["key"]stringArbitrary JWT claim
ip.srcstringClient IP from X-Forwarded-For

Actions

ActionDescription
allowAllow the call to proceed
denyDeny the call (returns error to the agent)

Policy Options

OptionDescription
LogLog the policy evaluation result to the events log
No logSuppress logging for this policy

Expression Templates

TemplateExpressionAction
Allow alltrueallow
Deny alltruedeny
Allow specific toolmcp.method = "tools/call" and mcp.tool = "namespace__tool_name"allow
Allow tool prefixmcp.method = "tools/call" and mcp.tool ~ "^namespace__.*"allow
Allow tool list by identitymcp.identity = "grok-agent" and mcp.tool in ["ns__tool1", "ns__tool2"]allow
Deny by identitymcp.identity = "name"deny
JWT subject checkauth.claim.sub = "subject-value"allow
Server + methodmcp.server = "namespace" and mcp.method = "tools/call"allow
Path traversal guardmcp.arg["path"] contains ".."deny

Policy Builder

The UI includes a visual expression builder that provides dropdowns for servers, tools, identities, and methods (populated from the live catalog), so you don’t need to memorize field names.

DLP Rules

Data Loss Prevention rules inspect request and response payloads for sensitive data and take action when detected.

DLP Fields

FieldDescription
NameUnique identifier within the team
Directionboth, request, or response — which payloads to inspect
Detectoremail, ssn, credit_card, api_key, phone, or custom (regex)
Find regexCustom regex pattern (when detector is custom)
Actionblock, redact, or tokenize
Token prefixPrefix for tokenized values (when action is tokenize)
Token TTLTime-to-live for tokens (when action is tokenize)
Apply toWhich parts of the payload to scan (default: json_strings)

DLP Actions

ActionDescription
blockReject the request/response and return an error to the agent
redactReplace matched values with [REDACTED]
tokenizeReplace matched values with a token; the original value is stored in Valkey for later detokenization

Guardrails

Guardrails detect prompt injection, jailbreak attempts, instruction overrides, and obfuscation in agent inputs and outputs.

Guardrail Packs

PackDescription
builtin:jailbreak_v1Detects common jailbreak patterns (e.g. “ignore previous instructions”)
builtin:instruction_overrideDetects attempts to override system instructions
builtin:obfuscationDetects obfuscated payloads (base64, unicode tricks, etc.)
customCustom regex pattern

Guardrail Fields

FieldDescription
NameUnique identifier within the team
Directionboth, request, or response
PackBuilt-in pack or custom
Find regexCustom regex (when pack is custom)
Actionblock, redact, or log

Skills

Skills are versioned markdown guides that agents can reference to understand how to use the gateway’s tools. A skill is published to make it available to agents.

Skill Fields

FieldDescription
NameUnique identifier within the team
DescriptionShort description shown to agents
TagsComma-separated tags for categorization
EnabledToggle to enable/disable the skill
Enable whenOptional expression (same language as policies) that determines when the skill is injected into agent context

Skill Versions

Skills are versioned. Each version has:

  • Frontmatter — YAML metadata (title, description, tags)
  • Body — Markdown content (the skill guide)
  • Files — Optional attached files (filename: content, one per line)

Skill Lifecycle

  1. Create a skill with name and description
  2. Create a version — add frontmatter, body, and optional files
  3. Publish — publish the latest version to make it active
  4. Rollback — revert to a previous version if needed

Import from URL

Import a skill from a URL (e.g. a GitHub raw URL). The gateway fetches the content and creates a skill with an optional auto-publish.

Traffic Tab

The Traffic tab shows live MCP requests flowing through the gateway in real time. Each entry shows the JSON-RPC method, tool name, identity, server, status, and latency. This is useful for debugging agent interactions and understanding what tools agents are calling.

Events Tab

The Events tab is an audit log of every JSON-RPC call through the gateway. Each event records:

FieldDescription
Request IDUnique ID for the request
Session IDMCP session ID
MethodJSON-RPC method
ToolTool name (for tools/call)
ActionGateway action taken (allow, deny, block, redact)
IdentityAuthenticated identity name
ServerTarget server namespace
TimestampWhen the event occurred

Filters: by action, method, and free-text search on request ID/tool/method.

Dashboard Tab

The Dashboard tab provides real-time gateway health and metrics:

  • Gateway status — reachable, configured, backend (rust/python)
  • Counters — requests, tools called, tools listed, auth success/failure, policy denied, rate limited, DLP blocked, guardrail blocked, upstream errors
  • Latency histogram — request latency distribution
  • Active sessions — current MCP session count
  • Open circuit breakers — servers with too many failures (auto-tripped)
  • Catalog freshness — per-server tools/resources/prompts count and last fetch time
  • Alert state — current alert thresholds and counts
  • Server status — per-server health, transport type, last seen, last error

Alerting

Configure webhook alerts for gateway events:

Event TypeDescription
guardrail_blockedA guardrail blocked a request
dlp_blockedA DLP rule blocked a request
policy_deniedA policy denied a request
auth_failedAn authentication failure
rate_limitedA rate limit was hit

Set a threshold per event type (0 = disabled). When the count of events in the recent window exceeds the threshold, a webhook is sent to the configured URL (e.g. Slack incoming webhook). The alert history shows recent alerts and webhook delivery status.

Settings Tab

General

SettingDescription
mcp_allowed_originsComma-separated list of allowed CORS origins (e.g. https://claude.ai,https://cursor.sh)
mcp_log_payloadsLog full request/response payloads in events (default: false — only metadata is logged)

JWT Configuration

SettingDescription
mcp_jwt_issuerExpected JWT issuer (for gateway-level JWT validation)
mcp_jwt_audienceExpected JWT audience
mcp_jwt_jwks_urlURL to fetch JWT signing keys

Rate Limiting

SettingDefaultDescription
mcp_default_rpm600Default requests-per-minute per identity
mcp_per_ip_limit0Per-IP rate limit (0 = disabled)
mcp_concurrent_limit0Maximum concurrent in-flight requests (0 = disabled)
mcp_team_rpm_overridesPer-team RPM overrides (JSON map of team_id → rpm)

Config Bundle

The gateway config bundle is a JSON file containing all teams, servers, identities, policies, DLP rules, guardrails, and skills. It’s generated by the backend and written to the shared volume where the gateway reads it.

  • Status — last generated timestamp and bundle size
  • Regenerate — manually regenerate the bundle (also happens automatically on any config change)

Connecting an AI Agent

Example: Claude Desktop

Add the following to your Claude Desktop configuration:

{
  "mcpServers": {
    "corex": {
      "url": "https://corex.example.com/mcp",
      "headers": {
        "Authorization": "Bearer <your-pat>"
      }
    }
  }
}

Example: Custom MCP Client

from mcp import Client

client = Client(
    url="https://corex.example.com/mcp",
    headers={"Authorization": "Bearer <your-pat>"}
)

# List all tools across all servers
tools = await client.call_tool("tools/list", {})

# Call a coreX Manager tool (namespaced as corex-manager__)
listeners = await client.call_tool("corex-manager__list_listeners", {})

# Call an external server tool (namespaced as filesystem__)
result = await client.call_tool("filesystem__read_file", {"path": "/data/config.txt"})

Tool Namespacing

All tools are prefixed with their server’s namespace: namespace__tool_name. This prevents collisions when multiple servers expose tools with the same name. For example:

  • corex-manager__list_listeners — coreX Platform tool
  • github__create_issue — GitHub MCP server tool
  • filesystem__read_file — Filesystem MCP server tool

Environment Variables

VariableDefaultDescription
MCP_GATEWAY_ENABLEDfalseEnable the MCP gateway and mcp-server containers
MCP_SECRETS_KEY(none)32+ byte Fernet key for encrypting server auth secrets. Required when gateway is enabled.
MCP_SELF_REGISTERtrueAuto-register the coreX Manager MCP server into the gateway on startup
MCP_SERVICE_TOKEN(none)Shared secret for rate-limit bypass on in-process MCP calls
MCP_GATEWAY_BACKENDrustGateway backend (rust or python)
MCP_GATEWAY_RS_INTERNAL_HOSTmcp-gateway-rsRust gateway hostname
MCP_GATEWAY_RS_INTERNAL_PORT8089Rust gateway port
MCP_SERVER_INTERNAL_HOSTmcp-serverMCP server hostname
MCP_SERVER_INTERNAL_PORT8082MCP server port
COREX_MCP_TOKEN(none)Bearer token for direct mcp-server connections (bypasses gateway)

Step-by-Step: Connect an AI Agent

  1. Enable the gateway:

    • Set MCP_GATEWAY_ENABLED=true and MCP_SECRETS_KEY in your environment
    • Restart the stack
  2. Create a team:

    • Navigate to Management > MCP Gateway > Teams
    • Click Add Team
    • Name: my-team
  3. Create an identity:

    • Navigate to Identities
    • Click Add Identity
    • Name: my-agent, Kind: PAT
    • Copy the generated token
  4. Configure your AI agent:

    • Add the MCP server URL and token to your agent’s configuration
    • URL: https://your-corex-domain/mcp
    • Header: Authorization: Bearer <token>
  5. Test the connection:

    • Ask your AI agent to list tools
    • Verify it can call corex-manager__list_listeners and receive results
  6. Add a policy (optional):

    • Navigate to Policies
    • Click Add Policy
    • Expression: mcp.method = "tools/call" and mcp.tool ~ "^corex-manager__list_.*"
    • Action: allow
    • This restricts the agent to read-only coreX Manager tools

Step-by-Step: Connect an External MCP Server

  1. Register the server:

    • Navigate to Management > MCP Gateway > Servers
    • Click Add Server
    • Team: select your team
    • Name: github, Namespace: github
    • Transport: Streamable HTTP
    • URL: https://api.githubcopilot.com/mcp/
    • Auth type: bearer, secret: your GitHub token
    • Click Test to verify connectivity
    • Click Save
  2. Wait for catalog refresh:

    • The gateway fetches the server’s catalog automatically
    • Check the Dashboard tab for catalog freshness
  3. Verify tools are available:

    • Ask your AI agent to list tools
    • Verify github__* tools appear alongside corex-manager__* tools

Step-by-Step: Install from Marketplace

  1. Navigate to Management > MCP Gateway > Marketplace
  2. Package manager: npm
  3. Search: filesystem
  4. Click the @modelcontextprotocol/server-filesystem result
  5. Review the details (README, versions)
  6. Click Install
  7. Team: select your team
  8. Name: filesystem, Namespace: filesystem
  9. The gateway installs the package and registers the server
  10. Configure env vars if prompted
  11. Verify filesystem__* tools appear in the agent’s tool list

Verification

  1. Check gateway health:

    curl https://your-corex-domain/mcp/healthz

    Expect {"status":"ok","configured":true}.

  2. Check OAuth metadata:

    curl https://your-corex-domain/mcp/.well-known/oauth-protected-resource

    Expect RFC 9728 metadata.

  3. Test authentication:

    curl -H "Authorization: Bearer <pat>" https://your-corex-domain/mcp/

    Expect a 200 or 406 (SSE listen not supported in v1).

  4. Check the dashboard:

    • Navigate to Management > MCP Gateway > Dashboard
    • Verify the gateway is reachable and configured
    • Verify metrics are incrementing as agents make calls
  5. Check events:

    • Navigate to Events
    • Verify JSON-RPC calls are logged with method, tool, action, and identity
  6. Check circuit breakers:

    • If a server is failing, the dashboard shows open circuit breakers
    • The gateway auto-trips after repeated failures and auto-resets after a cooldown

Next Steps