##################################### # MCP Gateway Configuration Example ##################################### # Basic Server Configuration # Application name displayed in UI and logs APP_NAME=MCP_Gateway # Host interface to bind to (0.0.0.0 = all interfaces, 127.0.0.1 = localhost only) HOST=0.0.0.0 # Port number for the HTTP server PORT=4444 # Runtime environment - affects CORS, cookies, and security defaults # Options: development, production # - development: Relaxed CORS (localhost:3000/8080), debug info, insecure cookies # - production: Strict CORS (APP_DOMAIN only), secure cookies, no debug info ENVIRONMENT=development # Domain name for CORS origins and cookie settings (use your actual domain in production) APP_DOMAIN=http://localhost # FastAPI root_path for reverse proxy deployments (empty = serve from root "/") # Used when gateway is behind a proxy with path prefix (e.g., "/api/v1") # See FastAPI docs: https://fastapi.tiangolo.com/advanced/behind-a-proxy/ APP_ROOT_PATH= # Enable HTTP Basic Auth for OpenAPI docs endpoints (/docs, /redoc) # Options: true, false (default: false) # When true: Allows accessing docs with BASIC_AUTH_USER/BASIC_AUTH_PASSWORD # When false: Only JWT Bearer token authentication is accepted DOCS_ALLOW_BASIC_AUTH=false # Database Configuration # SQLite (default) - good for development and small deployments # macOS note: If you see "sqlite3.OperationalError: disk I/O error" on macOS when running # `make serve`, move the DB to a safe APFS path (avoid iCloud/Dropbox/OneDrive/Google Drive, # network shares, or external exFAT) and use an absolute path, for example: # DATABASE_URL=sqlite:////Users/$USER/Library/Application Support/mcpgateway/mcp.db DATABASE_URL=sqlite:///./mcp.db # PostgreSQL - recommended for production deployments # DATABASE_URL=postgresql://postgres:mysecretpassword@localhost:5432/mcp # MariaDB/MySQL - fully supported for production # For container deployment: mysql+pymysql://mysql:changeme@mariadb:3306/mcp # For localhost: mysql+pymysql://mysql:changeme@localhost:3306/mcp # DATABASE_URL=mysql+pymysql://mysql:changeme@localhost:3306/mcp # Database Connection Pool Configuration # Maximum number of persistent connections (default: 200, optimized for SQLite) DB_POOL_SIZE=200 # Additional connections beyond pool_size (default: 10, reduced to 5 for SQLite) DB_MAX_OVERFLOW=5 # Seconds to wait for connection before timeout (default: 30, increased to 60 for reliability) DB_POOL_TIMEOUT=60 # Seconds before recreating connection (default: 3600) DB_POOL_RECYCLE=3600 # Maximum database retry attempts (default: 3, increased to 5 for stability) DB_MAX_RETRIES=5 # Retry interval in milliseconds (default: 2000) DB_RETRY_INTERVAL_MS=2000 # Cache Backend Configuration # Options: database (default), memory (in-process), redis (distributed) # - database: Uses SQLite/PostgreSQL for persistence (good for single-node) # - memory: Fast in-process caching (lost on restart, not shared between workers) # - redis: Distributed caching for multi-node deployments CACHE_TYPE=database # Redis connection URL (only used when CACHE_TYPE=redis) # Format: redis://[username:password@]host:port/database # Example: redis://localhost:6379/0 (local), redis://redis:6379/0 (container) # REDIS_URL=redis://localhost:6379/0 # Cache key prefix for Redis (used to namespace keys in shared Redis instances) # Default: "mcpgw:" CACHE_PREFIX=mcpgw: # Session time-to-live in seconds (how long sessions remain valid) # Default: 3600 (1 hour) SESSION_TTL=3600 # Message time-to-live in seconds (how long messages are retained) # Default: 600 (10 minutes) MESSAGE_TTL=600 # Maximum number of times to boot redis connection for cold start REDIS_MAX_RETRIES=3 # Interval time for next retry of redis connection REDIS_RETRY_INTERVAL_MS=2000 ##################################### # Protocol Settings ##################################### # MCP protocol version supported by this gateway PROTOCOL_VERSION=2025-06-18 ##################################### # Authentication ##################################### # Admin UI HTTP Basic Auth credentials # Used for: Admin UI login, /docs endpoint (if DOCS_ALLOW_BASIC_AUTH=true) # PRODUCTION: Change these to strong, unique values! BASIC_AUTH_USER=admin BASIC_AUTH_PASSWORD=changeme # Global authentication requirement # Options: true (default), false # When true: All endpoints require authentication (Basic or JWT) # When false: Endpoints are publicly accessible (NOT RECOMMENDED) AUTH_REQUIRED=true # Content type for outgoing HTTP requests to upstream services # Options: application/json (default), application/x-www-form-urlencoded, multipart/form-data FORGE_CONTENT_TYPE=application/json # JWT Algorithm Selection # Supported algorithms: # HMAC (Symmetric): HS256, HS384, HS512 - Simple deployments, shared secret # RSA (Asymmetric): RS256, RS384, RS512 - Enterprise, distributed systems # ECDSA (Asymmetric): ES256, ES384, ES512 - High performance, modern crypto JWT_ALGORITHM=HS256 # === HMAC (Symmetric) Configuration - Default for Development === # Secret used to sign JWTs (required for HMAC algorithms: HS256, HS384, HS512) # PRODUCTION: Use a strong, random secret (minimum 32 characters) # Generate with: openssl rand -base64 32 JWT_SECRET_KEY=my-test-key # === RSA/ECDSA (Asymmetric) Configuration - Recommended for Production === # Public and private key paths (required for asymmetric algorithms: RS*, ES*) # Generate RSA keys with: make certs-jwt # (creates certs/jwt/private.pem and certs/jwt/public.pem with proper permissions) # Generate ECDSA keys with: make certs-jwt-ecdsa # (creates certs/jwt/ec_private.pem and certs/jwt/ec_public.pem with proper permissions) # Generate both SSL and JWT keys: make certs-all #JWT_PUBLIC_KEY_PATH=certs/jwt/public.pem #JWT_PRIVATE_KEY_PATH=certs/jwt/private.pem # JWT Claims Configuration # PRODUCTION: Set these to your service-specific values JWT_AUDIENCE=mcpgateway-api JWT_ISSUER=mcpgateway # JWT Validation Options # Set to false for Dynamic Client Registration (DCR) scenarios where audience varies JWT_AUDIENCE_VERIFICATION=true # Expiry time for generated JWT tokens (in minutes; e.g. 7 days) TOKEN_EXPIRY=10080 REQUIRE_TOKEN_EXPIRATION=false ##################################### # Email-Based Authentication ##################################### # Enable email-based authentication system EMAIL_AUTH_ENABLED=true # Platform admin user (bootstrap from environment) # PRODUCTION: Change these to your actual admin credentials! PLATFORM_ADMIN_EMAIL=admin@example.com PLATFORM_ADMIN_PASSWORD=changeme PLATFORM_ADMIN_FULL_NAME=Platform Administrator # Argon2id Password Hashing Configuration # Time cost (iterations) - higher = more secure but slower ARGON2ID_TIME_COST=3 # Memory cost (KB) - higher = more secure but uses more RAM ARGON2ID_MEMORY_COST=65536 # Parallelism (threads) - typically 1 for web apps ARGON2ID_PARALLELISM=1 # Password Policy Configuration PASSWORD_MIN_LENGTH=8 PASSWORD_REQUIRE_UPPERCASE=false PASSWORD_REQUIRE_LOWERCASE=false PASSWORD_REQUIRE_NUMBERS=false PASSWORD_REQUIRE_SPECIAL=false # Account Security Configuration # Maximum failed login attempts before account lockout MAX_FAILED_LOGIN_ATTEMPTS=5 # Account lockout duration in minutes ACCOUNT_LOCKOUT_DURATION_MINUTES=30 # MCP Client Authentication MCP_CLIENT_AUTH_ENABLED=true TRUST_PROXY_AUTH=false PROXY_USER_HEADER=X-Authenticated-User # Used to derive an AES encryption key for secure auth storage # Must be a non-empty string (e.g. passphrase or random secret) AUTH_ENCRYPTION_SECRET=my-test-salt # OAuth Configuration OAUTH_REQUEST_TIMEOUT=30 OAUTH_MAX_RETRIES=3 OAUTH_DEFAULT_TIMEOUT=3600 # OAuth Security Settings # When MCP servers require OAuth authorization code flow, # tokens are stored per-user to prevent cross-user token access. # Users must individually authorize each OAuth-protected gateway. ##################################### # OAuth Dynamic Client Registration (DCR) and PKCE ##################################### # Enable Dynamic Client Registration (RFC 7591) # When enabled, MCP Gateway can automatically register as an OAuth client with Authorization Servers # that support DCR, eliminating the need for manual client credential configuration. DCR_ENABLED=true # Auto-register when gateway has issuer but no client_id # When true, gateway automatically registers with the Authorization Server when configured # with an issuer URL but no client credentials. DCR_AUTO_REGISTER_ON_MISSING_CREDENTIALS=true # Default scopes to request during DCR # JSON array of OAuth scopes to request when auto-registering DCR_DEFAULT_SCOPES=["mcp:read"] # Optional allowlist of issuer URLs for DCR (empty = allow any) # JSON array of trusted Authorization Server issuer URLs # Example: ["https://auth.example.com", "https://auth2.example.com"] # Empty array [] allows DCR with any issuer (not recommended for production) DCR_ALLOWED_ISSUERS=[] # Token endpoint authentication method for DCR # Options: client_secret_basic (default), client_secret_post, none # - client_secret_basic: Send credentials via HTTP Basic Auth header # - client_secret_post: Send credentials in POST body # - none: Public client (no client secret, PKCE-only) DCR_TOKEN_ENDPOINT_AUTH_METHOD=client_secret_basic # AS metadata cache TTL in seconds (RFC 8414 discovery) # How long to cache Authorization Server metadata after discovery DCR_METADATA_CACHE_TTL=3600 # Template for client_name in DCR requests # {gateway_name} will be replaced with the actual gateway name DCR_CLIENT_NAME_TEMPLATE=MCP Gateway ({gateway_name}) # Enable OAuth AS metadata discovery (RFC 8414) # When enabled, gateway automatically discovers Authorization Server endpoints # from the issuer URL using well-known metadata endpoints OAUTH_DISCOVERY_ENABLED=true # Preferred PKCE code challenge method # Options: S256 (SHA-256, recommended), plain (not recommended) # PKCE (Proof Key for Code Exchange) is always enabled for Authorization Code flows OAUTH_PREFERRED_CODE_CHALLENGE_METHOD=S256 # ============================================================================== # SSO (Single Sign-On) Configuration # ============================================================================== # Master SSO switch - enable Single Sign-On authentication # Options: true, false (default) # When true: Enables SSO login options alongside local auth SSO_ENABLED=false # GitHub OAuth Configuration # Options: true, false (default) # Requires: GitHub OAuth App (Settings > Developer settings > OAuth Apps) SSO_GITHUB_ENABLED=false # SSO_GITHUB_CLIENT_ID=your-github-client-id # SSO_GITHUB_CLIENT_SECRET=your-github-client-secret # Google OAuth Configuration SSO_GOOGLE_ENABLED=false # SSO_GOOGLE_CLIENT_ID=your-google-client-id.googleusercontent.com # SSO_GOOGLE_CLIENT_SECRET=your-google-client-secret # IBM Security Verify OIDC Configuration SSO_IBM_VERIFY_ENABLED=false # SSO_IBM_VERIFY_CLIENT_ID=your-ibm-verify-client-id # SSO_IBM_VERIFY_CLIENT_SECRET=your-ibm-verify-client-secret # SSO_IBM_VERIFY_ISSUER=https://your-tenant.verify.ibm.com/oidc/endpoint/default # Okta OIDC Configuration SSO_OKTA_ENABLED=false # SSO_OKTA_CLIENT_ID=your-okta-client-id # SSO_OKTA_CLIENT_SECRET=your-okta-client-secret # SSO_OKTA_ISSUER=https://your-okta-domain.okta.com # Keycloak OIDC Configuration (with auto-discovery) SSO_KEYCLOAK_ENABLED=false # SSO_KEYCLOAK_BASE_URL=https://keycloak.example.com # SSO_KEYCLOAK_REALM=master # SSO_KEYCLOAK_CLIENT_ID=mcp-gateway # SSO_KEYCLOAK_CLIENT_SECRET=your-keycloak-client-secret # SSO_KEYCLOAK_MAP_REALM_ROLES=true # SSO_KEYCLOAK_MAP_CLIENT_ROLES=false # SSO_KEYCLOAK_USERNAME_CLAIM=preferred_username # SSO_KEYCLOAK_EMAIL_CLAIM=email # SSO_KEYCLOAK_GROUPS_CLAIM=groups # Microsoft Entra ID (Azure AD) OIDC Configuration SSO_ENTRA_ENABLED=false # SSO_ENTRA_CLIENT_ID=your-entra-application-client-id # SSO_ENTRA_CLIENT_SECRET=your-entra-client-secret-value # SSO_ENTRA_TENANT_ID=your-entra-tenant-id # Generic OIDC Provider Configuration (Keycloak, Auth0, Authentik, etc.) SSO_GENERIC_ENABLED=false # SSO_GENERIC_PROVIDER_ID=keycloak # SSO_GENERIC_DISPLAY_NAME=Keycloak # SSO_GENERIC_CLIENT_ID=your-oidc-client-id # SSO_GENERIC_CLIENT_SECRET=your-oidc-client-secret # SSO_GENERIC_AUTHORIZATION_URL=https://keycloak.company.com/auth/realms/master/protocol/openid-connect/auth # SSO_GENERIC_TOKEN_URL=https://keycloak.company.com/auth/realms/master/protocol/openid-connect/token # SSO_GENERIC_USERINFO_URL=https://keycloak.company.com/auth/realms/master/protocol/openid-connect/userinfo # SSO_GENERIC_ISSUER=https://keycloak.company.com/auth/realms/master # SSO_GENERIC_SCOPE=openid profile email # SSO General Settings SSO_AUTO_CREATE_USERS=true # JSON array of trusted email domains, e.g., ["example.com", "company.org"] SSO_TRUSTED_DOMAINS=[] # Keep local admin authentication when SSO is enabled SSO_PRESERVE_ADMIN_AUTH=true # SSO Issuers Configuration # Optional JSON array of issuer URLs for SSO providers # Example: ["https://idp1.example.com", "https://idp2.example.com"] # Default: null (not set) # SSO_ISSUERS=["https://idp.example.com"] # SSO Admin Assignment Settings # Email domains that automatically get admin privileges, e.g., ["yourcompany.com"] SSO_AUTO_ADMIN_DOMAINS=[] # GitHub organizations whose members get admin privileges, e.g., ["your-org", "partner-org"] SSO_GITHUB_ADMIN_ORGS=[] # Google Workspace domains that get admin privileges, e.g., ["company.com"] SSO_GOOGLE_ADMIN_DOMAINS=[] # Require admin approval for new SSO registrations SSO_REQUIRE_ADMIN_APPROVAL=false ##################################### # Personal Teams Configuration ##################################### # Enable automatic personal team creation for new users AUTO_CREATE_PERSONAL_TEAMS=true # Personal team naming prefix PERSONAL_TEAM_PREFIX=personal # Team Limits MAX_TEAMS_PER_USER=50 MAX_MEMBERS_PER_TEAM=100 # Team Invitation Settings INVITATION_EXPIRY_DAYS=7 REQUIRE_EMAIL_VERIFICATION_FOR_INVITES=true ##################################### # Admin UI and API Toggles ##################################### # Enable the web-based Admin UI at /admin # Options: true (default), false # PRODUCTION: Set to false for security unless needed MCPGATEWAY_UI_ENABLED=true # Enable Admin REST API endpoints (/tools, /servers, /resources, etc.) # Options: true (default), false # Required for: Admin UI functionality, programmatic management MCPGATEWAY_ADMIN_API_ENABLED=true # Enable bulk import feature for mass tool/resource registration # Options: true (default), false # Allows importing multiple tools/resources in a single API call MCPGATEWAY_BULK_IMPORT_ENABLED=true # Maximum number of tools allowed per bulk import request MCPGATEWAY_BULK_IMPORT_MAX_TOOLS=200 # Rate limiting for bulk import endpoint (requests per minute) MCPGATEWAY_BULK_IMPORT_RATE_LIMIT=10 ##################################### # A2A (Agent-to-Agent) Configuration ##################################### # Enable A2A agent features (true/false) # Allows registration and management of external AI agents MCPGATEWAY_A2A_ENABLED=true # Maximum number of A2A agents allowed MCPGATEWAY_A2A_MAX_AGENTS=100 # Default timeout for A2A agent HTTP requests (seconds) MCPGATEWAY_A2A_DEFAULT_TIMEOUT=30 # Maximum retry attempts for failed A2A agent calls MCPGATEWAY_A2A_MAX_RETRIES=3 # Enable A2A agent metrics collection (true/false) MCPGATEWAY_A2A_METRICS_ENABLED=true ##################################### # MCP Server Catalog Configuration ##################################### # Enable MCP server catalog feature # Allows defining a catalog of pre-configured MCP servers in a YAML file # for easy discovery and management via the Admin UI # Options: true (default), false MCPGATEWAY_CATALOG_ENABLED=true # Path to the catalog configuration file # YAML file containing MCP server definitions # Default: mcp-catalog.yml MCPGATEWAY_CATALOG_FILE=mcp-catalog.yml # Automatically health check catalog servers on startup and periodically # Options: true (default), false MCPGATEWAY_CATALOG_AUTO_HEALTH_CHECK=true # Catalog cache TTL in seconds # How long to cache catalog data before refreshing # Default: 3600 (1 hour) MCPGATEWAY_CATALOG_CACHE_TTL=3600 # Number of catalog servers to display per page # Default: 100 MCPGATEWAY_CATALOG_PAGE_SIZE=100 ##################################### # Elicitation Support (MCP 2025-06-18) ##################################### # Enable elicitation passthrough - allows upstream MCP servers to request # structured user input through connected clients (e.g., Claude Desktop) # Per MCP spec 2025-06-18, elicitation enables interactive workflows where # servers can dynamically gather information from users during operations MCPGATEWAY_ELICITATION_ENABLED=true # Default timeout for user responses (seconds) # How long to wait for users to respond to elicitation requests MCPGATEWAY_ELICITATION_TIMEOUT=60 # Maximum concurrent elicitation requests # Prevents resource exhaustion from too many pending user input requests MCPGATEWAY_ELICITATION_MAX_CONCURRENT=100 ##################################### # Header Passthrough Configuration ##################################### # SECURITY WARNING: Header passthrough is disabled by default for security. # Only enable if you understand the security implications and have reviewed # which headers should be passed through to backing MCP servers. # ENABLE_HEADER_PASSTHROUGH=false # Enable overwriting of base headers (advanced usage only) # When disabled, passthrough headers cannot override gateway headers like Content-Type, Authorization # ENABLE_OVERWRITE_BASE_HEADERS=false # Default headers to pass through (when feature is enabled) # JSON array format recommended: ["X-Tenant-Id", "X-Trace-Id"] # Comma-separated also supported: X-Tenant-Id,X-Trace-Id # NOTE: Authorization header removed from defaults for security # DEFAULT_PASSTHROUGH_HEADERS=["X-Tenant-Id", "X-Trace-Id"] ##################################### # Security and CORS ##################################### # Skip SSL/TLS certificate verification for upstream requests # Options: true, false (default) # WARNING: Only use in development or with self-signed certificates! # PRODUCTION: Must be false for security SKIP_SSL_VERIFY=false # CORS allowed origins (JSON array of URLs) # Controls which domains can make cross-origin requests to the gateway # Format: JSON array starting with [ and ending with ] # Example: ["http://localhost:3000", "https://app.example.com"] # Use ["*"] to allow all origins (NOT RECOMMENDED) ALLOWED_ORIGINS='["http://localhost", "http://localhost:4444"]' # Enable CORS (Cross-Origin Resource Sharing) handling # Options: true (default), false # Required for: Web browser clients, cross-domain API access CORS_ENABLED=true # CORS allow credentials (true/false) CORS_ALLOW_CREDENTIALS=true # Environment setting (development/production) - affects security defaults # development: Auto-configures CORS for localhost:3000, localhost:8080, etc. # production: Uses APP_DOMAIN for HTTPS origins, enforces secure cookies # ENVIRONMENT is already defined in Basic Server Configuration section # Domain configuration for production CORS origins # In production, automatically creates origins: https://APP_DOMAIN, https://app.APP_DOMAIN, https://admin.APP_DOMAIN # For production: set to your actual domain (e.g., mycompany.com) # APP_DOMAIN is already defined in Basic Server Configuration section # Security settings for cookies # production: Automatically enables secure cookies regardless of this setting # development: Set to false for HTTP development, true for HTTPS SECURE_COOKIES=false # Cookie SameSite attribute for CSRF protection # strict: Maximum security, may break some OAuth flows # lax: Good balance of security and compatibility (recommended) # none: Requires Secure=true, allows cross-site usage COOKIE_SAMESITE=lax ##################################### # Security Headers Configuration ##################################### # Enable security headers middleware (true/false) SECURITY_HEADERS_ENABLED=true # X-Frame-Options setting (DENY, SAMEORIGIN, or ALLOW-FROM uri) # DENY: Prevents all iframe embedding (recommended for security) # SAMEORIGIN: Allows embedding from same domain only # To disable: Set to empty string X_FRAME_OPTIONS="" X_FRAME_OPTIONS=DENY # Other security headers (true/false) X_CONTENT_TYPE_OPTIONS_ENABLED=true X_XSS_PROTECTION_ENABLED=true X_DOWNLOAD_OPTIONS_ENABLED=true # HSTS (HTTP Strict Transport Security) settings HSTS_ENABLED=true # HSTS max age in seconds (31536000 = 1 year) HSTS_MAX_AGE=31536000 HSTS_INCLUDE_SUBDOMAINS=true # Remove server identification headers (true/false) REMOVE_SERVER_HEADERS=true # Enable HTTP Basic Auth for docs endpoints (in addition to Bearer token auth) # Uses the same credentials as BASIC_AUTH_USER and BASIC_AUTH_PASSWORD # DOCS_ALLOW_BASIC_AUTH is already defined in Basic Server Configuration section ##################################### # Response Compression Configuration ##################################### # Enable response compression (Brotli, Zstd, GZip) # Options: true (default), false # Reduces bandwidth by 30-70% for text-based responses (JSON, HTML, CSS, JS) # Automatically negotiates compression algorithm based on client Accept-Encoding header # Priority: Brotli (best compression) > Zstd (fast) > GZip (universal fallback) COMPRESSION_ENABLED=true # Minimum response size in bytes to compress # Responses smaller than this won't be compressed (compression overhead not worth it) # Default: 500 bytes # Set to 0 to compress all responses COMPRESSION_MINIMUM_SIZE=500 # GZip compression level (1-9) # 1 = fastest compression, larger files # 6 = balanced (recommended default) # 9 = best compression, slower # Default: 6 COMPRESSION_GZIP_LEVEL=6 # Brotli compression quality (0-11) # 0-3 = fast compression (lower quality) # 4-9 = balanced compression (recommended) # 10-11 = maximum compression (slower) # Default: 4 (balanced) # Note: Brotli offers 15-20% better compression than GZip at similar speeds COMPRESSION_BROTLI_QUALITY=4 # Zstd compression level (1-22) # 1-3 = fast compression # 4-9 = balanced compression # 10+ = slower, maximum compression # Default: 3 (fast) # Note: Zstd is the fastest algorithm with good compression ratio COMPRESSION_ZSTD_LEVEL=3 ##################################### # Retry Config for HTTP Requests ##################################### RETRY_MAX_ATTEMPTS=3 # seconds RETRY_BASE_DELAY=1.0 # seconds RETRY_MAX_DELAY=60.0 # fraction of delay RETRY_JITTER_MAX=0.5 ##################################### # Logging ##################################### # Logging verbosity level # Options: DEBUG, INFO, WARNING, ERROR (default), CRITICAL # DEBUG: Detailed diagnostic info (verbose) # INFO: General operational messages # WARNING: Warning messages for potential issues # ERROR: Error messages for failures (recommended for production) # CRITICAL: Only critical failures # PRODUCTION: Use ERROR to minimize I/O overhead and improve performance LOG_LEVEL=ERROR # Disable access logging for performance # Options: true, false (default) # When true: Disables both gunicorn and uvicorn access logs # PRODUCTION: Set to true for high-performance deployments # Access logs create massive I/O overhead under high concurrency # DISABLE_ACCESS_LOG=true # Log output format # Options: json (default), text # json: Structured JSON logs (good for log aggregation) # text: Human-readable plain text LOG_FORMAT=json # Enable file logging (in addition to console output) # Options: true, false (default) LOG_TO_FILE=false # Enable request payload logging for debugging # Options: true, false (default) # When enabled, logs HTTP request method, headers, query params, and body # Sensitive data (passwords, tokens, etc.) is automatically masked LOG_REQUESTS=false # File write mode when LOG_TO_FILE=true # Options: a+ (append, default), w (overwrite on startup) LOG_FILEMODE=a+ LOG_FILE=mcpgateway.log LOG_FOLDER=logs LOG_ROTATION_ENABLED=false LOG_MAX_SIZE_MB=1 LOG_BACKUP_COUNT=5 LOG_BUFFER_SIZE_MB=1.0 # Transport Protocol Configuration # Options: all (default), sse, streamablehttp, http # - all: Enable all transport protocols # - sse: Server-Sent Events only # - streamablehttp: Streaming HTTP only # - http: Standard HTTP JSON-RPC only TRANSPORT_TYPE=all # WebSocket keepalive ping interval in seconds # Prevents connection timeout for idle WebSocket connections WEBSOCKET_PING_INTERVAL=30 # SSE client retry timeout in milliseconds # Time client waits before reconnecting after SSE connection loss SSE_RETRY_TIMEOUT=5000 # Enable SSE keepalive events to prevent proxy/firewall timeouts # Options: true (default), false SSE_KEEPALIVE_ENABLED=true # SSE keepalive event interval in seconds # How often to send keepalive events when SSE_KEEPALIVE_ENABLED=true SSE_KEEPALIVE_INTERVAL=30 # Streaming HTTP Configuration # Enable stateful sessions (stores session state server-side) # Options: true, false (default) # false: Stateless mode (better for scaling) USE_STATEFUL_SESSIONS=false # Enable JSON response format for streaming HTTP # Options: true (default), false # true: Return JSON responses, false: Return SSE stream JSON_RESPONSE_ENABLED=true # Federation Configuration # Enable gateway federation (connect to other MCP gateways) # Options: true (default), false FEDERATION_ENABLED=true # Enable automatic peer discovery via mDNS/Zeroconf # Options: true, false (default) # Requires: python-zeroconf package FEDERATION_DISCOVERY=false # Static list of peer gateway URLs (JSON array) # Example: ["http://gateway1:4444", "https://gateway2.example.com"] FEDERATION_PEERS=[] # Timeout for federation requests in seconds # Default: 120 seconds (matches config.py) FEDERATION_TIMEOUT=120 # Interval between federation sync operations in seconds FEDERATION_SYNC_INTERVAL=300 # Resource Configuration RESOURCE_CACHE_SIZE=1000 RESOURCE_CACHE_TTL=3600 MAX_RESOURCE_SIZE=10485760 # Allowed MIME types for resources (JSON array) # Controls which content types are allowed for resource handling # Default includes common text, image, and data formats # Example: ["text/plain", "text/markdown", "application/json", "image/png"] # To add custom types: ["text/plain", "application/pdf", "video/mp4"] # ALLOWED_MIME_TYPES=["text/plain", "text/markdown", "text/html", "application/json", "application/xml", "image/png", "image/jpeg", "image/gif"] # Tool Configuration TOOL_TIMEOUT=60 MAX_TOOL_RETRIES=3 TOOL_RATE_LIMIT=100 TOOL_CONCURRENT_LIMIT=10 GATEWAY_TOOL_NAME_SEPARATOR=- # Prompt Configuration PROMPT_CACHE_SIZE=100 MAX_PROMPT_SIZE=102400 PROMPT_RENDER_TIMEOUT=10 # Health Check Configuration HEALTH_CHECK_INTERVAL=60 # Health check timeout in seconds (default: 10, matches config.py) HEALTH_CHECK_TIMEOUT=10 UNHEALTHY_THRESHOLD=5 # Gateway URL validation timeout in seconds (default: 5, matches config.py) GATEWAY_VALIDATION_TIMEOUT=5 # File lock name for gateway service leader election # Used to coordinate multiple gateway instances when running in cluster mode # Default: "gateway_service_leader.lock" FILELOCK_NAME=gateway_service_leader.lock # Default root paths (JSON array) # List of default root paths for resource resolution # Example: ["/api/v1", "/mcp"] # Default: [] DEFAULT_ROOTS=[] # OpenTelemetry Observability Configuration # Enable distributed tracing and metrics collection # Options: true (default), false OTEL_ENABLE_OBSERVABILITY=true # Traces exporter backend # Options: otlp (default), jaeger, zipkin, console, none # - otlp: OpenTelemetry Protocol (works with many backends) # - jaeger: Direct Jaeger integration # - zipkin: Direct Zipkin integration # - console: Print to stdout (debugging) # - none: Disable tracing OTEL_TRACES_EXPORTER=otlp # OTLP endpoint for traces and metrics # Examples: # - Phoenix: http://localhost:4317 # - Jaeger: http://localhost:4317 # - Tempo: http://localhost:4317 OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 # OTLP protocol # Options: grpc (default), http OTEL_EXPORTER_OTLP_PROTOCOL=grpc # Use insecure connection (no TLS) for OTLP # Options: true (default for localhost), false (use TLS) OTEL_EXPORTER_OTLP_INSECURE=true # OTEL_EXPORTER_OTLP_HEADERS=key1=value1,key2=value2 # OTEL_EXPORTER_JAEGER_ENDPOINT=http://localhost:14268/api/traces # OTEL_EXPORTER_ZIPKIN_ENDPOINT=http://localhost:9411/api/v2/spans OTEL_SERVICE_NAME=mcp-gateway # OTEL_RESOURCE_ATTRIBUTES=service.version=1.0.0,environment=production OTEL_BSP_MAX_QUEUE_SIZE=2048 OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512 OTEL_BSP_SCHEDULE_DELAY=5000 # Prometheus Metrics Configuration # Enable Prometheus-compatible metrics exposition for monitoring and alerting # Options: true (default), false # When true: Exposes metrics at /metrics/prometheus in Prometheus format # When false: Returns HTTP 503 on metrics endpoint ENABLE_METRICS=true # Comma-separated regex patterns for endpoints to exclude from metrics collection # Use this to avoid high-cardinality issues with dynamic paths or reduce overhead # Examples: # - Exclude SSE endpoints: /servers/.*/sse # - Exclude static files: /static/.* # - Exclude health checks: .*health.* # - Multiple patterns: /servers/.*/sse,/static/.*,.*health.* # Default: "" (no exclusions) METRICS_EXCLUDED_HANDLERS= # Prometheus metrics namespace (prefix for all metric names) # Used to group metrics by application or organization # Example: mycompany_gateway_http_requests_total # Default: "default" METRICS_NAMESPACE=default # Prometheus metrics subsystem (secondary prefix for metric names) # Used for further categorization within namespace # Example: mycompany_api_http_requests_total (if subsystem=api) # Default: "" (no subsystem) METRICS_SUBSYSTEM= # Custom static labels for app_info gauge metric # Format: comma-separated "key=value" pairs (low-cardinality values only) # WARNING: Never use high-cardinality values (user IDs, request IDs, timestamps) # Examples: # - Single label: environment=production # - Multiple labels: environment=production,region=us-east-1,team=platform # - K8s example: cluster=prod-us-east,namespace=mcp-gateway # Default: "" (no custom labels) METRICS_CUSTOM_LABELS= # Plugin Framework Configuration # Enable the plugin system for extending gateway functionality # Options: true, false (default) # When true: Loads and executes plugins from PLUGIN_CONFIG_FILE PLUGINS_ENABLED=true # Path to the plugin configuration file # Contains plugin definitions, hooks, and settings # Default: plugins/config.yaml PLUGIN_CONFIG_FILE=plugins/config.yaml # Optional defaults for mTLS when connecting to external MCP plugins (STREAMABLEHTTP transport) # Provide file paths inside the container. Plugin-specific TLS blocks override these defaults. # PLUGINS_CLIENT_MTLS_CA_BUNDLE=/app/certs/plugins/ca.crt # PLUGINS_CLIENT_MTLS_CERTFILE=/app/certs/plugins/gateway-client.pem # PLUGINS_CLIENT_MTLS_KEYFILE=/app/certs/plugins/gateway-client.key # PLUGINS_CLIENT_MTLS_KEYFILE_PASSWORD= # PLUGINS_CLIENT_MTLS_VERIFY=true # PLUGINS_CLIENT_MTLS_CHECK_HOSTNAME=true ##################################### # Well-Known URI Configuration ##################################### # Enable well-known URI endpoints (/.well-known/*) WELL_KNOWN_ENABLED=true # robots.txt content - Default blocks all crawlers (private API) # Use multiline with proper escaping or keep on one line WELL_KNOWN_ROBOTS_TXT="User-agent: *\nDisallow: /\n\n# MCP Gateway is a private API gateway\n# Public crawling is disabled by default" # security.txt content - Define your security contact information # Format: RFC 9116 (https://www.rfc-editor.org/rfc/rfc9116.html) # Leave empty to disable security.txt # Example: # WELL_KNOWN_SECURITY_TXT="Contact: mailto:security@example.com\nExpires: 2025-12-31T23:59:59Z\nPreferred-Languages: en\nCanonical: https://example.com/.well-known/security.txt" WELL_KNOWN_SECURITY_TXT="" # Additional custom well-known files (JSON format) # Example: {"ai.txt": "AI Usage: This service uses AI for tool orchestration...", "dnt-policy.txt": "We respect DNT headers..."} WELL_KNOWN_CUSTOM_FILES="{}" # Cache control for well-known files (seconds) - 3600 = 1 hour WELL_KNOWN_CACHE_MAX_AGE=3600 ##################################### # Well-Known URI Examples ##################################### # Example 1: Basic security.txt # WELL_KNOWN_SECURITY_TXT="Contact: mailto:security@mycompany.com\nContact: https://mycompany.com/security\nEncryption: https://mycompany.com/pgp-key.txt\nPreferred-Languages: en, es\nCanonical: https://api.mycompany.com/.well-known/security.txt" # Example 2: Custom AI policy # WELL_KNOWN_CUSTOM_FILES={"ai.txt": "# AI Usage Policy\n\nThis MCP Gateway uses AI for:\n- Tool orchestration\n- Response generation\n- Error handling\n\nWe do not use AI for:\n- User data analysis\n- Behavioral tracking\n- Decision making without human oversight"} # Example 3: Allow specific crawlers # WELL_KNOWN_ROBOTS_TXT="User-agent: internal-monitor\nAllow: /health\nAllow: /metrics\n\nUser-agent: *\nDisallow: /" # Example 4: Multiple custom files # WELL_KNOWN_CUSTOM_FILES={"ai.txt": "# AI Usage Policy\n\nThis MCP Gateway uses AI for:\n- Tool orchestration\n- Response generation\n- Error handling\n\nWe do not use AI for:\n- User data analysis\n- Behavioral tracking\n- Decision making without human oversight", "dnt-policy.txt": "# Do Not Track Policy\n\nWe respect the DNT header.\nNo tracking cookies are used.\nOnly essential session data is stored.", "change-password": "https://mycompany.com/account/password"} ##################################### # Validation Settings ##################################### # These settings control input validation and security patterns # Most users won't need to change these defaults # HTML/JavaScript injection patterns (regex) # Used to detect potentially dangerous HTML/JS content # VALIDATION_DANGEROUS_HTML_PATTERN - Pattern to detect dangerous HTML tags # VALIDATION_DANGEROUS_JS_PATTERN - Pattern to detect JavaScript injection attempts # Allowed URL schemes for external requests # Controls which URL schemes are permitted for gateway operations # Default: ["http://", "https://", "ws://", "wss://"] # VALIDATION_ALLOWED_URL_SCHEMES=["http://", "https://", "ws://", "wss://"] # Character validation patterns (regex) # Used to validate various input fields # VALIDATION_NAME_PATTERN - Pattern for validating names (allows spaces) # VALIDATION_IDENTIFIER_PATTERN - Pattern for validating IDs (no spaces) # VALIDATION_SAFE_URI_PATTERN - Pattern for safe URI characters # VALIDATION_UNSAFE_URI_PATTERN - Pattern to detect unsafe URI characters # VALIDATION_TOOL_NAME_PATTERN - MCP tool naming pattern # VALIDATION_TOOL_METHOD_PATTERN - MCP tool method naming pattern # Size limits for various inputs (in characters or bytes) # VALIDATION_MAX_NAME_LENGTH=255 # VALIDATION_MAX_DESCRIPTION_LENGTH=8192 # VALIDATION_MAX_TEMPLATE_LENGTH=65536 # VALIDATION_MAX_CONTENT_LENGTH=1048576 # VALIDATION_MAX_JSON_DEPTH=10 # VALIDATION_MAX_URL_LENGTH=2048 # VALIDATION_MAX_RPC_PARAM_SIZE=262144 # VALIDATION_MAX_METHOD_LENGTH=128 # Rate limiting for validation operations # Maximum requests per minute for validation endpoints # VALIDATION_MAX_REQUESTS_PER_MINUTE=60 # Allowed MIME types for validation (JSON array) # Controls which content types pass validation checks # VALIDATION_ALLOWED_MIME_TYPES=["text/plain", "text/html", "text/css", "text/markdown", "text/javascript", "application/json", "application/xml", "application/pdf", "image/png", "image/jpeg", "image/gif", "image/svg+xml", "application/octet-stream"] ##################################### # Development Configuration ##################################### # Enable development mode (relaxed security, verbose logging) # Options: true, false (default) # WARNING: Never use in production! DEV_MODE=false # Enable auto-reload on code changes (for development) # Options: true, false (default) # Requires: Running with uvicorn directly (not gunicorn) RELOAD=false # Enable debug mode (verbose error messages, stack traces) # Options: true, false (default) # WARNING: May expose sensitive information! DEBUG=false # Header Passthrough (WARNING: Security implications) ENABLE_HEADER_PASSTHROUGH=false ENABLE_OVERWRITE_BASE_HEADERS=false DEFAULT_PASSTHROUGH_HEADERS=["X-Tenant-Id", "X-Trace-Id"] # Authorization Header Conflict Resolution: # When gateway uses auth, use X-Upstream-Authorization header to pass # authorization to upstream servers (automatically renamed to Authorization) # Enable auto-completion for plugins CLI PLUGINS_CLI_COMPLETION=false MCPGATEWAY_UI_TOOL_TEST_TIMEOUT=120000 # Set markup mode for plugins CLI # Valid options: # rich: use rich markup # markdown: allow markdown in help strings # disabled: disable markup # If unset (commented out), uses "rich" if rich is detected, otherwise disables it. PLUGINS_CLI_MARKUP_MODE=rich ##################################### # Security Validation Settings ##################################### # Minimum length for secret keys (JWT, encryption) MIN_SECRET_LENGTH=32 # Minimum length for passwords MIN_PASSWORD_LENGTH=12 # Enforce strong secrets (set to true to fail startup on critical issues) # Default is false to maintain backward compatibility REQUIRE_STRONG_SECRETS=false # Security validation thresholds # Set to false to allow startup with security warnings # NOT RECOMMENDED for production! # REQUIRE_STRONG_SECRETS=false ##################################### # LLM Chat MCP Client Configuration ##################################### # Enable the LLM Chat functionality (true/false) # When disabled, LLM chat features will be completely hidden from UI and APIs # Default: false (must be explicitly enabled) LLMCHAT_ENABLED=false # LLM Provider Selection # Options: azure_openai, openai, anthropic, aws_bedrock, ollama # Default: azure_openai # LLM_PROVIDER=azure_openai # Redis Configuration for chat session storage and maintaining history # CACHE_TYPE should be set to "redis" and REDIS_URL configured appropriately as mentioned in the caching section. LLMCHAT_SESSION_TTL=300 # Seconds for active_session key TTL LLMCHAT_SESSION_LOCK_TTL=30 # Seconds for lock expiry LLMCHAT_SESSION_LOCK_RETRIES=10 # How many times to poll while waiting LLMCHAT_SESSION_LOCK_WAIT=0.2 # Seconds between polls LLMCHAT_CHAT_HISTORY_TTL=3600 # Seconds for chat history expiry LLMCHAT_CHAT_HISTORY_MAX_MESSAGES=50 # Maximum message history to store per user ##################################### # Azure OpenAI Configuration ##################################### # Use for Microsoft Azure OpenAI Service deployments # AZURE_OPENAI_API_KEY= # AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com # AZURE_OPENAI_API_VERSION=2024-02-15-preview # AZURE_OPENAI_DEPLOYMENT=gpt-4o # AZURE_OPENAI_MODEL=gpt-4o # AZURE_OPENAI_TEMPERATURE=0.7 ##################################### # OpenAI Configuration ##################################### # Use for direct OpenAI API access (non-Azure) or OpenAI-compatible endpoints # OPENAI_API_KEY=sk-... # OPENAI_MODEL=gpt-4o-mini # OPENAI_BASE_URL=https://api.openai.com/v1 # Optional: for OpenAI-compatible endpoints # OPENAI_TEMPERATURE=0.7 # OPENAI_MAX_RETRIES=2 ##################################### # Anthropic Claude Configuration ##################################### # Use for Anthropic Claude API # Requires: pip install langchain-anthropic # ANTHROPIC_API_KEY=sk-ant-... # ANTHROPIC_MODEL=claude-3-5-sonnet-20241022 # ANTHROPIC_TEMPERATURE=0.7 # ANTHROPIC_MAX_TOKENS=4096 # ANTHROPIC_MAX_RETRIES=2 ##################################### # AWS Bedrock Configuration ##################################### # Use for AWS Bedrock LLM services # Requires: pip install langchain-aws boto3 # Note: Uses AWS credential chain if credentials not explicitly provided # AWS_BEDROCK_MODEL_ID=anthropic.claude-v2 # AWS_BEDROCK_REGION=us-east-1 # AWS_BEDROCK_TEMPERATURE=0.7 # AWS_BEDROCK_MAX_TOKENS=4096 # Optional AWS credentials (uses default credential chain if not provided): # AWS_ACCESS_KEY_ID= # AWS_SECRET_ACCESS_KEY= # AWS_SESSION_TOKEN= ##################################### # IBM watsonx.ai Configuration ##################################### # Use for IBM WatsonX AI LLM services # Requires: pip install langchain-ibm # WATSONX_APIKEY=apikey # WATSONX_URL=https://us-south.ml.cloud.ibm.com # WATSONX_PROJECT_ID=project-id # WATSONX_MODEL_ID=ibm/granite-13b-chat-v2 # WATSONX_TEMPERATURE=0.7 ##################################### # Ollama Configuration ##################################### # Use for local or self-hosted Ollama instances # OLLAMA_MODEL=llama3 # OLLAMA_BASE_URL=http://localhost:11434 # OLLAMA_TEMPERATURE=0.7 ##################################### # Pagination Configuration ##################################### # Default number of items per page for paginated endpoints # Applies to: tools, resources, prompts, servers, gateways, users, teams, tokens, etc. # Default: 50, Min: 1, Max: 1000 PAGINATION_DEFAULT_PAGE_SIZE=50 # Maximum allowed items per page (prevents abuse) # Default: 500, Min: 1, Max: 10000 PAGINATION_MAX_PAGE_SIZE=500 # Minimum items per page # Default: 1 PAGINATION_MIN_PAGE_SIZE=1 # Threshold for switching from offset to cursor-based pagination # When result set exceeds this count, use cursor-based pagination for performance # Default: 10000 PAGINATION_CURSOR_THRESHOLD=10000 # Enable cursor-based pagination globally # Options: true (default), false # When false, only offset-based pagination is used PAGINATION_CURSOR_ENABLED=true # Default sort field for paginated queries # Default: created_at PAGINATION_DEFAULT_SORT_FIELD=created_at # Default sort order for paginated queries # Options: asc, desc (default) PAGINATION_DEFAULT_SORT_ORDER=desc # Maximum offset allowed for offset-based pagination (prevents abuse) # Default: 100000 (100K records) PAGINATION_MAX_OFFSET=100000 # Cache pagination counts for performance (seconds) # Set to 0 to disable caching # Default: 300 (5 minutes) PAGINATION_COUNT_CACHE_TTL=300 # Enable pagination links in API responses # Options: true (default), false PAGINATION_INCLUDE_LINKS=true # Base URL for pagination links (defaults to request URL) # PAGINATION_BASE_URL=https://api.example.com ##################################### # gRPC Support Settings (EXPERIMENTAL) ##################################### # Enable gRPC to MCP translation support (disabled by default) # Requires: pip install mcp-contextforge-gateway[grpc] # MCPGATEWAY_GRPC_ENABLED=false # Enable gRPC server reflection by default for service discovery # MCPGATEWAY_GRPC_REFLECTION_ENABLED=true # Maximum gRPC message size in bytes (4MB default) # MCPGATEWAY_GRPC_MAX_MESSAGE_SIZE=4194304 # Default gRPC call timeout in seconds # MCPGATEWAY_GRPC_TIMEOUT=30 # Enable TLS for gRPC connections by default # MCPGATEWAY_GRPC_TLS_ENABLED=false ##################################### # Observability Settings ##################################### # Enable observability tracing and metrics collection # When enabled, all HTTP requests will be traced with detailed timing, status codes, and context # OBSERVABILITY_ENABLED=false # Automatically trace HTTP requests # OBSERVABILITY_TRACE_HTTP_REQUESTS=true # Number of days to retain trace data # OBSERVABILITY_TRACE_RETENTION_DAYS=7 # Maximum number of traces to retain (prevents unbounded growth) # OBSERVABILITY_MAX_TRACES=100000 # Trace sampling rate (0.0-1.0) - 1.0 means trace everything, 0.1 means trace 10% # OBSERVABILITY_SAMPLE_RATE=1.0 # Paths to exclude from tracing (comma-separated regex patterns) # OBSERVABILITY_EXCLUDE_PATHS=/health,/healthz,/ready,/metrics,/static/.* # Enable metrics collection # OBSERVABILITY_METRICS_ENABLED=true # Enable event logging within spans # OBSERVABILITY_EVENTS_ENABLED=true ##################################### # Ed25519 Key Support ##################################### # Ed25519 private key for signing ENABLE_ED25519_SIGNING=false PREV_ED2519_PRIVATE_KEY="" ED25519_PRIVATE_KEY=private_key